225bd18d8591d7240b674de9376d90f57c478d0a
[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 llvm {
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 }  // end namespace llvm
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 /// @brief Internal constant writer. 
385 static void WriteConstantInt(std::ostream &Out, const Constant *CV, 
386                              bool PrintName,
387                              std::map<const Type *, std::string> &TypeTable,
388                              SlotMachine *Machine) {
389   if (const ConstantBool *CB = dyn_cast<ConstantBool>(CV)) {
390     Out << (CB == ConstantBool::True ? "true" : "false");
391   } else if (const ConstantSInt *CI = dyn_cast<ConstantSInt>(CV)) {
392     Out << CI->getValue();
393   } else if (const ConstantUInt *CI = dyn_cast<ConstantUInt>(CV)) {
394     Out << CI->getValue();
395   } else if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CV)) {
396     // We would like to output the FP constant value in exponential notation,
397     // but we cannot do this if doing so will lose precision.  Check here to
398     // make sure that we only output it in exponential format if we can parse
399     // the value back and get the same value.
400     //
401     std::string StrVal = ftostr(CFP->getValue());
402
403     // Check to make sure that the stringized number is not some string like
404     // "Inf" or NaN, that atof will accept, but the lexer will not.  Check that
405     // the string matches the "[-+]?[0-9]" regex.
406     //
407     if ((StrVal[0] >= '0' && StrVal[0] <= '9') ||
408         ((StrVal[0] == '-' || StrVal[0] == '+') &&
409          (StrVal[1] >= '0' && StrVal[1] <= '9')))
410       // Reparse stringized version!
411       if (atof(StrVal.c_str()) == CFP->getValue()) {
412         Out << StrVal; return;
413       }
414     
415     // Otherwise we could not reparse it to exactly the same value, so we must
416     // output the string in hexadecimal format!
417     //
418     // Behave nicely in the face of C TBAA rules... see:
419     // http://www.nullstone.com/htmls/category/aliastyp.htm
420     //
421     double Val = CFP->getValue();
422     char *Ptr = (char*)&Val;
423     assert(sizeof(double) == sizeof(uint64_t) && sizeof(double) == 8 &&
424            "assuming that double is 64 bits!");
425     Out << "0x" << utohexstr(*(uint64_t*)Ptr);
426
427   } else if (isa<ConstantAggregateZero>(CV)) {
428     Out << "zeroinitializer";
429   } else if (const ConstantArray *CA = dyn_cast<ConstantArray>(CV)) {
430     // As a special case, print the array as a string if it is an array of
431     // ubytes or an array of sbytes with positive values.
432     // 
433     const Type *ETy = CA->getType()->getElementType();
434     bool isString = (ETy == Type::SByteTy || ETy == Type::UByteTy);
435
436     if (ETy == Type::SByteTy)
437       for (unsigned i = 0; i < CA->getNumOperands(); ++i)
438         if (cast<ConstantSInt>(CA->getOperand(i))->getValue() < 0) {
439           isString = false;
440           break;
441         }
442
443     if (isString) {
444       Out << "c\"";
445       for (unsigned i = 0; i < CA->getNumOperands(); ++i) {
446         unsigned char C = 
447           (unsigned char)cast<ConstantInt>(CA->getOperand(i))->getRawValue();
448         
449         if (isprint(C) && C != '"' && C != '\\') {
450           Out << C;
451         } else {
452           Out << '\\'
453               << (char) ((C/16  < 10) ? ( C/16 +'0') : ( C/16 -10+'A'))
454               << (char)(((C&15) < 10) ? ((C&15)+'0') : ((C&15)-10+'A'));
455         }
456       }
457       Out << "\"";
458
459     } else {                // Cannot output in string format...
460       Out << '[';
461       if (CA->getNumOperands()) {
462         Out << ' ';
463         printTypeInt(Out, ETy, TypeTable);
464         WriteAsOperandInternal(Out, CA->getOperand(0),
465                                PrintName, TypeTable, Machine);
466         for (unsigned i = 1, e = CA->getNumOperands(); i != e; ++i) {
467           Out << ", ";
468           printTypeInt(Out, ETy, TypeTable);
469           WriteAsOperandInternal(Out, CA->getOperand(i), PrintName,
470                                  TypeTable, Machine);
471         }
472       }
473       Out << " ]";
474     }
475   } else if (const ConstantStruct *CS = dyn_cast<ConstantStruct>(CV)) {
476     Out << '{';
477     if (CS->getNumOperands()) {
478       Out << ' ';
479       printTypeInt(Out, CS->getOperand(0)->getType(), TypeTable);
480
481       WriteAsOperandInternal(Out, CS->getOperand(0),
482                              PrintName, TypeTable, Machine);
483
484       for (unsigned i = 1; i < CS->getNumOperands(); i++) {
485         Out << ", ";
486         printTypeInt(Out, CS->getOperand(i)->getType(), TypeTable);
487
488         WriteAsOperandInternal(Out, CS->getOperand(i),
489                                PrintName, TypeTable, Machine);
490       }
491     }
492
493     Out << " }";
494   } else if (isa<ConstantPointerNull>(CV)) {
495     Out << "null";
496
497   } else if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV)) {
498     Out << CE->getOpcodeName() << " (";
499     
500     for (User::const_op_iterator OI=CE->op_begin(); OI != CE->op_end(); ++OI) {
501       printTypeInt(Out, (*OI)->getType(), TypeTable);
502       WriteAsOperandInternal(Out, *OI, PrintName, TypeTable, Machine);
503       if (OI+1 != CE->op_end())
504         Out << ", ";
505     }
506     
507     if (CE->getOpcode() == Instruction::Cast) {
508       Out << " to ";
509       printTypeInt(Out, CE->getType(), TypeTable);
510     }
511     Out << ')';
512
513   } else {
514     Out << "<placeholder or erroneous Constant>";
515   }
516 }
517
518
519 /// WriteAsOperand - Write the name of the specified value out to the specified
520 /// ostream.  This can be useful when you just want to print int %reg126, not
521 /// the whole instruction that generated it.
522 ///
523 static void WriteAsOperandInternal(std::ostream &Out, const Value *V, 
524                                    bool PrintName,
525                                   std::map<const Type*, std::string> &TypeTable,
526                                    SlotMachine *Machine) {
527   Out << ' ';
528   if ((PrintName || isa<GlobalValue>(V)) && V->hasName())
529     Out << getLLVMName(V->getName());
530   else {
531     const Constant *CV = dyn_cast<Constant>(V);
532     if (CV && !isa<GlobalValue>(CV))
533       WriteConstantInt(Out, CV, PrintName, TypeTable, Machine);
534     else {
535       int Slot;
536       if (Machine) {
537         Slot = Machine->getSlot(V);
538       } else {
539         Machine = createSlotMachine(V);
540         if (Machine == 0) 
541           Slot = Machine->getSlot(V);
542         else
543           Slot = -1;
544         delete Machine;
545       }
546       if (Slot != -1)
547         Out << '%' << Slot;
548       else
549         Out << "<badref>";
550     }
551   }
552 }
553
554 /// WriteAsOperand - Write the name of the specified value out to the specified
555 /// ostream.  This can be useful when you just want to print int %reg126, not
556 /// the whole instruction that generated it.
557 ///
558 std::ostream &llvm::WriteAsOperand(std::ostream &Out, const Value *V,
559                                    bool PrintType, bool PrintName, 
560                                    const Module *Context) {
561   std::map<const Type *, std::string> TypeNames;
562   if (Context == 0) Context = getModuleFromVal(V);
563
564   if (Context)
565     fillTypeNameTable(Context, TypeNames);
566
567   if (PrintType)
568     printTypeInt(Out, V->getType(), TypeNames);
569   
570   WriteAsOperandInternal(Out, V, PrintName, TypeNames, 0);
571   return Out;
572 }
573
574 /// WriteAsOperandInternal - Write the name of the specified value out to 
575 /// the specified ostream.  This can be useful when you just want to print 
576 /// int %reg126, not the whole instruction that generated it.
577 ///
578 static void WriteAsOperandInternal(std::ostream &Out, const Type *T, 
579                                    bool PrintName,
580                                   std::map<const Type*, std::string> &TypeTable,
581                                    SlotMachine *Machine) {
582   Out << ' ';
583   int Slot;
584   if (Machine) {
585     Slot = Machine->getSlot(T);
586     if (Slot != -1)
587       Out << '%' << Slot;
588     else
589       Out << "<badref>";
590   } else {
591     Out << T->getDescription();
592   }
593 }
594
595 /// WriteAsOperand - Write the name of the specified value out to the specified
596 /// ostream.  This can be useful when you just want to print int %reg126, not
597 /// the whole instruction that generated it.
598 ///
599 std::ostream &llvm::WriteAsOperand(std::ostream &Out, const Type *Ty,
600                                    bool PrintType, bool PrintName, 
601                                    const Module *Context) {
602   std::map<const Type *, std::string> TypeNames;
603   assert(Context != 0 && "Can't write types as operand without module context");
604
605   fillTypeNameTable(Context, TypeNames);
606
607   // if (PrintType)
608     // printTypeInt(Out, V->getType(), TypeNames);
609   
610   printTypeInt(Out, Ty, TypeNames);
611
612   WriteAsOperandInternal(Out, Ty, PrintName, TypeNames, 0);
613   return Out;
614 }
615
616 namespace llvm {
617
618 class AssemblyWriter {
619   std::ostream &Out;
620   SlotMachine &Machine;
621   const Module *TheModule;
622   std::map<const Type *, std::string> TypeNames;
623   AssemblyAnnotationWriter *AnnotationWriter;
624 public:
625   inline AssemblyWriter(std::ostream &o, SlotMachine &Mac, const Module *M,
626                         AssemblyAnnotationWriter *AAW)
627     : Out(o), Machine(Mac), TheModule(M), AnnotationWriter(AAW) {
628
629     // If the module has a symbol table, take all global types and stuff their
630     // names into the TypeNames map.
631     //
632     fillTypeNameTable(M, TypeNames);
633   }
634
635   inline void write(const Module *M)         { printModule(M);      }
636   inline void write(const GlobalVariable *G) { printGlobal(G);      }
637   inline void write(const Function *F)       { printFunction(F);    }
638   inline void write(const BasicBlock *BB)    { printBasicBlock(BB); }
639   inline void write(const Instruction *I)    { printInstruction(*I); }
640   inline void write(const Constant *CPV)     { printConstant(CPV);  }
641   inline void write(const Type *Ty)          { printType(Ty);       }
642
643   void writeOperand(const Value *Op, bool PrintType, bool PrintName = true);
644
645   const Module* getModule() { return TheModule; }
646
647 private :
648   void printModule(const Module *M);
649   void printSymbolTable(const SymbolTable &ST);
650   void printConstant(const Constant *CPV);
651   void printGlobal(const GlobalVariable *GV);
652   void printFunction(const Function *F);
653   void printArgument(const Argument *FA);
654   void printBasicBlock(const BasicBlock *BB);
655   void printInstruction(const Instruction &I);
656
657   // printType - Go to extreme measures to attempt to print out a short,
658   // symbolic version of a type name.
659   //
660   std::ostream &printType(const Type *Ty) {
661     return printTypeInt(Out, Ty, TypeNames);
662   }
663
664   // printTypeAtLeastOneLevel - Print out one level of the possibly complex type
665   // without considering any symbolic types that we may have equal to it.
666   //
667   std::ostream &printTypeAtLeastOneLevel(const Type *Ty);
668
669   // printInfoComment - Print a little comment after the instruction indicating
670   // which slot it occupies.
671   void printInfoComment(const Value &V);
672 };
673 }  // end of llvm namespace
674
675 /// printTypeAtLeastOneLevel - Print out one level of the possibly complex type
676 /// without considering any symbolic types that we may have equal to it.
677 ///
678 std::ostream &AssemblyWriter::printTypeAtLeastOneLevel(const Type *Ty) {
679   if (const FunctionType *FTy = dyn_cast<FunctionType>(Ty)) {
680     printType(FTy->getReturnType()) << " (";
681     for (FunctionType::param_iterator I = FTy->param_begin(),
682            E = FTy->param_end(); I != E; ++I) {
683       if (I != FTy->param_begin())
684         Out << ", ";
685       printType(*I);
686     }
687     if (FTy->isVarArg()) {
688       if (FTy->getNumParams()) Out << ", ";
689       Out << "...";
690     }
691     Out << ')';
692   } else if (const StructType *STy = dyn_cast<StructType>(Ty)) {
693     Out << "{ ";
694     for (StructType::element_iterator I = STy->element_begin(),
695            E = STy->element_end(); I != E; ++I) {
696       if (I != STy->element_begin())
697         Out << ", ";
698       printType(*I);
699     }
700     Out << " }";
701   } else if (const PointerType *PTy = dyn_cast<PointerType>(Ty)) {
702     printType(PTy->getElementType()) << '*';
703   } else if (const ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
704     Out << '[' << ATy->getNumElements() << " x ";
705     printType(ATy->getElementType()) << ']';
706   } else if (const OpaqueType *OTy = dyn_cast<OpaqueType>(Ty)) {
707     Out << "opaque";
708   } else {
709     if (!Ty->isPrimitiveType())
710       Out << "<unknown derived type>";
711     printType(Ty);
712   }
713   return Out;
714 }
715
716
717 void AssemblyWriter::writeOperand(const Value *Operand, bool PrintType, 
718                                   bool PrintName) {
719   if (PrintType) { Out << ' '; printType(Operand->getType()); }
720   WriteAsOperandInternal(Out, Operand, PrintName, TypeNames, &Machine);
721 }
722
723
724 void AssemblyWriter::printModule(const Module *M) {
725   switch (M->getEndianness()) {
726   case Module::LittleEndian: Out << "target endian = little\n"; break;
727   case Module::BigEndian:    Out << "target endian = big\n";    break;
728   case Module::AnyEndianness: break;
729   }
730   switch (M->getPointerSize()) {
731   case Module::Pointer32:    Out << "target pointersize = 32\n"; break;
732   case Module::Pointer64:    Out << "target pointersize = 64\n"; break;
733   case Module::AnyPointerSize: break;
734   }
735   
736   // Loop over the symbol table, emitting all named constants...
737   printSymbolTable(M->getSymbolTable());
738   
739   for (Module::const_giterator I = M->gbegin(), E = M->gend(); I != E; ++I)
740     printGlobal(I);
741
742   Out << "\nimplementation   ; Functions:\n";
743   
744   // Output all of the functions...
745   for (Module::const_iterator I = M->begin(), E = M->end(); I != E; ++I)
746     printFunction(I);
747 }
748
749 void AssemblyWriter::printGlobal(const GlobalVariable *GV) {
750   if (GV->hasName()) Out << getLLVMName(GV->getName()) << " = ";
751
752   if (!GV->hasInitializer()) 
753     Out << "external ";
754   else
755     switch (GV->getLinkage()) {
756     case GlobalValue::InternalLinkage:  Out << "internal "; break;
757     case GlobalValue::LinkOnceLinkage:  Out << "linkonce "; break;
758     case GlobalValue::WeakLinkage:      Out << "weak "; break;
759     case GlobalValue::AppendingLinkage: Out << "appending "; break;
760     case GlobalValue::ExternalLinkage: break;
761     }
762
763   Out << (GV->isConstant() ? "constant " : "global ");
764   printType(GV->getType()->getElementType());
765
766   if (GV->hasInitializer()) {
767     Constant* C = cast<Constant>(GV->getInitializer());
768     assert(C &&  "GlobalVar initializer isn't constant?");
769     writeOperand(GV->getInitializer(), false, isa<GlobalValue>(C));
770   }
771
772   printInfoComment(*GV);
773   Out << "\n";
774 }
775
776
777 // printSymbolTable - Run through symbol table looking for constants
778 // and types. Emit their declarations.
779 void AssemblyWriter::printSymbolTable(const SymbolTable &ST) {
780
781   // Print the types.
782   for (SymbolTable::type_const_iterator TI = ST.type_begin();
783        TI != ST.type_end(); ++TI ) {
784     Out << "\t" << getLLVMName(TI->first) << " = type ";
785
786     // Make sure we print out at least one level of the type structure, so
787     // that we do not get %FILE = type %FILE
788     //
789     printTypeAtLeastOneLevel(TI->second) << "\n";
790   }
791     
792   // Print the constants, in type plane order.
793   for (SymbolTable::plane_const_iterator PI = ST.plane_begin();
794        PI != ST.plane_end(); ++PI ) {
795     SymbolTable::value_const_iterator VI = ST.value_begin(PI->first);
796     SymbolTable::value_const_iterator VE = ST.value_end(PI->first);
797
798     for (; VI != VE; ++VI) {
799       const Value* V = VI->second;
800       const Constant *CPV = dyn_cast<Constant>(V) ;
801       if (CPV && !isa<GlobalValue>(V)) {
802         printConstant(CPV);
803       }
804     }
805   }
806 }
807
808
809 /// printConstant - Print out a constant pool entry...
810 ///
811 void AssemblyWriter::printConstant(const Constant *CPV) {
812   // Don't print out unnamed constants, they will be inlined
813   if (!CPV->hasName()) return;
814
815   // Print out name...
816   Out << "\t" << getLLVMName(CPV->getName()) << " =";
817
818   // Write the value out now...
819   writeOperand(CPV, true, false);
820
821   printInfoComment(*CPV);
822   Out << "\n";
823 }
824
825 /// printFunction - Print all aspects of a function.
826 ///
827 void AssemblyWriter::printFunction(const Function *F) {
828   // Print out the return type and name...
829   Out << "\n";
830
831   if (AnnotationWriter) AnnotationWriter->emitFunctionAnnot(F, Out);
832
833   if (F->isExternal())
834     Out << "declare ";
835   else
836     switch (F->getLinkage()) {
837     case GlobalValue::InternalLinkage:  Out << "internal "; break;
838     case GlobalValue::LinkOnceLinkage:  Out << "linkonce "; break;
839     case GlobalValue::WeakLinkage:      Out << "weak "; break;
840     case GlobalValue::AppendingLinkage: Out << "appending "; break;
841     case GlobalValue::ExternalLinkage: break;
842     }
843
844   printType(F->getReturnType()) << ' ';
845   if (!F->getName().empty())
846     Out << getLLVMName(F->getName());
847   else
848     Out << "\"\"";
849   Out << '(';
850   Machine.incorporateFunction(F);
851
852   // Loop over the arguments, printing them...
853   const FunctionType *FT = F->getFunctionType();
854
855   for(Function::const_aiterator I = F->abegin(), E = F->aend(); I != E; ++I)
856     printArgument(I);
857
858   // Finish printing arguments...
859   if (FT->isVarArg()) {
860     if (FT->getNumParams()) Out << ", ";
861     Out << "...";  // Output varargs portion of signature!
862   }
863   Out << ')';
864
865   if (F->isExternal()) {
866     Out << "\n";
867   } else {
868     Out << " {";
869   
870     // Output all of its basic blocks... for the function
871     for (Function::const_iterator I = F->begin(), E = F->end(); I != E; ++I)
872       printBasicBlock(I);
873
874     Out << "}\n";
875   }
876
877   Machine.purgeFunction();
878 }
879
880 /// printArgument - This member is called for every argument that is passed into
881 /// the function.  Simply print it out
882 ///
883 void AssemblyWriter::printArgument(const Argument *Arg) {
884   // Insert commas as we go... the first arg doesn't get a comma
885   if (Arg != &Arg->getParent()->afront()) Out << ", ";
886
887   // Output type...
888   printType(Arg->getType());
889   
890   // Output name, if available...
891   if (Arg->hasName())
892     Out << ' ' << getLLVMName(Arg->getName());
893 }
894
895 /// printBasicBlock - This member is called for each basic block in a method.
896 ///
897 void AssemblyWriter::printBasicBlock(const BasicBlock *BB) {
898   if (BB->hasName()) {              // Print out the label if it exists...
899     Out << "\n" << BB->getName() << ':';
900   } else if (!BB->use_empty()) {      // Don't print block # of no uses...
901     Out << "\n; <label>:";
902     int Slot = Machine.getSlot(BB);
903     if (Slot != -1)
904       Out << Slot;
905     else
906       Out << "<badref>";
907   }
908
909   if (BB->getParent() == 0)
910     Out << "\t\t; Error: Block without parent!";
911   else {
912     if (BB != &BB->getParent()->front()) {  // Not the entry block?
913       // Output predecessors for the block...
914       Out << "\t\t;";
915       pred_const_iterator PI = pred_begin(BB), PE = pred_end(BB);
916       
917       if (PI == PE) {
918         Out << " No predecessors!";
919       } else {
920         Out << " preds =";
921         writeOperand(*PI, false, true);
922         for (++PI; PI != PE; ++PI) {
923           Out << ',';
924           writeOperand(*PI, false, true);
925         }
926       }
927     }
928   }
929   
930   Out << "\n";
931
932   if (AnnotationWriter) AnnotationWriter->emitBasicBlockStartAnnot(BB, Out);
933
934   // Output all of the instructions in the basic block...
935   for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I != E; ++I)
936     printInstruction(*I);
937
938   if (AnnotationWriter) AnnotationWriter->emitBasicBlockEndAnnot(BB, Out);
939 }
940
941
942 /// printInfoComment - Print a little comment after the instruction indicating
943 /// which slot it occupies.
944 ///
945 void AssemblyWriter::printInfoComment(const Value &V) {
946   if (V.getType() != Type::VoidTy) {
947     Out << "\t\t; <";
948     printType(V.getType()) << '>';
949
950     if (!V.hasName()) {
951       int SlotNum = Machine.getSlot(&V);
952       if (SlotNum == -1)
953         Out << ":<badref>";
954       else
955         Out << ':' << SlotNum; // Print out the def slot taken.
956     }
957     Out << " [#uses=" << V.use_size() << ']';  // Output # uses
958   }
959 }
960
961 /// printInstruction - This member is called for each Instruction in a function..
962 ///
963 void AssemblyWriter::printInstruction(const Instruction &I) {
964   if (AnnotationWriter) AnnotationWriter->emitInstructionAnnot(&I, Out);
965
966   Out << "\t";
967
968   // Print out name if it exists...
969   if (I.hasName())
970     Out << getLLVMName(I.getName()) << " = ";
971
972   // If this is a volatile load or store, print out the volatile marker
973   if ((isa<LoadInst>(I)  && cast<LoadInst>(I).isVolatile()) ||
974       (isa<StoreInst>(I) && cast<StoreInst>(I).isVolatile()))
975       Out << "volatile ";
976
977   // Print out the opcode...
978   Out << I.getOpcodeName();
979
980   // Print out the type of the operands...
981   const Value *Operand = I.getNumOperands() ? I.getOperand(0) : 0;
982
983   // Special case conditional branches to swizzle the condition out to the front
984   if (isa<BranchInst>(I) && I.getNumOperands() > 1) {
985     writeOperand(I.getOperand(2), true);
986     Out << ',';
987     writeOperand(Operand, true);
988     Out << ',';
989     writeOperand(I.getOperand(1), true);
990
991   } else if (isa<SwitchInst>(I)) {
992     // Special case switch statement to get formatting nice and correct...
993     writeOperand(Operand        , true); Out << ',';
994     writeOperand(I.getOperand(1), true); Out << " [";
995
996     for (unsigned op = 2, Eop = I.getNumOperands(); op < Eop; op += 2) {
997       Out << "\n\t\t";
998       writeOperand(I.getOperand(op  ), true); Out << ',';
999       writeOperand(I.getOperand(op+1), true);
1000     }
1001     Out << "\n\t]";
1002   } else if (isa<PHINode>(I)) {
1003     Out << ' ';
1004     printType(I.getType());
1005     Out << ' ';
1006
1007     for (unsigned op = 0, Eop = I.getNumOperands(); op < Eop; op += 2) {
1008       if (op) Out << ", ";
1009       Out << '[';  
1010       writeOperand(I.getOperand(op  ), false); Out << ',';
1011       writeOperand(I.getOperand(op+1), false); Out << " ]";
1012     }
1013   } else if (isa<ReturnInst>(I) && !Operand) {
1014     Out << " void";
1015   } else if (isa<CallInst>(I)) {
1016     const PointerType  *PTy = cast<PointerType>(Operand->getType());
1017     const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
1018     const Type       *RetTy = FTy->getReturnType();
1019
1020     // If possible, print out the short form of the call instruction.  We can
1021     // only do this if the first argument is a pointer to a nonvararg function,
1022     // and if the return type is not a pointer to a function.
1023     //
1024     if (!FTy->isVarArg() &&
1025         (!isa<PointerType>(RetTy) || 
1026          !isa<FunctionType>(cast<PointerType>(RetTy)->getElementType()))) {
1027       Out << ' '; printType(RetTy);
1028       writeOperand(Operand, false);
1029     } else {
1030       writeOperand(Operand, true);
1031     }
1032     Out << '(';
1033     if (I.getNumOperands() > 1) writeOperand(I.getOperand(1), true);
1034     for (unsigned op = 2, Eop = I.getNumOperands(); op < Eop; ++op) {
1035       Out << ',';
1036       writeOperand(I.getOperand(op), true);
1037     }
1038
1039     Out << " )";
1040   } else if (const InvokeInst *II = dyn_cast<InvokeInst>(&I)) {
1041     const PointerType  *PTy = cast<PointerType>(Operand->getType());
1042     const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
1043     const Type       *RetTy = FTy->getReturnType();
1044
1045     // If possible, print out the short form of the invoke instruction. We can
1046     // only do this if the first argument is a pointer to a nonvararg function,
1047     // and if the return type is not a pointer to a function.
1048     //
1049     if (!FTy->isVarArg() &&
1050         (!isa<PointerType>(RetTy) || 
1051          !isa<FunctionType>(cast<PointerType>(RetTy)->getElementType()))) {
1052       Out << ' '; printType(RetTy);
1053       writeOperand(Operand, false);
1054     } else {
1055       writeOperand(Operand, true);
1056     }
1057
1058     Out << '(';
1059     if (I.getNumOperands() > 3) writeOperand(I.getOperand(3), true);
1060     for (unsigned op = 4, Eop = I.getNumOperands(); op < Eop; ++op) {
1061       Out << ',';
1062       writeOperand(I.getOperand(op), true);
1063     }
1064
1065     Out << " )\n\t\t\tto";
1066     writeOperand(II->getNormalDest(), true);
1067     Out << " unwind";
1068     writeOperand(II->getUnwindDest(), true);
1069
1070   } else if (const AllocationInst *AI = dyn_cast<AllocationInst>(&I)) {
1071     Out << ' ';
1072     printType(AI->getType()->getElementType());
1073     if (AI->isArrayAllocation()) {
1074       Out << ',';
1075       writeOperand(AI->getArraySize(), true);
1076     }
1077   } else if (isa<CastInst>(I)) {
1078     if (Operand) writeOperand(Operand, true);   // Work with broken code
1079     Out << " to ";
1080     printType(I.getType());
1081   } else if (isa<VAArgInst>(I)) {
1082     if (Operand) writeOperand(Operand, true);   // Work with broken code
1083     Out << ", ";
1084     printType(I.getType());
1085   } else if (const VANextInst *VAN = dyn_cast<VANextInst>(&I)) {
1086     if (Operand) writeOperand(Operand, true);   // Work with broken code
1087     Out << ", ";
1088     printType(VAN->getArgType());
1089   } else if (Operand) {   // Print the normal way...
1090
1091     // PrintAllTypes - Instructions who have operands of all the same type 
1092     // omit the type from all but the first operand.  If the instruction has
1093     // different type operands (for example br), then they are all printed.
1094     bool PrintAllTypes = false;
1095     const Type *TheType = Operand->getType();
1096
1097     // Shift Left & Right print both types even for Ubyte LHS, and select prints
1098     // types even if all operands are bools.
1099     if (isa<ShiftInst>(I) || isa<SelectInst>(I)) {
1100       PrintAllTypes = true;
1101     } else {
1102       for (unsigned i = 1, E = I.getNumOperands(); i != E; ++i) {
1103         Operand = I.getOperand(i);
1104         if (Operand->getType() != TheType) {
1105           PrintAllTypes = true;    // We have differing types!  Print them all!
1106           break;
1107         }
1108       }
1109     }
1110     
1111     if (!PrintAllTypes) {
1112       Out << ' ';
1113       printType(TheType);
1114     }
1115
1116     for (unsigned i = 0, E = I.getNumOperands(); i != E; ++i) {
1117       if (i) Out << ',';
1118       writeOperand(I.getOperand(i), PrintAllTypes);
1119     }
1120   }
1121
1122   printInfoComment(I);
1123   Out << "\n";
1124 }
1125
1126
1127 //===----------------------------------------------------------------------===//
1128 //                       External Interface declarations
1129 //===----------------------------------------------------------------------===//
1130
1131 void Module::print(std::ostream &o, AssemblyAnnotationWriter *AAW) const {
1132   SlotMachine SlotTable(this);
1133   AssemblyWriter W(o, SlotTable, this, AAW);
1134   W.write(this);
1135 }
1136
1137 void GlobalVariable::print(std::ostream &o) const {
1138   SlotMachine SlotTable(getParent());
1139   AssemblyWriter W(o, SlotTable, getParent(), 0);
1140   W.write(this);
1141 }
1142
1143 void Function::print(std::ostream &o, AssemblyAnnotationWriter *AAW) const {
1144   SlotMachine SlotTable(getParent());
1145   AssemblyWriter W(o, SlotTable, getParent(), AAW);
1146
1147   W.write(this);
1148 }
1149
1150 void BasicBlock::print(std::ostream &o, AssemblyAnnotationWriter *AAW) const {
1151   SlotMachine SlotTable(getParent());
1152   AssemblyWriter W(o, SlotTable, 
1153                    getParent() ? getParent()->getParent() : 0, AAW);
1154   W.write(this);
1155 }
1156
1157 void Instruction::print(std::ostream &o, AssemblyAnnotationWriter *AAW) const {
1158   const Function *F = getParent() ? getParent()->getParent() : 0;
1159   SlotMachine SlotTable(F);
1160   AssemblyWriter W(o, SlotTable, F ? F->getParent() : 0, AAW);
1161
1162   W.write(this);
1163 }
1164
1165 void Constant::print(std::ostream &o) const {
1166   if (this == 0) { o << "<null> constant value\n"; return; }
1167
1168   o << ' ' << getType()->getDescription() << ' ';
1169
1170   std::map<const Type *, std::string> TypeTable;
1171   WriteConstantInt(o, this, false, TypeTable, 0);
1172 }
1173
1174 void Type::print(std::ostream &o) const { 
1175   if (this == 0)
1176     o << "<null Type>";
1177   else
1178     o << getDescription();
1179 }
1180
1181 void Argument::print(std::ostream &o) const {
1182   WriteAsOperand(o, this, true, true,
1183                  getParent() ? getParent()->getParent() : 0);
1184 }
1185
1186 // Value::dump - allow easy printing of  Values from the debugger.
1187 // Located here because so much of the needed functionality is here.
1188 void Value::dump() const { print(std::cerr); }
1189
1190 // Type::dump - allow easy printing of  Values from the debugger.
1191 // Located here because so much of the needed functionality is here.
1192 void Type::dump() const { print(std::cerr); }
1193
1194 //===----------------------------------------------------------------------===//
1195 //  CachedWriter Class Implementation
1196 //===----------------------------------------------------------------------===//
1197
1198 void CachedWriter::setModule(const Module *M) {
1199   delete SC; delete AW;
1200   if (M) {
1201     SC = new SlotMachine(M );
1202     AW = new AssemblyWriter(Out, *SC, M, 0);
1203   } else {
1204     SC = 0; AW = 0;
1205   }
1206 }
1207
1208 CachedWriter::~CachedWriter() {
1209   delete AW;
1210   delete SC;
1211 }
1212
1213 CachedWriter &CachedWriter::operator<<(const Value &V) {
1214   assert(AW && SC && "CachedWriter does not have a current module!");
1215   if (const Instruction *I = dyn_cast<Instruction>(&V))
1216     AW->write(I);
1217   else if (const BasicBlock *BB = dyn_cast<BasicBlock>(&V))
1218     AW->write(BB);
1219   else if (const Function *F = dyn_cast<Function>(&V))
1220     AW->write(F);
1221   else if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(&V))
1222     AW->write(GV);
1223   else 
1224     AW->writeOperand(&V, true, true);
1225   return *this;
1226 }
1227
1228 CachedWriter& CachedWriter::operator<<(const Type &Ty) {
1229   if (SymbolicTypes) {
1230     const Module *M = AW->getModule();
1231     if (M) WriteTypeSymbolic(Out, &Ty, M);
1232   } else {
1233     AW->write(&Ty);
1234   }
1235   return *this;
1236 }
1237
1238 //===----------------------------------------------------------------------===//
1239 //===--                    SlotMachine Implementation
1240 //===----------------------------------------------------------------------===//
1241
1242 #if 0
1243 #define SC_DEBUG(X) std::cerr << X
1244 #else
1245 #define SC_DEBUG(X)
1246 #endif
1247
1248 // Module level constructor. Causes the contents of the Module (sans functions)
1249 // to be added to the slot table.
1250 SlotMachine::SlotMachine(const Module *M) 
1251   : TheModule(M)    ///< Saved for lazy initialization.
1252   , TheFunction(0)
1253   , mMap()
1254   , mTypes()
1255   , fMap()
1256   , fTypes()
1257 {
1258 }
1259
1260 // Function level constructor. Causes the contents of the Module and the one
1261 // function provided to be added to the slot table.
1262 SlotMachine::SlotMachine(const Function *F ) 
1263   : TheModule( F ? F->getParent() : 0 ) ///< Saved for lazy initialization
1264   , TheFunction(F) ///< Saved for lazy initialization
1265   , mMap()
1266   , mTypes()
1267   , fMap()
1268   , fTypes()
1269 {
1270 }
1271
1272 inline void SlotMachine::initialize(void) {
1273   if ( TheModule) { 
1274     processModule(); 
1275     TheModule = 0; ///< Prevent re-processing next time we're called.
1276   }
1277   if ( TheFunction ) { 
1278     processFunction(); 
1279   }
1280 }
1281
1282 // Iterate through all the global variables, functions, and global
1283 // variable initializers and create slots for them. 
1284 void SlotMachine::processModule() {
1285   SC_DEBUG("begin processModule!\n");
1286
1287   // Add all of the global variables to the value table...
1288   for (Module::const_giterator I = TheModule->gbegin(), E = TheModule->gend();
1289        I != E; ++I)
1290     createSlot(I);
1291
1292   // Add all the functions to the table
1293   for (Module::const_iterator I = TheModule->begin(), E = TheModule->end();
1294        I != E; ++I)
1295     createSlot(I);
1296
1297   SC_DEBUG("end processModule!\n");
1298 }
1299
1300
1301 // Process the arguments, basic blocks, and instructions  of a function.
1302 void SlotMachine::processFunction() {
1303   SC_DEBUG("begin processFunction!\n");
1304
1305   // Add all the function arguments
1306   for(Function::const_aiterator AI = TheFunction->abegin(), 
1307       AE = TheFunction->aend(); AI != AE; ++AI)
1308     createSlot(AI);
1309
1310   SC_DEBUG("Inserting Instructions:\n");
1311
1312   // Add all of the basic blocks and instructions
1313   for (Function::const_iterator BB = TheFunction->begin(), 
1314        E = TheFunction->end(); BB != E; ++BB) {
1315     createSlot(BB);
1316     for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I!=E; ++I) {
1317       createSlot(I);
1318     }
1319   }
1320
1321   SC_DEBUG("end processFunction!\n");
1322 }
1323
1324 // Clean up after incorporating a function. This is the only way
1325 // to get out of the function incorporation state that affects the
1326 // getSlot/createSlot lock. Function incorporation state is indicated
1327 // by TheFunction != 0.
1328 void SlotMachine::purgeFunction() {
1329   SC_DEBUG("begin purgeFunction!\n");
1330   fMap.clear(); // Simply discard the function level map
1331   fTypes.clear();
1332   TheFunction = 0;
1333   SC_DEBUG("end purgeFunction!\n");
1334 }
1335
1336 /// Get the slot number for a value. This function will assert if you
1337 /// ask for a Value that hasn't previously been inserted with createSlot.
1338 /// Types are forbidden because Type does not inherit from Value (any more).
1339 int SlotMachine::getSlot(const Value *V) {
1340   assert( V && "Can't get slot for null Value" );
1341   assert(!isa<Constant>(V) || isa<GlobalValue>(V) && 
1342     "Can't insert a non-GlobalValue Constant into SlotMachine"); 
1343
1344   // Check for uninitialized state and do lazy initialization
1345   this->initialize();
1346
1347   // Get the type of the value
1348   const Type* VTy = V->getType();
1349
1350   // Find the type plane in the module map
1351   TypedPlanes::const_iterator MI = mMap.find(VTy);
1352
1353   if ( TheFunction ) {
1354     // Lookup the type in the function map too
1355     TypedPlanes::const_iterator FI = fMap.find(VTy);
1356     // If there is a corresponding type plane in the function map
1357     if ( FI != fMap.end() ) {
1358       // Lookup the Value in the function map
1359       ValueMap::const_iterator FVI = FI->second.map.find(V);
1360       // If the value doesn't exist in the function map
1361       if ( FVI == FI->second.map.end() ) {
1362         // Look up the value in the module map.
1363         if (MI == mMap.end()) return -1;
1364         ValueMap::const_iterator MVI = MI->second.map.find(V);
1365         // If we didn't find it, it wasn't inserted
1366         if (MVI == MI->second.map.end()) return -1;
1367         assert( MVI != MI->second.map.end() && "Value not found");
1368         // We found it only at the module level
1369         return MVI->second; 
1370
1371       // else the value exists in the function map
1372       } else {
1373         // Return the slot number as the module's contribution to
1374         // the type plane plus the index in the function's contribution
1375         // to the type plane.
1376         if (MI != mMap.end())
1377           return MI->second.next_slot + FVI->second;
1378         else
1379           return FVI->second;
1380       }
1381     }
1382   }
1383
1384   // N.B. Can get here only if either !TheFunction or the function doesn't
1385   // have a corresponding type plane for the Value
1386
1387   // Make sure the type plane exists
1388   if (MI == mMap.end()) return -1;
1389   // Lookup the value in the module's map
1390   ValueMap::const_iterator MVI = MI->second.map.find(V);
1391   // Make sure we found it.
1392   if (MVI == MI->second.map.end()) return -1;
1393   // Return it.
1394   return MVI->second;
1395 }
1396
1397 /// Get the slot number for a value. This function will assert if you
1398 /// ask for a Value that hasn't previously been inserted with createSlot.
1399 /// Types are forbidden because Type does not inherit from Value (any more).
1400 int SlotMachine::getSlot(const Type *Ty) {
1401   assert( Ty && "Can't get slot for null Type" );
1402
1403   // Check for uninitialized state and do lazy initialization
1404   this->initialize();
1405
1406   if ( TheFunction ) {
1407     // Lookup the Type in the function map
1408     TypeMap::const_iterator FTI = fTypes.map.find(Ty);
1409     // If the Type doesn't exist in the function map
1410     if ( FTI == fTypes.map.end() ) {
1411       TypeMap::const_iterator MTI = mTypes.map.find(Ty);
1412       // If we didn't find it, it wasn't inserted
1413       if (MTI == mTypes.map.end()) 
1414         return -1;
1415       // We found it only at the module level
1416       return MTI->second; 
1417
1418     // else the value exists in the function map
1419     } else {
1420       // Return the slot number as the module's contribution to
1421       // the type plane plus the index in the function's contribution
1422       // to the type plane.
1423       return mTypes.next_slot + FTI->second;
1424     }
1425   }
1426
1427   // N.B. Can get here only if either !TheFunction
1428
1429   // Lookup the value in the module's map
1430   TypeMap::const_iterator MTI = mTypes.map.find(Ty);
1431   // Make sure we found it.
1432   if (MTI == mTypes.map.end()) return -1;
1433   // Return it.
1434   return MTI->second;
1435 }
1436
1437 // Create a new slot, or return the existing slot if it is already
1438 // inserted. Note that the logic here parallels getSlot but instead
1439 // of asserting when the Value* isn't found, it inserts the value.
1440 unsigned SlotMachine::createSlot(const Value *V) {
1441   assert( V && "Can't insert a null Value to SlotMachine");
1442   assert(!isa<Constant>(V) || isa<GlobalValue>(V) && 
1443     "Can't insert a non-GlobalValue Constant into SlotMachine"); 
1444
1445   const Type* VTy = V->getType();
1446
1447   // Just ignore void typed things
1448   if (VTy == Type::VoidTy) return 0; // FIXME: Wrong return value!
1449
1450   // Look up the type plane for the Value's type from the module map
1451   TypedPlanes::const_iterator MI = mMap.find(VTy);
1452
1453   if ( TheFunction ) {
1454     // Get the type plane for the Value's type from the function map
1455     TypedPlanes::const_iterator FI = fMap.find(VTy);
1456     // If there is a corresponding type plane in the function map
1457     if ( FI != fMap.end() ) {
1458       // Lookup the Value in the function map
1459       ValueMap::const_iterator FVI = FI->second.map.find(V);
1460       // If the value doesn't exist in the function map
1461       if ( FVI == FI->second.map.end() ) {
1462         // If there is no corresponding type plane in the module map
1463         if ( MI == mMap.end() )
1464           return insertValue(V);
1465         // Look up the value in the module map
1466         ValueMap::const_iterator MVI = MI->second.map.find(V);
1467         // If we didn't find it, it wasn't inserted
1468         if ( MVI == MI->second.map.end() )
1469           return insertValue(V);
1470         else
1471           // We found it only at the module level
1472           return MVI->second;
1473
1474       // else the value exists in the function map
1475       } else {
1476         if ( MI == mMap.end() )
1477           return FVI->second;
1478         else
1479           // Return the slot number as the module's contribution to
1480           // the type plane plus the index in the function's contribution
1481           // to the type plane.
1482           return MI->second.next_slot + FVI->second;
1483       }
1484
1485     // else there is not a corresponding type plane in the function map
1486     } else {
1487       // If the type plane doesn't exists at the module level
1488       if ( MI == mMap.end() ) {
1489         return insertValue(V);
1490       // else type plane exists at the module level, examine it
1491       } else {
1492         // Look up the value in the module's map
1493         ValueMap::const_iterator MVI = MI->second.map.find(V);
1494         // If we didn't find it there either
1495         if ( MVI == MI->second.map.end() )
1496           // Return the slot number as the module's contribution to
1497           // the type plane plus the index of the function map insertion.
1498           return MI->second.next_slot + insertValue(V);
1499         else
1500           return MVI->second;
1501       }
1502     }
1503   }
1504
1505   // N.B. Can only get here if !TheFunction
1506
1507   // If the module map's type plane is not for the Value's type
1508   if ( MI != mMap.end() ) {
1509     // Lookup the value in the module's map
1510     ValueMap::const_iterator MVI = MI->second.map.find(V);
1511     if ( MVI != MI->second.map.end() ) 
1512       return MVI->second;
1513   }
1514
1515   return insertValue(V);
1516 }
1517
1518 // Create a new slot, or return the existing slot if it is already
1519 // inserted. Note that the logic here parallels getSlot but instead
1520 // of asserting when the Value* isn't found, it inserts the value.
1521 unsigned SlotMachine::createSlot(const Type *Ty) {
1522   assert( Ty && "Can't insert a null Type to SlotMachine");
1523
1524   if ( TheFunction ) {
1525     // Lookup the Type in the function map
1526     TypeMap::const_iterator FTI = fTypes.map.find(Ty);
1527     // If the type doesn't exist in the function map
1528     if ( FTI == fTypes.map.end() ) {
1529       // Look up the type in the module map
1530       TypeMap::const_iterator MTI = mTypes.map.find(Ty);
1531       // If we didn't find it, it wasn't inserted
1532       if ( MTI == mTypes.map.end() )
1533         return insertValue(Ty);
1534       else
1535         // We found it only at the module level
1536         return MTI->second;
1537
1538     // else the value exists in the function map
1539     } else {
1540       // Return the slot number as the module's contribution to
1541       // the type plane plus the index in the function's contribution
1542       // to the type plane.
1543       return mTypes.next_slot + FTI->second;
1544     }
1545   }
1546
1547   // N.B. Can only get here if !TheFunction
1548
1549   // Lookup the type in the module's map
1550   TypeMap::const_iterator MTI = mTypes.map.find(Ty);
1551   if ( MTI != mTypes.map.end() ) 
1552     return MTI->second;
1553
1554   return insertValue(Ty);
1555 }
1556
1557 // Low level insert function. Minimal checking is done. This
1558 // function is just for the convenience of createSlot (above).
1559 unsigned SlotMachine::insertValue(const Value *V ) {
1560   assert(V && "Can't insert a null Value into SlotMachine!");
1561   assert(!isa<Constant>(V) || isa<GlobalValue>(V) && 
1562     "Can't insert a non-GlobalValue Constant into SlotMachine"); 
1563
1564   // If this value does not contribute to a plane (is void)
1565   // or if the value already has a name then ignore it. 
1566   if (V->getType() == Type::VoidTy || V->hasName() ) {
1567       SC_DEBUG("ignored value " << *V << "\n");
1568       return 0;   // FIXME: Wrong return value
1569   }
1570
1571   const Type *VTy = V->getType();
1572   unsigned DestSlot = 0;
1573
1574   if ( TheFunction ) {
1575     TypedPlanes::iterator I = fMap.find( VTy );
1576     if ( I == fMap.end() ) 
1577       I = fMap.insert(std::make_pair(VTy,ValuePlane())).first;
1578     DestSlot = I->second.map[V] = I->second.next_slot++;
1579   } else {
1580     TypedPlanes::iterator I = mMap.find( VTy );
1581     if ( I == mMap.end() )
1582       I = mMap.insert(std::make_pair(VTy,ValuePlane())).first;
1583     DestSlot = I->second.map[V] = I->second.next_slot++;
1584   }
1585
1586   SC_DEBUG("  Inserting value [" << VTy << "] = " << V << " slot=" << 
1587            DestSlot << " [");
1588   // G = Global, C = Constant, T = Type, F = Function, o = other
1589   SC_DEBUG((isa<GlobalVariable>(V) ? 'G' : (isa<Function>(V) ? 'F' : 
1590            (isa<Constant>(V) ? 'C' : 'o'))));
1591   SC_DEBUG("]\n");
1592   return DestSlot;
1593 }
1594
1595 // Low level insert function. Minimal checking is done. This
1596 // function is just for the convenience of createSlot (above).
1597 unsigned SlotMachine::insertValue(const Type *Ty ) {
1598   assert(Ty && "Can't insert a null Type into SlotMachine!");
1599
1600   unsigned DestSlot = 0;
1601
1602   if ( TheFunction ) {
1603     DestSlot = fTypes.map[Ty] = fTypes.next_slot++;
1604   } else {
1605     DestSlot = fTypes.map[Ty] = fTypes.next_slot++;
1606   }
1607   SC_DEBUG("  Inserting type [" << DestSlot << "] = " << Ty << "\n");
1608   return DestSlot;
1609 }
1610
1611 // vim: sw=2