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