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