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