move handling of asm-verbose out of AsmPrinter.cpp into LLVMTargetMachine.cpp with...
[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 "llvm/Assembly/Writer.h"
17 #include "llvm/DerivedTypes.h"
18 #include "llvm/Constants.h"
19 #include "llvm/Module.h"
20 #include "llvm/CodeGen/DwarfWriter.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/Analysis/DebugInfo.h"
29 #include "llvm/MC/MCContext.h"
30 #include "llvm/MC/MCExpr.h"
31 #include "llvm/MC/MCInst.h"
32 #include "llvm/MC/MCSection.h"
33 #include "llvm/MC/MCStreamer.h"
34 #include "llvm/MC/MCSymbol.h"
35 #include "llvm/MC/MCAsmInfo.h"
36 #include "llvm/Target/Mangler.h"
37 #include "llvm/Target/TargetData.h"
38 #include "llvm/Target/TargetInstrInfo.h"
39 #include "llvm/Target/TargetLowering.h"
40 #include "llvm/Target/TargetLoweringObjectFile.h"
41 #include "llvm/Target/TargetOptions.h"
42 #include "llvm/Target/TargetRegisterInfo.h"
43 #include "llvm/ADT/SmallPtrSet.h"
44 #include "llvm/ADT/SmallString.h"
45 #include "llvm/ADT/Statistic.h"
46 #include "llvm/Support/CommandLine.h"
47 #include "llvm/Support/Debug.h"
48 #include "llvm/Support/ErrorHandling.h"
49 #include "llvm/Support/Format.h"
50 #include "llvm/Support/FormattedStream.h"
51 #include <cerrno>
52 using namespace llvm;
53
54 STATISTIC(EmittedInsts, "Number of machine instrs printed");
55
56 char AsmPrinter::ID = 0;
57 AsmPrinter::AsmPrinter(formatted_raw_ostream &o, TargetMachine &tm,
58                        const MCAsmInfo *T, bool VerboseAsm)
59   : MachineFunctionPass(&ID), O(o),
60     TM(tm), MAI(T), TRI(tm.getRegisterInfo()),
61
62     OutContext(*new MCContext()),
63     // FIXME: Pass instprinter to streamer.
64     OutStreamer(*createAsmStreamer(OutContext, O, *T,
65                                    TM.getTargetData()->isLittleEndian(),
66                                    VerboseAsm, 0)),
67
68     LastMI(0), LastFn(0), Counter(~0U), PrevDLT(NULL) {
69   DW = 0; MMI = 0;
70   this->VerboseAsm = VerboseAsm;
71 }
72
73 AsmPrinter::~AsmPrinter() {
74   for (gcp_iterator I = GCMetadataPrinters.begin(),
75                     E = GCMetadataPrinters.end(); I != E; ++I)
76     delete I->second;
77   
78   delete &OutStreamer;
79   delete &OutContext;
80 }
81
82 /// getFunctionNumber - Return a unique ID for the current function.
83 ///
84 unsigned AsmPrinter::getFunctionNumber() const {
85   return MF->getFunctionNumber();
86 }
87
88 TargetLoweringObjectFile &AsmPrinter::getObjFileLowering() const {
89   return TM.getTargetLowering()->getObjFileLowering();
90 }
91
92 /// getCurrentSection() - Return the current section we are emitting to.
93 const MCSection *AsmPrinter::getCurrentSection() const {
94   return OutStreamer.getCurrentSection();
95 }
96
97
98 void AsmPrinter::getAnalysisUsage(AnalysisUsage &AU) const {
99   AU.setPreservesAll();
100   MachineFunctionPass::getAnalysisUsage(AU);
101   AU.addRequired<GCModuleInfo>();
102   if (VerboseAsm)
103     AU.addRequired<MachineLoopInfo>();
104 }
105
106 bool AsmPrinter::doInitialization(Module &M) {
107   // Initialize TargetLoweringObjectFile.
108   const_cast<TargetLoweringObjectFile&>(getObjFileLowering())
109     .Initialize(OutContext, TM);
110   
111   Mang = new Mangler(*MAI);
112   
113   // Allow the target to emit any magic that it wants at the start of the file.
114   EmitStartOfAsmFile(M);
115
116   // Very minimal debug info. It is ignored if we emit actual debug info. If we
117   // don't, this at least helps the user find where a global came from.
118   if (MAI->hasSingleParameterDotFile()) {
119     // .file "foo.c"
120     OutStreamer.EmitFileDirective(M.getModuleIdentifier());
121   }
122
123   GCModuleInfo *MI = getAnalysisIfAvailable<GCModuleInfo>();
124   assert(MI && "AsmPrinter didn't require GCModuleInfo?");
125   for (GCModuleInfo::iterator I = MI->begin(), E = MI->end(); I != E; ++I)
126     if (GCMetadataPrinter *MP = GetOrCreateGCPrinter(*I))
127       MP->beginAssembly(O, *this, *MAI);
128   
129   if (!M.getModuleInlineAsm().empty())
130     O << MAI->getCommentString() << " Start of file scope inline assembly\n"
131       << M.getModuleInlineAsm()
132       << '\n' << MAI->getCommentString()
133       << " End of file scope inline assembly\n";
134
135   MMI = getAnalysisIfAvailable<MachineModuleInfo>();
136   if (MMI)
137     MMI->AnalyzeModule(M);
138   DW = getAnalysisIfAvailable<DwarfWriter>();
139   if (DW)
140     DW->BeginModule(&M, MMI, O, this, MAI);
141
142   return false;
143 }
144
145 void AsmPrinter::EmitLinkage(unsigned Linkage, MCSymbol *GVSym) const {
146   switch ((GlobalValue::LinkageTypes)Linkage) {
147   case GlobalValue::CommonLinkage:
148   case GlobalValue::LinkOnceAnyLinkage:
149   case GlobalValue::LinkOnceODRLinkage:
150   case GlobalValue::WeakAnyLinkage:
151   case GlobalValue::WeakODRLinkage:
152   case GlobalValue::LinkerPrivateLinkage:
153     if (MAI->getWeakDefDirective() != 0) {
154       // .globl _foo
155       OutStreamer.EmitSymbolAttribute(GVSym, MCSA_Global);
156       // .weak_definition _foo
157       OutStreamer.EmitSymbolAttribute(GVSym, MCSA_WeakDefinition);
158     } else if (const char *LinkOnce = MAI->getLinkOnceDirective()) {
159       // .globl _foo
160       OutStreamer.EmitSymbolAttribute(GVSym, MCSA_Global);
161       // FIXME: linkonce should be a section attribute, handled by COFF Section
162       // assignment.
163       // http://sourceware.org/binutils/docs-2.20/as/Linkonce.html#Linkonce
164       // .linkonce discard
165       // FIXME: It would be nice to use .linkonce samesize for non-common
166       // globals.
167       O << LinkOnce;
168     } else {
169       // .weak _foo
170       OutStreamer.EmitSymbolAttribute(GVSym, MCSA_Weak);
171     }
172     break;
173   case GlobalValue::DLLExportLinkage:
174   case GlobalValue::AppendingLinkage:
175     // FIXME: appending linkage variables should go into a section of
176     // their name or something.  For now, just emit them as external.
177   case GlobalValue::ExternalLinkage:
178     // If external or appending, declare as a global symbol.
179     // .globl _foo
180     OutStreamer.EmitSymbolAttribute(GVSym, MCSA_Global);
181     break;
182   case GlobalValue::PrivateLinkage:
183   case GlobalValue::InternalLinkage:
184     break;
185   default:
186     llvm_unreachable("Unknown linkage type!");
187   }
188 }
189
190
191 /// EmitGlobalVariable - Emit the specified global variable to the .s file.
192 void AsmPrinter::EmitGlobalVariable(const GlobalVariable *GV) {
193   if (!GV->hasInitializer())   // External globals require no code.
194     return;
195   
196   // Check to see if this is a special global used by LLVM, if so, emit it.
197   if (EmitSpecialLLVMGlobal(GV))
198     return;
199
200   MCSymbol *GVSym = GetGlobalValueSymbol(GV);
201   EmitVisibility(GVSym, GV->getVisibility());
202
203   if (MAI->hasDotTypeDotSizeDirective())
204     OutStreamer.EmitSymbolAttribute(GVSym, MCSA_ELF_TypeObject);
205   
206   SectionKind GVKind = TargetLoweringObjectFile::getKindForGlobal(GV, TM);
207
208   const TargetData *TD = TM.getTargetData();
209   unsigned Size = TD->getTypeAllocSize(GV->getType()->getElementType());
210   unsigned AlignLog = TD->getPreferredAlignmentLog(GV);
211   
212   // Handle common and BSS local symbols (.lcomm).
213   if (GVKind.isCommon() || GVKind.isBSSLocal()) {
214     if (Size == 0) Size = 1;   // .comm Foo, 0 is undefined, avoid it.
215     
216     if (VerboseAsm) {
217       WriteAsOperand(OutStreamer.GetCommentOS(), GV,
218                      /*PrintType=*/false, GV->getParent());
219       OutStreamer.GetCommentOS() << '\n';
220     }
221     
222     // Handle common symbols.
223     if (GVKind.isCommon()) {
224       // .comm _foo, 42, 4
225       OutStreamer.EmitCommonSymbol(GVSym, Size, 1 << AlignLog);
226       return;
227     }
228     
229     // Handle local BSS symbols.
230     if (MAI->hasMachoZeroFillDirective()) {
231       const MCSection *TheSection =
232         getObjFileLowering().SectionForGlobal(GV, GVKind, Mang, TM);
233       // .zerofill __DATA, __bss, _foo, 400, 5
234       OutStreamer.EmitZerofill(TheSection, GVSym, Size, 1 << AlignLog);
235       return;
236     }
237     
238     if (MAI->hasLCOMMDirective()) {
239       // .lcomm _foo, 42
240       OutStreamer.EmitLocalCommonSymbol(GVSym, Size);
241       return;
242     }
243     
244     // .local _foo
245     OutStreamer.EmitSymbolAttribute(GVSym, MCSA_Local);
246     // .comm _foo, 42, 4
247     OutStreamer.EmitCommonSymbol(GVSym, Size, 1 << AlignLog);
248     return;
249   }
250   
251   const MCSection *TheSection =
252     getObjFileLowering().SectionForGlobal(GV, GVKind, Mang, TM);
253
254   // Handle the zerofill directive on darwin, which is a special form of BSS
255   // emission.
256   if (GVKind.isBSSExtern() && MAI->hasMachoZeroFillDirective()) {
257     // .globl _foo
258     OutStreamer.EmitSymbolAttribute(GVSym, MCSA_Global);
259     // .zerofill __DATA, __common, _foo, 400, 5
260     OutStreamer.EmitZerofill(TheSection, GVSym, Size, 1 << AlignLog);
261     return;
262   }
263
264   OutStreamer.SwitchSection(TheSection);
265
266   EmitLinkage(GV->getLinkage(), GVSym);
267   EmitAlignment(AlignLog, GV);
268
269   if (VerboseAsm) {
270     WriteAsOperand(OutStreamer.GetCommentOS(), GV,
271                    /*PrintType=*/false, GV->getParent());
272     OutStreamer.GetCommentOS() << '\n';
273   }
274   OutStreamer.EmitLabel(GVSym);
275
276   EmitGlobalConstant(GV->getInitializer());
277
278   if (MAI->hasDotTypeDotSizeDirective())
279     // .size foo, 42
280     OutStreamer.EmitELFSize(GVSym, MCConstantExpr::Create(Size, OutContext));
281   
282   OutStreamer.AddBlankLine();
283 }
284
285 /// EmitFunctionHeader - This method emits the header for the current
286 /// function.
287 void AsmPrinter::EmitFunctionHeader() {
288   // Print out constants referenced by the function
289   EmitConstantPool();
290   
291   // Print the 'header' of function.
292   const Function *F = MF->getFunction();
293
294   OutStreamer.SwitchSection(getObjFileLowering().SectionForGlobal(F, Mang, TM));
295   EmitVisibility(CurrentFnSym, F->getVisibility());
296
297   EmitLinkage(F->getLinkage(), CurrentFnSym);
298   EmitAlignment(MF->getAlignment(), F);
299
300   if (MAI->hasDotTypeDotSizeDirective())
301     OutStreamer.EmitSymbolAttribute(CurrentFnSym, MCSA_ELF_TypeFunction);
302
303   if (VerboseAsm) {
304     WriteAsOperand(OutStreamer.GetCommentOS(), F,
305                    /*PrintType=*/false, F->getParent());
306     OutStreamer.GetCommentOS() << '\n';
307   }
308
309   // Emit the CurrentFnSym.  This is is a virtual function to allow targets to
310   // do their wild and crazy things as required.
311   EmitFunctionEntryLabel();
312   
313   // Add some workaround for linkonce linkage on Cygwin\MinGW.
314   if (MAI->getLinkOnceDirective() != 0 &&
315       (F->hasLinkOnceLinkage() || F->hasWeakLinkage()))
316     // FIXME: What is this?
317     O << "Lllvm$workaround$fake$stub$" << *CurrentFnSym << ":\n";
318   
319   // Emit pre-function debug and/or EH information.
320   if (MAI->doesSupportDebugInformation() || MAI->doesSupportExceptionHandling())
321     DW->BeginFunction(MF);
322 }
323
324 /// EmitFunctionEntryLabel - Emit the label that is the entrypoint for the
325 /// function.  This can be overridden by targets as required to do custom stuff.
326 void AsmPrinter::EmitFunctionEntryLabel() {
327   OutStreamer.EmitLabel(CurrentFnSym);
328 }
329
330
331 /// EmitFunctionBody - This method emits the body and trailer for a
332 /// function.
333 void AsmPrinter::EmitFunctionBody() {
334   // Emit target-specific gunk before the function body.
335   EmitFunctionBodyStart();
336   
337   // Print out code for the function.
338   bool HasAnyRealCode = false;
339   for (MachineFunction::const_iterator I = MF->begin(), E = MF->end();
340        I != E; ++I) {
341     // Print a label for the basic block.
342     EmitBasicBlockStart(I);
343     for (MachineBasicBlock::const_iterator II = I->begin(), IE = I->end();
344          II != IE; ++II) {
345       // Print the assembly for the instruction.
346       if (!II->isLabel())
347         HasAnyRealCode = true;
348       
349       ++EmittedInsts;
350       
351       // FIXME: Clean up processDebugLoc.
352       processDebugLoc(II, true);
353       
354       EmitInstruction(II);
355       
356       if (VerboseAsm)
357         EmitComments(*II);
358       O << '\n';
359       
360       // FIXME: Clean up processDebugLoc.
361       processDebugLoc(II, false);
362     }
363   }
364   
365   // If the function is empty and the object file uses .subsections_via_symbols,
366   // then we need to emit *something* to the function body to prevent the
367   // labels from collapsing together.  Just emit a 0 byte.
368   if (MAI->hasSubsectionsViaSymbols() && !HasAnyRealCode)
369     OutStreamer.EmitIntValue(0, 1, 0/*addrspace*/);
370   
371   // Emit target-specific gunk after the function body.
372   EmitFunctionBodyEnd();
373   
374   if (MAI->hasDotTypeDotSizeDirective())
375     O << "\t.size\t" << *CurrentFnSym << ", .-" << *CurrentFnSym << '\n';
376   
377   // Emit post-function debug information.
378   if (MAI->doesSupportDebugInformation() || MAI->doesSupportExceptionHandling())
379     DW->EndFunction(MF);
380   
381   // Print out jump tables referenced by the function.
382   EmitJumpTableInfo();
383 }
384
385
386 bool AsmPrinter::doFinalization(Module &M) {
387   // Emit global variables.
388   for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
389        I != E; ++I)
390     EmitGlobalVariable(I);
391   
392   // Emit final debug information.
393   if (MAI->doesSupportDebugInformation() || MAI->doesSupportExceptionHandling())
394     DW->EndModule();
395   
396   // If the target wants to know about weak references, print them all.
397   if (MAI->getWeakRefDirective()) {
398     // FIXME: This is not lazy, it would be nice to only print weak references
399     // to stuff that is actually used.  Note that doing so would require targets
400     // to notice uses in operands (due to constant exprs etc).  This should
401     // happen with the MC stuff eventually.
402
403     // Print out module-level global variables here.
404     for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
405          I != E; ++I) {
406       if (!I->hasExternalWeakLinkage()) continue;
407       OutStreamer.EmitSymbolAttribute(GetGlobalValueSymbol(I),
408                                       MCSA_WeakReference);
409     }
410     
411     for (Module::const_iterator I = M.begin(), E = M.end(); I != E; ++I) {
412       if (!I->hasExternalWeakLinkage()) continue;
413       OutStreamer.EmitSymbolAttribute(GetGlobalValueSymbol(I),
414                                       MCSA_WeakReference);
415     }
416   }
417
418   if (MAI->hasSetDirective()) {
419     OutStreamer.AddBlankLine();
420     for (Module::const_alias_iterator I = M.alias_begin(), E = M.alias_end();
421          I != E; ++I) {
422       MCSymbol *Name = GetGlobalValueSymbol(I);
423
424       const GlobalValue *GV = cast<GlobalValue>(I->getAliasedGlobal());
425       MCSymbol *Target = GetGlobalValueSymbol(GV);
426
427       if (I->hasExternalLinkage() || !MAI->getWeakRefDirective())
428         OutStreamer.EmitSymbolAttribute(Name, MCSA_Global);
429       else if (I->hasWeakLinkage())
430         OutStreamer.EmitSymbolAttribute(Name, MCSA_WeakReference);
431       else
432         assert(I->hasLocalLinkage() && "Invalid alias linkage");
433
434       EmitVisibility(Name, I->getVisibility());
435
436       // Emit the directives as assignments aka .set:
437       OutStreamer.EmitAssignment(Name, 
438                                  MCSymbolRefExpr::Create(Target, OutContext));
439     }
440   }
441
442   GCModuleInfo *MI = getAnalysisIfAvailable<GCModuleInfo>();
443   assert(MI && "AsmPrinter didn't require GCModuleInfo?");
444   for (GCModuleInfo::iterator I = MI->end(), E = MI->begin(); I != E; )
445     if (GCMetadataPrinter *MP = GetOrCreateGCPrinter(*--I))
446       MP->finishAssembly(O, *this, *MAI);
447
448   // If we don't have any trampolines, then we don't require stack memory
449   // to be executable. Some targets have a directive to declare this.
450   Function *InitTrampolineIntrinsic = M.getFunction("llvm.init.trampoline");
451   if (!InitTrampolineIntrinsic || InitTrampolineIntrinsic->use_empty())
452     if (MCSection *S = MAI->getNonexecutableStackSection(OutContext))
453       OutStreamer.SwitchSection(S);
454   
455   // Allow the target to emit any magic that it wants at the end of the file,
456   // after everything else has gone out.
457   EmitEndOfAsmFile(M);
458   
459   delete Mang; Mang = 0;
460   DW = 0; MMI = 0;
461   
462   OutStreamer.Finish();
463   return false;
464 }
465
466 void AsmPrinter::SetupMachineFunction(MachineFunction &MF) {
467   this->MF = &MF;
468   // Get the function symbol.
469   CurrentFnSym = GetGlobalValueSymbol(MF.getFunction());
470
471   if (VerboseAsm)
472     LI = &getAnalysis<MachineLoopInfo>();
473 }
474
475 namespace {
476   // SectionCPs - Keep track the alignment, constpool entries per Section.
477   struct SectionCPs {
478     const MCSection *S;
479     unsigned Alignment;
480     SmallVector<unsigned, 4> CPEs;
481     SectionCPs(const MCSection *s, unsigned a) : S(s), Alignment(a) {}
482   };
483 }
484
485 /// EmitConstantPool - Print to the current output stream assembly
486 /// representations of the constants in the constant pool MCP. This is
487 /// used to print out constants which have been "spilled to memory" by
488 /// the code generator.
489 ///
490 void AsmPrinter::EmitConstantPool() {
491   const MachineConstantPool *MCP = MF->getConstantPool();
492   const std::vector<MachineConstantPoolEntry> &CP = MCP->getConstants();
493   if (CP.empty()) return;
494
495   // Calculate sections for constant pool entries. We collect entries to go into
496   // the same section together to reduce amount of section switch statements.
497   SmallVector<SectionCPs, 4> CPSections;
498   for (unsigned i = 0, e = CP.size(); i != e; ++i) {
499     const MachineConstantPoolEntry &CPE = CP[i];
500     unsigned Align = CPE.getAlignment();
501     
502     SectionKind Kind;
503     switch (CPE.getRelocationInfo()) {
504     default: llvm_unreachable("Unknown section kind");
505     case 2: Kind = SectionKind::getReadOnlyWithRel(); break;
506     case 1:
507       Kind = SectionKind::getReadOnlyWithRelLocal();
508       break;
509     case 0:
510     switch (TM.getTargetData()->getTypeAllocSize(CPE.getType())) {
511     case 4:  Kind = SectionKind::getMergeableConst4(); break;
512     case 8:  Kind = SectionKind::getMergeableConst8(); break;
513     case 16: Kind = SectionKind::getMergeableConst16();break;
514     default: Kind = SectionKind::getMergeableConst(); break;
515     }
516     }
517
518     const MCSection *S = getObjFileLowering().getSectionForConstant(Kind);
519     
520     // The number of sections are small, just do a linear search from the
521     // last section to the first.
522     bool Found = false;
523     unsigned SecIdx = CPSections.size();
524     while (SecIdx != 0) {
525       if (CPSections[--SecIdx].S == S) {
526         Found = true;
527         break;
528       }
529     }
530     if (!Found) {
531       SecIdx = CPSections.size();
532       CPSections.push_back(SectionCPs(S, Align));
533     }
534
535     if (Align > CPSections[SecIdx].Alignment)
536       CPSections[SecIdx].Alignment = Align;
537     CPSections[SecIdx].CPEs.push_back(i);
538   }
539
540   // Now print stuff into the calculated sections.
541   for (unsigned i = 0, e = CPSections.size(); i != e; ++i) {
542     OutStreamer.SwitchSection(CPSections[i].S);
543     EmitAlignment(Log2_32(CPSections[i].Alignment));
544
545     unsigned Offset = 0;
546     for (unsigned j = 0, ee = CPSections[i].CPEs.size(); j != ee; ++j) {
547       unsigned CPI = CPSections[i].CPEs[j];
548       MachineConstantPoolEntry CPE = CP[CPI];
549
550       // Emit inter-object padding for alignment.
551       unsigned AlignMask = CPE.getAlignment() - 1;
552       unsigned NewOffset = (Offset + AlignMask) & ~AlignMask;
553       OutStreamer.EmitFill(NewOffset - Offset, 0/*fillval*/, 0/*addrspace*/);
554
555       const Type *Ty = CPE.getType();
556       Offset = NewOffset + TM.getTargetData()->getTypeAllocSize(Ty);
557
558       // Emit the label with a comment on it.
559       if (VerboseAsm) {
560         OutStreamer.GetCommentOS() << "constant pool ";
561         WriteTypeSymbolic(OutStreamer.GetCommentOS(), CPE.getType(),
562                           MF->getFunction()->getParent());
563         OutStreamer.GetCommentOS() << '\n';
564       }
565       OutStreamer.EmitLabel(GetCPISymbol(CPI));
566
567       if (CPE.isMachineConstantPoolEntry())
568         EmitMachineConstantPoolValue(CPE.Val.MachineCPVal);
569       else
570         EmitGlobalConstant(CPE.Val.ConstVal);
571     }
572   }
573 }
574
575 /// EmitJumpTableInfo - Print assembly representations of the jump tables used
576 /// by the current function to the current output stream.  
577 ///
578 void AsmPrinter::EmitJumpTableInfo() {
579   const MachineJumpTableInfo *MJTI = MF->getJumpTableInfo();
580   if (MJTI == 0) return;
581   const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables();
582   if (JT.empty()) return;
583
584   // Pick the directive to use to print the jump table entries, and switch to 
585   // the appropriate section.
586   const Function *F = MF->getFunction();
587   bool JTInDiffSection = false;
588   if (// In PIC mode, we need to emit the jump table to the same section as the
589       // function body itself, otherwise the label differences won't make sense.
590       // FIXME: Need a better predicate for this: what about custom entries?
591       MJTI->getEntryKind() == MachineJumpTableInfo::EK_LabelDifference32 ||
592       // We should also do if the section name is NULL or function is declared
593       // in discardable section
594       // FIXME: this isn't the right predicate, should be based on the MCSection
595       // for the function.
596       F->isWeakForLinker()) {
597     OutStreamer.SwitchSection(getObjFileLowering().SectionForGlobal(F,Mang,TM));
598   } else {
599     // Otherwise, drop it in the readonly section.
600     const MCSection *ReadOnlySection = 
601       getObjFileLowering().getSectionForConstant(SectionKind::getReadOnly());
602     OutStreamer.SwitchSection(ReadOnlySection);
603     JTInDiffSection = true;
604   }
605
606   EmitAlignment(Log2_32(MJTI->getEntryAlignment(*TM.getTargetData())));
607   
608   for (unsigned JTI = 0, e = JT.size(); JTI != e; ++JTI) {
609     const std::vector<MachineBasicBlock*> &JTBBs = JT[JTI].MBBs;
610     
611     // If this jump table was deleted, ignore it. 
612     if (JTBBs.empty()) continue;
613
614     // For the EK_LabelDifference32 entry, if the target supports .set, emit a
615     // .set directive for each unique entry.  This reduces the number of
616     // relocations the assembler will generate for the jump table.
617     if (MJTI->getEntryKind() == MachineJumpTableInfo::EK_LabelDifference32 &&
618         MAI->hasSetDirective()) {
619       SmallPtrSet<const MachineBasicBlock*, 16> EmittedSets;
620       const TargetLowering *TLI = TM.getTargetLowering();
621       const MCExpr *Base = TLI->getPICJumpTableRelocBaseExpr(MF,JTI,OutContext);
622       for (unsigned ii = 0, ee = JTBBs.size(); ii != ee; ++ii) {
623         const MachineBasicBlock *MBB = JTBBs[ii];
624         if (!EmittedSets.insert(MBB)) continue;
625         
626         // .set LJTSet, LBB32-base
627         const MCExpr *LHS =
628           MCSymbolRefExpr::Create(MBB->getSymbol(OutContext), OutContext);
629         OutStreamer.EmitAssignment(GetJTSetSymbol(JTI, MBB->getNumber()),
630                                 MCBinaryExpr::CreateSub(LHS, Base, OutContext));
631       }
632     }          
633     
634     // On some targets (e.g. Darwin) we want to emit two consequtive labels
635     // before each jump table.  The first label is never referenced, but tells
636     // the assembler and linker the extents of the jump table object.  The
637     // second label is actually referenced by the code.
638     if (JTInDiffSection && MAI->getLinkerPrivateGlobalPrefix()[0])
639       // FIXME: This doesn't have to have any specific name, just any randomly
640       // named and numbered 'l' label would work.  Simplify GetJTISymbol.
641       OutStreamer.EmitLabel(GetJTISymbol(JTI, true));
642
643     OutStreamer.EmitLabel(GetJTISymbol(JTI));
644
645     for (unsigned ii = 0, ee = JTBBs.size(); ii != ee; ++ii)
646       EmitJumpTableEntry(MJTI, JTBBs[ii], JTI);
647   }
648 }
649
650 /// EmitJumpTableEntry - Emit a jump table entry for the specified MBB to the
651 /// current stream.
652 void AsmPrinter::EmitJumpTableEntry(const MachineJumpTableInfo *MJTI,
653                                     const MachineBasicBlock *MBB,
654                                     unsigned UID) const {
655   const MCExpr *Value = 0;
656   switch (MJTI->getEntryKind()) {
657   case MachineJumpTableInfo::EK_Custom32:
658     Value = TM.getTargetLowering()->LowerCustomJumpTableEntry(MJTI, MBB, UID,
659                                                               OutContext);
660     break;
661   case MachineJumpTableInfo::EK_BlockAddress:
662     // EK_BlockAddress - Each entry is a plain address of block, e.g.:
663     //     .word LBB123
664     Value = MCSymbolRefExpr::Create(MBB->getSymbol(OutContext), OutContext);
665     break;
666   case MachineJumpTableInfo::EK_GPRel32BlockAddress: {
667     // EK_GPRel32BlockAddress - Each entry is an address of block, encoded
668     // with a relocation as gp-relative, e.g.:
669     //     .gprel32 LBB123
670     MCSymbol *MBBSym = MBB->getSymbol(OutContext);
671     OutStreamer.EmitGPRel32Value(MCSymbolRefExpr::Create(MBBSym, OutContext));
672     return;
673   }
674
675   case MachineJumpTableInfo::EK_LabelDifference32: {
676     // EK_LabelDifference32 - Each entry is the address of the block minus
677     // the address of the jump table.  This is used for PIC jump tables where
678     // gprel32 is not supported.  e.g.:
679     //      .word LBB123 - LJTI1_2
680     // If the .set directive is supported, this is emitted as:
681     //      .set L4_5_set_123, LBB123 - LJTI1_2
682     //      .word L4_5_set_123
683     
684     // If we have emitted set directives for the jump table entries, print 
685     // them rather than the entries themselves.  If we're emitting PIC, then
686     // emit the table entries as differences between two text section labels.
687     if (MAI->hasSetDirective()) {
688       // If we used .set, reference the .set's symbol.
689       Value = MCSymbolRefExpr::Create(GetJTSetSymbol(UID, MBB->getNumber()),
690                                       OutContext);
691       break;
692     }
693     // Otherwise, use the difference as the jump table entry.
694     Value = MCSymbolRefExpr::Create(MBB->getSymbol(OutContext), OutContext);
695     const MCExpr *JTI = MCSymbolRefExpr::Create(GetJTISymbol(UID), OutContext);
696     Value = MCBinaryExpr::CreateSub(Value, JTI, OutContext);
697     break;
698   }
699   }
700   
701   assert(Value && "Unknown entry kind!");
702  
703   unsigned EntrySize = MJTI->getEntrySize(*TM.getTargetData());
704   OutStreamer.EmitValue(Value, EntrySize, /*addrspace*/0);
705 }
706
707
708 /// EmitSpecialLLVMGlobal - Check to see if the specified global is a
709 /// special global used by LLVM.  If so, emit it and return true, otherwise
710 /// do nothing and return false.
711 bool AsmPrinter::EmitSpecialLLVMGlobal(const GlobalVariable *GV) {
712   if (GV->getName() == "llvm.used") {
713     if (MAI->hasNoDeadStrip())    // No need to emit this at all.
714       EmitLLVMUsedList(GV->getInitializer());
715     return true;
716   }
717
718   // Ignore debug and non-emitted data.  This handles llvm.compiler.used.
719   if (GV->getSection() == "llvm.metadata" ||
720       GV->hasAvailableExternallyLinkage())
721     return true;
722   
723   if (!GV->hasAppendingLinkage()) return false;
724
725   assert(GV->hasInitializer() && "Not a special LLVM global!");
726   
727   const TargetData *TD = TM.getTargetData();
728   unsigned Align = Log2_32(TD->getPointerPrefAlignment());
729   if (GV->getName() == "llvm.global_ctors") {
730     OutStreamer.SwitchSection(getObjFileLowering().getStaticCtorSection());
731     EmitAlignment(Align, 0);
732     EmitXXStructorList(GV->getInitializer());
733     
734     if (TM.getRelocationModel() == Reloc::Static &&
735         MAI->hasStaticCtorDtorReferenceInStaticMode()) {
736       StringRef Sym(".constructors_used");
737       OutStreamer.EmitSymbolAttribute(OutContext.GetOrCreateSymbol(Sym),
738                                       MCSA_Reference);
739     }
740     return true;
741   } 
742   
743   if (GV->getName() == "llvm.global_dtors") {
744     OutStreamer.SwitchSection(getObjFileLowering().getStaticDtorSection());
745     EmitAlignment(Align, 0);
746     EmitXXStructorList(GV->getInitializer());
747
748     if (TM.getRelocationModel() == Reloc::Static &&
749         MAI->hasStaticCtorDtorReferenceInStaticMode()) {
750       StringRef Sym(".destructors_used");
751       OutStreamer.EmitSymbolAttribute(OutContext.GetOrCreateSymbol(Sym),
752                                       MCSA_Reference);
753     }
754     return true;
755   }
756   
757   return false;
758 }
759
760 /// EmitLLVMUsedList - For targets that define a MAI::UsedDirective, mark each
761 /// global in the specified llvm.used list for which emitUsedDirectiveFor
762 /// is true, as being used with this directive.
763 void AsmPrinter::EmitLLVMUsedList(Constant *List) {
764   // Should be an array of 'i8*'.
765   ConstantArray *InitList = dyn_cast<ConstantArray>(List);
766   if (InitList == 0) return;
767   
768   for (unsigned i = 0, e = InitList->getNumOperands(); i != e; ++i) {
769     const GlobalValue *GV =
770       dyn_cast<GlobalValue>(InitList->getOperand(i)->stripPointerCasts());
771     if (GV && getObjFileLowering().shouldEmitUsedDirectiveFor(GV, Mang))
772       OutStreamer.EmitSymbolAttribute(GetGlobalValueSymbol(GV),
773                                       MCSA_NoDeadStrip);
774   }
775 }
776
777 /// EmitXXStructorList - Emit the ctor or dtor list.  This just prints out the 
778 /// function pointers, ignoring the init priority.
779 void AsmPrinter::EmitXXStructorList(Constant *List) {
780   // Should be an array of '{ int, void ()* }' structs.  The first value is the
781   // init priority, which we ignore.
782   if (!isa<ConstantArray>(List)) return;
783   ConstantArray *InitList = cast<ConstantArray>(List);
784   for (unsigned i = 0, e = InitList->getNumOperands(); i != e; ++i)
785     if (ConstantStruct *CS = dyn_cast<ConstantStruct>(InitList->getOperand(i))){
786       if (CS->getNumOperands() != 2) return;  // Not array of 2-element structs.
787
788       if (CS->getOperand(1)->isNullValue())
789         return;  // Found a null terminator, exit printing.
790       // Emit the function pointer.
791       EmitGlobalConstant(CS->getOperand(1));
792     }
793 }
794
795 //===--------------------------------------------------------------------===//
796 // Emission and print routines
797 //
798
799 /// EmitInt8 - Emit a byte directive and value.
800 ///
801 void AsmPrinter::EmitInt8(int Value) const {
802   OutStreamer.EmitIntValue(Value, 1, 0/*addrspace*/);
803 }
804
805 /// EmitInt16 - Emit a short directive and value.
806 ///
807 void AsmPrinter::EmitInt16(int Value) const {
808   OutStreamer.EmitIntValue(Value, 2, 0/*addrspace*/);
809 }
810
811 /// EmitInt32 - Emit a long directive and value.
812 ///
813 void AsmPrinter::EmitInt32(int Value) const {
814   OutStreamer.EmitIntValue(Value, 4, 0/*addrspace*/);
815 }
816
817 /// EmitInt64 - Emit a long long directive and value.
818 ///
819 void AsmPrinter::EmitInt64(uint64_t Value) const {
820   OutStreamer.EmitIntValue(Value, 8, 0/*addrspace*/);
821 }
822
823 //===----------------------------------------------------------------------===//
824
825 // EmitAlignment - Emit an alignment directive to the specified power of
826 // two boundary.  For example, if you pass in 3 here, you will get an 8
827 // byte alignment.  If a global value is specified, and if that global has
828 // an explicit alignment requested, it will unconditionally override the
829 // alignment request.  However, if ForcedAlignBits is specified, this value
830 // has final say: the ultimate alignment will be the max of ForcedAlignBits
831 // and the alignment computed with NumBits and the global.
832 //
833 // The algorithm is:
834 //     Align = NumBits;
835 //     if (GV && GV->hasalignment) Align = GV->getalignment();
836 //     Align = std::max(Align, ForcedAlignBits);
837 //
838 void AsmPrinter::EmitAlignment(unsigned NumBits, const GlobalValue *GV,
839                                unsigned ForcedAlignBits,
840                                bool UseFillExpr) const {
841   if (GV && GV->getAlignment())
842     NumBits = Log2_32(GV->getAlignment());
843   NumBits = std::max(NumBits, ForcedAlignBits);
844   
845   if (NumBits == 0) return;   // No need to emit alignment.
846   
847   unsigned FillValue = 0;
848   if (getCurrentSection()->getKind().isText())
849     FillValue = MAI->getTextAlignFillValue();
850   
851   OutStreamer.EmitValueToAlignment(1 << NumBits, FillValue, 1, 0);
852 }
853
854 /// LowerConstant - Lower the specified LLVM Constant to an MCExpr.
855 ///
856 static const MCExpr *LowerConstant(const Constant *CV, AsmPrinter &AP) {
857   MCContext &Ctx = AP.OutContext;
858   
859   if (CV->isNullValue() || isa<UndefValue>(CV))
860     return MCConstantExpr::Create(0, Ctx);
861
862   if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV))
863     return MCConstantExpr::Create(CI->getZExtValue(), Ctx);
864   
865   if (const GlobalValue *GV = dyn_cast<GlobalValue>(CV))
866     return MCSymbolRefExpr::Create(AP.GetGlobalValueSymbol(GV), Ctx);
867   if (const BlockAddress *BA = dyn_cast<BlockAddress>(CV))
868     return MCSymbolRefExpr::Create(AP.GetBlockAddressSymbol(BA), Ctx);
869   
870   const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV);
871   if (CE == 0) {
872     llvm_unreachable("Unknown constant value to lower!");
873     return MCConstantExpr::Create(0, Ctx);
874   }
875   
876   switch (CE->getOpcode()) {
877   case Instruction::ZExt:
878   case Instruction::SExt:
879   case Instruction::FPTrunc:
880   case Instruction::FPExt:
881   case Instruction::UIToFP:
882   case Instruction::SIToFP:
883   case Instruction::FPToUI:
884   case Instruction::FPToSI:
885   default: llvm_unreachable("FIXME: Don't support this constant cast expr");
886   case Instruction::GetElementPtr: {
887     const TargetData &TD = *AP.TM.getTargetData();
888     // Generate a symbolic expression for the byte address
889     const Constant *PtrVal = CE->getOperand(0);
890     SmallVector<Value*, 8> IdxVec(CE->op_begin()+1, CE->op_end());
891     int64_t Offset = TD.getIndexedOffset(PtrVal->getType(), &IdxVec[0],
892                                          IdxVec.size());
893     
894     const MCExpr *Base = LowerConstant(CE->getOperand(0), AP);
895     if (Offset == 0)
896       return Base;
897     
898     // Truncate/sext the offset to the pointer size.
899     if (TD.getPointerSizeInBits() != 64) {
900       int SExtAmount = 64-TD.getPointerSizeInBits();
901       Offset = (Offset << SExtAmount) >> SExtAmount;
902     }
903     
904     return MCBinaryExpr::CreateAdd(Base, MCConstantExpr::Create(Offset, Ctx),
905                                    Ctx);
906   }
907       
908   case Instruction::Trunc:
909     // We emit the value and depend on the assembler to truncate the generated
910     // expression properly.  This is important for differences between
911     // blockaddress labels.  Since the two labels are in the same function, it
912     // is reasonable to treat their delta as a 32-bit value.
913     // FALL THROUGH.
914   case Instruction::BitCast:
915     return LowerConstant(CE->getOperand(0), AP);
916
917   case Instruction::IntToPtr: {
918     const TargetData &TD = *AP.TM.getTargetData();
919     // Handle casts to pointers by changing them into casts to the appropriate
920     // integer type.  This promotes constant folding and simplifies this code.
921     Constant *Op = CE->getOperand(0);
922     Op = ConstantExpr::getIntegerCast(Op, TD.getIntPtrType(CV->getContext()),
923                                       false/*ZExt*/);
924     return LowerConstant(Op, AP);
925   }
926     
927   case Instruction::PtrToInt: {
928     const TargetData &TD = *AP.TM.getTargetData();
929     // Support only foldable casts to/from pointers that can be eliminated by
930     // changing the pointer to the appropriately sized integer type.
931     Constant *Op = CE->getOperand(0);
932     const Type *Ty = CE->getType();
933
934     const MCExpr *OpExpr = LowerConstant(Op, AP);
935
936     // We can emit the pointer value into this slot if the slot is an
937     // integer slot equal to the size of the pointer.
938     if (TD.getTypeAllocSize(Ty) == TD.getTypeAllocSize(Op->getType()))
939       return OpExpr;
940
941     // Otherwise the pointer is smaller than the resultant integer, mask off
942     // the high bits so we are sure to get a proper truncation if the input is
943     // a constant expr.
944     unsigned InBits = TD.getTypeAllocSizeInBits(Op->getType());
945     const MCExpr *MaskExpr = MCConstantExpr::Create(~0ULL >> (64-InBits), Ctx);
946     return MCBinaryExpr::CreateAnd(OpExpr, MaskExpr, Ctx);
947   }
948       
949   case Instruction::Add:
950   case Instruction::Sub:
951   case Instruction::And:
952   case Instruction::Or:
953   case Instruction::Xor: {
954     const MCExpr *LHS = LowerConstant(CE->getOperand(0), AP);
955     const MCExpr *RHS = LowerConstant(CE->getOperand(1), AP);
956     switch (CE->getOpcode()) {
957     default: llvm_unreachable("Unknown binary operator constant cast expr");
958     case Instruction::Add: return MCBinaryExpr::CreateAdd(LHS, RHS, Ctx);
959     case Instruction::Sub: return MCBinaryExpr::CreateSub(LHS, RHS, Ctx);
960     case Instruction::And: return MCBinaryExpr::CreateAnd(LHS, RHS, Ctx);
961     case Instruction::Or:  return MCBinaryExpr::CreateOr (LHS, RHS, Ctx);
962     case Instruction::Xor: return MCBinaryExpr::CreateXor(LHS, RHS, Ctx);
963     }
964   }
965   }
966 }
967
968 static void EmitGlobalConstantArray(const ConstantArray *CA, unsigned AddrSpace,
969                                     AsmPrinter &AP) {
970   if (AddrSpace != 0 || !CA->isString()) {
971     // Not a string.  Print the values in successive locations
972     for (unsigned i = 0, e = CA->getNumOperands(); i != e; ++i)
973       AP.EmitGlobalConstant(CA->getOperand(i), AddrSpace);
974     return;
975   }
976   
977   // Otherwise, it can be emitted as .ascii.
978   SmallVector<char, 128> TmpVec;
979   TmpVec.reserve(CA->getNumOperands());
980   for (unsigned i = 0, e = CA->getNumOperands(); i != e; ++i)
981     TmpVec.push_back(cast<ConstantInt>(CA->getOperand(i))->getZExtValue());
982
983   AP.OutStreamer.EmitBytes(StringRef(TmpVec.data(), TmpVec.size()), AddrSpace);
984 }
985
986 static void EmitGlobalConstantVector(const ConstantVector *CV,
987                                      unsigned AddrSpace, AsmPrinter &AP) {
988   for (unsigned i = 0, e = CV->getType()->getNumElements(); i != e; ++i)
989     AP.EmitGlobalConstant(CV->getOperand(i), AddrSpace);
990 }
991
992 static void EmitGlobalConstantStruct(const ConstantStruct *CS,
993                                      unsigned AddrSpace, AsmPrinter &AP) {
994   // Print the fields in successive locations. Pad to align if needed!
995   const TargetData *TD = AP.TM.getTargetData();
996   unsigned Size = TD->getTypeAllocSize(CS->getType());
997   const StructLayout *Layout = TD->getStructLayout(CS->getType());
998   uint64_t SizeSoFar = 0;
999   for (unsigned i = 0, e = CS->getNumOperands(); i != e; ++i) {
1000     const Constant *Field = CS->getOperand(i);
1001
1002     // Check if padding is needed and insert one or more 0s.
1003     uint64_t FieldSize = TD->getTypeAllocSize(Field->getType());
1004     uint64_t PadSize = ((i == e-1 ? Size : Layout->getElementOffset(i+1))
1005                         - Layout->getElementOffset(i)) - FieldSize;
1006     SizeSoFar += FieldSize + PadSize;
1007
1008     // Now print the actual field value.
1009     AP.EmitGlobalConstant(Field, AddrSpace);
1010
1011     // Insert padding - this may include padding to increase the size of the
1012     // current field up to the ABI size (if the struct is not packed) as well
1013     // as padding to ensure that the next field starts at the right offset.
1014     AP.OutStreamer.EmitZeros(PadSize, AddrSpace);
1015   }
1016   assert(SizeSoFar == Layout->getSizeInBytes() &&
1017          "Layout of constant struct may be incorrect!");
1018 }
1019
1020 static void EmitGlobalConstantFP(const ConstantFP *CFP, unsigned AddrSpace,
1021                                  AsmPrinter &AP) {
1022   // FP Constants are printed as integer constants to avoid losing
1023   // precision.
1024   if (CFP->getType()->isDoubleTy()) {
1025     if (AP.VerboseAsm) {
1026       double Val = CFP->getValueAPF().convertToDouble();
1027       AP.OutStreamer.GetCommentOS() << "double " << Val << '\n';
1028     }
1029
1030     uint64_t Val = CFP->getValueAPF().bitcastToAPInt().getZExtValue();
1031     AP.OutStreamer.EmitIntValue(Val, 8, AddrSpace);
1032     return;
1033   }
1034   
1035   if (CFP->getType()->isFloatTy()) {
1036     if (AP.VerboseAsm) {
1037       float Val = CFP->getValueAPF().convertToFloat();
1038       AP.OutStreamer.GetCommentOS() << "float " << Val << '\n';
1039     }
1040     uint64_t Val = CFP->getValueAPF().bitcastToAPInt().getZExtValue();
1041     AP.OutStreamer.EmitIntValue(Val, 4, AddrSpace);
1042     return;
1043   }
1044   
1045   if (CFP->getType()->isX86_FP80Ty()) {
1046     // all long double variants are printed as hex
1047     // api needed to prevent premature destruction
1048     APInt API = CFP->getValueAPF().bitcastToAPInt();
1049     const uint64_t *p = API.getRawData();
1050     if (AP.VerboseAsm) {
1051       // Convert to double so we can print the approximate val as a comment.
1052       APFloat DoubleVal = CFP->getValueAPF();
1053       bool ignored;
1054       DoubleVal.convert(APFloat::IEEEdouble, APFloat::rmNearestTiesToEven,
1055                         &ignored);
1056       AP.OutStreamer.GetCommentOS() << "x86_fp80 ~= "
1057         << DoubleVal.convertToDouble() << '\n';
1058     }
1059     
1060     if (AP.TM.getTargetData()->isBigEndian()) {
1061       AP.OutStreamer.EmitIntValue(p[1], 2, AddrSpace);
1062       AP.OutStreamer.EmitIntValue(p[0], 8, AddrSpace);
1063     } else {
1064       AP.OutStreamer.EmitIntValue(p[0], 8, AddrSpace);
1065       AP.OutStreamer.EmitIntValue(p[1], 2, AddrSpace);
1066     }
1067     
1068     // Emit the tail padding for the long double.
1069     const TargetData &TD = *AP.TM.getTargetData();
1070     AP.OutStreamer.EmitZeros(TD.getTypeAllocSize(CFP->getType()) -
1071                              TD.getTypeStoreSize(CFP->getType()), AddrSpace);
1072     return;
1073   }
1074   
1075   assert(CFP->getType()->isPPC_FP128Ty() &&
1076          "Floating point constant type not handled");
1077   // All long double variants are printed as hex api needed to prevent
1078   // premature destruction.
1079   APInt API = CFP->getValueAPF().bitcastToAPInt();
1080   const uint64_t *p = API.getRawData();
1081   if (AP.TM.getTargetData()->isBigEndian()) {
1082     AP.OutStreamer.EmitIntValue(p[0], 8, AddrSpace);
1083     AP.OutStreamer.EmitIntValue(p[1], 8, AddrSpace);
1084   } else {
1085     AP.OutStreamer.EmitIntValue(p[1], 8, AddrSpace);
1086     AP.OutStreamer.EmitIntValue(p[0], 8, AddrSpace);
1087   }
1088 }
1089
1090 static void EmitGlobalConstantLargeInt(const ConstantInt *CI,
1091                                        unsigned AddrSpace, AsmPrinter &AP) {
1092   const TargetData *TD = AP.TM.getTargetData();
1093   unsigned BitWidth = CI->getBitWidth();
1094   assert((BitWidth & 63) == 0 && "only support multiples of 64-bits");
1095
1096   // We don't expect assemblers to support integer data directives
1097   // for more than 64 bits, so we emit the data in at most 64-bit
1098   // quantities at a time.
1099   const uint64_t *RawData = CI->getValue().getRawData();
1100   for (unsigned i = 0, e = BitWidth / 64; i != e; ++i) {
1101     uint64_t Val = TD->isBigEndian() ? RawData[e - i - 1] : RawData[i];
1102     AP.OutStreamer.EmitIntValue(Val, 8, AddrSpace);
1103   }
1104 }
1105
1106 /// EmitGlobalConstant - Print a general LLVM constant to the .s file.
1107 void AsmPrinter::EmitGlobalConstant(const Constant *CV, unsigned AddrSpace) {
1108   if (isa<ConstantAggregateZero>(CV) || isa<UndefValue>(CV)) {
1109     uint64_t Size = TM.getTargetData()->getTypeAllocSize(CV->getType());
1110     return OutStreamer.EmitZeros(Size, AddrSpace);
1111   }
1112
1113   if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV)) {
1114     unsigned Size = TM.getTargetData()->getTypeAllocSize(CV->getType());
1115     switch (Size) {
1116     case 1:
1117     case 2:
1118     case 4:
1119     case 8:
1120       if (VerboseAsm)
1121         OutStreamer.GetCommentOS() << format("0x%llx\n", CI->getZExtValue());
1122       OutStreamer.EmitIntValue(CI->getZExtValue(), Size, AddrSpace);
1123       return;
1124     default:
1125       EmitGlobalConstantLargeInt(CI, AddrSpace, *this);
1126       return;
1127     }
1128   }
1129   
1130   if (const ConstantArray *CVA = dyn_cast<ConstantArray>(CV))
1131     return EmitGlobalConstantArray(CVA, AddrSpace, *this);
1132   
1133   if (const ConstantStruct *CVS = dyn_cast<ConstantStruct>(CV))
1134     return EmitGlobalConstantStruct(CVS, AddrSpace, *this);
1135
1136   if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CV))
1137     return EmitGlobalConstantFP(CFP, AddrSpace, *this);
1138   
1139   if (const ConstantVector *V = dyn_cast<ConstantVector>(CV))
1140     return EmitGlobalConstantVector(V, AddrSpace, *this);
1141
1142   if (isa<ConstantPointerNull>(CV)) {
1143     unsigned Size = TM.getTargetData()->getTypeAllocSize(CV->getType());
1144     OutStreamer.EmitIntValue(0, Size, AddrSpace);
1145     return;
1146   }
1147   
1148   // Otherwise, it must be a ConstantExpr.  Lower it to an MCExpr, then emit it
1149   // thread the streamer with EmitValue.
1150   OutStreamer.EmitValue(LowerConstant(CV, *this),
1151                         TM.getTargetData()->getTypeAllocSize(CV->getType()),
1152                         AddrSpace);
1153 }
1154
1155 void AsmPrinter::EmitMachineConstantPoolValue(MachineConstantPoolValue *MCPV) {
1156   // Target doesn't support this yet!
1157   llvm_unreachable("Target does not support EmitMachineConstantPoolValue");
1158 }
1159
1160 /// PrintSpecial - Print information related to the specified machine instr
1161 /// that is independent of the operand, and may be independent of the instr
1162 /// itself.  This can be useful for portably encoding the comment character
1163 /// or other bits of target-specific knowledge into the asmstrings.  The
1164 /// syntax used is ${:comment}.  Targets can override this to add support
1165 /// for their own strange codes.
1166 void AsmPrinter::PrintSpecial(const MachineInstr *MI, const char *Code) const {
1167   if (!strcmp(Code, "private")) {
1168     O << MAI->getPrivateGlobalPrefix();
1169   } else if (!strcmp(Code, "comment")) {
1170     if (VerboseAsm)
1171       O << MAI->getCommentString();
1172   } else if (!strcmp(Code, "uid")) {
1173     // Comparing the address of MI isn't sufficient, because machineinstrs may
1174     // be allocated to the same address across functions.
1175     const Function *ThisF = MI->getParent()->getParent()->getFunction();
1176     
1177     // If this is a new LastFn instruction, bump the counter.
1178     if (LastMI != MI || LastFn != ThisF) {
1179       ++Counter;
1180       LastMI = MI;
1181       LastFn = ThisF;
1182     }
1183     O << Counter;
1184   } else {
1185     std::string msg;
1186     raw_string_ostream Msg(msg);
1187     Msg << "Unknown special formatter '" << Code
1188          << "' for machine instr: " << *MI;
1189     llvm_report_error(Msg.str());
1190   }    
1191 }
1192
1193 /// processDebugLoc - Processes the debug information of each machine
1194 /// instruction's DebugLoc.
1195 void AsmPrinter::processDebugLoc(const MachineInstr *MI, 
1196                                  bool BeforePrintingInsn) {
1197   if (!MAI || !DW || !MAI->doesSupportDebugInformation()
1198       || !DW->ShouldEmitDwarfDebug())
1199     return;
1200   DebugLoc DL = MI->getDebugLoc();
1201   if (DL.isUnknown())
1202     return;
1203   DILocation CurDLT = MF->getDILocation(DL);
1204   if (CurDLT.getScope().isNull())
1205     return;
1206
1207   if (!BeforePrintingInsn) {
1208     // After printing instruction
1209     DW->EndScope(MI);
1210   } else if (CurDLT.getNode() != PrevDLT) {
1211     unsigned L = DW->RecordSourceLine(CurDLT.getLineNumber(), 
1212                                       CurDLT.getColumnNumber(),
1213                                       CurDLT.getScope().getNode());
1214     printLabel(L);
1215     O << '\n';
1216     DW->BeginScope(MI, L);
1217     PrevDLT = CurDLT.getNode();
1218   }
1219 }
1220
1221
1222 /// printInlineAsm - This method formats and prints the specified machine
1223 /// instruction that is an inline asm.
1224 void AsmPrinter::printInlineAsm(const MachineInstr *MI) const {
1225   unsigned NumOperands = MI->getNumOperands();
1226   
1227   // Count the number of register definitions.
1228   unsigned NumDefs = 0;
1229   for (; MI->getOperand(NumDefs).isReg() && MI->getOperand(NumDefs).isDef();
1230        ++NumDefs)
1231     assert(NumDefs != NumOperands-1 && "No asm string?");
1232   
1233   assert(MI->getOperand(NumDefs).isSymbol() && "No asm string?");
1234
1235   // Disassemble the AsmStr, printing out the literal pieces, the operands, etc.
1236   const char *AsmStr = MI->getOperand(NumDefs).getSymbolName();
1237
1238   O << '\t';
1239
1240   // If this asmstr is empty, just print the #APP/#NOAPP markers.
1241   // These are useful to see where empty asm's wound up.
1242   if (AsmStr[0] == 0) {
1243     O << MAI->getCommentString() << MAI->getInlineAsmStart() << "\n\t";
1244     O << MAI->getCommentString() << MAI->getInlineAsmEnd() << '\n';
1245     return;
1246   }
1247   
1248   O << MAI->getCommentString() << MAI->getInlineAsmStart() << "\n\t";
1249
1250   // The variant of the current asmprinter.
1251   int AsmPrinterVariant = MAI->getAssemblerDialect();
1252
1253   int CurVariant = -1;            // The number of the {.|.|.} region we are in.
1254   const char *LastEmitted = AsmStr; // One past the last character emitted.
1255   
1256   while (*LastEmitted) {
1257     switch (*LastEmitted) {
1258     default: {
1259       // Not a special case, emit the string section literally.
1260       const char *LiteralEnd = LastEmitted+1;
1261       while (*LiteralEnd && *LiteralEnd != '{' && *LiteralEnd != '|' &&
1262              *LiteralEnd != '}' && *LiteralEnd != '$' && *LiteralEnd != '\n')
1263         ++LiteralEnd;
1264       if (CurVariant == -1 || CurVariant == AsmPrinterVariant)
1265         O.write(LastEmitted, LiteralEnd-LastEmitted);
1266       LastEmitted = LiteralEnd;
1267       break;
1268     }
1269     case '\n':
1270       ++LastEmitted;   // Consume newline character.
1271       O << '\n';       // Indent code with newline.
1272       break;
1273     case '$': {
1274       ++LastEmitted;   // Consume '$' character.
1275       bool Done = true;
1276
1277       // Handle escapes.
1278       switch (*LastEmitted) {
1279       default: Done = false; break;
1280       case '$':     // $$ -> $
1281         if (CurVariant == -1 || CurVariant == AsmPrinterVariant)
1282           O << '$';
1283         ++LastEmitted;  // Consume second '$' character.
1284         break;
1285       case '(':             // $( -> same as GCC's { character.
1286         ++LastEmitted;      // Consume '(' character.
1287         if (CurVariant != -1) {
1288           llvm_report_error("Nested variants found in inline asm string: '"
1289                             + std::string(AsmStr) + "'");
1290         }
1291         CurVariant = 0;     // We're in the first variant now.
1292         break;
1293       case '|':
1294         ++LastEmitted;  // consume '|' character.
1295         if (CurVariant == -1)
1296           O << '|';       // this is gcc's behavior for | outside a variant
1297         else
1298           ++CurVariant;   // We're in the next variant.
1299         break;
1300       case ')':         // $) -> same as GCC's } char.
1301         ++LastEmitted;  // consume ')' character.
1302         if (CurVariant == -1)
1303           O << '}';     // this is gcc's behavior for } outside a variant
1304         else 
1305           CurVariant = -1;
1306         break;
1307       }
1308       if (Done) break;
1309       
1310       bool HasCurlyBraces = false;
1311       if (*LastEmitted == '{') {     // ${variable}
1312         ++LastEmitted;               // Consume '{' character.
1313         HasCurlyBraces = true;
1314       }
1315       
1316       // If we have ${:foo}, then this is not a real operand reference, it is a
1317       // "magic" string reference, just like in .td files.  Arrange to call
1318       // PrintSpecial.
1319       if (HasCurlyBraces && *LastEmitted == ':') {
1320         ++LastEmitted;
1321         const char *StrStart = LastEmitted;
1322         const char *StrEnd = strchr(StrStart, '}');
1323         if (StrEnd == 0) {
1324           llvm_report_error("Unterminated ${:foo} operand in inline asm string: '" 
1325                             + std::string(AsmStr) + "'");
1326         }
1327         
1328         std::string Val(StrStart, StrEnd);
1329         PrintSpecial(MI, Val.c_str());
1330         LastEmitted = StrEnd+1;
1331         break;
1332       }
1333             
1334       const char *IDStart = LastEmitted;
1335       char *IDEnd;
1336       errno = 0;
1337       long Val = strtol(IDStart, &IDEnd, 10); // We only accept numbers for IDs.
1338       if (!isdigit(*IDStart) || (Val == 0 && errno == EINVAL)) {
1339         llvm_report_error("Bad $ operand number in inline asm string: '" 
1340                           + std::string(AsmStr) + "'");
1341       }
1342       LastEmitted = IDEnd;
1343       
1344       char Modifier[2] = { 0, 0 };
1345       
1346       if (HasCurlyBraces) {
1347         // If we have curly braces, check for a modifier character.  This
1348         // supports syntax like ${0:u}, which correspond to "%u0" in GCC asm.
1349         if (*LastEmitted == ':') {
1350           ++LastEmitted;    // Consume ':' character.
1351           if (*LastEmitted == 0) {
1352             llvm_report_error("Bad ${:} expression in inline asm string: '" 
1353                               + std::string(AsmStr) + "'");
1354           }
1355           
1356           Modifier[0] = *LastEmitted;
1357           ++LastEmitted;    // Consume modifier character.
1358         }
1359         
1360         if (*LastEmitted != '}') {
1361           llvm_report_error("Bad ${} expression in inline asm string: '" 
1362                             + std::string(AsmStr) + "'");
1363         }
1364         ++LastEmitted;    // Consume '}' character.
1365       }
1366       
1367       if ((unsigned)Val >= NumOperands-1) {
1368         llvm_report_error("Invalid $ operand number in inline asm string: '" 
1369                           + std::string(AsmStr) + "'");
1370       }
1371       
1372       // Okay, we finally have a value number.  Ask the target to print this
1373       // operand!
1374       if (CurVariant == -1 || CurVariant == AsmPrinterVariant) {
1375         unsigned OpNo = 1;
1376
1377         bool Error = false;
1378
1379         // Scan to find the machine operand number for the operand.
1380         for (; Val; --Val) {
1381           if (OpNo >= MI->getNumOperands()) break;
1382           unsigned OpFlags = MI->getOperand(OpNo).getImm();
1383           OpNo += InlineAsm::getNumOperandRegisters(OpFlags) + 1;
1384         }
1385
1386         if (OpNo >= MI->getNumOperands()) {
1387           Error = true;
1388         } else {
1389           unsigned OpFlags = MI->getOperand(OpNo).getImm();
1390           ++OpNo;  // Skip over the ID number.
1391
1392           if (Modifier[0] == 'l')  // labels are target independent
1393             O << *MI->getOperand(OpNo).getMBB()->getSymbol(OutContext);
1394           else {
1395             AsmPrinter *AP = const_cast<AsmPrinter*>(this);
1396             if ((OpFlags & 7) == 4) {
1397               Error = AP->PrintAsmMemoryOperand(MI, OpNo, AsmPrinterVariant,
1398                                                 Modifier[0] ? Modifier : 0);
1399             } else {
1400               Error = AP->PrintAsmOperand(MI, OpNo, AsmPrinterVariant,
1401                                           Modifier[0] ? Modifier : 0);
1402             }
1403           }
1404         }
1405         if (Error) {
1406           std::string msg;
1407           raw_string_ostream Msg(msg);
1408           Msg << "Invalid operand found in inline asm: '" << AsmStr << "'\n";
1409           MI->print(Msg);
1410           llvm_report_error(Msg.str());
1411         }
1412       }
1413       break;
1414     }
1415     }
1416   }
1417   O << "\n\t" << MAI->getCommentString() << MAI->getInlineAsmEnd();
1418 }
1419
1420 /// printImplicitDef - This method prints the specified machine instruction
1421 /// that is an implicit def.
1422 void AsmPrinter::printImplicitDef(const MachineInstr *MI) const {
1423   if (!VerboseAsm) return;
1424   O.PadToColumn(MAI->getCommentColumn());
1425   O << MAI->getCommentString() << " implicit-def: "
1426     << TRI->getName(MI->getOperand(0).getReg());
1427 }
1428
1429 void AsmPrinter::printKill(const MachineInstr *MI) const {
1430   if (!VerboseAsm) return;
1431   O.PadToColumn(MAI->getCommentColumn());
1432   O << MAI->getCommentString() << " kill:";
1433   for (unsigned n = 0, e = MI->getNumOperands(); n != e; ++n) {
1434     const MachineOperand &op = MI->getOperand(n);
1435     assert(op.isReg() && "KILL instruction must have only register operands");
1436     O << ' ' << TRI->getName(op.getReg()) << (op.isDef() ? "<def>" : "<kill>");
1437   }
1438 }
1439
1440 /// printLabel - This method prints a local label used by debug and
1441 /// exception handling tables.
1442 void AsmPrinter::printLabel(const MachineInstr *MI) const {
1443   printLabel(MI->getOperand(0).getImm());
1444 }
1445
1446 void AsmPrinter::printLabel(unsigned Id) const {
1447   O << MAI->getPrivateGlobalPrefix() << "label" << Id << ':';
1448 }
1449
1450 /// PrintAsmOperand - Print the specified operand of MI, an INLINEASM
1451 /// instruction, using the specified assembler variant.  Targets should
1452 /// override this to format as appropriate.
1453 bool AsmPrinter::PrintAsmOperand(const MachineInstr *MI, unsigned OpNo,
1454                                  unsigned AsmVariant, const char *ExtraCode) {
1455   // Target doesn't support this yet!
1456   return true;
1457 }
1458
1459 bool AsmPrinter::PrintAsmMemoryOperand(const MachineInstr *MI, unsigned OpNo,
1460                                        unsigned AsmVariant,
1461                                        const char *ExtraCode) {
1462   // Target doesn't support this yet!
1463   return true;
1464 }
1465
1466 MCSymbol *AsmPrinter::GetBlockAddressSymbol(const BlockAddress *BA,
1467                                             const char *Suffix) const {
1468   return GetBlockAddressSymbol(BA->getFunction(), BA->getBasicBlock(), Suffix);
1469 }
1470
1471 MCSymbol *AsmPrinter::GetBlockAddressSymbol(const Function *F,
1472                                             const BasicBlock *BB,
1473                                             const char *Suffix) const {
1474   assert(BB->hasName() &&
1475          "Address of anonymous basic block not supported yet!");
1476
1477   // This code must use the function name itself, and not the function number,
1478   // since it must be possible to generate the label name from within other
1479   // functions.
1480   SmallString<60> FnName;
1481   Mang->getNameWithPrefix(FnName, F, false);
1482
1483   // FIXME: THIS IS BROKEN IF THE LLVM BASIC BLOCK DOESN'T HAVE A NAME!
1484   SmallString<60> NameResult;
1485   Mang->getNameWithPrefix(NameResult,
1486                           StringRef("BA") + Twine((unsigned)FnName.size()) + 
1487                           "_" + FnName.str() + "_" + BB->getName() + Suffix, 
1488                           Mangler::Private);
1489
1490   return OutContext.GetOrCreateSymbol(NameResult.str());
1491 }
1492
1493 /// GetCPISymbol - Return the symbol for the specified constant pool entry.
1494 MCSymbol *AsmPrinter::GetCPISymbol(unsigned CPID) const {
1495   SmallString<60> Name;
1496   raw_svector_ostream(Name) << MAI->getPrivateGlobalPrefix() << "CPI"
1497     << getFunctionNumber() << '_' << CPID;
1498   return OutContext.GetOrCreateSymbol(Name.str());
1499 }
1500
1501 /// GetJTISymbol - Return the symbol for the specified jump table entry.
1502 MCSymbol *AsmPrinter::GetJTISymbol(unsigned JTID, bool isLinkerPrivate) const {
1503   return MF->getJTISymbol(JTID, OutContext, isLinkerPrivate);
1504 }
1505
1506 /// GetJTSetSymbol - Return the symbol for the specified jump table .set
1507 /// FIXME: privatize to AsmPrinter.
1508 MCSymbol *AsmPrinter::GetJTSetSymbol(unsigned UID, unsigned MBBID) const {
1509   SmallString<60> Name;
1510   raw_svector_ostream(Name) << MAI->getPrivateGlobalPrefix()
1511     << getFunctionNumber() << '_' << UID << "_set_" << MBBID;
1512   return OutContext.GetOrCreateSymbol(Name.str());
1513 }
1514
1515 /// GetGlobalValueSymbol - Return the MCSymbol for the specified global
1516 /// value.
1517 MCSymbol *AsmPrinter::GetGlobalValueSymbol(const GlobalValue *GV) const {
1518   SmallString<60> NameStr;
1519   Mang->getNameWithPrefix(NameStr, GV, false);
1520   return OutContext.GetOrCreateSymbol(NameStr.str());
1521 }
1522
1523 /// GetSymbolWithGlobalValueBase - Return the MCSymbol for a symbol with
1524 /// global value name as its base, with the specified suffix, and where the
1525 /// symbol is forced to have private linkage if ForcePrivate is true.
1526 MCSymbol *AsmPrinter::GetSymbolWithGlobalValueBase(const GlobalValue *GV,
1527                                                    StringRef Suffix,
1528                                                    bool ForcePrivate) const {
1529   SmallString<60> NameStr;
1530   Mang->getNameWithPrefix(NameStr, GV, ForcePrivate);
1531   NameStr.append(Suffix.begin(), Suffix.end());
1532   return OutContext.GetOrCreateSymbol(NameStr.str());
1533 }
1534
1535 /// GetExternalSymbolSymbol - Return the MCSymbol for the specified
1536 /// ExternalSymbol.
1537 MCSymbol *AsmPrinter::GetExternalSymbolSymbol(StringRef Sym) const {
1538   SmallString<60> NameStr;
1539   Mang->getNameWithPrefix(NameStr, Sym);
1540   return OutContext.GetOrCreateSymbol(NameStr.str());
1541 }  
1542
1543
1544
1545 /// PrintParentLoopComment - Print comments about parent loops of this one.
1546 static void PrintParentLoopComment(raw_ostream &OS, const MachineLoop *Loop,
1547                                    unsigned FunctionNumber) {
1548   if (Loop == 0) return;
1549   PrintParentLoopComment(OS, Loop->getParentLoop(), FunctionNumber);
1550   OS.indent(Loop->getLoopDepth()*2)
1551     << "Parent Loop BB" << FunctionNumber << "_"
1552     << Loop->getHeader()->getNumber()
1553     << " Depth=" << Loop->getLoopDepth() << '\n';
1554 }
1555
1556
1557 /// PrintChildLoopComment - Print comments about child loops within
1558 /// the loop for this basic block, with nesting.
1559 static void PrintChildLoopComment(raw_ostream &OS, const MachineLoop *Loop,
1560                                   unsigned FunctionNumber) {
1561   // Add child loop information
1562   for (MachineLoop::iterator CL = Loop->begin(), E = Loop->end();CL != E; ++CL){
1563     OS.indent((*CL)->getLoopDepth()*2)
1564       << "Child Loop BB" << FunctionNumber << "_"
1565       << (*CL)->getHeader()->getNumber() << " Depth " << (*CL)->getLoopDepth()
1566       << '\n';
1567     PrintChildLoopComment(OS, *CL, FunctionNumber);
1568   }
1569 }
1570
1571 /// EmitComments - Pretty-print comments for basic blocks.
1572 static void PrintBasicBlockLoopComments(const MachineBasicBlock &MBB,
1573                                         const MachineLoopInfo *LI,
1574                                         const AsmPrinter &AP) {
1575   // Add loop depth information
1576   const MachineLoop *Loop = LI->getLoopFor(&MBB);
1577   if (Loop == 0) return;
1578   
1579   MachineBasicBlock *Header = Loop->getHeader();
1580   assert(Header && "No header for loop");
1581   
1582   // If this block is not a loop header, just print out what is the loop header
1583   // and return.
1584   if (Header != &MBB) {
1585     AP.OutStreamer.AddComment("  in Loop: Header=BB" +
1586                               Twine(AP.getFunctionNumber())+"_" +
1587                               Twine(Loop->getHeader()->getNumber())+
1588                               " Depth="+Twine(Loop->getLoopDepth()));
1589     return;
1590   }
1591   
1592   // Otherwise, it is a loop header.  Print out information about child and
1593   // parent loops.
1594   raw_ostream &OS = AP.OutStreamer.GetCommentOS();
1595   
1596   PrintParentLoopComment(OS, Loop->getParentLoop(), AP.getFunctionNumber()); 
1597   
1598   OS << "=>";
1599   OS.indent(Loop->getLoopDepth()*2-2);
1600   
1601   OS << "This ";
1602   if (Loop->empty())
1603     OS << "Inner ";
1604   OS << "Loop Header: Depth=" + Twine(Loop->getLoopDepth()) << '\n';
1605   
1606   PrintChildLoopComment(OS, Loop, AP.getFunctionNumber());
1607 }
1608
1609
1610 /// EmitBasicBlockStart - This method prints the label for the specified
1611 /// MachineBasicBlock, an alignment (if present) and a comment describing
1612 /// it if appropriate.
1613 void AsmPrinter::EmitBasicBlockStart(const MachineBasicBlock *MBB) const {
1614   // Emit an alignment directive for this block, if needed.
1615   if (unsigned Align = MBB->getAlignment())
1616     EmitAlignment(Log2_32(Align));
1617
1618   // If the block has its address taken, emit a special label to satisfy
1619   // references to the block. This is done so that we don't need to
1620   // remember the number of this label, and so that we can make
1621   // forward references to labels without knowing what their numbers
1622   // will be.
1623   if (MBB->hasAddressTaken()) {
1624     const BasicBlock *BB = MBB->getBasicBlock();
1625     if (VerboseAsm)
1626       OutStreamer.AddComment("Address Taken");
1627     OutStreamer.EmitLabel(GetBlockAddressSymbol(BB->getParent(), BB));
1628   }
1629
1630   // Print the main label for the block.
1631   if (MBB->pred_empty() || MBB->isOnlyReachableByFallthrough()) {
1632     if (VerboseAsm) {
1633       // NOTE: Want this comment at start of line.
1634       O << MAI->getCommentString() << " BB#" << MBB->getNumber() << ':';
1635       if (const BasicBlock *BB = MBB->getBasicBlock())
1636         if (BB->hasName())
1637           OutStreamer.AddComment("%" + BB->getName());
1638       
1639       PrintBasicBlockLoopComments(*MBB, LI, *this);
1640       OutStreamer.AddBlankLine();
1641     }
1642   } else {
1643     if (VerboseAsm) {
1644       if (const BasicBlock *BB = MBB->getBasicBlock())
1645         if (BB->hasName())
1646           OutStreamer.AddComment("%" + BB->getName());
1647       PrintBasicBlockLoopComments(*MBB, LI, *this);
1648     }
1649
1650     OutStreamer.EmitLabel(MBB->getSymbol(OutContext));
1651   }
1652 }
1653
1654 void AsmPrinter::EmitVisibility(MCSymbol *Sym, unsigned Visibility) const {
1655   MCSymbolAttr Attr = MCSA_Invalid;
1656   
1657   switch (Visibility) {
1658   default: break;
1659   case GlobalValue::HiddenVisibility:
1660     Attr = MAI->getHiddenVisibilityAttr();
1661     break;
1662   case GlobalValue::ProtectedVisibility:
1663     Attr = MAI->getProtectedVisibilityAttr();
1664     break;
1665   }
1666
1667   if (Attr != MCSA_Invalid)
1668     OutStreamer.EmitSymbolAttribute(Sym, Attr);
1669 }
1670
1671 void AsmPrinter::printOffset(int64_t Offset) const {
1672   if (Offset > 0)
1673     O << '+' << Offset;
1674   else if (Offset < 0)
1675     O << Offset;
1676 }
1677
1678 GCMetadataPrinter *AsmPrinter::GetOrCreateGCPrinter(GCStrategy *S) {
1679   if (!S->usesMetadata())
1680     return 0;
1681   
1682   gcp_iterator GCPI = GCMetadataPrinters.find(S);
1683   if (GCPI != GCMetadataPrinters.end())
1684     return GCPI->second;
1685   
1686   const char *Name = S->getName().c_str();
1687   
1688   for (GCMetadataPrinterRegistry::iterator
1689          I = GCMetadataPrinterRegistry::begin(),
1690          E = GCMetadataPrinterRegistry::end(); I != E; ++I)
1691     if (strcmp(Name, I->getName()) == 0) {
1692       GCMetadataPrinter *GMP = I->instantiate();
1693       GMP->S = S;
1694       GCMetadataPrinters.insert(std::make_pair(S, GMP));
1695       return GMP;
1696     }
1697   
1698   llvm_report_error("no GCMetadataPrinter registered for GC: " + Twine(Name));
1699   return 0;
1700 }
1701
1702 /// EmitComments - Pretty-print comments for instructions
1703 void AsmPrinter::EmitComments(const MachineInstr &MI) const {
1704   if (!VerboseAsm)
1705     return;
1706
1707   bool Newline = false;
1708
1709   if (!MI.getDebugLoc().isUnknown()) {
1710     DILocation DLT = MF->getDILocation(MI.getDebugLoc());
1711
1712     // Print source line info.
1713     O.PadToColumn(MAI->getCommentColumn());
1714     O << MAI->getCommentString() << ' ';
1715     DIScope Scope = DLT.getScope();
1716     // Omit the directory, because it's likely to be long and uninteresting.
1717     if (!Scope.isNull())
1718       O << Scope.getFilename();
1719     else
1720       O << "<unknown>";
1721     O << ':' << DLT.getLineNumber();
1722     if (DLT.getColumnNumber() != 0)
1723       O << ':' << DLT.getColumnNumber();
1724     Newline = true;
1725   }
1726
1727   // Check for spills and reloads
1728   int FI;
1729
1730   const MachineFrameInfo *FrameInfo =
1731     MI.getParent()->getParent()->getFrameInfo();
1732
1733   // We assume a single instruction only has a spill or reload, not
1734   // both.
1735   const MachineMemOperand *MMO;
1736   if (TM.getInstrInfo()->isLoadFromStackSlotPostFE(&MI, FI)) {
1737     if (FrameInfo->isSpillSlotObjectIndex(FI)) {
1738       MMO = *MI.memoperands_begin();
1739       if (Newline) O << '\n';
1740       O.PadToColumn(MAI->getCommentColumn());
1741       O << MAI->getCommentString() << ' ' << MMO->getSize() << "-byte Reload";
1742       Newline = true;
1743     }
1744   }
1745   else if (TM.getInstrInfo()->hasLoadFromStackSlot(&MI, MMO, FI)) {
1746     if (FrameInfo->isSpillSlotObjectIndex(FI)) {
1747       if (Newline) O << '\n';
1748       O.PadToColumn(MAI->getCommentColumn());
1749       O << MAI->getCommentString() << ' '
1750         << MMO->getSize() << "-byte Folded Reload";
1751       Newline = true;
1752     }
1753   }
1754   else if (TM.getInstrInfo()->isStoreToStackSlotPostFE(&MI, FI)) {
1755     if (FrameInfo->isSpillSlotObjectIndex(FI)) {
1756       MMO = *MI.memoperands_begin();
1757       if (Newline) O << '\n';
1758       O.PadToColumn(MAI->getCommentColumn());
1759       O << MAI->getCommentString() << ' ' << MMO->getSize() << "-byte Spill";
1760       Newline = true;
1761     }
1762   }
1763   else if (TM.getInstrInfo()->hasStoreToStackSlot(&MI, MMO, FI)) {
1764     if (FrameInfo->isSpillSlotObjectIndex(FI)) {
1765       if (Newline) O << '\n';
1766       O.PadToColumn(MAI->getCommentColumn());
1767       O << MAI->getCommentString() << ' '
1768         << MMO->getSize() << "-byte Folded Spill";
1769       Newline = true;
1770     }
1771   }
1772
1773   // Check for spill-induced copies
1774   unsigned SrcReg, DstReg, SrcSubIdx, DstSubIdx;
1775   if (TM.getInstrInfo()->isMoveInstr(MI, SrcReg, DstReg,
1776                                       SrcSubIdx, DstSubIdx)) {
1777     if (MI.getAsmPrinterFlag(ReloadReuse)) {
1778       if (Newline) O << '\n';
1779       O.PadToColumn(MAI->getCommentColumn());
1780       O << MAI->getCommentString() << " Reload Reuse";
1781     }
1782   }
1783 }
1784