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/raw_ostream.h"
39 // Make virtual table appear in this compilation unit.
40 AssemblyAnnotationWriter::~AssemblyAnnotationWriter() {}
42 //===----------------------------------------------------------------------===//
44 //===----------------------------------------------------------------------===//
46 static const Module *getModuleFromVal(const Value *V) {
47 if (const Argument *MA = dyn_cast<Argument>(V))
48 return MA->getParent() ? MA->getParent()->getParent() : 0;
50 if (const BasicBlock *BB = dyn_cast<BasicBlock>(V))
51 return BB->getParent() ? BB->getParent()->getParent() : 0;
53 if (const Instruction *I = dyn_cast<Instruction>(V)) {
54 const Function *M = I->getParent() ? I->getParent()->getParent() : 0;
55 return M ? M->getParent() : 0;
58 if (const GlobalValue *GV = dyn_cast<GlobalValue>(V))
59 return GV->getParent();
63 // PrintEscapedString - Print each character of the specified string, escaping
64 // it if it is not printable or if it is an escape char.
65 static void PrintEscapedString(const char *Str, unsigned Length,
67 for (unsigned i = 0; i != Length; ++i) {
68 unsigned char C = Str[i];
69 if (isprint(C) && C != '\\' && C != '"' && isprint(C))
72 Out << '\\' << hexdigit(C >> 4) << hexdigit(C & 0x0F);
76 // PrintEscapedString - Print each character of the specified string, escaping
77 // it if it is not printable or if it is an escape char.
78 static void PrintEscapedString(const std::string &Str, raw_ostream &Out) {
79 PrintEscapedString(Str.c_str(), Str.size(), Out);
89 /// PrintLLVMName - Turn the specified name into an 'LLVM name', which is either
90 /// prefixed with % (if the string only contains simple characters) or is
91 /// surrounded with ""'s (if it has special chars in it). Print it out.
92 static void PrintLLVMName(raw_ostream &OS, const char *NameStr,
93 unsigned NameLen, PrefixType Prefix) {
94 assert(NameStr && "Cannot get empty name!");
96 default: assert(0 && "Bad prefix!");
98 case GlobalPrefix: OS << '@'; break;
99 case LabelPrefix: break;
100 case LocalPrefix: OS << '%'; break;
103 // Scan the name to see if it needs quotes first.
104 bool NeedsQuotes = isdigit(NameStr[0]);
106 for (unsigned i = 0; i != NameLen; ++i) {
108 if (!isalnum(C) && C != '-' && C != '.' && C != '_') {
115 // If we didn't need any quotes, just write out the name in one blast.
117 OS.write(NameStr, NameLen);
121 // Okay, we need quotes. Output the quotes and escape any scary characters as
124 PrintEscapedString(NameStr, NameLen, OS);
128 /// PrintLLVMName - Turn the specified name into an 'LLVM name', which is either
129 /// prefixed with % (if the string only contains simple characters) or is
130 /// surrounded with ""'s (if it has special chars in it). Print it out.
131 static void PrintLLVMName(raw_ostream &OS, const Value *V) {
132 PrintLLVMName(OS, V->getNameStart(), V->getNameLen(),
133 isa<GlobalValue>(V) ? GlobalPrefix : LocalPrefix);
136 //===----------------------------------------------------------------------===//
137 // TypePrinting Class: Type printing machinery
138 //===----------------------------------------------------------------------===//
141 /// TypePrinting - Type printing machinery.
143 std::map<const Type *, std::string> TypeNames;
146 TypePrinting(const Module *M, raw_ostream &os);
148 void print(const Type *Ty);
149 void printAtLeastOneLevel(const Type *Ty);
152 void CalcTypeName(const Type *Ty, SmallVectorImpl<const Type *> &TypeStack,
153 raw_ostream &Result);
155 } // end anonymous namespace.
157 TypePrinting::TypePrinting(const Module *M, raw_ostream &os) : OS(os) {
160 // If the module has a symbol table, take all global types and stuff their
161 // names into the TypeNames map.
162 const TypeSymbolTable &ST = M->getTypeSymbolTable();
163 for (TypeSymbolTable::const_iterator TI = ST.begin(), E = ST.end();
165 const Type *Ty = cast<Type>(TI->second);
167 // As a heuristic, don't insert pointer to primitive types, because
168 // they are used too often to have a single useful name.
169 if (const PointerType *PTy = dyn_cast<PointerType>(Ty)) {
170 const Type *PETy = PTy->getElementType();
171 if ((PETy->isPrimitiveType() || PETy->isInteger()) &&
172 !isa<OpaqueType>(PETy))
176 // Get the name as a string and insert it into TypeNames.
178 raw_string_ostream NameOS(NameStr);
179 PrintLLVMName(NameOS, TI->first.c_str(), TI->first.length(), LocalPrefix);
180 TypeNames.insert(std::make_pair(Ty, NameOS.str()));
184 /// CalcTypeName - Write the specified type to the specified raw_ostream, making
185 /// use of type names or up references to shorten the type name where possible.
186 void TypePrinting::CalcTypeName(const Type *Ty,
187 SmallVectorImpl<const Type *> &TypeStack,
188 raw_ostream &Result) {
189 if (Ty->isInteger() || (Ty->isPrimitiveType() && !isa<OpaqueType>(Ty))) {
190 Result << Ty->getDescription(); // Base case
194 // Check to see if the type is named.
195 std::map<const Type *, std::string>::iterator I = TypeNames.find(Ty);
196 if (I != TypeNames.end() &&
197 // If the name wasn't temporarily removed use it.
198 !I->second.empty()) {
203 // Check to see if the Type is already on the stack...
204 unsigned Slot = 0, CurSize = TypeStack.size();
205 while (Slot < CurSize && TypeStack[Slot] != Ty) ++Slot; // Scan for type
207 // This is another base case for the recursion. In this case, we know
208 // that we have looped back to a type that we have previously visited.
209 // Generate the appropriate upreference to handle this.
210 if (Slot < CurSize) {
211 Result << '\\' << unsigned(CurSize-Slot); // Here's the upreference
215 TypeStack.push_back(Ty); // Recursive case: Add us to the stack..
217 switch (Ty->getTypeID()) {
218 case Type::FunctionTyID: {
219 const FunctionType *FTy = cast<FunctionType>(Ty);
220 CalcTypeName(FTy->getReturnType(), TypeStack, Result);
222 for (FunctionType::param_iterator I = FTy->param_begin(),
223 E = FTy->param_end(); I != E; ++I) {
224 if (I != FTy->param_begin())
226 CalcTypeName(*I, TypeStack, Result);
228 if (FTy->isVarArg()) {
229 if (FTy->getNumParams()) Result << ", ";
235 case Type::StructTyID: {
236 const StructType *STy = cast<StructType>(Ty);
240 for (StructType::element_iterator I = STy->element_begin(),
241 E = STy->element_end(); I != E; ++I) {
242 CalcTypeName(*I, TypeStack, Result);
243 if (next(I) != STy->element_end())
252 case Type::PointerTyID: {
253 const PointerType *PTy = cast<PointerType>(Ty);
254 CalcTypeName(PTy->getElementType(), TypeStack, Result);
255 if (unsigned AddressSpace = PTy->getAddressSpace())
256 Result << " addrspace(" << AddressSpace << ')';
260 case Type::ArrayTyID: {
261 const ArrayType *ATy = cast<ArrayType>(Ty);
262 Result << '[' << ATy->getNumElements() << " x ";
263 CalcTypeName(ATy->getElementType(), TypeStack, Result);
267 case Type::VectorTyID: {
268 const VectorType *PTy = cast<VectorType>(Ty);
269 Result << "<" << PTy->getNumElements() << " x ";
270 CalcTypeName(PTy->getElementType(), TypeStack, Result);
274 case Type::OpaqueTyID:
278 Result << "<unrecognized-type>";
282 TypeStack.pop_back(); // Remove self from stack.
285 /// printTypeInt - The internal guts of printing out a type that has a
286 /// potentially named portion.
288 void TypePrinting::print(const Type *Ty) {
289 // Primitive types always print out their description, regardless of whether
290 // they have been named or not.
291 if (Ty->isInteger() || (Ty->isPrimitiveType() && !isa<OpaqueType>(Ty))) {
292 OS << Ty->getDescription();
296 // Check to see if the type is named.
297 std::map<const Type*, std::string>::iterator I = TypeNames.find(Ty);
298 if (I != TypeNames.end()) {
303 // Otherwise we have a type that has not been named but is a derived type.
304 // Carefully recurse the type hierarchy to print out any contained symbolic
306 SmallVector<const Type *, 16> TypeStack;
307 std::string TypeName;
309 raw_string_ostream TypeOS(TypeName);
310 CalcTypeName(Ty, TypeStack, TypeOS);
313 // Cache type name for later use.
314 TypeNames.insert(std::make_pair(Ty, TypeOS.str()));
317 /// printAtLeastOneLevel - Print out one level of the possibly complex type
318 /// without considering any symbolic types that we may have equal to it.
319 void TypePrinting::printAtLeastOneLevel(const Type *Ty) {
320 // If the type does not have a name, then it is already guaranteed to print at
322 std::map<const Type*, std::string>::iterator I = TypeNames.find(Ty);
323 if (I == TypeNames.end())
326 // Otherwise, temporarily remove the name and print it.
328 std::swap(OldName, I->second);
330 // Print the type without the name.
331 SmallVector<const Type *, 16> TypeStack;
332 CalcTypeName(Ty, TypeStack, OS);
335 std::swap(OldName, I->second);
339 /// WriteTypeSymbolic - This attempts to write the specified type as a symbolic
340 /// type, iff there is an entry in the modules symbol table for the specified
341 /// type or one of it's component types.
343 void llvm::WriteTypeSymbolic(raw_ostream &Out, const Type *Ty, const Module *M){
344 TypePrinting(M, Out).print(Ty);
347 //===----------------------------------------------------------------------===//
348 // SlotTracker Class: Enumerate slot numbers for unnamed values
349 //===----------------------------------------------------------------------===//
353 /// This class provides computation of slot numbers for LLVM Assembly writing.
357 /// ValueMap - A mapping of Values to slot numbers
358 typedef DenseMap<const Value*, unsigned> ValueMap;
361 /// TheModule - The module for which we are holding slot numbers
362 const Module* TheModule;
364 /// TheFunction - The function for which we are holding slot numbers
365 const Function* TheFunction;
366 bool FunctionProcessed;
368 /// mMap - The TypePlanes map for the module level data
372 /// fMap - The TypePlanes map for the function level data
377 /// Construct from a module
378 explicit SlotTracker(const Module *M);
379 /// Construct from a function, starting out in incorp state.
380 explicit SlotTracker(const Function *F);
382 /// Return the slot number of the specified value in it's type
383 /// plane. If something is not in the SlotTracker, return -1.
384 int getLocalSlot(const Value *V);
385 int getGlobalSlot(const GlobalValue *V);
387 /// If you'd like to deal with a function instead of just a module, use
388 /// this method to get its data into the SlotTracker.
389 void incorporateFunction(const Function *F) {
391 FunctionProcessed = false;
394 /// After calling incorporateFunction, use this method to remove the
395 /// most recently incorporated function from the SlotTracker. This
396 /// will reset the state of the machine back to just the module contents.
397 void purgeFunction();
399 // Implementation Details
401 /// This function does the actual initialization.
402 inline void initialize();
404 /// CreateModuleSlot - Insert the specified GlobalValue* into the slot table.
405 void CreateModuleSlot(const GlobalValue *V);
407 /// CreateFunctionSlot - Insert the specified Value* into the slot table.
408 void CreateFunctionSlot(const Value *V);
410 /// Add all of the module level global variables (and their initializers)
411 /// and function declarations, but not the contents of those functions.
412 void processModule();
414 /// Add all of the functions arguments, basic blocks, and instructions
415 void processFunction();
417 SlotTracker(const SlotTracker &); // DO NOT IMPLEMENT
418 void operator=(const SlotTracker &); // DO NOT IMPLEMENT
421 } // end anonymous namespace
424 static SlotTracker *createSlotTracker(const Value *V) {
425 if (const Argument *FA = dyn_cast<Argument>(V))
426 return new SlotTracker(FA->getParent());
428 if (const Instruction *I = dyn_cast<Instruction>(V))
429 return new SlotTracker(I->getParent()->getParent());
431 if (const BasicBlock *BB = dyn_cast<BasicBlock>(V))
432 return new SlotTracker(BB->getParent());
434 if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(V))
435 return new SlotTracker(GV->getParent());
437 if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(V))
438 return new SlotTracker(GA->getParent());
440 if (const Function *Func = dyn_cast<Function>(V))
441 return new SlotTracker(Func);
447 #define ST_DEBUG(X) cerr << X
452 // Module level constructor. Causes the contents of the Module (sans functions)
453 // to be added to the slot table.
454 SlotTracker::SlotTracker(const Module *M)
455 : TheModule(M), TheFunction(0), FunctionProcessed(false), mNext(0), fNext(0) {
458 // Function level constructor. Causes the contents of the Module and the one
459 // function provided to be added to the slot table.
460 SlotTracker::SlotTracker(const Function *F)
461 : TheModule(F ? F->getParent() : 0), TheFunction(F), FunctionProcessed(false),
465 inline void SlotTracker::initialize() {
468 TheModule = 0; ///< Prevent re-processing next time we're called.
471 if (TheFunction && !FunctionProcessed)
475 // Iterate through all the global variables, functions, and global
476 // variable initializers and create slots for them.
477 void SlotTracker::processModule() {
478 ST_DEBUG("begin processModule!\n");
480 // Add all of the unnamed global variables to the value table.
481 for (Module::const_global_iterator I = TheModule->global_begin(),
482 E = TheModule->global_end(); I != E; ++I)
486 // Add all the unnamed functions to the table.
487 for (Module::const_iterator I = TheModule->begin(), E = TheModule->end();
492 ST_DEBUG("end processModule!\n");
496 // Process the arguments, basic blocks, and instructions of a function.
497 void SlotTracker::processFunction() {
498 ST_DEBUG("begin processFunction!\n");
501 // Add all the function arguments with no names.
502 for(Function::const_arg_iterator AI = TheFunction->arg_begin(),
503 AE = TheFunction->arg_end(); AI != AE; ++AI)
505 CreateFunctionSlot(AI);
507 ST_DEBUG("Inserting Instructions:\n");
509 // Add all of the basic blocks and instructions with no names.
510 for (Function::const_iterator BB = TheFunction->begin(),
511 E = TheFunction->end(); BB != E; ++BB) {
513 CreateFunctionSlot(BB);
514 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I != E; ++I)
515 if (I->getType() != Type::VoidTy && !I->hasName())
516 CreateFunctionSlot(I);
519 FunctionProcessed = true;
521 ST_DEBUG("end processFunction!\n");
524 /// Clean up after incorporating a function. This is the only way to get out of
525 /// the function incorporation state that affects get*Slot/Create*Slot. Function
526 /// incorporation state is indicated by TheFunction != 0.
527 void SlotTracker::purgeFunction() {
528 ST_DEBUG("begin purgeFunction!\n");
529 fMap.clear(); // Simply discard the function level map
531 FunctionProcessed = false;
532 ST_DEBUG("end purgeFunction!\n");
535 /// getGlobalSlot - Get the slot number of a global value.
536 int SlotTracker::getGlobalSlot(const GlobalValue *V) {
537 // Check for uninitialized state and do lazy initialization.
540 // Find the type plane in the module map
541 ValueMap::iterator MI = mMap.find(V);
542 return MI == mMap.end() ? -1 : (int)MI->second;
546 /// getLocalSlot - Get the slot number for a value that is local to a function.
547 int SlotTracker::getLocalSlot(const Value *V) {
548 assert(!isa<Constant>(V) && "Can't get a constant or global slot with this!");
550 // Check for uninitialized state and do lazy initialization.
553 ValueMap::iterator FI = fMap.find(V);
554 return FI == fMap.end() ? -1 : (int)FI->second;
558 /// CreateModuleSlot - Insert the specified GlobalValue* into the slot table.
559 void SlotTracker::CreateModuleSlot(const GlobalValue *V) {
560 assert(V && "Can't insert a null Value into SlotTracker!");
561 assert(V->getType() != Type::VoidTy && "Doesn't need a slot!");
562 assert(!V->hasName() && "Doesn't need a slot!");
564 unsigned DestSlot = mNext++;
567 ST_DEBUG(" Inserting value [" << V->getType() << "] = " << V << " slot=" <<
569 // G = Global, F = Function, A = Alias, o = other
570 ST_DEBUG((isa<GlobalVariable>(V) ? 'G' :
571 (isa<Function>(V) ? 'F' :
572 (isa<GlobalAlias>(V) ? 'A' : 'o'))) << "]\n");
576 /// CreateSlot - Create a new slot for the specified value if it has no name.
577 void SlotTracker::CreateFunctionSlot(const Value *V) {
578 assert(V->getType() != Type::VoidTy && !V->hasName() &&
579 "Doesn't need a slot!");
581 unsigned DestSlot = fNext++;
584 // G = Global, F = Function, o = other
585 ST_DEBUG(" Inserting value [" << V->getType() << "] = " << V << " slot=" <<
586 DestSlot << " [o]\n");
591 //===----------------------------------------------------------------------===//
592 // AsmWriter Implementation
593 //===----------------------------------------------------------------------===//
595 static void WriteAsOperandInternal(raw_ostream &Out, const Value *V,
596 TypePrinting &TypePrinter,
597 SlotTracker *Machine);
601 static const char *getPredicateText(unsigned predicate) {
602 const char * pred = "unknown";
604 case FCmpInst::FCMP_FALSE: pred = "false"; break;
605 case FCmpInst::FCMP_OEQ: pred = "oeq"; break;
606 case FCmpInst::FCMP_OGT: pred = "ogt"; break;
607 case FCmpInst::FCMP_OGE: pred = "oge"; break;
608 case FCmpInst::FCMP_OLT: pred = "olt"; break;
609 case FCmpInst::FCMP_OLE: pred = "ole"; break;
610 case FCmpInst::FCMP_ONE: pred = "one"; break;
611 case FCmpInst::FCMP_ORD: pred = "ord"; break;
612 case FCmpInst::FCMP_UNO: pred = "uno"; break;
613 case FCmpInst::FCMP_UEQ: pred = "ueq"; break;
614 case FCmpInst::FCMP_UGT: pred = "ugt"; break;
615 case FCmpInst::FCMP_UGE: pred = "uge"; break;
616 case FCmpInst::FCMP_ULT: pred = "ult"; break;
617 case FCmpInst::FCMP_ULE: pred = "ule"; break;
618 case FCmpInst::FCMP_UNE: pred = "une"; break;
619 case FCmpInst::FCMP_TRUE: pred = "true"; break;
620 case ICmpInst::ICMP_EQ: pred = "eq"; break;
621 case ICmpInst::ICMP_NE: pred = "ne"; break;
622 case ICmpInst::ICMP_SGT: pred = "sgt"; break;
623 case ICmpInst::ICMP_SGE: pred = "sge"; break;
624 case ICmpInst::ICMP_SLT: pred = "slt"; break;
625 case ICmpInst::ICMP_SLE: pred = "sle"; break;
626 case ICmpInst::ICMP_UGT: pred = "ugt"; break;
627 case ICmpInst::ICMP_UGE: pred = "uge"; break;
628 case ICmpInst::ICMP_ULT: pred = "ult"; break;
629 case ICmpInst::ICMP_ULE: pred = "ule"; break;
634 static void WriteConstantInt(raw_ostream &Out, const Constant *CV,
635 TypePrinting &TypePrinter, SlotTracker *Machine) {
636 if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV)) {
637 if (CI->getType() == Type::Int1Ty) {
638 Out << (CI->getZExtValue() ? "true" : "false");
641 Out << CI->getValue();
645 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CV)) {
646 if (&CFP->getValueAPF().getSemantics() == &APFloat::IEEEdouble ||
647 &CFP->getValueAPF().getSemantics() == &APFloat::IEEEsingle) {
648 // We would like to output the FP constant value in exponential notation,
649 // but we cannot do this if doing so will lose precision. Check here to
650 // make sure that we only output it in exponential format if we can parse
651 // the value back and get the same value.
654 bool isDouble = &CFP->getValueAPF().getSemantics()==&APFloat::IEEEdouble;
655 double Val = isDouble ? CFP->getValueAPF().convertToDouble() :
656 CFP->getValueAPF().convertToFloat();
657 std::string StrVal = ftostr(CFP->getValueAPF());
659 // Check to make sure that the stringized number is not some string like
660 // "Inf" or NaN, that atof will accept, but the lexer will not. Check
661 // that the string matches the "[-+]?[0-9]" regex.
663 if ((StrVal[0] >= '0' && StrVal[0] <= '9') ||
664 ((StrVal[0] == '-' || StrVal[0] == '+') &&
665 (StrVal[1] >= '0' && StrVal[1] <= '9'))) {
666 // Reparse stringized version!
667 if (atof(StrVal.c_str()) == Val) {
672 // Otherwise we could not reparse it to exactly the same value, so we must
673 // output the string in hexadecimal format! Note that loading and storing
674 // floating point types changes the bits of NaNs on some hosts, notably
675 // x86, so we must not use these types.
676 assert(sizeof(double) == sizeof(uint64_t) &&
677 "assuming that double is 64 bits!");
679 APFloat apf = CFP->getValueAPF();
680 // Floats are represented in ASCII IR as double, convert.
682 apf.convert(APFloat::IEEEdouble, APFloat::rmNearestTiesToEven,
685 utohex_buffer(uint64_t(apf.bitcastToAPInt().getZExtValue()),
690 // Some form of long double. These appear as a magic letter identifying
691 // the type, then a fixed number of hex digits.
693 if (&CFP->getValueAPF().getSemantics() == &APFloat::x87DoubleExtended)
695 else if (&CFP->getValueAPF().getSemantics() == &APFloat::IEEEquad)
697 else if (&CFP->getValueAPF().getSemantics() == &APFloat::PPCDoubleDouble)
700 assert(0 && "Unsupported floating point type");
701 // api needed to prevent premature destruction
702 APInt api = CFP->getValueAPF().bitcastToAPInt();
703 const uint64_t* p = api.getRawData();
706 int width = api.getBitWidth();
707 for (int j=0; j<width; j+=4, shiftcount-=4) {
708 unsigned int nibble = (word>>shiftcount) & 15;
710 Out << (unsigned char)(nibble + '0');
712 Out << (unsigned char)(nibble - 10 + 'A');
713 if (shiftcount == 0 && j+4 < width) {
717 shiftcount = width-j-4;
723 if (isa<ConstantAggregateZero>(CV)) {
724 Out << "zeroinitializer";
728 if (const ConstantArray *CA = dyn_cast<ConstantArray>(CV)) {
729 // As a special case, print the array as a string if it is an array of
730 // i8 with ConstantInt values.
732 const Type *ETy = CA->getType()->getElementType();
733 if (CA->isString()) {
735 PrintEscapedString(CA->getAsString(), Out);
737 } else { // Cannot output in string format...
739 if (CA->getNumOperands()) {
740 TypePrinter.print(ETy);
742 WriteAsOperandInternal(Out, CA->getOperand(0),
743 TypePrinter, Machine);
744 for (unsigned i = 1, e = CA->getNumOperands(); i != e; ++i) {
746 TypePrinter.print(ETy);
748 WriteAsOperandInternal(Out, CA->getOperand(i), TypePrinter, Machine);
756 if (const ConstantStruct *CS = dyn_cast<ConstantStruct>(CV)) {
757 if (CS->getType()->isPacked())
760 unsigned N = CS->getNumOperands();
763 TypePrinter.print(CS->getOperand(0)->getType());
766 WriteAsOperandInternal(Out, CS->getOperand(0), TypePrinter, Machine);
768 for (unsigned i = 1; i < N; i++) {
770 TypePrinter.print(CS->getOperand(i)->getType());
773 WriteAsOperandInternal(Out, CS->getOperand(i), TypePrinter, Machine);
779 if (CS->getType()->isPacked())
784 if (const ConstantVector *CP = dyn_cast<ConstantVector>(CV)) {
785 const Type *ETy = CP->getType()->getElementType();
786 assert(CP->getNumOperands() > 0 &&
787 "Number of operands for a PackedConst must be > 0");
789 TypePrinter.print(ETy);
791 WriteAsOperandInternal(Out, CP->getOperand(0), TypePrinter, Machine);
792 for (unsigned i = 1, e = CP->getNumOperands(); i != e; ++i) {
794 TypePrinter.print(ETy);
796 WriteAsOperandInternal(Out, CP->getOperand(i), TypePrinter, Machine);
802 if (isa<ConstantPointerNull>(CV)) {
807 if (isa<UndefValue>(CV)) {
812 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV)) {
813 Out << CE->getOpcodeName();
815 Out << ' ' << getPredicateText(CE->getPredicate());
818 for (User::const_op_iterator OI=CE->op_begin(); OI != CE->op_end(); ++OI) {
819 TypePrinter.print((*OI)->getType());
821 WriteAsOperandInternal(Out, *OI, TypePrinter, Machine);
822 if (OI+1 != CE->op_end())
826 if (CE->hasIndices()) {
827 const SmallVector<unsigned, 4> &Indices = CE->getIndices();
828 for (unsigned i = 0, e = Indices.size(); i != e; ++i)
829 Out << ", " << Indices[i];
834 TypePrinter.print(CE->getType());
841 Out << "<placeholder or erroneous Constant>";
845 /// WriteAsOperand - Write the name of the specified value out to the specified
846 /// ostream. This can be useful when you just want to print int %reg126, not
847 /// the whole instruction that generated it.
849 static void WriteAsOperandInternal(raw_ostream &Out, const Value *V,
850 TypePrinting &TypePrinter,
851 SlotTracker *Machine) {
853 PrintLLVMName(Out, V);
857 const Constant *CV = dyn_cast<Constant>(V);
858 if (CV && !isa<GlobalValue>(CV)) {
859 WriteConstantInt(Out, CV, TypePrinter, Machine);
863 if (const InlineAsm *IA = dyn_cast<InlineAsm>(V)) {
865 if (IA->hasSideEffects())
866 Out << "sideeffect ";
868 PrintEscapedString(IA->getAsmString(), Out);
870 PrintEscapedString(IA->getConstraintString(), Out);
878 if (const GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
879 Slot = Machine->getGlobalSlot(GV);
882 Slot = Machine->getLocalSlot(V);
885 Machine = createSlotTracker(V);
887 if (const GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
888 Slot = Machine->getGlobalSlot(GV);
891 Slot = Machine->getLocalSlot(V);
900 Out << Prefix << Slot;
905 /// WriteAsOperand - Write the name of the specified value out to the specified
906 /// ostream. This can be useful when you just want to print int %reg126, not
907 /// the whole instruction that generated it.
909 void llvm::WriteAsOperand(std::ostream &Out, const Value *V, bool PrintType,
910 const Module *Context) {
911 raw_os_ostream OS(Out);
912 WriteAsOperand(OS, V, PrintType, Context);
915 void llvm::WriteAsOperand(raw_ostream &Out, const Value *V, bool PrintType,
916 const Module *Context) {
917 if (Context == 0) Context = getModuleFromVal(V);
919 TypePrinting TypePrinter(Context, Out);
921 TypePrinter.print(V->getType());
925 WriteAsOperandInternal(Out, V, TypePrinter, 0);
931 class AssemblyWriter {
933 SlotTracker &Machine;
934 const Module *TheModule;
935 TypePrinting TypePrinter;
936 AssemblyAnnotationWriter *AnnotationWriter;
938 inline AssemblyWriter(raw_ostream &o, SlotTracker &Mac, const Module *M,
939 AssemblyAnnotationWriter *AAW)
940 : Out(o), Machine(Mac), TheModule(M), TypePrinter(M, Out),
941 AnnotationWriter(AAW) {
944 void write(const Module *M) { printModule(M); }
946 void write(const GlobalValue *G) {
947 if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(G))
949 else if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(G))
951 else if (const Function *F = dyn_cast<Function>(G))
954 assert(0 && "Unknown global");
957 void write(const BasicBlock *BB) { printBasicBlock(BB); }
958 void write(const Instruction *I) { printInstruction(*I); }
959 // void write(const Type *Ty) { printType(Ty); }
961 void writeOperand(const Value *Op, bool PrintType);
962 void writeParamOperand(const Value *Operand, Attributes Attrs);
964 const Module* getModule() { return TheModule; }
967 void printModule(const Module *M);
968 void printTypeSymbolTable(const TypeSymbolTable &ST);
969 void printGlobal(const GlobalVariable *GV);
970 void printAlias(const GlobalAlias *GV);
971 void printFunction(const Function *F);
972 void printArgument(const Argument *FA, Attributes Attrs);
973 void printBasicBlock(const BasicBlock *BB);
974 void printInstruction(const Instruction &I);
976 // printType - Go to extreme measures to attempt to print out a short,
977 // symbolic version of a type name.
979 void printType(const Type *Ty) {
980 TypePrinter.print(Ty);
983 // printInfoComment - Print a little comment after the instruction indicating
984 // which slot it occupies.
985 void printInfoComment(const Value &V);
987 } // end of llvm namespace
990 void AssemblyWriter::writeOperand(const Value *Operand, bool PrintType) {
992 Out << "<null operand!>";
995 printType(Operand->getType());
998 WriteAsOperandInternal(Out, Operand, TypePrinter, &Machine);
1002 void AssemblyWriter::writeParamOperand(const Value *Operand,
1005 Out << "<null operand!>";
1008 printType(Operand->getType());
1009 // Print parameter attributes list
1010 if (Attrs != Attribute::None)
1011 Out << ' ' << Attribute::getAsString(Attrs);
1013 // Print the operand
1014 WriteAsOperandInternal(Out, Operand, TypePrinter, &Machine);
1018 void AssemblyWriter::printModule(const Module *M) {
1019 if (!M->getModuleIdentifier().empty() &&
1020 // Don't print the ID if it will start a new line (which would
1021 // require a comment char before it).
1022 M->getModuleIdentifier().find('\n') == std::string::npos)
1023 Out << "; ModuleID = '" << M->getModuleIdentifier() << "'\n";
1025 if (!M->getDataLayout().empty())
1026 Out << "target datalayout = \"" << M->getDataLayout() << "\"\n";
1027 if (!M->getTargetTriple().empty())
1028 Out << "target triple = \"" << M->getTargetTriple() << "\"\n";
1030 if (!M->getModuleInlineAsm().empty()) {
1031 // Split the string into lines, to make it easier to read the .ll file.
1032 std::string Asm = M->getModuleInlineAsm();
1034 size_t NewLine = Asm.find_first_of('\n', CurPos);
1035 while (NewLine != std::string::npos) {
1036 // We found a newline, print the portion of the asm string from the
1037 // last newline up to this newline.
1038 Out << "module asm \"";
1039 PrintEscapedString(std::string(Asm.begin()+CurPos, Asm.begin()+NewLine),
1043 NewLine = Asm.find_first_of('\n', CurPos);
1045 Out << "module asm \"";
1046 PrintEscapedString(std::string(Asm.begin()+CurPos, Asm.end()), Out);
1050 // Loop over the dependent libraries and emit them.
1051 Module::lib_iterator LI = M->lib_begin();
1052 Module::lib_iterator LE = M->lib_end();
1054 Out << "deplibs = [ ";
1056 Out << '"' << *LI << '"';
1064 // Loop over the symbol table, emitting all named constants.
1065 printTypeSymbolTable(M->getTypeSymbolTable());
1067 for (Module::const_global_iterator I = M->global_begin(), E = M->global_end();
1071 // Output all aliases.
1072 if (!M->alias_empty()) Out << "\n";
1073 for (Module::const_alias_iterator I = M->alias_begin(), E = M->alias_end();
1077 // Output all of the functions.
1078 for (Module::const_iterator I = M->begin(), E = M->end(); I != E; ++I)
1082 static void PrintLinkage(GlobalValue::LinkageTypes LT, raw_ostream &Out) {
1084 case GlobalValue::PrivateLinkage: Out << "private "; break;
1085 case GlobalValue::InternalLinkage: Out << "internal "; break;
1086 case GlobalValue::LinkOnceLinkage: Out << "linkonce "; break;
1087 case GlobalValue::WeakLinkage: Out << "weak "; break;
1088 case GlobalValue::CommonLinkage: Out << "common "; break;
1089 case GlobalValue::AppendingLinkage: Out << "appending "; break;
1090 case GlobalValue::DLLImportLinkage: Out << "dllimport "; break;
1091 case GlobalValue::DLLExportLinkage: Out << "dllexport "; break;
1092 case GlobalValue::ExternalWeakLinkage: Out << "extern_weak "; break;
1093 case GlobalValue::ExternalLinkage: break;
1094 case GlobalValue::GhostLinkage:
1095 Out << "GhostLinkage not allowed in AsmWriter!\n";
1101 static void PrintVisibility(GlobalValue::VisibilityTypes Vis,
1104 default: assert(0 && "Invalid visibility style!");
1105 case GlobalValue::DefaultVisibility: break;
1106 case GlobalValue::HiddenVisibility: Out << "hidden "; break;
1107 case GlobalValue::ProtectedVisibility: Out << "protected "; break;
1111 void AssemblyWriter::printGlobal(const GlobalVariable *GV) {
1112 if (GV->hasName()) {
1113 PrintLLVMName(Out, GV);
1117 if (!GV->hasInitializer() && GV->hasExternalLinkage())
1120 PrintLinkage(GV->getLinkage(), Out);
1121 PrintVisibility(GV->getVisibility(), Out);
1123 if (GV->isThreadLocal()) Out << "thread_local ";
1124 if (unsigned AddressSpace = GV->getType()->getAddressSpace())
1125 Out << "addrspace(" << AddressSpace << ") ";
1126 Out << (GV->isConstant() ? "constant " : "global ");
1127 printType(GV->getType()->getElementType());
1129 if (GV->hasInitializer()) {
1131 writeOperand(GV->getInitializer(), false);
1134 if (GV->hasSection())
1135 Out << ", section \"" << GV->getSection() << '"';
1136 if (GV->getAlignment())
1137 Out << ", align " << GV->getAlignment();
1139 printInfoComment(*GV);
1143 void AssemblyWriter::printAlias(const GlobalAlias *GA) {
1144 // Don't crash when dumping partially built GA
1146 Out << "<<nameless>> = ";
1148 PrintLLVMName(Out, GA);
1151 PrintVisibility(GA->getVisibility(), Out);
1155 PrintLinkage(GA->getLinkage(), Out);
1157 const Constant *Aliasee = GA->getAliasee();
1159 if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(Aliasee)) {
1160 printType(GV->getType());
1162 PrintLLVMName(Out, GV);
1163 } else if (const Function *F = dyn_cast<Function>(Aliasee)) {
1164 printType(F->getFunctionType());
1167 WriteAsOperandInternal(Out, F, TypePrinter, &Machine);
1168 } else if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(Aliasee)) {
1169 printType(GA->getType());
1171 PrintLLVMName(Out, GA);
1173 const ConstantExpr *CE = 0;
1174 if ((CE = dyn_cast<ConstantExpr>(Aliasee)) &&
1175 (CE->getOpcode() == Instruction::BitCast)) {
1176 writeOperand(CE, false);
1178 assert(0 && "Unsupported aliasee");
1181 printInfoComment(*GA);
1185 void AssemblyWriter::printTypeSymbolTable(const TypeSymbolTable &ST) {
1187 for (TypeSymbolTable::const_iterator TI = ST.begin(), TE = ST.end();
1190 PrintLLVMName(Out, &TI->first[0], TI->first.size(), LocalPrefix);
1193 // Make sure we print out at least one level of the type structure, so
1194 // that we do not get %FILE = type %FILE
1195 TypePrinter.printAtLeastOneLevel(TI->second);
1200 /// printFunction - Print all aspects of a function.
1202 void AssemblyWriter::printFunction(const Function *F) {
1203 // Print out the return type and name.
1206 if (AnnotationWriter) AnnotationWriter->emitFunctionAnnot(F, Out);
1208 if (F->isDeclaration())
1213 PrintLinkage(F->getLinkage(), Out);
1214 PrintVisibility(F->getVisibility(), Out);
1216 // Print the calling convention.
1217 switch (F->getCallingConv()) {
1218 case CallingConv::C: break; // default
1219 case CallingConv::Fast: Out << "fastcc "; break;
1220 case CallingConv::Cold: Out << "coldcc "; break;
1221 case CallingConv::X86_StdCall: Out << "x86_stdcallcc "; break;
1222 case CallingConv::X86_FastCall: Out << "x86_fastcallcc "; break;
1223 default: Out << "cc" << F->getCallingConv() << " "; break;
1226 const FunctionType *FT = F->getFunctionType();
1227 const AttrListPtr &Attrs = F->getAttributes();
1228 Attributes RetAttrs = Attrs.getRetAttributes();
1229 if (RetAttrs != Attribute::None)
1230 Out << Attribute::getAsString(Attrs.getRetAttributes()) << ' ';
1231 printType(F->getReturnType());
1233 WriteAsOperandInternal(Out, F, TypePrinter, &Machine);
1235 Machine.incorporateFunction(F);
1237 // Loop over the arguments, printing them...
1240 if (!F->isDeclaration()) {
1241 // If this isn't a declaration, print the argument names as well.
1242 for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
1244 // Insert commas as we go... the first arg doesn't get a comma
1245 if (I != F->arg_begin()) Out << ", ";
1246 printArgument(I, Attrs.getParamAttributes(Idx));
1250 // Otherwise, print the types from the function type.
1251 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
1252 // Insert commas as we go... the first arg doesn't get a comma
1256 printType(FT->getParamType(i));
1258 Attributes ArgAttrs = Attrs.getParamAttributes(i+1);
1259 if (ArgAttrs != Attribute::None)
1260 Out << ' ' << Attribute::getAsString(ArgAttrs);
1264 // Finish printing arguments...
1265 if (FT->isVarArg()) {
1266 if (FT->getNumParams()) Out << ", ";
1267 Out << "..."; // Output varargs portion of signature!
1270 Attributes FnAttrs = Attrs.getFnAttributes();
1271 if (FnAttrs != Attribute::None)
1272 Out << ' ' << Attribute::getAsString(Attrs.getFnAttributes());
1273 if (F->hasSection())
1274 Out << " section \"" << F->getSection() << '"';
1275 if (F->getAlignment())
1276 Out << " align " << F->getAlignment();
1278 Out << " gc \"" << F->getGC() << '"';
1279 if (F->isDeclaration()) {
1284 // Output all of its basic blocks... for the function
1285 for (Function::const_iterator I = F->begin(), E = F->end(); I != E; ++I)
1291 Machine.purgeFunction();
1294 /// printArgument - This member is called for every argument that is passed into
1295 /// the function. Simply print it out
1297 void AssemblyWriter::printArgument(const Argument *Arg,
1300 printType(Arg->getType());
1302 // Output parameter attributes list
1303 if (Attrs != Attribute::None)
1304 Out << ' ' << Attribute::getAsString(Attrs);
1306 // Output name, if available...
1307 if (Arg->hasName()) {
1309 PrintLLVMName(Out, Arg);
1313 /// printBasicBlock - This member is called for each basic block in a method.
1315 void AssemblyWriter::printBasicBlock(const BasicBlock *BB) {
1316 if (BB->hasName()) { // Print out the label if it exists...
1318 PrintLLVMName(Out, BB->getNameStart(), BB->getNameLen(), LabelPrefix);
1320 } else if (!BB->use_empty()) { // Don't print block # of no uses...
1321 Out << "\n; <label>:";
1322 int Slot = Machine.getLocalSlot(BB);
1329 if (BB->getParent() == 0)
1330 Out << "\t\t; Error: Block without parent!";
1331 else if (BB != &BB->getParent()->getEntryBlock()) { // Not the entry block?
1332 // Output predecessors for the block...
1334 pred_const_iterator PI = pred_begin(BB), PE = pred_end(BB);
1337 Out << " No predecessors!";
1340 writeOperand(*PI, false);
1341 for (++PI; PI != PE; ++PI) {
1343 writeOperand(*PI, false);
1350 if (AnnotationWriter) AnnotationWriter->emitBasicBlockStartAnnot(BB, Out);
1352 // Output all of the instructions in the basic block...
1353 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I != E; ++I)
1354 printInstruction(*I);
1356 if (AnnotationWriter) AnnotationWriter->emitBasicBlockEndAnnot(BB, Out);
1360 /// printInfoComment - Print a little comment after the instruction indicating
1361 /// which slot it occupies.
1363 void AssemblyWriter::printInfoComment(const Value &V) {
1364 if (V.getType() != Type::VoidTy) {
1366 printType(V.getType());
1369 if (!V.hasName() && !isa<Instruction>(V)) {
1371 if (const GlobalValue *GV = dyn_cast<GlobalValue>(&V))
1372 SlotNum = Machine.getGlobalSlot(GV);
1374 SlotNum = Machine.getLocalSlot(&V);
1378 Out << ':' << SlotNum; // Print out the def slot taken.
1380 Out << " [#uses=" << V.getNumUses() << ']'; // Output # uses
1384 // This member is called for each Instruction in a function..
1385 void AssemblyWriter::printInstruction(const Instruction &I) {
1386 if (AnnotationWriter) AnnotationWriter->emitInstructionAnnot(&I, Out);
1390 // Print out name if it exists...
1392 PrintLLVMName(Out, &I);
1394 } else if (I.getType() != Type::VoidTy) {
1395 // Print out the def slot taken.
1396 int SlotNum = Machine.getLocalSlot(&I);
1398 Out << "<badref> = ";
1400 Out << '%' << SlotNum << " = ";
1403 // If this is a volatile load or store, print out the volatile marker.
1404 if ((isa<LoadInst>(I) && cast<LoadInst>(I).isVolatile()) ||
1405 (isa<StoreInst>(I) && cast<StoreInst>(I).isVolatile())) {
1407 } else if (isa<CallInst>(I) && cast<CallInst>(I).isTailCall()) {
1408 // If this is a call, check if it's a tail call.
1412 // Print out the opcode...
1413 Out << I.getOpcodeName();
1415 // Print out the compare instruction predicates
1416 if (const CmpInst *CI = dyn_cast<CmpInst>(&I))
1417 Out << ' ' << getPredicateText(CI->getPredicate());
1419 // Print out the type of the operands...
1420 const Value *Operand = I.getNumOperands() ? I.getOperand(0) : 0;
1422 // Special case conditional branches to swizzle the condition out to the front
1423 if (isa<BranchInst>(I) && cast<BranchInst>(I).isConditional()) {
1424 BranchInst &BI(cast<BranchInst>(I));
1426 writeOperand(BI.getCondition(), true);
1428 writeOperand(BI.getSuccessor(0), true);
1430 writeOperand(BI.getSuccessor(1), true);
1432 } else if (isa<SwitchInst>(I)) {
1433 // Special case switch statement to get formatting nice and correct...
1435 writeOperand(Operand , true);
1437 writeOperand(I.getOperand(1), true);
1440 for (unsigned op = 2, Eop = I.getNumOperands(); op < Eop; op += 2) {
1442 writeOperand(I.getOperand(op ), true);
1444 writeOperand(I.getOperand(op+1), true);
1447 } else if (isa<PHINode>(I)) {
1449 printType(I.getType());
1452 for (unsigned op = 0, Eop = I.getNumOperands(); op < Eop; op += 2) {
1453 if (op) Out << ", ";
1455 writeOperand(I.getOperand(op ), false); Out << ", ";
1456 writeOperand(I.getOperand(op+1), false); Out << " ]";
1458 } else if (const ExtractValueInst *EVI = dyn_cast<ExtractValueInst>(&I)) {
1460 writeOperand(I.getOperand(0), true);
1461 for (const unsigned *i = EVI->idx_begin(), *e = EVI->idx_end(); i != e; ++i)
1463 } else if (const InsertValueInst *IVI = dyn_cast<InsertValueInst>(&I)) {
1465 writeOperand(I.getOperand(0), true); Out << ", ";
1466 writeOperand(I.getOperand(1), true);
1467 for (const unsigned *i = IVI->idx_begin(), *e = IVI->idx_end(); i != e; ++i)
1469 } else if (isa<ReturnInst>(I) && !Operand) {
1471 } else if (const CallInst *CI = dyn_cast<CallInst>(&I)) {
1472 // Print the calling convention being used.
1473 switch (CI->getCallingConv()) {
1474 case CallingConv::C: break; // default
1475 case CallingConv::Fast: Out << " fastcc"; break;
1476 case CallingConv::Cold: Out << " coldcc"; break;
1477 case CallingConv::X86_StdCall: Out << " x86_stdcallcc"; break;
1478 case CallingConv::X86_FastCall: Out << " x86_fastcallcc"; break;
1479 default: Out << " cc" << CI->getCallingConv(); break;
1482 const PointerType *PTy = cast<PointerType>(Operand->getType());
1483 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
1484 const Type *RetTy = FTy->getReturnType();
1485 const AttrListPtr &PAL = CI->getAttributes();
1487 if (PAL.getRetAttributes() != Attribute::None)
1488 Out << ' ' << Attribute::getAsString(PAL.getRetAttributes());
1490 // If possible, print out the short form of the call instruction. We can
1491 // only do this if the first argument is a pointer to a nonvararg function,
1492 // and if the return type is not a pointer to a function.
1495 if (!FTy->isVarArg() &&
1496 (!isa<PointerType>(RetTy) ||
1497 !isa<FunctionType>(cast<PointerType>(RetTy)->getElementType()))) {
1500 writeOperand(Operand, false);
1502 writeOperand(Operand, true);
1505 for (unsigned op = 1, Eop = I.getNumOperands(); op < Eop; ++op) {
1508 writeParamOperand(I.getOperand(op), PAL.getParamAttributes(op));
1511 if (PAL.getFnAttributes() != Attribute::None)
1512 Out << ' ' << Attribute::getAsString(PAL.getFnAttributes());
1513 } else if (const InvokeInst *II = dyn_cast<InvokeInst>(&I)) {
1514 const PointerType *PTy = cast<PointerType>(Operand->getType());
1515 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
1516 const Type *RetTy = FTy->getReturnType();
1517 const AttrListPtr &PAL = II->getAttributes();
1519 // Print the calling convention being used.
1520 switch (II->getCallingConv()) {
1521 case CallingConv::C: break; // default
1522 case CallingConv::Fast: Out << " fastcc"; break;
1523 case CallingConv::Cold: Out << " coldcc"; break;
1524 case CallingConv::X86_StdCall: Out << " x86_stdcallcc"; break;
1525 case CallingConv::X86_FastCall: Out << " x86_fastcallcc"; break;
1526 default: Out << " cc" << II->getCallingConv(); break;
1529 if (PAL.getRetAttributes() != Attribute::None)
1530 Out << ' ' << Attribute::getAsString(PAL.getRetAttributes());
1532 // If possible, print out the short form of the invoke instruction. We can
1533 // only do this if the first argument is a pointer to a nonvararg function,
1534 // and if the return type is not a pointer to a function.
1537 if (!FTy->isVarArg() &&
1538 (!isa<PointerType>(RetTy) ||
1539 !isa<FunctionType>(cast<PointerType>(RetTy)->getElementType()))) {
1542 writeOperand(Operand, false);
1544 writeOperand(Operand, true);
1547 for (unsigned op = 3, Eop = I.getNumOperands(); op < Eop; ++op) {
1550 writeParamOperand(I.getOperand(op), PAL.getParamAttributes(op-2));
1554 if (PAL.getFnAttributes() != Attribute::None)
1555 Out << ' ' << Attribute::getAsString(PAL.getFnAttributes());
1557 Out << "\n\t\t\tto ";
1558 writeOperand(II->getNormalDest(), true);
1560 writeOperand(II->getUnwindDest(), true);
1562 } else if (const AllocationInst *AI = dyn_cast<AllocationInst>(&I)) {
1564 printType(AI->getType()->getElementType());
1565 if (AI->isArrayAllocation()) {
1567 writeOperand(AI->getArraySize(), true);
1569 if (AI->getAlignment()) {
1570 Out << ", align " << AI->getAlignment();
1572 } else if (isa<CastInst>(I)) {
1575 writeOperand(Operand, true); // Work with broken code
1578 printType(I.getType());
1579 } else if (isa<VAArgInst>(I)) {
1582 writeOperand(Operand, true); // Work with broken code
1585 printType(I.getType());
1586 } else if (Operand) { // Print the normal way...
1588 // PrintAllTypes - Instructions who have operands of all the same type
1589 // omit the type from all but the first operand. If the instruction has
1590 // different type operands (for example br), then they are all printed.
1591 bool PrintAllTypes = false;
1592 const Type *TheType = Operand->getType();
1594 // Select, Store and ShuffleVector always print all types.
1595 if (isa<SelectInst>(I) || isa<StoreInst>(I) || isa<ShuffleVectorInst>(I)
1596 || isa<ReturnInst>(I)) {
1597 PrintAllTypes = true;
1599 for (unsigned i = 1, E = I.getNumOperands(); i != E; ++i) {
1600 Operand = I.getOperand(i);
1601 // note that Operand shouldn't be null, but the test helps make dump()
1602 // more tolerant of malformed IR
1603 if (Operand && Operand->getType() != TheType) {
1604 PrintAllTypes = true; // We have differing types! Print them all!
1610 if (!PrintAllTypes) {
1616 for (unsigned i = 0, E = I.getNumOperands(); i != E; ++i) {
1618 writeOperand(I.getOperand(i), PrintAllTypes);
1622 // Print post operand alignment for load/store
1623 if (isa<LoadInst>(I) && cast<LoadInst>(I).getAlignment()) {
1624 Out << ", align " << cast<LoadInst>(I).getAlignment();
1625 } else if (isa<StoreInst>(I) && cast<StoreInst>(I).getAlignment()) {
1626 Out << ", align " << cast<StoreInst>(I).getAlignment();
1629 printInfoComment(I);
1634 //===----------------------------------------------------------------------===//
1635 // External Interface declarations
1636 //===----------------------------------------------------------------------===//
1638 void Module::print(std::ostream &o, AssemblyAnnotationWriter *AAW) const {
1639 raw_os_ostream OS(o);
1642 void Module::print(raw_ostream &OS, AssemblyAnnotationWriter *AAW) const {
1643 SlotTracker SlotTable(this);
1644 AssemblyWriter W(OS, SlotTable, this, AAW);
1648 void Type::print(std::ostream &o) const {
1649 raw_os_ostream OS(o);
1653 void Type::print(raw_ostream &OS) const {
1655 OS << "<null Type>";
1658 TypePrinting(0, OS).print(this);
1661 void Value::print(raw_ostream &OS, AssemblyAnnotationWriter *AAW) const {
1663 OS << "printing a <null> value\n";
1667 if (const Instruction *I = dyn_cast<Instruction>(this)) {
1668 const Function *F = I->getParent() ? I->getParent()->getParent() : 0;
1669 SlotTracker SlotTable(F);
1670 AssemblyWriter W(OS, SlotTable, F ? F->getParent() : 0, AAW);
1672 } else if (const BasicBlock *BB = dyn_cast<BasicBlock>(this)) {
1673 SlotTracker SlotTable(BB->getParent());
1674 AssemblyWriter W(OS, SlotTable,
1675 BB->getParent() ? BB->getParent()->getParent() : 0, AAW);
1677 } else if (const GlobalValue *GV = dyn_cast<GlobalValue>(this)) {
1678 SlotTracker SlotTable(GV->getParent());
1679 AssemblyWriter W(OS, SlotTable, GV->getParent(), 0);
1681 } else if (const Constant *C = dyn_cast<Constant>(this)) {
1682 TypePrinting TypePrinter(0, OS);
1683 TypePrinter.print(C->getType());
1685 WriteConstantInt(OS, C, TypePrinter, 0);
1686 } else if (const Argument *A = dyn_cast<Argument>(this)) {
1687 WriteAsOperand(OS, this, true,
1688 A->getParent() ? A->getParent()->getParent() : 0);
1689 } else if (isa<InlineAsm>(this)) {
1690 WriteAsOperand(OS, this, true, 0);
1692 assert(0 && "Unknown value to print out!");
1696 void Value::print(std::ostream &O, AssemblyAnnotationWriter *AAW) const {
1697 raw_os_ostream OS(O);
1701 // Value::dump - allow easy printing of Values from the debugger.
1702 void Value::dump() const { print(errs()); errs() << '\n'; errs().flush(); }
1704 // Type::dump - allow easy printing of Types from the debugger.
1705 // This one uses type names from the given context module
1706 void Type::dump(const Module *Context) const {
1707 WriteTypeSymbolic(errs(), this, Context);
1712 // Type::dump - allow easy printing of Types from the debugger.
1713 void Type::dump() const { dump(0); }
1716 // Module::dump() - Allow printing of Modules from the debugger.
1717 void Module::dump() const { print(errs(), 0); errs().flush(); }