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