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