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