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