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