9aca4e25ac055b57159060e6120566f4e42eaced
[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/Target/TargetMachine.h"
24 #include <iostream>
25 #include <cerrno>
26 using namespace llvm;
27
28 AsmPrinter::AsmPrinter(std::ostream &o, TargetMachine &tm)
29 : FunctionNumber(0), O(o), TM(tm),
30   CommentString("#"),
31   GlobalPrefix(""),
32   PrivateGlobalPrefix("."),
33   GlobalVarAddrPrefix(""),
34   GlobalVarAddrSuffix(""),
35   FunctionAddrPrefix(""),
36   FunctionAddrSuffix(""),
37   InlineAsmStart("#APP"),
38   InlineAsmEnd("#NO_APP"),
39   ZeroDirective("\t.zero\t"),
40   ZeroDirectiveSuffix(0),
41   AsciiDirective("\t.ascii\t"),
42   AscizDirective("\t.asciz\t"),
43   Data8bitsDirective("\t.byte\t"),
44   Data16bitsDirective("\t.short\t"),
45   Data32bitsDirective("\t.long\t"),
46   Data64bitsDirective("\t.quad\t"),
47   AlignDirective("\t.align\t"),
48   AlignmentIsInBytes(true),
49   SwitchToSectionDirective("\t.section\t"),
50   MLSections(false),
51   ConstantPoolSection("\t.section .rodata\n"),
52   JumpTableSection("\t.section .rodata\n"),
53   StaticCtorsSection("\t.section .ctors,\"aw\",@progbits"),
54   StaticDtorsSection("\t.section .dtors,\"aw\",@progbits"),
55   LCOMMDirective(0),
56   COMMDirective("\t.comm\t"),
57   COMMDirectiveTakesAlignment(true),
58   HasDotTypeDotSizeDirective(true) {
59 }
60
61
62 /// SwitchSection - Switch to the specified section of the executable if we
63 /// are not already in it!
64 ///
65 void AsmPrinter::SwitchSection(const char *NewSection, const GlobalValue *GV) {
66   std::string NS;
67
68   // Microsoft ML/MASM has a fundamentally different approach to handling
69   // sections.
70
71   if (MLSections) {
72     if (*NewSection == 0) {
73       // Simply end the current section, if any.
74       if (!CurrentSection.empty()) {
75         O << CurrentSection << "\tends\n\n";
76         CurrentSection.clear();
77       }
78       return;
79     }
80
81     bool isData = strcmp(NewSection , ".data") == 0;
82
83     if (GV && GV->hasSection())
84       NS = GV->getSection();
85     else if (isData)
86       NS = "_data";
87     else
88       NS = "_text";
89
90     if (CurrentSection != NS) {
91       if (!CurrentSection.empty())
92         O << CurrentSection << "\tends\n\n";
93       CurrentSection = NS;
94       O << CurrentSection << (isData ? "\tsegment 'DATA'\n"
95                                      : "\tsegment 'CODE'\n");
96     }
97   } else {
98     if (GV && GV->hasSection())
99       NS = SwitchToSectionDirective + GV->getSection();
100     else
101       NS = std::string("\t")+NewSection;
102     
103     if (CurrentSection != NS) {
104       CurrentSection = NS;
105       if (!CurrentSection.empty())
106         O << CurrentSection << '\n';
107     }
108   }
109 }
110
111 bool AsmPrinter::doInitialization(Module &M) {
112   Mang = new Mangler(M, GlobalPrefix);
113   
114   if (!M.getModuleInlineAsm().empty())
115     O << CommentString << " Start of file scope inline assembly\n"
116       << M.getModuleInlineAsm()
117       << "\n" << CommentString << " End of file scope inline assembly\n";
118
119   SwitchSection("", 0);   // Reset back to no section.
120   
121   if (MachineDebugInfo *DebugInfo = getAnalysisToUpdate<MachineDebugInfo>()) {
122     DebugInfo->AnalyzeModule(M);
123   }
124   
125   return false;
126 }
127
128 bool AsmPrinter::doFinalization(Module &M) {
129   delete Mang; Mang = 0;
130   return false;
131 }
132
133 void AsmPrinter::SetupMachineFunction(MachineFunction &MF) {
134   // What's my mangled name?
135   CurrentFnName = Mang->getValueName(MF.getFunction());
136   IncrementFunctionNumber();
137 }
138
139 /// EmitConstantPool - Print to the current output stream assembly
140 /// representations of the constants in the constant pool MCP. This is
141 /// used to print out constants which have been "spilled to memory" by
142 /// the code generator.
143 ///
144 void AsmPrinter::EmitConstantPool(MachineConstantPool *MCP) {
145   const std::vector<MachineConstantPoolEntry> &CP = MCP->getConstants();
146   if (CP.empty()) return;
147   const TargetData *TD = TM.getTargetData();
148   
149   SwitchSection(ConstantPoolSection, 0);
150   EmitAlignment(MCP->getConstantPoolAlignment());
151   for (unsigned i = 0, e = CP.size(); i != e; ++i) {
152     O << PrivateGlobalPrefix << "CPI" << getFunctionNumber() << '_' << i
153       << ":\t\t\t\t\t" << CommentString << " ";
154     WriteTypeSymbolic(O, CP[i].Val->getType(), 0) << '\n';
155     EmitGlobalConstant(CP[i].Val);
156     if (i != e-1) {
157       unsigned EntSize = TM.getTargetData()->getTypeSize(CP[i].Val->getType());
158       unsigned ValEnd = CP[i].Offset + EntSize;
159       // Emit inter-object padding for alignment.
160       EmitZeros(CP[i+1].Offset-ValEnd);
161     }
162   }
163 }
164
165 /// EmitJumpTableInfo - Print assembly representations of the jump tables used
166 /// by the current function to the current output stream.  
167 ///
168 void AsmPrinter::EmitJumpTableInfo(MachineJumpTableInfo *MJTI) {
169   const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables();
170   if (JT.empty()) return;
171   const TargetData *TD = TM.getTargetData();
172   
173   // FIXME: someday we need to handle PIC jump tables
174   assert((TM.getRelocationModel() == Reloc::Static ||
175           TM.getRelocationModel() == Reloc::DynamicNoPIC) &&
176          "Unhandled relocation model emitting jump table information!");
177   
178   SwitchSection(JumpTableSection, 0);
179   EmitAlignment(Log2_32(TD->getPointerAlignment()));
180   for (unsigned i = 0, e = JT.size(); i != e; ++i) {
181     O << PrivateGlobalPrefix << "JTI" << getFunctionNumber() << '_' << i 
182       << ":\n";
183     const std::vector<MachineBasicBlock*> &JTBBs = JT[i].MBBs;
184     for (unsigned ii = 0, ee = JTBBs.size(); ii != ee; ++ii) {
185       O << Data32bitsDirective << ' ';
186       printBasicBlockLabel(JTBBs[ii]);
187       O << '\n';
188     }
189   }
190 }
191
192 /// EmitSpecialLLVMGlobal - Check to see if the specified global is a
193 /// special global used by LLVM.  If so, emit it and return true, otherwise
194 /// do nothing and return false.
195 bool AsmPrinter::EmitSpecialLLVMGlobal(const GlobalVariable *GV) {
196   // Ignore debug and non-emitted data.
197   if (GV->getSection() == "llvm.metadata") return true;
198   
199   if (!GV->hasAppendingLinkage()) return false;
200
201   assert(GV->hasInitializer() && "Not a special LLVM global!");
202   
203   if (GV->getName() == "llvm.used")
204     return true;  // No need to emit this at all.
205
206   if (GV->getName() == "llvm.global_ctors" && GV->use_empty()) {
207     SwitchSection(StaticCtorsSection, 0);
208     EmitAlignment(2, 0);
209     EmitXXStructorList(GV->getInitializer());
210     return true;
211   } 
212   
213   if (GV->getName() == "llvm.global_dtors" && GV->use_empty()) {
214     SwitchSection(StaticDtorsSection, 0);
215     EmitAlignment(2, 0);
216     EmitXXStructorList(GV->getInitializer());
217     return true;
218   }
219   
220   return false;
221 }
222
223 /// EmitXXStructorList - Emit the ctor or dtor list.  This just prints out the 
224 /// function pointers, ignoring the init priority.
225 void AsmPrinter::EmitXXStructorList(Constant *List) {
226   // Should be an array of '{ int, void ()* }' structs.  The first value is the
227   // init priority, which we ignore.
228   if (!isa<ConstantArray>(List)) return;
229   ConstantArray *InitList = cast<ConstantArray>(List);
230   for (unsigned i = 0, e = InitList->getNumOperands(); i != e; ++i)
231     if (ConstantStruct *CS = dyn_cast<ConstantStruct>(InitList->getOperand(i))){
232       if (CS->getNumOperands() != 2) return;  // Not array of 2-element structs.
233
234       if (CS->getOperand(1)->isNullValue())
235         return;  // Found a null terminator, exit printing.
236       // Emit the function pointer.
237       EmitGlobalConstant(CS->getOperand(1));
238     }
239 }
240
241 /// getPreferredAlignmentLog - Return the preferred alignment of the
242 /// specified global, returned in log form.  This includes an explicitly
243 /// requested alignment (if the global has one).
244 unsigned AsmPrinter::getPreferredAlignmentLog(const GlobalVariable *GV) const {
245   unsigned Alignment = TM.getTargetData()->getTypeAlignmentShift(GV->getType());
246   if (GV->getAlignment() > (1U << Alignment))
247     Alignment = Log2_32(GV->getAlignment());
248   
249   if (GV->hasInitializer()) {
250     // Always round up alignment of global doubles to 8 bytes.
251     if (GV->getType()->getElementType() == Type::DoubleTy && Alignment < 3)
252       Alignment = 3;
253     if (Alignment < 4) {
254       // If the global is not external, see if it is large.  If so, give it a
255       // larger alignment.
256       if (TM.getTargetData()->getTypeSize(GV->getType()->getElementType()) > 128)
257         Alignment = 4;    // 16-byte alignment.
258     }
259   }
260   return Alignment;
261 }
262
263 // EmitAlignment - Emit an alignment directive to the specified power of two.
264 void AsmPrinter::EmitAlignment(unsigned NumBits, const GlobalValue *GV) const {
265   if (GV && GV->getAlignment())
266     NumBits = Log2_32(GV->getAlignment());
267   if (NumBits == 0) return;   // No need to emit alignment.
268   if (AlignmentIsInBytes) NumBits = 1 << NumBits;
269   O << AlignDirective << NumBits << "\n";
270 }
271
272 /// EmitZeros - Emit a block of zeros.
273 ///
274 void AsmPrinter::EmitZeros(uint64_t NumZeros) const {
275   if (NumZeros) {
276     if (ZeroDirective) {
277       O << ZeroDirective << NumZeros;
278       if (ZeroDirectiveSuffix)
279         O << ZeroDirectiveSuffix;
280       O << "\n";
281     } else {
282       for (; NumZeros; --NumZeros)
283         O << Data8bitsDirective << "0\n";
284     }
285   }
286 }
287
288 // Print out the specified constant, without a storage class.  Only the
289 // constants valid in constant expressions can occur here.
290 void AsmPrinter::EmitConstantValueOnly(const Constant *CV) {
291   if (CV->isNullValue() || isa<UndefValue>(CV))
292     O << "0";
293   else if (const ConstantBool *CB = dyn_cast<ConstantBool>(CV)) {
294     assert(CB == ConstantBool::True);
295     O << "1";
296   } else if (const ConstantSInt *CI = dyn_cast<ConstantSInt>(CV))
297     if (((CI->getValue() << 32) >> 32) == CI->getValue())
298       O << CI->getValue();
299     else
300       O << (uint64_t)CI->getValue();
301   else if (const ConstantUInt *CI = dyn_cast<ConstantUInt>(CV))
302     O << CI->getValue();
303   else if (const GlobalValue *GV = dyn_cast<GlobalValue>(CV)) {
304     // This is a constant address for a global variable or function. Use the
305     // name of the variable or function as the address value, possibly
306     // decorating it with GlobalVarAddrPrefix/Suffix or
307     // FunctionAddrPrefix/Suffix (these all default to "" )
308     if (isa<Function>(GV))
309       O << FunctionAddrPrefix << Mang->getValueName(GV) << FunctionAddrSuffix;
310     else
311       O << GlobalVarAddrPrefix << Mang->getValueName(GV) << GlobalVarAddrSuffix;
312   } else if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV)) {
313     const TargetData *TD = TM.getTargetData();
314     switch(CE->getOpcode()) {
315     case Instruction::GetElementPtr: {
316       // generate a symbolic expression for the byte address
317       const Constant *ptrVal = CE->getOperand(0);
318       std::vector<Value*> idxVec(CE->op_begin()+1, CE->op_end());
319       if (int64_t Offset = TD->getIndexedOffset(ptrVal->getType(), idxVec)) {
320         if (Offset)
321           O << "(";
322         EmitConstantValueOnly(ptrVal);
323         if (Offset > 0)
324           O << ") + " << Offset;
325         else if (Offset < 0)
326           O << ") - " << -Offset;
327       } else {
328         EmitConstantValueOnly(ptrVal);
329       }
330       break;
331     }
332     case Instruction::Cast: {
333       // Support only non-converting or widening casts for now, that is, ones
334       // that do not involve a change in value.  This assertion is really gross,
335       // and may not even be a complete check.
336       Constant *Op = CE->getOperand(0);
337       const Type *OpTy = Op->getType(), *Ty = CE->getType();
338
339       // Remember, kids, pointers can be losslessly converted back and forth
340       // into 32-bit or wider integers, regardless of signedness. :-P
341       assert(((isa<PointerType>(OpTy)
342                && (Ty == Type::LongTy || Ty == Type::ULongTy
343                    || Ty == Type::IntTy || Ty == Type::UIntTy))
344               || (isa<PointerType>(Ty)
345                   && (OpTy == Type::LongTy || OpTy == Type::ULongTy
346                       || OpTy == Type::IntTy || OpTy == Type::UIntTy))
347               || (((TD->getTypeSize(Ty) >= TD->getTypeSize(OpTy))
348                    && OpTy->isLosslesslyConvertibleTo(Ty))))
349              && "FIXME: Don't yet support this kind of constant cast expr");
350       EmitConstantValueOnly(Op);
351       break;
352     }
353     case Instruction::Add:
354       O << "(";
355       EmitConstantValueOnly(CE->getOperand(0));
356       O << ") + (";
357       EmitConstantValueOnly(CE->getOperand(1));
358       O << ")";
359       break;
360     default:
361       assert(0 && "Unsupported operator!");
362     }
363   } else {
364     assert(0 && "Unknown constant value!");
365   }
366 }
367
368 /// toOctal - Convert the low order bits of X into an octal digit.
369 ///
370 static inline char toOctal(int X) {
371   return (X&7)+'0';
372 }
373
374 /// printAsCString - Print the specified array as a C compatible string, only if
375 /// the predicate isString is true.
376 ///
377 static void printAsCString(std::ostream &O, const ConstantArray *CVA,
378                            unsigned LastElt) {
379   assert(CVA->isString() && "Array is not string compatible!");
380
381   O << "\"";
382   for (unsigned i = 0; i != LastElt; ++i) {
383     unsigned char C =
384         (unsigned char)cast<ConstantInt>(CVA->getOperand(i))->getRawValue();
385
386     if (C == '"') {
387       O << "\\\"";
388     } else if (C == '\\') {
389       O << "\\\\";
390     } else if (isprint(C)) {
391       O << C;
392     } else {
393       switch(C) {
394       case '\b': O << "\\b"; break;
395       case '\f': O << "\\f"; break;
396       case '\n': O << "\\n"; break;
397       case '\r': O << "\\r"; break;
398       case '\t': O << "\\t"; break;
399       default:
400         O << '\\';
401         O << toOctal(C >> 6);
402         O << toOctal(C >> 3);
403         O << toOctal(C >> 0);
404         break;
405       }
406     }
407   }
408   O << "\"";
409 }
410
411 /// EmitString - Emit a zero-byte-terminated string constant.
412 ///
413 void AsmPrinter::EmitString(const ConstantArray *CVA) const {
414   unsigned NumElts = CVA->getNumOperands();
415   if (AscizDirective && NumElts && 
416       cast<ConstantInt>(CVA->getOperand(NumElts-1))->getRawValue() == 0) {
417     O << AscizDirective;
418     printAsCString(O, CVA, NumElts-1);
419   } else {
420     O << AsciiDirective;
421     printAsCString(O, CVA, NumElts);
422   }
423   O << "\n";
424 }
425
426 /// EmitGlobalConstant - Print a general LLVM constant to the .s file.
427 ///
428 void AsmPrinter::EmitGlobalConstant(const Constant *CV) {
429   const TargetData *TD = TM.getTargetData();
430
431   if (CV->isNullValue() || isa<UndefValue>(CV)) {
432     EmitZeros(TD->getTypeSize(CV->getType()));
433     return;
434   } else if (const ConstantArray *CVA = dyn_cast<ConstantArray>(CV)) {
435     if (CVA->isString()) {
436       EmitString(CVA);
437     } else { // Not a string.  Print the values in successive locations
438       for (unsigned i = 0, e = CVA->getNumOperands(); i != e; ++i)
439         EmitGlobalConstant(CVA->getOperand(i));
440     }
441     return;
442   } else if (const ConstantStruct *CVS = dyn_cast<ConstantStruct>(CV)) {
443     // Print the fields in successive locations. Pad to align if needed!
444     const StructLayout *cvsLayout = TD->getStructLayout(CVS->getType());
445     uint64_t sizeSoFar = 0;
446     for (unsigned i = 0, e = CVS->getNumOperands(); i != e; ++i) {
447       const Constant* field = CVS->getOperand(i);
448
449       // Check if padding is needed and insert one or more 0s.
450       uint64_t fieldSize = TD->getTypeSize(field->getType());
451       uint64_t padSize = ((i == e-1? cvsLayout->StructSize
452                            : cvsLayout->MemberOffsets[i+1])
453                           - cvsLayout->MemberOffsets[i]) - fieldSize;
454       sizeSoFar += fieldSize + padSize;
455
456       // Now print the actual field value
457       EmitGlobalConstant(field);
458
459       // Insert the field padding unless it's zero bytes...
460       EmitZeros(padSize);
461     }
462     assert(sizeSoFar == cvsLayout->StructSize &&
463            "Layout of constant struct may be incorrect!");
464     return;
465   } else if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CV)) {
466     // FP Constants are printed as integer constants to avoid losing
467     // precision...
468     double Val = CFP->getValue();
469     if (CFP->getType() == Type::DoubleTy) {
470       if (Data64bitsDirective)
471         O << Data64bitsDirective << DoubleToBits(Val) << "\t" << CommentString
472           << " double value: " << Val << "\n";
473       else if (TD->isBigEndian()) {
474         O << Data32bitsDirective << unsigned(DoubleToBits(Val) >> 32)
475           << "\t" << CommentString << " double most significant word "
476           << Val << "\n";
477         O << Data32bitsDirective << unsigned(DoubleToBits(Val))
478           << "\t" << CommentString << " double least significant word "
479           << Val << "\n";
480       } else {
481         O << Data32bitsDirective << unsigned(DoubleToBits(Val))
482           << "\t" << CommentString << " double least significant word " << Val
483           << "\n";
484         O << Data32bitsDirective << unsigned(DoubleToBits(Val) >> 32)
485           << "\t" << CommentString << " double most significant word " << Val
486           << "\n";
487       }
488       return;
489     } else {
490       O << Data32bitsDirective << FloatToBits(Val) << "\t" << CommentString
491         << " float " << Val << "\n";
492       return;
493     }
494   } else if (CV->getType() == Type::ULongTy || CV->getType() == Type::LongTy) {
495     if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV)) {
496       uint64_t Val = CI->getRawValue();
497
498       if (Data64bitsDirective)
499         O << Data64bitsDirective << Val << "\n";
500       else if (TD->isBigEndian()) {
501         O << Data32bitsDirective << unsigned(Val >> 32)
502           << "\t" << CommentString << " Double-word most significant word "
503           << Val << "\n";
504         O << Data32bitsDirective << unsigned(Val)
505           << "\t" << CommentString << " Double-word least significant word "
506           << Val << "\n";
507       } else {
508         O << Data32bitsDirective << unsigned(Val)
509           << "\t" << CommentString << " Double-word least significant word "
510           << Val << "\n";
511         O << Data32bitsDirective << unsigned(Val >> 32)
512           << "\t" << CommentString << " Double-word most significant word "
513           << Val << "\n";
514       }
515       return;
516     }
517   } else if (const ConstantPacked *CP = dyn_cast<ConstantPacked>(CV)) {
518     const PackedType *PTy = CP->getType();
519     
520     for (unsigned I = 0, E = PTy->getNumElements(); I < E; ++I)
521       EmitGlobalConstant(CP->getOperand(I));
522     
523     return;
524   }
525
526   const Type *type = CV->getType();
527   switch (type->getTypeID()) {
528   case Type::BoolTyID:
529   case Type::UByteTyID: case Type::SByteTyID:
530     O << Data8bitsDirective;
531     break;
532   case Type::UShortTyID: case Type::ShortTyID:
533     O << Data16bitsDirective;
534     break;
535   case Type::PointerTyID:
536     if (TD->getPointerSize() == 8) {
537       O << Data64bitsDirective;
538       break;
539     }
540     //Fall through for pointer size == int size
541   case Type::UIntTyID: case Type::IntTyID:
542     O << Data32bitsDirective;
543     break;
544   case Type::ULongTyID: case Type::LongTyID:
545     assert(Data64bitsDirective &&"Target cannot handle 64-bit constant exprs!");
546     O << Data64bitsDirective;
547     break;
548   case Type::FloatTyID: case Type::DoubleTyID:
549     assert (0 && "Should have already output floating point constant.");
550   default:
551     assert (0 && "Can't handle printing this type of thing");
552     break;
553   }
554   EmitConstantValueOnly(CV);
555   O << "\n";
556 }
557
558 /// printInlineAsm - This method formats and prints the specified machine
559 /// instruction that is an inline asm.
560 void AsmPrinter::printInlineAsm(const MachineInstr *MI) const {
561   O << InlineAsmStart << "\n\t";
562   unsigned NumOperands = MI->getNumOperands();
563   
564   // Count the number of register definitions.
565   unsigned NumDefs = 0;
566   for (; MI->getOperand(NumDefs).isDef(); ++NumDefs)
567     assert(NumDefs != NumOperands-1 && "No asm string?");
568   
569   assert(MI->getOperand(NumDefs).isExternalSymbol() && "No asm string?");
570
571   // Disassemble the AsmStr, printing out the literal pieces, the operands, etc.
572   const char *AsmStr = MI->getOperand(NumDefs).getSymbolName();
573
574   // The variant of the current asmprinter: FIXME: change.
575   int AsmPrinterVariant = 0;
576   
577   int CurVariant = -1;            // The number of the {.|.|.} region we are in.
578   const char *LastEmitted = AsmStr; // One past the last character emitted.
579   
580   while (*LastEmitted) {
581     switch (*LastEmitted) {
582     default: {
583       // Not a special case, emit the string section literally.
584       const char *LiteralEnd = LastEmitted+1;
585       while (*LiteralEnd && *LiteralEnd != '{' && *LiteralEnd != '|' &&
586              *LiteralEnd != '}' && *LiteralEnd != '$' && *LiteralEnd != '\n')
587         ++LiteralEnd;
588       if (CurVariant == -1 || CurVariant == AsmPrinterVariant)
589         O.write(LastEmitted, LiteralEnd-LastEmitted);
590       LastEmitted = LiteralEnd;
591       break;
592     }
593     case '\n':
594       ++LastEmitted;   // Consume newline character.
595       O << "\n\t";     // Indent code with newline.
596       break;
597     case '$': {
598       ++LastEmitted;   // Consume '$' character.
599       if (*LastEmitted == '$') { // $$ -> $
600         if (CurVariant == -1 || CurVariant == AsmPrinterVariant)
601           O << '$';
602         ++LastEmitted;  // Consume second '$' character.
603         break;
604       }
605       
606       bool HasCurlyBraces = false;
607       if (*LastEmitted == '{') {     // ${variable}
608         ++LastEmitted;               // Consume '{' character.
609         HasCurlyBraces = true;
610       }
611       
612       const char *IDStart = LastEmitted;
613       char *IDEnd;
614       long Val = strtol(IDStart, &IDEnd, 10); // We only accept numbers for IDs.
615       if (!isdigit(*IDStart) || (Val == 0 && errno == EINVAL)) {
616         std::cerr << "Bad $ operand number in inline asm string: '" 
617                   << AsmStr << "'\n";
618         exit(1);
619       }
620       LastEmitted = IDEnd;
621       
622       char Modifier[2] = { 0, 0 };
623       
624       if (HasCurlyBraces) {
625         // If we have curly braces, check for a modifier character.  This
626         // supports syntax like ${0:u}, which correspond to "%u0" in GCC asm.
627         if (*LastEmitted == ':') {
628           ++LastEmitted;    // Consume ':' character.
629           if (*LastEmitted == 0) {
630             std::cerr << "Bad ${:} expression in inline asm string: '" 
631                       << AsmStr << "'\n";
632             exit(1);
633           }
634           
635           Modifier[0] = *LastEmitted;
636           ++LastEmitted;    // Consume modifier character.
637         }
638         
639         if (*LastEmitted != '}') {
640           std::cerr << "Bad ${} expression in inline asm string: '" 
641                     << AsmStr << "'\n";
642           exit(1);
643         }
644         ++LastEmitted;    // Consume '}' character.
645       }
646       
647       if ((unsigned)Val >= NumOperands-1) {
648         std::cerr << "Invalid $ operand number in inline asm string: '" 
649                   << AsmStr << "'\n";
650         exit(1);
651       }
652       
653       // Okay, we finally have a value number.  Ask the target to print this
654       // operand!
655       if (CurVariant == -1 || CurVariant == AsmPrinterVariant) {
656         unsigned OpNo = 1;
657         
658         // Scan to find the machine operand number for the operand.
659         for (; Val; --Val) {
660           unsigned OpFlags = MI->getOperand(OpNo).getImmedValue();
661           OpNo += (OpFlags >> 3) + 1;
662         }
663         
664         unsigned OpFlags = MI->getOperand(OpNo).getImmedValue();
665         ++OpNo;  // Skip over the ID number.
666
667         bool Error;
668         AsmPrinter *AP = const_cast<AsmPrinter*>(this);
669         if ((OpFlags & 7) == 4 /*ADDR MODE*/) {
670           Error = AP->PrintAsmMemoryOperand(MI, OpNo, AsmPrinterVariant,
671                                             Modifier[0] ? Modifier : 0);
672         } else {
673           Error = AP->PrintAsmOperand(MI, OpNo, AsmPrinterVariant,
674                                       Modifier[0] ? Modifier : 0);
675         }
676         if (Error) {
677           std::cerr << "Invalid operand found in inline asm: '"
678                     << AsmStr << "'\n";
679           MI->dump();
680           exit(1);
681         }
682       }
683       break;
684     }
685     case '{':
686       ++LastEmitted;      // Consume '{' character.
687       if (CurVariant != -1) {
688         std::cerr << "Nested variants found in inline asm string: '"
689                   << AsmStr << "'\n";
690         exit(1);
691       }
692       CurVariant = 0;     // We're in the first variant now.
693       break;
694     case '|':
695       ++LastEmitted;  // consume '|' character.
696       if (CurVariant == -1) {
697         std::cerr << "Found '|' character outside of variant in inline asm "
698                   << "string: '" << AsmStr << "'\n";
699         exit(1);
700       }
701       ++CurVariant;   // We're in the next variant.
702       break;
703     case '}':
704       ++LastEmitted;  // consume '}' character.
705       if (CurVariant == -1) {
706         std::cerr << "Found '}' character outside of variant in inline asm "
707                   << "string: '" << AsmStr << "'\n";
708         exit(1);
709       }
710       CurVariant = -1;
711       break;
712     }
713   }
714   O << "\n\t" << InlineAsmEnd << "\n";
715 }
716
717 /// PrintAsmOperand - Print the specified operand of MI, an INLINEASM
718 /// instruction, using the specified assembler variant.  Targets should
719 /// overried this to format as appropriate.
720 bool AsmPrinter::PrintAsmOperand(const MachineInstr *MI, unsigned OpNo,
721                                  unsigned AsmVariant, const char *ExtraCode) {
722   // Target doesn't support this yet!
723   return true;
724 }
725
726 bool AsmPrinter::PrintAsmMemoryOperand(const MachineInstr *MI, unsigned OpNo,
727                                        unsigned AsmVariant,
728                                        const char *ExtraCode) {
729   // Target doesn't support this yet!
730   return true;
731 }
732
733 /// printBasicBlockLabel - This method prints the label for the specified
734 /// MachineBasicBlock
735 void AsmPrinter::printBasicBlockLabel(const MachineBasicBlock *MBB,
736                                       bool printColon,
737                                       bool printComment) const {
738   O << PrivateGlobalPrefix << "BB" << FunctionNumber << "_"
739     << MBB->getNumber();
740   if (printColon)
741     O << ':';
742   if (printComment)
743     O << '\t' << CommentString << MBB->getBasicBlock()->getName();
744 }