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<GlobalObject>(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 
1387   if (auto *GA = dyn_cast<GlobalAlias>(&GIS)) {
1388     // If the aliasee does not correspond to a symbol in the output, i.e. the
1389     // alias is not of an object or the aliased object is private, then set the
1390     // size of the alias symbol from the type of the alias. We don't do this in
1391     // other situations as the alias and aliasee having differing types but same
1392     // size may be intentional.
1393     const GlobalObject *BaseObject = GA->getBaseObject();
1394     if (MAI->hasDotTypeDotSizeDirective() && GA->getValueType()->isSized() &&
1395         (!BaseObject || BaseObject->hasPrivateLinkage())) {
1396       const DataLayout &DL = M.getDataLayout();
1397       uint64_t Size = DL.getTypeAllocSize(GA->getValueType());
1398       OutStreamer->emitELFSize(Name, MCConstantExpr::create(Size, OutContext));
1399     }
1400   }
1401 }
1402 
1403 void AsmPrinter::emitRemarksSection(remarks::RemarkStreamer &RS) {
1404   if (!RS.needsSection())
1405     return;
1406 
1407   remarks::RemarkSerializer &RemarkSerializer = RS.getSerializer();
1408 
1409   Optional<SmallString<128>> Filename;
1410   if (Optional<StringRef> FilenameRef = RS.getFilename()) {
1411     Filename = *FilenameRef;
1412     sys::fs::make_absolute(*Filename);
1413     assert(!Filename->empty() && "The filename can't be empty.");
1414   }
1415 
1416   std::string Buf;
1417   raw_string_ostream OS(Buf);
1418   std::unique_ptr<remarks::MetaSerializer> MetaSerializer =
1419       Filename ? RemarkSerializer.metaSerializer(OS, StringRef(*Filename))
1420                : RemarkSerializer.metaSerializer(OS);
1421   MetaSerializer->emit();
1422 
1423   // Switch to the remarks section.
1424   MCSection *RemarksSection =
1425       OutContext.getObjectFileInfo()->getRemarksSection();
1426   OutStreamer->SwitchSection(RemarksSection);
1427 
1428   OutStreamer->EmitBinaryData(OS.str());
1429 }
1430 
1431 bool AsmPrinter::doFinalization(Module &M) {
1432   // Set the MachineFunction to nullptr so that we can catch attempted
1433   // accesses to MF specific features at the module level and so that
1434   // we can conditionalize accesses based on whether or not it is nullptr.
1435   MF = nullptr;
1436 
1437   // Gather all GOT equivalent globals in the module. We really need two
1438   // passes over the globals: one to compute and another to avoid its emission
1439   // in EmitGlobalVariable, otherwise we would not be able to handle cases
1440   // where the got equivalent shows up before its use.
1441   computeGlobalGOTEquivs(M);
1442 
1443   // Emit global variables.
1444   for (const auto &G : M.globals())
1445     EmitGlobalVariable(&G);
1446 
1447   // Emit remaining GOT equivalent globals.
1448   emitGlobalGOTEquivs();
1449 
1450   // Emit visibility info for declarations
1451   for (const Function &F : M) {
1452     if (!F.isDeclarationForLinker())
1453       continue;
1454     GlobalValue::VisibilityTypes V = F.getVisibility();
1455     if (V == GlobalValue::DefaultVisibility)
1456       continue;
1457 
1458     MCSymbol *Name = getSymbol(&F);
1459     EmitVisibility(Name, V, false);
1460   }
1461 
1462   // Emit the remarks section contents.
1463   // FIXME: Figure out when is the safest time to emit this section. It should
1464   // not come after debug info.
1465   if (remarks::RemarkStreamer *RS = M.getContext().getMainRemarkStreamer())
1466     emitRemarksSection(*RS);
1467 
1468   const TargetLoweringObjectFile &TLOF = getObjFileLowering();
1469 
1470   TLOF.emitModuleMetadata(*OutStreamer, M);
1471 
1472   if (TM.getTargetTriple().isOSBinFormatELF()) {
1473     MachineModuleInfoELF &MMIELF = MMI->getObjFileInfo<MachineModuleInfoELF>();
1474 
1475     // Output stubs for external and common global variables.
1476     MachineModuleInfoELF::SymbolListTy Stubs = MMIELF.GetGVStubList();
1477     if (!Stubs.empty()) {
1478       OutStreamer->SwitchSection(TLOF.getDataSection());
1479       const DataLayout &DL = M.getDataLayout();
1480 
1481       EmitAlignment(Align(DL.getPointerSize()));
1482       for (const auto &Stub : Stubs) {
1483         OutStreamer->EmitLabel(Stub.first);
1484         OutStreamer->EmitSymbolValue(Stub.second.getPointer(),
1485                                      DL.getPointerSize());
1486       }
1487     }
1488   }
1489 
1490   if (TM.getTargetTriple().isOSBinFormatCOFF()) {
1491     MachineModuleInfoCOFF &MMICOFF =
1492         MMI->getObjFileInfo<MachineModuleInfoCOFF>();
1493 
1494     // Output stubs for external and common global variables.
1495     MachineModuleInfoCOFF::SymbolListTy Stubs = MMICOFF.GetGVStubList();
1496     if (!Stubs.empty()) {
1497       const DataLayout &DL = M.getDataLayout();
1498 
1499       for (const auto &Stub : Stubs) {
1500         SmallString<256> SectionName = StringRef(".rdata$");
1501         SectionName += Stub.first->getName();
1502         OutStreamer->SwitchSection(OutContext.getCOFFSection(
1503             SectionName,
1504             COFF::IMAGE_SCN_CNT_INITIALIZED_DATA | COFF::IMAGE_SCN_MEM_READ |
1505                 COFF::IMAGE_SCN_LNK_COMDAT,
1506             SectionKind::getReadOnly(), Stub.first->getName(),
1507             COFF::IMAGE_COMDAT_SELECT_ANY));
1508         EmitAlignment(Align(DL.getPointerSize()));
1509         OutStreamer->EmitSymbolAttribute(Stub.first, MCSA_Global);
1510         OutStreamer->EmitLabel(Stub.first);
1511         OutStreamer->EmitSymbolValue(Stub.second.getPointer(),
1512                                      DL.getPointerSize());
1513       }
1514     }
1515   }
1516 
1517   // Finalize debug and EH information.
1518   for (const HandlerInfo &HI : Handlers) {
1519     NamedRegionTimer T(HI.TimerName, HI.TimerDescription, HI.TimerGroupName,
1520                        HI.TimerGroupDescription, TimePassesIsEnabled);
1521     HI.Handler->endModule();
1522   }
1523   Handlers.clear();
1524   DD = nullptr;
1525 
1526   // If the target wants to know about weak references, print them all.
1527   if (MAI->getWeakRefDirective()) {
1528     // FIXME: This is not lazy, it would be nice to only print weak references
1529     // to stuff that is actually used.  Note that doing so would require targets
1530     // to notice uses in operands (due to constant exprs etc).  This should
1531     // happen with the MC stuff eventually.
1532 
1533     // Print out module-level global objects here.
1534     for (const auto &GO : M.global_objects()) {
1535       if (!GO.hasExternalWeakLinkage())
1536         continue;
1537       OutStreamer->EmitSymbolAttribute(getSymbol(&GO), MCSA_WeakReference);
1538     }
1539   }
1540 
1541   // Print aliases in topological order, that is, for each alias a = b,
1542   // b must be printed before a.
1543   // This is because on some targets (e.g. PowerPC) linker expects aliases in
1544   // such an order to generate correct TOC information.
1545   SmallVector<const GlobalAlias *, 16> AliasStack;
1546   SmallPtrSet<const GlobalAlias *, 16> AliasVisited;
1547   for (const auto &Alias : M.aliases()) {
1548     for (const GlobalAlias *Cur = &Alias; Cur;
1549          Cur = dyn_cast<GlobalAlias>(Cur->getAliasee())) {
1550       if (!AliasVisited.insert(Cur).second)
1551         break;
1552       AliasStack.push_back(Cur);
1553     }
1554     for (const GlobalAlias *AncestorAlias : llvm::reverse(AliasStack))
1555       emitGlobalIndirectSymbol(M, *AncestorAlias);
1556     AliasStack.clear();
1557   }
1558   for (const auto &IFunc : M.ifuncs())
1559     emitGlobalIndirectSymbol(M, IFunc);
1560 
1561   GCModuleInfo *MI = getAnalysisIfAvailable<GCModuleInfo>();
1562   assert(MI && "AsmPrinter didn't require GCModuleInfo?");
1563   for (GCModuleInfo::iterator I = MI->end(), E = MI->begin(); I != E; )
1564     if (GCMetadataPrinter *MP = GetOrCreateGCPrinter(**--I))
1565       MP->finishAssembly(M, *MI, *this);
1566 
1567   // Emit llvm.ident metadata in an '.ident' directive.
1568   EmitModuleIdents(M);
1569 
1570   // Emit bytes for llvm.commandline metadata.
1571   EmitModuleCommandLines(M);
1572 
1573   // Emit __morestack address if needed for indirect calls.
1574   if (MMI->usesMorestackAddr()) {
1575     unsigned Align = 1;
1576     MCSection *ReadOnlySection = getObjFileLowering().getSectionForConstant(
1577         getDataLayout(), SectionKind::getReadOnly(),
1578         /*C=*/nullptr, Align);
1579     OutStreamer->SwitchSection(ReadOnlySection);
1580 
1581     MCSymbol *AddrSymbol =
1582         OutContext.getOrCreateSymbol(StringRef("__morestack_addr"));
1583     OutStreamer->EmitLabel(AddrSymbol);
1584 
1585     unsigned PtrSize = MAI->getCodePointerSize();
1586     OutStreamer->EmitSymbolValue(GetExternalSymbolSymbol("__morestack"),
1587                                  PtrSize);
1588   }
1589 
1590   // Emit .note.GNU-split-stack and .note.GNU-no-split-stack sections if
1591   // split-stack is used.
1592   if (TM.getTargetTriple().isOSBinFormatELF() && MMI->hasSplitStack()) {
1593     OutStreamer->SwitchSection(
1594         OutContext.getELFSection(".note.GNU-split-stack", ELF::SHT_PROGBITS, 0));
1595     if (MMI->hasNosplitStack())
1596       OutStreamer->SwitchSection(
1597           OutContext.getELFSection(".note.GNU-no-split-stack", ELF::SHT_PROGBITS, 0));
1598   }
1599 
1600   // If we don't have any trampolines, then we don't require stack memory
1601   // to be executable. Some targets have a directive to declare this.
1602   Function *InitTrampolineIntrinsic = M.getFunction("llvm.init.trampoline");
1603   if (!InitTrampolineIntrinsic || InitTrampolineIntrinsic->use_empty())
1604     if (MCSection *S = MAI->getNonexecutableStackSection(OutContext))
1605       OutStreamer->SwitchSection(S);
1606 
1607   if (TM.getTargetTriple().isOSBinFormatCOFF()) {
1608     // Emit /EXPORT: flags for each exported global as necessary.
1609     const auto &TLOF = getObjFileLowering();
1610     std::string Flags;
1611 
1612     for (const GlobalValue &GV : M.global_values()) {
1613       raw_string_ostream OS(Flags);
1614       TLOF.emitLinkerFlagsForGlobal(OS, &GV);
1615       OS.flush();
1616       if (!Flags.empty()) {
1617         OutStreamer->SwitchSection(TLOF.getDrectveSection());
1618         OutStreamer->EmitBytes(Flags);
1619       }
1620       Flags.clear();
1621     }
1622 
1623     // Emit /INCLUDE: flags for each used global as necessary.
1624     if (const auto *LU = M.getNamedGlobal("llvm.used")) {
1625       assert(LU->hasInitializer() &&
1626              "expected llvm.used to have an initializer");
1627       assert(isa<ArrayType>(LU->getValueType()) &&
1628              "expected llvm.used to be an array type");
1629       if (const auto *A = cast<ConstantArray>(LU->getInitializer())) {
1630         for (const Value *Op : A->operands()) {
1631           const auto *GV = cast<GlobalValue>(Op->stripPointerCasts());
1632           // Global symbols with internal or private linkage are not visible to
1633           // the linker, and thus would cause an error when the linker tried to
1634           // preserve the symbol due to the `/include:` directive.
1635           if (GV->hasLocalLinkage())
1636             continue;
1637 
1638           raw_string_ostream OS(Flags);
1639           TLOF.emitLinkerFlagsForUsed(OS, GV);
1640           OS.flush();
1641 
1642           if (!Flags.empty()) {
1643             OutStreamer->SwitchSection(TLOF.getDrectveSection());
1644             OutStreamer->EmitBytes(Flags);
1645           }
1646           Flags.clear();
1647         }
1648       }
1649     }
1650   }
1651 
1652   if (TM.Options.EmitAddrsig) {
1653     // Emit address-significance attributes for all globals.
1654     OutStreamer->EmitAddrsig();
1655     for (const GlobalValue &GV : M.global_values())
1656       if (!GV.use_empty() && !GV.isThreadLocal() &&
1657           !GV.hasDLLImportStorageClass() && !GV.getName().startswith("llvm.") &&
1658           !GV.hasAtLeastLocalUnnamedAddr())
1659         OutStreamer->EmitAddrsigSym(getSymbol(&GV));
1660   }
1661 
1662   // Emit symbol partition specifications (ELF only).
1663   if (TM.getTargetTriple().isOSBinFormatELF()) {
1664     unsigned UniqueID = 0;
1665     for (const GlobalValue &GV : M.global_values()) {
1666       if (!GV.hasPartition() || GV.isDeclarationForLinker() ||
1667           GV.getVisibility() != GlobalValue::DefaultVisibility)
1668         continue;
1669 
1670       OutStreamer->SwitchSection(OutContext.getELFSection(
1671           ".llvm_sympart", ELF::SHT_LLVM_SYMPART, 0, 0, "", ++UniqueID));
1672       OutStreamer->EmitBytes(GV.getPartition());
1673       OutStreamer->EmitZeros(1);
1674       OutStreamer->EmitValue(
1675           MCSymbolRefExpr::create(getSymbol(&GV), OutContext),
1676           MAI->getCodePointerSize());
1677     }
1678   }
1679 
1680   // Allow the target to emit any magic that it wants at the end of the file,
1681   // after everything else has gone out.
1682   EmitEndOfAsmFile(M);
1683 
1684   MMI = nullptr;
1685 
1686   OutStreamer->Finish();
1687   OutStreamer->reset();
1688   OwnedMLI.reset();
1689   OwnedMDT.reset();
1690 
1691   return false;
1692 }
1693 
1694 MCSymbol *AsmPrinter::getCurExceptionSym() {
1695   if (!CurExceptionSym)
1696     CurExceptionSym = createTempSymbol("exception");
1697   return CurExceptionSym;
1698 }
1699 
1700 void AsmPrinter::SetupMachineFunction(MachineFunction &MF) {
1701   this->MF = &MF;
1702   const Function &F = MF.getFunction();
1703 
1704   // Get the function symbol.
1705   if (TM.getTargetTriple().isOSAIX()) {
1706     // AIX is unique here in that the name of the symbol emitted for the
1707     // function body does not have the same name as the source function's
1708     // C-linkage name.
1709     assert(MAI->needsFunctionDescriptors() && "AIX ABI is descriptor based.");
1710     assert(CurrentFnDescSym && "The function descriptor symbol needs to be"
1711 		                           " initalized first.");
1712 
1713     // Get the function entry point symbol.
1714     CurrentFnSym =
1715         OutContext.getOrCreateSymbol("." + CurrentFnDescSym->getName());
1716 
1717     // Set the containing csect.
1718     MCSectionXCOFF *FnEntryPointSec =
1719         cast<MCSectionXCOFF>(getObjFileLowering().SectionForGlobal(&F, TM));
1720     cast<MCSymbolXCOFF>(CurrentFnSym)->setContainingCsect(FnEntryPointSec);
1721   } else {
1722     CurrentFnSym = getSymbol(&MF.getFunction());
1723   }
1724 
1725   CurrentFnSymForSize = CurrentFnSym;
1726   CurrentFnBegin = nullptr;
1727   CurExceptionSym = nullptr;
1728   bool NeedsLocalForSize = MAI->needsLocalForSize();
1729   if (F.hasFnAttribute("patchable-function-entry") ||
1730       needFuncLabelsForEHOrDebugInfo(MF, MMI) || NeedsLocalForSize ||
1731       MF.getTarget().Options.EmitStackSizeSection) {
1732     CurrentFnBegin = createTempSymbol("func_begin");
1733     if (NeedsLocalForSize)
1734       CurrentFnSymForSize = CurrentFnBegin;
1735   }
1736 
1737   ORE = &getAnalysis<MachineOptimizationRemarkEmitterPass>().getORE();
1738   PSI = &getAnalysis<ProfileSummaryInfoWrapperPass>().getPSI();
1739   MBFI = (PSI && PSI->hasProfileSummary()) ?
1740          // ORE conditionally computes MBFI. If available, use it, otherwise
1741          // request it.
1742          (ORE->getBFI() ? ORE->getBFI() :
1743           &getAnalysis<LazyMachineBlockFrequencyInfoPass>().getBFI()) :
1744          nullptr;
1745 }
1746 
1747 namespace {
1748 
1749 // Keep track the alignment, constpool entries per Section.
1750   struct SectionCPs {
1751     MCSection *S;
1752     unsigned Alignment;
1753     SmallVector<unsigned, 4> CPEs;
1754 
1755     SectionCPs(MCSection *s, unsigned a) : S(s), Alignment(a) {}
1756   };
1757 
1758 } // end anonymous namespace
1759 
1760 /// EmitConstantPool - Print to the current output stream assembly
1761 /// representations of the constants in the constant pool MCP. This is
1762 /// used to print out constants which have been "spilled to memory" by
1763 /// the code generator.
1764 void AsmPrinter::EmitConstantPool() {
1765   const MachineConstantPool *MCP = MF->getConstantPool();
1766   const std::vector<MachineConstantPoolEntry> &CP = MCP->getConstants();
1767   if (CP.empty()) return;
1768 
1769   // Calculate sections for constant pool entries. We collect entries to go into
1770   // the same section together to reduce amount of section switch statements.
1771   SmallVector<SectionCPs, 4> CPSections;
1772   for (unsigned i = 0, e = CP.size(); i != e; ++i) {
1773     const MachineConstantPoolEntry &CPE = CP[i];
1774     unsigned Align = CPE.getAlignment();
1775 
1776     SectionKind Kind = CPE.getSectionKind(&getDataLayout());
1777 
1778     const Constant *C = nullptr;
1779     if (!CPE.isMachineConstantPoolEntry())
1780       C = CPE.Val.ConstVal;
1781 
1782     MCSection *S = getObjFileLowering().getSectionForConstant(getDataLayout(),
1783                                                               Kind, C, Align);
1784 
1785     // The number of sections are small, just do a linear search from the
1786     // last section to the first.
1787     bool Found = false;
1788     unsigned SecIdx = CPSections.size();
1789     while (SecIdx != 0) {
1790       if (CPSections[--SecIdx].S == S) {
1791         Found = true;
1792         break;
1793       }
1794     }
1795     if (!Found) {
1796       SecIdx = CPSections.size();
1797       CPSections.push_back(SectionCPs(S, Align));
1798     }
1799 
1800     if (Align > CPSections[SecIdx].Alignment)
1801       CPSections[SecIdx].Alignment = Align;
1802     CPSections[SecIdx].CPEs.push_back(i);
1803   }
1804 
1805   // Now print stuff into the calculated sections.
1806   const MCSection *CurSection = nullptr;
1807   unsigned Offset = 0;
1808   for (unsigned i = 0, e = CPSections.size(); i != e; ++i) {
1809     for (unsigned j = 0, ee = CPSections[i].CPEs.size(); j != ee; ++j) {
1810       unsigned CPI = CPSections[i].CPEs[j];
1811       MCSymbol *Sym = GetCPISymbol(CPI);
1812       if (!Sym->isUndefined())
1813         continue;
1814 
1815       if (TM.getTargetTriple().isOSBinFormatXCOFF()) {
1816         cast<MCSymbolXCOFF>(Sym)->setContainingCsect(
1817             cast<MCSectionXCOFF>(CPSections[i].S));
1818       }
1819 
1820       if (CurSection != CPSections[i].S) {
1821         OutStreamer->SwitchSection(CPSections[i].S);
1822         EmitAlignment(Align(CPSections[i].Alignment));
1823         CurSection = CPSections[i].S;
1824         Offset = 0;
1825       }
1826 
1827       MachineConstantPoolEntry CPE = CP[CPI];
1828 
1829       // Emit inter-object padding for alignment.
1830       unsigned AlignMask = CPE.getAlignment() - 1;
1831       unsigned NewOffset = (Offset + AlignMask) & ~AlignMask;
1832       OutStreamer->EmitZeros(NewOffset - Offset);
1833 
1834       Type *Ty = CPE.getType();
1835       Offset = NewOffset + getDataLayout().getTypeAllocSize(Ty);
1836 
1837       OutStreamer->EmitLabel(Sym);
1838       if (CPE.isMachineConstantPoolEntry())
1839         EmitMachineConstantPoolValue(CPE.Val.MachineCPVal);
1840       else
1841         EmitGlobalConstant(getDataLayout(), CPE.Val.ConstVal);
1842     }
1843   }
1844 }
1845 
1846 /// EmitJumpTableInfo - Print assembly representations of the jump tables used
1847 /// by the current function to the current output stream.
1848 void AsmPrinter::EmitJumpTableInfo() {
1849   const DataLayout &DL = MF->getDataLayout();
1850   const MachineJumpTableInfo *MJTI = MF->getJumpTableInfo();
1851   if (!MJTI) return;
1852   if (MJTI->getEntryKind() == MachineJumpTableInfo::EK_Inline) return;
1853   const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables();
1854   if (JT.empty()) return;
1855 
1856   // Pick the directive to use to print the jump table entries, and switch to
1857   // the appropriate section.
1858   const Function &F = MF->getFunction();
1859   const TargetLoweringObjectFile &TLOF = getObjFileLowering();
1860   bool JTInDiffSection = !TLOF.shouldPutJumpTableInFunctionSection(
1861       MJTI->getEntryKind() == MachineJumpTableInfo::EK_LabelDifference32,
1862       F);
1863   if (JTInDiffSection) {
1864     // Drop it in the readonly section.
1865     MCSection *ReadOnlySection = TLOF.getSectionForJumpTable(F, TM);
1866     OutStreamer->SwitchSection(ReadOnlySection);
1867   }
1868 
1869   EmitAlignment(Align(MJTI->getEntryAlignment(DL)));
1870 
1871   // Jump tables in code sections are marked with a data_region directive
1872   // where that's supported.
1873   if (!JTInDiffSection)
1874     OutStreamer->EmitDataRegion(MCDR_DataRegionJT32);
1875 
1876   for (unsigned JTI = 0, e = JT.size(); JTI != e; ++JTI) {
1877     const std::vector<MachineBasicBlock*> &JTBBs = JT[JTI].MBBs;
1878 
1879     // If this jump table was deleted, ignore it.
1880     if (JTBBs.empty()) continue;
1881 
1882     // For the EK_LabelDifference32 entry, if using .set avoids a relocation,
1883     /// emit a .set directive for each unique entry.
1884     if (MJTI->getEntryKind() == MachineJumpTableInfo::EK_LabelDifference32 &&
1885         MAI->doesSetDirectiveSuppressReloc()) {
1886       SmallPtrSet<const MachineBasicBlock*, 16> EmittedSets;
1887       const TargetLowering *TLI = MF->getSubtarget().getTargetLowering();
1888       const MCExpr *Base = TLI->getPICJumpTableRelocBaseExpr(MF,JTI,OutContext);
1889       for (unsigned ii = 0, ee = JTBBs.size(); ii != ee; ++ii) {
1890         const MachineBasicBlock *MBB = JTBBs[ii];
1891         if (!EmittedSets.insert(MBB).second)
1892           continue;
1893 
1894         // .set LJTSet, LBB32-base
1895         const MCExpr *LHS =
1896           MCSymbolRefExpr::create(MBB->getSymbol(), OutContext);
1897         OutStreamer->EmitAssignment(GetJTSetSymbol(JTI, MBB->getNumber()),
1898                                     MCBinaryExpr::createSub(LHS, Base,
1899                                                             OutContext));
1900       }
1901     }
1902 
1903     // On some targets (e.g. Darwin) we want to emit two consecutive labels
1904     // before each jump table.  The first label is never referenced, but tells
1905     // the assembler and linker the extents of the jump table object.  The
1906     // second label is actually referenced by the code.
1907     if (JTInDiffSection && DL.hasLinkerPrivateGlobalPrefix())
1908       // FIXME: This doesn't have to have any specific name, just any randomly
1909       // named and numbered local label started with 'l' would work.  Simplify
1910       // GetJTISymbol.
1911       OutStreamer->EmitLabel(GetJTISymbol(JTI, true));
1912 
1913     MCSymbol* JTISymbol = GetJTISymbol(JTI);
1914     if (TM.getTargetTriple().isOSBinFormatXCOFF()) {
1915       cast<MCSymbolXCOFF>(JTISymbol)->setContainingCsect(
1916           cast<MCSectionXCOFF>(TLOF.getSectionForJumpTable(F, TM)));
1917     }
1918     OutStreamer->EmitLabel(JTISymbol);
1919 
1920     for (unsigned ii = 0, ee = JTBBs.size(); ii != ee; ++ii)
1921       EmitJumpTableEntry(MJTI, JTBBs[ii], JTI);
1922   }
1923   if (!JTInDiffSection)
1924     OutStreamer->EmitDataRegion(MCDR_DataRegionEnd);
1925 }
1926 
1927 /// EmitJumpTableEntry - Emit a jump table entry for the specified MBB to the
1928 /// current stream.
1929 void AsmPrinter::EmitJumpTableEntry(const MachineJumpTableInfo *MJTI,
1930                                     const MachineBasicBlock *MBB,
1931                                     unsigned UID) const {
1932   assert(MBB && MBB->getNumber() >= 0 && "Invalid basic block");
1933   const MCExpr *Value = nullptr;
1934   switch (MJTI->getEntryKind()) {
1935   case MachineJumpTableInfo::EK_Inline:
1936     llvm_unreachable("Cannot emit EK_Inline jump table entry");
1937   case MachineJumpTableInfo::EK_Custom32:
1938     Value = MF->getSubtarget().getTargetLowering()->LowerCustomJumpTableEntry(
1939         MJTI, MBB, UID, OutContext);
1940     break;
1941   case MachineJumpTableInfo::EK_BlockAddress:
1942     // EK_BlockAddress - Each entry is a plain address of block, e.g.:
1943     //     .word LBB123
1944     Value = MCSymbolRefExpr::create(MBB->getSymbol(), OutContext);
1945     break;
1946   case MachineJumpTableInfo::EK_GPRel32BlockAddress: {
1947     // EK_GPRel32BlockAddress - Each entry is an address of block, encoded
1948     // with a relocation as gp-relative, e.g.:
1949     //     .gprel32 LBB123
1950     MCSymbol *MBBSym = MBB->getSymbol();
1951     OutStreamer->EmitGPRel32Value(MCSymbolRefExpr::create(MBBSym, OutContext));
1952     return;
1953   }
1954 
1955   case MachineJumpTableInfo::EK_GPRel64BlockAddress: {
1956     // EK_GPRel64BlockAddress - Each entry is an address of block, encoded
1957     // with a relocation as gp-relative, e.g.:
1958     //     .gpdword LBB123
1959     MCSymbol *MBBSym = MBB->getSymbol();
1960     OutStreamer->EmitGPRel64Value(MCSymbolRefExpr::create(MBBSym, OutContext));
1961     return;
1962   }
1963 
1964   case MachineJumpTableInfo::EK_LabelDifference32: {
1965     // Each entry is the address of the block minus the address of the jump
1966     // table. This is used for PIC jump tables where gprel32 is not supported.
1967     // e.g.:
1968     //      .word LBB123 - LJTI1_2
1969     // If the .set directive avoids relocations, this is emitted as:
1970     //      .set L4_5_set_123, LBB123 - LJTI1_2
1971     //      .word L4_5_set_123
1972     if (MAI->doesSetDirectiveSuppressReloc()) {
1973       Value = MCSymbolRefExpr::create(GetJTSetSymbol(UID, MBB->getNumber()),
1974                                       OutContext);
1975       break;
1976     }
1977     Value = MCSymbolRefExpr::create(MBB->getSymbol(), OutContext);
1978     const TargetLowering *TLI = MF->getSubtarget().getTargetLowering();
1979     const MCExpr *Base = TLI->getPICJumpTableRelocBaseExpr(MF, UID, OutContext);
1980     Value = MCBinaryExpr::createSub(Value, Base, OutContext);
1981     break;
1982   }
1983   }
1984 
1985   assert(Value && "Unknown entry kind!");
1986 
1987   unsigned EntrySize = MJTI->getEntrySize(getDataLayout());
1988   OutStreamer->EmitValue(Value, EntrySize);
1989 }
1990 
1991 /// EmitSpecialLLVMGlobal - Check to see if the specified global is a
1992 /// special global used by LLVM.  If so, emit it and return true, otherwise
1993 /// do nothing and return false.
1994 bool AsmPrinter::EmitSpecialLLVMGlobal(const GlobalVariable *GV) {
1995   if (GV->getName() == "llvm.used") {
1996     if (MAI->hasNoDeadStrip())    // No need to emit this at all.
1997       EmitLLVMUsedList(cast<ConstantArray>(GV->getInitializer()));
1998     return true;
1999   }
2000 
2001   // Ignore debug and non-emitted data.  This handles llvm.compiler.used.
2002   if (GV->getSection() == "llvm.metadata" ||
2003       GV->hasAvailableExternallyLinkage())
2004     return true;
2005 
2006   if (!GV->hasAppendingLinkage()) return false;
2007 
2008   assert(GV->hasInitializer() && "Not a special LLVM global!");
2009 
2010   if (GV->getName() == "llvm.global_ctors") {
2011     EmitXXStructorList(GV->getParent()->getDataLayout(), GV->getInitializer(),
2012                        /* isCtor */ true);
2013 
2014     return true;
2015   }
2016 
2017   if (GV->getName() == "llvm.global_dtors") {
2018     EmitXXStructorList(GV->getParent()->getDataLayout(), GV->getInitializer(),
2019                        /* isCtor */ false);
2020 
2021     return true;
2022   }
2023 
2024   report_fatal_error("unknown special variable");
2025 }
2026 
2027 /// EmitLLVMUsedList - For targets that define a MAI::UsedDirective, mark each
2028 /// global in the specified llvm.used list.
2029 void AsmPrinter::EmitLLVMUsedList(const ConstantArray *InitList) {
2030   // Should be an array of 'i8*'.
2031   for (unsigned i = 0, e = InitList->getNumOperands(); i != e; ++i) {
2032     const GlobalValue *GV =
2033       dyn_cast<GlobalValue>(InitList->getOperand(i)->stripPointerCasts());
2034     if (GV)
2035       OutStreamer->EmitSymbolAttribute(getSymbol(GV), MCSA_NoDeadStrip);
2036   }
2037 }
2038 
2039 namespace {
2040 
2041 struct Structor {
2042   int Priority = 0;
2043   Constant *Func = nullptr;
2044   GlobalValue *ComdatKey = nullptr;
2045 
2046   Structor() = default;
2047 };
2048 
2049 } // end anonymous namespace
2050 
2051 /// EmitXXStructorList - Emit the ctor or dtor list taking into account the init
2052 /// priority.
2053 void AsmPrinter::EmitXXStructorList(const DataLayout &DL, const Constant *List,
2054                                     bool isCtor) {
2055   // Should be an array of '{ i32, void ()*, i8* }' structs.  The first value is the
2056   // init priority.
2057   if (!isa<ConstantArray>(List)) return;
2058 
2059   // Sanity check the structors list.
2060   const ConstantArray *InitList = dyn_cast<ConstantArray>(List);
2061   if (!InitList) return; // Not an array!
2062   StructType *ETy = dyn_cast<StructType>(InitList->getType()->getElementType());
2063   if (!ETy || ETy->getNumElements() != 3 ||
2064       !isa<IntegerType>(ETy->getTypeAtIndex(0U)) ||
2065       !isa<PointerType>(ETy->getTypeAtIndex(1U)) ||
2066       !isa<PointerType>(ETy->getTypeAtIndex(2U)))
2067     return; // Not (int, ptr, ptr).
2068 
2069   // Gather the structors in a form that's convenient for sorting by priority.
2070   SmallVector<Structor, 8> Structors;
2071   for (Value *O : InitList->operands()) {
2072     ConstantStruct *CS = dyn_cast<ConstantStruct>(O);
2073     if (!CS) continue; // Malformed.
2074     if (CS->getOperand(1)->isNullValue())
2075       break;  // Found a null terminator, skip the rest.
2076     ConstantInt *Priority = dyn_cast<ConstantInt>(CS->getOperand(0));
2077     if (!Priority) continue; // Malformed.
2078     Structors.push_back(Structor());
2079     Structor &S = Structors.back();
2080     S.Priority = Priority->getLimitedValue(65535);
2081     S.Func = CS->getOperand(1);
2082     if (!CS->getOperand(2)->isNullValue())
2083       S.ComdatKey =
2084           dyn_cast<GlobalValue>(CS->getOperand(2)->stripPointerCasts());
2085   }
2086 
2087   // Emit the function pointers in the target-specific order
2088   llvm::stable_sort(Structors, [](const Structor &L, const Structor &R) {
2089     return L.Priority < R.Priority;
2090   });
2091   const Align Align = DL.getPointerPrefAlignment();
2092   for (Structor &S : Structors) {
2093     const TargetLoweringObjectFile &Obj = getObjFileLowering();
2094     const MCSymbol *KeySym = nullptr;
2095     if (GlobalValue *GV = S.ComdatKey) {
2096       if (GV->isDeclarationForLinker())
2097         // If the associated variable is not defined in this module
2098         // (it might be available_externally, or have been an
2099         // available_externally definition that was dropped by the
2100         // EliminateAvailableExternally pass), some other TU
2101         // will provide its dynamic initializer.
2102         continue;
2103 
2104       KeySym = getSymbol(GV);
2105     }
2106     MCSection *OutputSection =
2107         (isCtor ? Obj.getStaticCtorSection(S.Priority, KeySym)
2108                 : Obj.getStaticDtorSection(S.Priority, KeySym));
2109     OutStreamer->SwitchSection(OutputSection);
2110     if (OutStreamer->getCurrentSection() != OutStreamer->getPreviousSection())
2111       EmitAlignment(Align);
2112     EmitXXStructor(DL, S.Func);
2113   }
2114 }
2115 
2116 void AsmPrinter::EmitModuleIdents(Module &M) {
2117   if (!MAI->hasIdentDirective())
2118     return;
2119 
2120   if (const NamedMDNode *NMD = M.getNamedMetadata("llvm.ident")) {
2121     for (unsigned i = 0, e = NMD->getNumOperands(); i != e; ++i) {
2122       const MDNode *N = NMD->getOperand(i);
2123       assert(N->getNumOperands() == 1 &&
2124              "llvm.ident metadata entry can have only one operand");
2125       const MDString *S = cast<MDString>(N->getOperand(0));
2126       OutStreamer->EmitIdent(S->getString());
2127     }
2128   }
2129 }
2130 
2131 void AsmPrinter::EmitModuleCommandLines(Module &M) {
2132   MCSection *CommandLine = getObjFileLowering().getSectionForCommandLines();
2133   if (!CommandLine)
2134     return;
2135 
2136   const NamedMDNode *NMD = M.getNamedMetadata("llvm.commandline");
2137   if (!NMD || !NMD->getNumOperands())
2138     return;
2139 
2140   OutStreamer->PushSection();
2141   OutStreamer->SwitchSection(CommandLine);
2142   OutStreamer->EmitZeros(1);
2143   for (unsigned i = 0, e = NMD->getNumOperands(); i != e; ++i) {
2144     const MDNode *N = NMD->getOperand(i);
2145     assert(N->getNumOperands() == 1 &&
2146            "llvm.commandline metadata entry can have only one operand");
2147     const MDString *S = cast<MDString>(N->getOperand(0));
2148     OutStreamer->EmitBytes(S->getString());
2149     OutStreamer->EmitZeros(1);
2150   }
2151   OutStreamer->PopSection();
2152 }
2153 
2154 //===--------------------------------------------------------------------===//
2155 // Emission and print routines
2156 //
2157 
2158 /// Emit a byte directive and value.
2159 ///
2160 void AsmPrinter::emitInt8(int Value) const {
2161   OutStreamer->EmitIntValue(Value, 1);
2162 }
2163 
2164 /// Emit a short directive and value.
2165 void AsmPrinter::emitInt16(int Value) const {
2166   OutStreamer->EmitIntValue(Value, 2);
2167 }
2168 
2169 /// Emit a long directive and value.
2170 void AsmPrinter::emitInt32(int Value) const {
2171   OutStreamer->EmitIntValue(Value, 4);
2172 }
2173 
2174 /// Emit a long long directive and value.
2175 void AsmPrinter::emitInt64(uint64_t Value) const {
2176   OutStreamer->EmitIntValue(Value, 8);
2177 }
2178 
2179 /// Emit something like ".long Hi-Lo" where the size in bytes of the directive
2180 /// is specified by Size and Hi/Lo specify the labels. This implicitly uses
2181 /// .set if it avoids relocations.
2182 void AsmPrinter::EmitLabelDifference(const MCSymbol *Hi, const MCSymbol *Lo,
2183                                      unsigned Size) const {
2184   OutStreamer->emitAbsoluteSymbolDiff(Hi, Lo, Size);
2185 }
2186 
2187 /// EmitLabelPlusOffset - Emit something like ".long Label+Offset"
2188 /// where the size in bytes of the directive is specified by Size and Label
2189 /// specifies the label.  This implicitly uses .set if it is available.
2190 void AsmPrinter::EmitLabelPlusOffset(const MCSymbol *Label, uint64_t Offset,
2191                                      unsigned Size,
2192                                      bool IsSectionRelative) const {
2193   if (MAI->needsDwarfSectionOffsetDirective() && IsSectionRelative) {
2194     OutStreamer->EmitCOFFSecRel32(Label, Offset);
2195     if (Size > 4)
2196       OutStreamer->EmitZeros(Size - 4);
2197     return;
2198   }
2199 
2200   // Emit Label+Offset (or just Label if Offset is zero)
2201   const MCExpr *Expr = MCSymbolRefExpr::create(Label, OutContext);
2202   if (Offset)
2203     Expr = MCBinaryExpr::createAdd(
2204         Expr, MCConstantExpr::create(Offset, OutContext), OutContext);
2205 
2206   OutStreamer->EmitValue(Expr, Size);
2207 }
2208 
2209 //===----------------------------------------------------------------------===//
2210 
2211 // EmitAlignment - Emit an alignment directive to the specified power of
2212 // two boundary.  If a global value is specified, and if that global has
2213 // an explicit alignment requested, it will override the alignment request
2214 // if required for correctness.
2215 void AsmPrinter::EmitAlignment(Align Alignment, const GlobalObject *GV) const {
2216   if (GV)
2217     Alignment = getGVAlignment(GV, GV->getParent()->getDataLayout(), Alignment);
2218 
2219   if (Alignment == Align(1))
2220     return; // 1-byte aligned: no need to emit alignment.
2221 
2222   if (getCurrentSection()->getKind().isText())
2223     OutStreamer->EmitCodeAlignment(Alignment.value());
2224   else
2225     OutStreamer->EmitValueToAlignment(Alignment.value());
2226 }
2227 
2228 //===----------------------------------------------------------------------===//
2229 // Constant emission.
2230 //===----------------------------------------------------------------------===//
2231 
2232 const MCExpr *AsmPrinter::lowerConstant(const Constant *CV) {
2233   MCContext &Ctx = OutContext;
2234 
2235   if (CV->isNullValue() || isa<UndefValue>(CV))
2236     return MCConstantExpr::create(0, Ctx);
2237 
2238   if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV))
2239     return MCConstantExpr::create(CI->getZExtValue(), Ctx);
2240 
2241   if (const GlobalValue *GV = dyn_cast<GlobalValue>(CV))
2242     return MCSymbolRefExpr::create(getSymbol(GV), Ctx);
2243 
2244   if (const BlockAddress *BA = dyn_cast<BlockAddress>(CV))
2245     return MCSymbolRefExpr::create(GetBlockAddressSymbol(BA), Ctx);
2246 
2247   const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV);
2248   if (!CE) {
2249     llvm_unreachable("Unknown constant value to lower!");
2250   }
2251 
2252   switch (CE->getOpcode()) {
2253   default:
2254     // If the code isn't optimized, there may be outstanding folding
2255     // opportunities. Attempt to fold the expression using DataLayout as a
2256     // last resort before giving up.
2257     if (Constant *C = ConstantFoldConstant(CE, getDataLayout()))
2258       if (C != CE)
2259         return lowerConstant(C);
2260 
2261     // Otherwise report the problem to the user.
2262     {
2263       std::string S;
2264       raw_string_ostream OS(S);
2265       OS << "Unsupported expression in static initializer: ";
2266       CE->printAsOperand(OS, /*PrintType=*/false,
2267                      !MF ? nullptr : MF->getFunction().getParent());
2268       report_fatal_error(OS.str());
2269     }
2270   case Instruction::GetElementPtr: {
2271     // Generate a symbolic expression for the byte address
2272     APInt OffsetAI(getDataLayout().getPointerTypeSizeInBits(CE->getType()), 0);
2273     cast<GEPOperator>(CE)->accumulateConstantOffset(getDataLayout(), OffsetAI);
2274 
2275     const MCExpr *Base = lowerConstant(CE->getOperand(0));
2276     if (!OffsetAI)
2277       return Base;
2278 
2279     int64_t Offset = OffsetAI.getSExtValue();
2280     return MCBinaryExpr::createAdd(Base, MCConstantExpr::create(Offset, Ctx),
2281                                    Ctx);
2282   }
2283 
2284   case Instruction::Trunc:
2285     // We emit the value and depend on the assembler to truncate the generated
2286     // expression properly.  This is important for differences between
2287     // blockaddress labels.  Since the two labels are in the same function, it
2288     // is reasonable to treat their delta as a 32-bit value.
2289     LLVM_FALLTHROUGH;
2290   case Instruction::BitCast:
2291     return lowerConstant(CE->getOperand(0));
2292 
2293   case Instruction::IntToPtr: {
2294     const DataLayout &DL = getDataLayout();
2295 
2296     // Handle casts to pointers by changing them into casts to the appropriate
2297     // integer type.  This promotes constant folding and simplifies this code.
2298     Constant *Op = CE->getOperand(0);
2299     Op = ConstantExpr::getIntegerCast(Op, DL.getIntPtrType(CV->getType()),
2300                                       false/*ZExt*/);
2301     return lowerConstant(Op);
2302   }
2303 
2304   case Instruction::PtrToInt: {
2305     const DataLayout &DL = getDataLayout();
2306 
2307     // Support only foldable casts to/from pointers that can be eliminated by
2308     // changing the pointer to the appropriately sized integer type.
2309     Constant *Op = CE->getOperand(0);
2310     Type *Ty = CE->getType();
2311 
2312     const MCExpr *OpExpr = lowerConstant(Op);
2313 
2314     // We can emit the pointer value into this slot if the slot is an
2315     // integer slot equal to the size of the pointer.
2316     //
2317     // If the pointer is larger than the resultant integer, then
2318     // as with Trunc just depend on the assembler to truncate it.
2319     if (DL.getTypeAllocSize(Ty) <= DL.getTypeAllocSize(Op->getType()))
2320       return OpExpr;
2321 
2322     // Otherwise the pointer is smaller than the resultant integer, mask off
2323     // the high bits so we are sure to get a proper truncation if the input is
2324     // a constant expr.
2325     unsigned InBits = DL.getTypeAllocSizeInBits(Op->getType());
2326     const MCExpr *MaskExpr = MCConstantExpr::create(~0ULL >> (64-InBits), Ctx);
2327     return MCBinaryExpr::createAnd(OpExpr, MaskExpr, Ctx);
2328   }
2329 
2330   case Instruction::Sub: {
2331     GlobalValue *LHSGV;
2332     APInt LHSOffset;
2333     if (IsConstantOffsetFromGlobal(CE->getOperand(0), LHSGV, LHSOffset,
2334                                    getDataLayout())) {
2335       GlobalValue *RHSGV;
2336       APInt RHSOffset;
2337       if (IsConstantOffsetFromGlobal(CE->getOperand(1), RHSGV, RHSOffset,
2338                                      getDataLayout())) {
2339         const MCExpr *RelocExpr =
2340             getObjFileLowering().lowerRelativeReference(LHSGV, RHSGV, TM);
2341         if (!RelocExpr)
2342           RelocExpr = MCBinaryExpr::createSub(
2343               MCSymbolRefExpr::create(getSymbol(LHSGV), Ctx),
2344               MCSymbolRefExpr::create(getSymbol(RHSGV), Ctx), Ctx);
2345         int64_t Addend = (LHSOffset - RHSOffset).getSExtValue();
2346         if (Addend != 0)
2347           RelocExpr = MCBinaryExpr::createAdd(
2348               RelocExpr, MCConstantExpr::create(Addend, Ctx), Ctx);
2349         return RelocExpr;
2350       }
2351     }
2352   }
2353   // else fallthrough
2354   LLVM_FALLTHROUGH;
2355 
2356   // The MC library also has a right-shift operator, but it isn't consistently
2357   // signed or unsigned between different targets.
2358   case Instruction::Add:
2359   case Instruction::Mul:
2360   case Instruction::SDiv:
2361   case Instruction::SRem:
2362   case Instruction::Shl:
2363   case Instruction::And:
2364   case Instruction::Or:
2365   case Instruction::Xor: {
2366     const MCExpr *LHS = lowerConstant(CE->getOperand(0));
2367     const MCExpr *RHS = lowerConstant(CE->getOperand(1));
2368     switch (CE->getOpcode()) {
2369     default: llvm_unreachable("Unknown binary operator constant cast expr");
2370     case Instruction::Add: return MCBinaryExpr::createAdd(LHS, RHS, Ctx);
2371     case Instruction::Sub: return MCBinaryExpr::createSub(LHS, RHS, Ctx);
2372     case Instruction::Mul: return MCBinaryExpr::createMul(LHS, RHS, Ctx);
2373     case Instruction::SDiv: return MCBinaryExpr::createDiv(LHS, RHS, Ctx);
2374     case Instruction::SRem: return MCBinaryExpr::createMod(LHS, RHS, Ctx);
2375     case Instruction::Shl: return MCBinaryExpr::createShl(LHS, RHS, Ctx);
2376     case Instruction::And: return MCBinaryExpr::createAnd(LHS, RHS, Ctx);
2377     case Instruction::Or:  return MCBinaryExpr::createOr (LHS, RHS, Ctx);
2378     case Instruction::Xor: return MCBinaryExpr::createXor(LHS, RHS, Ctx);
2379     }
2380   }
2381   }
2382 }
2383 
2384 static void emitGlobalConstantImpl(const DataLayout &DL, const Constant *C,
2385                                    AsmPrinter &AP,
2386                                    const Constant *BaseCV = nullptr,
2387                                    uint64_t Offset = 0);
2388 
2389 static void emitGlobalConstantFP(const ConstantFP *CFP, AsmPrinter &AP);
2390 static void emitGlobalConstantFP(APFloat APF, Type *ET, AsmPrinter &AP);
2391 
2392 /// isRepeatedByteSequence - Determine whether the given value is
2393 /// composed of a repeated sequence of identical bytes and return the
2394 /// byte value.  If it is not a repeated sequence, return -1.
2395 static int isRepeatedByteSequence(const ConstantDataSequential *V) {
2396   StringRef Data = V->getRawDataValues();
2397   assert(!Data.empty() && "Empty aggregates should be CAZ node");
2398   char C = Data[0];
2399   for (unsigned i = 1, e = Data.size(); i != e; ++i)
2400     if (Data[i] != C) return -1;
2401   return static_cast<uint8_t>(C); // Ensure 255 is not returned as -1.
2402 }
2403 
2404 /// isRepeatedByteSequence - Determine whether the given value is
2405 /// composed of a repeated sequence of identical bytes and return the
2406 /// byte value.  If it is not a repeated sequence, return -1.
2407 static int isRepeatedByteSequence(const Value *V, const DataLayout &DL) {
2408   if (const ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
2409     uint64_t Size = DL.getTypeAllocSizeInBits(V->getType());
2410     assert(Size % 8 == 0);
2411 
2412     // Extend the element to take zero padding into account.
2413     APInt Value = CI->getValue().zextOrSelf(Size);
2414     if (!Value.isSplat(8))
2415       return -1;
2416 
2417     return Value.zextOrTrunc(8).getZExtValue();
2418   }
2419   if (const ConstantArray *CA = dyn_cast<ConstantArray>(V)) {
2420     // Make sure all array elements are sequences of the same repeated
2421     // byte.
2422     assert(CA->getNumOperands() != 0 && "Should be a CAZ");
2423     Constant *Op0 = CA->getOperand(0);
2424     int Byte = isRepeatedByteSequence(Op0, DL);
2425     if (Byte == -1)
2426       return -1;
2427 
2428     // All array elements must be equal.
2429     for (unsigned i = 1, e = CA->getNumOperands(); i != e; ++i)
2430       if (CA->getOperand(i) != Op0)
2431         return -1;
2432     return Byte;
2433   }
2434 
2435   if (const ConstantDataSequential *CDS = dyn_cast<ConstantDataSequential>(V))
2436     return isRepeatedByteSequence(CDS);
2437 
2438   return -1;
2439 }
2440 
2441 static void emitGlobalConstantDataSequential(const DataLayout &DL,
2442                                              const ConstantDataSequential *CDS,
2443                                              AsmPrinter &AP) {
2444   // See if we can aggregate this into a .fill, if so, emit it as such.
2445   int Value = isRepeatedByteSequence(CDS, DL);
2446   if (Value != -1) {
2447     uint64_t Bytes = DL.getTypeAllocSize(CDS->getType());
2448     // Don't emit a 1-byte object as a .fill.
2449     if (Bytes > 1)
2450       return AP.OutStreamer->emitFill(Bytes, Value);
2451   }
2452 
2453   // If this can be emitted with .ascii/.asciz, emit it as such.
2454   if (CDS->isString())
2455     return AP.OutStreamer->EmitBytes(CDS->getAsString());
2456 
2457   // Otherwise, emit the values in successive locations.
2458   unsigned ElementByteSize = CDS->getElementByteSize();
2459   if (isa<IntegerType>(CDS->getElementType())) {
2460     for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) {
2461       if (AP.isVerbose())
2462         AP.OutStreamer->GetCommentOS() << format("0x%" PRIx64 "\n",
2463                                                  CDS->getElementAsInteger(i));
2464       AP.OutStreamer->EmitIntValue(CDS->getElementAsInteger(i),
2465                                    ElementByteSize);
2466     }
2467   } else {
2468     Type *ET = CDS->getElementType();
2469     for (unsigned I = 0, E = CDS->getNumElements(); I != E; ++I)
2470       emitGlobalConstantFP(CDS->getElementAsAPFloat(I), ET, AP);
2471   }
2472 
2473   unsigned Size = DL.getTypeAllocSize(CDS->getType());
2474   unsigned EmittedSize = DL.getTypeAllocSize(CDS->getType()->getElementType()) *
2475                         CDS->getNumElements();
2476   assert(EmittedSize <= Size && "Size cannot be less than EmittedSize!");
2477   if (unsigned Padding = Size - EmittedSize)
2478     AP.OutStreamer->EmitZeros(Padding);
2479 }
2480 
2481 static void emitGlobalConstantArray(const DataLayout &DL,
2482                                     const ConstantArray *CA, AsmPrinter &AP,
2483                                     const Constant *BaseCV, uint64_t Offset) {
2484   // See if we can aggregate some values.  Make sure it can be
2485   // represented as a series of bytes of the constant value.
2486   int Value = isRepeatedByteSequence(CA, DL);
2487 
2488   if (Value != -1) {
2489     uint64_t Bytes = DL.getTypeAllocSize(CA->getType());
2490     AP.OutStreamer->emitFill(Bytes, Value);
2491   }
2492   else {
2493     for (unsigned i = 0, e = CA->getNumOperands(); i != e; ++i) {
2494       emitGlobalConstantImpl(DL, CA->getOperand(i), AP, BaseCV, Offset);
2495       Offset += DL.getTypeAllocSize(CA->getOperand(i)->getType());
2496     }
2497   }
2498 }
2499 
2500 static void emitGlobalConstantVector(const DataLayout &DL,
2501                                      const ConstantVector *CV, AsmPrinter &AP) {
2502   for (unsigned i = 0, e = CV->getType()->getNumElements(); i != e; ++i)
2503     emitGlobalConstantImpl(DL, CV->getOperand(i), AP);
2504 
2505   unsigned Size = DL.getTypeAllocSize(CV->getType());
2506   unsigned EmittedSize = DL.getTypeAllocSize(CV->getType()->getElementType()) *
2507                          CV->getType()->getNumElements();
2508   if (unsigned Padding = Size - EmittedSize)
2509     AP.OutStreamer->EmitZeros(Padding);
2510 }
2511 
2512 static void emitGlobalConstantStruct(const DataLayout &DL,
2513                                      const ConstantStruct *CS, AsmPrinter &AP,
2514                                      const Constant *BaseCV, uint64_t Offset) {
2515   // Print the fields in successive locations. Pad to align if needed!
2516   unsigned Size = DL.getTypeAllocSize(CS->getType());
2517   const StructLayout *Layout = DL.getStructLayout(CS->getType());
2518   uint64_t SizeSoFar = 0;
2519   for (unsigned i = 0, e = CS->getNumOperands(); i != e; ++i) {
2520     const Constant *Field = CS->getOperand(i);
2521 
2522     // Print the actual field value.
2523     emitGlobalConstantImpl(DL, Field, AP, BaseCV, Offset + SizeSoFar);
2524 
2525     // Check if padding is needed and insert one or more 0s.
2526     uint64_t FieldSize = DL.getTypeAllocSize(Field->getType());
2527     uint64_t PadSize = ((i == e-1 ? Size : Layout->getElementOffset(i+1))
2528                         - Layout->getElementOffset(i)) - FieldSize;
2529     SizeSoFar += FieldSize + PadSize;
2530 
2531     // Insert padding - this may include padding to increase the size of the
2532     // current field up to the ABI size (if the struct is not packed) as well
2533     // as padding to ensure that the next field starts at the right offset.
2534     AP.OutStreamer->EmitZeros(PadSize);
2535   }
2536   assert(SizeSoFar == Layout->getSizeInBytes() &&
2537          "Layout of constant struct may be incorrect!");
2538 }
2539 
2540 static void emitGlobalConstantFP(APFloat APF, Type *ET, AsmPrinter &AP) {
2541   assert(ET && "Unknown float type");
2542   APInt API = APF.bitcastToAPInt();
2543 
2544   // First print a comment with what we think the original floating-point value
2545   // should have been.
2546   if (AP.isVerbose()) {
2547     SmallString<8> StrVal;
2548     APF.toString(StrVal);
2549     ET->print(AP.OutStreamer->GetCommentOS());
2550     AP.OutStreamer->GetCommentOS() << ' ' << StrVal << '\n';
2551   }
2552 
2553   // Now iterate through the APInt chunks, emitting them in endian-correct
2554   // order, possibly with a smaller chunk at beginning/end (e.g. for x87 80-bit
2555   // floats).
2556   unsigned NumBytes = API.getBitWidth() / 8;
2557   unsigned TrailingBytes = NumBytes % sizeof(uint64_t);
2558   const uint64_t *p = API.getRawData();
2559 
2560   // PPC's long double has odd notions of endianness compared to how LLVM
2561   // handles it: p[0] goes first for *big* endian on PPC.
2562   if (AP.getDataLayout().isBigEndian() && !ET->isPPC_FP128Ty()) {
2563     int Chunk = API.getNumWords() - 1;
2564 
2565     if (TrailingBytes)
2566       AP.OutStreamer->EmitIntValueInHexWithPadding(p[Chunk--], TrailingBytes);
2567 
2568     for (; Chunk >= 0; --Chunk)
2569       AP.OutStreamer->EmitIntValueInHexWithPadding(p[Chunk], sizeof(uint64_t));
2570   } else {
2571     unsigned Chunk;
2572     for (Chunk = 0; Chunk < NumBytes / sizeof(uint64_t); ++Chunk)
2573       AP.OutStreamer->EmitIntValueInHexWithPadding(p[Chunk], sizeof(uint64_t));
2574 
2575     if (TrailingBytes)
2576       AP.OutStreamer->EmitIntValueInHexWithPadding(p[Chunk], TrailingBytes);
2577   }
2578 
2579   // Emit the tail padding for the long double.
2580   const DataLayout &DL = AP.getDataLayout();
2581   AP.OutStreamer->EmitZeros(DL.getTypeAllocSize(ET) - DL.getTypeStoreSize(ET));
2582 }
2583 
2584 static void emitGlobalConstantFP(const ConstantFP *CFP, AsmPrinter &AP) {
2585   emitGlobalConstantFP(CFP->getValueAPF(), CFP->getType(), AP);
2586 }
2587 
2588 static void emitGlobalConstantLargeInt(const ConstantInt *CI, AsmPrinter &AP) {
2589   const DataLayout &DL = AP.getDataLayout();
2590   unsigned BitWidth = CI->getBitWidth();
2591 
2592   // Copy the value as we may massage the layout for constants whose bit width
2593   // is not a multiple of 64-bits.
2594   APInt Realigned(CI->getValue());
2595   uint64_t ExtraBits = 0;
2596   unsigned ExtraBitsSize = BitWidth & 63;
2597 
2598   if (ExtraBitsSize) {
2599     // The bit width of the data is not a multiple of 64-bits.
2600     // The extra bits are expected to be at the end of the chunk of the memory.
2601     // Little endian:
2602     // * Nothing to be done, just record the extra bits to emit.
2603     // Big endian:
2604     // * Record the extra bits to emit.
2605     // * Realign the raw data to emit the chunks of 64-bits.
2606     if (DL.isBigEndian()) {
2607       // Basically the structure of the raw data is a chunk of 64-bits cells:
2608       //    0        1         BitWidth / 64
2609       // [chunk1][chunk2] ... [chunkN].
2610       // The most significant chunk is chunkN and it should be emitted first.
2611       // However, due to the alignment issue chunkN contains useless bits.
2612       // Realign the chunks so that they contain only useless information:
2613       // ExtraBits     0       1       (BitWidth / 64) - 1
2614       //       chu[nk1 chu][nk2 chu] ... [nkN-1 chunkN]
2615       ExtraBits = Realigned.getRawData()[0] &
2616         (((uint64_t)-1) >> (64 - ExtraBitsSize));
2617       Realigned.lshrInPlace(ExtraBitsSize);
2618     } else
2619       ExtraBits = Realigned.getRawData()[BitWidth / 64];
2620   }
2621 
2622   // We don't expect assemblers to support integer data directives
2623   // for more than 64 bits, so we emit the data in at most 64-bit
2624   // quantities at a time.
2625   const uint64_t *RawData = Realigned.getRawData();
2626   for (unsigned i = 0, e = BitWidth / 64; i != e; ++i) {
2627     uint64_t Val = DL.isBigEndian() ? RawData[e - i - 1] : RawData[i];
2628     AP.OutStreamer->EmitIntValue(Val, 8);
2629   }
2630 
2631   if (ExtraBitsSize) {
2632     // Emit the extra bits after the 64-bits chunks.
2633 
2634     // Emit a directive that fills the expected size.
2635     uint64_t Size = AP.getDataLayout().getTypeAllocSize(CI->getType());
2636     Size -= (BitWidth / 64) * 8;
2637     assert(Size && Size * 8 >= ExtraBitsSize &&
2638            (ExtraBits & (((uint64_t)-1) >> (64 - ExtraBitsSize)))
2639            == ExtraBits && "Directive too small for extra bits.");
2640     AP.OutStreamer->EmitIntValue(ExtraBits, Size);
2641   }
2642 }
2643 
2644 /// Transform a not absolute MCExpr containing a reference to a GOT
2645 /// equivalent global, by a target specific GOT pc relative access to the
2646 /// final symbol.
2647 static void handleIndirectSymViaGOTPCRel(AsmPrinter &AP, const MCExpr **ME,
2648                                          const Constant *BaseCst,
2649                                          uint64_t Offset) {
2650   // The global @foo below illustrates a global that uses a got equivalent.
2651   //
2652   //  @bar = global i32 42
2653   //  @gotequiv = private unnamed_addr constant i32* @bar
2654   //  @foo = i32 trunc (i64 sub (i64 ptrtoint (i32** @gotequiv to i64),
2655   //                             i64 ptrtoint (i32* @foo to i64))
2656   //                        to i32)
2657   //
2658   // The cstexpr in @foo is converted into the MCExpr `ME`, where we actually
2659   // check whether @foo is suitable to use a GOTPCREL. `ME` is usually in the
2660   // form:
2661   //
2662   //  foo = cstexpr, where
2663   //    cstexpr := <gotequiv> - "." + <cst>
2664   //    cstexpr := <gotequiv> - (<foo> - <offset from @foo base>) + <cst>
2665   //
2666   // After canonicalization by evaluateAsRelocatable `ME` turns into:
2667   //
2668   //  cstexpr := <gotequiv> - <foo> + gotpcrelcst, where
2669   //    gotpcrelcst := <offset from @foo base> + <cst>
2670   MCValue MV;
2671   if (!(*ME)->evaluateAsRelocatable(MV, nullptr, nullptr) || MV.isAbsolute())
2672     return;
2673   const MCSymbolRefExpr *SymA = MV.getSymA();
2674   if (!SymA)
2675     return;
2676 
2677   // Check that GOT equivalent symbol is cached.
2678   const MCSymbol *GOTEquivSym = &SymA->getSymbol();
2679   if (!AP.GlobalGOTEquivs.count(GOTEquivSym))
2680     return;
2681 
2682   const GlobalValue *BaseGV = dyn_cast_or_null<GlobalValue>(BaseCst);
2683   if (!BaseGV)
2684     return;
2685 
2686   // Check for a valid base symbol
2687   const MCSymbol *BaseSym = AP.getSymbol(BaseGV);
2688   const MCSymbolRefExpr *SymB = MV.getSymB();
2689 
2690   if (!SymB || BaseSym != &SymB->getSymbol())
2691     return;
2692 
2693   // Make sure to match:
2694   //
2695   //    gotpcrelcst := <offset from @foo base> + <cst>
2696   //
2697   // If gotpcrelcst is positive it means that we can safely fold the pc rel
2698   // displacement into the GOTPCREL. We can also can have an extra offset <cst>
2699   // if the target knows how to encode it.
2700   int64_t GOTPCRelCst = Offset + MV.getConstant();
2701   if (GOTPCRelCst < 0)
2702     return;
2703   if (!AP.getObjFileLowering().supportGOTPCRelWithOffset() && GOTPCRelCst != 0)
2704     return;
2705 
2706   // Emit the GOT PC relative to replace the got equivalent global, i.e.:
2707   //
2708   //  bar:
2709   //    .long 42
2710   //  gotequiv:
2711   //    .quad bar
2712   //  foo:
2713   //    .long gotequiv - "." + <cst>
2714   //
2715   // is replaced by the target specific equivalent to:
2716   //
2717   //  bar:
2718   //    .long 42
2719   //  foo:
2720   //    .long bar@GOTPCREL+<gotpcrelcst>
2721   AsmPrinter::GOTEquivUsePair Result = AP.GlobalGOTEquivs[GOTEquivSym];
2722   const GlobalVariable *GV = Result.first;
2723   int NumUses = (int)Result.second;
2724   const GlobalValue *FinalGV = dyn_cast<GlobalValue>(GV->getOperand(0));
2725   const MCSymbol *FinalSym = AP.getSymbol(FinalGV);
2726   *ME = AP.getObjFileLowering().getIndirectSymViaGOTPCRel(
2727       FinalGV, FinalSym, MV, Offset, AP.MMI, *AP.OutStreamer);
2728 
2729   // Update GOT equivalent usage information
2730   --NumUses;
2731   if (NumUses >= 0)
2732     AP.GlobalGOTEquivs[GOTEquivSym] = std::make_pair(GV, NumUses);
2733 }
2734 
2735 static void emitGlobalConstantImpl(const DataLayout &DL, const Constant *CV,
2736                                    AsmPrinter &AP, const Constant *BaseCV,
2737                                    uint64_t Offset) {
2738   uint64_t Size = DL.getTypeAllocSize(CV->getType());
2739 
2740   // Globals with sub-elements such as combinations of arrays and structs
2741   // are handled recursively by emitGlobalConstantImpl. Keep track of the
2742   // constant symbol base and the current position with BaseCV and Offset.
2743   if (!BaseCV && CV->hasOneUse())
2744     BaseCV = dyn_cast<Constant>(CV->user_back());
2745 
2746   if (isa<ConstantAggregateZero>(CV) || isa<UndefValue>(CV))
2747     return AP.OutStreamer->EmitZeros(Size);
2748 
2749   if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV)) {
2750     switch (Size) {
2751     case 1:
2752     case 2:
2753     case 4:
2754     case 8:
2755       if (AP.isVerbose())
2756         AP.OutStreamer->GetCommentOS() << format("0x%" PRIx64 "\n",
2757                                                  CI->getZExtValue());
2758       AP.OutStreamer->EmitIntValue(CI->getZExtValue(), Size);
2759       return;
2760     default:
2761       emitGlobalConstantLargeInt(CI, AP);
2762       return;
2763     }
2764   }
2765 
2766   if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CV))
2767     return emitGlobalConstantFP(CFP, AP);
2768 
2769   if (isa<ConstantPointerNull>(CV)) {
2770     AP.OutStreamer->EmitIntValue(0, Size);
2771     return;
2772   }
2773 
2774   if (const ConstantDataSequential *CDS = dyn_cast<ConstantDataSequential>(CV))
2775     return emitGlobalConstantDataSequential(DL, CDS, AP);
2776 
2777   if (const ConstantArray *CVA = dyn_cast<ConstantArray>(CV))
2778     return emitGlobalConstantArray(DL, CVA, AP, BaseCV, Offset);
2779 
2780   if (const ConstantStruct *CVS = dyn_cast<ConstantStruct>(CV))
2781     return emitGlobalConstantStruct(DL, CVS, AP, BaseCV, Offset);
2782 
2783   if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV)) {
2784     // Look through bitcasts, which might not be able to be MCExpr'ized (e.g. of
2785     // vectors).
2786     if (CE->getOpcode() == Instruction::BitCast)
2787       return emitGlobalConstantImpl(DL, CE->getOperand(0), AP);
2788 
2789     if (Size > 8) {
2790       // If the constant expression's size is greater than 64-bits, then we have
2791       // to emit the value in chunks. Try to constant fold the value and emit it
2792       // that way.
2793       Constant *New = ConstantFoldConstant(CE, DL);
2794       if (New && New != CE)
2795         return emitGlobalConstantImpl(DL, New, AP);
2796     }
2797   }
2798 
2799   if (const ConstantVector *V = dyn_cast<ConstantVector>(CV))
2800     return emitGlobalConstantVector(DL, V, AP);
2801 
2802   // Otherwise, it must be a ConstantExpr.  Lower it to an MCExpr, then emit it
2803   // thread the streamer with EmitValue.
2804   const MCExpr *ME = AP.lowerConstant(CV);
2805 
2806   // Since lowerConstant already folded and got rid of all IR pointer and
2807   // integer casts, detect GOT equivalent accesses by looking into the MCExpr
2808   // directly.
2809   if (AP.getObjFileLowering().supportIndirectSymViaGOTPCRel())
2810     handleIndirectSymViaGOTPCRel(AP, &ME, BaseCV, Offset);
2811 
2812   AP.OutStreamer->EmitValue(ME, Size);
2813 }
2814 
2815 /// EmitGlobalConstant - Print a general LLVM constant to the .s file.
2816 void AsmPrinter::EmitGlobalConstant(const DataLayout &DL, const Constant *CV) {
2817   uint64_t Size = DL.getTypeAllocSize(CV->getType());
2818   if (Size)
2819     emitGlobalConstantImpl(DL, CV, *this);
2820   else if (MAI->hasSubsectionsViaSymbols()) {
2821     // If the global has zero size, emit a single byte so that two labels don't
2822     // look like they are at the same location.
2823     OutStreamer->EmitIntValue(0, 1);
2824   }
2825 }
2826 
2827 void AsmPrinter::EmitMachineConstantPoolValue(MachineConstantPoolValue *MCPV) {
2828   // Target doesn't support this yet!
2829   llvm_unreachable("Target does not support EmitMachineConstantPoolValue");
2830 }
2831 
2832 void AsmPrinter::printOffset(int64_t Offset, raw_ostream &OS) const {
2833   if (Offset > 0)
2834     OS << '+' << Offset;
2835   else if (Offset < 0)
2836     OS << Offset;
2837 }
2838 
2839 void AsmPrinter::emitNops(unsigned N) {
2840   MCInst Nop;
2841   MF->getSubtarget().getInstrInfo()->getNoop(Nop);
2842   for (; N; --N)
2843     EmitToStreamer(*OutStreamer, Nop);
2844 }
2845 
2846 //===----------------------------------------------------------------------===//
2847 // Symbol Lowering Routines.
2848 //===----------------------------------------------------------------------===//
2849 
2850 MCSymbol *AsmPrinter::createTempSymbol(const Twine &Name) const {
2851   return OutContext.createTempSymbol(Name, true);
2852 }
2853 
2854 MCSymbol *AsmPrinter::GetBlockAddressSymbol(const BlockAddress *BA) const {
2855   return MMI->getAddrLabelSymbol(BA->getBasicBlock());
2856 }
2857 
2858 MCSymbol *AsmPrinter::GetBlockAddressSymbol(const BasicBlock *BB) const {
2859   return MMI->getAddrLabelSymbol(BB);
2860 }
2861 
2862 /// GetCPISymbol - Return the symbol for the specified constant pool entry.
2863 MCSymbol *AsmPrinter::GetCPISymbol(unsigned CPID) const {
2864   if (getSubtargetInfo().getTargetTriple().isWindowsMSVCEnvironment()) {
2865     const MachineConstantPoolEntry &CPE =
2866         MF->getConstantPool()->getConstants()[CPID];
2867     if (!CPE.isMachineConstantPoolEntry()) {
2868       const DataLayout &DL = MF->getDataLayout();
2869       SectionKind Kind = CPE.getSectionKind(&DL);
2870       const Constant *C = CPE.Val.ConstVal;
2871       unsigned Align = CPE.Alignment;
2872       if (const MCSectionCOFF *S = dyn_cast<MCSectionCOFF>(
2873               getObjFileLowering().getSectionForConstant(DL, Kind, C, Align))) {
2874         if (MCSymbol *Sym = S->getCOMDATSymbol()) {
2875           if (Sym->isUndefined())
2876             OutStreamer->EmitSymbolAttribute(Sym, MCSA_Global);
2877           return Sym;
2878         }
2879       }
2880     }
2881   }
2882 
2883   const DataLayout &DL = getDataLayout();
2884   return OutContext.getOrCreateSymbol(Twine(DL.getPrivateGlobalPrefix()) +
2885                                       "CPI" + Twine(getFunctionNumber()) + "_" +
2886                                       Twine(CPID));
2887 }
2888 
2889 /// GetJTISymbol - Return the symbol for the specified jump table entry.
2890 MCSymbol *AsmPrinter::GetJTISymbol(unsigned JTID, bool isLinkerPrivate) const {
2891   return MF->getJTISymbol(JTID, OutContext, isLinkerPrivate);
2892 }
2893 
2894 /// GetJTSetSymbol - Return the symbol for the specified jump table .set
2895 /// FIXME: privatize to AsmPrinter.
2896 MCSymbol *AsmPrinter::GetJTSetSymbol(unsigned UID, unsigned MBBID) const {
2897   const DataLayout &DL = getDataLayout();
2898   return OutContext.getOrCreateSymbol(Twine(DL.getPrivateGlobalPrefix()) +
2899                                       Twine(getFunctionNumber()) + "_" +
2900                                       Twine(UID) + "_set_" + Twine(MBBID));
2901 }
2902 
2903 MCSymbol *AsmPrinter::getSymbolWithGlobalValueBase(const GlobalValue *GV,
2904                                                    StringRef Suffix) const {
2905   return getObjFileLowering().getSymbolWithGlobalValueBase(GV, Suffix, TM);
2906 }
2907 
2908 /// Return the MCSymbol for the specified ExternalSymbol.
2909 MCSymbol *AsmPrinter::GetExternalSymbolSymbol(StringRef Sym) const {
2910   SmallString<60> NameStr;
2911   Mangler::getNameWithPrefix(NameStr, Sym, getDataLayout());
2912   return OutContext.getOrCreateSymbol(NameStr);
2913 }
2914 
2915 /// PrintParentLoopComment - Print comments about parent loops of this one.
2916 static void PrintParentLoopComment(raw_ostream &OS, const MachineLoop *Loop,
2917                                    unsigned FunctionNumber) {
2918   if (!Loop) return;
2919   PrintParentLoopComment(OS, Loop->getParentLoop(), FunctionNumber);
2920   OS.indent(Loop->getLoopDepth()*2)
2921     << "Parent Loop BB" << FunctionNumber << "_"
2922     << Loop->getHeader()->getNumber()
2923     << " Depth=" << Loop->getLoopDepth() << '\n';
2924 }
2925 
2926 /// PrintChildLoopComment - Print comments about child loops within
2927 /// the loop for this basic block, with nesting.
2928 static void PrintChildLoopComment(raw_ostream &OS, const MachineLoop *Loop,
2929                                   unsigned FunctionNumber) {
2930   // Add child loop information
2931   for (const MachineLoop *CL : *Loop) {
2932     OS.indent(CL->getLoopDepth()*2)
2933       << "Child Loop BB" << FunctionNumber << "_"
2934       << CL->getHeader()->getNumber() << " Depth " << CL->getLoopDepth()
2935       << '\n';
2936     PrintChildLoopComment(OS, CL, FunctionNumber);
2937   }
2938 }
2939 
2940 /// emitBasicBlockLoopComments - Pretty-print comments for basic blocks.
2941 static void emitBasicBlockLoopComments(const MachineBasicBlock &MBB,
2942                                        const MachineLoopInfo *LI,
2943                                        const AsmPrinter &AP) {
2944   // Add loop depth information
2945   const MachineLoop *Loop = LI->getLoopFor(&MBB);
2946   if (!Loop) return;
2947 
2948   MachineBasicBlock *Header = Loop->getHeader();
2949   assert(Header && "No header for loop");
2950 
2951   // If this block is not a loop header, just print out what is the loop header
2952   // and return.
2953   if (Header != &MBB) {
2954     AP.OutStreamer->AddComment("  in Loop: Header=BB" +
2955                                Twine(AP.getFunctionNumber())+"_" +
2956                                Twine(Loop->getHeader()->getNumber())+
2957                                " Depth="+Twine(Loop->getLoopDepth()));
2958     return;
2959   }
2960 
2961   // Otherwise, it is a loop header.  Print out information about child and
2962   // parent loops.
2963   raw_ostream &OS = AP.OutStreamer->GetCommentOS();
2964 
2965   PrintParentLoopComment(OS, Loop->getParentLoop(), AP.getFunctionNumber());
2966 
2967   OS << "=>";
2968   OS.indent(Loop->getLoopDepth()*2-2);
2969 
2970   OS << "This ";
2971   if (Loop->empty())
2972     OS << "Inner ";
2973   OS << "Loop Header: Depth=" + Twine(Loop->getLoopDepth()) << '\n';
2974 
2975   PrintChildLoopComment(OS, Loop, AP.getFunctionNumber());
2976 }
2977 
2978 /// EmitBasicBlockStart - This method prints the label for the specified
2979 /// MachineBasicBlock, an alignment (if present) and a comment describing
2980 /// it if appropriate.
2981 void AsmPrinter::EmitBasicBlockStart(const MachineBasicBlock &MBB) {
2982   // End the previous funclet and start a new one.
2983   if (MBB.isEHFuncletEntry()) {
2984     for (const HandlerInfo &HI : Handlers) {
2985       HI.Handler->endFunclet();
2986       HI.Handler->beginFunclet(MBB);
2987     }
2988   }
2989 
2990   // Emit an alignment directive for this block, if needed.
2991   const Align Alignment = MBB.getAlignment();
2992   if (Alignment != Align(1))
2993     EmitAlignment(Alignment);
2994 
2995   // If the block has its address taken, emit any labels that were used to
2996   // reference the block.  It is possible that there is more than one label
2997   // here, because multiple LLVM BB's may have been RAUW'd to this block after
2998   // the references were generated.
2999   if (MBB.hasAddressTaken()) {
3000     const BasicBlock *BB = MBB.getBasicBlock();
3001     if (isVerbose())
3002       OutStreamer->AddComment("Block address taken");
3003 
3004     // MBBs can have their address taken as part of CodeGen without having
3005     // their corresponding BB's address taken in IR
3006     if (BB->hasAddressTaken())
3007       for (MCSymbol *Sym : MMI->getAddrLabelSymbolToEmit(BB))
3008         OutStreamer->EmitLabel(Sym);
3009   }
3010 
3011   // Print some verbose block comments.
3012   if (isVerbose()) {
3013     if (const BasicBlock *BB = MBB.getBasicBlock()) {
3014       if (BB->hasName()) {
3015         BB->printAsOperand(OutStreamer->GetCommentOS(),
3016                            /*PrintType=*/false, BB->getModule());
3017         OutStreamer->GetCommentOS() << '\n';
3018       }
3019     }
3020 
3021     assert(MLI != nullptr && "MachineLoopInfo should has been computed");
3022     emitBasicBlockLoopComments(MBB, MLI, *this);
3023   }
3024 
3025   // Print the main label for the block.
3026   if (MBB.pred_empty() ||
3027       (isBlockOnlyReachableByFallthrough(&MBB) && !MBB.isEHFuncletEntry() &&
3028        !MBB.hasLabelMustBeEmitted())) {
3029     if (isVerbose()) {
3030       // NOTE: Want this comment at start of line, don't emit with AddComment.
3031       OutStreamer->emitRawComment(" %bb." + Twine(MBB.getNumber()) + ":",
3032                                   false);
3033     }
3034   } else {
3035     if (isVerbose() && MBB.hasLabelMustBeEmitted())
3036       OutStreamer->AddComment("Label of block must be emitted");
3037     OutStreamer->EmitLabel(MBB.getSymbol());
3038   }
3039 }
3040 
3041 void AsmPrinter::EmitBasicBlockEnd(const MachineBasicBlock &MBB) {}
3042 
3043 void AsmPrinter::EmitVisibility(MCSymbol *Sym, unsigned Visibility,
3044                                 bool IsDefinition) const {
3045   MCSymbolAttr Attr = MCSA_Invalid;
3046 
3047   switch (Visibility) {
3048   default: break;
3049   case GlobalValue::HiddenVisibility:
3050     if (IsDefinition)
3051       Attr = MAI->getHiddenVisibilityAttr();
3052     else
3053       Attr = MAI->getHiddenDeclarationVisibilityAttr();
3054     break;
3055   case GlobalValue::ProtectedVisibility:
3056     Attr = MAI->getProtectedVisibilityAttr();
3057     break;
3058   }
3059 
3060   if (Attr != MCSA_Invalid)
3061     OutStreamer->EmitSymbolAttribute(Sym, Attr);
3062 }
3063 
3064 /// isBlockOnlyReachableByFallthough - Return true if the basic block has
3065 /// exactly one predecessor and the control transfer mechanism between
3066 /// the predecessor and this block is a fall-through.
3067 bool AsmPrinter::
3068 isBlockOnlyReachableByFallthrough(const MachineBasicBlock *MBB) const {
3069   // If this is a landing pad, it isn't a fall through.  If it has no preds,
3070   // then nothing falls through to it.
3071   if (MBB->isEHPad() || MBB->pred_empty())
3072     return false;
3073 
3074   // If there isn't exactly one predecessor, it can't be a fall through.
3075   if (MBB->pred_size() > 1)
3076     return false;
3077 
3078   // The predecessor has to be immediately before this block.
3079   MachineBasicBlock *Pred = *MBB->pred_begin();
3080   if (!Pred->isLayoutSuccessor(MBB))
3081     return false;
3082 
3083   // If the block is completely empty, then it definitely does fall through.
3084   if (Pred->empty())
3085     return true;
3086 
3087   // Check the terminators in the previous blocks
3088   for (const auto &MI : Pred->terminators()) {
3089     // If it is not a simple branch, we are in a table somewhere.
3090     if (!MI.isBranch() || MI.isIndirectBranch())
3091       return false;
3092 
3093     // If we are the operands of one of the branches, this is not a fall
3094     // through. Note that targets with delay slots will usually bundle
3095     // terminators with the delay slot instruction.
3096     for (ConstMIBundleOperands OP(MI); OP.isValid(); ++OP) {
3097       if (OP->isJTI())
3098         return false;
3099       if (OP->isMBB() && OP->getMBB() == MBB)
3100         return false;
3101     }
3102   }
3103 
3104   return true;
3105 }
3106 
3107 GCMetadataPrinter *AsmPrinter::GetOrCreateGCPrinter(GCStrategy &S) {
3108   if (!S.usesMetadata())
3109     return nullptr;
3110 
3111   gcp_map_type &GCMap = getGCMap(GCMetadataPrinters);
3112   gcp_map_type::iterator GCPI = GCMap.find(&S);
3113   if (GCPI != GCMap.end())
3114     return GCPI->second.get();
3115 
3116   auto Name = S.getName();
3117 
3118   for (GCMetadataPrinterRegistry::iterator
3119          I = GCMetadataPrinterRegistry::begin(),
3120          E = GCMetadataPrinterRegistry::end(); I != E; ++I)
3121     if (Name == I->getName()) {
3122       std::unique_ptr<GCMetadataPrinter> GMP = I->instantiate();
3123       GMP->S = &S;
3124       auto IterBool = GCMap.insert(std::make_pair(&S, std::move(GMP)));
3125       return IterBool.first->second.get();
3126     }
3127 
3128   report_fatal_error("no GCMetadataPrinter registered for GC: " + Twine(Name));
3129 }
3130 
3131 void AsmPrinter::emitStackMaps(StackMaps &SM) {
3132   GCModuleInfo *MI = getAnalysisIfAvailable<GCModuleInfo>();
3133   assert(MI && "AsmPrinter didn't require GCModuleInfo?");
3134   bool NeedsDefault = false;
3135   if (MI->begin() == MI->end())
3136     // No GC strategy, use the default format.
3137     NeedsDefault = true;
3138   else
3139     for (auto &I : *MI) {
3140       if (GCMetadataPrinter *MP = GetOrCreateGCPrinter(*I))
3141         if (MP->emitStackMaps(SM, *this))
3142           continue;
3143       // The strategy doesn't have printer or doesn't emit custom stack maps.
3144       // Use the default format.
3145       NeedsDefault = true;
3146     }
3147 
3148   if (NeedsDefault)
3149     SM.serializeToStackMapSection();
3150 }
3151 
3152 /// Pin vtable to this file.
3153 AsmPrinterHandler::~AsmPrinterHandler() = default;
3154 
3155 void AsmPrinterHandler::markFunctionEnd() {}
3156 
3157 // In the binary's "xray_instr_map" section, an array of these function entries
3158 // describes each instrumentation point.  When XRay patches your code, the index
3159 // into this table will be given to your handler as a patch point identifier.
3160 void AsmPrinter::XRayFunctionEntry::emit(int Bytes, MCStreamer *Out,
3161                                          const MCSymbol *CurrentFnSym) const {
3162   Out->EmitSymbolValue(Sled, Bytes);
3163   Out->EmitSymbolValue(CurrentFnSym, Bytes);
3164   auto Kind8 = static_cast<uint8_t>(Kind);
3165   Out->EmitBinaryData(StringRef(reinterpret_cast<const char *>(&Kind8), 1));
3166   Out->EmitBinaryData(
3167       StringRef(reinterpret_cast<const char *>(&AlwaysInstrument), 1));
3168   Out->EmitBinaryData(StringRef(reinterpret_cast<const char *>(&Version), 1));
3169   auto Padding = (4 * Bytes) - ((2 * Bytes) + 3);
3170   assert(Padding >= 0 && "Instrumentation map entry > 4 * Word Size");
3171   Out->EmitZeros(Padding);
3172 }
3173 
3174 void AsmPrinter::emitXRayTable() {
3175   if (Sleds.empty())
3176     return;
3177 
3178   auto PrevSection = OutStreamer->getCurrentSectionOnly();
3179   const Function &F = MF->getFunction();
3180   MCSection *InstMap = nullptr;
3181   MCSection *FnSledIndex = nullptr;
3182   if (MF->getSubtarget().getTargetTriple().isOSBinFormatELF()) {
3183     auto LinkedToSym = dyn_cast<MCSymbolELF>(CurrentFnSym);
3184     assert(LinkedToSym != nullptr);
3185     auto Flags = ELF::SHF_WRITE | ELF::SHF_ALLOC | ELF::SHF_LINK_ORDER;
3186     std::string GroupName;
3187     if (F.hasComdat()) {
3188       Flags |= ELF::SHF_GROUP;
3189       GroupName = std::string(F.getComdat()->getName());
3190     }
3191 
3192     auto UniqueID = ++XRayFnUniqueID;
3193     InstMap =
3194         OutContext.getELFSection("xray_instr_map", ELF::SHT_PROGBITS, Flags, 0,
3195                                  GroupName, UniqueID, LinkedToSym);
3196     FnSledIndex =
3197         OutContext.getELFSection("xray_fn_idx", ELF::SHT_PROGBITS, Flags, 0,
3198                                  GroupName, UniqueID, LinkedToSym);
3199   } else if (MF->getSubtarget().getTargetTriple().isOSBinFormatMachO()) {
3200     InstMap = OutContext.getMachOSection("__DATA", "xray_instr_map", 0,
3201                                          SectionKind::getReadOnlyWithRel());
3202     FnSledIndex = OutContext.getMachOSection("__DATA", "xray_fn_idx", 0,
3203                                              SectionKind::getReadOnlyWithRel());
3204   } else {
3205     llvm_unreachable("Unsupported target");
3206   }
3207 
3208   auto WordSizeBytes = MAI->getCodePointerSize();
3209 
3210   // Now we switch to the instrumentation map section. Because this is done
3211   // per-function, we are able to create an index entry that will represent the
3212   // range of sleds associated with a function.
3213   MCSymbol *SledsStart = OutContext.createTempSymbol("xray_sleds_start", true);
3214   OutStreamer->SwitchSection(InstMap);
3215   OutStreamer->EmitLabel(SledsStart);
3216   for (const auto &Sled : Sleds)
3217     Sled.emit(WordSizeBytes, OutStreamer.get(), CurrentFnSym);
3218   MCSymbol *SledsEnd = OutContext.createTempSymbol("xray_sleds_end", true);
3219   OutStreamer->EmitLabel(SledsEnd);
3220 
3221   // We then emit a single entry in the index per function. We use the symbols
3222   // that bound the instrumentation map as the range for a specific function.
3223   // Each entry here will be 2 * word size aligned, as we're writing down two
3224   // pointers. This should work for both 32-bit and 64-bit platforms.
3225   OutStreamer->SwitchSection(FnSledIndex);
3226   OutStreamer->EmitCodeAlignment(2 * WordSizeBytes);
3227   OutStreamer->EmitSymbolValue(SledsStart, WordSizeBytes, false);
3228   OutStreamer->EmitSymbolValue(SledsEnd, WordSizeBytes, false);
3229   OutStreamer->SwitchSection(PrevSection);
3230   Sleds.clear();
3231 }
3232 
3233 void AsmPrinter::recordSled(MCSymbol *Sled, const MachineInstr &MI,
3234                             SledKind Kind, uint8_t Version) {
3235   const Function &F = MI.getMF()->getFunction();
3236   auto Attr = F.getFnAttribute("function-instrument");
3237   bool LogArgs = F.hasFnAttribute("xray-log-args");
3238   bool AlwaysInstrument =
3239     Attr.isStringAttribute() && Attr.getValueAsString() == "xray-always";
3240   if (Kind == SledKind::FUNCTION_ENTER && LogArgs)
3241     Kind = SledKind::LOG_ARGS_ENTER;
3242   Sleds.emplace_back(XRayFunctionEntry{Sled, CurrentFnSym, Kind,
3243                                        AlwaysInstrument, &F, Version});
3244 }
3245 
3246 void AsmPrinter::emitPatchableFunctionEntries() {
3247   const Function &F = MF->getFunction();
3248   unsigned PatchableFunctionPrefix = 0, PatchableFunctionEntry = 0;
3249   (void)F.getFnAttribute("patchable-function-prefix")
3250       .getValueAsString()
3251       .getAsInteger(10, PatchableFunctionPrefix);
3252   (void)F.getFnAttribute("patchable-function-entry")
3253       .getValueAsString()
3254       .getAsInteger(10, PatchableFunctionEntry);
3255   if (!PatchableFunctionPrefix && !PatchableFunctionEntry)
3256     return;
3257   const unsigned PointerSize = getPointerSize();
3258   if (TM.getTargetTriple().isOSBinFormatELF()) {
3259     auto Flags = ELF::SHF_WRITE | ELF::SHF_ALLOC;
3260 
3261     // As of binutils 2.33, GNU as does not support section flag "o" or linkage
3262     // field "unique". Use SHF_LINK_ORDER if we are using the integrated
3263     // assembler.
3264     if (MAI->useIntegratedAssembler()) {
3265       Flags |= ELF::SHF_LINK_ORDER;
3266       std::string GroupName;
3267       if (F.hasComdat()) {
3268         Flags |= ELF::SHF_GROUP;
3269         GroupName = std::string(F.getComdat()->getName());
3270       }
3271       MCSection *Section = getObjFileLowering().SectionForGlobal(&F, TM);
3272       unsigned UniqueID =
3273           PatchableFunctionEntryID
3274               .try_emplace(Section, PatchableFunctionEntryID.size())
3275               .first->second;
3276       OutStreamer->SwitchSection(OutContext.getELFSection(
3277           "__patchable_function_entries", ELF::SHT_PROGBITS, Flags, 0,
3278           GroupName, UniqueID, cast<MCSymbolELF>(CurrentFnSym)));
3279     } else {
3280       OutStreamer->SwitchSection(OutContext.getELFSection(
3281           "__patchable_function_entries", ELF::SHT_PROGBITS, Flags));
3282     }
3283     EmitAlignment(Align(PointerSize));
3284     OutStreamer->EmitSymbolValue(CurrentPatchableFunctionEntrySym, PointerSize);
3285   }
3286 }
3287 
3288 uint16_t AsmPrinter::getDwarfVersion() const {
3289   return OutStreamer->getContext().getDwarfVersion();
3290 }
3291 
3292 void AsmPrinter::setDwarfVersion(uint16_t Version) {
3293   OutStreamer->getContext().setDwarfVersion(Version);
3294 }
3295