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