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