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