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