1 //===-- AsmWriter.cpp - Printing LLVM as an assembly file -----------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This library implements the functionality defined in llvm/Assembly/Writer.h
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.
15 //===----------------------------------------------------------------------===//
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/DenseMap.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/Streams.h"
35 #include "llvm/Support/raw_ostream.h"
42 // Make virtual table appear in this compilation unit.
43 AssemblyAnnotationWriter::~AssemblyAnnotationWriter() {}
45 /// This class provides computation of slot numbers for LLVM Assembly writing.
49 /// ValueMap - A mapping of Values to slot numbers
50 typedef DenseMap<const Value*, unsigned> ValueMap;
53 /// TheModule - The module for which we are holding slot numbers
54 const Module* TheModule;
56 /// TheFunction - The function for which we are holding slot numbers
57 const Function* TheFunction;
58 bool FunctionProcessed;
60 /// mMap - The TypePlanes map for the module level data
64 /// fMap - The TypePlanes map for the function level data
69 /// Construct from a module
70 explicit SlotTracker(const Module *M);
71 /// Construct from a function, starting out in incorp state.
72 explicit SlotTracker(const Function *F);
74 /// Return the slot number of the specified value in it's type
75 /// plane. If something is not in the SlotTracker, return -1.
76 int getLocalSlot(const Value *V);
77 int getGlobalSlot(const GlobalValue *V);
79 /// If you'd like to deal with a function instead of just a module, use
80 /// this method to get its data into the SlotTracker.
81 void incorporateFunction(const Function *F) {
83 FunctionProcessed = false;
86 /// After calling incorporateFunction, use this method to remove the
87 /// most recently incorporated function from the SlotTracker. This
88 /// will reset the state of the machine back to just the module contents.
91 // Implementation Details
93 /// This function does the actual initialization.
94 inline void initialize();
96 /// CreateModuleSlot - Insert the specified GlobalValue* into the slot table.
97 void CreateModuleSlot(const GlobalValue *V);
99 /// CreateFunctionSlot - Insert the specified Value* into the slot table.
100 void CreateFunctionSlot(const Value *V);
102 /// Add all of the module level global variables (and their initializers)
103 /// and function declarations, but not the contents of those functions.
104 void processModule();
106 /// Add all of the functions arguments, basic blocks, and instructions
107 void processFunction();
109 SlotTracker(const SlotTracker &); // DO NOT IMPLEMENT
110 void operator=(const SlotTracker &); // DO NOT IMPLEMENT
113 } // end namespace llvm
115 char PrintModulePass::ID = 0;
116 static RegisterPass<PrintModulePass>
117 X("printm", "Print module to stderr");
118 char PrintFunctionPass::ID = 0;
119 static RegisterPass<PrintFunctionPass>
120 Y("print","Print function to stderr");
122 static void WriteAsOperandInternal(std::ostream &Out, const Value *V,
123 std::map<const Type *, std::string> &TypeTable,
124 SlotTracker *Machine);
126 static const Module *getModuleFromVal(const Value *V) {
127 if (const Argument *MA = dyn_cast<Argument>(V))
128 return MA->getParent() ? MA->getParent()->getParent() : 0;
129 else if (const BasicBlock *BB = dyn_cast<BasicBlock>(V))
130 return BB->getParent() ? BB->getParent()->getParent() : 0;
131 else if (const Instruction *I = dyn_cast<Instruction>(V)) {
132 const Function *M = I->getParent() ? I->getParent()->getParent() : 0;
133 return M ? M->getParent() : 0;
134 } else if (const GlobalValue *GV = dyn_cast<GlobalValue>(V))
135 return GV->getParent();
139 static SlotTracker *createSlotTracker(const Value *V) {
140 if (const Argument *FA = dyn_cast<Argument>(V)) {
141 return new SlotTracker(FA->getParent());
142 } else if (const Instruction *I = dyn_cast<Instruction>(V)) {
143 return new SlotTracker(I->getParent()->getParent());
144 } else if (const BasicBlock *BB = dyn_cast<BasicBlock>(V)) {
145 return new SlotTracker(BB->getParent());
146 } else if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(V)){
147 return new SlotTracker(GV->getParent());
148 } else if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(V)){
149 return new SlotTracker(GA->getParent());
150 } else if (const Function *Func = dyn_cast<Function>(V)) {
151 return new SlotTracker(Func);
156 /// NameNeedsQuotes - Return true if the specified llvm name should be wrapped
158 static std::string QuoteNameIfNeeded(const std::string &Name) {
160 bool needsQuotes = Name[0] >= '0' && Name[0] <= '9';
161 // Scan the name to see if it needs quotes and to replace funky chars with
162 // their octal equivalent.
163 for (unsigned i = 0, e = Name.size(); i != e; ++i) {
165 assert(C != '"' && "Illegal character in LLVM value name!");
166 if (isalnum(C) || C == '-' || C == '.' || C == '_')
168 else if (C == '\\') {
171 } else if (isprint(C)) {
177 char hex1 = (C >> 4) & 0x0F;
179 result += hex1 + '0';
181 result += hex1 - 10 + 'A';
182 char hex2 = C & 0x0F;
184 result += hex2 + '0';
186 result += hex2 - 10 + 'A';
190 result.insert(0,"\"");
196 /// getLLVMName - Turn the specified string into an 'LLVM name', which is either
197 /// prefixed with % (if the string only contains simple characters) or is
198 /// surrounded with ""'s (if it has special chars in it).
199 static std::string getLLVMName(const std::string &Name) {
200 assert(!Name.empty() && "Cannot get empty name!");
201 return '%' + QuoteNameIfNeeded(Name);
210 /// PrintLLVMName - Turn the specified name into an 'LLVM name', which is either
211 /// prefixed with % (if the string only contains simple characters) or is
212 /// surrounded with ""'s (if it has special chars in it). Print it out.
213 static void PrintLLVMName(std::ostream &OS, const ValueName *Name,
215 assert(Name && "Cannot get empty name!");
217 default: assert(0 && "Bad prefix!");
218 case GlobalPrefix: OS << '@'; break;
219 case LabelPrefix: break;
220 case LocalPrefix: OS << '%'; break;
223 // Scan the name to see if it needs quotes first.
224 const char *NameStr = Name->getKeyData();
225 unsigned NameLen = Name->getKeyLength();
227 bool NeedsQuotes = NameStr[0] >= '0' && NameStr[0] <= '9';
229 for (unsigned i = 0; i != NameLen; ++i) {
231 if (!isalnum(C) && C != '-' && C != '.' && C != '_') {
238 // If we didn't need any quotes, just write out the name in one blast.
240 OS.write(NameStr, NameLen);
244 // Okay, we need quotes. Output the quotes and escape any scary characters as
247 for (unsigned i = 0; i != NameLen; ++i) {
249 assert(C != '"' && "Illegal character in LLVM value name!");
252 } else if (isprint(C)) {
256 char hex1 = (C >> 4) & 0x0F;
258 OS << (char)(hex1 + '0');
260 OS << (char)(hex1 - 10 + 'A');
261 char hex2 = C & 0x0F;
263 OS << (char)(hex2 + '0');
265 OS << (char)(hex2 - 10 + 'A');
271 static void PrintLLVMName(std::ostream &OS, const Value *V) {
272 PrintLLVMName(OS, V->getValueName(),
273 isa<GlobalValue>(V) ? GlobalPrefix : LocalPrefix);
277 /// fillTypeNameTable - If the module has a symbol table, take all global types
278 /// and stuff their names into the TypeNames map.
280 static void fillTypeNameTable(const Module *M,
281 std::map<const Type *, std::string> &TypeNames) {
283 const TypeSymbolTable &ST = M->getTypeSymbolTable();
284 TypeSymbolTable::const_iterator TI = ST.begin();
285 for (; TI != ST.end(); ++TI) {
286 // As a heuristic, don't insert pointer to primitive types, because
287 // they are used too often to have a single useful name.
289 const Type *Ty = cast<Type>(TI->second);
290 if (!isa<PointerType>(Ty) ||
291 !cast<PointerType>(Ty)->getElementType()->isPrimitiveType() ||
292 !cast<PointerType>(Ty)->getElementType()->isInteger() ||
293 isa<OpaqueType>(cast<PointerType>(Ty)->getElementType()))
294 TypeNames.insert(std::make_pair(Ty, getLLVMName(TI->first)));
300 static void calcTypeName(const Type *Ty,
301 std::vector<const Type *> &TypeStack,
302 std::map<const Type *, std::string> &TypeNames,
303 std::string & Result){
304 if (Ty->isInteger() || (Ty->isPrimitiveType() && !isa<OpaqueType>(Ty))) {
305 Result += Ty->getDescription(); // Base case
309 // Check to see if the type is named.
310 std::map<const Type *, std::string>::iterator I = TypeNames.find(Ty);
311 if (I != TypeNames.end()) {
316 if (isa<OpaqueType>(Ty)) {
321 // Check to see if the Type is already on the stack...
322 unsigned Slot = 0, CurSize = TypeStack.size();
323 while (Slot < CurSize && TypeStack[Slot] != Ty) ++Slot; // Scan for type
325 // This is another base case for the recursion. In this case, we know
326 // that we have looped back to a type that we have previously visited.
327 // Generate the appropriate upreference to handle this.
328 if (Slot < CurSize) {
329 Result += "\\" + utostr(CurSize-Slot); // Here's the upreference
333 TypeStack.push_back(Ty); // Recursive case: Add us to the stack..
335 switch (Ty->getTypeID()) {
336 case Type::IntegerTyID: {
337 unsigned BitWidth = cast<IntegerType>(Ty)->getBitWidth();
338 Result += "i" + utostr(BitWidth);
341 case Type::FunctionTyID: {
342 const FunctionType *FTy = cast<FunctionType>(Ty);
343 calcTypeName(FTy->getReturnType(), TypeStack, TypeNames, Result);
345 for (FunctionType::param_iterator I = FTy->param_begin(),
346 E = FTy->param_end(); I != E; ++I) {
347 if (I != FTy->param_begin())
349 calcTypeName(*I, TypeStack, TypeNames, Result);
351 if (FTy->isVarArg()) {
352 if (FTy->getNumParams()) Result += ", ";
358 case Type::StructTyID: {
359 const StructType *STy = cast<StructType>(Ty);
363 for (StructType::element_iterator I = STy->element_begin(),
364 E = STy->element_end(); I != E; ++I) {
365 if (I != STy->element_begin())
367 calcTypeName(*I, TypeStack, TypeNames, Result);
374 case Type::PointerTyID: {
375 const PointerType *PTy = cast<PointerType>(Ty);
376 calcTypeName(PTy->getElementType(),
377 TypeStack, TypeNames, Result);
378 if (unsigned AddressSpace = PTy->getAddressSpace())
379 Result += " addrspace(" + utostr(AddressSpace) + ")";
383 case Type::ArrayTyID: {
384 const ArrayType *ATy = cast<ArrayType>(Ty);
385 Result += "[" + utostr(ATy->getNumElements()) + " x ";
386 calcTypeName(ATy->getElementType(), TypeStack, TypeNames, Result);
390 case Type::VectorTyID: {
391 const VectorType *PTy = cast<VectorType>(Ty);
392 Result += "<" + utostr(PTy->getNumElements()) + " x ";
393 calcTypeName(PTy->getElementType(), TypeStack, TypeNames, Result);
397 case Type::OpaqueTyID:
401 Result += "<unrecognized-type>";
405 TypeStack.pop_back(); // Remove self from stack...
409 /// printTypeInt - The internal guts of printing out a type that has a
410 /// potentially named portion.
412 static std::ostream &printTypeInt(std::ostream &Out, const Type *Ty,
413 std::map<const Type *, std::string> &TypeNames) {
414 // Primitive types always print out their description, regardless of whether
415 // they have been named or not.
417 if (Ty->isInteger() || (Ty->isPrimitiveType() && !isa<OpaqueType>(Ty)))
418 return Out << Ty->getDescription();
420 // Check to see if the type is named.
421 std::map<const Type *, std::string>::iterator I = TypeNames.find(Ty);
422 if (I != TypeNames.end()) return Out << I->second;
424 // Otherwise we have a type that has not been named but is a derived type.
425 // Carefully recurse the type hierarchy to print out any contained symbolic
428 std::vector<const Type *> TypeStack;
429 std::string TypeName;
430 calcTypeName(Ty, TypeStack, TypeNames, TypeName);
431 TypeNames.insert(std::make_pair(Ty, TypeName));//Cache type name for later use
432 return (Out << TypeName);
436 /// WriteTypeSymbolic - This attempts to write the specified type as a symbolic
437 /// type, iff there is an entry in the modules symbol table for the specified
438 /// type or one of it's component types. This is slower than a simple x << Type
440 std::ostream &llvm::WriteTypeSymbolic(std::ostream &Out, const Type *Ty,
444 // If they want us to print out a type, but there is no context, we can't
445 // print it symbolically.
447 return Out << Ty->getDescription();
449 std::map<const Type *, std::string> TypeNames;
450 fillTypeNameTable(M, TypeNames);
451 return printTypeInt(Out, Ty, TypeNames);
454 // PrintEscapedString - Print each character of the specified string, escaping
455 // it if it is not printable or if it is an escape char.
456 static void PrintEscapedString(const std::string &Str, std::ostream &Out) {
457 for (unsigned i = 0, e = Str.size(); i != e; ++i) {
458 unsigned char C = Str[i];
459 if (isprint(C) && C != '"' && C != '\\') {
463 << (char) ((C/16 < 10) ? ( C/16 +'0') : ( C/16 -10+'A'))
464 << (char)(((C&15) < 10) ? ((C&15)+'0') : ((C&15)-10+'A'));
469 static const char *getPredicateText(unsigned predicate) {
470 const char * pred = "unknown";
472 case FCmpInst::FCMP_FALSE: pred = "false"; break;
473 case FCmpInst::FCMP_OEQ: pred = "oeq"; break;
474 case FCmpInst::FCMP_OGT: pred = "ogt"; break;
475 case FCmpInst::FCMP_OGE: pred = "oge"; break;
476 case FCmpInst::FCMP_OLT: pred = "olt"; break;
477 case FCmpInst::FCMP_OLE: pred = "ole"; break;
478 case FCmpInst::FCMP_ONE: pred = "one"; break;
479 case FCmpInst::FCMP_ORD: pred = "ord"; break;
480 case FCmpInst::FCMP_UNO: pred = "uno"; break;
481 case FCmpInst::FCMP_UEQ: pred = "ueq"; break;
482 case FCmpInst::FCMP_UGT: pred = "ugt"; break;
483 case FCmpInst::FCMP_UGE: pred = "uge"; break;
484 case FCmpInst::FCMP_ULT: pred = "ult"; break;
485 case FCmpInst::FCMP_ULE: pred = "ule"; break;
486 case FCmpInst::FCMP_UNE: pred = "une"; break;
487 case FCmpInst::FCMP_TRUE: pred = "true"; break;
488 case ICmpInst::ICMP_EQ: pred = "eq"; break;
489 case ICmpInst::ICMP_NE: pred = "ne"; break;
490 case ICmpInst::ICMP_SGT: pred = "sgt"; break;
491 case ICmpInst::ICMP_SGE: pred = "sge"; break;
492 case ICmpInst::ICMP_SLT: pred = "slt"; break;
493 case ICmpInst::ICMP_SLE: pred = "sle"; break;
494 case ICmpInst::ICMP_UGT: pred = "ugt"; break;
495 case ICmpInst::ICMP_UGE: pred = "uge"; break;
496 case ICmpInst::ICMP_ULT: pred = "ult"; break;
497 case ICmpInst::ICMP_ULE: pred = "ule"; break;
502 static void WriteConstantInt(std::ostream &Out, const Constant *CV,
503 std::map<const Type *, std::string> &TypeTable,
504 SlotTracker *Machine) {
505 const int IndentSize = 4;
506 // FIXME: WHY IS INDENT STATIC??
507 static std::string Indent = "\n";
508 if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV)) {
509 if (CI->getType() == Type::Int1Ty) {
510 Out << (CI->getZExtValue() ? "true" : "false");
513 Out << CI->getValue();
517 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CV)) {
518 if (&CFP->getValueAPF().getSemantics() == &APFloat::IEEEdouble ||
519 &CFP->getValueAPF().getSemantics() == &APFloat::IEEEsingle) {
520 // We would like to output the FP constant value in exponential notation,
521 // but we cannot do this if doing so will lose precision. Check here to
522 // make sure that we only output it in exponential format if we can parse
523 // the value back and get the same value.
525 bool isDouble = &CFP->getValueAPF().getSemantics()==&APFloat::IEEEdouble;
526 double Val = isDouble ? CFP->getValueAPF().convertToDouble() :
527 CFP->getValueAPF().convertToFloat();
528 std::string StrVal = ftostr(CFP->getValueAPF());
530 // Check to make sure that the stringized number is not some string like
531 // "Inf" or NaN, that atof will accept, but the lexer will not. Check
532 // that the string matches the "[-+]?[0-9]" regex.
534 if ((StrVal[0] >= '0' && StrVal[0] <= '9') ||
535 ((StrVal[0] == '-' || StrVal[0] == '+') &&
536 (StrVal[1] >= '0' && StrVal[1] <= '9'))) {
537 // Reparse stringized version!
538 if (atof(StrVal.c_str()) == Val) {
543 // Otherwise we could not reparse it to exactly the same value, so we must
544 // output the string in hexadecimal format!
545 assert(sizeof(double) == sizeof(uint64_t) &&
546 "assuming that double is 64 bits!");
547 Out << "0x" << utohexstr(DoubleToBits(Val));
549 // Some form of long double. These appear as a magic letter identifying
550 // the type, then a fixed number of hex digits.
552 if (&CFP->getValueAPF().getSemantics() == &APFloat::x87DoubleExtended)
554 else if (&CFP->getValueAPF().getSemantics() == &APFloat::IEEEquad)
556 else if (&CFP->getValueAPF().getSemantics() == &APFloat::PPCDoubleDouble)
559 assert(0 && "Unsupported floating point type");
560 // api needed to prevent premature destruction
561 APInt api = CFP->getValueAPF().convertToAPInt();
562 const uint64_t* p = api.getRawData();
565 int width = api.getBitWidth();
566 for (int j=0; j<width; j+=4, shiftcount-=4) {
567 unsigned int nibble = (word>>shiftcount) & 15;
569 Out << (unsigned char)(nibble + '0');
571 Out << (unsigned char)(nibble - 10 + 'A');
572 if (shiftcount == 0 && j+4 < width) {
576 shiftcount = width-j-4;
580 } else if (isa<ConstantAggregateZero>(CV)) {
581 Out << "zeroinitializer";
582 } else if (const ConstantArray *CA = dyn_cast<ConstantArray>(CV)) {
583 // As a special case, print the array as a string if it is an array of
584 // i8 with ConstantInt values.
586 const Type *ETy = CA->getType()->getElementType();
587 if (CA->isString()) {
589 PrintEscapedString(CA->getAsString(), Out);
592 } else { // Cannot output in string format...
594 if (CA->getNumOperands()) {
596 printTypeInt(Out, ETy, TypeTable);
597 WriteAsOperandInternal(Out, CA->getOperand(0),
599 for (unsigned i = 1, e = CA->getNumOperands(); i != e; ++i) {
601 printTypeInt(Out, ETy, TypeTable);
602 WriteAsOperandInternal(Out, CA->getOperand(i), TypeTable, Machine);
607 } else if (const ConstantStruct *CS = dyn_cast<ConstantStruct>(CV)) {
608 if (CS->getType()->isPacked())
611 unsigned N = CS->getNumOperands();
614 Indent += std::string(IndentSize, ' ');
619 printTypeInt(Out, CS->getOperand(0)->getType(), TypeTable);
621 WriteAsOperandInternal(Out, CS->getOperand(0), TypeTable, Machine);
623 for (unsigned i = 1; i < N; i++) {
625 if (N > 2) Out << Indent;
626 printTypeInt(Out, CS->getOperand(i)->getType(), TypeTable);
628 WriteAsOperandInternal(Out, CS->getOperand(i), TypeTable, Machine);
630 if (N > 2) Indent.resize(Indent.size() - IndentSize);
634 if (CS->getType()->isPacked())
636 } else if (const ConstantVector *CP = dyn_cast<ConstantVector>(CV)) {
637 const Type *ETy = CP->getType()->getElementType();
638 assert(CP->getNumOperands() > 0 &&
639 "Number of operands for a PackedConst must be > 0");
642 printTypeInt(Out, ETy, TypeTable);
643 WriteAsOperandInternal(Out, CP->getOperand(0), TypeTable, Machine);
644 for (unsigned i = 1, e = CP->getNumOperands(); i != e; ++i) {
646 printTypeInt(Out, ETy, TypeTable);
647 WriteAsOperandInternal(Out, CP->getOperand(i), TypeTable, Machine);
650 } else if (isa<ConstantPointerNull>(CV)) {
653 } else if (isa<UndefValue>(CV)) {
656 } else if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV)) {
657 Out << CE->getOpcodeName();
659 Out << " " << getPredicateText(CE->getPredicate());
662 for (User::const_op_iterator OI=CE->op_begin(); OI != CE->op_end(); ++OI) {
663 printTypeInt(Out, (*OI)->getType(), TypeTable);
664 WriteAsOperandInternal(Out, *OI, TypeTable, Machine);
665 if (OI+1 != CE->op_end())
669 if (CE->hasIndices()) {
670 const SmallVector<unsigned, 4> &Indices = CE->getIndices();
671 for (unsigned i = 0, e = Indices.size(); i != e; ++i)
672 Out << ", " << Indices[i];
677 printTypeInt(Out, CE->getType(), TypeTable);
683 Out << "<placeholder or erroneous Constant>";
688 /// WriteAsOperand - Write the name of the specified value out to the specified
689 /// ostream. This can be useful when you just want to print int %reg126, not
690 /// the whole instruction that generated it.
692 static void WriteAsOperandInternal(std::ostream &Out, const Value *V,
693 std::map<const Type*, std::string> &TypeTable,
694 SlotTracker *Machine) {
697 PrintLLVMName(Out, V);
701 const Constant *CV = dyn_cast<Constant>(V);
702 if (CV && !isa<GlobalValue>(CV)) {
703 WriteConstantInt(Out, CV, TypeTable, Machine);
704 } else if (const InlineAsm *IA = dyn_cast<InlineAsm>(V)) {
706 if (IA->hasSideEffects())
707 Out << "sideeffect ";
709 PrintEscapedString(IA->getAsmString(), Out);
711 PrintEscapedString(IA->getConstraintString(), Out);
717 if (const GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
718 Slot = Machine->getGlobalSlot(GV);
721 Slot = Machine->getLocalSlot(V);
724 Machine = createSlotTracker(V);
726 if (const GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
727 Slot = Machine->getGlobalSlot(GV);
730 Slot = Machine->getLocalSlot(V);
738 Out << Prefix << Slot;
744 /// WriteAsOperand - Write the name of the specified value out to the specified
745 /// ostream. This can be useful when you just want to print int %reg126, not
746 /// the whole instruction that generated it.
748 std::ostream &llvm::WriteAsOperand(std::ostream &Out, const Value *V,
749 bool PrintType, const Module *Context) {
750 std::map<const Type *, std::string> TypeNames;
751 if (Context == 0) Context = getModuleFromVal(V);
754 fillTypeNameTable(Context, TypeNames);
757 printTypeInt(Out, V->getType(), TypeNames);
759 WriteAsOperandInternal(Out, V, TypeNames, 0);
766 class AssemblyWriter {
768 SlotTracker &Machine;
769 const Module *TheModule;
770 std::map<const Type *, std::string> TypeNames;
771 AssemblyAnnotationWriter *AnnotationWriter;
773 inline AssemblyWriter(std::ostream &o, SlotTracker &Mac, const Module *M,
774 AssemblyAnnotationWriter *AAW)
775 : Out(o), Machine(Mac), TheModule(M), AnnotationWriter(AAW) {
777 // If the module has a symbol table, take all global types and stuff their
778 // names into the TypeNames map.
780 fillTypeNameTable(M, TypeNames);
783 inline void write(const Module *M) { printModule(M); }
784 inline void write(const GlobalVariable *G) { printGlobal(G); }
785 inline void write(const GlobalAlias *G) { printAlias(G); }
786 inline void write(const Function *F) { printFunction(F); }
787 inline void write(const BasicBlock *BB) { printBasicBlock(BB); }
788 inline void write(const Instruction *I) { printInstruction(*I); }
789 inline void write(const Type *Ty) { printType(Ty); }
791 void writeOperand(const Value *Op, bool PrintType);
792 void writeParamOperand(const Value *Operand, ParameterAttributes Attrs);
794 const Module* getModule() { return TheModule; }
797 void printModule(const Module *M);
798 void printTypeSymbolTable(const TypeSymbolTable &ST);
799 void printGlobal(const GlobalVariable *GV);
800 void printAlias(const GlobalAlias *GV);
801 void printFunction(const Function *F);
802 void printArgument(const Argument *FA, ParameterAttributes Attrs);
803 void printBasicBlock(const BasicBlock *BB);
804 void printInstruction(const Instruction &I);
806 // printType - Go to extreme measures to attempt to print out a short,
807 // symbolic version of a type name.
809 std::ostream &printType(const Type *Ty) {
810 return printTypeInt(Out, Ty, TypeNames);
813 // printTypeAtLeastOneLevel - Print out one level of the possibly complex type
814 // without considering any symbolic types that we may have equal to it.
816 std::ostream &printTypeAtLeastOneLevel(const Type *Ty);
818 // printInfoComment - Print a little comment after the instruction indicating
819 // which slot it occupies.
820 void printInfoComment(const Value &V);
822 } // end of llvm namespace
824 /// printTypeAtLeastOneLevel - Print out one level of the possibly complex type
825 /// without considering any symbolic types that we may have equal to it.
827 std::ostream &AssemblyWriter::printTypeAtLeastOneLevel(const Type *Ty) {
828 if (const IntegerType *ITy = dyn_cast<IntegerType>(Ty))
829 Out << "i" << utostr(ITy->getBitWidth());
830 else if (const FunctionType *FTy = dyn_cast<FunctionType>(Ty)) {
831 printType(FTy->getReturnType());
833 for (FunctionType::param_iterator I = FTy->param_begin(),
834 E = FTy->param_end(); I != E; ++I) {
835 if (I != FTy->param_begin())
839 if (FTy->isVarArg()) {
840 if (FTy->getNumParams()) Out << ", ";
844 } else if (const StructType *STy = dyn_cast<StructType>(Ty)) {
848 for (StructType::element_iterator I = STy->element_begin(),
849 E = STy->element_end(); I != E; ++I) {
850 if (I != STy->element_begin())
857 } else if (const PointerType *PTy = dyn_cast<PointerType>(Ty)) {
858 printType(PTy->getElementType());
859 if (unsigned AddressSpace = PTy->getAddressSpace())
860 Out << " addrspace(" << AddressSpace << ")";
862 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
863 Out << '[' << ATy->getNumElements() << " x ";
864 printType(ATy->getElementType()) << ']';
865 } else if (const VectorType *PTy = dyn_cast<VectorType>(Ty)) {
866 Out << '<' << PTy->getNumElements() << " x ";
867 printType(PTy->getElementType()) << '>';
869 else if (isa<OpaqueType>(Ty)) {
872 if (!Ty->isPrimitiveType())
873 Out << "<unknown derived type>";
880 void AssemblyWriter::writeOperand(const Value *Operand, bool PrintType) {
882 Out << "<null operand!>";
884 if (PrintType) { Out << ' '; printType(Operand->getType()); }
885 WriteAsOperandInternal(Out, Operand, TypeNames, &Machine);
889 void AssemblyWriter::writeParamOperand(const Value *Operand,
890 ParameterAttributes Attrs) {
892 Out << "<null operand!>";
896 printType(Operand->getType());
897 // Print parameter attributes list
898 if (Attrs != ParamAttr::None)
899 Out << ' ' << ParamAttr::getAsString(Attrs);
901 WriteAsOperandInternal(Out, Operand, TypeNames, &Machine);
905 void AssemblyWriter::printModule(const Module *M) {
906 if (!M->getModuleIdentifier().empty() &&
907 // Don't print the ID if it will start a new line (which would
908 // require a comment char before it).
909 M->getModuleIdentifier().find('\n') == std::string::npos)
910 Out << "; ModuleID = '" << M->getModuleIdentifier() << "'\n";
912 if (!M->getDataLayout().empty())
913 Out << "target datalayout = \"" << M->getDataLayout() << "\"\n";
914 if (!M->getTargetTriple().empty())
915 Out << "target triple = \"" << M->getTargetTriple() << "\"\n";
917 if (!M->getModuleInlineAsm().empty()) {
918 // Split the string into lines, to make it easier to read the .ll file.
919 std::string Asm = M->getModuleInlineAsm();
921 size_t NewLine = Asm.find_first_of('\n', CurPos);
922 while (NewLine != std::string::npos) {
923 // We found a newline, print the portion of the asm string from the
924 // last newline up to this newline.
925 Out << "module asm \"";
926 PrintEscapedString(std::string(Asm.begin()+CurPos, Asm.begin()+NewLine),
930 NewLine = Asm.find_first_of('\n', CurPos);
932 Out << "module asm \"";
933 PrintEscapedString(std::string(Asm.begin()+CurPos, Asm.end()), Out);
937 // Loop over the dependent libraries and emit them.
938 Module::lib_iterator LI = M->lib_begin();
939 Module::lib_iterator LE = M->lib_end();
941 Out << "deplibs = [ ";
943 Out << '"' << *LI << '"';
951 // Loop over the symbol table, emitting all named constants.
952 printTypeSymbolTable(M->getTypeSymbolTable());
954 for (Module::const_global_iterator I = M->global_begin(), E = M->global_end();
958 // Output all aliases.
959 if (!M->alias_empty()) Out << "\n";
960 for (Module::const_alias_iterator I = M->alias_begin(), E = M->alias_end();
964 // Output all of the functions.
965 for (Module::const_iterator I = M->begin(), E = M->end(); I != E; ++I)
969 void AssemblyWriter::printGlobal(const GlobalVariable *GV) {
971 PrintLLVMName(Out, GV);
975 if (!GV->hasInitializer()) {
976 switch (GV->getLinkage()) {
977 case GlobalValue::DLLImportLinkage: Out << "dllimport "; break;
978 case GlobalValue::ExternalWeakLinkage: Out << "extern_weak "; break;
979 default: Out << "external "; break;
982 switch (GV->getLinkage()) {
983 case GlobalValue::InternalLinkage: Out << "internal "; break;
984 case GlobalValue::CommonLinkage: Out << "common "; break;
985 case GlobalValue::LinkOnceLinkage: Out << "linkonce "; break;
986 case GlobalValue::WeakLinkage: Out << "weak "; break;
987 case GlobalValue::AppendingLinkage: Out << "appending "; break;
988 case GlobalValue::DLLImportLinkage: Out << "dllimport "; break;
989 case GlobalValue::DLLExportLinkage: Out << "dllexport "; break;
990 case GlobalValue::ExternalWeakLinkage: Out << "extern_weak "; break;
991 case GlobalValue::ExternalLinkage: break;
992 case GlobalValue::GhostLinkage:
993 cerr << "GhostLinkage not allowed in AsmWriter!\n";
996 switch (GV->getVisibility()) {
997 default: assert(0 && "Invalid visibility style!");
998 case GlobalValue::DefaultVisibility: break;
999 case GlobalValue::HiddenVisibility: Out << "hidden "; break;
1000 case GlobalValue::ProtectedVisibility: Out << "protected "; break;
1004 if (GV->isThreadLocal()) Out << "thread_local ";
1005 Out << (GV->isConstant() ? "constant " : "global ");
1006 printType(GV->getType()->getElementType());
1008 if (GV->hasInitializer())
1009 writeOperand(GV->getInitializer(), false);
1011 if (unsigned AddressSpace = GV->getType()->getAddressSpace())
1012 Out << " addrspace(" << AddressSpace << ") ";
1014 if (GV->hasSection())
1015 Out << ", section \"" << GV->getSection() << '"';
1016 if (GV->getAlignment())
1017 Out << ", align " << GV->getAlignment();
1019 printInfoComment(*GV);
1023 void AssemblyWriter::printAlias(const GlobalAlias *GA) {
1024 // Don't crash when dumping partially built GA
1026 Out << "<<nameless>> = ";
1028 PrintLLVMName(Out, GA);
1031 switch (GA->getVisibility()) {
1032 default: assert(0 && "Invalid visibility style!");
1033 case GlobalValue::DefaultVisibility: break;
1034 case GlobalValue::HiddenVisibility: Out << "hidden "; break;
1035 case GlobalValue::ProtectedVisibility: Out << "protected "; break;
1040 switch (GA->getLinkage()) {
1041 case GlobalValue::WeakLinkage: Out << "weak "; break;
1042 case GlobalValue::InternalLinkage: Out << "internal "; break;
1043 case GlobalValue::ExternalLinkage: break;
1045 assert(0 && "Invalid alias linkage");
1048 const Constant *Aliasee = GA->getAliasee();
1050 if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(Aliasee)) {
1051 printType(GV->getType());
1053 PrintLLVMName(Out, GV);
1054 } else if (const Function *F = dyn_cast<Function>(Aliasee)) {
1055 printType(F->getFunctionType());
1059 PrintLLVMName(Out, F);
1062 } else if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(Aliasee)) {
1063 printType(GA->getType());
1065 PrintLLVMName(Out, GA);
1067 const ConstantExpr *CE = 0;
1068 if ((CE = dyn_cast<ConstantExpr>(Aliasee)) &&
1069 (CE->getOpcode() == Instruction::BitCast)) {
1070 writeOperand(CE, false);
1072 assert(0 && "Unsupported aliasee");
1075 printInfoComment(*GA);
1079 void AssemblyWriter::printTypeSymbolTable(const TypeSymbolTable &ST) {
1081 for (TypeSymbolTable::const_iterator TI = ST.begin(), TE = ST.end();
1083 Out << "\t" << getLLVMName(TI->first) << " = type ";
1085 // Make sure we print out at least one level of the type structure, so
1086 // that we do not get %FILE = type %FILE
1088 printTypeAtLeastOneLevel(TI->second) << "\n";
1092 /// printFunction - Print all aspects of a function.
1094 void AssemblyWriter::printFunction(const Function *F) {
1095 // Print out the return type and name...
1098 if (AnnotationWriter) AnnotationWriter->emitFunctionAnnot(F, Out);
1100 if (F->isDeclaration())
1105 switch (F->getLinkage()) {
1106 case GlobalValue::InternalLinkage: Out << "internal "; break;
1107 case GlobalValue::LinkOnceLinkage: Out << "linkonce "; break;
1108 case GlobalValue::WeakLinkage: Out << "weak "; break;
1109 case GlobalValue::CommonLinkage: Out << "common "; break;
1110 case GlobalValue::AppendingLinkage: Out << "appending "; break;
1111 case GlobalValue::DLLImportLinkage: Out << "dllimport "; break;
1112 case GlobalValue::DLLExportLinkage: Out << "dllexport "; break;
1113 case GlobalValue::ExternalWeakLinkage: Out << "extern_weak "; break;
1114 case GlobalValue::ExternalLinkage: break;
1115 case GlobalValue::GhostLinkage:
1116 cerr << "GhostLinkage not allowed in AsmWriter!\n";
1119 switch (F->getVisibility()) {
1120 default: assert(0 && "Invalid visibility style!");
1121 case GlobalValue::DefaultVisibility: break;
1122 case GlobalValue::HiddenVisibility: Out << "hidden "; break;
1123 case GlobalValue::ProtectedVisibility: Out << "protected "; break;
1126 // Print the calling convention.
1127 switch (F->getCallingConv()) {
1128 case CallingConv::C: break; // default
1129 case CallingConv::Fast: Out << "fastcc "; break;
1130 case CallingConv::Cold: Out << "coldcc "; break;
1131 case CallingConv::X86_StdCall: Out << "x86_stdcallcc "; break;
1132 case CallingConv::X86_FastCall: Out << "x86_fastcallcc "; break;
1133 case CallingConv::X86_SSECall: Out << "x86_ssecallcc "; break;
1134 default: Out << "cc" << F->getCallingConv() << " "; break;
1137 const FunctionType *FT = F->getFunctionType();
1138 const PAListPtr &Attrs = F->getParamAttrs();
1139 printType(F->getReturnType()) << ' ';
1141 PrintLLVMName(Out, F);
1145 Machine.incorporateFunction(F);
1147 // Loop over the arguments, printing them...
1150 if (!F->isDeclaration()) {
1151 // If this isn't a declaration, print the argument names as well.
1152 for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
1154 // Insert commas as we go... the first arg doesn't get a comma
1155 if (I != F->arg_begin()) Out << ", ";
1156 printArgument(I, Attrs.getParamAttrs(Idx));
1160 // Otherwise, print the types from the function type.
1161 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
1162 // Insert commas as we go... the first arg doesn't get a comma
1166 printType(FT->getParamType(i));
1168 ParameterAttributes ArgAttrs = Attrs.getParamAttrs(i+1);
1169 if (ArgAttrs != ParamAttr::None)
1170 Out << ' ' << ParamAttr::getAsString(ArgAttrs);
1174 // Finish printing arguments...
1175 if (FT->isVarArg()) {
1176 if (FT->getNumParams()) Out << ", ";
1177 Out << "..."; // Output varargs portion of signature!
1180 ParameterAttributes RetAttrs = Attrs.getParamAttrs(0);
1181 if (RetAttrs != ParamAttr::None)
1182 Out << ' ' << ParamAttr::getAsString(Attrs.getParamAttrs(0));
1183 if (F->hasSection())
1184 Out << " section \"" << F->getSection() << '"';
1185 if (F->getAlignment())
1186 Out << " align " << F->getAlignment();
1188 Out << " gc \"" << F->getGC() << '"';
1190 if (F->isDeclaration()) {
1195 // Output all of its basic blocks... for the function
1196 for (Function::const_iterator I = F->begin(), E = F->end(); I != E; ++I)
1202 Machine.purgeFunction();
1205 /// printArgument - This member is called for every argument that is passed into
1206 /// the function. Simply print it out
1208 void AssemblyWriter::printArgument(const Argument *Arg,
1209 ParameterAttributes Attrs) {
1211 printType(Arg->getType());
1213 // Output parameter attributes list
1214 if (Attrs != ParamAttr::None)
1215 Out << ' ' << ParamAttr::getAsString(Attrs);
1217 // Output name, if available...
1218 if (Arg->hasName()) {
1220 PrintLLVMName(Out, Arg);
1224 /// printBasicBlock - This member is called for each basic block in a method.
1226 void AssemblyWriter::printBasicBlock(const BasicBlock *BB) {
1227 if (BB->hasName()) { // Print out the label if it exists...
1229 PrintLLVMName(Out, BB->getValueName(), LabelPrefix);
1231 } else if (!BB->use_empty()) { // Don't print block # of no uses...
1232 Out << "\n; <label>:";
1233 int Slot = Machine.getLocalSlot(BB);
1240 if (BB->getParent() == 0)
1241 Out << "\t\t; Error: Block without parent!";
1242 else if (BB != &BB->getParent()->getEntryBlock()) { // Not the entry block?
1243 // Output predecessors for the block...
1245 pred_const_iterator PI = pred_begin(BB), PE = pred_end(BB);
1248 Out << " No predecessors!";
1251 writeOperand(*PI, false);
1252 for (++PI; PI != PE; ++PI) {
1254 writeOperand(*PI, false);
1261 if (AnnotationWriter) AnnotationWriter->emitBasicBlockStartAnnot(BB, Out);
1263 // Output all of the instructions in the basic block...
1264 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I != E; ++I)
1265 printInstruction(*I);
1267 if (AnnotationWriter) AnnotationWriter->emitBasicBlockEndAnnot(BB, Out);
1271 /// printInfoComment - Print a little comment after the instruction indicating
1272 /// which slot it occupies.
1274 void AssemblyWriter::printInfoComment(const Value &V) {
1275 if (V.getType() != Type::VoidTy) {
1277 printType(V.getType()) << '>';
1281 if (const GlobalValue *GV = dyn_cast<GlobalValue>(&V))
1282 SlotNum = Machine.getGlobalSlot(GV);
1284 SlotNum = Machine.getLocalSlot(&V);
1288 Out << ':' << SlotNum; // Print out the def slot taken.
1290 Out << " [#uses=" << V.getNumUses() << ']'; // Output # uses
1294 // This member is called for each Instruction in a function..
1295 void AssemblyWriter::printInstruction(const Instruction &I) {
1296 if (AnnotationWriter) AnnotationWriter->emitInstructionAnnot(&I, Out);
1300 // Print out name if it exists...
1302 PrintLLVMName(Out, &I);
1306 // If this is a volatile load or store, print out the volatile marker.
1307 if ((isa<LoadInst>(I) && cast<LoadInst>(I).isVolatile()) ||
1308 (isa<StoreInst>(I) && cast<StoreInst>(I).isVolatile())) {
1310 } else if (isa<CallInst>(I) && cast<CallInst>(I).isTailCall()) {
1311 // If this is a call, check if it's a tail call.
1315 // Print out the opcode...
1316 Out << I.getOpcodeName();
1318 // Print out the compare instruction predicates
1319 if (const CmpInst *CI = dyn_cast<CmpInst>(&I))
1320 Out << " " << getPredicateText(CI->getPredicate());
1322 // Print out the type of the operands...
1323 const Value *Operand = I.getNumOperands() ? I.getOperand(0) : 0;
1325 // Special case conditional branches to swizzle the condition out to the front
1326 if (isa<BranchInst>(I) && I.getNumOperands() > 1) {
1327 writeOperand(I.getOperand(2), true);
1329 writeOperand(Operand, true);
1331 writeOperand(I.getOperand(1), true);
1333 } else if (isa<SwitchInst>(I)) {
1334 // Special case switch statement to get formatting nice and correct...
1335 writeOperand(Operand , true); Out << ',';
1336 writeOperand(I.getOperand(1), true); Out << " [";
1338 for (unsigned op = 2, Eop = I.getNumOperands(); op < Eop; op += 2) {
1340 writeOperand(I.getOperand(op ), true); Out << ',';
1341 writeOperand(I.getOperand(op+1), true);
1344 } else if (isa<PHINode>(I)) {
1346 printType(I.getType());
1349 for (unsigned op = 0, Eop = I.getNumOperands(); op < Eop; op += 2) {
1350 if (op) Out << ", ";
1352 writeOperand(I.getOperand(op ), false); Out << ',';
1353 writeOperand(I.getOperand(op+1), false); Out << " ]";
1355 } else if (const ExtractValueInst *EVI = dyn_cast<ExtractValueInst>(&I)) {
1356 writeOperand(I.getOperand(0), true);
1357 for (const unsigned *i = EVI->idx_begin(), *e = EVI->idx_end(); i != e; ++i)
1359 } else if (const InsertValueInst *IVI = dyn_cast<InsertValueInst>(&I)) {
1360 writeOperand(I.getOperand(0), true); Out << ',';
1361 writeOperand(I.getOperand(1), true);
1362 for (const unsigned *i = IVI->idx_begin(), *e = IVI->idx_end(); i != e; ++i)
1364 } else if (isa<ReturnInst>(I) && !Operand) {
1366 } else if (const CallInst *CI = dyn_cast<CallInst>(&I)) {
1367 // Print the calling convention being used.
1368 switch (CI->getCallingConv()) {
1369 case CallingConv::C: break; // default
1370 case CallingConv::Fast: Out << " fastcc"; break;
1371 case CallingConv::Cold: Out << " coldcc"; break;
1372 case CallingConv::X86_StdCall: Out << " x86_stdcallcc"; break;
1373 case CallingConv::X86_FastCall: Out << " x86_fastcallcc"; break;
1374 case CallingConv::X86_SSECall: Out << " x86_ssecallcc"; break;
1375 default: Out << " cc" << CI->getCallingConv(); break;
1378 const PointerType *PTy = cast<PointerType>(Operand->getType());
1379 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
1380 const Type *RetTy = FTy->getReturnType();
1381 const PAListPtr &PAL = CI->getParamAttrs();
1383 // If possible, print out the short form of the call instruction. We can
1384 // only do this if the first argument is a pointer to a nonvararg function,
1385 // and if the return type is not a pointer to a function.
1387 if (!FTy->isVarArg() &&
1388 (!isa<PointerType>(RetTy) ||
1389 !isa<FunctionType>(cast<PointerType>(RetTy)->getElementType()))) {
1390 Out << ' '; printType(RetTy);
1391 writeOperand(Operand, false);
1393 writeOperand(Operand, true);
1396 for (unsigned op = 1, Eop = I.getNumOperands(); op < Eop; ++op) {
1399 writeParamOperand(I.getOperand(op), PAL.getParamAttrs(op));
1402 if (PAL.getParamAttrs(0) != ParamAttr::None)
1403 Out << ' ' << ParamAttr::getAsString(PAL.getParamAttrs(0));
1404 } else if (const InvokeInst *II = dyn_cast<InvokeInst>(&I)) {
1405 const PointerType *PTy = cast<PointerType>(Operand->getType());
1406 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
1407 const Type *RetTy = FTy->getReturnType();
1408 const PAListPtr &PAL = II->getParamAttrs();
1410 // Print the calling convention being used.
1411 switch (II->getCallingConv()) {
1412 case CallingConv::C: break; // default
1413 case CallingConv::Fast: Out << " fastcc"; break;
1414 case CallingConv::Cold: Out << " coldcc"; break;
1415 case CallingConv::X86_StdCall: Out << "x86_stdcallcc "; break;
1416 case CallingConv::X86_FastCall: Out << "x86_fastcallcc "; break;
1417 case CallingConv::X86_SSECall: Out << "x86_ssecallcc "; break;
1418 default: Out << " cc" << II->getCallingConv(); break;
1421 // If possible, print out the short form of the invoke instruction. We can
1422 // only do this if the first argument is a pointer to a nonvararg function,
1423 // and if the return type is not a pointer to a function.
1425 if (!FTy->isVarArg() &&
1426 (!isa<PointerType>(RetTy) ||
1427 !isa<FunctionType>(cast<PointerType>(RetTy)->getElementType()))) {
1428 Out << ' '; printType(RetTy);
1429 writeOperand(Operand, false);
1431 writeOperand(Operand, true);
1435 for (unsigned op = 3, Eop = I.getNumOperands(); op < Eop; ++op) {
1438 writeParamOperand(I.getOperand(op), PAL.getParamAttrs(op-2));
1442 if (PAL.getParamAttrs(0) != ParamAttr::None)
1443 Out << ' ' << ParamAttr::getAsString(PAL.getParamAttrs(0));
1444 Out << "\n\t\t\tto";
1445 writeOperand(II->getNormalDest(), true);
1447 writeOperand(II->getUnwindDest(), true);
1449 } else if (const AllocationInst *AI = dyn_cast<AllocationInst>(&I)) {
1451 printType(AI->getType()->getElementType());
1452 if (AI->isArrayAllocation()) {
1454 writeOperand(AI->getArraySize(), true);
1456 if (AI->getAlignment()) {
1457 Out << ", align " << AI->getAlignment();
1459 } else if (isa<CastInst>(I)) {
1460 if (Operand) writeOperand(Operand, true); // Work with broken code
1462 printType(I.getType());
1463 } else if (isa<VAArgInst>(I)) {
1464 if (Operand) writeOperand(Operand, true); // Work with broken code
1466 printType(I.getType());
1467 } else if (Operand) { // Print the normal way...
1469 // PrintAllTypes - Instructions who have operands of all the same type
1470 // omit the type from all but the first operand. If the instruction has
1471 // different type operands (for example br), then they are all printed.
1472 bool PrintAllTypes = false;
1473 const Type *TheType = Operand->getType();
1475 // Select, Store and ShuffleVector always print all types.
1476 if (isa<SelectInst>(I) || isa<StoreInst>(I) || isa<ShuffleVectorInst>(I)
1477 || isa<ReturnInst>(I)) {
1478 PrintAllTypes = true;
1480 for (unsigned i = 1, E = I.getNumOperands(); i != E; ++i) {
1481 Operand = I.getOperand(i);
1482 if (Operand->getType() != TheType) {
1483 PrintAllTypes = true; // We have differing types! Print them all!
1489 if (!PrintAllTypes) {
1494 for (unsigned i = 0, E = I.getNumOperands(); i != E; ++i) {
1496 writeOperand(I.getOperand(i), PrintAllTypes);
1500 // Print post operand alignment for load/store
1501 if (isa<LoadInst>(I) && cast<LoadInst>(I).getAlignment()) {
1502 Out << ", align " << cast<LoadInst>(I).getAlignment();
1503 } else if (isa<StoreInst>(I) && cast<StoreInst>(I).getAlignment()) {
1504 Out << ", align " << cast<StoreInst>(I).getAlignment();
1507 printInfoComment(I);
1512 //===----------------------------------------------------------------------===//
1513 // External Interface declarations
1514 //===----------------------------------------------------------------------===//
1516 void Module::print(std::ostream &o, AssemblyAnnotationWriter *AAW) const {
1517 SlotTracker SlotTable(this);
1518 AssemblyWriter W(o, SlotTable, this, AAW);
1522 void GlobalVariable::print(std::ostream &o) const {
1523 SlotTracker SlotTable(getParent());
1524 AssemblyWriter W(o, SlotTable, getParent(), 0);
1528 void GlobalAlias::print(std::ostream &o) const {
1529 SlotTracker SlotTable(getParent());
1530 AssemblyWriter W(o, SlotTable, getParent(), 0);
1534 void Function::print(std::ostream &o, AssemblyAnnotationWriter *AAW) const {
1535 SlotTracker SlotTable(getParent());
1536 AssemblyWriter W(o, SlotTable, getParent(), AAW);
1541 void InlineAsm::print(std::ostream &o, AssemblyAnnotationWriter *AAW) const {
1542 WriteAsOperand(o, this, true, 0);
1545 void BasicBlock::print(std::ostream &o, AssemblyAnnotationWriter *AAW) const {
1546 SlotTracker SlotTable(getParent());
1547 AssemblyWriter W(o, SlotTable,
1548 getParent() ? getParent()->getParent() : 0, AAW);
1552 void Instruction::print(std::ostream &o, AssemblyAnnotationWriter *AAW) const {
1553 const Function *F = getParent() ? getParent()->getParent() : 0;
1554 SlotTracker SlotTable(F);
1555 AssemblyWriter W(o, SlotTable, F ? F->getParent() : 0, AAW);
1560 void Constant::print(std::ostream &o) const {
1561 if (this == 0) { o << "<null> constant value\n"; return; }
1563 o << ' ' << getType()->getDescription() << ' ';
1565 std::map<const Type *, std::string> TypeTable;
1566 WriteConstantInt(o, this, TypeTable, 0);
1569 void Type::print(std::ostream &o) const {
1573 o << getDescription();
1576 void Argument::print(std::ostream &o) const {
1577 WriteAsOperand(o, this, true, getParent() ? getParent()->getParent() : 0);
1580 // Value::dump - allow easy printing of Values from the debugger.
1581 // Located here because so much of the needed functionality is here.
1582 void Value::dump() const { print(*cerr.stream()); cerr << '\n'; }
1584 // Type::dump - allow easy printing of Values from the debugger.
1585 // Located here because so much of the needed functionality is here.
1586 void Type::dump() const { print(*cerr.stream()); cerr << '\n'; }
1588 //===----------------------------------------------------------------------===//
1589 // SlotTracker Implementation
1590 //===----------------------------------------------------------------------===//
1593 #define SC_DEBUG(X) cerr << X
1598 // Module level constructor. Causes the contents of the Module (sans functions)
1599 // to be added to the slot table.
1600 SlotTracker::SlotTracker(const Module *M)
1601 : TheModule(M) ///< Saved for lazy initialization.
1603 , FunctionProcessed(false)
1604 , mNext(0), fNext(0)
1608 // Function level constructor. Causes the contents of the Module and the one
1609 // function provided to be added to the slot table.
1610 SlotTracker::SlotTracker(const Function *F)
1611 : TheModule(F ? F->getParent() : 0) ///< Saved for lazy initialization
1612 , TheFunction(F) ///< Saved for lazy initialization
1613 , FunctionProcessed(false)
1614 , mNext(0), fNext(0)
1618 inline void SlotTracker::initialize() {
1621 TheModule = 0; ///< Prevent re-processing next time we're called.
1623 if (TheFunction && !FunctionProcessed)
1627 // Iterate through all the global variables, functions, and global
1628 // variable initializers and create slots for them.
1629 void SlotTracker::processModule() {
1630 SC_DEBUG("begin processModule!\n");
1632 // Add all of the unnamed global variables to the value table.
1633 for (Module::const_global_iterator I = TheModule->global_begin(),
1634 E = TheModule->global_end(); I != E; ++I)
1636 CreateModuleSlot(I);
1638 // Add all the unnamed functions to the table.
1639 for (Module::const_iterator I = TheModule->begin(), E = TheModule->end();
1642 CreateModuleSlot(I);
1644 SC_DEBUG("end processModule!\n");
1648 // Process the arguments, basic blocks, and instructions of a function.
1649 void SlotTracker::processFunction() {
1650 SC_DEBUG("begin processFunction!\n");
1653 // Add all the function arguments with no names.
1654 for(Function::const_arg_iterator AI = TheFunction->arg_begin(),
1655 AE = TheFunction->arg_end(); AI != AE; ++AI)
1657 CreateFunctionSlot(AI);
1659 SC_DEBUG("Inserting Instructions:\n");
1661 // Add all of the basic blocks and instructions with no names.
1662 for (Function::const_iterator BB = TheFunction->begin(),
1663 E = TheFunction->end(); BB != E; ++BB) {
1665 CreateFunctionSlot(BB);
1666 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I != E; ++I)
1667 if (I->getType() != Type::VoidTy && !I->hasName())
1668 CreateFunctionSlot(I);
1671 FunctionProcessed = true;
1673 SC_DEBUG("end processFunction!\n");
1676 /// Clean up after incorporating a function. This is the only way to get out of
1677 /// the function incorporation state that affects get*Slot/Create*Slot. Function
1678 /// incorporation state is indicated by TheFunction != 0.
1679 void SlotTracker::purgeFunction() {
1680 SC_DEBUG("begin purgeFunction!\n");
1681 fMap.clear(); // Simply discard the function level map
1683 FunctionProcessed = false;
1684 SC_DEBUG("end purgeFunction!\n");
1687 /// getGlobalSlot - Get the slot number of a global value.
1688 int SlotTracker::getGlobalSlot(const GlobalValue *V) {
1689 // Check for uninitialized state and do lazy initialization.
1692 // Find the type plane in the module map
1693 ValueMap::iterator MI = mMap.find(V);
1694 return MI == mMap.end() ? -1 : MI->second;
1698 /// getLocalSlot - Get the slot number for a value that is local to a function.
1699 int SlotTracker::getLocalSlot(const Value *V) {
1700 assert(!isa<Constant>(V) && "Can't get a constant or global slot with this!");
1702 // Check for uninitialized state and do lazy initialization.
1705 ValueMap::iterator FI = fMap.find(V);
1706 return FI == fMap.end() ? -1 : FI->second;
1710 /// CreateModuleSlot - Insert the specified GlobalValue* into the slot table.
1711 void SlotTracker::CreateModuleSlot(const GlobalValue *V) {
1712 assert(V && "Can't insert a null Value into SlotTracker!");
1713 assert(V->getType() != Type::VoidTy && "Doesn't need a slot!");
1714 assert(!V->hasName() && "Doesn't need a slot!");
1716 unsigned DestSlot = mNext++;
1719 SC_DEBUG(" Inserting value [" << V->getType() << "] = " << V << " slot=" <<
1721 // G = Global, F = Function, A = Alias, o = other
1722 SC_DEBUG((isa<GlobalVariable>(V) ? 'G' :
1723 (isa<Function>(V) ? 'F' :
1724 (isa<GlobalAlias>(V) ? 'A' : 'o'))) << "]\n");
1728 /// CreateSlot - Create a new slot for the specified value if it has no name.
1729 void SlotTracker::CreateFunctionSlot(const Value *V) {
1730 assert(V->getType() != Type::VoidTy && !V->hasName() &&
1731 "Doesn't need a slot!");
1733 unsigned DestSlot = fNext++;
1736 // G = Global, F = Function, o = other
1737 SC_DEBUG(" Inserting value [" << V->getType() << "] = " << V << " slot=" <<
1738 DestSlot << " [o]\n");