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