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