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