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