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