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