Adjust how LLVM names are produced:
[oota-llvm.git] / lib / VMCore / AsmWriter.cpp
1 //===-- AsmWriter.cpp - Printing LLVM as an assembly file -----------------===//
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 library implements the functionality defined in llvm/Assembly/Writer.h
11 //
12 // Note that these routines must be extremely tolerant of various errors in the
13 // LLVM code, because it can be used for debugging transformations.
14 //
15 //===----------------------------------------------------------------------===//
16
17 #include "llvm/Assembly/Writer.h"
18 #include "llvm/Assembly/PrintModulePass.h"
19 #include "llvm/Assembly/AsmAnnotationWriter.h"
20 #include "llvm/CallingConv.h"
21 #include "llvm/Constants.h"
22 #include "llvm/DerivedTypes.h"
23 #include "llvm/ParameterAttributes.h"
24 #include "llvm/InlineAsm.h"
25 #include "llvm/Instruction.h"
26 #include "llvm/Instructions.h"
27 #include "llvm/Module.h"
28 #include "llvm/ValueSymbolTable.h"
29 #include "llvm/TypeSymbolTable.h"
30 #include "llvm/ADT/StringExtras.h"
31 #include "llvm/ADT/STLExtras.h"
32 #include "llvm/Support/CFG.h"
33 #include "llvm/Support/MathExtras.h"
34 #include "llvm/Support/Streams.h"
35 #include <algorithm>
36 #include <cctype>
37 using namespace llvm;
38
39 namespace llvm {
40
41 // Make virtual table appear in this compilation unit.
42 AssemblyAnnotationWriter::~AssemblyAnnotationWriter() {}
43
44 /// This class provides computation of slot numbers for LLVM Assembly writing.
45 /// @brief LLVM Assembly Writing Slot Computation.
46 class SlotMachine {
47
48 /// @name Types
49 /// @{
50 public:
51
52   /// @brief A mapping of Values to slot numbers
53   typedef std::map<const Value*,unsigned> ValueMap;
54
55 /// @}
56 /// @name Constructors
57 /// @{
58 public:
59   /// @brief Construct from a module
60   SlotMachine(const Module *M);
61
62   /// @brief Construct from a function, starting out in incorp state.
63   SlotMachine(const Function *F);
64
65 /// @}
66 /// @name Accessors
67 /// @{
68 public:
69   /// Return the slot number of the specified value in it's type
70   /// plane.  If something is not in the SlotMachine, return -1.
71   int getLocalSlot(const Value *V);
72   int getGlobalSlot(const GlobalValue *V);
73
74 /// @}
75 /// @name Mutators
76 /// @{
77 public:
78   /// If you'd like to deal with a function instead of just a module, use
79   /// this method to get its data into the SlotMachine.
80   void incorporateFunction(const Function *F) {
81     TheFunction = F;
82     FunctionProcessed = false;
83   }
84
85   /// After calling incorporateFunction, use this method to remove the
86   /// most recently incorporated function from the SlotMachine. This
87   /// will reset the state of the machine back to just the module contents.
88   void purgeFunction();
89
90 /// @}
91 /// @name Implementation Details
92 /// @{
93 private:
94   /// This function does the actual initialization.
95   inline void initialize();
96
97   /// CreateModuleSlot - Insert the specified GlobalValue* into the slot table.
98   void CreateModuleSlot(const GlobalValue *V);
99   
100   /// CreateFunctionSlot - Insert the specified Value* into the slot table.
101   void CreateFunctionSlot(const Value *V);
102
103   /// Add all of the module level global variables (and their initializers)
104   /// and function declarations, but not the contents of those functions.
105   void processModule();
106
107   /// Add all of the functions arguments, basic blocks, and instructions
108   void processFunction();
109
110   SlotMachine(const SlotMachine &);  // DO NOT IMPLEMENT
111   void operator=(const SlotMachine &);  // DO NOT IMPLEMENT
112
113 /// @}
114 /// @name Data
115 /// @{
116 public:
117
118   /// @brief The module for which we are holding slot numbers
119   const Module* TheModule;
120
121   /// @brief The function for which we are holding slot numbers
122   const Function* TheFunction;
123   bool FunctionProcessed;
124
125   /// @brief The TypePlanes map for the module level data
126   ValueMap mMap;
127   unsigned mNext;
128
129   /// @brief The TypePlanes map for the function level data
130   ValueMap fMap;
131   unsigned fNext;
132
133 /// @}
134
135 };
136
137 }  // end namespace llvm
138
139 char PrintModulePass::ID = 0;
140 static RegisterPass<PrintModulePass>
141 X("printm", "Print module to stderr");
142 char PrintFunctionPass::ID = 0;
143 static RegisterPass<PrintFunctionPass>
144 Y("print","Print function to stderr");
145
146 static void WriteAsOperandInternal(std::ostream &Out, const Value *V,
147                                std::map<const Type *, std::string> &TypeTable,
148                                    SlotMachine *Machine);
149
150 static const Module *getModuleFromVal(const Value *V) {
151   if (const Argument *MA = dyn_cast<Argument>(V))
152     return MA->getParent() ? MA->getParent()->getParent() : 0;
153   else if (const BasicBlock *BB = dyn_cast<BasicBlock>(V))
154     return BB->getParent() ? BB->getParent()->getParent() : 0;
155   else if (const Instruction *I = dyn_cast<Instruction>(V)) {
156     const Function *M = I->getParent() ? I->getParent()->getParent() : 0;
157     return M ? M->getParent() : 0;
158   } else if (const GlobalValue *GV = dyn_cast<GlobalValue>(V))
159     return GV->getParent();
160   return 0;
161 }
162
163 static SlotMachine *createSlotMachine(const Value *V) {
164   if (const Argument *FA = dyn_cast<Argument>(V)) {
165     return new SlotMachine(FA->getParent());
166   } else if (const Instruction *I = dyn_cast<Instruction>(V)) {
167     return new SlotMachine(I->getParent()->getParent());
168   } else if (const BasicBlock *BB = dyn_cast<BasicBlock>(V)) {
169     return new SlotMachine(BB->getParent());
170   } else if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(V)){
171     return new SlotMachine(GV->getParent());
172   } else if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(V)){
173     return new SlotMachine(GA->getParent());    
174   } else if (const Function *Func = dyn_cast<Function>(V)) {
175     return new SlotMachine(Func);
176   }
177   return 0;
178 }
179
180 /// NameNeedsQuotes - Return true if the specified llvm name should be wrapped
181 /// with ""'s.
182 static std::string QuoteNameIfNeeded(const std::string &Name) {
183   std::string result;
184   bool needsQuotes = Name[0] >= '0' && Name[0] <= '9';
185   // Scan the name to see if it needs quotes and to replace funky chars with
186   // their octal equivalent.
187   for (unsigned i = 0, e = Name.size(); i != e; ++i) {
188     char C = Name[i];
189     assert(C != '"' && "Illegal character in LLVM value name!");
190     if (isalnum(C) || C == '-' || C == '.' || C == '_')
191       result += C;
192     else if (isprint(C)) {
193       needsQuotes = true;
194       result += C;
195     } else {
196       needsQuotes = true;
197       result += "\\";
198       char hex1 = C & 0x0F;
199       if (hex1 < 10)
200         result += hex1 + '0';
201       else 
202         result += hex1 - 10 + 'A';
203       char hex2 = (C >> 4) & 0x0F;
204       if (hex2 < 10)
205         result += hex2 + '0';
206       else 
207         result += hex2 - 10 + 'A';
208     }
209   }
210   if (needsQuotes) {
211     result.insert(0,"\"");
212     result += '"';
213   }
214   return result;
215 }
216
217 enum PrefixType {
218   GlobalPrefix,
219   LabelPrefix,
220   LocalPrefix
221 };
222
223 /// getLLVMName - Turn the specified string into an 'LLVM name', which is either
224 /// prefixed with % (if the string only contains simple characters) or is
225 /// surrounded with ""'s (if it has special chars in it).
226 static std::string getLLVMName(const std::string &Name, PrefixType Prefix) {
227   assert(!Name.empty() && "Cannot get empty name!");
228   switch (Prefix) {
229   default: assert(0 && "Bad prefix!");
230   case GlobalPrefix: return '@' + QuoteNameIfNeeded(Name);
231   case LabelPrefix:  return QuoteNameIfNeeded(Name);
232   case LocalPrefix:  return '%' + QuoteNameIfNeeded(Name);
233   }      
234 }
235
236
237 /// fillTypeNameTable - If the module has a symbol table, take all global types
238 /// and stuff their names into the TypeNames map.
239 ///
240 static void fillTypeNameTable(const Module *M,
241                               std::map<const Type *, std::string> &TypeNames) {
242   if (!M) return;
243   const TypeSymbolTable &ST = M->getTypeSymbolTable();
244   TypeSymbolTable::const_iterator TI = ST.begin();
245   for (; TI != ST.end(); ++TI) {
246     // As a heuristic, don't insert pointer to primitive types, because
247     // they are used too often to have a single useful name.
248     //
249     const Type *Ty = cast<Type>(TI->second);
250     if (!isa<PointerType>(Ty) ||
251         !cast<PointerType>(Ty)->getElementType()->isPrimitiveType() ||
252         !cast<PointerType>(Ty)->getElementType()->isInteger() ||
253         isa<OpaqueType>(cast<PointerType>(Ty)->getElementType()))
254       TypeNames.insert(std::make_pair(Ty, getLLVMName(TI->first, LocalPrefix)));
255   }
256 }
257
258
259
260 static void calcTypeName(const Type *Ty,
261                          std::vector<const Type *> &TypeStack,
262                          std::map<const Type *, std::string> &TypeNames,
263                          std::string & Result){
264   if (Ty->isInteger() || (Ty->isPrimitiveType() && !isa<OpaqueType>(Ty))) {
265     Result += Ty->getDescription();  // Base case
266     return;
267   }
268
269   // Check to see if the type is named.
270   std::map<const Type *, std::string>::iterator I = TypeNames.find(Ty);
271   if (I != TypeNames.end()) {
272     Result += I->second;
273     return;
274   }
275
276   if (isa<OpaqueType>(Ty)) {
277     Result += "opaque";
278     return;
279   }
280
281   // Check to see if the Type is already on the stack...
282   unsigned Slot = 0, CurSize = TypeStack.size();
283   while (Slot < CurSize && TypeStack[Slot] != Ty) ++Slot; // Scan for type
284
285   // This is another base case for the recursion.  In this case, we know
286   // that we have looped back to a type that we have previously visited.
287   // Generate the appropriate upreference to handle this.
288   if (Slot < CurSize) {
289     Result += "\\" + utostr(CurSize-Slot);     // Here's the upreference
290     return;
291   }
292
293   TypeStack.push_back(Ty);    // Recursive case: Add us to the stack..
294
295   switch (Ty->getTypeID()) {
296   case Type::IntegerTyID: {
297     unsigned BitWidth = cast<IntegerType>(Ty)->getBitWidth();
298     Result += "i" + utostr(BitWidth);
299     break;
300   }
301   case Type::FunctionTyID: {
302     const FunctionType *FTy = cast<FunctionType>(Ty);
303     calcTypeName(FTy->getReturnType(), TypeStack, TypeNames, Result);
304     Result += " (";
305     unsigned Idx = 1;
306     const ParamAttrsList *Attrs = FTy->getParamAttrs();
307     for (FunctionType::param_iterator I = FTy->param_begin(),
308            E = FTy->param_end(); I != E; ++I) {
309       if (I != FTy->param_begin())
310         Result += ", ";
311       calcTypeName(*I, TypeStack, TypeNames, Result);
312       if (Attrs && Attrs->getParamAttrs(Idx) != ParamAttr::None) {
313         Result += + " ";
314         Result += Attrs->getParamAttrsTextByIndex(Idx);
315       }
316       Idx++;
317     }
318     if (FTy->isVarArg()) {
319       if (FTy->getNumParams()) Result += ", ";
320       Result += "...";
321     }
322     Result += ")";
323     if (Attrs && Attrs->getParamAttrs(0) != ParamAttr::None) {
324       Result += " ";
325       Result += Attrs->getParamAttrsTextByIndex(0);
326     }
327     break;
328   }
329   case Type::StructTyID: {
330     const StructType *STy = cast<StructType>(Ty);
331     if (STy->isPacked())
332       Result += '<';
333     Result += "{ ";
334     for (StructType::element_iterator I = STy->element_begin(),
335            E = STy->element_end(); I != E; ++I) {
336       if (I != STy->element_begin())
337         Result += ", ";
338       calcTypeName(*I, TypeStack, TypeNames, Result);
339     }
340     Result += " }";
341     if (STy->isPacked())
342       Result += '>';
343     break;
344   }
345   case Type::PointerTyID:
346     calcTypeName(cast<PointerType>(Ty)->getElementType(),
347                           TypeStack, TypeNames, Result);
348     Result += "*";
349     break;
350   case Type::ArrayTyID: {
351     const ArrayType *ATy = cast<ArrayType>(Ty);
352     Result += "[" + utostr(ATy->getNumElements()) + " x ";
353     calcTypeName(ATy->getElementType(), TypeStack, TypeNames, Result);
354     Result += "]";
355     break;
356   }
357   case Type::VectorTyID: {
358     const VectorType *PTy = cast<VectorType>(Ty);
359     Result += "<" + utostr(PTy->getNumElements()) + " x ";
360     calcTypeName(PTy->getElementType(), TypeStack, TypeNames, Result);
361     Result += ">";
362     break;
363   }
364   case Type::OpaqueTyID:
365     Result += "opaque";
366     break;
367   default:
368     Result += "<unrecognized-type>";
369     break;
370   }
371
372   TypeStack.pop_back();       // Remove self from stack...
373 }
374
375
376 /// printTypeInt - The internal guts of printing out a type that has a
377 /// potentially named portion.
378 ///
379 static std::ostream &printTypeInt(std::ostream &Out, const Type *Ty,
380                               std::map<const Type *, std::string> &TypeNames) {
381   // Primitive types always print out their description, regardless of whether
382   // they have been named or not.
383   //
384   if (Ty->isInteger() || (Ty->isPrimitiveType() && !isa<OpaqueType>(Ty)))
385     return Out << Ty->getDescription();
386
387   // Check to see if the type is named.
388   std::map<const Type *, std::string>::iterator I = TypeNames.find(Ty);
389   if (I != TypeNames.end()) return Out << I->second;
390
391   // Otherwise we have a type that has not been named but is a derived type.
392   // Carefully recurse the type hierarchy to print out any contained symbolic
393   // names.
394   //
395   std::vector<const Type *> TypeStack;
396   std::string TypeName;
397   calcTypeName(Ty, TypeStack, TypeNames, TypeName);
398   TypeNames.insert(std::make_pair(Ty, TypeName));//Cache type name for later use
399   return (Out << TypeName);
400 }
401
402
403 /// WriteTypeSymbolic - This attempts to write the specified type as a symbolic
404 /// type, iff there is an entry in the modules symbol table for the specified
405 /// type or one of it's component types. This is slower than a simple x << Type
406 ///
407 std::ostream &llvm::WriteTypeSymbolic(std::ostream &Out, const Type *Ty,
408                                       const Module *M) {
409   Out << ' ';
410
411   // If they want us to print out a type, but there is no context, we can't
412   // print it symbolically.
413   if (!M)
414     return Out << Ty->getDescription();
415     
416   std::map<const Type *, std::string> TypeNames;
417   fillTypeNameTable(M, TypeNames);
418   return printTypeInt(Out, Ty, TypeNames);
419 }
420
421 // PrintEscapedString - Print each character of the specified string, escaping
422 // it if it is not printable or if it is an escape char.
423 static void PrintEscapedString(const std::string &Str, std::ostream &Out) {
424   for (unsigned i = 0, e = Str.size(); i != e; ++i) {
425     unsigned char C = Str[i];
426     if (isprint(C) && C != '"' && C != '\\') {
427       Out << C;
428     } else {
429       Out << '\\'
430           << (char) ((C/16  < 10) ? ( C/16 +'0') : ( C/16 -10+'A'))
431           << (char)(((C&15) < 10) ? ((C&15)+'0') : ((C&15)-10+'A'));
432     }
433   }
434 }
435
436 static const char *getPredicateText(unsigned predicate) {
437   const char * pred = "unknown";
438   switch (predicate) {
439     case FCmpInst::FCMP_FALSE: pred = "false"; break;
440     case FCmpInst::FCMP_OEQ:   pred = "oeq"; break;
441     case FCmpInst::FCMP_OGT:   pred = "ogt"; break;
442     case FCmpInst::FCMP_OGE:   pred = "oge"; break;
443     case FCmpInst::FCMP_OLT:   pred = "olt"; break;
444     case FCmpInst::FCMP_OLE:   pred = "ole"; break;
445     case FCmpInst::FCMP_ONE:   pred = "one"; break;
446     case FCmpInst::FCMP_ORD:   pred = "ord"; break;
447     case FCmpInst::FCMP_UNO:   pred = "uno"; break;
448     case FCmpInst::FCMP_UEQ:   pred = "ueq"; break;
449     case FCmpInst::FCMP_UGT:   pred = "ugt"; break;
450     case FCmpInst::FCMP_UGE:   pred = "uge"; break;
451     case FCmpInst::FCMP_ULT:   pred = "ult"; break;
452     case FCmpInst::FCMP_ULE:   pred = "ule"; break;
453     case FCmpInst::FCMP_UNE:   pred = "une"; break;
454     case FCmpInst::FCMP_TRUE:  pred = "true"; break;
455     case ICmpInst::ICMP_EQ:    pred = "eq"; break;
456     case ICmpInst::ICMP_NE:    pred = "ne"; break;
457     case ICmpInst::ICMP_SGT:   pred = "sgt"; break;
458     case ICmpInst::ICMP_SGE:   pred = "sge"; break;
459     case ICmpInst::ICMP_SLT:   pred = "slt"; break;
460     case ICmpInst::ICMP_SLE:   pred = "sle"; break;
461     case ICmpInst::ICMP_UGT:   pred = "ugt"; break;
462     case ICmpInst::ICMP_UGE:   pred = "uge"; break;
463     case ICmpInst::ICMP_ULT:   pred = "ult"; break;
464     case ICmpInst::ICMP_ULE:   pred = "ule"; break;
465   }
466   return pred;
467 }
468
469 /// @brief Internal constant writer.
470 static void WriteConstantInt(std::ostream &Out, const Constant *CV,
471                              std::map<const Type *, std::string> &TypeTable,
472                              SlotMachine *Machine) {
473   const int IndentSize = 4;
474   static std::string Indent = "\n";
475   if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV)) {
476     if (CI->getType() == Type::Int1Ty) 
477       Out << (CI->getZExtValue() ? "true" : "false");
478     else 
479       Out << CI->getValue().toStringSigned(10);
480   } else if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CV)) {
481     // We would like to output the FP constant value in exponential notation,
482     // but we cannot do this if doing so will lose precision.  Check here to
483     // make sure that we only output it in exponential format if we can parse
484     // the value back and get the same value.
485     //
486     std::string StrVal = ftostr(CFP->getValue());
487
488     // Check to make sure that the stringized number is not some string like
489     // "Inf" or NaN, that atof will accept, but the lexer will not.  Check that
490     // the string matches the "[-+]?[0-9]" regex.
491     //
492     if ((StrVal[0] >= '0' && StrVal[0] <= '9') ||
493         ((StrVal[0] == '-' || StrVal[0] == '+') &&
494          (StrVal[1] >= '0' && StrVal[1] <= '9')))
495       // Reparse stringized version!
496       if (atof(StrVal.c_str()) == CFP->getValue()) {
497         Out << StrVal;
498         return;
499       }
500
501     // Otherwise we could not reparse it to exactly the same value, so we must
502     // output the string in hexadecimal format!
503     assert(sizeof(double) == sizeof(uint64_t) &&
504            "assuming that double is 64 bits!");
505     Out << "0x" << utohexstr(DoubleToBits(CFP->getValue()));
506
507   } else if (isa<ConstantAggregateZero>(CV)) {
508     Out << "zeroinitializer";
509   } else if (const ConstantArray *CA = dyn_cast<ConstantArray>(CV)) {
510     // As a special case, print the array as a string if it is an array of
511     // ubytes or an array of sbytes with positive values.
512     //
513     const Type *ETy = CA->getType()->getElementType();
514     if (CA->isString()) {
515       Out << "c\"";
516       PrintEscapedString(CA->getAsString(), Out);
517       Out << "\"";
518
519     } else {                // Cannot output in string format...
520       Out << '[';
521       if (CA->getNumOperands()) {
522         Out << ' ';
523         printTypeInt(Out, ETy, TypeTable);
524         WriteAsOperandInternal(Out, CA->getOperand(0),
525                                TypeTable, Machine);
526         for (unsigned i = 1, e = CA->getNumOperands(); i != e; ++i) {
527           Out << ", ";
528           printTypeInt(Out, ETy, TypeTable);
529           WriteAsOperandInternal(Out, CA->getOperand(i), TypeTable, Machine);
530         }
531       }
532       Out << " ]";
533     }
534   } else if (const ConstantStruct *CS = dyn_cast<ConstantStruct>(CV)) {
535     if (CS->getType()->isPacked())
536       Out << '<';
537     Out << '{';
538     unsigned N = CS->getNumOperands();
539     if (N) {
540       if (N > 2) {
541         Indent += std::string(IndentSize, ' ');
542         Out << Indent;
543       } else {
544         Out << ' ';
545       }
546       printTypeInt(Out, CS->getOperand(0)->getType(), TypeTable);
547
548       WriteAsOperandInternal(Out, CS->getOperand(0), TypeTable, Machine);
549
550       for (unsigned i = 1; i < N; i++) {
551         Out << ", ";
552         if (N > 2) Out << Indent;
553         printTypeInt(Out, CS->getOperand(i)->getType(), TypeTable);
554
555         WriteAsOperandInternal(Out, CS->getOperand(i), TypeTable, Machine);
556       }
557       if (N > 2) Indent.resize(Indent.size() - IndentSize);
558     }
559  
560     Out << " }";
561     if (CS->getType()->isPacked())
562       Out << '>';
563   } else if (const ConstantVector *CP = dyn_cast<ConstantVector>(CV)) {
564       const Type *ETy = CP->getType()->getElementType();
565       assert(CP->getNumOperands() > 0 &&
566              "Number of operands for a PackedConst must be > 0");
567       Out << '<';
568       Out << ' ';
569       printTypeInt(Out, ETy, TypeTable);
570       WriteAsOperandInternal(Out, CP->getOperand(0), TypeTable, Machine);
571       for (unsigned i = 1, e = CP->getNumOperands(); i != e; ++i) {
572           Out << ", ";
573           printTypeInt(Out, ETy, TypeTable);
574           WriteAsOperandInternal(Out, CP->getOperand(i), TypeTable, Machine);
575       }
576       Out << " >";
577   } else if (isa<ConstantPointerNull>(CV)) {
578     Out << "null";
579
580   } else if (isa<UndefValue>(CV)) {
581     Out << "undef";
582
583   } else if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV)) {
584     Out << CE->getOpcodeName();
585     if (CE->isCompare())
586       Out << " " << getPredicateText(CE->getPredicate());
587     Out << " (";
588
589     for (User::const_op_iterator OI=CE->op_begin(); OI != CE->op_end(); ++OI) {
590       printTypeInt(Out, (*OI)->getType(), TypeTable);
591       WriteAsOperandInternal(Out, *OI, TypeTable, Machine);
592       if (OI+1 != CE->op_end())
593         Out << ", ";
594     }
595
596     if (CE->isCast()) {
597       Out << " to ";
598       printTypeInt(Out, CE->getType(), TypeTable);
599     }
600
601     Out << ')';
602
603   } else {
604     Out << "<placeholder or erroneous Constant>";
605   }
606 }
607
608
609 /// WriteAsOperand - Write the name of the specified value out to the specified
610 /// ostream.  This can be useful when you just want to print int %reg126, not
611 /// the whole instruction that generated it.
612 ///
613 static void WriteAsOperandInternal(std::ostream &Out, const Value *V,
614                                   std::map<const Type*, std::string> &TypeTable,
615                                    SlotMachine *Machine) {
616   Out << ' ';
617   if (V->hasName())
618     Out << getLLVMName(V->getName(),
619                        isa<GlobalValue>(V) ? GlobalPrefix : LocalPrefix);
620   else {
621     const Constant *CV = dyn_cast<Constant>(V);
622     if (CV && !isa<GlobalValue>(CV)) {
623       WriteConstantInt(Out, CV, TypeTable, Machine);
624     } else if (const InlineAsm *IA = dyn_cast<InlineAsm>(V)) {
625       Out << "asm ";
626       if (IA->hasSideEffects())
627         Out << "sideeffect ";
628       Out << '"';
629       PrintEscapedString(IA->getAsmString(), Out);
630       Out << "\", \"";
631       PrintEscapedString(IA->getConstraintString(), Out);
632       Out << '"';
633     } else {
634       char Prefix = '%';
635       int Slot;
636       if (Machine) {
637         if (const GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
638           Slot = Machine->getGlobalSlot(GV);
639           Prefix = '@';
640         } else {
641           Slot = Machine->getLocalSlot(V);
642         }
643       } else {
644         Machine = createSlotMachine(V);
645         if (Machine) {
646           if (const GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
647             Slot = Machine->getGlobalSlot(GV);
648             Prefix = '@';
649           } else {
650             Slot = Machine->getLocalSlot(V);
651           }
652         } else {
653           Slot = -1;
654         }
655         delete Machine;
656       }
657       if (Slot != -1)
658         Out << Prefix << Slot;
659       else
660         Out << "<badref>";
661     }
662   }
663 }
664
665 /// WriteAsOperand - Write the name of the specified value out to the specified
666 /// ostream.  This can be useful when you just want to print int %reg126, not
667 /// the whole instruction that generated it.
668 ///
669 std::ostream &llvm::WriteAsOperand(std::ostream &Out, const Value *V,
670                                    bool PrintType, const Module *Context) {
671   std::map<const Type *, std::string> TypeNames;
672   if (Context == 0) Context = getModuleFromVal(V);
673
674   if (Context)
675     fillTypeNameTable(Context, TypeNames);
676
677   if (PrintType)
678     printTypeInt(Out, V->getType(), TypeNames);
679
680   WriteAsOperandInternal(Out, V, TypeNames, 0);
681   return Out;
682 }
683
684
685 namespace llvm {
686
687 class AssemblyWriter {
688   std::ostream &Out;
689   SlotMachine &Machine;
690   const Module *TheModule;
691   std::map<const Type *, std::string> TypeNames;
692   AssemblyAnnotationWriter *AnnotationWriter;
693 public:
694   inline AssemblyWriter(std::ostream &o, SlotMachine &Mac, const Module *M,
695                         AssemblyAnnotationWriter *AAW)
696     : Out(o), Machine(Mac), TheModule(M), AnnotationWriter(AAW) {
697
698     // If the module has a symbol table, take all global types and stuff their
699     // names into the TypeNames map.
700     //
701     fillTypeNameTable(M, TypeNames);
702   }
703
704   inline void write(const Module *M)         { printModule(M);       }
705   inline void write(const GlobalVariable *G) { printGlobal(G);       }
706   inline void write(const GlobalAlias *G)    { printAlias(G);        }
707   inline void write(const Function *F)       { printFunction(F);     }
708   inline void write(const BasicBlock *BB)    { printBasicBlock(BB);  }
709   inline void write(const Instruction *I)    { printInstruction(*I); }
710   inline void write(const Type *Ty)          { printType(Ty);        }
711
712   void writeOperand(const Value *Op, bool PrintType);
713
714   const Module* getModule() { return TheModule; }
715
716 private:
717   void printModule(const Module *M);
718   void printTypeSymbolTable(const TypeSymbolTable &ST);
719   void printGlobal(const GlobalVariable *GV);
720   void printAlias(const GlobalAlias *GV);
721   void printFunction(const Function *F);
722   void printArgument(const Argument *FA, uint16_t ParamAttrs);
723   void printBasicBlock(const BasicBlock *BB);
724   void printInstruction(const Instruction &I);
725
726   // printType - Go to extreme measures to attempt to print out a short,
727   // symbolic version of a type name.
728   //
729   std::ostream &printType(const Type *Ty) {
730     return printTypeInt(Out, Ty, TypeNames);
731   }
732
733   // printTypeAtLeastOneLevel - Print out one level of the possibly complex type
734   // without considering any symbolic types that we may have equal to it.
735   //
736   std::ostream &printTypeAtLeastOneLevel(const Type *Ty);
737
738   // printInfoComment - Print a little comment after the instruction indicating
739   // which slot it occupies.
740   void printInfoComment(const Value &V);
741 };
742 }  // end of llvm namespace
743
744 /// printTypeAtLeastOneLevel - Print out one level of the possibly complex type
745 /// without considering any symbolic types that we may have equal to it.
746 ///
747 std::ostream &AssemblyWriter::printTypeAtLeastOneLevel(const Type *Ty) {
748   if (const IntegerType *ITy = dyn_cast<IntegerType>(Ty))
749     Out << "i" << utostr(ITy->getBitWidth());
750   else if (const FunctionType *FTy = dyn_cast<FunctionType>(Ty)) {
751     printType(FTy->getReturnType());
752     Out << " (";
753     unsigned Idx = 1;
754     const ParamAttrsList *Attrs = FTy->getParamAttrs();
755     for (FunctionType::param_iterator I = FTy->param_begin(),
756            E = FTy->param_end(); I != E; ++I) {
757       if (I != FTy->param_begin())
758         Out << ", ";
759       printType(*I);
760       if (Attrs && Attrs->getParamAttrs(Idx) != ParamAttr::None) {
761         Out << " " << Attrs->getParamAttrsTextByIndex(Idx);
762       }
763       Idx++;
764     }
765     if (FTy->isVarArg()) {
766       if (FTy->getNumParams()) Out << ", ";
767       Out << "...";
768     }
769     Out << ')';
770     if (Attrs && Attrs->getParamAttrs(0) != ParamAttr::None)
771       Out << ' ' << Attrs->getParamAttrsTextByIndex(0);
772   } else if (const StructType *STy = dyn_cast<StructType>(Ty)) {
773     if (STy->isPacked())
774       Out << '<';
775     Out << "{ ";
776     for (StructType::element_iterator I = STy->element_begin(),
777            E = STy->element_end(); I != E; ++I) {
778       if (I != STy->element_begin())
779         Out << ", ";
780       printType(*I);
781     }
782     Out << " }";
783     if (STy->isPacked())
784       Out << '>';
785   } else if (const PointerType *PTy = dyn_cast<PointerType>(Ty)) {
786     printType(PTy->getElementType()) << '*';
787   } else if (const ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
788     Out << '[' << ATy->getNumElements() << " x ";
789     printType(ATy->getElementType()) << ']';
790   } else if (const VectorType *PTy = dyn_cast<VectorType>(Ty)) {
791     Out << '<' << PTy->getNumElements() << " x ";
792     printType(PTy->getElementType()) << '>';
793   }
794   else if (isa<OpaqueType>(Ty)) {
795     Out << "opaque";
796   } else {
797     if (!Ty->isPrimitiveType())
798       Out << "<unknown derived type>";
799     printType(Ty);
800   }
801   return Out;
802 }
803
804
805 void AssemblyWriter::writeOperand(const Value *Operand, bool PrintType) {
806   if (Operand == 0) {
807     Out << "<null operand!>";
808   } else {
809     if (PrintType) { Out << ' '; printType(Operand->getType()); }
810     WriteAsOperandInternal(Out, Operand, TypeNames, &Machine);
811   }
812 }
813
814
815 void AssemblyWriter::printModule(const Module *M) {
816   if (!M->getModuleIdentifier().empty() &&
817       // Don't print the ID if it will start a new line (which would
818       // require a comment char before it).
819       M->getModuleIdentifier().find('\n') == std::string::npos)
820     Out << "; ModuleID = '" << M->getModuleIdentifier() << "'\n";
821
822   if (!M->getDataLayout().empty())
823     Out << "target datalayout = \"" << M->getDataLayout() << "\"\n";
824   if (!M->getTargetTriple().empty())
825     Out << "target triple = \"" << M->getTargetTriple() << "\"\n";
826
827   if (!M->getModuleInlineAsm().empty()) {
828     // Split the string into lines, to make it easier to read the .ll file.
829     std::string Asm = M->getModuleInlineAsm();
830     size_t CurPos = 0;
831     size_t NewLine = Asm.find_first_of('\n', CurPos);
832     while (NewLine != std::string::npos) {
833       // We found a newline, print the portion of the asm string from the
834       // last newline up to this newline.
835       Out << "module asm \"";
836       PrintEscapedString(std::string(Asm.begin()+CurPos, Asm.begin()+NewLine),
837                          Out);
838       Out << "\"\n";
839       CurPos = NewLine+1;
840       NewLine = Asm.find_first_of('\n', CurPos);
841     }
842     Out << "module asm \"";
843     PrintEscapedString(std::string(Asm.begin()+CurPos, Asm.end()), Out);
844     Out << "\"\n";
845   }
846   
847   // Loop over the dependent libraries and emit them.
848   Module::lib_iterator LI = M->lib_begin();
849   Module::lib_iterator LE = M->lib_end();
850   if (LI != LE) {
851     Out << "deplibs = [ ";
852     while (LI != LE) {
853       Out << '"' << *LI << '"';
854       ++LI;
855       if (LI != LE)
856         Out << ", ";
857     }
858     Out << " ]\n";
859   }
860
861   // Loop over the symbol table, emitting all named constants.
862   printTypeSymbolTable(M->getTypeSymbolTable());
863
864   for (Module::const_global_iterator I = M->global_begin(), E = M->global_end();
865        I != E; ++I)
866     printGlobal(I);
867   
868   // Output all aliases.
869   if (!M->alias_empty()) Out << "\n";
870   for (Module::const_alias_iterator I = M->alias_begin(), E = M->alias_end();
871        I != E; ++I)
872     printAlias(I);
873
874   // Output all of the functions.
875   for (Module::const_iterator I = M->begin(), E = M->end(); I != E; ++I)
876     printFunction(I);
877 }
878
879 void AssemblyWriter::printGlobal(const GlobalVariable *GV) {
880   if (GV->hasName()) Out << getLLVMName(GV->getName(), GlobalPrefix) << " = ";
881
882   if (!GV->hasInitializer())
883     switch (GV->getLinkage()) {
884      case GlobalValue::DLLImportLinkage:   Out << "dllimport "; break;
885      case GlobalValue::ExternalWeakLinkage: Out << "extern_weak "; break;
886      default: Out << "external "; break;
887     } else {
888     switch (GV->getLinkage()) {
889     case GlobalValue::InternalLinkage:     Out << "internal "; break;
890     case GlobalValue::LinkOnceLinkage:     Out << "linkonce "; break;
891     case GlobalValue::WeakLinkage:         Out << "weak "; break;
892     case GlobalValue::AppendingLinkage:    Out << "appending "; break;
893     case GlobalValue::DLLImportLinkage:    Out << "dllimport "; break;
894     case GlobalValue::DLLExportLinkage:    Out << "dllexport "; break;     
895     case GlobalValue::ExternalWeakLinkage: Out << "extern_weak "; break;
896     case GlobalValue::ExternalLinkage:     break;
897     case GlobalValue::GhostLinkage:
898       cerr << "GhostLinkage not allowed in AsmWriter!\n";
899       abort();
900     }
901     switch (GV->getVisibility()) {
902     default: assert(0 && "Invalid visibility style!");
903     case GlobalValue::DefaultVisibility: break;
904     case GlobalValue::HiddenVisibility: Out << "hidden "; break;
905     case GlobalValue::ProtectedVisibility: Out << "protected "; break;
906     }
907   }
908
909   if (GV->isThreadLocal()) Out << "thread_local ";
910   Out << (GV->isConstant() ? "constant " : "global ");
911   printType(GV->getType()->getElementType());
912
913   if (GV->hasInitializer()) {
914     Constant* C = cast<Constant>(GV->getInitializer());
915     assert(C &&  "GlobalVar initializer isn't constant?");
916     writeOperand(GV->getInitializer(), false);
917   }
918
919   if (GV->hasSection())
920     Out << ", section \"" << GV->getSection() << '"';
921   if (GV->getAlignment())
922     Out << ", align " << GV->getAlignment();
923
924   printInfoComment(*GV);
925   Out << "\n";
926 }
927
928 void AssemblyWriter::printAlias(const GlobalAlias *GA) {
929   Out << getLLVMName(GA->getName(), GlobalPrefix) << " = ";
930   switch (GA->getVisibility()) {
931   default: assert(0 && "Invalid visibility style!");
932   case GlobalValue::DefaultVisibility: break;
933   case GlobalValue::HiddenVisibility: Out << "hidden "; break;
934   case GlobalValue::ProtectedVisibility: Out << "protected "; break;
935   }
936
937   Out << "alias ";
938
939   switch (GA->getLinkage()) {
940   case GlobalValue::WeakLinkage: Out << "weak "; break;
941   case GlobalValue::InternalLinkage: Out << "internal "; break;
942   case GlobalValue::ExternalLinkage: break;
943   default:
944    assert(0 && "Invalid alias linkage");
945   }
946   
947   const Constant *Aliasee = GA->getAliasee();
948     
949   if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(Aliasee)) {
950     printType(GV->getType());
951     Out << " " << getLLVMName(GV->getName(), GlobalPrefix);
952   } else if (const Function *F = dyn_cast<Function>(Aliasee)) {
953     printType(F->getFunctionType());
954     Out << "* ";
955
956     if (!F->getName().empty())
957       Out << getLLVMName(F->getName(), GlobalPrefix);
958     else
959       Out << "@\"\"";
960   } else {
961     const ConstantExpr *CE = 0;
962     if ((CE = dyn_cast<ConstantExpr>(Aliasee)) &&
963         (CE->getOpcode() == Instruction::BitCast)) {
964       writeOperand(CE, false);    
965     } else
966       assert(0 && "Unsupported aliasee");
967   }
968   
969   printInfoComment(*GA);
970   Out << "\n";
971 }
972
973 void AssemblyWriter::printTypeSymbolTable(const TypeSymbolTable &ST) {
974   // Print the types.
975   for (TypeSymbolTable::const_iterator TI = ST.begin(), TE = ST.end();
976        TI != TE; ++TI) {
977     Out << "\t" << getLLVMName(TI->first, LocalPrefix) << " = type ";
978
979     // Make sure we print out at least one level of the type structure, so
980     // that we do not get %FILE = type %FILE
981     //
982     printTypeAtLeastOneLevel(TI->second) << "\n";
983   }
984 }
985
986 /// printFunction - Print all aspects of a function.
987 ///
988 void AssemblyWriter::printFunction(const Function *F) {
989   // Print out the return type and name...
990   Out << "\n";
991
992   if (AnnotationWriter) AnnotationWriter->emitFunctionAnnot(F, Out);
993
994   if (F->isDeclaration())
995     switch (F->getLinkage()) {
996     case GlobalValue::DLLImportLinkage:    Out << "declare dllimport "; break;
997     case GlobalValue::ExternalWeakLinkage: Out << "declare extern_weak "; break;
998     default: Out << "declare ";
999     }
1000   else {
1001     Out << "define ";
1002     switch (F->getLinkage()) {
1003     case GlobalValue::InternalLinkage:     Out << "internal "; break;
1004     case GlobalValue::LinkOnceLinkage:     Out << "linkonce "; break;
1005     case GlobalValue::WeakLinkage:         Out << "weak "; break;
1006     case GlobalValue::AppendingLinkage:    Out << "appending "; break;
1007     case GlobalValue::DLLImportLinkage:    Out << "dllimport "; break;
1008     case GlobalValue::DLLExportLinkage:    Out << "dllexport "; break;
1009     case GlobalValue::ExternalWeakLinkage: Out << "extern_weak "; break;      
1010     case GlobalValue::ExternalLinkage: break;
1011     case GlobalValue::GhostLinkage:
1012       cerr << "GhostLinkage not allowed in AsmWriter!\n";
1013       abort();
1014     }
1015     switch (F->getVisibility()) {
1016     default: assert(0 && "Invalid visibility style!");
1017     case GlobalValue::DefaultVisibility: break;
1018     case GlobalValue::HiddenVisibility: Out << "hidden "; break;
1019     case GlobalValue::ProtectedVisibility: Out << "protected "; break;
1020     }
1021   }
1022
1023   // Print the calling convention.
1024   switch (F->getCallingConv()) {
1025   case CallingConv::C: break;   // default
1026   case CallingConv::Fast:         Out << "fastcc "; break;
1027   case CallingConv::Cold:         Out << "coldcc "; break;
1028   case CallingConv::X86_StdCall:  Out << "x86_stdcallcc "; break;
1029   case CallingConv::X86_FastCall: Out << "x86_fastcallcc "; break; 
1030   default: Out << "cc" << F->getCallingConv() << " "; break;
1031   }
1032
1033   const FunctionType *FT = F->getFunctionType();
1034   const ParamAttrsList *Attrs = FT->getParamAttrs();
1035   printType(F->getReturnType()) << ' ';
1036   if (!F->getName().empty())
1037     Out << getLLVMName(F->getName(), GlobalPrefix);
1038   else
1039     Out << "@\"\"";
1040   Out << '(';
1041   Machine.incorporateFunction(F);
1042
1043   // Loop over the arguments, printing them...
1044
1045   unsigned Idx = 1;
1046   if (!F->isDeclaration()) {
1047     // If this isn't a declaration, print the argument names as well.
1048     for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
1049          I != E; ++I) {
1050       // Insert commas as we go... the first arg doesn't get a comma
1051       if (I != F->arg_begin()) Out << ", ";
1052       printArgument(I, (Attrs ? Attrs->getParamAttrs(Idx)
1053                               : uint16_t(ParamAttr::None)));
1054       Idx++;
1055     }
1056   } else {
1057     // Otherwise, print the types from the function type.
1058     for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
1059       // Insert commas as we go... the first arg doesn't get a comma
1060       if (i) Out << ", ";
1061       
1062       // Output type...
1063       printType(FT->getParamType(i));
1064       
1065       unsigned ArgAttrs = ParamAttr::None;
1066       if (Attrs) ArgAttrs = Attrs->getParamAttrs(i+1);
1067       if (ArgAttrs != ParamAttr::None)
1068         Out << ' ' << ParamAttrsList::getParamAttrsText(ArgAttrs);
1069     }
1070   }
1071
1072   // Finish printing arguments...
1073   if (FT->isVarArg()) {
1074     if (FT->getNumParams()) Out << ", ";
1075     Out << "...";  // Output varargs portion of signature!
1076   }
1077   Out << ')';
1078   if (Attrs && Attrs->getParamAttrs(0) != ParamAttr::None)
1079     Out << ' ' << Attrs->getParamAttrsTextByIndex(0);
1080   if (F->hasSection())
1081     Out << " section \"" << F->getSection() << '"';
1082   if (F->getAlignment())
1083     Out << " align " << F->getAlignment();
1084
1085   if (F->isDeclaration()) {
1086     Out << "\n";
1087   } else {
1088     Out << " {";
1089
1090     // Output all of its basic blocks... for the function
1091     for (Function::const_iterator I = F->begin(), E = F->end(); I != E; ++I)
1092       printBasicBlock(I);
1093
1094     Out << "}\n";
1095   }
1096
1097   Machine.purgeFunction();
1098 }
1099
1100 /// printArgument - This member is called for every argument that is passed into
1101 /// the function.  Simply print it out
1102 ///
1103 void AssemblyWriter::printArgument(const Argument *Arg, uint16_t Attrs) {
1104   // Output type...
1105   printType(Arg->getType());
1106
1107   if (Attrs != ParamAttr::None)
1108     Out << ' ' << ParamAttrsList::getParamAttrsText(Attrs);
1109
1110   // Output name, if available...
1111   if (Arg->hasName())
1112     Out << ' ' << getLLVMName(Arg->getName(), LocalPrefix);
1113 }
1114
1115 /// printBasicBlock - This member is called for each basic block in a method.
1116 ///
1117 void AssemblyWriter::printBasicBlock(const BasicBlock *BB) {
1118   if (BB->hasName()) {              // Print out the label if it exists...
1119     Out << "\n" << getLLVMName(BB->getName(), LabelPrefix) << ':';
1120   } else if (!BB->use_empty()) {      // Don't print block # of no uses...
1121     Out << "\n; <label>:";
1122     int Slot = Machine.getLocalSlot(BB);
1123     if (Slot != -1)
1124       Out << Slot;
1125     else
1126       Out << "<badref>";
1127   }
1128
1129   if (BB->getParent() == 0)
1130     Out << "\t\t; Error: Block without parent!";
1131   else {
1132     if (BB != &BB->getParent()->getEntryBlock()) {  // Not the entry block?
1133       // Output predecessors for the block...
1134       Out << "\t\t;";
1135       pred_const_iterator PI = pred_begin(BB), PE = pred_end(BB);
1136
1137       if (PI == PE) {
1138         Out << " No predecessors!";
1139       } else {
1140         Out << " preds =";
1141         writeOperand(*PI, false);
1142         for (++PI; PI != PE; ++PI) {
1143           Out << ',';
1144           writeOperand(*PI, false);
1145         }
1146       }
1147     }
1148   }
1149
1150   Out << "\n";
1151
1152   if (AnnotationWriter) AnnotationWriter->emitBasicBlockStartAnnot(BB, Out);
1153
1154   // Output all of the instructions in the basic block...
1155   for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I != E; ++I)
1156     printInstruction(*I);
1157
1158   if (AnnotationWriter) AnnotationWriter->emitBasicBlockEndAnnot(BB, Out);
1159 }
1160
1161
1162 /// printInfoComment - Print a little comment after the instruction indicating
1163 /// which slot it occupies.
1164 ///
1165 void AssemblyWriter::printInfoComment(const Value &V) {
1166   if (V.getType() != Type::VoidTy) {
1167     Out << "\t\t; <";
1168     printType(V.getType()) << '>';
1169
1170     if (!V.hasName()) {
1171       int SlotNum;
1172       if (const GlobalValue *GV = dyn_cast<GlobalValue>(&V))
1173         SlotNum = Machine.getGlobalSlot(GV);
1174       else
1175         SlotNum = Machine.getLocalSlot(&V);
1176       if (SlotNum == -1)
1177         Out << ":<badref>";
1178       else
1179         Out << ':' << SlotNum; // Print out the def slot taken.
1180     }
1181     Out << " [#uses=" << V.getNumUses() << ']';  // Output # uses
1182   }
1183 }
1184
1185 // This member is called for each Instruction in a function..
1186 void AssemblyWriter::printInstruction(const Instruction &I) {
1187   if (AnnotationWriter) AnnotationWriter->emitInstructionAnnot(&I, Out);
1188
1189   Out << "\t";
1190
1191   // Print out name if it exists...
1192   if (I.hasName())
1193     Out << getLLVMName(I.getName(), LocalPrefix) << " = ";
1194
1195   // If this is a volatile load or store, print out the volatile marker.
1196   if ((isa<LoadInst>(I)  && cast<LoadInst>(I).isVolatile()) ||
1197       (isa<StoreInst>(I) && cast<StoreInst>(I).isVolatile())) {
1198       Out << "volatile ";
1199   } else if (isa<CallInst>(I) && cast<CallInst>(I).isTailCall()) {
1200     // If this is a call, check if it's a tail call.
1201     Out << "tail ";
1202   }
1203
1204   // Print out the opcode...
1205   Out << I.getOpcodeName();
1206
1207   // Print out the compare instruction predicates
1208   if (const FCmpInst *FCI = dyn_cast<FCmpInst>(&I)) {
1209     Out << " " << getPredicateText(FCI->getPredicate());
1210   } else if (const ICmpInst *ICI = dyn_cast<ICmpInst>(&I)) {
1211     Out << " " << getPredicateText(ICI->getPredicate());
1212   }
1213
1214   // Print out the type of the operands...
1215   const Value *Operand = I.getNumOperands() ? I.getOperand(0) : 0;
1216
1217   // Special case conditional branches to swizzle the condition out to the front
1218   if (isa<BranchInst>(I) && I.getNumOperands() > 1) {
1219     writeOperand(I.getOperand(2), true);
1220     Out << ',';
1221     writeOperand(Operand, true);
1222     Out << ',';
1223     writeOperand(I.getOperand(1), true);
1224
1225   } else if (isa<SwitchInst>(I)) {
1226     // Special case switch statement to get formatting nice and correct...
1227     writeOperand(Operand        , true); Out << ',';
1228     writeOperand(I.getOperand(1), true); Out << " [";
1229
1230     for (unsigned op = 2, Eop = I.getNumOperands(); op < Eop; op += 2) {
1231       Out << "\n\t\t";
1232       writeOperand(I.getOperand(op  ), true); Out << ',';
1233       writeOperand(I.getOperand(op+1), true);
1234     }
1235     Out << "\n\t]";
1236   } else if (isa<PHINode>(I)) {
1237     Out << ' ';
1238     printType(I.getType());
1239     Out << ' ';
1240
1241     for (unsigned op = 0, Eop = I.getNumOperands(); op < Eop; op += 2) {
1242       if (op) Out << ", ";
1243       Out << '[';
1244       writeOperand(I.getOperand(op  ), false); Out << ',';
1245       writeOperand(I.getOperand(op+1), false); Out << " ]";
1246     }
1247   } else if (isa<ReturnInst>(I) && !Operand) {
1248     Out << " void";
1249   } else if (const CallInst *CI = dyn_cast<CallInst>(&I)) {
1250     // Print the calling convention being used.
1251     switch (CI->getCallingConv()) {
1252     case CallingConv::C: break;   // default
1253     case CallingConv::Fast:  Out << " fastcc"; break;
1254     case CallingConv::Cold:  Out << " coldcc"; break;
1255     case CallingConv::X86_StdCall:  Out << "x86_stdcallcc "; break;
1256     case CallingConv::X86_FastCall: Out << "x86_fastcallcc "; break; 
1257     default: Out << " cc" << CI->getCallingConv(); break;
1258     }
1259
1260     const PointerType    *PTy = cast<PointerType>(Operand->getType());
1261     const FunctionType   *FTy = cast<FunctionType>(PTy->getElementType());
1262     const Type         *RetTy = FTy->getReturnType();
1263     const ParamAttrsList *PAL = FTy->getParamAttrs();
1264
1265     // If possible, print out the short form of the call instruction.  We can
1266     // only do this if the first argument is a pointer to a nonvararg function,
1267     // and if the return type is not a pointer to a function.
1268     //
1269     if (!FTy->isVarArg() &&
1270         (!isa<PointerType>(RetTy) ||
1271          !isa<FunctionType>(cast<PointerType>(RetTy)->getElementType()))) {
1272       Out << ' '; printType(RetTy);
1273       writeOperand(Operand, false);
1274     } else {
1275       writeOperand(Operand, true);
1276     }
1277     Out << '(';
1278     for (unsigned op = 1, Eop = I.getNumOperands(); op < Eop; ++op) {
1279       if (op > 1)
1280         Out << ',';
1281       writeOperand(I.getOperand(op), true);
1282       if (PAL && PAL->getParamAttrs(op) != ParamAttr::None)
1283         Out << " " << PAL->getParamAttrsTextByIndex(op);
1284     }
1285     Out << " )";
1286     if (PAL && PAL->getParamAttrs(0) != ParamAttr::None)
1287       Out << ' ' << PAL->getParamAttrsTextByIndex(0);
1288   } else if (const InvokeInst *II = dyn_cast<InvokeInst>(&I)) {
1289     const PointerType    *PTy = cast<PointerType>(Operand->getType());
1290     const FunctionType   *FTy = cast<FunctionType>(PTy->getElementType());
1291     const Type         *RetTy = FTy->getReturnType();
1292     const ParamAttrsList *PAL = FTy->getParamAttrs();
1293
1294     // Print the calling convention being used.
1295     switch (II->getCallingConv()) {
1296     case CallingConv::C: break;   // default
1297     case CallingConv::Fast:  Out << " fastcc"; break;
1298     case CallingConv::Cold:  Out << " coldcc"; break;
1299     case CallingConv::X86_StdCall:  Out << "x86_stdcallcc "; break;
1300     case CallingConv::X86_FastCall: Out << "x86_fastcallcc "; break;
1301     default: Out << " cc" << II->getCallingConv(); break;
1302     }
1303
1304     // If possible, print out the short form of the invoke instruction. We can
1305     // only do this if the first argument is a pointer to a nonvararg function,
1306     // and if the return type is not a pointer to a function.
1307     //
1308     if (!FTy->isVarArg() &&
1309         (!isa<PointerType>(RetTy) ||
1310          !isa<FunctionType>(cast<PointerType>(RetTy)->getElementType()))) {
1311       Out << ' '; printType(RetTy);
1312       writeOperand(Operand, false);
1313     } else {
1314       writeOperand(Operand, true);
1315     }
1316
1317     Out << '(';
1318     for (unsigned op = 3, Eop = I.getNumOperands(); op < Eop; ++op) {
1319       if (op > 3)
1320         Out << ',';
1321       writeOperand(I.getOperand(op), true);
1322       if (PAL && PAL->getParamAttrs(op-2) != ParamAttr::None)
1323         Out << " " << PAL->getParamAttrsTextByIndex(op-2);
1324     }
1325
1326     Out << " )";
1327     if (PAL && PAL->getParamAttrs(0) != ParamAttr::None)
1328       Out << " " << PAL->getParamAttrsTextByIndex(0);
1329     Out << "\n\t\t\tto";
1330     writeOperand(II->getNormalDest(), true);
1331     Out << " unwind";
1332     writeOperand(II->getUnwindDest(), true);
1333
1334   } else if (const AllocationInst *AI = dyn_cast<AllocationInst>(&I)) {
1335     Out << ' ';
1336     printType(AI->getType()->getElementType());
1337     if (AI->isArrayAllocation()) {
1338       Out << ',';
1339       writeOperand(AI->getArraySize(), true);
1340     }
1341     if (AI->getAlignment()) {
1342       Out << ", align " << AI->getAlignment();
1343     }
1344   } else if (isa<CastInst>(I)) {
1345     if (Operand) writeOperand(Operand, true);   // Work with broken code
1346     Out << " to ";
1347     printType(I.getType());
1348   } else if (isa<VAArgInst>(I)) {
1349     if (Operand) writeOperand(Operand, true);   // Work with broken code
1350     Out << ", ";
1351     printType(I.getType());
1352   } else if (Operand) {   // Print the normal way...
1353
1354     // PrintAllTypes - Instructions who have operands of all the same type
1355     // omit the type from all but the first operand.  If the instruction has
1356     // different type operands (for example br), then they are all printed.
1357     bool PrintAllTypes = false;
1358     const Type *TheType = Operand->getType();
1359
1360     // Select, Store and ShuffleVector always print all types.
1361     if (isa<SelectInst>(I) || isa<StoreInst>(I) || isa<ShuffleVectorInst>(I)) {
1362       PrintAllTypes = true;
1363     } else {
1364       for (unsigned i = 1, E = I.getNumOperands(); i != E; ++i) {
1365         Operand = I.getOperand(i);
1366         if (Operand->getType() != TheType) {
1367           PrintAllTypes = true;    // We have differing types!  Print them all!
1368           break;
1369         }
1370       }
1371     }
1372
1373     if (!PrintAllTypes) {
1374       Out << ' ';
1375       printType(TheType);
1376     }
1377
1378     for (unsigned i = 0, E = I.getNumOperands(); i != E; ++i) {
1379       if (i) Out << ',';
1380       writeOperand(I.getOperand(i), PrintAllTypes);
1381     }
1382   }
1383   
1384   // Print post operand alignment for load/store
1385   if (isa<LoadInst>(I) && cast<LoadInst>(I).getAlignment()) {
1386     Out << ", align " << cast<LoadInst>(I).getAlignment();
1387   } else if (isa<StoreInst>(I) && cast<StoreInst>(I).getAlignment()) {
1388     Out << ", align " << cast<StoreInst>(I).getAlignment();
1389   }
1390
1391   printInfoComment(I);
1392   Out << "\n";
1393 }
1394
1395
1396 //===----------------------------------------------------------------------===//
1397 //                       External Interface declarations
1398 //===----------------------------------------------------------------------===//
1399
1400 void Module::print(std::ostream &o, AssemblyAnnotationWriter *AAW) const {
1401   SlotMachine SlotTable(this);
1402   AssemblyWriter W(o, SlotTable, this, AAW);
1403   W.write(this);
1404 }
1405
1406 void GlobalVariable::print(std::ostream &o) const {
1407   SlotMachine SlotTable(getParent());
1408   AssemblyWriter W(o, SlotTable, getParent(), 0);
1409   W.write(this);
1410 }
1411
1412 void GlobalAlias::print(std::ostream &o) const {
1413   SlotMachine SlotTable(getParent());
1414   AssemblyWriter W(o, SlotTable, getParent(), 0);
1415   W.write(this);
1416 }
1417
1418 void Function::print(std::ostream &o, AssemblyAnnotationWriter *AAW) const {
1419   SlotMachine SlotTable(getParent());
1420   AssemblyWriter W(o, SlotTable, getParent(), AAW);
1421
1422   W.write(this);
1423 }
1424
1425 void InlineAsm::print(std::ostream &o, AssemblyAnnotationWriter *AAW) const {
1426   WriteAsOperand(o, this, true, 0);
1427 }
1428
1429 void BasicBlock::print(std::ostream &o, AssemblyAnnotationWriter *AAW) const {
1430   SlotMachine SlotTable(getParent());
1431   AssemblyWriter W(o, SlotTable,
1432                    getParent() ? getParent()->getParent() : 0, AAW);
1433   W.write(this);
1434 }
1435
1436 void Instruction::print(std::ostream &o, AssemblyAnnotationWriter *AAW) const {
1437   const Function *F = getParent() ? getParent()->getParent() : 0;
1438   SlotMachine SlotTable(F);
1439   AssemblyWriter W(o, SlotTable, F ? F->getParent() : 0, AAW);
1440
1441   W.write(this);
1442 }
1443
1444 void Constant::print(std::ostream &o) const {
1445   if (this == 0) { o << "<null> constant value\n"; return; }
1446
1447   o << ' ' << getType()->getDescription() << ' ';
1448
1449   std::map<const Type *, std::string> TypeTable;
1450   WriteConstantInt(o, this, TypeTable, 0);
1451 }
1452
1453 void Type::print(std::ostream &o) const {
1454   if (this == 0)
1455     o << "<null Type>";
1456   else
1457     o << getDescription();
1458 }
1459
1460 void Argument::print(std::ostream &o) const {
1461   WriteAsOperand(o, this, true, getParent() ? getParent()->getParent() : 0);
1462 }
1463
1464 // Value::dump - allow easy printing of  Values from the debugger.
1465 // Located here because so much of the needed functionality is here.
1466 void Value::dump() const { print(*cerr.stream()); cerr << '\n'; }
1467
1468 // Type::dump - allow easy printing of  Values from the debugger.
1469 // Located here because so much of the needed functionality is here.
1470 void Type::dump() const { print(*cerr.stream()); cerr << '\n'; }
1471
1472 void
1473 ParamAttrsList::dump() const {
1474   cerr << "PAL[ ";
1475   for (unsigned i = 0; i < attrs.size(); ++i) {
1476     uint16_t index = getParamIndex(i);
1477     uint16_t attrs = getParamAttrs(index);
1478     cerr << "{" << index << "," << attrs << "} ";
1479   }
1480   cerr << "]\n";
1481 }
1482
1483 //===----------------------------------------------------------------------===//
1484 //                         SlotMachine Implementation
1485 //===----------------------------------------------------------------------===//
1486
1487 #if 0
1488 #define SC_DEBUG(X) cerr << X
1489 #else
1490 #define SC_DEBUG(X)
1491 #endif
1492
1493 // Module level constructor. Causes the contents of the Module (sans functions)
1494 // to be added to the slot table.
1495 SlotMachine::SlotMachine(const Module *M)
1496   : TheModule(M)    ///< Saved for lazy initialization.
1497   , TheFunction(0)
1498   , FunctionProcessed(false)
1499   , mMap(), mNext(0), fMap(), fNext(0)
1500 {
1501 }
1502
1503 // Function level constructor. Causes the contents of the Module and the one
1504 // function provided to be added to the slot table.
1505 SlotMachine::SlotMachine(const Function *F)
1506   : TheModule(F ? F->getParent() : 0) ///< Saved for lazy initialization
1507   , TheFunction(F) ///< Saved for lazy initialization
1508   , FunctionProcessed(false)
1509   , mMap(), mNext(0), fMap(), fNext(0)
1510 {
1511 }
1512
1513 inline void SlotMachine::initialize() {
1514   if (TheModule) {
1515     processModule();
1516     TheModule = 0; ///< Prevent re-processing next time we're called.
1517   }
1518   if (TheFunction && !FunctionProcessed)
1519     processFunction();
1520 }
1521
1522 // Iterate through all the global variables, functions, and global
1523 // variable initializers and create slots for them.
1524 void SlotMachine::processModule() {
1525   SC_DEBUG("begin processModule!\n");
1526
1527   // Add all of the unnamed global variables to the value table.
1528   for (Module::const_global_iterator I = TheModule->global_begin(),
1529        E = TheModule->global_end(); I != E; ++I)
1530     if (!I->hasName()) 
1531       CreateModuleSlot(I);
1532
1533   // Add all the unnamed functions to the table.
1534   for (Module::const_iterator I = TheModule->begin(), E = TheModule->end();
1535        I != E; ++I)
1536     if (!I->hasName())
1537       CreateModuleSlot(I);
1538
1539   SC_DEBUG("end processModule!\n");
1540 }
1541
1542
1543 // Process the arguments, basic blocks, and instructions  of a function.
1544 void SlotMachine::processFunction() {
1545   SC_DEBUG("begin processFunction!\n");
1546   fNext = 0;
1547
1548   // Add all the function arguments with no names.
1549   for(Function::const_arg_iterator AI = TheFunction->arg_begin(),
1550       AE = TheFunction->arg_end(); AI != AE; ++AI)
1551     if (!AI->hasName())
1552       CreateFunctionSlot(AI);
1553
1554   SC_DEBUG("Inserting Instructions:\n");
1555
1556   // Add all of the basic blocks and instructions with no names.
1557   for (Function::const_iterator BB = TheFunction->begin(),
1558        E = TheFunction->end(); BB != E; ++BB) {
1559     if (!BB->hasName())
1560       CreateFunctionSlot(BB);
1561     for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I != E; ++I)
1562       if (I->getType() != Type::VoidTy && !I->hasName())
1563         CreateFunctionSlot(I);
1564   }
1565
1566   FunctionProcessed = true;
1567
1568   SC_DEBUG("end processFunction!\n");
1569 }
1570
1571 /// Clean up after incorporating a function. This is the only way to get out of
1572 /// the function incorporation state that affects get*Slot/Create*Slot. Function
1573 /// incorporation state is indicated by TheFunction != 0.
1574 void SlotMachine::purgeFunction() {
1575   SC_DEBUG("begin purgeFunction!\n");
1576   fMap.clear(); // Simply discard the function level map
1577   TheFunction = 0;
1578   FunctionProcessed = false;
1579   SC_DEBUG("end purgeFunction!\n");
1580 }
1581
1582 /// getGlobalSlot - Get the slot number of a global value.
1583 int SlotMachine::getGlobalSlot(const GlobalValue *V) {
1584   // Check for uninitialized state and do lazy initialization.
1585   initialize();
1586   
1587   // Find the type plane in the module map
1588   ValueMap::const_iterator MI = mMap.find(V);
1589   if (MI == mMap.end()) return -1;
1590
1591   return MI->second;
1592 }
1593
1594
1595 /// getLocalSlot - Get the slot number for a value that is local to a function.
1596 int SlotMachine::getLocalSlot(const Value *V) {
1597   assert(!isa<Constant>(V) && "Can't get a constant or global slot with this!");
1598
1599   // Check for uninitialized state and do lazy initialization.
1600   initialize();
1601
1602   ValueMap::const_iterator FI = fMap.find(V);
1603   if (FI == fMap.end()) return -1;
1604   
1605   return FI->second;
1606 }
1607
1608
1609 /// CreateModuleSlot - Insert the specified GlobalValue* into the slot table.
1610 void SlotMachine::CreateModuleSlot(const GlobalValue *V) {
1611   assert(V && "Can't insert a null Value into SlotMachine!");
1612   assert(V->getType() != Type::VoidTy && "Doesn't need a slot!");
1613   assert(!V->hasName() && "Doesn't need a slot!");
1614   
1615   unsigned DestSlot = mNext++;
1616   mMap[V] = DestSlot;
1617   
1618   SC_DEBUG("  Inserting value [" << V->getType() << "] = " << V << " slot=" <<
1619            DestSlot << " [");
1620   // G = Global, F = Function, A = Alias, o = other
1621   SC_DEBUG((isa<GlobalVariable>(V) ? 'G' :
1622             (isa<Function> ? 'F' :
1623              (isa<GlobalAlias> ? 'A' : 'o'))) << "]\n");
1624 }
1625
1626
1627 /// CreateSlot - Create a new slot for the specified value if it has no name.
1628 void SlotMachine::CreateFunctionSlot(const Value *V) {
1629   const Type *VTy = V->getType();
1630   assert(VTy != Type::VoidTy && !V->hasName() && "Doesn't need a slot!");
1631   
1632   unsigned DestSlot = fNext++;
1633   fMap[V] = DestSlot;
1634   
1635   // G = Global, F = Function, o = other
1636   SC_DEBUG("  Inserting value [" << VTy << "] = " << V << " slot=" <<
1637            DestSlot << " [o]\n");
1638 }