8757d303ec80a8de23c215cc8df071cc9b5cd8f1
[oota-llvm.git] / lib / CodeGen / AsmPrinter.cpp
1 //===-- AsmPrinter.cpp - Common AsmPrinter code ---------------------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file was developed by the LLVM research group and is distributed under
6 // the University of Illinois Open Source 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/MachineConstantPool.h"
20 #include "llvm/CodeGen/MachineJumpTableInfo.h"
21 #include "llvm/Support/Mangler.h"
22 #include "llvm/Support/MathExtras.h"
23 #include "llvm/Support/Streams.h"
24 #include "llvm/Target/TargetAsmInfo.h"
25 #include "llvm/Target/TargetData.h"
26 #include "llvm/Target/TargetLowering.h"
27 #include "llvm/Target/TargetMachine.h"
28 #include <cerrno>
29 using namespace llvm;
30
31 AsmPrinter::AsmPrinter(std::ostream &o, TargetMachine &tm,
32                        const TargetAsmInfo *T)
33 : FunctionNumber(0), O(o), TM(tm), TAI(T)
34 {}
35
36 std::string AsmPrinter::getSectionForFunction(const Function &F) const {
37   return TAI->getTextSection();
38 }
39
40
41 /// SwitchToTextSection - Switch to the specified text section of the executable
42 /// if we are not already in it!
43 ///
44 void AsmPrinter::SwitchToTextSection(const char *NewSection,
45                                      const GlobalValue *GV) {
46   std::string NS;
47   if (GV && GV->hasSection())
48     NS = TAI->getSwitchToSectionDirective() + GV->getSection();
49   else
50     NS = NewSection;
51   
52   // If we're already in this section, we're done.
53   if (CurrentSection == NS) return;
54
55   // Close the current section, if applicable.
56   if (TAI->getSectionEndDirectiveSuffix() && !CurrentSection.empty())
57     O << CurrentSection << TAI->getSectionEndDirectiveSuffix() << "\n";
58
59   CurrentSection = NS;
60
61   if (!CurrentSection.empty())
62     O << CurrentSection << TAI->getTextSectionStartSuffix() << '\n';
63 }
64
65 /// SwitchToDataSection - Switch to the specified data section of the executable
66 /// if we are not already in it!
67 ///
68 void AsmPrinter::SwitchToDataSection(const char *NewSection,
69                                      const GlobalValue *GV) {
70   std::string NS;
71   if (GV && GV->hasSection())
72     NS = TAI->getSwitchToSectionDirective() + GV->getSection();
73   else
74     NS = NewSection;
75   
76   // If we're already in this section, we're done.
77   if (CurrentSection == NS) return;
78
79   // Close the current section, if applicable.
80   if (TAI->getSectionEndDirectiveSuffix() && !CurrentSection.empty())
81     O << CurrentSection << TAI->getSectionEndDirectiveSuffix() << "\n";
82
83   CurrentSection = NS;
84   
85   if (!CurrentSection.empty())
86     O << CurrentSection << TAI->getDataSectionStartSuffix() << '\n';
87 }
88
89
90 bool AsmPrinter::doInitialization(Module &M) {
91   Mang = new Mangler(M, TAI->getGlobalPrefix());
92   
93   if (!M.getModuleInlineAsm().empty())
94     O << TAI->getCommentString() << " Start of file scope inline assembly\n"
95       << M.getModuleInlineAsm()
96       << "\n" << TAI->getCommentString()
97       << " End of file scope inline assembly\n";
98
99   SwitchToDataSection("");   // Reset back to no section.
100   
101   if (MachineDebugInfo *DebugInfo = getAnalysisToUpdate<MachineDebugInfo>()) {
102     DebugInfo->AnalyzeModule(M);
103   }
104   
105   return false;
106 }
107
108 bool AsmPrinter::doFinalization(Module &M) {
109   delete Mang; Mang = 0;
110   return false;
111 }
112
113 void AsmPrinter::SetupMachineFunction(MachineFunction &MF) {
114   // What's my mangled name?
115   CurrentFnName = Mang->getValueName(MF.getFunction());
116   IncrementFunctionNumber();
117 }
118
119 /// EmitConstantPool - Print to the current output stream assembly
120 /// representations of the constants in the constant pool MCP. This is
121 /// used to print out constants which have been "spilled to memory" by
122 /// the code generator.
123 ///
124 void AsmPrinter::EmitConstantPool(MachineConstantPool *MCP) {
125   const std::vector<MachineConstantPoolEntry> &CP = MCP->getConstants();
126   if (CP.empty()) return;
127
128   // Some targets require 4-, 8-, and 16- byte constant literals to be placed
129   // in special sections.
130   std::vector<std::pair<MachineConstantPoolEntry,unsigned> > FourByteCPs;
131   std::vector<std::pair<MachineConstantPoolEntry,unsigned> > EightByteCPs;
132   std::vector<std::pair<MachineConstantPoolEntry,unsigned> > SixteenByteCPs;
133   std::vector<std::pair<MachineConstantPoolEntry,unsigned> > OtherCPs;
134   std::vector<std::pair<MachineConstantPoolEntry,unsigned> > TargetCPs;
135   for (unsigned i = 0, e = CP.size(); i != e; ++i) {
136     MachineConstantPoolEntry CPE = CP[i];
137     const Type *Ty = CPE.getType();
138     if (TAI->getFourByteConstantSection() &&
139         TM.getTargetData()->getTypeSize(Ty) == 4)
140       FourByteCPs.push_back(std::make_pair(CPE, i));
141     else if (TAI->getEightByteConstantSection() &&
142              TM.getTargetData()->getTypeSize(Ty) == 8)
143       EightByteCPs.push_back(std::make_pair(CPE, i));
144     else if (TAI->getSixteenByteConstantSection() &&
145              TM.getTargetData()->getTypeSize(Ty) == 16)
146       SixteenByteCPs.push_back(std::make_pair(CPE, i));
147     else
148       OtherCPs.push_back(std::make_pair(CPE, i));
149   }
150
151   unsigned Alignment = MCP->getConstantPoolAlignment();
152   EmitConstantPool(Alignment, TAI->getFourByteConstantSection(), FourByteCPs);
153   EmitConstantPool(Alignment, TAI->getEightByteConstantSection(), EightByteCPs);
154   EmitConstantPool(Alignment, TAI->getSixteenByteConstantSection(),
155                    SixteenByteCPs);
156   EmitConstantPool(Alignment, TAI->getConstantPoolSection(), OtherCPs);
157 }
158
159 void AsmPrinter::EmitConstantPool(unsigned Alignment, const char *Section,
160                std::vector<std::pair<MachineConstantPoolEntry,unsigned> > &CP) {
161   if (CP.empty()) return;
162
163   SwitchToDataSection(Section);
164   EmitAlignment(Alignment);
165   for (unsigned i = 0, e = CP.size(); i != e; ++i) {
166     O << TAI->getPrivateGlobalPrefix() << "CPI" << getFunctionNumber() << '_'
167       << CP[i].second << ":\t\t\t\t\t" << TAI->getCommentString() << " ";
168     WriteTypeSymbolic(O, CP[i].first.getType(), 0) << '\n';
169     if (CP[i].first.isMachineConstantPoolEntry())
170       EmitMachineConstantPoolValue(CP[i].first.Val.MachineCPVal);
171      else
172       EmitGlobalConstant(CP[i].first.Val.ConstVal);
173     if (i != e-1) {
174       const Type *Ty = CP[i].first.getType();
175       unsigned EntSize =
176         TM.getTargetData()->getTypeSize(Ty);
177       unsigned ValEnd = CP[i].first.getOffset() + EntSize;
178       // Emit inter-object padding for alignment.
179       EmitZeros(CP[i+1].first.getOffset()-ValEnd);
180     }
181   }
182 }
183
184 /// EmitJumpTableInfo - Print assembly representations of the jump tables used
185 /// by the current function to the current output stream.  
186 ///
187 void AsmPrinter::EmitJumpTableInfo(MachineJumpTableInfo *MJTI,
188                                    MachineFunction &MF) {
189   const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables();
190   if (JT.empty()) return;
191   bool IsPic = TM.getRelocationModel() == Reloc::PIC_;
192   
193   // Use JumpTableDirective otherwise honor the entry size from the jump table
194   // info.
195   const char *JTEntryDirective = TAI->getJumpTableDirective();
196   bool HadJTEntryDirective = JTEntryDirective != NULL;
197   if (!HadJTEntryDirective) {
198     JTEntryDirective = MJTI->getEntrySize() == 4 ?
199       TAI->getData32bitsDirective() : TAI->getData64bitsDirective();
200   }
201   
202   // Pick the directive to use to print the jump table entries, and switch to 
203   // the appropriate section.
204   TargetLowering *LoweringInfo = TM.getTargetLowering();
205   
206   if (IsPic && !(LoweringInfo && LoweringInfo->usesGlobalOffsetTable())) {
207     // In PIC mode, we need to emit the jump table to the same section as the
208     // function body itself, otherwise the label differences won't make sense.
209     const Function *F = MF.getFunction();
210     SwitchToTextSection(getSectionForFunction(*F).c_str(), F);
211   } else {
212     SwitchToDataSection(TAI->getJumpTableDataSection());
213   }
214   
215   EmitAlignment(Log2_32(MJTI->getAlignment()));
216   
217   for (unsigned i = 0, e = JT.size(); i != e; ++i) {
218     const std::vector<MachineBasicBlock*> &JTBBs = JT[i].MBBs;
219     
220     // If this jump table was deleted, ignore it. 
221     if (JTBBs.empty()) continue;
222
223     // For PIC codegen, if possible we want to use the SetDirective to reduce
224     // the number of relocations the assembler will generate for the jump table.
225     // Set directives are all printed before the jump table itself.
226     std::set<MachineBasicBlock*> EmittedSets;
227     if (TAI->getSetDirective() && IsPic)
228       for (unsigned ii = 0, ee = JTBBs.size(); ii != ee; ++ii)
229         if (EmittedSets.insert(JTBBs[ii]).second)
230           printSetLabel(i, JTBBs[ii]);
231     
232     O << TAI->getPrivateGlobalPrefix() << "JTI" << getFunctionNumber() 
233       << '_' << i << ":\n";
234     
235     for (unsigned ii = 0, ee = JTBBs.size(); ii != ee; ++ii) {
236       O << JTEntryDirective << ' ';
237       // If we have emitted set directives for the jump table entries, print 
238       // them rather than the entries themselves.  If we're emitting PIC, then
239       // emit the table entries as differences between two text section labels.
240       // If we're emitting non-PIC code, then emit the entries as direct
241       // references to the target basic blocks.
242       if (!EmittedSets.empty()) {
243         O << TAI->getPrivateGlobalPrefix() << getFunctionNumber()
244           << '_' << i << "_set_" << JTBBs[ii]->getNumber();
245       } else if (IsPic) {
246         printBasicBlockLabel(JTBBs[ii], false, false);
247         //If the arch uses custom Jump Table directives, don't calc relative to JT
248         if (!HadJTEntryDirective) 
249           O << '-' << TAI->getPrivateGlobalPrefix() << "JTI"
250             << getFunctionNumber() << '_' << i;
251       } else {
252         printBasicBlockLabel(JTBBs[ii], false, false);
253       }
254       O << '\n';
255     }
256   }
257 }
258
259 /// EmitSpecialLLVMGlobal - Check to see if the specified global is a
260 /// special global used by LLVM.  If so, emit it and return true, otherwise
261 /// do nothing and return false.
262 bool AsmPrinter::EmitSpecialLLVMGlobal(const GlobalVariable *GV) {
263   // Ignore debug and non-emitted data.
264   if (GV->getSection() == "llvm.metadata") return true;
265   
266   if (!GV->hasAppendingLinkage()) return false;
267
268   assert(GV->hasInitializer() && "Not a special LLVM global!");
269   
270   if (GV->getName() == "llvm.used") {
271     if (TAI->getUsedDirective() != 0)    // No need to emit this at all.
272       EmitLLVMUsedList(GV->getInitializer());
273     return true;
274   }
275
276   if (GV->getName() == "llvm.global_ctors" && GV->use_empty()) {
277     SwitchToDataSection(TAI->getStaticCtorsSection());
278     EmitAlignment(2, 0);
279     EmitXXStructorList(GV->getInitializer());
280     return true;
281   } 
282   
283   if (GV->getName() == "llvm.global_dtors" && GV->use_empty()) {
284     SwitchToDataSection(TAI->getStaticDtorsSection());
285     EmitAlignment(2, 0);
286     EmitXXStructorList(GV->getInitializer());
287     return true;
288   }
289   
290   return false;
291 }
292
293 /// EmitLLVMUsedList - For targets that define a TAI::UsedDirective, mark each
294 /// global in the specified llvm.used list as being used with this directive.
295 void AsmPrinter::EmitLLVMUsedList(Constant *List) {
296   const char *Directive = TAI->getUsedDirective();
297
298   // Should be an array of 'sbyte*'.
299   ConstantArray *InitList = dyn_cast<ConstantArray>(List);
300   if (InitList == 0) return;
301   
302   for (unsigned i = 0, e = InitList->getNumOperands(); i != e; ++i) {
303     O << Directive;
304     EmitConstantValueOnly(InitList->getOperand(i));
305     O << "\n";
306   }
307 }
308
309 /// EmitXXStructorList - Emit the ctor or dtor list.  This just prints out the 
310 /// function pointers, ignoring the init priority.
311 void AsmPrinter::EmitXXStructorList(Constant *List) {
312   // Should be an array of '{ int, void ()* }' structs.  The first value is the
313   // init priority, which we ignore.
314   if (!isa<ConstantArray>(List)) return;
315   ConstantArray *InitList = cast<ConstantArray>(List);
316   for (unsigned i = 0, e = InitList->getNumOperands(); i != e; ++i)
317     if (ConstantStruct *CS = dyn_cast<ConstantStruct>(InitList->getOperand(i))){
318       if (CS->getNumOperands() != 2) return;  // Not array of 2-element structs.
319
320       if (CS->getOperand(1)->isNullValue())
321         return;  // Found a null terminator, exit printing.
322       // Emit the function pointer.
323       EmitGlobalConstant(CS->getOperand(1));
324     }
325 }
326
327 /// getGlobalLinkName - Returns the asm/link name of of the specified
328 /// global variable.  Should be overridden by each target asm printer to
329 /// generate the appropriate value.
330 const std::string AsmPrinter::getGlobalLinkName(const GlobalVariable *GV) const{
331   std::string LinkName;
332   
333   if (isa<Function>(GV)) {
334     LinkName += TAI->getFunctionAddrPrefix();
335     LinkName += Mang->getValueName(GV);
336     LinkName += TAI->getFunctionAddrSuffix();
337   } else {
338     LinkName += TAI->getGlobalVarAddrPrefix();
339     LinkName += Mang->getValueName(GV);
340     LinkName += TAI->getGlobalVarAddrSuffix();
341   }  
342   
343   return LinkName;
344 }
345
346 // EmitAlignment - Emit an alignment directive to the specified power of two.
347 void AsmPrinter::EmitAlignment(unsigned NumBits, const GlobalValue *GV) const {
348   if (GV && GV->getAlignment())
349     NumBits = Log2_32(GV->getAlignment());
350   if (NumBits == 0) return;   // No need to emit alignment.
351   if (TAI->getAlignmentIsInBytes()) NumBits = 1 << NumBits;
352   O << TAI->getAlignDirective() << NumBits << "\n";
353 }
354
355 /// EmitZeros - Emit a block of zeros.
356 ///
357 void AsmPrinter::EmitZeros(uint64_t NumZeros) const {
358   if (NumZeros) {
359     if (TAI->getZeroDirective()) {
360       O << TAI->getZeroDirective() << NumZeros;
361       if (TAI->getZeroDirectiveSuffix())
362         O << TAI->getZeroDirectiveSuffix();
363       O << "\n";
364     } else {
365       for (; NumZeros; --NumZeros)
366         O << TAI->getData8bitsDirective() << "0\n";
367     }
368   }
369 }
370
371 // Print out the specified constant, without a storage class.  Only the
372 // constants valid in constant expressions can occur here.
373 void AsmPrinter::EmitConstantValueOnly(const Constant *CV) {
374   if (CV->isNullValue() || isa<UndefValue>(CV))
375     O << "0";
376   else if (const ConstantBool *CB = dyn_cast<ConstantBool>(CV)) {
377     assert(CB->getValue());
378     O << "1";
379   } else if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV)) {
380     if (CI->getType()->isSigned()) {
381       if (((CI->getSExtValue() << 32) >> 32) == CI->getSExtValue())
382         O << CI->getSExtValue();
383       else
384         O << (uint64_t)CI->getSExtValue();
385     } else 
386       O << CI->getZExtValue();
387   } else if (const GlobalValue *GV = dyn_cast<GlobalValue>(CV)) {
388     // This is a constant address for a global variable or function. Use the
389     // name of the variable or function as the address value, possibly
390     // decorating it with GlobalVarAddrPrefix/Suffix or
391     // FunctionAddrPrefix/Suffix (these all default to "" )
392     if (isa<Function>(GV)) {
393       O << TAI->getFunctionAddrPrefix()
394         << Mang->getValueName(GV)
395         << TAI->getFunctionAddrSuffix();
396     } else {
397       O << TAI->getGlobalVarAddrPrefix()
398         << Mang->getValueName(GV)
399         << TAI->getGlobalVarAddrSuffix();
400     }
401   } else if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV)) {
402     const TargetData *TD = TM.getTargetData();
403     switch(CE->getOpcode()) {
404     case Instruction::GetElementPtr: {
405       // generate a symbolic expression for the byte address
406       const Constant *ptrVal = CE->getOperand(0);
407       std::vector<Value*> idxVec(CE->op_begin()+1, CE->op_end());
408       if (int64_t Offset = TD->getIndexedOffset(ptrVal->getType(), idxVec)) {
409         if (Offset)
410           O << "(";
411         EmitConstantValueOnly(ptrVal);
412         if (Offset > 0)
413           O << ") + " << Offset;
414         else if (Offset < 0)
415           O << ") - " << -Offset;
416       } else {
417         EmitConstantValueOnly(ptrVal);
418       }
419       break;
420     }
421     case Instruction::Trunc:
422     case Instruction::ZExt:
423     case Instruction::SExt:
424     case Instruction::FPTrunc:
425     case Instruction::FPExt:
426     case Instruction::UIToFP:
427     case Instruction::SIToFP:
428     case Instruction::FPToUI:
429     case Instruction::FPToSI:
430       assert(0 && "FIXME: Don't yet support this kind of constant cast expr");
431       break;
432     case Instruction::BitCast:
433       return EmitConstantValueOnly(CE->getOperand(0));
434
435     case Instruction::IntToPtr: {
436       // Handle casts to pointers by changing them into casts to the appropriate
437       // integer type.  This promotes constant folding and simplifies this code.
438       Constant *Op = CE->getOperand(0);
439       Op = ConstantExpr::getIntegerCast(Op, TD->getIntPtrType(), false/*ZExt*/);
440       return EmitConstantValueOnly(Op);
441     }
442       
443       
444     case Instruction::PtrToInt: {
445       // Support only foldable casts to/from pointers that can be eliminated by
446       // changing the pointer to the appropriately sized integer type.
447       Constant *Op = CE->getOperand(0);
448       const Type *Ty = CE->getType();
449
450       // We can emit the pointer value into this slot if the slot is an
451       // integer slot greater or equal to the size of the pointer.
452       if (Ty->isIntegral() &&
453           Ty->getPrimitiveSize() >= TD->getTypeSize(Op->getType()))
454         return EmitConstantValueOnly(Op);
455       
456       assert(0 && "FIXME: Don't yet support this kind of constant cast expr");
457       EmitConstantValueOnly(Op);
458       break;
459     }
460     case Instruction::Add:
461       O << "(";
462       EmitConstantValueOnly(CE->getOperand(0));
463       O << ") + (";
464       EmitConstantValueOnly(CE->getOperand(1));
465       O << ")";
466       break;
467     default:
468       assert(0 && "Unsupported operator!");
469     }
470   } else {
471     assert(0 && "Unknown constant value!");
472   }
473 }
474
475 /// toOctal - Convert the low order bits of X into an octal digit.
476 ///
477 static inline char toOctal(int X) {
478   return (X&7)+'0';
479 }
480
481 /// printAsCString - Print the specified array as a C compatible string, only if
482 /// the predicate isString is true.
483 ///
484 static void printAsCString(std::ostream &O, const ConstantArray *CVA,
485                            unsigned LastElt) {
486   assert(CVA->isString() && "Array is not string compatible!");
487
488   O << "\"";
489   for (unsigned i = 0; i != LastElt; ++i) {
490     unsigned char C =
491         (unsigned char)cast<ConstantInt>(CVA->getOperand(i))->getZExtValue();
492
493     if (C == '"') {
494       O << "\\\"";
495     } else if (C == '\\') {
496       O << "\\\\";
497     } else if (isprint(C)) {
498       O << C;
499     } else {
500       switch(C) {
501       case '\b': O << "\\b"; break;
502       case '\f': O << "\\f"; break;
503       case '\n': O << "\\n"; break;
504       case '\r': O << "\\r"; break;
505       case '\t': O << "\\t"; break;
506       default:
507         O << '\\';
508         O << toOctal(C >> 6);
509         O << toOctal(C >> 3);
510         O << toOctal(C >> 0);
511         break;
512       }
513     }
514   }
515   O << "\"";
516 }
517
518 /// EmitString - Emit a zero-byte-terminated string constant.
519 ///
520 void AsmPrinter::EmitString(const ConstantArray *CVA) const {
521   unsigned NumElts = CVA->getNumOperands();
522   if (TAI->getAscizDirective() && NumElts && 
523       cast<ConstantInt>(CVA->getOperand(NumElts-1))->getZExtValue() == 0) {
524     O << TAI->getAscizDirective();
525     printAsCString(O, CVA, NumElts-1);
526   } else {
527     O << TAI->getAsciiDirective();
528     printAsCString(O, CVA, NumElts);
529   }
530   O << "\n";
531 }
532
533 /// EmitGlobalConstant - Print a general LLVM constant to the .s file.
534 ///
535 void AsmPrinter::EmitGlobalConstant(const Constant *CV) {
536   const TargetData *TD = TM.getTargetData();
537
538   if (CV->isNullValue() || isa<UndefValue>(CV)) {
539     EmitZeros(TD->getTypeSize(CV->getType()));
540     return;
541   } else if (const ConstantArray *CVA = dyn_cast<ConstantArray>(CV)) {
542     if (CVA->isString()) {
543       EmitString(CVA);
544     } else { // Not a string.  Print the values in successive locations
545       for (unsigned i = 0, e = CVA->getNumOperands(); i != e; ++i)
546         EmitGlobalConstant(CVA->getOperand(i));
547     }
548     return;
549   } else if (const ConstantStruct *CVS = dyn_cast<ConstantStruct>(CV)) {
550     // Print the fields in successive locations. Pad to align if needed!
551     const StructLayout *cvsLayout = TD->getStructLayout(CVS->getType());
552     uint64_t sizeSoFar = 0;
553     for (unsigned i = 0, e = CVS->getNumOperands(); i != e; ++i) {
554       const Constant* field = CVS->getOperand(i);
555
556       // Check if padding is needed and insert one or more 0s.
557       uint64_t fieldSize = TD->getTypeSize(field->getType());
558       uint64_t padSize = ((i == e-1? cvsLayout->StructSize
559                            : cvsLayout->MemberOffsets[i+1])
560                           - cvsLayout->MemberOffsets[i]) - fieldSize;
561       sizeSoFar += fieldSize + padSize;
562
563       // Now print the actual field value
564       EmitGlobalConstant(field);
565
566       // Insert the field padding unless it's zero bytes...
567       EmitZeros(padSize);
568     }
569     assert(sizeSoFar == cvsLayout->StructSize &&
570            "Layout of constant struct may be incorrect!");
571     return;
572   } else if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CV)) {
573     // FP Constants are printed as integer constants to avoid losing
574     // precision...
575     double Val = CFP->getValue();
576     if (CFP->getType() == Type::DoubleTy) {
577       if (TAI->getData64bitsDirective())
578         O << TAI->getData64bitsDirective() << DoubleToBits(Val) << "\t"
579           << TAI->getCommentString() << " double value: " << Val << "\n";
580       else if (TD->isBigEndian()) {
581         O << TAI->getData32bitsDirective() << unsigned(DoubleToBits(Val) >> 32)
582           << "\t" << TAI->getCommentString()
583           << " double most significant word " << Val << "\n";
584         O << TAI->getData32bitsDirective() << unsigned(DoubleToBits(Val))
585           << "\t" << TAI->getCommentString()
586           << " double least significant word " << Val << "\n";
587       } else {
588         O << TAI->getData32bitsDirective() << unsigned(DoubleToBits(Val))
589           << "\t" << TAI->getCommentString()
590           << " double least significant word " << Val << "\n";
591         O << TAI->getData32bitsDirective() << unsigned(DoubleToBits(Val) >> 32)
592           << "\t" << TAI->getCommentString()
593           << " double most significant word " << Val << "\n";
594       }
595       return;
596     } else {
597       O << TAI->getData32bitsDirective() << FloatToBits(Val)
598         << "\t" << TAI->getCommentString() << " float " << Val << "\n";
599       return;
600     }
601   } else if (CV->getType() == Type::ULongTy || CV->getType() == Type::LongTy) {
602     if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV)) {
603       uint64_t Val = CI->getZExtValue();
604
605       if (TAI->getData64bitsDirective())
606         O << TAI->getData64bitsDirective() << Val << "\n";
607       else if (TD->isBigEndian()) {
608         O << TAI->getData32bitsDirective() << unsigned(Val >> 32)
609           << "\t" << TAI->getCommentString()
610           << " Double-word most significant word " << Val << "\n";
611         O << TAI->getData32bitsDirective() << unsigned(Val)
612           << "\t" << TAI->getCommentString()
613           << " Double-word least significant word " << Val << "\n";
614       } else {
615         O << TAI->getData32bitsDirective() << unsigned(Val)
616           << "\t" << TAI->getCommentString()
617           << " Double-word least significant word " << Val << "\n";
618         O << TAI->getData32bitsDirective() << unsigned(Val >> 32)
619           << "\t" << TAI->getCommentString()
620           << " Double-word most significant word " << Val << "\n";
621       }
622       return;
623     }
624   } else if (const ConstantPacked *CP = dyn_cast<ConstantPacked>(CV)) {
625     const PackedType *PTy = CP->getType();
626     
627     for (unsigned I = 0, E = PTy->getNumElements(); I < E; ++I)
628       EmitGlobalConstant(CP->getOperand(I));
629     
630     return;
631   }
632
633   const Type *type = CV->getType();
634   printDataDirective(type);
635   EmitConstantValueOnly(CV);
636   O << "\n";
637 }
638
639 void
640 AsmPrinter::EmitMachineConstantPoolValue(MachineConstantPoolValue *MCPV) {
641   // Target doesn't support this yet!
642   abort();
643 }
644
645 /// PrintSpecial - Print information related to the specified machine instr
646 /// that is independent of the operand, and may be independent of the instr
647 /// itself.  This can be useful for portably encoding the comment character
648 /// or other bits of target-specific knowledge into the asmstrings.  The
649 /// syntax used is ${:comment}.  Targets can override this to add support
650 /// for their own strange codes.
651 void AsmPrinter::PrintSpecial(const MachineInstr *MI, const char *Code) {
652   if (!strcmp(Code, "private")) {
653     O << TAI->getPrivateGlobalPrefix();
654   } else if (!strcmp(Code, "comment")) {
655     O << TAI->getCommentString();
656   } else if (!strcmp(Code, "uid")) {
657     // Assign a unique ID to this machine instruction.
658     static const MachineInstr *LastMI = 0;
659     static unsigned Counter = 0U-1;
660     // If this is a new machine instruction, bump the counter.
661     if (LastMI != MI) { ++Counter; LastMI = MI; }
662     O << Counter;
663   } else {
664     cerr << "Unknown special formatter '" << Code
665          << "' for machine instr: " << *MI;
666     exit(1);
667   }    
668 }
669
670
671 /// printInlineAsm - This method formats and prints the specified machine
672 /// instruction that is an inline asm.
673 void AsmPrinter::printInlineAsm(const MachineInstr *MI) const {
674   unsigned NumOperands = MI->getNumOperands();
675   
676   // Count the number of register definitions.
677   unsigned NumDefs = 0;
678   for (; MI->getOperand(NumDefs).isReg() && MI->getOperand(NumDefs).isDef();
679        ++NumDefs)
680     assert(NumDefs != NumOperands-1 && "No asm string?");
681   
682   assert(MI->getOperand(NumDefs).isExternalSymbol() && "No asm string?");
683
684   // Disassemble the AsmStr, printing out the literal pieces, the operands, etc.
685   const char *AsmStr = MI->getOperand(NumDefs).getSymbolName();
686
687   // If this asmstr is empty, don't bother printing the #APP/#NOAPP markers.
688   if (AsmStr[0] == 0) {
689     O << "\n";  // Tab already printed, avoid double indenting next instr.
690     return;
691   }
692   
693   O << TAI->getInlineAsmStart() << "\n\t";
694
695   // The variant of the current asmprinter: FIXME: change.
696   int AsmPrinterVariant = 0;
697   
698   int CurVariant = -1;            // The number of the {.|.|.} region we are in.
699   const char *LastEmitted = AsmStr; // One past the last character emitted.
700   
701   while (*LastEmitted) {
702     switch (*LastEmitted) {
703     default: {
704       // Not a special case, emit the string section literally.
705       const char *LiteralEnd = LastEmitted+1;
706       while (*LiteralEnd && *LiteralEnd != '{' && *LiteralEnd != '|' &&
707              *LiteralEnd != '}' && *LiteralEnd != '$' && *LiteralEnd != '\n')
708         ++LiteralEnd;
709       if (CurVariant == -1 || CurVariant == AsmPrinterVariant)
710         O.write(LastEmitted, LiteralEnd-LastEmitted);
711       LastEmitted = LiteralEnd;
712       break;
713     }
714     case '\n':
715       ++LastEmitted;   // Consume newline character.
716       O << "\n\t";     // Indent code with newline.
717       break;
718     case '$': {
719       ++LastEmitted;   // Consume '$' character.
720       bool Done = true;
721
722       // Handle escapes.
723       switch (*LastEmitted) {
724       default: Done = false; break;
725       case '$':     // $$ -> $
726         if (CurVariant == -1 || CurVariant == AsmPrinterVariant)
727           O << '$';
728         ++LastEmitted;  // Consume second '$' character.
729         break;
730       case '(':             // $( -> same as GCC's { character.
731         ++LastEmitted;      // Consume '(' character.
732         if (CurVariant != -1) {
733           cerr << "Nested variants found in inline asm string: '"
734                << AsmStr << "'\n";
735           exit(1);
736         }
737         CurVariant = 0;     // We're in the first variant now.
738         break;
739       case '|':
740         ++LastEmitted;  // consume '|' character.
741         if (CurVariant == -1) {
742           cerr << "Found '|' character outside of variant in inline asm "
743                << "string: '" << AsmStr << "'\n";
744           exit(1);
745         }
746         ++CurVariant;   // We're in the next variant.
747         break;
748       case ')':         // $) -> same as GCC's } char.
749         ++LastEmitted;  // consume ')' character.
750         if (CurVariant == -1) {
751           cerr << "Found '}' character outside of variant in inline asm "
752                << "string: '" << AsmStr << "'\n";
753           exit(1);
754         }
755         CurVariant = -1;
756         break;
757       }
758       if (Done) break;
759       
760       bool HasCurlyBraces = false;
761       if (*LastEmitted == '{') {     // ${variable}
762         ++LastEmitted;               // Consume '{' character.
763         HasCurlyBraces = true;
764       }
765       
766       const char *IDStart = LastEmitted;
767       char *IDEnd;
768       long Val = strtol(IDStart, &IDEnd, 10); // We only accept numbers for IDs.
769       if (!isdigit(*IDStart) || (Val == 0 && errno == EINVAL)) {
770         cerr << "Bad $ operand number in inline asm string: '" 
771              << AsmStr << "'\n";
772         exit(1);
773       }
774       LastEmitted = IDEnd;
775       
776       char Modifier[2] = { 0, 0 };
777       
778       if (HasCurlyBraces) {
779         // If we have curly braces, check for a modifier character.  This
780         // supports syntax like ${0:u}, which correspond to "%u0" in GCC asm.
781         if (*LastEmitted == ':') {
782           ++LastEmitted;    // Consume ':' character.
783           if (*LastEmitted == 0) {
784             cerr << "Bad ${:} expression in inline asm string: '" 
785                  << AsmStr << "'\n";
786             exit(1);
787           }
788           
789           Modifier[0] = *LastEmitted;
790           ++LastEmitted;    // Consume modifier character.
791         }
792         
793         if (*LastEmitted != '}') {
794           cerr << "Bad ${} expression in inline asm string: '" 
795                << AsmStr << "'\n";
796           exit(1);
797         }
798         ++LastEmitted;    // Consume '}' character.
799       }
800       
801       if ((unsigned)Val >= NumOperands-1) {
802         cerr << "Invalid $ operand number in inline asm string: '" 
803              << AsmStr << "'\n";
804         exit(1);
805       }
806       
807       // Okay, we finally have a value number.  Ask the target to print this
808       // operand!
809       if (CurVariant == -1 || CurVariant == AsmPrinterVariant) {
810         unsigned OpNo = 1;
811
812         bool Error = false;
813
814         // Scan to find the machine operand number for the operand.
815         for (; Val; --Val) {
816           if (OpNo >= MI->getNumOperands()) break;
817           unsigned OpFlags = MI->getOperand(OpNo).getImmedValue();
818           OpNo += (OpFlags >> 3) + 1;
819         }
820
821         if (OpNo >= MI->getNumOperands()) {
822           Error = true;
823         } else {
824           unsigned OpFlags = MI->getOperand(OpNo).getImmedValue();
825           ++OpNo;  // Skip over the ID number.
826
827           AsmPrinter *AP = const_cast<AsmPrinter*>(this);
828           if ((OpFlags & 7) == 4 /*ADDR MODE*/) {
829             Error = AP->PrintAsmMemoryOperand(MI, OpNo, AsmPrinterVariant,
830                                               Modifier[0] ? Modifier : 0);
831           } else {
832             Error = AP->PrintAsmOperand(MI, OpNo, AsmPrinterVariant,
833                                         Modifier[0] ? Modifier : 0);
834           }
835         }
836         if (Error) {
837           cerr << "Invalid operand found in inline asm: '"
838                << AsmStr << "'\n";
839           MI->dump();
840           exit(1);
841         }
842       }
843       break;
844     }
845     }
846   }
847   O << "\n\t" << TAI->getInlineAsmEnd() << "\n";
848 }
849
850 /// PrintAsmOperand - Print the specified operand of MI, an INLINEASM
851 /// instruction, using the specified assembler variant.  Targets should
852 /// overried this to format as appropriate.
853 bool AsmPrinter::PrintAsmOperand(const MachineInstr *MI, unsigned OpNo,
854                                  unsigned AsmVariant, const char *ExtraCode) {
855   // Target doesn't support this yet!
856   return true;
857 }
858
859 bool AsmPrinter::PrintAsmMemoryOperand(const MachineInstr *MI, unsigned OpNo,
860                                        unsigned AsmVariant,
861                                        const char *ExtraCode) {
862   // Target doesn't support this yet!
863   return true;
864 }
865
866 /// printBasicBlockLabel - This method prints the label for the specified
867 /// MachineBasicBlock
868 void AsmPrinter::printBasicBlockLabel(const MachineBasicBlock *MBB,
869                                       bool printColon,
870                                       bool printComment) const {
871   O << TAI->getPrivateGlobalPrefix() << "BB" << FunctionNumber << "_"
872     << MBB->getNumber();
873   if (printColon)
874     O << ':';
875   if (printComment && MBB->getBasicBlock())
876     O << '\t' << TAI->getCommentString() << MBB->getBasicBlock()->getName();
877 }
878
879 /// printSetLabel - This method prints a set label for the specified
880 /// MachineBasicBlock
881 void AsmPrinter::printSetLabel(unsigned uid, 
882                                const MachineBasicBlock *MBB) const {
883   if (!TAI->getSetDirective())
884     return;
885   
886   O << TAI->getSetDirective() << ' ' << TAI->getPrivateGlobalPrefix()
887     << getFunctionNumber() << '_' << uid << "_set_" << MBB->getNumber() << ',';
888   printBasicBlockLabel(MBB, false, false);
889   O << '-' << TAI->getPrivateGlobalPrefix() << "JTI" << getFunctionNumber() 
890     << '_' << uid << '\n';
891 }
892
893 void AsmPrinter::printSetLabel(unsigned uid, unsigned uid2,
894                                const MachineBasicBlock *MBB) const {
895   if (!TAI->getSetDirective())
896     return;
897   
898   O << TAI->getSetDirective() << ' ' << TAI->getPrivateGlobalPrefix()
899     << getFunctionNumber() << '_' << uid << '_' << uid2
900     << "_set_" << MBB->getNumber() << ',';
901   printBasicBlockLabel(MBB, false, false);
902   O << '-' << TAI->getPrivateGlobalPrefix() << "JTI" << getFunctionNumber() 
903     << '_' << uid << '_' << uid2 << '\n';
904 }
905
906 /// printDataDirective - This method prints the asm directive for the
907 /// specified type.
908 void AsmPrinter::printDataDirective(const Type *type) {
909   const TargetData *TD = TM.getTargetData();
910   switch (type->getTypeID()) {
911   case Type::BoolTyID:
912   case Type::UByteTyID: case Type::SByteTyID:
913     O << TAI->getData8bitsDirective();
914     break;
915   case Type::UShortTyID: case Type::ShortTyID:
916     O << TAI->getData16bitsDirective();
917     break;
918   case Type::PointerTyID:
919     if (TD->getPointerSize() == 8) {
920       assert(TAI->getData64bitsDirective() &&
921              "Target cannot handle 64-bit pointer exprs!");
922       O << TAI->getData64bitsDirective();
923       break;
924     }
925     //Fall through for pointer size == int size
926   case Type::UIntTyID: case Type::IntTyID:
927     O << TAI->getData32bitsDirective();
928     break;
929   case Type::ULongTyID: case Type::LongTyID:
930     assert(TAI->getData64bitsDirective() &&
931            "Target cannot handle 64-bit constant exprs!");
932     O << TAI->getData64bitsDirective();
933     break;
934   case Type::FloatTyID: case Type::DoubleTyID:
935     assert (0 && "Should have already output floating point constant.");
936   default:
937     assert (0 && "Can't handle printing this type of thing");
938     break;
939   }
940 }