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