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