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