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