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