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