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