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