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