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