Second installment of "BasicBlock operands to the back"
[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 is distributed under the University of Illinois Open Source
6 // 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/Writer.h"
18 #include "llvm/Assembly/PrintModulePass.h"
19 #include "llvm/Assembly/AsmAnnotationWriter.h"
20 #include "llvm/CallingConv.h"
21 #include "llvm/Constants.h"
22 #include "llvm/DerivedTypes.h"
23 #include "llvm/InlineAsm.h"
24 #include "llvm/Instruction.h"
25 #include "llvm/Instructions.h"
26 #include "llvm/Module.h"
27 #include "llvm/ValueSymbolTable.h"
28 #include "llvm/TypeSymbolTable.h"
29 #include "llvm/ADT/DenseSet.h"
30 #include "llvm/ADT/StringExtras.h"
31 #include "llvm/ADT/STLExtras.h"
32 #include "llvm/Support/CFG.h"
33 #include "llvm/Support/MathExtras.h"
34 #include "llvm/Support/raw_ostream.h"
35 #include <algorithm>
36 #include <cctype>
37 using namespace llvm;
38
39 // Make virtual table appear in this compilation unit.
40 AssemblyAnnotationWriter::~AssemblyAnnotationWriter() {}
41
42 //===----------------------------------------------------------------------===//
43 // Helper Functions
44 //===----------------------------------------------------------------------===//
45
46 static const Module *getModuleFromVal(const Value *V) {
47   if (const Argument *MA = dyn_cast<Argument>(V))
48     return MA->getParent() ? MA->getParent()->getParent() : 0;
49   
50   if (const BasicBlock *BB = dyn_cast<BasicBlock>(V))
51     return BB->getParent() ? BB->getParent()->getParent() : 0;
52   
53   if (const Instruction *I = dyn_cast<Instruction>(V)) {
54     const Function *M = I->getParent() ? I->getParent()->getParent() : 0;
55     return M ? M->getParent() : 0;
56   }
57   
58   if (const GlobalValue *GV = dyn_cast<GlobalValue>(V))
59     return GV->getParent();
60   return 0;
61 }
62
63 // PrintEscapedString - Print each character of the specified string, escaping
64 // it if it is not printable or if it is an escape char.
65 static void PrintEscapedString(const char *Str, unsigned Length,
66                                raw_ostream &Out) {
67   for (unsigned i = 0; i != Length; ++i) {
68     unsigned char C = Str[i];
69     if (isprint(C) && C != '\\' && C != '"' && isprint(C))
70       Out << C;
71     else
72       Out << '\\' << hexdigit(C >> 4) << hexdigit(C & 0x0F);
73   }
74 }
75
76 // PrintEscapedString - Print each character of the specified string, escaping
77 // it if it is not printable or if it is an escape char.
78 static void PrintEscapedString(const std::string &Str, raw_ostream &Out) {
79   PrintEscapedString(Str.c_str(), Str.size(), Out);
80 }
81
82 enum PrefixType {
83   GlobalPrefix,
84   LabelPrefix,
85   LocalPrefix,
86   NoPrefix
87 };
88
89 /// PrintLLVMName - Turn the specified name into an 'LLVM name', which is either
90 /// prefixed with % (if the string only contains simple characters) or is
91 /// surrounded with ""'s (if it has special chars in it).  Print it out.
92 static void PrintLLVMName(raw_ostream &OS, const char *NameStr,
93                           unsigned NameLen, PrefixType Prefix) {
94   assert(NameStr && "Cannot get empty name!");
95   switch (Prefix) {
96   default: assert(0 && "Bad prefix!");
97   case NoPrefix: break;
98   case GlobalPrefix: OS << '@'; break;
99   case LabelPrefix:  break;
100   case LocalPrefix:  OS << '%'; break;
101   }      
102   
103   // Scan the name to see if it needs quotes first.
104   bool NeedsQuotes = isdigit(NameStr[0]);
105   if (!NeedsQuotes) {
106     for (unsigned i = 0; i != NameLen; ++i) {
107       char C = NameStr[i];
108       if (!isalnum(C) && C != '-' && C != '.' && C != '_') {
109         NeedsQuotes = true;
110         break;
111       }
112     }
113   }
114   
115   // If we didn't need any quotes, just write out the name in one blast.
116   if (!NeedsQuotes) {
117     OS.write(NameStr, NameLen);
118     return;
119   }
120   
121   // Okay, we need quotes.  Output the quotes and escape any scary characters as
122   // needed.
123   OS << '"';
124   PrintEscapedString(NameStr, NameLen, OS);
125   OS << '"';
126 }
127
128 /// PrintLLVMName - Turn the specified name into an 'LLVM name', which is either
129 /// prefixed with % (if the string only contains simple characters) or is
130 /// surrounded with ""'s (if it has special chars in it).  Print it out.
131 static void PrintLLVMName(raw_ostream &OS, const Value *V) {
132   PrintLLVMName(OS, V->getNameStart(), V->getNameLen(),
133                 isa<GlobalValue>(V) ? GlobalPrefix : LocalPrefix);
134 }
135
136 //===----------------------------------------------------------------------===//
137 // TypePrinting Class: Type printing machinery
138 //===----------------------------------------------------------------------===//
139
140 static DenseMap<const Type *, std::string> &getTypeNamesMap(void *M) {
141   return *static_cast<DenseMap<const Type *, std::string>*>(M);
142 }
143
144 void TypePrinting::clear() {
145   getTypeNamesMap(TypeNames).clear();
146 }
147
148 bool TypePrinting::hasTypeName(const Type *Ty) const {
149   return getTypeNamesMap(TypeNames).count(Ty);
150 }
151
152 void TypePrinting::addTypeName(const Type *Ty, const std::string &N) {
153   getTypeNamesMap(TypeNames).insert(std::make_pair(Ty, N));
154 }
155
156
157 TypePrinting::TypePrinting() {
158   TypeNames = new DenseMap<const Type *, std::string>();
159 }
160
161 TypePrinting::~TypePrinting() {
162   delete &getTypeNamesMap(TypeNames);
163 }
164
165 /// CalcTypeName - Write the specified type to the specified raw_ostream, making
166 /// use of type names or up references to shorten the type name where possible.
167 void TypePrinting::CalcTypeName(const Type *Ty,
168                                 SmallVectorImpl<const Type *> &TypeStack,
169                                 raw_ostream &OS, bool IgnoreTopLevelName) {
170   // Check to see if the type is named.
171   if (!IgnoreTopLevelName) {
172     DenseMap<const Type*, std::string> &TM = getTypeNamesMap(TypeNames);
173     DenseMap<const Type *, std::string>::iterator I = TM.find(Ty);
174     if (I != TM.end()) {
175       OS << I->second;
176       return;
177     }
178   }
179   
180   // Check to see if the Type is already on the stack...
181   unsigned Slot = 0, CurSize = TypeStack.size();
182   while (Slot < CurSize && TypeStack[Slot] != Ty) ++Slot; // Scan for type
183   
184   // This is another base case for the recursion.  In this case, we know
185   // that we have looped back to a type that we have previously visited.
186   // Generate the appropriate upreference to handle this.
187   if (Slot < CurSize) {
188     OS << '\\' << unsigned(CurSize-Slot);     // Here's the upreference
189     return;
190   }
191   
192   TypeStack.push_back(Ty);    // Recursive case: Add us to the stack..
193   
194   switch (Ty->getTypeID()) {
195   case Type::VoidTyID:      OS << "void"; break;
196   case Type::FloatTyID:     OS << "float"; break;
197   case Type::DoubleTyID:    OS << "double"; break;
198   case Type::X86_FP80TyID:  OS << "x86_fp80"; break;
199   case Type::FP128TyID:     OS << "fp128"; break;
200   case Type::PPC_FP128TyID: OS << "ppc_fp128"; break;
201   case Type::LabelTyID:     OS << "label"; break;
202   case Type::IntegerTyID:
203     OS << 'i' << cast<IntegerType>(Ty)->getBitWidth();
204     break;
205       
206   case Type::FunctionTyID: {
207     const FunctionType *FTy = cast<FunctionType>(Ty);
208     CalcTypeName(FTy->getReturnType(), TypeStack, OS);
209     OS << " (";
210     for (FunctionType::param_iterator I = FTy->param_begin(),
211          E = FTy->param_end(); I != E; ++I) {
212       if (I != FTy->param_begin())
213         OS << ", ";
214       CalcTypeName(*I, TypeStack, OS);
215     }
216     if (FTy->isVarArg()) {
217       if (FTy->getNumParams()) OS << ", ";
218       OS << "...";
219     }
220     OS << ')';
221     break;
222   }
223   case Type::StructTyID: {
224     const StructType *STy = cast<StructType>(Ty);
225     if (STy->isPacked())
226       OS << '<';
227     OS << "{ ";
228     for (StructType::element_iterator I = STy->element_begin(),
229          E = STy->element_end(); I != E; ++I) {
230       CalcTypeName(*I, TypeStack, OS);
231       if (next(I) != STy->element_end())
232         OS << ',';
233       OS << ' ';
234     }
235     OS << '}';
236     if (STy->isPacked())
237       OS << '>';
238     break;
239   }
240   case Type::PointerTyID: {
241     const PointerType *PTy = cast<PointerType>(Ty);
242     CalcTypeName(PTy->getElementType(), TypeStack, OS);
243     if (unsigned AddressSpace = PTy->getAddressSpace())
244       OS << " addrspace(" << AddressSpace << ')';
245     OS << '*';
246     break;
247   }
248   case Type::ArrayTyID: {
249     const ArrayType *ATy = cast<ArrayType>(Ty);
250     OS << '[' << ATy->getNumElements() << " x ";
251     CalcTypeName(ATy->getElementType(), TypeStack, OS);
252     OS << ']';
253     break;
254   }
255   case Type::VectorTyID: {
256     const VectorType *PTy = cast<VectorType>(Ty);
257     OS << "<" << PTy->getNumElements() << " x ";
258     CalcTypeName(PTy->getElementType(), TypeStack, OS);
259     OS << '>';
260     break;
261   }
262   case Type::OpaqueTyID:
263     OS << "opaque";
264     break;
265   default:
266     OS << "<unrecognized-type>";
267     break;
268   }
269   
270   TypeStack.pop_back();       // Remove self from stack.
271 }
272
273 /// printTypeInt - The internal guts of printing out a type that has a
274 /// potentially named portion.
275 ///
276 void TypePrinting::print(const Type *Ty, raw_ostream &OS,
277                          bool IgnoreTopLevelName) {
278   // Check to see if the type is named.
279   DenseMap<const Type*, std::string> &TM = getTypeNamesMap(TypeNames);
280   if (!IgnoreTopLevelName) {
281     DenseMap<const Type*, std::string>::iterator I = TM.find(Ty);
282     if (I != TM.end()) {
283       OS << I->second;
284       return;
285     }
286   }
287   
288   // Otherwise we have a type that has not been named but is a derived type.
289   // Carefully recurse the type hierarchy to print out any contained symbolic
290   // names.
291   SmallVector<const Type *, 16> TypeStack;
292   std::string TypeName;
293   
294   raw_string_ostream TypeOS(TypeName);
295   CalcTypeName(Ty, TypeStack, TypeOS, IgnoreTopLevelName);
296   OS << TypeOS.str();
297
298   // Cache type name for later use.
299   if (!IgnoreTopLevelName)
300     TM.insert(std::make_pair(Ty, TypeOS.str()));
301 }
302
303 namespace {
304   class TypeFinder {
305     // To avoid walking constant expressions multiple times and other IR
306     // objects, we keep several helper maps.
307     DenseSet<const Value*> VisitedConstants;
308     DenseSet<const Type*> VisitedTypes;
309     
310     TypePrinting &TP;
311     std::vector<const Type*> &NumberedTypes;
312   public:
313     TypeFinder(TypePrinting &tp, std::vector<const Type*> &numberedTypes)
314       : TP(tp), NumberedTypes(numberedTypes) {}
315     
316     void Run(const Module &M) {
317       // Get types from the type symbol table.  This gets opaque types referened
318       // only through derived named types.
319       const TypeSymbolTable &ST = M.getTypeSymbolTable();
320       for (TypeSymbolTable::const_iterator TI = ST.begin(), E = ST.end();
321            TI != E; ++TI)
322         IncorporateType(TI->second);
323       
324       // Get types from global variables.
325       for (Module::const_global_iterator I = M.global_begin(),
326            E = M.global_end(); I != E; ++I) {
327         IncorporateType(I->getType());
328         if (I->hasInitializer())
329           IncorporateValue(I->getInitializer());
330       }
331       
332       // Get types from aliases.
333       for (Module::const_alias_iterator I = M.alias_begin(),
334            E = M.alias_end(); I != E; ++I) {
335         IncorporateType(I->getType());
336         IncorporateValue(I->getAliasee());
337       }
338       
339       // Get types from functions.
340       for (Module::const_iterator FI = M.begin(), E = M.end(); FI != E; ++FI) {
341         IncorporateType(FI->getType());
342         
343         for (Function::const_iterator BB = FI->begin(), E = FI->end();
344              BB != E;++BB)
345           for (BasicBlock::const_iterator II = BB->begin(),
346                E = BB->end(); II != E; ++II) {
347             const Instruction &I = *II;
348             // Incorporate the type of the instruction and all its operands.
349             IncorporateType(I.getType());
350             for (User::const_op_iterator OI = I.op_begin(), OE = I.op_end();
351                  OI != OE; ++OI)
352               IncorporateValue(*OI);
353           }
354       }
355     }
356     
357   private:
358     void IncorporateType(const Type *Ty) {
359       // Check to see if we're already visited this type.
360       if (!VisitedTypes.insert(Ty).second)
361         return;
362       
363       // If this is a structure or opaque type, add a name for the type.
364       if ((isa<StructType>(Ty) || isa<OpaqueType>(Ty))
365           && !TP.hasTypeName(Ty)) {
366         TP.addTypeName(Ty, "%"+utostr(unsigned(NumberedTypes.size())));
367         NumberedTypes.push_back(Ty);
368       }
369       
370       // Recursively walk all contained types.
371       for (Type::subtype_iterator I = Ty->subtype_begin(),
372            E = Ty->subtype_end(); I != E; ++I)
373         IncorporateType(*I);      
374     }
375     
376     /// IncorporateValue - This method is used to walk operand lists finding
377     /// types hiding in constant expressions and other operands that won't be
378     /// walked in other ways.  GlobalValues, basic blocks, instructions, and
379     /// inst operands are all explicitly enumerated.
380     void IncorporateValue(const Value *V) {
381       if (V == 0 || !isa<Constant>(V) || isa<GlobalValue>(V)) return;
382       
383       // Already visited?
384       if (!VisitedConstants.insert(V).second)
385         return;
386       
387       // Check this type.
388       IncorporateType(V->getType());
389       
390       // Look in operands for types.
391       const Constant *C = cast<Constant>(V);
392       for (Constant::const_op_iterator I = C->op_begin(),
393            E = C->op_end(); I != E;++I)
394         IncorporateValue(*I);
395     }
396   };
397 } // end anonymous namespace
398
399
400 /// AddModuleTypesToPrinter - Add all of the symbolic type names for types in
401 /// the specified module to the TypePrinter and all numbered types to it and the
402 /// NumberedTypes table.
403 static void AddModuleTypesToPrinter(TypePrinting &TP, 
404                                     std::vector<const Type*> &NumberedTypes,
405                                     const Module *M) {
406   if (M == 0) return;
407   
408   // If the module has a symbol table, take all global types and stuff their
409   // names into the TypeNames map.
410   const TypeSymbolTable &ST = M->getTypeSymbolTable();
411   for (TypeSymbolTable::const_iterator TI = ST.begin(), E = ST.end();
412        TI != E; ++TI) {
413     const Type *Ty = cast<Type>(TI->second);
414     
415     // As a heuristic, don't insert pointer to primitive types, because
416     // they are used too often to have a single useful name.
417     if (const PointerType *PTy = dyn_cast<PointerType>(Ty)) {
418       const Type *PETy = PTy->getElementType();
419       if ((PETy->isPrimitiveType() || PETy->isInteger()) &&
420           !isa<OpaqueType>(PETy))
421         continue;
422     }
423     
424     // Likewise don't insert primitives either.
425     if (Ty->isInteger() || Ty->isPrimitiveType())
426       continue;
427     
428     // Get the name as a string and insert it into TypeNames.
429     std::string NameStr;
430     raw_string_ostream NameOS(NameStr);
431     PrintLLVMName(NameOS, TI->first.c_str(), TI->first.length(), LocalPrefix);
432     TP.addTypeName(Ty, NameOS.str());
433   }
434   
435   // Walk the entire module to find references to unnamed structure and opaque
436   // types.  This is required for correctness by opaque types (because multiple
437   // uses of an unnamed opaque type needs to be referred to by the same ID) and
438   // it shrinks complex recursive structure types substantially in some cases.
439   TypeFinder(TP, NumberedTypes).Run(*M);
440 }
441
442
443 /// WriteTypeSymbolic - This attempts to write the specified type as a symbolic
444 /// type, iff there is an entry in the modules symbol table for the specified
445 /// type or one of it's component types.
446 ///
447 void llvm::WriteTypeSymbolic(raw_ostream &OS, const Type *Ty, const Module *M) {
448   TypePrinting Printer;
449   std::vector<const Type*> NumberedTypes;
450   AddModuleTypesToPrinter(Printer, NumberedTypes, M);
451   Printer.print(Ty, OS);
452 }
453
454 //===----------------------------------------------------------------------===//
455 // SlotTracker Class: Enumerate slot numbers for unnamed values
456 //===----------------------------------------------------------------------===//
457
458 namespace {
459
460 /// This class provides computation of slot numbers for LLVM Assembly writing.
461 ///
462 class SlotTracker {
463 public:
464   /// ValueMap - A mapping of Values to slot numbers
465   typedef DenseMap<const Value*, unsigned> ValueMap;
466   
467 private:  
468   /// TheModule - The module for which we are holding slot numbers
469   const Module* TheModule;
470   
471   /// TheFunction - The function for which we are holding slot numbers
472   const Function* TheFunction;
473   bool FunctionProcessed;
474   
475   /// mMap - The TypePlanes map for the module level data
476   ValueMap mMap;
477   unsigned mNext;
478   
479   /// fMap - The TypePlanes map for the function level data
480   ValueMap fMap;
481   unsigned fNext;
482   
483 public:
484   /// Construct from a module
485   explicit SlotTracker(const Module *M);
486   /// Construct from a function, starting out in incorp state.
487   explicit SlotTracker(const Function *F);
488
489   /// Return the slot number of the specified value in it's type
490   /// plane.  If something is not in the SlotTracker, return -1.
491   int getLocalSlot(const Value *V);
492   int getGlobalSlot(const GlobalValue *V);
493
494   /// If you'd like to deal with a function instead of just a module, use
495   /// this method to get its data into the SlotTracker.
496   void incorporateFunction(const Function *F) {
497     TheFunction = F;
498     FunctionProcessed = false;
499   }
500
501   /// After calling incorporateFunction, use this method to remove the
502   /// most recently incorporated function from the SlotTracker. This
503   /// will reset the state of the machine back to just the module contents.
504   void purgeFunction();
505
506   // Implementation Details
507 private:
508   /// This function does the actual initialization.
509   inline void initialize();
510
511   /// CreateModuleSlot - Insert the specified GlobalValue* into the slot table.
512   void CreateModuleSlot(const GlobalValue *V);
513   
514   /// CreateFunctionSlot - Insert the specified Value* into the slot table.
515   void CreateFunctionSlot(const Value *V);
516
517   /// Add all of the module level global variables (and their initializers)
518   /// and function declarations, but not the contents of those functions.
519   void processModule();
520
521   /// Add all of the functions arguments, basic blocks, and instructions
522   void processFunction();
523
524   SlotTracker(const SlotTracker &);  // DO NOT IMPLEMENT
525   void operator=(const SlotTracker &);  // DO NOT IMPLEMENT
526 };
527
528 }  // end anonymous namespace
529
530
531 static SlotTracker *createSlotTracker(const Value *V) {
532   if (const Argument *FA = dyn_cast<Argument>(V))
533     return new SlotTracker(FA->getParent());
534   
535   if (const Instruction *I = dyn_cast<Instruction>(V))
536     return new SlotTracker(I->getParent()->getParent());
537   
538   if (const BasicBlock *BB = dyn_cast<BasicBlock>(V))
539     return new SlotTracker(BB->getParent());
540   
541   if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(V))
542     return new SlotTracker(GV->getParent());
543   
544   if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(V))
545     return new SlotTracker(GA->getParent());    
546   
547   if (const Function *Func = dyn_cast<Function>(V))
548     return new SlotTracker(Func);
549   
550   return 0;
551 }
552
553 #if 0
554 #define ST_DEBUG(X) cerr << X
555 #else
556 #define ST_DEBUG(X)
557 #endif
558
559 // Module level constructor. Causes the contents of the Module (sans functions)
560 // to be added to the slot table.
561 SlotTracker::SlotTracker(const Module *M)
562   : TheModule(M), TheFunction(0), FunctionProcessed(false), mNext(0), fNext(0) {
563 }
564
565 // Function level constructor. Causes the contents of the Module and the one
566 // function provided to be added to the slot table.
567 SlotTracker::SlotTracker(const Function *F)
568   : TheModule(F ? F->getParent() : 0), TheFunction(F), FunctionProcessed(false),
569     mNext(0), fNext(0) {
570 }
571
572 inline void SlotTracker::initialize() {
573   if (TheModule) {
574     processModule();
575     TheModule = 0; ///< Prevent re-processing next time we're called.
576   }
577   
578   if (TheFunction && !FunctionProcessed)
579     processFunction();
580 }
581
582 // Iterate through all the global variables, functions, and global
583 // variable initializers and create slots for them.
584 void SlotTracker::processModule() {
585   ST_DEBUG("begin processModule!\n");
586   
587   // Add all of the unnamed global variables to the value table.
588   for (Module::const_global_iterator I = TheModule->global_begin(),
589        E = TheModule->global_end(); I != E; ++I)
590     if (!I->hasName()) 
591       CreateModuleSlot(I);
592   
593   // Add all the unnamed functions to the table.
594   for (Module::const_iterator I = TheModule->begin(), E = TheModule->end();
595        I != E; ++I)
596     if (!I->hasName())
597       CreateModuleSlot(I);
598   
599   ST_DEBUG("end processModule!\n");
600 }
601
602
603 // Process the arguments, basic blocks, and instructions  of a function.
604 void SlotTracker::processFunction() {
605   ST_DEBUG("begin processFunction!\n");
606   fNext = 0;
607   
608   // Add all the function arguments with no names.
609   for(Function::const_arg_iterator AI = TheFunction->arg_begin(),
610       AE = TheFunction->arg_end(); AI != AE; ++AI)
611     if (!AI->hasName())
612       CreateFunctionSlot(AI);
613   
614   ST_DEBUG("Inserting Instructions:\n");
615   
616   // Add all of the basic blocks and instructions with no names.
617   for (Function::const_iterator BB = TheFunction->begin(),
618        E = TheFunction->end(); BB != E; ++BB) {
619     if (!BB->hasName())
620       CreateFunctionSlot(BB);
621     for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I != E; ++I)
622       if (I->getType() != Type::VoidTy && !I->hasName())
623         CreateFunctionSlot(I);
624   }
625   
626   FunctionProcessed = true;
627   
628   ST_DEBUG("end processFunction!\n");
629 }
630
631 /// Clean up after incorporating a function. This is the only way to get out of
632 /// the function incorporation state that affects get*Slot/Create*Slot. Function
633 /// incorporation state is indicated by TheFunction != 0.
634 void SlotTracker::purgeFunction() {
635   ST_DEBUG("begin purgeFunction!\n");
636   fMap.clear(); // Simply discard the function level map
637   TheFunction = 0;
638   FunctionProcessed = false;
639   ST_DEBUG("end purgeFunction!\n");
640 }
641
642 /// getGlobalSlot - Get the slot number of a global value.
643 int SlotTracker::getGlobalSlot(const GlobalValue *V) {
644   // Check for uninitialized state and do lazy initialization.
645   initialize();
646   
647   // Find the type plane in the module map
648   ValueMap::iterator MI = mMap.find(V);
649   return MI == mMap.end() ? -1 : (int)MI->second;
650 }
651
652
653 /// getLocalSlot - Get the slot number for a value that is local to a function.
654 int SlotTracker::getLocalSlot(const Value *V) {
655   assert(!isa<Constant>(V) && "Can't get a constant or global slot with this!");
656   
657   // Check for uninitialized state and do lazy initialization.
658   initialize();
659   
660   ValueMap::iterator FI = fMap.find(V);
661   return FI == fMap.end() ? -1 : (int)FI->second;
662 }
663
664
665 /// CreateModuleSlot - Insert the specified GlobalValue* into the slot table.
666 void SlotTracker::CreateModuleSlot(const GlobalValue *V) {
667   assert(V && "Can't insert a null Value into SlotTracker!");
668   assert(V->getType() != Type::VoidTy && "Doesn't need a slot!");
669   assert(!V->hasName() && "Doesn't need a slot!");
670   
671   unsigned DestSlot = mNext++;
672   mMap[V] = DestSlot;
673   
674   ST_DEBUG("  Inserting value [" << V->getType() << "] = " << V << " slot=" <<
675            DestSlot << " [");
676   // G = Global, F = Function, A = Alias, o = other
677   ST_DEBUG((isa<GlobalVariable>(V) ? 'G' :
678             (isa<Function>(V) ? 'F' :
679              (isa<GlobalAlias>(V) ? 'A' : 'o'))) << "]\n");
680 }
681
682
683 /// CreateSlot - Create a new slot for the specified value if it has no name.
684 void SlotTracker::CreateFunctionSlot(const Value *V) {
685   assert(V->getType() != Type::VoidTy && !V->hasName() &&
686          "Doesn't need a slot!");
687   
688   unsigned DestSlot = fNext++;
689   fMap[V] = DestSlot;
690   
691   // G = Global, F = Function, o = other
692   ST_DEBUG("  Inserting value [" << V->getType() << "] = " << V << " slot=" <<
693            DestSlot << " [o]\n");
694 }  
695
696
697
698 //===----------------------------------------------------------------------===//
699 // AsmWriter Implementation
700 //===----------------------------------------------------------------------===//
701
702 static void WriteAsOperandInternal(raw_ostream &Out, const Value *V,
703                                    TypePrinting &TypePrinter,
704                                    SlotTracker *Machine);
705
706
707
708 static const char *getPredicateText(unsigned predicate) {
709   const char * pred = "unknown";
710   switch (predicate) {
711     case FCmpInst::FCMP_FALSE: pred = "false"; break;
712     case FCmpInst::FCMP_OEQ:   pred = "oeq"; break;
713     case FCmpInst::FCMP_OGT:   pred = "ogt"; break;
714     case FCmpInst::FCMP_OGE:   pred = "oge"; break;
715     case FCmpInst::FCMP_OLT:   pred = "olt"; break;
716     case FCmpInst::FCMP_OLE:   pred = "ole"; break;
717     case FCmpInst::FCMP_ONE:   pred = "one"; break;
718     case FCmpInst::FCMP_ORD:   pred = "ord"; break;
719     case FCmpInst::FCMP_UNO:   pred = "uno"; break;
720     case FCmpInst::FCMP_UEQ:   pred = "ueq"; break;
721     case FCmpInst::FCMP_UGT:   pred = "ugt"; break;
722     case FCmpInst::FCMP_UGE:   pred = "uge"; break;
723     case FCmpInst::FCMP_ULT:   pred = "ult"; break;
724     case FCmpInst::FCMP_ULE:   pred = "ule"; break;
725     case FCmpInst::FCMP_UNE:   pred = "une"; break;
726     case FCmpInst::FCMP_TRUE:  pred = "true"; break;
727     case ICmpInst::ICMP_EQ:    pred = "eq"; break;
728     case ICmpInst::ICMP_NE:    pred = "ne"; break;
729     case ICmpInst::ICMP_SGT:   pred = "sgt"; break;
730     case ICmpInst::ICMP_SGE:   pred = "sge"; break;
731     case ICmpInst::ICMP_SLT:   pred = "slt"; break;
732     case ICmpInst::ICMP_SLE:   pred = "sle"; break;
733     case ICmpInst::ICMP_UGT:   pred = "ugt"; break;
734     case ICmpInst::ICMP_UGE:   pred = "uge"; break;
735     case ICmpInst::ICMP_ULT:   pred = "ult"; break;
736     case ICmpInst::ICMP_ULE:   pred = "ule"; break;
737   }
738   return pred;
739 }
740
741 static void WriteConstantInt(raw_ostream &Out, const Constant *CV,
742                              TypePrinting &TypePrinter, SlotTracker *Machine) {
743   if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV)) {
744     if (CI->getType() == Type::Int1Ty) {
745       Out << (CI->getZExtValue() ? "true" : "false");
746       return;
747     }
748     Out << CI->getValue();
749     return;
750   }
751   
752   if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CV)) {
753     if (&CFP->getValueAPF().getSemantics() == &APFloat::IEEEdouble ||
754         &CFP->getValueAPF().getSemantics() == &APFloat::IEEEsingle) {
755       // We would like to output the FP constant value in exponential notation,
756       // but we cannot do this if doing so will lose precision.  Check here to
757       // make sure that we only output it in exponential format if we can parse
758       // the value back and get the same value.
759       //
760       bool ignored;
761       bool isDouble = &CFP->getValueAPF().getSemantics()==&APFloat::IEEEdouble;
762       double Val = isDouble ? CFP->getValueAPF().convertToDouble() :
763                               CFP->getValueAPF().convertToFloat();
764       std::string StrVal = ftostr(CFP->getValueAPF());
765
766       // Check to make sure that the stringized number is not some string like
767       // "Inf" or NaN, that atof will accept, but the lexer will not.  Check
768       // that the string matches the "[-+]?[0-9]" regex.
769       //
770       if ((StrVal[0] >= '0' && StrVal[0] <= '9') ||
771           ((StrVal[0] == '-' || StrVal[0] == '+') &&
772            (StrVal[1] >= '0' && StrVal[1] <= '9'))) {
773         // Reparse stringized version!
774         if (atof(StrVal.c_str()) == Val) {
775           Out << StrVal;
776           return;
777         }
778       }
779       // Otherwise we could not reparse it to exactly the same value, so we must
780       // output the string in hexadecimal format!  Note that loading and storing
781       // floating point types changes the bits of NaNs on some hosts, notably
782       // x86, so we must not use these types.
783       assert(sizeof(double) == sizeof(uint64_t) &&
784              "assuming that double is 64 bits!");
785       char Buffer[40];
786       APFloat apf = CFP->getValueAPF();
787       // Floats are represented in ASCII IR as double, convert.
788       if (!isDouble)
789         apf.convert(APFloat::IEEEdouble, APFloat::rmNearestTiesToEven, 
790                           &ignored);
791       Out << "0x" << 
792               utohex_buffer(uint64_t(apf.bitcastToAPInt().getZExtValue()), 
793                             Buffer+40);
794       return;
795     }
796     
797     // Some form of long double.  These appear as a magic letter identifying
798     // the type, then a fixed number of hex digits.
799     Out << "0x";
800     if (&CFP->getValueAPF().getSemantics() == &APFloat::x87DoubleExtended)
801       Out << 'K';
802     else if (&CFP->getValueAPF().getSemantics() == &APFloat::IEEEquad)
803       Out << 'L';
804     else if (&CFP->getValueAPF().getSemantics() == &APFloat::PPCDoubleDouble)
805       Out << 'M';
806     else
807       assert(0 && "Unsupported floating point type");
808     // api needed to prevent premature destruction
809     APInt api = CFP->getValueAPF().bitcastToAPInt();
810     const uint64_t* p = api.getRawData();
811     uint64_t word = *p;
812     int shiftcount=60;
813     int width = api.getBitWidth();
814     for (int j=0; j<width; j+=4, shiftcount-=4) {
815       unsigned int nibble = (word>>shiftcount) & 15;
816       if (nibble < 10)
817         Out << (unsigned char)(nibble + '0');
818       else
819         Out << (unsigned char)(nibble - 10 + 'A');
820       if (shiftcount == 0 && j+4 < width) {
821         word = *(++p);
822         shiftcount = 64;
823         if (width-j-4 < 64)
824           shiftcount = width-j-4;
825       }
826     }
827     return;
828   }
829   
830   if (isa<ConstantAggregateZero>(CV)) {
831     Out << "zeroinitializer";
832     return;
833   }
834   
835   if (const ConstantArray *CA = dyn_cast<ConstantArray>(CV)) {
836     // As a special case, print the array as a string if it is an array of
837     // i8 with ConstantInt values.
838     //
839     const Type *ETy = CA->getType()->getElementType();
840     if (CA->isString()) {
841       Out << "c\"";
842       PrintEscapedString(CA->getAsString(), Out);
843       Out << '"';
844     } else {                // Cannot output in string format...
845       Out << '[';
846       if (CA->getNumOperands()) {
847         TypePrinter.print(ETy, Out);
848         Out << ' ';
849         WriteAsOperandInternal(Out, CA->getOperand(0),
850                                TypePrinter, Machine);
851         for (unsigned i = 1, e = CA->getNumOperands(); i != e; ++i) {
852           Out << ", ";
853           TypePrinter.print(ETy, Out);
854           Out << ' ';
855           WriteAsOperandInternal(Out, CA->getOperand(i), TypePrinter, Machine);
856         }
857       }
858       Out << ']';
859     }
860     return;
861   }
862   
863   if (const ConstantStruct *CS = dyn_cast<ConstantStruct>(CV)) {
864     if (CS->getType()->isPacked())
865       Out << '<';
866     Out << '{';
867     unsigned N = CS->getNumOperands();
868     if (N) {
869       Out << ' ';
870       TypePrinter.print(CS->getOperand(0)->getType(), Out);
871       Out << ' ';
872
873       WriteAsOperandInternal(Out, CS->getOperand(0), TypePrinter, Machine);
874
875       for (unsigned i = 1; i < N; i++) {
876         Out << ", ";
877         TypePrinter.print(CS->getOperand(i)->getType(), Out);
878         Out << ' ';
879
880         WriteAsOperandInternal(Out, CS->getOperand(i), TypePrinter, Machine);
881       }
882       Out << ' ';
883     }
884  
885     Out << '}';
886     if (CS->getType()->isPacked())
887       Out << '>';
888     return;
889   }
890   
891   if (const ConstantVector *CP = dyn_cast<ConstantVector>(CV)) {
892     const Type *ETy = CP->getType()->getElementType();
893     assert(CP->getNumOperands() > 0 &&
894            "Number of operands for a PackedConst must be > 0");
895     Out << '<';
896     TypePrinter.print(ETy, Out);
897     Out << ' ';
898     WriteAsOperandInternal(Out, CP->getOperand(0), TypePrinter, Machine);
899     for (unsigned i = 1, e = CP->getNumOperands(); i != e; ++i) {
900       Out << ", ";
901       TypePrinter.print(ETy, Out);
902       Out << ' ';
903       WriteAsOperandInternal(Out, CP->getOperand(i), TypePrinter, Machine);
904     }
905     Out << '>';
906     return;
907   }
908   
909   if (isa<ConstantPointerNull>(CV)) {
910     Out << "null";
911     return;
912   }
913   
914   if (isa<UndefValue>(CV)) {
915     Out << "undef";
916     return;
917   }
918
919   if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV)) {
920     Out << CE->getOpcodeName();
921     if (CE->isCompare())
922       Out << ' ' << getPredicateText(CE->getPredicate());
923     Out << " (";
924
925     for (User::const_op_iterator OI=CE->op_begin(); OI != CE->op_end(); ++OI) {
926       TypePrinter.print((*OI)->getType(), Out);
927       Out << ' ';
928       WriteAsOperandInternal(Out, *OI, TypePrinter, Machine);
929       if (OI+1 != CE->op_end())
930         Out << ", ";
931     }
932
933     if (CE->hasIndices()) {
934       const SmallVector<unsigned, 4> &Indices = CE->getIndices();
935       for (unsigned i = 0, e = Indices.size(); i != e; ++i)
936         Out << ", " << Indices[i];
937     }
938
939     if (CE->isCast()) {
940       Out << " to ";
941       TypePrinter.print(CE->getType(), Out);
942     }
943
944     Out << ')';
945     return;
946   }
947   
948   Out << "<placeholder or erroneous Constant>";
949 }
950
951
952 /// WriteAsOperand - Write the name of the specified value out to the specified
953 /// ostream.  This can be useful when you just want to print int %reg126, not
954 /// the whole instruction that generated it.
955 ///
956 static void WriteAsOperandInternal(raw_ostream &Out, const Value *V,
957                                    TypePrinting &TypePrinter,
958                                    SlotTracker *Machine) {
959   if (V->hasName()) {
960     PrintLLVMName(Out, V);
961     return;
962   }
963   
964   const Constant *CV = dyn_cast<Constant>(V);
965   if (CV && !isa<GlobalValue>(CV)) {
966     WriteConstantInt(Out, CV, TypePrinter, Machine);
967     return;
968   }
969   
970   if (const InlineAsm *IA = dyn_cast<InlineAsm>(V)) {
971     Out << "asm ";
972     if (IA->hasSideEffects())
973       Out << "sideeffect ";
974     Out << '"';
975     PrintEscapedString(IA->getAsmString(), Out);
976     Out << "\", \"";
977     PrintEscapedString(IA->getConstraintString(), Out);
978     Out << '"';
979     return;
980   }
981   
982   char Prefix = '%';
983   int Slot;
984   if (Machine) {
985     if (const GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
986       Slot = Machine->getGlobalSlot(GV);
987       Prefix = '@';
988     } else {
989       Slot = Machine->getLocalSlot(V);
990     }
991   } else {
992     Machine = createSlotTracker(V);
993     if (Machine) {
994       if (const GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
995         Slot = Machine->getGlobalSlot(GV);
996         Prefix = '@';
997       } else {
998         Slot = Machine->getLocalSlot(V);
999       }
1000     } else {
1001       Slot = -1;
1002     }
1003     delete Machine;
1004   }
1005   
1006   if (Slot != -1)
1007     Out << Prefix << Slot;
1008   else
1009     Out << "<badref>";
1010 }
1011
1012 /// WriteAsOperand - Write the name of the specified value out to the specified
1013 /// ostream.  This can be useful when you just want to print int %reg126, not
1014 /// the whole instruction that generated it.
1015 ///
1016 void llvm::WriteAsOperand(std::ostream &Out, const Value *V, bool PrintType,
1017                           const Module *Context) {
1018   raw_os_ostream OS(Out);
1019   WriteAsOperand(OS, V, PrintType, Context);
1020 }
1021
1022 void llvm::WriteAsOperand(raw_ostream &Out, const Value *V, bool PrintType,
1023                           const Module *Context) {
1024   if (Context == 0) Context = getModuleFromVal(V);
1025
1026   TypePrinting TypePrinter;
1027   std::vector<const Type*> NumberedTypes;
1028   AddModuleTypesToPrinter(TypePrinter, NumberedTypes, Context);
1029   if (PrintType) {
1030     TypePrinter.print(V->getType(), Out);
1031     Out << ' ';
1032   }
1033
1034   WriteAsOperandInternal(Out, V, TypePrinter, 0);
1035 }
1036
1037
1038 namespace {
1039
1040 class AssemblyWriter {
1041   raw_ostream &Out;
1042   SlotTracker &Machine;
1043   const Module *TheModule;
1044   TypePrinting TypePrinter;
1045   AssemblyAnnotationWriter *AnnotationWriter;
1046   std::vector<const Type*> NumberedTypes;
1047 public:
1048   inline AssemblyWriter(raw_ostream &o, SlotTracker &Mac, const Module *M,
1049                         AssemblyAnnotationWriter *AAW)
1050     : Out(o), Machine(Mac), TheModule(M), AnnotationWriter(AAW) {
1051     AddModuleTypesToPrinter(TypePrinter, NumberedTypes, M);
1052   }
1053
1054   void write(const Module *M) { printModule(M); }
1055   
1056   void write(const GlobalValue *G) {
1057     if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(G))
1058       printGlobal(GV);
1059     else if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(G))
1060       printAlias(GA);
1061     else if (const Function *F = dyn_cast<Function>(G))
1062       printFunction(F);
1063     else
1064       assert(0 && "Unknown global");
1065   }
1066   
1067   void write(const BasicBlock *BB)    { printBasicBlock(BB);  }
1068   void write(const Instruction *I)    { printInstruction(*I); }
1069
1070   void writeOperand(const Value *Op, bool PrintType);
1071   void writeParamOperand(const Value *Operand, Attributes Attrs);
1072
1073   const Module* getModule() { return TheModule; }
1074
1075 private:
1076   void printModule(const Module *M);
1077   void printTypeSymbolTable(const TypeSymbolTable &ST);
1078   void printGlobal(const GlobalVariable *GV);
1079   void printAlias(const GlobalAlias *GV);
1080   void printFunction(const Function *F);
1081   void printArgument(const Argument *FA, Attributes Attrs);
1082   void printBasicBlock(const BasicBlock *BB);
1083   void printInstruction(const Instruction &I);
1084
1085   // printInfoComment - Print a little comment after the instruction indicating
1086   // which slot it occupies.
1087   void printInfoComment(const Value &V);
1088 };
1089 }  // end of anonymous namespace
1090
1091
1092 void AssemblyWriter::writeOperand(const Value *Operand, bool PrintType) {
1093   if (Operand == 0) {
1094     Out << "<null operand!>";
1095   } else {
1096     if (PrintType) {
1097       TypePrinter.print(Operand->getType(), Out);
1098       Out << ' ';
1099     }
1100     WriteAsOperandInternal(Out, Operand, TypePrinter, &Machine);
1101   }
1102 }
1103
1104 void AssemblyWriter::writeParamOperand(const Value *Operand, 
1105                                        Attributes Attrs) {
1106   if (Operand == 0) {
1107     Out << "<null operand!>";
1108   } else {
1109     // Print the type
1110     TypePrinter.print(Operand->getType(), Out);
1111     // Print parameter attributes list
1112     if (Attrs != Attribute::None)
1113       Out << ' ' << Attribute::getAsString(Attrs);
1114     Out << ' ';
1115     // Print the operand
1116     WriteAsOperandInternal(Out, Operand, TypePrinter, &Machine);
1117   }
1118 }
1119
1120 void AssemblyWriter::printModule(const Module *M) {
1121   if (!M->getModuleIdentifier().empty() &&
1122       // Don't print the ID if it will start a new line (which would
1123       // require a comment char before it).
1124       M->getModuleIdentifier().find('\n') == std::string::npos)
1125     Out << "; ModuleID = '" << M->getModuleIdentifier() << "'\n";
1126
1127   if (!M->getDataLayout().empty())
1128     Out << "target datalayout = \"" << M->getDataLayout() << "\"\n";
1129   if (!M->getTargetTriple().empty())
1130     Out << "target triple = \"" << M->getTargetTriple() << "\"\n";
1131
1132   if (!M->getModuleInlineAsm().empty()) {
1133     // Split the string into lines, to make it easier to read the .ll file.
1134     std::string Asm = M->getModuleInlineAsm();
1135     size_t CurPos = 0;
1136     size_t NewLine = Asm.find_first_of('\n', CurPos);
1137     while (NewLine != std::string::npos) {
1138       // We found a newline, print the portion of the asm string from the
1139       // last newline up to this newline.
1140       Out << "module asm \"";
1141       PrintEscapedString(std::string(Asm.begin()+CurPos, Asm.begin()+NewLine),
1142                          Out);
1143       Out << "\"\n";
1144       CurPos = NewLine+1;
1145       NewLine = Asm.find_first_of('\n', CurPos);
1146     }
1147     Out << "module asm \"";
1148     PrintEscapedString(std::string(Asm.begin()+CurPos, Asm.end()), Out);
1149     Out << "\"\n";
1150   }
1151   
1152   // Loop over the dependent libraries and emit them.
1153   Module::lib_iterator LI = M->lib_begin();
1154   Module::lib_iterator LE = M->lib_end();
1155   if (LI != LE) {
1156     Out << "deplibs = [ ";
1157     while (LI != LE) {
1158       Out << '"' << *LI << '"';
1159       ++LI;
1160       if (LI != LE)
1161         Out << ", ";
1162     }
1163     Out << " ]\n";
1164   }
1165
1166   // Loop over the symbol table, emitting all id'd types.
1167   printTypeSymbolTable(M->getTypeSymbolTable());
1168
1169   for (Module::const_global_iterator I = M->global_begin(), E = M->global_end();
1170        I != E; ++I)
1171     printGlobal(I);
1172   
1173   // Output all aliases.
1174   if (!M->alias_empty()) Out << "\n";
1175   for (Module::const_alias_iterator I = M->alias_begin(), E = M->alias_end();
1176        I != E; ++I)
1177     printAlias(I);
1178
1179   // Output all of the functions.
1180   for (Module::const_iterator I = M->begin(), E = M->end(); I != E; ++I)
1181     printFunction(I);
1182 }
1183
1184 static void PrintLinkage(GlobalValue::LinkageTypes LT, raw_ostream &Out) {
1185   switch (LT) {
1186   case GlobalValue::PrivateLinkage:     Out << "private "; break;
1187   case GlobalValue::InternalLinkage:    Out << "internal "; break;
1188   case GlobalValue::LinkOnceAnyLinkage: Out << "linkonce "; break;
1189   case GlobalValue::LinkOnceODRLinkage: Out << "linkonce_odr "; break;
1190   case GlobalValue::WeakAnyLinkage:     Out << "weak "; break;
1191   case GlobalValue::WeakODRLinkage:     Out << "weak_odr "; break;
1192   case GlobalValue::CommonLinkage:      Out << "common "; break;
1193   case GlobalValue::AppendingLinkage:   Out << "appending "; break;
1194   case GlobalValue::DLLImportLinkage:   Out << "dllimport "; break;
1195   case GlobalValue::DLLExportLinkage:   Out << "dllexport "; break;
1196   case GlobalValue::ExternalWeakLinkage: Out << "extern_weak "; break;
1197   case GlobalValue::ExternalLinkage: break;
1198   case GlobalValue::GhostLinkage:
1199     Out << "GhostLinkage not allowed in AsmWriter!\n";
1200     abort();
1201   }
1202 }
1203
1204
1205 static void PrintVisibility(GlobalValue::VisibilityTypes Vis,
1206                             raw_ostream &Out) {
1207   switch (Vis) {
1208   default: assert(0 && "Invalid visibility style!");
1209   case GlobalValue::DefaultVisibility: break;
1210   case GlobalValue::HiddenVisibility:    Out << "hidden "; break;
1211   case GlobalValue::ProtectedVisibility: Out << "protected "; break;
1212   }
1213 }
1214
1215 void AssemblyWriter::printGlobal(const GlobalVariable *GV) {
1216   if (GV->hasName()) {
1217     PrintLLVMName(Out, GV);
1218     Out << " = ";
1219   }
1220
1221   if (!GV->hasInitializer() && GV->hasExternalLinkage())
1222     Out << "external ";
1223   
1224   PrintLinkage(GV->getLinkage(), Out);
1225   PrintVisibility(GV->getVisibility(), Out);
1226
1227   if (GV->isThreadLocal()) Out << "thread_local ";
1228   if (unsigned AddressSpace = GV->getType()->getAddressSpace())
1229     Out << "addrspace(" << AddressSpace << ") ";
1230   Out << (GV->isConstant() ? "constant " : "global ");
1231   TypePrinter.print(GV->getType()->getElementType(), Out);
1232
1233   if (GV->hasInitializer()) {
1234     Out << ' ';
1235     writeOperand(GV->getInitializer(), false);
1236   }
1237     
1238   if (GV->hasSection())
1239     Out << ", section \"" << GV->getSection() << '"';
1240   if (GV->getAlignment())
1241     Out << ", align " << GV->getAlignment();
1242
1243   printInfoComment(*GV);
1244   Out << '\n';
1245 }
1246
1247 void AssemblyWriter::printAlias(const GlobalAlias *GA) {
1248   // Don't crash when dumping partially built GA
1249   if (!GA->hasName())
1250     Out << "<<nameless>> = ";
1251   else {
1252     PrintLLVMName(Out, GA);
1253     Out << " = ";
1254   }
1255   PrintVisibility(GA->getVisibility(), Out);
1256
1257   Out << "alias ";
1258
1259   PrintLinkage(GA->getLinkage(), Out);
1260   
1261   const Constant *Aliasee = GA->getAliasee();
1262     
1263   if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(Aliasee)) {
1264     TypePrinter.print(GV->getType(), Out);
1265     Out << ' ';
1266     PrintLLVMName(Out, GV);
1267   } else if (const Function *F = dyn_cast<Function>(Aliasee)) {
1268     TypePrinter.print(F->getFunctionType(), Out);
1269     Out << "* ";
1270
1271     WriteAsOperandInternal(Out, F, TypePrinter, &Machine);
1272   } else if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(Aliasee)) {
1273     TypePrinter.print(GA->getType(), Out);
1274     Out << ' ';
1275     PrintLLVMName(Out, GA);
1276   } else {
1277     const ConstantExpr *CE = 0;
1278     if ((CE = dyn_cast<ConstantExpr>(Aliasee)) &&
1279         (CE->getOpcode() == Instruction::BitCast)) {
1280       writeOperand(CE, false);    
1281     } else
1282       assert(0 && "Unsupported aliasee");
1283   }
1284   
1285   printInfoComment(*GA);
1286   Out << '\n';
1287 }
1288
1289 void AssemblyWriter::printTypeSymbolTable(const TypeSymbolTable &ST) {
1290   // Emit all numbered types.
1291   for (unsigned i = 0, e = NumberedTypes.size(); i != e; ++i) {
1292     Out << "\ttype ";
1293     
1294     // Make sure we print out at least one level of the type structure, so
1295     // that we do not get %2 = type %2
1296     TypePrinter.printAtLeastOneLevel(NumberedTypes[i], Out);
1297     Out << "\t\t; type %" << i << '\n';
1298   }
1299   
1300   // Print the named types.
1301   for (TypeSymbolTable::const_iterator TI = ST.begin(), TE = ST.end();
1302        TI != TE; ++TI) {
1303     Out << '\t';
1304     PrintLLVMName(Out, &TI->first[0], TI->first.size(), LocalPrefix);
1305     Out << " = type ";
1306
1307     // Make sure we print out at least one level of the type structure, so
1308     // that we do not get %FILE = type %FILE
1309     TypePrinter.printAtLeastOneLevel(TI->second, Out);
1310     Out << '\n';
1311   }
1312 }
1313
1314 /// printFunction - Print all aspects of a function.
1315 ///
1316 void AssemblyWriter::printFunction(const Function *F) {
1317   // Print out the return type and name.
1318   Out << '\n';
1319
1320   if (AnnotationWriter) AnnotationWriter->emitFunctionAnnot(F, Out);
1321
1322   if (F->isDeclaration())
1323     Out << "declare ";
1324   else
1325     Out << "define ";
1326   
1327   PrintLinkage(F->getLinkage(), Out);
1328   PrintVisibility(F->getVisibility(), Out);
1329
1330   // Print the calling convention.
1331   switch (F->getCallingConv()) {
1332   case CallingConv::C: break;   // default
1333   case CallingConv::Fast:         Out << "fastcc "; break;
1334   case CallingConv::Cold:         Out << "coldcc "; break;
1335   case CallingConv::X86_StdCall:  Out << "x86_stdcallcc "; break;
1336   case CallingConv::X86_FastCall: Out << "x86_fastcallcc "; break; 
1337   default: Out << "cc" << F->getCallingConv() << " "; break;
1338   }
1339
1340   const FunctionType *FT = F->getFunctionType();
1341   const AttrListPtr &Attrs = F->getAttributes();
1342   Attributes RetAttrs = Attrs.getRetAttributes();
1343   if (RetAttrs != Attribute::None)
1344     Out <<  Attribute::getAsString(Attrs.getRetAttributes()) << ' ';
1345   TypePrinter.print(F->getReturnType(), Out);
1346   Out << ' ';
1347   WriteAsOperandInternal(Out, F, TypePrinter, &Machine);
1348   Out << '(';
1349   Machine.incorporateFunction(F);
1350
1351   // Loop over the arguments, printing them...
1352
1353   unsigned Idx = 1;
1354   if (!F->isDeclaration()) {
1355     // If this isn't a declaration, print the argument names as well.
1356     for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
1357          I != E; ++I) {
1358       // Insert commas as we go... the first arg doesn't get a comma
1359       if (I != F->arg_begin()) Out << ", ";
1360       printArgument(I, Attrs.getParamAttributes(Idx));
1361       Idx++;
1362     }
1363   } else {
1364     // Otherwise, print the types from the function type.
1365     for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
1366       // Insert commas as we go... the first arg doesn't get a comma
1367       if (i) Out << ", ";
1368       
1369       // Output type...
1370       TypePrinter.print(FT->getParamType(i), Out);
1371       
1372       Attributes ArgAttrs = Attrs.getParamAttributes(i+1);
1373       if (ArgAttrs != Attribute::None)
1374         Out << ' ' << Attribute::getAsString(ArgAttrs);
1375     }
1376   }
1377
1378   // Finish printing arguments...
1379   if (FT->isVarArg()) {
1380     if (FT->getNumParams()) Out << ", ";
1381     Out << "...";  // Output varargs portion of signature!
1382   }
1383   Out << ')';
1384   Attributes FnAttrs = Attrs.getFnAttributes();
1385   if (FnAttrs != Attribute::None)
1386     Out << ' ' << Attribute::getAsString(Attrs.getFnAttributes());
1387   if (F->hasSection())
1388     Out << " section \"" << F->getSection() << '"';
1389   if (F->getAlignment())
1390     Out << " align " << F->getAlignment();
1391   if (F->hasGC())
1392     Out << " gc \"" << F->getGC() << '"';
1393   if (F->isDeclaration()) {
1394     Out << "\n";
1395   } else {
1396     Out << " {";
1397
1398     // Output all of its basic blocks... for the function
1399     for (Function::const_iterator I = F->begin(), E = F->end(); I != E; ++I)
1400       printBasicBlock(I);
1401
1402     Out << "}\n";
1403   }
1404
1405   Machine.purgeFunction();
1406 }
1407
1408 /// printArgument - This member is called for every argument that is passed into
1409 /// the function.  Simply print it out
1410 ///
1411 void AssemblyWriter::printArgument(const Argument *Arg, 
1412                                    Attributes Attrs) {
1413   // Output type...
1414   TypePrinter.print(Arg->getType(), Out);
1415
1416   // Output parameter attributes list
1417   if (Attrs != Attribute::None)
1418     Out << ' ' << Attribute::getAsString(Attrs);
1419
1420   // Output name, if available...
1421   if (Arg->hasName()) {
1422     Out << ' ';
1423     PrintLLVMName(Out, Arg);
1424   }
1425 }
1426
1427 /// printBasicBlock - This member is called for each basic block in a method.
1428 ///
1429 void AssemblyWriter::printBasicBlock(const BasicBlock *BB) {
1430   if (BB->hasName()) {              // Print out the label if it exists...
1431     Out << "\n";
1432     PrintLLVMName(Out, BB->getNameStart(), BB->getNameLen(), LabelPrefix);
1433     Out << ':';
1434   } else if (!BB->use_empty()) {      // Don't print block # of no uses...
1435     Out << "\n; <label>:";
1436     int Slot = Machine.getLocalSlot(BB);
1437     if (Slot != -1)
1438       Out << Slot;
1439     else
1440       Out << "<badref>";
1441   }
1442
1443   if (BB->getParent() == 0)
1444     Out << "\t\t; Error: Block without parent!";
1445   else if (BB != &BB->getParent()->getEntryBlock()) {  // Not the entry block?
1446     // Output predecessors for the block...
1447     Out << "\t\t;";
1448     pred_const_iterator PI = pred_begin(BB), PE = pred_end(BB);
1449     
1450     if (PI == PE) {
1451       Out << " No predecessors!";
1452     } else {
1453       Out << " preds = ";
1454       writeOperand(*PI, false);
1455       for (++PI; PI != PE; ++PI) {
1456         Out << ", ";
1457         writeOperand(*PI, false);
1458       }
1459     }
1460   }
1461
1462   Out << "\n";
1463
1464   if (AnnotationWriter) AnnotationWriter->emitBasicBlockStartAnnot(BB, Out);
1465
1466   // Output all of the instructions in the basic block...
1467   for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I != E; ++I)
1468     printInstruction(*I);
1469
1470   if (AnnotationWriter) AnnotationWriter->emitBasicBlockEndAnnot(BB, Out);
1471 }
1472
1473
1474 /// printInfoComment - Print a little comment after the instruction indicating
1475 /// which slot it occupies.
1476 ///
1477 void AssemblyWriter::printInfoComment(const Value &V) {
1478   if (V.getType() != Type::VoidTy) {
1479     Out << "\t\t; <";
1480     TypePrinter.print(V.getType(), Out);
1481     Out << '>';
1482
1483     if (!V.hasName() && !isa<Instruction>(V)) {
1484       int SlotNum;
1485       if (const GlobalValue *GV = dyn_cast<GlobalValue>(&V))
1486         SlotNum = Machine.getGlobalSlot(GV);
1487       else
1488         SlotNum = Machine.getLocalSlot(&V);
1489       if (SlotNum == -1)
1490         Out << ":<badref>";
1491       else
1492         Out << ':' << SlotNum; // Print out the def slot taken.
1493     }
1494     Out << " [#uses=" << V.getNumUses() << ']';  // Output # uses
1495   }
1496 }
1497
1498 // This member is called for each Instruction in a function..
1499 void AssemblyWriter::printInstruction(const Instruction &I) {
1500   if (AnnotationWriter) AnnotationWriter->emitInstructionAnnot(&I, Out);
1501
1502   Out << '\t';
1503
1504   // Print out name if it exists...
1505   if (I.hasName()) {
1506     PrintLLVMName(Out, &I);
1507     Out << " = ";
1508   } else if (I.getType() != Type::VoidTy) {
1509     // Print out the def slot taken.
1510     int SlotNum = Machine.getLocalSlot(&I);
1511     if (SlotNum == -1)
1512       Out << "<badref> = ";
1513     else
1514       Out << '%' << SlotNum << " = ";
1515   }
1516
1517   // If this is a volatile load or store, print out the volatile marker.
1518   if ((isa<LoadInst>(I)  && cast<LoadInst>(I).isVolatile()) ||
1519       (isa<StoreInst>(I) && cast<StoreInst>(I).isVolatile())) {
1520       Out << "volatile ";
1521   } else if (isa<CallInst>(I) && cast<CallInst>(I).isTailCall()) {
1522     // If this is a call, check if it's a tail call.
1523     Out << "tail ";
1524   }
1525
1526   // Print out the opcode...
1527   Out << I.getOpcodeName();
1528
1529   // Print out the compare instruction predicates
1530   if (const CmpInst *CI = dyn_cast<CmpInst>(&I))
1531     Out << ' ' << getPredicateText(CI->getPredicate());
1532
1533   // Print out the type of the operands...
1534   const Value *Operand = I.getNumOperands() ? I.getOperand(0) : 0;
1535
1536   // Special case conditional branches to swizzle the condition out to the front
1537   if (isa<BranchInst>(I) && cast<BranchInst>(I).isConditional()) {
1538     BranchInst &BI(cast<BranchInst>(I));
1539     Out << ' ';
1540     writeOperand(BI.getCondition(), true);
1541     Out << ", ";
1542     writeOperand(BI.getSuccessor(0), true);
1543     Out << ", ";
1544     writeOperand(BI.getSuccessor(1), true);
1545
1546   } else if (isa<SwitchInst>(I)) {
1547     // Special case switch statement to get formatting nice and correct...
1548     Out << ' ';
1549     writeOperand(Operand        , true);
1550     Out << ", ";
1551     writeOperand(I.getOperand(1), true);
1552     Out << " [";
1553
1554     for (unsigned op = 2, Eop = I.getNumOperands(); op < Eop; op += 2) {
1555       Out << "\n\t\t";
1556       writeOperand(I.getOperand(op  ), true);
1557       Out << ", ";
1558       writeOperand(I.getOperand(op+1), true);
1559     }
1560     Out << "\n\t]";
1561   } else if (isa<PHINode>(I)) {
1562     Out << ' ';
1563     TypePrinter.print(I.getType(), Out);
1564     Out << ' ';
1565
1566     for (unsigned op = 0, Eop = I.getNumOperands(); op < Eop; op += 2) {
1567       if (op) Out << ", ";
1568       Out << "[ ";
1569       writeOperand(I.getOperand(op  ), false); Out << ", ";
1570       writeOperand(I.getOperand(op+1), false); Out << " ]";
1571     }
1572   } else if (const ExtractValueInst *EVI = dyn_cast<ExtractValueInst>(&I)) {
1573     Out << ' ';
1574     writeOperand(I.getOperand(0), true);
1575     for (const unsigned *i = EVI->idx_begin(), *e = EVI->idx_end(); i != e; ++i)
1576       Out << ", " << *i;
1577   } else if (const InsertValueInst *IVI = dyn_cast<InsertValueInst>(&I)) {
1578     Out << ' ';
1579     writeOperand(I.getOperand(0), true); Out << ", ";
1580     writeOperand(I.getOperand(1), true);
1581     for (const unsigned *i = IVI->idx_begin(), *e = IVI->idx_end(); i != e; ++i)
1582       Out << ", " << *i;
1583   } else if (isa<ReturnInst>(I) && !Operand) {
1584     Out << " void";
1585   } else if (const CallInst *CI = dyn_cast<CallInst>(&I)) {
1586     // Print the calling convention being used.
1587     switch (CI->getCallingConv()) {
1588     case CallingConv::C: break;   // default
1589     case CallingConv::Fast:  Out << " fastcc"; break;
1590     case CallingConv::Cold:  Out << " coldcc"; break;
1591     case CallingConv::X86_StdCall:  Out << " x86_stdcallcc"; break;
1592     case CallingConv::X86_FastCall: Out << " x86_fastcallcc"; break; 
1593     default: Out << " cc" << CI->getCallingConv(); break;
1594     }
1595
1596     const PointerType    *PTy = cast<PointerType>(Operand->getType());
1597     const FunctionType   *FTy = cast<FunctionType>(PTy->getElementType());
1598     const Type         *RetTy = FTy->getReturnType();
1599     const AttrListPtr &PAL = CI->getAttributes();
1600
1601     if (PAL.getRetAttributes() != Attribute::None)
1602       Out << ' ' << Attribute::getAsString(PAL.getRetAttributes());
1603
1604     // If possible, print out the short form of the call instruction.  We can
1605     // only do this if the first argument is a pointer to a nonvararg function,
1606     // and if the return type is not a pointer to a function.
1607     //
1608     Out << ' ';
1609     if (!FTy->isVarArg() &&
1610         (!isa<PointerType>(RetTy) ||
1611          !isa<FunctionType>(cast<PointerType>(RetTy)->getElementType()))) {
1612       TypePrinter.print(RetTy, Out);
1613       Out << ' ';
1614       writeOperand(Operand, false);
1615     } else {
1616       writeOperand(Operand, true);
1617     }
1618     Out << '(';
1619     for (unsigned op = 1, Eop = I.getNumOperands(); op < Eop; ++op) {
1620       if (op > 1)
1621         Out << ", ";
1622       writeParamOperand(I.getOperand(op), PAL.getParamAttributes(op));
1623     }
1624     Out << ')';
1625     if (PAL.getFnAttributes() != Attribute::None)
1626       Out << ' ' << Attribute::getAsString(PAL.getFnAttributes());
1627   } else if (const InvokeInst *II = dyn_cast<InvokeInst>(&I)) {
1628     Operand = II->getCalledValue();
1629     const PointerType    *PTy = cast<PointerType>(Operand->getType());
1630     const FunctionType   *FTy = cast<FunctionType>(PTy->getElementType());
1631     const Type         *RetTy = FTy->getReturnType();
1632     const AttrListPtr &PAL = II->getAttributes();
1633
1634     // Print the calling convention being used.
1635     switch (II->getCallingConv()) {
1636     case CallingConv::C: break;   // default
1637     case CallingConv::Fast:  Out << " fastcc"; break;
1638     case CallingConv::Cold:  Out << " coldcc"; break;
1639     case CallingConv::X86_StdCall:  Out << " x86_stdcallcc"; break;
1640     case CallingConv::X86_FastCall: Out << " x86_fastcallcc"; break;
1641     default: Out << " cc" << II->getCallingConv(); break;
1642     }
1643
1644     if (PAL.getRetAttributes() != Attribute::None)
1645       Out << ' ' << Attribute::getAsString(PAL.getRetAttributes());
1646
1647     // If possible, print out the short form of the invoke instruction. We can
1648     // only do this if the first argument is a pointer to a nonvararg function,
1649     // and if the return type is not a pointer to a function.
1650     //
1651     Out << ' ';
1652     if (!FTy->isVarArg() &&
1653         (!isa<PointerType>(RetTy) ||
1654          !isa<FunctionType>(cast<PointerType>(RetTy)->getElementType()))) {
1655       TypePrinter.print(RetTy, Out);
1656       Out << ' ';
1657       writeOperand(Operand, false);
1658     } else {
1659       writeOperand(Operand, true);
1660     }
1661     Out << '(';
1662     for (unsigned op = 0, Eop = I.getNumOperands() - 3; op < Eop; ++op) {
1663       if (op)
1664         Out << ", ";
1665       writeParamOperand(I.getOperand(op), PAL.getParamAttributes(op + 1));
1666     }
1667
1668     Out << ')';
1669     if (PAL.getFnAttributes() != Attribute::None)
1670       Out << ' ' << Attribute::getAsString(PAL.getFnAttributes());
1671
1672     Out << "\n\t\t\tto ";
1673     writeOperand(II->getNormalDest(), true);
1674     Out << " unwind ";
1675     writeOperand(II->getUnwindDest(), true);
1676
1677   } else if (const AllocationInst *AI = dyn_cast<AllocationInst>(&I)) {
1678     Out << ' ';
1679     TypePrinter.print(AI->getType()->getElementType(), Out);
1680     if (AI->isArrayAllocation()) {
1681       Out << ", ";
1682       writeOperand(AI->getArraySize(), true);
1683     }
1684     if (AI->getAlignment()) {
1685       Out << ", align " << AI->getAlignment();
1686     }
1687   } else if (isa<CastInst>(I)) {
1688     if (Operand) {
1689       Out << ' ';
1690       writeOperand(Operand, true);   // Work with broken code
1691     }
1692     Out << " to ";
1693     TypePrinter.print(I.getType(), Out);
1694   } else if (isa<VAArgInst>(I)) {
1695     if (Operand) {
1696       Out << ' ';
1697       writeOperand(Operand, true);   // Work with broken code
1698     }
1699     Out << ", ";
1700     TypePrinter.print(I.getType(), Out);
1701   } else if (Operand) {   // Print the normal way.
1702
1703     // PrintAllTypes - Instructions who have operands of all the same type
1704     // omit the type from all but the first operand.  If the instruction has
1705     // different type operands (for example br), then they are all printed.
1706     bool PrintAllTypes = false;
1707     const Type *TheType = Operand->getType();
1708
1709     // Select, Store and ShuffleVector always print all types.
1710     if (isa<SelectInst>(I) || isa<StoreInst>(I) || isa<ShuffleVectorInst>(I)
1711         || isa<ReturnInst>(I)) {
1712       PrintAllTypes = true;
1713     } else {
1714       for (unsigned i = 1, E = I.getNumOperands(); i != E; ++i) {
1715         Operand = I.getOperand(i);
1716         // note that Operand shouldn't be null, but the test helps make dump()
1717         // more tolerant of malformed IR
1718         if (Operand && Operand->getType() != TheType) {
1719           PrintAllTypes = true;    // We have differing types!  Print them all!
1720           break;
1721         }
1722       }
1723     }
1724
1725     if (!PrintAllTypes) {
1726       Out << ' ';
1727       TypePrinter.print(TheType, Out);
1728     }
1729
1730     Out << ' ';
1731     for (unsigned i = 0, E = I.getNumOperands(); i != E; ++i) {
1732       if (i) Out << ", ";
1733       writeOperand(I.getOperand(i), PrintAllTypes);
1734     }
1735   }
1736   
1737   // Print post operand alignment for load/store
1738   if (isa<LoadInst>(I) && cast<LoadInst>(I).getAlignment()) {
1739     Out << ", align " << cast<LoadInst>(I).getAlignment();
1740   } else if (isa<StoreInst>(I) && cast<StoreInst>(I).getAlignment()) {
1741     Out << ", align " << cast<StoreInst>(I).getAlignment();
1742   }
1743
1744   printInfoComment(I);
1745   Out << '\n';
1746 }
1747
1748
1749 //===----------------------------------------------------------------------===//
1750 //                       External Interface declarations
1751 //===----------------------------------------------------------------------===//
1752
1753 void Module::print(std::ostream &o, AssemblyAnnotationWriter *AAW) const {
1754   raw_os_ostream OS(o);
1755   print(OS, AAW);
1756 }
1757 void Module::print(raw_ostream &OS, AssemblyAnnotationWriter *AAW) const {
1758   SlotTracker SlotTable(this);
1759   AssemblyWriter W(OS, SlotTable, this, AAW);
1760   W.write(this);
1761 }
1762
1763 void Type::print(std::ostream &o) const {
1764   raw_os_ostream OS(o);
1765   print(OS);
1766 }
1767
1768 void Type::print(raw_ostream &OS) const {
1769   if (this == 0) {
1770     OS << "<null Type>";
1771     return;
1772   }
1773   TypePrinting().print(this, OS);
1774 }
1775
1776 void Value::print(raw_ostream &OS, AssemblyAnnotationWriter *AAW) const {
1777   if (this == 0) {
1778     OS << "printing a <null> value\n";
1779     return;
1780   }
1781
1782   if (const Instruction *I = dyn_cast<Instruction>(this)) {
1783     const Function *F = I->getParent() ? I->getParent()->getParent() : 0;
1784     SlotTracker SlotTable(F);
1785     AssemblyWriter W(OS, SlotTable, F ? F->getParent() : 0, AAW);
1786     W.write(I);
1787   } else if (const BasicBlock *BB = dyn_cast<BasicBlock>(this)) {
1788     SlotTracker SlotTable(BB->getParent());
1789     AssemblyWriter W(OS, SlotTable,
1790                      BB->getParent() ? BB->getParent()->getParent() : 0, AAW);
1791     W.write(BB);
1792   } else if (const GlobalValue *GV = dyn_cast<GlobalValue>(this)) {
1793     SlotTracker SlotTable(GV->getParent());
1794     AssemblyWriter W(OS, SlotTable, GV->getParent(), 0);
1795     W.write(GV);
1796   } else if (const Constant *C = dyn_cast<Constant>(this)) {
1797     TypePrinting TypePrinter;
1798     TypePrinter.print(C->getType(), OS);
1799     OS << ' ';
1800     WriteConstantInt(OS, C, TypePrinter, 0);
1801   } else if (const Argument *A = dyn_cast<Argument>(this)) {
1802     WriteAsOperand(OS, this, true,
1803                    A->getParent() ? A->getParent()->getParent() : 0);
1804   } else if (isa<InlineAsm>(this)) {
1805     WriteAsOperand(OS, this, true, 0);
1806   } else {
1807     assert(0 && "Unknown value to print out!");
1808   }
1809 }
1810
1811 void Value::print(std::ostream &O, AssemblyAnnotationWriter *AAW) const {
1812   raw_os_ostream OS(O);
1813   print(OS, AAW);
1814 }
1815
1816 // Value::dump - allow easy printing of Values from the debugger.
1817 void Value::dump() const { print(errs()); errs() << '\n'; errs().flush(); }
1818
1819 // Type::dump - allow easy printing of Types from the debugger.
1820 // This one uses type names from the given context module
1821 void Type::dump(const Module *Context) const {
1822   WriteTypeSymbolic(errs(), this, Context);
1823   errs() << '\n';
1824   errs().flush();
1825 }
1826
1827 // Type::dump - allow easy printing of Types from the debugger.
1828 void Type::dump() const { dump(0); }
1829
1830 // Module::dump() - Allow printing of Modules from the debugger.
1831 void Module::dump() const { print(errs(), 0); errs().flush(); }