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