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