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