Use the vanilla func_end symbol for .size.
[oota-llvm.git] / lib / CodeGen / AsmPrinter / AsmPrinter.cpp
1 //===-- AsmPrinter.cpp - Common AsmPrinter code ---------------------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file implements the AsmPrinter class.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #include "llvm/CodeGen/AsmPrinter.h"
15 #include "DwarfDebug.h"
16 #include "DwarfException.h"
17 #include "Win64Exception.h"
18 #include "WinCodeViewLineTables.h"
19 #include "llvm/ADT/SmallString.h"
20 #include "llvm/ADT/Statistic.h"
21 #include "llvm/Analysis/ConstantFolding.h"
22 #include "llvm/Analysis/JumpInstrTableInfo.h"
23 #include "llvm/CodeGen/Analysis.h"
24 #include "llvm/CodeGen/GCMetadataPrinter.h"
25 #include "llvm/CodeGen/MachineConstantPool.h"
26 #include "llvm/CodeGen/MachineFrameInfo.h"
27 #include "llvm/CodeGen/MachineFunction.h"
28 #include "llvm/CodeGen/MachineInstrBundle.h"
29 #include "llvm/CodeGen/MachineJumpTableInfo.h"
30 #include "llvm/CodeGen/MachineLoopInfo.h"
31 #include "llvm/CodeGen/MachineModuleInfo.h"
32 #include "llvm/IR/DataLayout.h"
33 #include "llvm/IR/DebugInfo.h"
34 #include "llvm/IR/Mangler.h"
35 #include "llvm/IR/Module.h"
36 #include "llvm/IR/Operator.h"
37 #include "llvm/MC/MCAsmInfo.h"
38 #include "llvm/MC/MCContext.h"
39 #include "llvm/MC/MCExpr.h"
40 #include "llvm/MC/MCInst.h"
41 #include "llvm/MC/MCSection.h"
42 #include "llvm/MC/MCStreamer.h"
43 #include "llvm/MC/MCSymbol.h"
44 #include "llvm/MC/MCValue.h"
45 #include "llvm/Support/ErrorHandling.h"
46 #include "llvm/Support/Format.h"
47 #include "llvm/Support/MathExtras.h"
48 #include "llvm/Support/TargetRegistry.h"
49 #include "llvm/Support/Timer.h"
50 #include "llvm/Target/TargetFrameLowering.h"
51 #include "llvm/Target/TargetInstrInfo.h"
52 #include "llvm/Target/TargetLowering.h"
53 #include "llvm/Target/TargetLoweringObjectFile.h"
54 #include "llvm/Target/TargetRegisterInfo.h"
55 #include "llvm/Target/TargetSubtargetInfo.h"
56 using namespace llvm;
57
58 #define DEBUG_TYPE "asm-printer"
59
60 static const char *const DWARFGroupName = "DWARF Emission";
61 static const char *const DbgTimerName = "Debug Info Emission";
62 static const char *const EHTimerName = "DWARF Exception Writer";
63 static const char *const CodeViewLineTablesGroupName = "CodeView Line Tables";
64
65 STATISTIC(EmittedInsts, "Number of machine instrs printed");
66
67 char AsmPrinter::ID = 0;
68
69 typedef DenseMap<GCStrategy*, std::unique_ptr<GCMetadataPrinter>> gcp_map_type;
70 static gcp_map_type &getGCMap(void *&P) {
71   if (!P)
72     P = new gcp_map_type();
73   return *(gcp_map_type*)P;
74 }
75
76
77 /// getGVAlignmentLog2 - Return the alignment to use for the specified global
78 /// value in log2 form.  This rounds up to the preferred alignment if possible
79 /// and legal.
80 static unsigned getGVAlignmentLog2(const GlobalValue *GV, const DataLayout &TD,
81                                    unsigned InBits = 0) {
82   unsigned NumBits = 0;
83   if (const GlobalVariable *GVar = dyn_cast<GlobalVariable>(GV))
84     NumBits = TD.getPreferredAlignmentLog(GVar);
85
86   // If InBits is specified, round it to it.
87   if (InBits > NumBits)
88     NumBits = InBits;
89
90   // If the GV has a specified alignment, take it into account.
91   if (GV->getAlignment() == 0)
92     return NumBits;
93
94   unsigned GVAlign = Log2_32(GV->getAlignment());
95
96   // If the GVAlign is larger than NumBits, or if we are required to obey
97   // NumBits because the GV has an assigned section, obey it.
98   if (GVAlign > NumBits || GV->hasSection())
99     NumBits = GVAlign;
100   return NumBits;
101 }
102
103 AsmPrinter::AsmPrinter(TargetMachine &tm, std::unique_ptr<MCStreamer> Streamer)
104     : MachineFunctionPass(ID), TM(tm), MAI(tm.getMCAsmInfo()),
105       OutContext(Streamer->getContext()), OutStreamer(*Streamer.release()),
106       LastMI(nullptr), LastFn(0), Counter(~0U), SetCounter(0) {
107   DD = nullptr;
108   MMI = nullptr;
109   LI = nullptr;
110   MF = nullptr;
111   CurrentFnSym = CurrentFnSymForSize = nullptr;
112   CurrentFnBegin = nullptr;
113   CurrentFnEnd = nullptr;
114   GCMetadataPrinters = nullptr;
115   VerboseAsm = OutStreamer.isVerboseAsm();
116 }
117
118 AsmPrinter::~AsmPrinter() {
119   assert(!DD && Handlers.empty() && "Debug/EH info didn't get finalized");
120
121   if (GCMetadataPrinters) {
122     gcp_map_type &GCMap = getGCMap(GCMetadataPrinters);
123
124     delete &GCMap;
125     GCMetadataPrinters = nullptr;
126   }
127
128   delete &OutStreamer;
129 }
130
131 /// getFunctionNumber - Return a unique ID for the current function.
132 ///
133 unsigned AsmPrinter::getFunctionNumber() const {
134   return MF->getFunctionNumber();
135 }
136
137 const TargetLoweringObjectFile &AsmPrinter::getObjFileLowering() const {
138   return *TM.getObjFileLowering();
139 }
140
141 /// getDataLayout - Return information about data layout.
142 const DataLayout &AsmPrinter::getDataLayout() const {
143   return *TM.getDataLayout();
144 }
145
146 const MCSubtargetInfo &AsmPrinter::getSubtargetInfo() const {
147   assert(MF && "getSubtargetInfo requires a valid MachineFunction!");
148   return MF->getSubtarget<MCSubtargetInfo>();
149 }
150
151 void AsmPrinter::EmitToStreamer(MCStreamer &S, const MCInst &Inst) {
152   S.EmitInstruction(Inst, getSubtargetInfo());
153 }
154
155 StringRef AsmPrinter::getTargetTriple() const {
156   return TM.getTargetTriple();
157 }
158
159 /// getCurrentSection() - Return the current section we are emitting to.
160 const MCSection *AsmPrinter::getCurrentSection() const {
161   return OutStreamer.getCurrentSection().first;
162 }
163
164
165
166 void AsmPrinter::getAnalysisUsage(AnalysisUsage &AU) const {
167   AU.setPreservesAll();
168   MachineFunctionPass::getAnalysisUsage(AU);
169   AU.addRequired<MachineModuleInfo>();
170   AU.addRequired<GCModuleInfo>();
171   if (isVerbose())
172     AU.addRequired<MachineLoopInfo>();
173 }
174
175 bool AsmPrinter::doInitialization(Module &M) {
176   MMI = getAnalysisIfAvailable<MachineModuleInfo>();
177   MMI->AnalyzeModule(M);
178
179   // Initialize TargetLoweringObjectFile.
180   const_cast<TargetLoweringObjectFile&>(getObjFileLowering())
181     .Initialize(OutContext, TM);
182
183   OutStreamer.InitSections(false);
184
185   Mang = new Mangler(TM.getDataLayout());
186
187   // Emit the version-min deplyment target directive if needed.
188   //
189   // FIXME: If we end up with a collection of these sorts of Darwin-specific
190   // or ELF-specific things, it may make sense to have a platform helper class
191   // that will work with the target helper class. For now keep it here, as the
192   // alternative is duplicated code in each of the target asm printers that
193   // use the directive, where it would need the same conditionalization
194   // anyway.
195   Triple TT(getTargetTriple());
196   if (TT.isOSDarwin()) {
197     unsigned Major, Minor, Update;
198     TT.getOSVersion(Major, Minor, Update);
199     // If there is a version specified, Major will be non-zero.
200     if (Major)
201       OutStreamer.EmitVersionMin((TT.isMacOSX() ?
202                                   MCVM_OSXVersionMin : MCVM_IOSVersionMin),
203                                  Major, Minor, Update);
204   }
205
206   // Allow the target to emit any magic that it wants at the start of the file.
207   EmitStartOfAsmFile(M);
208
209   // Very minimal debug info. It is ignored if we emit actual debug info. If we
210   // don't, this at least helps the user find where a global came from.
211   if (MAI->hasSingleParameterDotFile()) {
212     // .file "foo.c"
213     OutStreamer.EmitFileDirective(M.getModuleIdentifier());
214   }
215
216   GCModuleInfo *MI = getAnalysisIfAvailable<GCModuleInfo>();
217   assert(MI && "AsmPrinter didn't require GCModuleInfo?");
218   for (auto &I : *MI)
219     if (GCMetadataPrinter *MP = GetOrCreateGCPrinter(*I))
220       MP->beginAssembly(M, *MI, *this);
221
222   // Emit module-level inline asm if it exists.
223   if (!M.getModuleInlineAsm().empty()) {
224     OutStreamer.AddComment("Start of file scope inline assembly");
225     OutStreamer.AddBlankLine();
226     EmitInlineAsm(M.getModuleInlineAsm()+"\n");
227     OutStreamer.AddComment("End of file scope inline assembly");
228     OutStreamer.AddBlankLine();
229   }
230
231   if (MAI->doesSupportDebugInformation()) {
232     bool skip_dwarf = false;
233     if (Triple(TM.getTargetTriple()).isKnownWindowsMSVCEnvironment()) {
234       Handlers.push_back(HandlerInfo(new WinCodeViewLineTables(this),
235                                      DbgTimerName,
236                                      CodeViewLineTablesGroupName));
237       // FIXME: Don't emit DWARF debug info if there's at least one function
238       // with AddressSanitizer instrumentation.
239       // This is a band-aid fix for PR22032.
240       for (auto &F : M.functions()) {
241         if (F.hasFnAttribute(Attribute::SanitizeAddress)) {
242           skip_dwarf = true;
243           break;
244         }
245       }
246     }
247     if (!skip_dwarf) {
248       DD = new DwarfDebug(this, &M);
249       Handlers.push_back(HandlerInfo(DD, DbgTimerName, DWARFGroupName));
250     }
251   }
252
253   EHStreamer *ES = nullptr;
254   switch (MAI->getExceptionHandlingType()) {
255   case ExceptionHandling::None:
256     break;
257   case ExceptionHandling::SjLj:
258   case ExceptionHandling::DwarfCFI:
259     ES = new DwarfCFIException(this);
260     break;
261   case ExceptionHandling::ARM:
262     ES = new ARMException(this);
263     break;
264   case ExceptionHandling::WinEH:
265     switch (MAI->getWinEHEncodingType()) {
266     default: llvm_unreachable("unsupported unwinding information encoding");
267     case WinEH::EncodingType::Itanium:
268       ES = new Win64Exception(this);
269       break;
270     }
271     break;
272   }
273   if (ES)
274     Handlers.push_back(HandlerInfo(ES, EHTimerName, DWARFGroupName));
275   return false;
276 }
277
278 static bool canBeHidden(const GlobalValue *GV, const MCAsmInfo &MAI) {
279   if (!MAI.hasWeakDefCanBeHiddenDirective())
280     return false;
281
282   return canBeOmittedFromSymbolTable(GV);
283 }
284
285 void AsmPrinter::EmitLinkage(const GlobalValue *GV, MCSymbol *GVSym) const {
286   GlobalValue::LinkageTypes Linkage = GV->getLinkage();
287   switch (Linkage) {
288   case GlobalValue::CommonLinkage:
289   case GlobalValue::LinkOnceAnyLinkage:
290   case GlobalValue::LinkOnceODRLinkage:
291   case GlobalValue::WeakAnyLinkage:
292   case GlobalValue::WeakODRLinkage:
293     if (MAI->hasWeakDefDirective()) {
294       // .globl _foo
295       OutStreamer.EmitSymbolAttribute(GVSym, MCSA_Global);
296
297       if (!canBeHidden(GV, *MAI))
298         // .weak_definition _foo
299         OutStreamer.EmitSymbolAttribute(GVSym, MCSA_WeakDefinition);
300       else
301         OutStreamer.EmitSymbolAttribute(GVSym, MCSA_WeakDefAutoPrivate);
302     } else if (MAI->hasLinkOnceDirective()) {
303       // .globl _foo
304       OutStreamer.EmitSymbolAttribute(GVSym, MCSA_Global);
305       //NOTE: linkonce is handled by the section the symbol was assigned to.
306     } else {
307       // .weak _foo
308       OutStreamer.EmitSymbolAttribute(GVSym, MCSA_Weak);
309     }
310     return;
311   case GlobalValue::AppendingLinkage:
312     // FIXME: appending linkage variables should go into a section of
313     // their name or something.  For now, just emit them as external.
314   case GlobalValue::ExternalLinkage:
315     // If external or appending, declare as a global symbol.
316     // .globl _foo
317     OutStreamer.EmitSymbolAttribute(GVSym, MCSA_Global);
318     return;
319   case GlobalValue::PrivateLinkage:
320   case GlobalValue::InternalLinkage:
321     return;
322   case GlobalValue::AvailableExternallyLinkage:
323     llvm_unreachable("Should never emit this");
324   case GlobalValue::ExternalWeakLinkage:
325     llvm_unreachable("Don't know how to emit these");
326   }
327   llvm_unreachable("Unknown linkage type!");
328 }
329
330 void AsmPrinter::getNameWithPrefix(SmallVectorImpl<char> &Name,
331                                    const GlobalValue *GV) const {
332   TM.getNameWithPrefix(Name, GV, *Mang);
333 }
334
335 MCSymbol *AsmPrinter::getSymbol(const GlobalValue *GV) const {
336   return TM.getSymbol(GV, *Mang);
337 }
338
339 /// EmitGlobalVariable - Emit the specified global variable to the .s file.
340 void AsmPrinter::EmitGlobalVariable(const GlobalVariable *GV) {
341   if (GV->hasInitializer()) {
342     // Check to see if this is a special global used by LLVM, if so, emit it.
343     if (EmitSpecialLLVMGlobal(GV))
344       return;
345
346     // Skip the emission of global equivalents. The symbol can be emitted later
347     // on by emitGlobalGOTEquivs in case it turns out to be needed.
348     if (GlobalGOTEquivs.count(getSymbol(GV)))
349       return;
350
351     if (isVerbose()) {
352       GV->printAsOperand(OutStreamer.GetCommentOS(),
353                      /*PrintType=*/false, GV->getParent());
354       OutStreamer.GetCommentOS() << '\n';
355     }
356   }
357
358   MCSymbol *GVSym = getSymbol(GV);
359   EmitVisibility(GVSym, GV->getVisibility(), !GV->isDeclaration());
360
361   if (!GV->hasInitializer())   // External globals require no extra code.
362     return;
363
364   GVSym->redefineIfPossible();
365   if (GVSym->isDefined() || GVSym->isVariable())
366     report_fatal_error("symbol '" + Twine(GVSym->getName()) +
367                        "' is already defined");
368
369   if (MAI->hasDotTypeDotSizeDirective())
370     OutStreamer.EmitSymbolAttribute(GVSym, MCSA_ELF_TypeObject);
371
372   SectionKind GVKind = TargetLoweringObjectFile::getKindForGlobal(GV, TM);
373
374   const DataLayout *DL = TM.getDataLayout();
375   uint64_t Size = DL->getTypeAllocSize(GV->getType()->getElementType());
376
377   // If the alignment is specified, we *must* obey it.  Overaligning a global
378   // with a specified alignment is a prompt way to break globals emitted to
379   // sections and expected to be contiguous (e.g. ObjC metadata).
380   unsigned AlignLog = getGVAlignmentLog2(GV, *DL);
381
382   for (const HandlerInfo &HI : Handlers) {
383     NamedRegionTimer T(HI.TimerName, HI.TimerGroupName, TimePassesIsEnabled);
384     HI.Handler->setSymbolSize(GVSym, Size);
385   }
386
387   // Handle common and BSS local symbols (.lcomm).
388   if (GVKind.isCommon() || GVKind.isBSSLocal()) {
389     if (Size == 0) Size = 1;   // .comm Foo, 0 is undefined, avoid it.
390     unsigned Align = 1 << AlignLog;
391
392     // Handle common symbols.
393     if (GVKind.isCommon()) {
394       if (!getObjFileLowering().getCommDirectiveSupportsAlignment())
395         Align = 0;
396
397       // .comm _foo, 42, 4
398       OutStreamer.EmitCommonSymbol(GVSym, Size, Align);
399       return;
400     }
401
402     // Handle local BSS symbols.
403     if (MAI->hasMachoZeroFillDirective()) {
404       const MCSection *TheSection =
405         getObjFileLowering().SectionForGlobal(GV, GVKind, *Mang, TM);
406       // .zerofill __DATA, __bss, _foo, 400, 5
407       OutStreamer.EmitZerofill(TheSection, GVSym, Size, Align);
408       return;
409     }
410
411     // Use .lcomm only if it supports user-specified alignment.
412     // Otherwise, while it would still be correct to use .lcomm in some
413     // cases (e.g. when Align == 1), the external assembler might enfore
414     // some -unknown- default alignment behavior, which could cause
415     // spurious differences between external and integrated assembler.
416     // Prefer to simply fall back to .local / .comm in this case.
417     if (MAI->getLCOMMDirectiveAlignmentType() != LCOMM::NoAlignment) {
418       // .lcomm _foo, 42
419       OutStreamer.EmitLocalCommonSymbol(GVSym, Size, Align);
420       return;
421     }
422
423     if (!getObjFileLowering().getCommDirectiveSupportsAlignment())
424       Align = 0;
425
426     // .local _foo
427     OutStreamer.EmitSymbolAttribute(GVSym, MCSA_Local);
428     // .comm _foo, 42, 4
429     OutStreamer.EmitCommonSymbol(GVSym, Size, Align);
430     return;
431   }
432
433   const MCSection *TheSection =
434     getObjFileLowering().SectionForGlobal(GV, GVKind, *Mang, TM);
435
436   // Handle the zerofill directive on darwin, which is a special form of BSS
437   // emission.
438   if (GVKind.isBSSExtern() && MAI->hasMachoZeroFillDirective()) {
439     if (Size == 0) Size = 1;  // zerofill of 0 bytes is undefined.
440
441     // .globl _foo
442     OutStreamer.EmitSymbolAttribute(GVSym, MCSA_Global);
443     // .zerofill __DATA, __common, _foo, 400, 5
444     OutStreamer.EmitZerofill(TheSection, GVSym, Size, 1 << AlignLog);
445     return;
446   }
447
448   // Handle thread local data for mach-o which requires us to output an
449   // additional structure of data and mangle the original symbol so that we
450   // can reference it later.
451   //
452   // TODO: This should become an "emit thread local global" method on TLOF.
453   // All of this macho specific stuff should be sunk down into TLOFMachO and
454   // stuff like "TLSExtraDataSection" should no longer be part of the parent
455   // TLOF class.  This will also make it more obvious that stuff like
456   // MCStreamer::EmitTBSSSymbol is macho specific and only called from macho
457   // specific code.
458   if (GVKind.isThreadLocal() && MAI->hasMachoTBSSDirective()) {
459     // Emit the .tbss symbol
460     MCSymbol *MangSym =
461       OutContext.GetOrCreateSymbol(GVSym->getName() + Twine("$tlv$init"));
462
463     if (GVKind.isThreadBSS()) {
464       TheSection = getObjFileLowering().getTLSBSSSection();
465       OutStreamer.EmitTBSSSymbol(TheSection, MangSym, Size, 1 << AlignLog);
466     } else if (GVKind.isThreadData()) {
467       OutStreamer.SwitchSection(TheSection);
468
469       EmitAlignment(AlignLog, GV);
470       OutStreamer.EmitLabel(MangSym);
471
472       EmitGlobalConstant(GV->getInitializer());
473     }
474
475     OutStreamer.AddBlankLine();
476
477     // Emit the variable struct for the runtime.
478     const MCSection *TLVSect
479       = getObjFileLowering().getTLSExtraDataSection();
480
481     OutStreamer.SwitchSection(TLVSect);
482     // Emit the linkage here.
483     EmitLinkage(GV, GVSym);
484     OutStreamer.EmitLabel(GVSym);
485
486     // Three pointers in size:
487     //   - __tlv_bootstrap - used to make sure support exists
488     //   - spare pointer, used when mapped by the runtime
489     //   - pointer to mangled symbol above with initializer
490     unsigned PtrSize = DL->getPointerTypeSize(GV->getType());
491     OutStreamer.EmitSymbolValue(GetExternalSymbolSymbol("_tlv_bootstrap"),
492                                 PtrSize);
493     OutStreamer.EmitIntValue(0, PtrSize);
494     OutStreamer.EmitSymbolValue(MangSym, PtrSize);
495
496     OutStreamer.AddBlankLine();
497     return;
498   }
499
500   OutStreamer.SwitchSection(TheSection);
501
502   EmitLinkage(GV, GVSym);
503   EmitAlignment(AlignLog, GV);
504
505   OutStreamer.EmitLabel(GVSym);
506
507   EmitGlobalConstant(GV->getInitializer());
508
509   if (MAI->hasDotTypeDotSizeDirective())
510     // .size foo, 42
511     OutStreamer.EmitELFSize(GVSym, MCConstantExpr::Create(Size, OutContext));
512
513   OutStreamer.AddBlankLine();
514 }
515
516 /// EmitFunctionHeader - This method emits the header for the current
517 /// function.
518 void AsmPrinter::EmitFunctionHeader() {
519   // Print out constants referenced by the function
520   EmitConstantPool();
521
522   // Print the 'header' of function.
523   const Function *F = MF->getFunction();
524
525   OutStreamer.SwitchSection(
526       getObjFileLowering().SectionForGlobal(F, *Mang, TM));
527   EmitVisibility(CurrentFnSym, F->getVisibility());
528
529   EmitLinkage(F, CurrentFnSym);
530   EmitAlignment(MF->getAlignment(), F);
531
532   if (MAI->hasDotTypeDotSizeDirective())
533     OutStreamer.EmitSymbolAttribute(CurrentFnSym, MCSA_ELF_TypeFunction);
534
535   if (isVerbose()) {
536     F->printAsOperand(OutStreamer.GetCommentOS(),
537                    /*PrintType=*/false, F->getParent());
538     OutStreamer.GetCommentOS() << '\n';
539   }
540
541   // Emit the prefix data.
542   if (F->hasPrefixData())
543     EmitGlobalConstant(F->getPrefixData());
544
545   // Emit the CurrentFnSym.  This is a virtual function to allow targets to
546   // do their wild and crazy things as required.
547   EmitFunctionEntryLabel();
548
549   // If the function had address-taken blocks that got deleted, then we have
550   // references to the dangling symbols.  Emit them at the start of the function
551   // so that we don't get references to undefined symbols.
552   std::vector<MCSymbol*> DeadBlockSyms;
553   MMI->takeDeletedSymbolsForFunction(F, DeadBlockSyms);
554   for (unsigned i = 0, e = DeadBlockSyms.size(); i != e; ++i) {
555     OutStreamer.AddComment("Address taken block that was later removed");
556     OutStreamer.EmitLabel(DeadBlockSyms[i]);
557   }
558
559   if (!MMI->getLandingPads().empty()) {
560     CurrentFnBegin = createTempSymbol("func_begin", getFunctionNumber());
561
562     if (MAI->useAssignmentForEHBegin()) {
563       MCSymbol *CurPos = OutContext.CreateTempSymbol();
564       OutStreamer.EmitLabel(CurPos);
565       OutStreamer.EmitAssignment(CurrentFnBegin,
566                                  MCSymbolRefExpr::Create(CurPos, OutContext));
567     } else {
568       OutStreamer.EmitLabel(CurrentFnBegin);
569     }
570   }
571
572   // Emit pre-function debug and/or EH information.
573   for (const HandlerInfo &HI : Handlers) {
574     NamedRegionTimer T(HI.TimerName, HI.TimerGroupName, TimePassesIsEnabled);
575     HI.Handler->beginFunction(MF);
576   }
577
578   // Emit the prologue data.
579   if (F->hasPrologueData())
580     EmitGlobalConstant(F->getPrologueData());
581 }
582
583 /// EmitFunctionEntryLabel - Emit the label that is the entrypoint for the
584 /// function.  This can be overridden by targets as required to do custom stuff.
585 void AsmPrinter::EmitFunctionEntryLabel() {
586   CurrentFnSym->redefineIfPossible();
587
588   // The function label could have already been emitted if two symbols end up
589   // conflicting due to asm renaming.  Detect this and emit an error.
590   if (CurrentFnSym->isVariable())
591     report_fatal_error("'" + Twine(CurrentFnSym->getName()) +
592                        "' is a protected alias");
593   if (CurrentFnSym->isDefined())
594     report_fatal_error("'" + Twine(CurrentFnSym->getName()) +
595                        "' label emitted multiple times to assembly file");
596
597   return OutStreamer.EmitLabel(CurrentFnSym);
598 }
599
600 /// emitComments - Pretty-print comments for instructions.
601 static void emitComments(const MachineInstr &MI, raw_ostream &CommentOS) {
602   const MachineFunction *MF = MI.getParent()->getParent();
603   const TargetInstrInfo *TII = MF->getSubtarget().getInstrInfo();
604
605   // Check for spills and reloads
606   int FI;
607
608   const MachineFrameInfo *FrameInfo = MF->getFrameInfo();
609
610   // We assume a single instruction only has a spill or reload, not
611   // both.
612   const MachineMemOperand *MMO;
613   if (TII->isLoadFromStackSlotPostFE(&MI, FI)) {
614     if (FrameInfo->isSpillSlotObjectIndex(FI)) {
615       MMO = *MI.memoperands_begin();
616       CommentOS << MMO->getSize() << "-byte Reload\n";
617     }
618   } else if (TII->hasLoadFromStackSlot(&MI, MMO, FI)) {
619     if (FrameInfo->isSpillSlotObjectIndex(FI))
620       CommentOS << MMO->getSize() << "-byte Folded Reload\n";
621   } else if (TII->isStoreToStackSlotPostFE(&MI, FI)) {
622     if (FrameInfo->isSpillSlotObjectIndex(FI)) {
623       MMO = *MI.memoperands_begin();
624       CommentOS << MMO->getSize() << "-byte Spill\n";
625     }
626   } else if (TII->hasStoreToStackSlot(&MI, MMO, FI)) {
627     if (FrameInfo->isSpillSlotObjectIndex(FI))
628       CommentOS << MMO->getSize() << "-byte Folded Spill\n";
629   }
630
631   // Check for spill-induced copies
632   if (MI.getAsmPrinterFlag(MachineInstr::ReloadReuse))
633     CommentOS << " Reload Reuse\n";
634 }
635
636 /// emitImplicitDef - This method emits the specified machine instruction
637 /// that is an implicit def.
638 void AsmPrinter::emitImplicitDef(const MachineInstr *MI) const {
639   unsigned RegNo = MI->getOperand(0).getReg();
640   OutStreamer.AddComment(Twine("implicit-def: ") +
641                          MMI->getContext().getRegisterInfo()->getName(RegNo));
642   OutStreamer.AddBlankLine();
643 }
644
645 static void emitKill(const MachineInstr *MI, AsmPrinter &AP) {
646   std::string Str = "kill:";
647   for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
648     const MachineOperand &Op = MI->getOperand(i);
649     assert(Op.isReg() && "KILL instruction must have only register operands");
650     Str += ' ';
651     Str += AP.MMI->getContext().getRegisterInfo()->getName(Op.getReg());
652     Str += (Op.isDef() ? "<def>" : "<kill>");
653   }
654   AP.OutStreamer.AddComment(Str);
655   AP.OutStreamer.AddBlankLine();
656 }
657
658 /// emitDebugValueComment - This method handles the target-independent form
659 /// of DBG_VALUE, returning true if it was able to do so.  A false return
660 /// means the target will need to handle MI in EmitInstruction.
661 static bool emitDebugValueComment(const MachineInstr *MI, AsmPrinter &AP) {
662   // This code handles only the 4-operand target-independent form.
663   if (MI->getNumOperands() != 4)
664     return false;
665
666   SmallString<128> Str;
667   raw_svector_ostream OS(Str);
668   OS << "DEBUG_VALUE: ";
669
670   DIVariable V = MI->getDebugVariable();
671   if (V.getContext().isSubprogram()) {
672     StringRef Name = DISubprogram(V.getContext()).getDisplayName();
673     if (!Name.empty())
674       OS << Name << ":";
675   }
676   OS << V.getName();
677
678   DIExpression Expr = MI->getDebugExpression();
679   if (Expr.isBitPiece())
680     OS << " [bit_piece offset=" << Expr.getBitPieceOffset()
681        << " size=" << Expr.getBitPieceSize() << "]";
682   OS << " <- ";
683
684   // The second operand is only an offset if it's an immediate.
685   bool Deref = MI->getOperand(0).isReg() && MI->getOperand(1).isImm();
686   int64_t Offset = Deref ? MI->getOperand(1).getImm() : 0;
687
688   // Register or immediate value. Register 0 means undef.
689   if (MI->getOperand(0).isFPImm()) {
690     APFloat APF = APFloat(MI->getOperand(0).getFPImm()->getValueAPF());
691     if (MI->getOperand(0).getFPImm()->getType()->isFloatTy()) {
692       OS << (double)APF.convertToFloat();
693     } else if (MI->getOperand(0).getFPImm()->getType()->isDoubleTy()) {
694       OS << APF.convertToDouble();
695     } else {
696       // There is no good way to print long double.  Convert a copy to
697       // double.  Ah well, it's only a comment.
698       bool ignored;
699       APF.convert(APFloat::IEEEdouble, APFloat::rmNearestTiesToEven,
700                   &ignored);
701       OS << "(long double) " << APF.convertToDouble();
702     }
703   } else if (MI->getOperand(0).isImm()) {
704     OS << MI->getOperand(0).getImm();
705   } else if (MI->getOperand(0).isCImm()) {
706     MI->getOperand(0).getCImm()->getValue().print(OS, false /*isSigned*/);
707   } else {
708     unsigned Reg;
709     if (MI->getOperand(0).isReg()) {
710       Reg = MI->getOperand(0).getReg();
711     } else {
712       assert(MI->getOperand(0).isFI() && "Unknown operand type");
713       const TargetFrameLowering *TFI = AP.MF->getSubtarget().getFrameLowering();
714       Offset += TFI->getFrameIndexReference(*AP.MF,
715                                             MI->getOperand(0).getIndex(), Reg);
716       Deref = true;
717     }
718     if (Reg == 0) {
719       // Suppress offset, it is not meaningful here.
720       OS << "undef";
721       // NOTE: Want this comment at start of line, don't emit with AddComment.
722       AP.OutStreamer.emitRawComment(OS.str());
723       return true;
724     }
725     if (Deref)
726       OS << '[';
727     OS << AP.MMI->getContext().getRegisterInfo()->getName(Reg);
728   }
729
730   if (Deref)
731     OS << '+' << Offset << ']';
732
733   // NOTE: Want this comment at start of line, don't emit with AddComment.
734   AP.OutStreamer.emitRawComment(OS.str());
735   return true;
736 }
737
738 AsmPrinter::CFIMoveType AsmPrinter::needsCFIMoves() {
739   if (MAI->getExceptionHandlingType() == ExceptionHandling::DwarfCFI &&
740       MF->getFunction()->needsUnwindTableEntry())
741     return CFI_M_EH;
742
743   if (MMI->hasDebugInfo())
744     return CFI_M_Debug;
745
746   return CFI_M_None;
747 }
748
749 bool AsmPrinter::needsSEHMoves() {
750   return MAI->usesWindowsCFI() && MF->getFunction()->needsUnwindTableEntry();
751 }
752
753 void AsmPrinter::emitCFIInstruction(const MachineInstr &MI) {
754   ExceptionHandling ExceptionHandlingType = MAI->getExceptionHandlingType();
755   if (ExceptionHandlingType != ExceptionHandling::DwarfCFI &&
756       ExceptionHandlingType != ExceptionHandling::ARM)
757     return;
758
759   if (needsCFIMoves() == CFI_M_None)
760     return;
761
762   const MachineModuleInfo &MMI = MF->getMMI();
763   const std::vector<MCCFIInstruction> &Instrs = MMI.getFrameInstructions();
764   unsigned CFIIndex = MI.getOperand(0).getCFIIndex();
765   const MCCFIInstruction &CFI = Instrs[CFIIndex];
766   emitCFIInstruction(CFI);
767 }
768
769 void AsmPrinter::emitFrameAlloc(const MachineInstr &MI) {
770   // The operands are the MCSymbol and the frame offset of the allocation.
771   MCSymbol *FrameAllocSym = MI.getOperand(0).getMCSymbol();
772   int FrameOffset = MI.getOperand(1).getImm();
773
774   // Emit a symbol assignment.
775   OutStreamer.EmitAssignment(FrameAllocSym,
776                              MCConstantExpr::Create(FrameOffset, OutContext));
777 }
778
779 /// EmitFunctionBody - This method emits the body and trailer for a
780 /// function.
781 void AsmPrinter::EmitFunctionBody() {
782   // Emit target-specific gunk before the function body.
783   EmitFunctionBodyStart();
784
785   bool ShouldPrintDebugScopes = MMI->hasDebugInfo();
786
787   // Print out code for the function.
788   bool HasAnyRealCode = false;
789   for (auto &MBB : *MF) {
790     // Print a label for the basic block.
791     EmitBasicBlockStart(MBB);
792     for (auto &MI : MBB) {
793
794       // Print the assembly for the instruction.
795       if (!MI.isPosition() && !MI.isImplicitDef() && !MI.isKill() &&
796           !MI.isDebugValue()) {
797         HasAnyRealCode = true;
798         ++EmittedInsts;
799       }
800
801       if (ShouldPrintDebugScopes) {
802         for (const HandlerInfo &HI : Handlers) {
803           NamedRegionTimer T(HI.TimerName, HI.TimerGroupName,
804                              TimePassesIsEnabled);
805           HI.Handler->beginInstruction(&MI);
806         }
807       }
808
809       if (isVerbose())
810         emitComments(MI, OutStreamer.GetCommentOS());
811
812       switch (MI.getOpcode()) {
813       case TargetOpcode::CFI_INSTRUCTION:
814         emitCFIInstruction(MI);
815         break;
816
817       case TargetOpcode::FRAME_ALLOC:
818         emitFrameAlloc(MI);
819         break;
820
821       case TargetOpcode::EH_LABEL:
822       case TargetOpcode::GC_LABEL:
823         OutStreamer.EmitLabel(MI.getOperand(0).getMCSymbol());
824         break;
825       case TargetOpcode::INLINEASM:
826         EmitInlineAsm(&MI);
827         break;
828       case TargetOpcode::DBG_VALUE:
829         if (isVerbose()) {
830           if (!emitDebugValueComment(&MI, *this))
831             EmitInstruction(&MI);
832         }
833         break;
834       case TargetOpcode::IMPLICIT_DEF:
835         if (isVerbose()) emitImplicitDef(&MI);
836         break;
837       case TargetOpcode::KILL:
838         if (isVerbose()) emitKill(&MI, *this);
839         break;
840       default:
841         EmitInstruction(&MI);
842         break;
843       }
844
845       if (ShouldPrintDebugScopes) {
846         for (const HandlerInfo &HI : Handlers) {
847           NamedRegionTimer T(HI.TimerName, HI.TimerGroupName,
848                              TimePassesIsEnabled);
849           HI.Handler->endInstruction();
850         }
851       }
852     }
853
854     EmitBasicBlockEnd(MBB);
855   }
856
857   // If the function is empty and the object file uses .subsections_via_symbols,
858   // then we need to emit *something* to the function body to prevent the
859   // labels from collapsing together.  Just emit a noop.
860   if ((MAI->hasSubsectionsViaSymbols() && !HasAnyRealCode)) {
861     MCInst Noop;
862     MF->getSubtarget().getInstrInfo()->getNoopForMachoTarget(Noop);
863     OutStreamer.AddComment("avoids zero-length function");
864
865     // Targets can opt-out of emitting the noop here by leaving the opcode
866     // unspecified.
867     if (Noop.getOpcode())
868       OutStreamer.EmitInstruction(Noop, getSubtargetInfo());
869   }
870
871   const Function *F = MF->getFunction();
872   for (const auto &BB : *F) {
873     if (!BB.hasAddressTaken())
874       continue;
875     MCSymbol *Sym = GetBlockAddressSymbol(&BB);
876     if (Sym->isDefined())
877       continue;
878     OutStreamer.AddComment("Address of block that was removed by CodeGen");
879     OutStreamer.EmitLabel(Sym);
880   }
881
882   // Emit target-specific gunk after the function body.
883   EmitFunctionBodyEnd();
884
885   if (!MMI->getLandingPads().empty() || MAI->hasDotTypeDotSizeDirective()) {
886     // Create a symbol for the end of function.
887     CurrentFnEnd = createTempSymbol("func_end", getFunctionNumber());
888     OutStreamer.EmitLabel(CurrentFnEnd);
889   }
890
891   // If the target wants a .size directive for the size of the function, emit
892   // it.
893   if (MAI->hasDotTypeDotSizeDirective()) {
894     // We can get the size as difference between the function label and the
895     // temp label.
896     const MCExpr *SizeExp =
897       MCBinaryExpr::CreateSub(MCSymbolRefExpr::Create(CurrentFnEnd, OutContext),
898                               MCSymbolRefExpr::Create(CurrentFnSymForSize,
899                                                       OutContext),
900                               OutContext);
901     OutStreamer.EmitELFSize(CurrentFnSym, SizeExp);
902   }
903
904   // Emit post-function debug and/or EH information.
905   for (const HandlerInfo &HI : Handlers) {
906     NamedRegionTimer T(HI.TimerName, HI.TimerGroupName, TimePassesIsEnabled);
907     HI.Handler->endFunction(MF);
908   }
909   MMI->EndFunction();
910
911   // Print out jump tables referenced by the function.
912   EmitJumpTableInfo();
913
914   OutStreamer.AddBlankLine();
915 }
916
917 /// \brief Compute the number of Global Variables that uses a Constant.
918 static unsigned getNumGlobalVariableUses(const Constant *C) {
919   if (!C)
920     return 0;
921
922   if (isa<GlobalVariable>(C))
923     return 1;
924
925   unsigned NumUses = 0;
926   for (auto *CU : C->users())
927     NumUses += getNumGlobalVariableUses(dyn_cast<Constant>(CU));
928
929   return NumUses;
930 }
931
932 /// \brief Only consider global GOT equivalents if at least one user is a
933 /// cstexpr inside an initializer of another global variables. Also, don't
934 /// handle cstexpr inside instructions. During global variable emission,
935 /// candidates are skipped and are emitted later in case at least one cstexpr
936 /// isn't replaced by a PC relative GOT entry access.
937 static bool isGOTEquivalentCandidate(const GlobalVariable *GV,
938                                      unsigned &NumGOTEquivUsers) {
939   // Global GOT equivalents are unnamed private globals with a constant
940   // pointer initializer to another global symbol. They must point to a
941   // GlobalVariable or Function, i.e., as GlobalValue.
942   if (!GV->hasUnnamedAddr() || !GV->hasInitializer() || !GV->isConstant() ||
943       !GV->isDiscardableIfUnused() || !dyn_cast<GlobalValue>(GV->getOperand(0)))
944     return false;
945
946   // To be a got equivalent, at least one of its users need to be a constant
947   // expression used by another global variable.
948   for (auto *U : GV->users())
949     NumGOTEquivUsers += getNumGlobalVariableUses(cast<Constant>(U));
950
951   return NumGOTEquivUsers > 0;
952 }
953
954 /// \brief Unnamed constant global variables solely contaning a pointer to
955 /// another globals variable is equivalent to a GOT table entry; it contains the
956 /// the address of another symbol. Optimize it and replace accesses to these
957 /// "GOT equivalents" by using the GOT entry for the final global instead.
958 /// Compute GOT equivalent candidates among all global variables to avoid
959 /// emitting them if possible later on, after it use is replaced by a GOT entry
960 /// access.
961 void AsmPrinter::computeGlobalGOTEquivs(Module &M) {
962   if (!getObjFileLowering().supportIndirectSymViaGOTPCRel())
963     return;
964
965   for (const auto &G : M.globals()) {
966     unsigned NumGOTEquivUsers = 0;
967     if (!isGOTEquivalentCandidate(&G, NumGOTEquivUsers))
968       continue;
969
970     const MCSymbol *GOTEquivSym = getSymbol(&G);
971     GlobalGOTEquivs[GOTEquivSym] = std::make_pair(&G, NumGOTEquivUsers);
972   }
973 }
974
975 /// \brief Constant expressions using GOT equivalent globals may not be eligible
976 /// for PC relative GOT entry conversion, in such cases we need to emit such
977 /// globals we previously omitted in EmitGlobalVariable.
978 void AsmPrinter::emitGlobalGOTEquivs() {
979   if (!getObjFileLowering().supportIndirectSymViaGOTPCRel())
980     return;
981
982   while (!GlobalGOTEquivs.empty()) {
983     DenseMap<const MCSymbol *, GOTEquivUsePair>::iterator I =
984       GlobalGOTEquivs.begin();
985     const MCSymbol *S = I->first;
986     const GlobalVariable *GV = I->second.first;
987     GlobalGOTEquivs.erase(S);
988     EmitGlobalVariable(GV);
989   }
990 }
991
992 bool AsmPrinter::doFinalization(Module &M) {
993   // Gather all GOT equivalent globals in the module. We really need two
994   // passes over the globals: one to compute and another to avoid its emission
995   // in EmitGlobalVariable, otherwise we would not be able to handle cases
996   // where the got equivalent shows up before its use.
997   computeGlobalGOTEquivs(M);
998
999   // Emit global variables.
1000   for (const auto &G : M.globals())
1001     EmitGlobalVariable(&G);
1002
1003   // Emit remaining GOT equivalent globals.
1004   emitGlobalGOTEquivs();
1005
1006   // Emit visibility info for declarations
1007   for (const Function &F : M) {
1008     if (!F.isDeclaration())
1009       continue;
1010     GlobalValue::VisibilityTypes V = F.getVisibility();
1011     if (V == GlobalValue::DefaultVisibility)
1012       continue;
1013
1014     MCSymbol *Name = getSymbol(&F);
1015     EmitVisibility(Name, V, false);
1016   }
1017
1018   // Emit module flags.
1019   SmallVector<Module::ModuleFlagEntry, 8> ModuleFlags;
1020   M.getModuleFlagsMetadata(ModuleFlags);
1021   if (!ModuleFlags.empty())
1022     getObjFileLowering().emitModuleFlags(OutStreamer, ModuleFlags, *Mang, TM);
1023
1024   // Make sure we wrote out everything we need.
1025   OutStreamer.Flush();
1026
1027   // Finalize debug and EH information.
1028   for (const HandlerInfo &HI : Handlers) {
1029     NamedRegionTimer T(HI.TimerName, HI.TimerGroupName,
1030                        TimePassesIsEnabled);
1031     HI.Handler->endModule();
1032     delete HI.Handler;
1033   }
1034   Handlers.clear();
1035   DD = nullptr;
1036
1037   // If the target wants to know about weak references, print them all.
1038   if (MAI->getWeakRefDirective()) {
1039     // FIXME: This is not lazy, it would be nice to only print weak references
1040     // to stuff that is actually used.  Note that doing so would require targets
1041     // to notice uses in operands (due to constant exprs etc).  This should
1042     // happen with the MC stuff eventually.
1043
1044     // Print out module-level global variables here.
1045     for (const auto &G : M.globals()) {
1046       if (!G.hasExternalWeakLinkage())
1047         continue;
1048       OutStreamer.EmitSymbolAttribute(getSymbol(&G), MCSA_WeakReference);
1049     }
1050
1051     for (const auto &F : M) {
1052       if (!F.hasExternalWeakLinkage())
1053         continue;
1054       OutStreamer.EmitSymbolAttribute(getSymbol(&F), MCSA_WeakReference);
1055     }
1056   }
1057
1058   OutStreamer.AddBlankLine();
1059   for (const auto &Alias : M.aliases()) {
1060     MCSymbol *Name = getSymbol(&Alias);
1061
1062     if (Alias.hasExternalLinkage() || !MAI->getWeakRefDirective())
1063       OutStreamer.EmitSymbolAttribute(Name, MCSA_Global);
1064     else if (Alias.hasWeakLinkage() || Alias.hasLinkOnceLinkage())
1065       OutStreamer.EmitSymbolAttribute(Name, MCSA_WeakReference);
1066     else
1067       assert(Alias.hasLocalLinkage() && "Invalid alias linkage");
1068
1069     EmitVisibility(Name, Alias.getVisibility());
1070
1071     // Emit the directives as assignments aka .set:
1072     OutStreamer.EmitAssignment(Name, lowerConstant(Alias.getAliasee()));
1073   }
1074
1075   GCModuleInfo *MI = getAnalysisIfAvailable<GCModuleInfo>();
1076   assert(MI && "AsmPrinter didn't require GCModuleInfo?");
1077   for (GCModuleInfo::iterator I = MI->end(), E = MI->begin(); I != E; )
1078     if (GCMetadataPrinter *MP = GetOrCreateGCPrinter(**--I))
1079       MP->finishAssembly(M, *MI, *this);
1080
1081   // Emit llvm.ident metadata in an '.ident' directive.
1082   EmitModuleIdents(M);
1083
1084   // Emit __morestack address if needed for indirect calls.
1085   if (MMI->usesMorestackAddr()) {
1086     const MCSection *ReadOnlySection =
1087         getObjFileLowering().getSectionForConstant(SectionKind::getReadOnly(),
1088                                                    /*C=*/nullptr);
1089     OutStreamer.SwitchSection(ReadOnlySection);
1090
1091     MCSymbol *AddrSymbol =
1092         OutContext.GetOrCreateSymbol(StringRef("__morestack_addr"));
1093     OutStreamer.EmitLabel(AddrSymbol);
1094
1095     unsigned PtrSize = TM.getDataLayout()->getPointerSize(0);
1096     OutStreamer.EmitSymbolValue(GetExternalSymbolSymbol("__morestack"),
1097                                 PtrSize);
1098   }
1099
1100   // If we don't have any trampolines, then we don't require stack memory
1101   // to be executable. Some targets have a directive to declare this.
1102   Function *InitTrampolineIntrinsic = M.getFunction("llvm.init.trampoline");
1103   if (!InitTrampolineIntrinsic || InitTrampolineIntrinsic->use_empty())
1104     if (const MCSection *S = MAI->getNonexecutableStackSection(OutContext))
1105       OutStreamer.SwitchSection(S);
1106
1107   // Allow the target to emit any magic that it wants at the end of the file,
1108   // after everything else has gone out.
1109   EmitEndOfAsmFile(M);
1110
1111   delete Mang; Mang = nullptr;
1112   MMI = nullptr;
1113
1114   OutStreamer.Finish();
1115   OutStreamer.reset();
1116
1117   return false;
1118 }
1119
1120 void AsmPrinter::SetupMachineFunction(MachineFunction &MF) {
1121   this->MF = &MF;
1122   // Get the function symbol.
1123   CurrentFnSym = getSymbol(MF.getFunction());
1124   CurrentFnSymForSize = CurrentFnSym;
1125
1126   if (isVerbose())
1127     LI = &getAnalysis<MachineLoopInfo>();
1128 }
1129
1130 namespace {
1131   // SectionCPs - Keep track the alignment, constpool entries per Section.
1132   struct SectionCPs {
1133     const MCSection *S;
1134     unsigned Alignment;
1135     SmallVector<unsigned, 4> CPEs;
1136     SectionCPs(const MCSection *s, unsigned a) : S(s), Alignment(a) {}
1137   };
1138 }
1139
1140 /// EmitConstantPool - Print to the current output stream assembly
1141 /// representations of the constants in the constant pool MCP. This is
1142 /// used to print out constants which have been "spilled to memory" by
1143 /// the code generator.
1144 ///
1145 void AsmPrinter::EmitConstantPool() {
1146   const MachineConstantPool *MCP = MF->getConstantPool();
1147   const std::vector<MachineConstantPoolEntry> &CP = MCP->getConstants();
1148   if (CP.empty()) return;
1149
1150   // Calculate sections for constant pool entries. We collect entries to go into
1151   // the same section together to reduce amount of section switch statements.
1152   SmallVector<SectionCPs, 4> CPSections;
1153   for (unsigned i = 0, e = CP.size(); i != e; ++i) {
1154     const MachineConstantPoolEntry &CPE = CP[i];
1155     unsigned Align = CPE.getAlignment();
1156
1157     SectionKind Kind =
1158         CPE.getSectionKind(TM.getDataLayout());
1159
1160     const Constant *C = nullptr;
1161     if (!CPE.isMachineConstantPoolEntry())
1162       C = CPE.Val.ConstVal;
1163
1164     const MCSection *S = getObjFileLowering().getSectionForConstant(Kind, C);
1165
1166     // The number of sections are small, just do a linear search from the
1167     // last section to the first.
1168     bool Found = false;
1169     unsigned SecIdx = CPSections.size();
1170     while (SecIdx != 0) {
1171       if (CPSections[--SecIdx].S == S) {
1172         Found = true;
1173         break;
1174       }
1175     }
1176     if (!Found) {
1177       SecIdx = CPSections.size();
1178       CPSections.push_back(SectionCPs(S, Align));
1179     }
1180
1181     if (Align > CPSections[SecIdx].Alignment)
1182       CPSections[SecIdx].Alignment = Align;
1183     CPSections[SecIdx].CPEs.push_back(i);
1184   }
1185
1186   // Now print stuff into the calculated sections.
1187   const MCSection *CurSection = nullptr;
1188   unsigned Offset = 0;
1189   for (unsigned i = 0, e = CPSections.size(); i != e; ++i) {
1190     for (unsigned j = 0, ee = CPSections[i].CPEs.size(); j != ee; ++j) {
1191       unsigned CPI = CPSections[i].CPEs[j];
1192       MCSymbol *Sym = GetCPISymbol(CPI);
1193       if (!Sym->isUndefined())
1194         continue;
1195
1196       if (CurSection != CPSections[i].S) {
1197         OutStreamer.SwitchSection(CPSections[i].S);
1198         EmitAlignment(Log2_32(CPSections[i].Alignment));
1199         CurSection = CPSections[i].S;
1200         Offset = 0;
1201       }
1202
1203       MachineConstantPoolEntry CPE = CP[CPI];
1204
1205       // Emit inter-object padding for alignment.
1206       unsigned AlignMask = CPE.getAlignment() - 1;
1207       unsigned NewOffset = (Offset + AlignMask) & ~AlignMask;
1208       OutStreamer.EmitZeros(NewOffset - Offset);
1209
1210       Type *Ty = CPE.getType();
1211       Offset = NewOffset +
1212                TM.getDataLayout()->getTypeAllocSize(Ty);
1213
1214       OutStreamer.EmitLabel(Sym);
1215       if (CPE.isMachineConstantPoolEntry())
1216         EmitMachineConstantPoolValue(CPE.Val.MachineCPVal);
1217       else
1218         EmitGlobalConstant(CPE.Val.ConstVal);
1219     }
1220   }
1221 }
1222
1223 /// EmitJumpTableInfo - Print assembly representations of the jump tables used
1224 /// by the current function to the current output stream.
1225 ///
1226 void AsmPrinter::EmitJumpTableInfo() {
1227   const DataLayout *DL = MF->getTarget().getDataLayout();
1228   const MachineJumpTableInfo *MJTI = MF->getJumpTableInfo();
1229   if (!MJTI) return;
1230   if (MJTI->getEntryKind() == MachineJumpTableInfo::EK_Inline) return;
1231   const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables();
1232   if (JT.empty()) return;
1233
1234   // Pick the directive to use to print the jump table entries, and switch to
1235   // the appropriate section.
1236   const Function *F = MF->getFunction();
1237   const TargetLoweringObjectFile &TLOF = getObjFileLowering();
1238   bool JTInDiffSection = !TLOF.shouldPutJumpTableInFunctionSection(
1239       MJTI->getEntryKind() == MachineJumpTableInfo::EK_LabelDifference32,
1240       *F);
1241   if (!JTInDiffSection) {
1242     OutStreamer.SwitchSection(TLOF.SectionForGlobal(F, *Mang, TM));
1243   } else {
1244     // Otherwise, drop it in the readonly section.
1245     const MCSection *ReadOnlySection =
1246         TLOF.getSectionForJumpTable(*F, *Mang, TM);
1247     OutStreamer.SwitchSection(ReadOnlySection);
1248   }
1249
1250   EmitAlignment(Log2_32(
1251       MJTI->getEntryAlignment(*TM.getDataLayout())));
1252
1253   // Jump tables in code sections are marked with a data_region directive
1254   // where that's supported.
1255   if (!JTInDiffSection)
1256     OutStreamer.EmitDataRegion(MCDR_DataRegionJT32);
1257
1258   for (unsigned JTI = 0, e = JT.size(); JTI != e; ++JTI) {
1259     const std::vector<MachineBasicBlock*> &JTBBs = JT[JTI].MBBs;
1260
1261     // If this jump table was deleted, ignore it.
1262     if (JTBBs.empty()) continue;
1263
1264     // For the EK_LabelDifference32 entry, if using .set avoids a relocation,
1265     /// emit a .set directive for each unique entry.
1266     if (MJTI->getEntryKind() == MachineJumpTableInfo::EK_LabelDifference32 &&
1267         MAI->doesSetDirectiveSuppressesReloc()) {
1268       SmallPtrSet<const MachineBasicBlock*, 16> EmittedSets;
1269       const TargetLowering *TLI = MF->getSubtarget().getTargetLowering();
1270       const MCExpr *Base = TLI->getPICJumpTableRelocBaseExpr(MF,JTI,OutContext);
1271       for (unsigned ii = 0, ee = JTBBs.size(); ii != ee; ++ii) {
1272         const MachineBasicBlock *MBB = JTBBs[ii];
1273         if (!EmittedSets.insert(MBB).second)
1274           continue;
1275
1276         // .set LJTSet, LBB32-base
1277         const MCExpr *LHS =
1278           MCSymbolRefExpr::Create(MBB->getSymbol(), OutContext);
1279         OutStreamer.EmitAssignment(GetJTSetSymbol(JTI, MBB->getNumber()),
1280                                 MCBinaryExpr::CreateSub(LHS, Base, OutContext));
1281       }
1282     }
1283
1284     // On some targets (e.g. Darwin) we want to emit two consecutive labels
1285     // before each jump table.  The first label is never referenced, but tells
1286     // the assembler and linker the extents of the jump table object.  The
1287     // second label is actually referenced by the code.
1288     if (JTInDiffSection && DL->hasLinkerPrivateGlobalPrefix())
1289       // FIXME: This doesn't have to have any specific name, just any randomly
1290       // named and numbered 'l' label would work.  Simplify GetJTISymbol.
1291       OutStreamer.EmitLabel(GetJTISymbol(JTI, true));
1292
1293     OutStreamer.EmitLabel(GetJTISymbol(JTI));
1294
1295     for (unsigned ii = 0, ee = JTBBs.size(); ii != ee; ++ii)
1296       EmitJumpTableEntry(MJTI, JTBBs[ii], JTI);
1297   }
1298   if (!JTInDiffSection)
1299     OutStreamer.EmitDataRegion(MCDR_DataRegionEnd);
1300 }
1301
1302 /// EmitJumpTableEntry - Emit a jump table entry for the specified MBB to the
1303 /// current stream.
1304 void AsmPrinter::EmitJumpTableEntry(const MachineJumpTableInfo *MJTI,
1305                                     const MachineBasicBlock *MBB,
1306                                     unsigned UID) const {
1307   assert(MBB && MBB->getNumber() >= 0 && "Invalid basic block");
1308   const MCExpr *Value = nullptr;
1309   switch (MJTI->getEntryKind()) {
1310   case MachineJumpTableInfo::EK_Inline:
1311     llvm_unreachable("Cannot emit EK_Inline jump table entry");
1312   case MachineJumpTableInfo::EK_Custom32:
1313     Value = MF->getSubtarget().getTargetLowering()->LowerCustomJumpTableEntry(
1314         MJTI, MBB, UID, OutContext);
1315     break;
1316   case MachineJumpTableInfo::EK_BlockAddress:
1317     // EK_BlockAddress - Each entry is a plain address of block, e.g.:
1318     //     .word LBB123
1319     Value = MCSymbolRefExpr::Create(MBB->getSymbol(), OutContext);
1320     break;
1321   case MachineJumpTableInfo::EK_GPRel32BlockAddress: {
1322     // EK_GPRel32BlockAddress - Each entry is an address of block, encoded
1323     // with a relocation as gp-relative, e.g.:
1324     //     .gprel32 LBB123
1325     MCSymbol *MBBSym = MBB->getSymbol();
1326     OutStreamer.EmitGPRel32Value(MCSymbolRefExpr::Create(MBBSym, OutContext));
1327     return;
1328   }
1329
1330   case MachineJumpTableInfo::EK_GPRel64BlockAddress: {
1331     // EK_GPRel64BlockAddress - Each entry is an address of block, encoded
1332     // with a relocation as gp-relative, e.g.:
1333     //     .gpdword LBB123
1334     MCSymbol *MBBSym = MBB->getSymbol();
1335     OutStreamer.EmitGPRel64Value(MCSymbolRefExpr::Create(MBBSym, OutContext));
1336     return;
1337   }
1338
1339   case MachineJumpTableInfo::EK_LabelDifference32: {
1340     // Each entry is the address of the block minus the address of the jump
1341     // table. This is used for PIC jump tables where gprel32 is not supported.
1342     // e.g.:
1343     //      .word LBB123 - LJTI1_2
1344     // If the .set directive avoids relocations, this is emitted as:
1345     //      .set L4_5_set_123, LBB123 - LJTI1_2
1346     //      .word L4_5_set_123
1347     if (MAI->doesSetDirectiveSuppressesReloc()) {
1348       Value = MCSymbolRefExpr::Create(GetJTSetSymbol(UID, MBB->getNumber()),
1349                                       OutContext);
1350       break;
1351     }
1352     Value = MCSymbolRefExpr::Create(MBB->getSymbol(), OutContext);
1353     const TargetLowering *TLI = MF->getSubtarget().getTargetLowering();
1354     const MCExpr *Base = TLI->getPICJumpTableRelocBaseExpr(MF, UID, OutContext);
1355     Value = MCBinaryExpr::CreateSub(Value, Base, OutContext);
1356     break;
1357   }
1358   }
1359
1360   assert(Value && "Unknown entry kind!");
1361
1362   unsigned EntrySize =
1363       MJTI->getEntrySize(*TM.getDataLayout());
1364   OutStreamer.EmitValue(Value, EntrySize);
1365 }
1366
1367
1368 /// EmitSpecialLLVMGlobal - Check to see if the specified global is a
1369 /// special global used by LLVM.  If so, emit it and return true, otherwise
1370 /// do nothing and return false.
1371 bool AsmPrinter::EmitSpecialLLVMGlobal(const GlobalVariable *GV) {
1372   if (GV->getName() == "llvm.used") {
1373     if (MAI->hasNoDeadStrip())    // No need to emit this at all.
1374       EmitLLVMUsedList(cast<ConstantArray>(GV->getInitializer()));
1375     return true;
1376   }
1377
1378   // Ignore debug and non-emitted data.  This handles llvm.compiler.used.
1379   if (StringRef(GV->getSection()) == "llvm.metadata" ||
1380       GV->hasAvailableExternallyLinkage())
1381     return true;
1382
1383   if (!GV->hasAppendingLinkage()) return false;
1384
1385   assert(GV->hasInitializer() && "Not a special LLVM global!");
1386
1387   if (GV->getName() == "llvm.global_ctors") {
1388     EmitXXStructorList(GV->getInitializer(), /* isCtor */ true);
1389
1390     if (TM.getRelocationModel() == Reloc::Static &&
1391         MAI->hasStaticCtorDtorReferenceInStaticMode()) {
1392       StringRef Sym(".constructors_used");
1393       OutStreamer.EmitSymbolAttribute(OutContext.GetOrCreateSymbol(Sym),
1394                                       MCSA_Reference);
1395     }
1396     return true;
1397   }
1398
1399   if (GV->getName() == "llvm.global_dtors") {
1400     EmitXXStructorList(GV->getInitializer(), /* isCtor */ false);
1401
1402     if (TM.getRelocationModel() == Reloc::Static &&
1403         MAI->hasStaticCtorDtorReferenceInStaticMode()) {
1404       StringRef Sym(".destructors_used");
1405       OutStreamer.EmitSymbolAttribute(OutContext.GetOrCreateSymbol(Sym),
1406                                       MCSA_Reference);
1407     }
1408     return true;
1409   }
1410
1411   return false;
1412 }
1413
1414 /// EmitLLVMUsedList - For targets that define a MAI::UsedDirective, mark each
1415 /// global in the specified llvm.used list for which emitUsedDirectiveFor
1416 /// is true, as being used with this directive.
1417 void AsmPrinter::EmitLLVMUsedList(const ConstantArray *InitList) {
1418   // Should be an array of 'i8*'.
1419   for (unsigned i = 0, e = InitList->getNumOperands(); i != e; ++i) {
1420     const GlobalValue *GV =
1421       dyn_cast<GlobalValue>(InitList->getOperand(i)->stripPointerCasts());
1422     if (GV)
1423       OutStreamer.EmitSymbolAttribute(getSymbol(GV), MCSA_NoDeadStrip);
1424   }
1425 }
1426
1427 namespace {
1428 struct Structor {
1429   Structor() : Priority(0), Func(nullptr), ComdatKey(nullptr) {}
1430   int Priority;
1431   llvm::Constant *Func;
1432   llvm::GlobalValue *ComdatKey;
1433 };
1434 } // end namespace
1435
1436 /// EmitXXStructorList - Emit the ctor or dtor list taking into account the init
1437 /// priority.
1438 void AsmPrinter::EmitXXStructorList(const Constant *List, bool isCtor) {
1439   // Should be an array of '{ int, void ()* }' structs.  The first value is the
1440   // init priority.
1441   if (!isa<ConstantArray>(List)) return;
1442
1443   // Sanity check the structors list.
1444   const ConstantArray *InitList = dyn_cast<ConstantArray>(List);
1445   if (!InitList) return; // Not an array!
1446   StructType *ETy = dyn_cast<StructType>(InitList->getType()->getElementType());
1447   // FIXME: Only allow the 3-field form in LLVM 4.0.
1448   if (!ETy || ETy->getNumElements() < 2 || ETy->getNumElements() > 3)
1449     return; // Not an array of two or three elements!
1450   if (!isa<IntegerType>(ETy->getTypeAtIndex(0U)) ||
1451       !isa<PointerType>(ETy->getTypeAtIndex(1U))) return; // Not (int, ptr).
1452   if (ETy->getNumElements() == 3 && !isa<PointerType>(ETy->getTypeAtIndex(2U)))
1453     return; // Not (int, ptr, ptr).
1454
1455   // Gather the structors in a form that's convenient for sorting by priority.
1456   SmallVector<Structor, 8> Structors;
1457   for (Value *O : InitList->operands()) {
1458     ConstantStruct *CS = dyn_cast<ConstantStruct>(O);
1459     if (!CS) continue; // Malformed.
1460     if (CS->getOperand(1)->isNullValue())
1461       break;  // Found a null terminator, skip the rest.
1462     ConstantInt *Priority = dyn_cast<ConstantInt>(CS->getOperand(0));
1463     if (!Priority) continue; // Malformed.
1464     Structors.push_back(Structor());
1465     Structor &S = Structors.back();
1466     S.Priority = Priority->getLimitedValue(65535);
1467     S.Func = CS->getOperand(1);
1468     if (ETy->getNumElements() == 3 && !CS->getOperand(2)->isNullValue())
1469       S.ComdatKey = dyn_cast<GlobalValue>(CS->getOperand(2)->stripPointerCasts());
1470   }
1471
1472   // Emit the function pointers in the target-specific order
1473   const DataLayout *DL = TM.getDataLayout();
1474   unsigned Align = Log2_32(DL->getPointerPrefAlignment());
1475   std::stable_sort(Structors.begin(), Structors.end(),
1476                    [](const Structor &L,
1477                       const Structor &R) { return L.Priority < R.Priority; });
1478   for (Structor &S : Structors) {
1479     const TargetLoweringObjectFile &Obj = getObjFileLowering();
1480     const MCSymbol *KeySym = nullptr;
1481     if (GlobalValue *GV = S.ComdatKey) {
1482       if (GV->hasAvailableExternallyLinkage())
1483         // If the associated variable is available_externally, some other TU
1484         // will provide its dynamic initializer.
1485         continue;
1486
1487       KeySym = getSymbol(GV);
1488     }
1489     const MCSection *OutputSection =
1490         (isCtor ? Obj.getStaticCtorSection(S.Priority, KeySym)
1491                 : Obj.getStaticDtorSection(S.Priority, KeySym));
1492     OutStreamer.SwitchSection(OutputSection);
1493     if (OutStreamer.getCurrentSection() != OutStreamer.getPreviousSection())
1494       EmitAlignment(Align);
1495     EmitXXStructor(S.Func);
1496   }
1497 }
1498
1499 void AsmPrinter::EmitModuleIdents(Module &M) {
1500   if (!MAI->hasIdentDirective())
1501     return;
1502
1503   if (const NamedMDNode *NMD = M.getNamedMetadata("llvm.ident")) {
1504     for (unsigned i = 0, e = NMD->getNumOperands(); i != e; ++i) {
1505       const MDNode *N = NMD->getOperand(i);
1506       assert(N->getNumOperands() == 1 &&
1507              "llvm.ident metadata entry can have only one operand");
1508       const MDString *S = cast<MDString>(N->getOperand(0));
1509       OutStreamer.EmitIdent(S->getString());
1510     }
1511   }
1512 }
1513
1514 //===--------------------------------------------------------------------===//
1515 // Emission and print routines
1516 //
1517
1518 /// EmitInt8 - Emit a byte directive and value.
1519 ///
1520 void AsmPrinter::EmitInt8(int Value) const {
1521   OutStreamer.EmitIntValue(Value, 1);
1522 }
1523
1524 /// EmitInt16 - Emit a short directive and value.
1525 ///
1526 void AsmPrinter::EmitInt16(int Value) const {
1527   OutStreamer.EmitIntValue(Value, 2);
1528 }
1529
1530 /// EmitInt32 - Emit a long directive and value.
1531 ///
1532 void AsmPrinter::EmitInt32(int Value) const {
1533   OutStreamer.EmitIntValue(Value, 4);
1534 }
1535
1536 /// Emit something like ".long Hi-Lo" where the size in bytes of the directive
1537 /// is specified by Size and Hi/Lo specify the labels. This implicitly uses
1538 /// .set if it avoids relocations.
1539 void AsmPrinter::EmitLabelDifference(const MCSymbol *Hi, const MCSymbol *Lo,
1540                                      unsigned Size) const {
1541   // Get the Hi-Lo expression.
1542   const MCExpr *Diff =
1543     MCBinaryExpr::CreateSub(MCSymbolRefExpr::Create(Hi, OutContext),
1544                             MCSymbolRefExpr::Create(Lo, OutContext),
1545                             OutContext);
1546
1547   if (!MAI->doesSetDirectiveSuppressesReloc()) {
1548     OutStreamer.EmitValue(Diff, Size);
1549     return;
1550   }
1551
1552   // Otherwise, emit with .set (aka assignment).
1553   MCSymbol *SetLabel = GetTempSymbol("set", SetCounter++);
1554   OutStreamer.EmitAssignment(SetLabel, Diff);
1555   OutStreamer.EmitSymbolValue(SetLabel, Size);
1556 }
1557
1558 /// EmitLabelPlusOffset - Emit something like ".long Label+Offset"
1559 /// where the size in bytes of the directive is specified by Size and Label
1560 /// specifies the label.  This implicitly uses .set if it is available.
1561 void AsmPrinter::EmitLabelPlusOffset(const MCSymbol *Label, uint64_t Offset,
1562                                      unsigned Size,
1563                                      bool IsSectionRelative) const {
1564   if (MAI->needsDwarfSectionOffsetDirective() && IsSectionRelative) {
1565     OutStreamer.EmitCOFFSecRel32(Label);
1566     return;
1567   }
1568
1569   // Emit Label+Offset (or just Label if Offset is zero)
1570   const MCExpr *Expr = MCSymbolRefExpr::Create(Label, OutContext);
1571   if (Offset)
1572     Expr = MCBinaryExpr::CreateAdd(
1573         Expr, MCConstantExpr::Create(Offset, OutContext), OutContext);
1574
1575   OutStreamer.EmitValue(Expr, Size);
1576 }
1577
1578 //===----------------------------------------------------------------------===//
1579
1580 // EmitAlignment - Emit an alignment directive to the specified power of
1581 // two boundary.  For example, if you pass in 3 here, you will get an 8
1582 // byte alignment.  If a global value is specified, and if that global has
1583 // an explicit alignment requested, it will override the alignment request
1584 // if required for correctness.
1585 //
1586 void AsmPrinter::EmitAlignment(unsigned NumBits, const GlobalObject *GV) const {
1587   if (GV)
1588     NumBits = getGVAlignmentLog2(GV, *TM.getDataLayout(),
1589                                  NumBits);
1590
1591   if (NumBits == 0) return;   // 1-byte aligned: no need to emit alignment.
1592
1593   assert(NumBits <
1594              static_cast<unsigned>(std::numeric_limits<unsigned>::digits) &&
1595          "undefined behavior");
1596   if (getCurrentSection()->getKind().isText())
1597     OutStreamer.EmitCodeAlignment(1u << NumBits);
1598   else
1599     OutStreamer.EmitValueToAlignment(1u << NumBits);
1600 }
1601
1602 //===----------------------------------------------------------------------===//
1603 // Constant emission.
1604 //===----------------------------------------------------------------------===//
1605
1606 const MCExpr *AsmPrinter::lowerConstant(const Constant *CV) {
1607   MCContext &Ctx = OutContext;
1608
1609   if (CV->isNullValue() || isa<UndefValue>(CV))
1610     return MCConstantExpr::Create(0, Ctx);
1611
1612   if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV))
1613     return MCConstantExpr::Create(CI->getZExtValue(), Ctx);
1614
1615   if (const GlobalValue *GV = dyn_cast<GlobalValue>(CV))
1616     return MCSymbolRefExpr::Create(getSymbol(GV), Ctx);
1617
1618   if (const BlockAddress *BA = dyn_cast<BlockAddress>(CV))
1619     return MCSymbolRefExpr::Create(GetBlockAddressSymbol(BA), Ctx);
1620
1621   const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV);
1622   if (!CE) {
1623     llvm_unreachable("Unknown constant value to lower!");
1624   }
1625
1626   if (const MCExpr *RelocExpr
1627       = getObjFileLowering().getExecutableRelativeSymbol(CE, *Mang, TM))
1628     return RelocExpr;
1629
1630   switch (CE->getOpcode()) {
1631   default:
1632     // If the code isn't optimized, there may be outstanding folding
1633     // opportunities. Attempt to fold the expression using DataLayout as a
1634     // last resort before giving up.
1635     if (Constant *C = ConstantFoldConstantExpression(
1636             CE, TM.getDataLayout()))
1637       if (C != CE)
1638         return lowerConstant(C);
1639
1640     // Otherwise report the problem to the user.
1641     {
1642       std::string S;
1643       raw_string_ostream OS(S);
1644       OS << "Unsupported expression in static initializer: ";
1645       CE->printAsOperand(OS, /*PrintType=*/false,
1646                      !MF ? nullptr : MF->getFunction()->getParent());
1647       report_fatal_error(OS.str());
1648     }
1649   case Instruction::GetElementPtr: {
1650     const DataLayout &DL = *TM.getDataLayout();
1651
1652     // Generate a symbolic expression for the byte address
1653     APInt OffsetAI(DL.getPointerTypeSizeInBits(CE->getType()), 0);
1654     cast<GEPOperator>(CE)->accumulateConstantOffset(DL, OffsetAI);
1655
1656     const MCExpr *Base = lowerConstant(CE->getOperand(0));
1657     if (!OffsetAI)
1658       return Base;
1659
1660     int64_t Offset = OffsetAI.getSExtValue();
1661     return MCBinaryExpr::CreateAdd(Base, MCConstantExpr::Create(Offset, Ctx),
1662                                    Ctx);
1663   }
1664
1665   case Instruction::Trunc:
1666     // We emit the value and depend on the assembler to truncate the generated
1667     // expression properly.  This is important for differences between
1668     // blockaddress labels.  Since the two labels are in the same function, it
1669     // is reasonable to treat their delta as a 32-bit value.
1670     // FALL THROUGH.
1671   case Instruction::BitCast:
1672     return lowerConstant(CE->getOperand(0));
1673
1674   case Instruction::IntToPtr: {
1675     const DataLayout &DL = *TM.getDataLayout();
1676
1677     // Handle casts to pointers by changing them into casts to the appropriate
1678     // integer type.  This promotes constant folding and simplifies this code.
1679     Constant *Op = CE->getOperand(0);
1680     Op = ConstantExpr::getIntegerCast(Op, DL.getIntPtrType(CV->getType()),
1681                                       false/*ZExt*/);
1682     return lowerConstant(Op);
1683   }
1684
1685   case Instruction::PtrToInt: {
1686     const DataLayout &DL = *TM.getDataLayout();
1687
1688     // Support only foldable casts to/from pointers that can be eliminated by
1689     // changing the pointer to the appropriately sized integer type.
1690     Constant *Op = CE->getOperand(0);
1691     Type *Ty = CE->getType();
1692
1693     const MCExpr *OpExpr = lowerConstant(Op);
1694
1695     // We can emit the pointer value into this slot if the slot is an
1696     // integer slot equal to the size of the pointer.
1697     if (DL.getTypeAllocSize(Ty) == DL.getTypeAllocSize(Op->getType()))
1698       return OpExpr;
1699
1700     // Otherwise the pointer is smaller than the resultant integer, mask off
1701     // the high bits so we are sure to get a proper truncation if the input is
1702     // a constant expr.
1703     unsigned InBits = DL.getTypeAllocSizeInBits(Op->getType());
1704     const MCExpr *MaskExpr = MCConstantExpr::Create(~0ULL >> (64-InBits), Ctx);
1705     return MCBinaryExpr::CreateAnd(OpExpr, MaskExpr, Ctx);
1706   }
1707
1708   // The MC library also has a right-shift operator, but it isn't consistently
1709   // signed or unsigned between different targets.
1710   case Instruction::Add:
1711   case Instruction::Sub:
1712   case Instruction::Mul:
1713   case Instruction::SDiv:
1714   case Instruction::SRem:
1715   case Instruction::Shl:
1716   case Instruction::And:
1717   case Instruction::Or:
1718   case Instruction::Xor: {
1719     const MCExpr *LHS = lowerConstant(CE->getOperand(0));
1720     const MCExpr *RHS = lowerConstant(CE->getOperand(1));
1721     switch (CE->getOpcode()) {
1722     default: llvm_unreachable("Unknown binary operator constant cast expr");
1723     case Instruction::Add: return MCBinaryExpr::CreateAdd(LHS, RHS, Ctx);
1724     case Instruction::Sub: return MCBinaryExpr::CreateSub(LHS, RHS, Ctx);
1725     case Instruction::Mul: return MCBinaryExpr::CreateMul(LHS, RHS, Ctx);
1726     case Instruction::SDiv: return MCBinaryExpr::CreateDiv(LHS, RHS, Ctx);
1727     case Instruction::SRem: return MCBinaryExpr::CreateMod(LHS, RHS, Ctx);
1728     case Instruction::Shl: return MCBinaryExpr::CreateShl(LHS, RHS, Ctx);
1729     case Instruction::And: return MCBinaryExpr::CreateAnd(LHS, RHS, Ctx);
1730     case Instruction::Or:  return MCBinaryExpr::CreateOr (LHS, RHS, Ctx);
1731     case Instruction::Xor: return MCBinaryExpr::CreateXor(LHS, RHS, Ctx);
1732     }
1733   }
1734   }
1735 }
1736
1737 static void emitGlobalConstantImpl(const Constant *C, AsmPrinter &AP,
1738                                    const Constant *BaseCV = nullptr,
1739                                    uint64_t Offset = 0);
1740
1741 /// isRepeatedByteSequence - Determine whether the given value is
1742 /// composed of a repeated sequence of identical bytes and return the
1743 /// byte value.  If it is not a repeated sequence, return -1.
1744 static int isRepeatedByteSequence(const ConstantDataSequential *V) {
1745   StringRef Data = V->getRawDataValues();
1746   assert(!Data.empty() && "Empty aggregates should be CAZ node");
1747   char C = Data[0];
1748   for (unsigned i = 1, e = Data.size(); i != e; ++i)
1749     if (Data[i] != C) return -1;
1750   return static_cast<uint8_t>(C); // Ensure 255 is not returned as -1.
1751 }
1752
1753
1754 /// isRepeatedByteSequence - Determine whether the given value is
1755 /// composed of a repeated sequence of identical bytes and return the
1756 /// byte value.  If it is not a repeated sequence, return -1.
1757 static int isRepeatedByteSequence(const Value *V, TargetMachine &TM) {
1758
1759   if (const ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
1760     if (CI->getBitWidth() > 64) return -1;
1761
1762     uint64_t Size =
1763         TM.getDataLayout()->getTypeAllocSize(V->getType());
1764     uint64_t Value = CI->getZExtValue();
1765
1766     // Make sure the constant is at least 8 bits long and has a power
1767     // of 2 bit width.  This guarantees the constant bit width is
1768     // always a multiple of 8 bits, avoiding issues with padding out
1769     // to Size and other such corner cases.
1770     if (CI->getBitWidth() < 8 || !isPowerOf2_64(CI->getBitWidth())) return -1;
1771
1772     uint8_t Byte = static_cast<uint8_t>(Value);
1773
1774     for (unsigned i = 1; i < Size; ++i) {
1775       Value >>= 8;
1776       if (static_cast<uint8_t>(Value) != Byte) return -1;
1777     }
1778     return Byte;
1779   }
1780   if (const ConstantArray *CA = dyn_cast<ConstantArray>(V)) {
1781     // Make sure all array elements are sequences of the same repeated
1782     // byte.
1783     assert(CA->getNumOperands() != 0 && "Should be a CAZ");
1784     int Byte = isRepeatedByteSequence(CA->getOperand(0), TM);
1785     if (Byte == -1) return -1;
1786
1787     for (unsigned i = 1, e = CA->getNumOperands(); i != e; ++i) {
1788       int ThisByte = isRepeatedByteSequence(CA->getOperand(i), TM);
1789       if (ThisByte == -1) return -1;
1790       if (Byte != ThisByte) return -1;
1791     }
1792     return Byte;
1793   }
1794
1795   if (const ConstantDataSequential *CDS = dyn_cast<ConstantDataSequential>(V))
1796     return isRepeatedByteSequence(CDS);
1797
1798   return -1;
1799 }
1800
1801 static void emitGlobalConstantDataSequential(const ConstantDataSequential *CDS,
1802                                              AsmPrinter &AP){
1803
1804   // See if we can aggregate this into a .fill, if so, emit it as such.
1805   int Value = isRepeatedByteSequence(CDS, AP.TM);
1806   if (Value != -1) {
1807     uint64_t Bytes =
1808         AP.TM.getDataLayout()->getTypeAllocSize(
1809             CDS->getType());
1810     // Don't emit a 1-byte object as a .fill.
1811     if (Bytes > 1)
1812       return AP.OutStreamer.EmitFill(Bytes, Value);
1813   }
1814
1815   // If this can be emitted with .ascii/.asciz, emit it as such.
1816   if (CDS->isString())
1817     return AP.OutStreamer.EmitBytes(CDS->getAsString());
1818
1819   // Otherwise, emit the values in successive locations.
1820   unsigned ElementByteSize = CDS->getElementByteSize();
1821   if (isa<IntegerType>(CDS->getElementType())) {
1822     for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) {
1823       if (AP.isVerbose())
1824         AP.OutStreamer.GetCommentOS() << format("0x%" PRIx64 "\n",
1825                                                 CDS->getElementAsInteger(i));
1826       AP.OutStreamer.EmitIntValue(CDS->getElementAsInteger(i),
1827                                   ElementByteSize);
1828     }
1829   } else if (ElementByteSize == 4) {
1830     // FP Constants are printed as integer constants to avoid losing
1831     // precision.
1832     assert(CDS->getElementType()->isFloatTy());
1833     for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) {
1834       union {
1835         float F;
1836         uint32_t I;
1837       };
1838
1839       F = CDS->getElementAsFloat(i);
1840       if (AP.isVerbose())
1841         AP.OutStreamer.GetCommentOS() << "float " << F << '\n';
1842       AP.OutStreamer.EmitIntValue(I, 4);
1843     }
1844   } else {
1845     assert(CDS->getElementType()->isDoubleTy());
1846     for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) {
1847       union {
1848         double F;
1849         uint64_t I;
1850       };
1851
1852       F = CDS->getElementAsDouble(i);
1853       if (AP.isVerbose())
1854         AP.OutStreamer.GetCommentOS() << "double " << F << '\n';
1855       AP.OutStreamer.EmitIntValue(I, 8);
1856     }
1857   }
1858
1859   const DataLayout &DL = *AP.TM.getDataLayout();
1860   unsigned Size = DL.getTypeAllocSize(CDS->getType());
1861   unsigned EmittedSize = DL.getTypeAllocSize(CDS->getType()->getElementType()) *
1862                         CDS->getNumElements();
1863   if (unsigned Padding = Size - EmittedSize)
1864     AP.OutStreamer.EmitZeros(Padding);
1865
1866 }
1867
1868 static void emitGlobalConstantArray(const ConstantArray *CA, AsmPrinter &AP,
1869                                     const Constant *BaseCV, uint64_t Offset) {
1870   // See if we can aggregate some values.  Make sure it can be
1871   // represented as a series of bytes of the constant value.
1872   int Value = isRepeatedByteSequence(CA, AP.TM);
1873   const DataLayout &DL = *AP.TM.getDataLayout();
1874
1875   if (Value != -1) {
1876     uint64_t Bytes = DL.getTypeAllocSize(CA->getType());
1877     AP.OutStreamer.EmitFill(Bytes, Value);
1878   }
1879   else {
1880     for (unsigned i = 0, e = CA->getNumOperands(); i != e; ++i) {
1881       emitGlobalConstantImpl(CA->getOperand(i), AP, BaseCV, Offset);
1882       Offset += DL.getTypeAllocSize(CA->getOperand(i)->getType());
1883     }
1884   }
1885 }
1886
1887 static void emitGlobalConstantVector(const ConstantVector *CV, AsmPrinter &AP) {
1888   for (unsigned i = 0, e = CV->getType()->getNumElements(); i != e; ++i)
1889     emitGlobalConstantImpl(CV->getOperand(i), AP);
1890
1891   const DataLayout &DL = *AP.TM.getDataLayout();
1892   unsigned Size = DL.getTypeAllocSize(CV->getType());
1893   unsigned EmittedSize = DL.getTypeAllocSize(CV->getType()->getElementType()) *
1894                          CV->getType()->getNumElements();
1895   if (unsigned Padding = Size - EmittedSize)
1896     AP.OutStreamer.EmitZeros(Padding);
1897 }
1898
1899 static void emitGlobalConstantStruct(const ConstantStruct *CS, AsmPrinter &AP,
1900                                      const Constant *BaseCV, uint64_t Offset) {
1901   // Print the fields in successive locations. Pad to align if needed!
1902   const DataLayout *DL = AP.TM.getDataLayout();
1903   unsigned Size = DL->getTypeAllocSize(CS->getType());
1904   const StructLayout *Layout = DL->getStructLayout(CS->getType());
1905   uint64_t SizeSoFar = 0;
1906   for (unsigned i = 0, e = CS->getNumOperands(); i != e; ++i) {
1907     const Constant *Field = CS->getOperand(i);
1908
1909     // Print the actual field value.
1910     emitGlobalConstantImpl(Field, AP, BaseCV, Offset+SizeSoFar);
1911
1912     // Check if padding is needed and insert one or more 0s.
1913     uint64_t FieldSize = DL->getTypeAllocSize(Field->getType());
1914     uint64_t PadSize = ((i == e-1 ? Size : Layout->getElementOffset(i+1))
1915                         - Layout->getElementOffset(i)) - FieldSize;
1916     SizeSoFar += FieldSize + PadSize;
1917
1918     // Insert padding - this may include padding to increase the size of the
1919     // current field up to the ABI size (if the struct is not packed) as well
1920     // as padding to ensure that the next field starts at the right offset.
1921     AP.OutStreamer.EmitZeros(PadSize);
1922   }
1923   assert(SizeSoFar == Layout->getSizeInBytes() &&
1924          "Layout of constant struct may be incorrect!");
1925 }
1926
1927 static void emitGlobalConstantFP(const ConstantFP *CFP, AsmPrinter &AP) {
1928   APInt API = CFP->getValueAPF().bitcastToAPInt();
1929
1930   // First print a comment with what we think the original floating-point value
1931   // should have been.
1932   if (AP.isVerbose()) {
1933     SmallString<8> StrVal;
1934     CFP->getValueAPF().toString(StrVal);
1935
1936     if (CFP->getType())
1937       CFP->getType()->print(AP.OutStreamer.GetCommentOS());
1938     else
1939       AP.OutStreamer.GetCommentOS() << "Printing <null> Type";
1940     AP.OutStreamer.GetCommentOS() << ' ' << StrVal << '\n';
1941   }
1942
1943   // Now iterate through the APInt chunks, emitting them in endian-correct
1944   // order, possibly with a smaller chunk at beginning/end (e.g. for x87 80-bit
1945   // floats).
1946   unsigned NumBytes = API.getBitWidth() / 8;
1947   unsigned TrailingBytes = NumBytes % sizeof(uint64_t);
1948   const uint64_t *p = API.getRawData();
1949
1950   // PPC's long double has odd notions of endianness compared to how LLVM
1951   // handles it: p[0] goes first for *big* endian on PPC.
1952   if (AP.TM.getDataLayout()->isBigEndian() &&
1953       !CFP->getType()->isPPC_FP128Ty()) {
1954     int Chunk = API.getNumWords() - 1;
1955
1956     if (TrailingBytes)
1957       AP.OutStreamer.EmitIntValue(p[Chunk--], TrailingBytes);
1958
1959     for (; Chunk >= 0; --Chunk)
1960       AP.OutStreamer.EmitIntValue(p[Chunk], sizeof(uint64_t));
1961   } else {
1962     unsigned Chunk;
1963     for (Chunk = 0; Chunk < NumBytes / sizeof(uint64_t); ++Chunk)
1964       AP.OutStreamer.EmitIntValue(p[Chunk], sizeof(uint64_t));
1965
1966     if (TrailingBytes)
1967       AP.OutStreamer.EmitIntValue(p[Chunk], TrailingBytes);
1968   }
1969
1970   // Emit the tail padding for the long double.
1971   const DataLayout &DL = *AP.TM.getDataLayout();
1972   AP.OutStreamer.EmitZeros(DL.getTypeAllocSize(CFP->getType()) -
1973                            DL.getTypeStoreSize(CFP->getType()));
1974 }
1975
1976 static void emitGlobalConstantLargeInt(const ConstantInt *CI, AsmPrinter &AP) {
1977   const DataLayout *DL = AP.TM.getDataLayout();
1978   unsigned BitWidth = CI->getBitWidth();
1979
1980   // Copy the value as we may massage the layout for constants whose bit width
1981   // is not a multiple of 64-bits.
1982   APInt Realigned(CI->getValue());
1983   uint64_t ExtraBits = 0;
1984   unsigned ExtraBitsSize = BitWidth & 63;
1985
1986   if (ExtraBitsSize) {
1987     // The bit width of the data is not a multiple of 64-bits.
1988     // The extra bits are expected to be at the end of the chunk of the memory.
1989     // Little endian:
1990     // * Nothing to be done, just record the extra bits to emit.
1991     // Big endian:
1992     // * Record the extra bits to emit.
1993     // * Realign the raw data to emit the chunks of 64-bits.
1994     if (DL->isBigEndian()) {
1995       // Basically the structure of the raw data is a chunk of 64-bits cells:
1996       //    0        1         BitWidth / 64
1997       // [chunk1][chunk2] ... [chunkN].
1998       // The most significant chunk is chunkN and it should be emitted first.
1999       // However, due to the alignment issue chunkN contains useless bits.
2000       // Realign the chunks so that they contain only useless information:
2001       // ExtraBits     0       1       (BitWidth / 64) - 1
2002       //       chu[nk1 chu][nk2 chu] ... [nkN-1 chunkN]
2003       ExtraBits = Realigned.getRawData()[0] &
2004         (((uint64_t)-1) >> (64 - ExtraBitsSize));
2005       Realigned = Realigned.lshr(ExtraBitsSize);
2006     } else
2007       ExtraBits = Realigned.getRawData()[BitWidth / 64];
2008   }
2009
2010   // We don't expect assemblers to support integer data directives
2011   // for more than 64 bits, so we emit the data in at most 64-bit
2012   // quantities at a time.
2013   const uint64_t *RawData = Realigned.getRawData();
2014   for (unsigned i = 0, e = BitWidth / 64; i != e; ++i) {
2015     uint64_t Val = DL->isBigEndian() ? RawData[e - i - 1] : RawData[i];
2016     AP.OutStreamer.EmitIntValue(Val, 8);
2017   }
2018
2019   if (ExtraBitsSize) {
2020     // Emit the extra bits after the 64-bits chunks.
2021
2022     // Emit a directive that fills the expected size.
2023     uint64_t Size = AP.TM.getDataLayout()->getTypeAllocSize(
2024         CI->getType());
2025     Size -= (BitWidth / 64) * 8;
2026     assert(Size && Size * 8 >= ExtraBitsSize &&
2027            (ExtraBits & (((uint64_t)-1) >> (64 - ExtraBitsSize)))
2028            == ExtraBits && "Directive too small for extra bits.");
2029     AP.OutStreamer.EmitIntValue(ExtraBits, Size);
2030   }
2031 }
2032
2033 /// \brief Transform a not absolute MCExpr containing a reference to a GOT
2034 /// equivalent global, by a target specific GOT pc relative access to the
2035 /// final symbol.
2036 static void handleIndirectSymViaGOTPCRel(AsmPrinter &AP, const MCExpr **ME,
2037                                          const Constant *BaseCst,
2038                                          uint64_t Offset) {
2039   // The global @foo below illustrates a global that uses a got equivalent.
2040   //
2041   //  @bar = global i32 42
2042   //  @gotequiv = private unnamed_addr constant i32* @bar
2043   //  @foo = i32 trunc (i64 sub (i64 ptrtoint (i32** @gotequiv to i64),
2044   //                             i64 ptrtoint (i32* @foo to i64))
2045   //                        to i32)
2046   //
2047   // The cstexpr in @foo is converted into the MCExpr `ME`, where we actually
2048   // check whether @foo is suitable to use a GOTPCREL. `ME` is usually in the
2049   // form:
2050   //
2051   //  foo = cstexpr, where
2052   //    cstexpr := <gotequiv> - "." + <cst>
2053   //    cstexpr := <gotequiv> - (<foo> - <offset from @foo base>) + <cst>
2054   //
2055   // After canonicalization by EvaluateAsRelocatable `ME` turns into:
2056   //
2057   //  cstexpr := <gotequiv> - <foo> + gotpcrelcst, where
2058   //    gotpcrelcst := <offset from @foo base> + <cst>
2059   //
2060   MCValue MV;
2061   if (!(*ME)->EvaluateAsRelocatable(MV, nullptr, nullptr) || MV.isAbsolute())
2062     return;
2063
2064   const MCSymbol *GOTEquivSym = &MV.getSymA()->getSymbol();
2065   if (!AP.GlobalGOTEquivs.count(GOTEquivSym))
2066     return;
2067
2068   const GlobalValue *BaseGV = dyn_cast<GlobalValue>(BaseCst);
2069   if (!BaseGV)
2070     return;
2071
2072   const MCSymbol *BaseSym = AP.getSymbol(BaseGV);
2073   if (BaseSym != &MV.getSymB()->getSymbol())
2074     return;
2075
2076   // Make sure to match:
2077   //
2078   //    gotpcrelcst := <offset from @foo base> + <cst>
2079   //
2080   int64_t GOTPCRelCst = Offset + MV.getConstant();
2081   if (GOTPCRelCst < 0)
2082     return;
2083
2084   // Emit the GOT PC relative to replace the got equivalent global, i.e.:
2085   //
2086   //  bar:
2087   //    .long 42
2088   //  gotequiv:
2089   //    .quad bar
2090   //  foo:
2091   //    .long gotequiv - "." + <cst>
2092   //
2093   // is replaced by the target specific equivalent to:
2094   //
2095   //  bar:
2096   //    .long 42
2097   //  foo:
2098   //    .long bar@GOTPCREL+<gotpcrelcst>
2099   //
2100   AsmPrinter::GOTEquivUsePair Result = AP.GlobalGOTEquivs[GOTEquivSym];
2101   const GlobalVariable *GV = Result.first;
2102   unsigned NumUses = Result.second;
2103   const GlobalValue *FinalGV = dyn_cast<GlobalValue>(GV->getOperand(0));
2104   const MCSymbol *FinalSym = AP.getSymbol(FinalGV);
2105   *ME = AP.getObjFileLowering().getIndirectSymViaGOTPCRel(FinalSym,
2106                                                           GOTPCRelCst);
2107
2108   // Update GOT equivalent usage information
2109   --NumUses;
2110   if (NumUses)
2111     AP.GlobalGOTEquivs[GOTEquivSym] = std::make_pair(GV, NumUses);
2112   else
2113     AP.GlobalGOTEquivs.erase(GOTEquivSym);
2114 }
2115
2116 static void emitGlobalConstantImpl(const Constant *CV, AsmPrinter &AP,
2117                                    const Constant *BaseCV, uint64_t Offset) {
2118   const DataLayout *DL = AP.TM.getDataLayout();
2119   uint64_t Size = DL->getTypeAllocSize(CV->getType());
2120
2121   // Globals with sub-elements such as combinations of arrays and structs
2122   // are handled recursively by emitGlobalConstantImpl. Keep track of the
2123   // constant symbol base and the current position with BaseCV and Offset.
2124   if (!BaseCV && CV->hasOneUse())
2125     BaseCV = dyn_cast<Constant>(CV->user_back());
2126
2127   if (isa<ConstantAggregateZero>(CV) || isa<UndefValue>(CV))
2128     return AP.OutStreamer.EmitZeros(Size);
2129
2130   if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV)) {
2131     switch (Size) {
2132     case 1:
2133     case 2:
2134     case 4:
2135     case 8:
2136       if (AP.isVerbose())
2137         AP.OutStreamer.GetCommentOS() << format("0x%" PRIx64 "\n",
2138                                                 CI->getZExtValue());
2139       AP.OutStreamer.EmitIntValue(CI->getZExtValue(), Size);
2140       return;
2141     default:
2142       emitGlobalConstantLargeInt(CI, AP);
2143       return;
2144     }
2145   }
2146
2147   if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CV))
2148     return emitGlobalConstantFP(CFP, AP);
2149
2150   if (isa<ConstantPointerNull>(CV)) {
2151     AP.OutStreamer.EmitIntValue(0, Size);
2152     return;
2153   }
2154
2155   if (const ConstantDataSequential *CDS = dyn_cast<ConstantDataSequential>(CV))
2156     return emitGlobalConstantDataSequential(CDS, AP);
2157
2158   if (const ConstantArray *CVA = dyn_cast<ConstantArray>(CV))
2159     return emitGlobalConstantArray(CVA, AP, BaseCV, Offset);
2160
2161   if (const ConstantStruct *CVS = dyn_cast<ConstantStruct>(CV))
2162     return emitGlobalConstantStruct(CVS, AP, BaseCV, Offset);
2163
2164   if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV)) {
2165     // Look through bitcasts, which might not be able to be MCExpr'ized (e.g. of
2166     // vectors).
2167     if (CE->getOpcode() == Instruction::BitCast)
2168       return emitGlobalConstantImpl(CE->getOperand(0), AP);
2169
2170     if (Size > 8) {
2171       // If the constant expression's size is greater than 64-bits, then we have
2172       // to emit the value in chunks. Try to constant fold the value and emit it
2173       // that way.
2174       Constant *New = ConstantFoldConstantExpression(CE, DL);
2175       if (New && New != CE)
2176         return emitGlobalConstantImpl(New, AP);
2177     }
2178   }
2179
2180   if (const ConstantVector *V = dyn_cast<ConstantVector>(CV))
2181     return emitGlobalConstantVector(V, AP);
2182
2183   // Otherwise, it must be a ConstantExpr.  Lower it to an MCExpr, then emit it
2184   // thread the streamer with EmitValue.
2185   const MCExpr *ME = AP.lowerConstant(CV);
2186
2187   // Since lowerConstant already folded and got rid of all IR pointer and
2188   // integer casts, detect GOT equivalent accesses by looking into the MCExpr
2189   // directly.
2190   if (AP.getObjFileLowering().supportIndirectSymViaGOTPCRel())
2191     handleIndirectSymViaGOTPCRel(AP, &ME, BaseCV, Offset);
2192
2193   AP.OutStreamer.EmitValue(ME, Size);
2194 }
2195
2196 /// EmitGlobalConstant - Print a general LLVM constant to the .s file.
2197 void AsmPrinter::EmitGlobalConstant(const Constant *CV) {
2198   uint64_t Size =
2199       TM.getDataLayout()->getTypeAllocSize(CV->getType());
2200   if (Size)
2201     emitGlobalConstantImpl(CV, *this);
2202   else if (MAI->hasSubsectionsViaSymbols()) {
2203     // If the global has zero size, emit a single byte so that two labels don't
2204     // look like they are at the same location.
2205     OutStreamer.EmitIntValue(0, 1);
2206   }
2207 }
2208
2209 void AsmPrinter::EmitMachineConstantPoolValue(MachineConstantPoolValue *MCPV) {
2210   // Target doesn't support this yet!
2211   llvm_unreachable("Target does not support EmitMachineConstantPoolValue");
2212 }
2213
2214 void AsmPrinter::printOffset(int64_t Offset, raw_ostream &OS) const {
2215   if (Offset > 0)
2216     OS << '+' << Offset;
2217   else if (Offset < 0)
2218     OS << Offset;
2219 }
2220
2221 //===----------------------------------------------------------------------===//
2222 // Symbol Lowering Routines.
2223 //===----------------------------------------------------------------------===//
2224
2225 /// GetTempSymbol - Return the MCSymbol corresponding to the assembler
2226 /// temporary label with the specified stem and unique ID.
2227 MCSymbol *AsmPrinter::GetTempSymbol(const Twine &Name, unsigned ID) const {
2228   const DataLayout *DL = TM.getDataLayout();
2229   return OutContext.GetOrCreateSymbol(Twine(DL->getPrivateGlobalPrefix()) +
2230                                       Name + Twine(ID));
2231 }
2232
2233 /// GetTempSymbol - Return an assembler temporary label with the specified
2234 /// stem.
2235 MCSymbol *AsmPrinter::GetTempSymbol(const Twine &Name) const {
2236   const DataLayout *DL = TM.getDataLayout();
2237   return OutContext.GetOrCreateSymbol(Twine(DL->getPrivateGlobalPrefix())+
2238                                       Name);
2239 }
2240
2241 MCSymbol *AsmPrinter::createTempSymbol(const Twine &Name, unsigned ID) const {
2242   return OutContext.createTempSymbol(Name + Twine(ID));
2243 }
2244
2245 MCSymbol *AsmPrinter::GetBlockAddressSymbol(const BlockAddress *BA) const {
2246   return MMI->getAddrLabelSymbol(BA->getBasicBlock());
2247 }
2248
2249 MCSymbol *AsmPrinter::GetBlockAddressSymbol(const BasicBlock *BB) const {
2250   return MMI->getAddrLabelSymbol(BB);
2251 }
2252
2253 /// GetCPISymbol - Return the symbol for the specified constant pool entry.
2254 MCSymbol *AsmPrinter::GetCPISymbol(unsigned CPID) const {
2255   const DataLayout *DL = TM.getDataLayout();
2256   return OutContext.GetOrCreateSymbol
2257     (Twine(DL->getPrivateGlobalPrefix()) + "CPI" + Twine(getFunctionNumber())
2258      + "_" + Twine(CPID));
2259 }
2260
2261 /// GetJTISymbol - Return the symbol for the specified jump table entry.
2262 MCSymbol *AsmPrinter::GetJTISymbol(unsigned JTID, bool isLinkerPrivate) const {
2263   return MF->getJTISymbol(JTID, OutContext, isLinkerPrivate);
2264 }
2265
2266 /// GetJTSetSymbol - Return the symbol for the specified jump table .set
2267 /// FIXME: privatize to AsmPrinter.
2268 MCSymbol *AsmPrinter::GetJTSetSymbol(unsigned UID, unsigned MBBID) const {
2269   const DataLayout *DL = TM.getDataLayout();
2270   return OutContext.GetOrCreateSymbol
2271   (Twine(DL->getPrivateGlobalPrefix()) + Twine(getFunctionNumber()) + "_" +
2272    Twine(UID) + "_set_" + Twine(MBBID));
2273 }
2274
2275 MCSymbol *AsmPrinter::getSymbolWithGlobalValueBase(const GlobalValue *GV,
2276                                                    StringRef Suffix) const {
2277   return getObjFileLowering().getSymbolWithGlobalValueBase(GV, Suffix, *Mang,
2278                                                            TM);
2279 }
2280
2281 /// GetExternalSymbolSymbol - Return the MCSymbol for the specified
2282 /// ExternalSymbol.
2283 MCSymbol *AsmPrinter::GetExternalSymbolSymbol(StringRef Sym) const {
2284   SmallString<60> NameStr;
2285   Mang->getNameWithPrefix(NameStr, Sym);
2286   return OutContext.GetOrCreateSymbol(NameStr.str());
2287 }
2288
2289
2290
2291 /// PrintParentLoopComment - Print comments about parent loops of this one.
2292 static void PrintParentLoopComment(raw_ostream &OS, const MachineLoop *Loop,
2293                                    unsigned FunctionNumber) {
2294   if (!Loop) return;
2295   PrintParentLoopComment(OS, Loop->getParentLoop(), FunctionNumber);
2296   OS.indent(Loop->getLoopDepth()*2)
2297     << "Parent Loop BB" << FunctionNumber << "_"
2298     << Loop->getHeader()->getNumber()
2299     << " Depth=" << Loop->getLoopDepth() << '\n';
2300 }
2301
2302
2303 /// PrintChildLoopComment - Print comments about child loops within
2304 /// the loop for this basic block, with nesting.
2305 static void PrintChildLoopComment(raw_ostream &OS, const MachineLoop *Loop,
2306                                   unsigned FunctionNumber) {
2307   // Add child loop information
2308   for (const MachineLoop *CL : *Loop) {
2309     OS.indent(CL->getLoopDepth()*2)
2310       << "Child Loop BB" << FunctionNumber << "_"
2311       << CL->getHeader()->getNumber() << " Depth " << CL->getLoopDepth()
2312       << '\n';
2313     PrintChildLoopComment(OS, CL, FunctionNumber);
2314   }
2315 }
2316
2317 /// emitBasicBlockLoopComments - Pretty-print comments for basic blocks.
2318 static void emitBasicBlockLoopComments(const MachineBasicBlock &MBB,
2319                                        const MachineLoopInfo *LI,
2320                                        const AsmPrinter &AP) {
2321   // Add loop depth information
2322   const MachineLoop *Loop = LI->getLoopFor(&MBB);
2323   if (!Loop) return;
2324
2325   MachineBasicBlock *Header = Loop->getHeader();
2326   assert(Header && "No header for loop");
2327
2328   // If this block is not a loop header, just print out what is the loop header
2329   // and return.
2330   if (Header != &MBB) {
2331     AP.OutStreamer.AddComment("  in Loop: Header=BB" +
2332                               Twine(AP.getFunctionNumber())+"_" +
2333                               Twine(Loop->getHeader()->getNumber())+
2334                               " Depth="+Twine(Loop->getLoopDepth()));
2335     return;
2336   }
2337
2338   // Otherwise, it is a loop header.  Print out information about child and
2339   // parent loops.
2340   raw_ostream &OS = AP.OutStreamer.GetCommentOS();
2341
2342   PrintParentLoopComment(OS, Loop->getParentLoop(), AP.getFunctionNumber());
2343
2344   OS << "=>";
2345   OS.indent(Loop->getLoopDepth()*2-2);
2346
2347   OS << "This ";
2348   if (Loop->empty())
2349     OS << "Inner ";
2350   OS << "Loop Header: Depth=" + Twine(Loop->getLoopDepth()) << '\n';
2351
2352   PrintChildLoopComment(OS, Loop, AP.getFunctionNumber());
2353 }
2354
2355
2356 /// EmitBasicBlockStart - This method prints the label for the specified
2357 /// MachineBasicBlock, an alignment (if present) and a comment describing
2358 /// it if appropriate.
2359 void AsmPrinter::EmitBasicBlockStart(const MachineBasicBlock &MBB) const {
2360   // Emit an alignment directive for this block, if needed.
2361   if (unsigned Align = MBB.getAlignment())
2362     EmitAlignment(Align);
2363
2364   // If the block has its address taken, emit any labels that were used to
2365   // reference the block.  It is possible that there is more than one label
2366   // here, because multiple LLVM BB's may have been RAUW'd to this block after
2367   // the references were generated.
2368   if (MBB.hasAddressTaken()) {
2369     const BasicBlock *BB = MBB.getBasicBlock();
2370     if (isVerbose())
2371       OutStreamer.AddComment("Block address taken");
2372
2373     std::vector<MCSymbol*> Symbols = MMI->getAddrLabelSymbolToEmit(BB);
2374     for (auto *Sym : Symbols)
2375       OutStreamer.EmitLabel(Sym);
2376   }
2377
2378   // Print some verbose block comments.
2379   if (isVerbose()) {
2380     if (const BasicBlock *BB = MBB.getBasicBlock())
2381       if (BB->hasName())
2382         OutStreamer.AddComment("%" + BB->getName());
2383     emitBasicBlockLoopComments(MBB, LI, *this);
2384   }
2385
2386   // Print the main label for the block.
2387   if (MBB.pred_empty() || isBlockOnlyReachableByFallthrough(&MBB)) {
2388     if (isVerbose()) {
2389       // NOTE: Want this comment at start of line, don't emit with AddComment.
2390       OutStreamer.emitRawComment(" BB#" + Twine(MBB.getNumber()) + ":", false);
2391     }
2392   } else {
2393     OutStreamer.EmitLabel(MBB.getSymbol());
2394   }
2395 }
2396
2397 void AsmPrinter::EmitVisibility(MCSymbol *Sym, unsigned Visibility,
2398                                 bool IsDefinition) const {
2399   MCSymbolAttr Attr = MCSA_Invalid;
2400
2401   switch (Visibility) {
2402   default: break;
2403   case GlobalValue::HiddenVisibility:
2404     if (IsDefinition)
2405       Attr = MAI->getHiddenVisibilityAttr();
2406     else
2407       Attr = MAI->getHiddenDeclarationVisibilityAttr();
2408     break;
2409   case GlobalValue::ProtectedVisibility:
2410     Attr = MAI->getProtectedVisibilityAttr();
2411     break;
2412   }
2413
2414   if (Attr != MCSA_Invalid)
2415     OutStreamer.EmitSymbolAttribute(Sym, Attr);
2416 }
2417
2418 /// isBlockOnlyReachableByFallthough - Return true if the basic block has
2419 /// exactly one predecessor and the control transfer mechanism between
2420 /// the predecessor and this block is a fall-through.
2421 bool AsmPrinter::
2422 isBlockOnlyReachableByFallthrough(const MachineBasicBlock *MBB) const {
2423   // If this is a landing pad, it isn't a fall through.  If it has no preds,
2424   // then nothing falls through to it.
2425   if (MBB->isLandingPad() || MBB->pred_empty())
2426     return false;
2427
2428   // If there isn't exactly one predecessor, it can't be a fall through.
2429   if (MBB->pred_size() > 1)
2430     return false;
2431
2432   // The predecessor has to be immediately before this block.
2433   MachineBasicBlock *Pred = *MBB->pred_begin();
2434   if (!Pred->isLayoutSuccessor(MBB))
2435     return false;
2436
2437   // If the block is completely empty, then it definitely does fall through.
2438   if (Pred->empty())
2439     return true;
2440
2441   // Check the terminators in the previous blocks
2442   for (const auto &MI : Pred->terminators()) {
2443     // If it is not a simple branch, we are in a table somewhere.
2444     if (!MI.isBranch() || MI.isIndirectBranch())
2445       return false;
2446
2447     // If we are the operands of one of the branches, this is not a fall
2448     // through. Note that targets with delay slots will usually bundle
2449     // terminators with the delay slot instruction.
2450     for (ConstMIBundleOperands OP(&MI); OP.isValid(); ++OP) {
2451       if (OP->isJTI())
2452         return false;
2453       if (OP->isMBB() && OP->getMBB() == MBB)
2454         return false;
2455     }
2456   }
2457
2458   return true;
2459 }
2460
2461
2462
2463 GCMetadataPrinter *AsmPrinter::GetOrCreateGCPrinter(GCStrategy &S) {
2464   if (!S.usesMetadata())
2465     return nullptr;
2466
2467   assert(!S.useStatepoints() && "statepoints do not currently support custom"
2468          " stackmap formats, please see the documentation for a description of"
2469          " the default format.  If you really need a custom serialized format,"
2470          " please file a bug");
2471
2472   gcp_map_type &GCMap = getGCMap(GCMetadataPrinters);
2473   gcp_map_type::iterator GCPI = GCMap.find(&S);
2474   if (GCPI != GCMap.end())
2475     return GCPI->second.get();
2476
2477   const char *Name = S.getName().c_str();
2478
2479   for (GCMetadataPrinterRegistry::iterator
2480          I = GCMetadataPrinterRegistry::begin(),
2481          E = GCMetadataPrinterRegistry::end(); I != E; ++I)
2482     if (strcmp(Name, I->getName()) == 0) {
2483       std::unique_ptr<GCMetadataPrinter> GMP = I->instantiate();
2484       GMP->S = &S;
2485       auto IterBool = GCMap.insert(std::make_pair(&S, std::move(GMP)));
2486       return IterBool.first->second.get();
2487     }
2488
2489   report_fatal_error("no GCMetadataPrinter registered for GC: " + Twine(Name));
2490 }
2491
2492 /// Pin vtable to this file.
2493 AsmPrinterHandler::~AsmPrinterHandler() {}