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