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