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