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 /// getLLVMName - Turn the specified string into an 'LLVM name', which is
129 /// surrounded with ""'s and escaped if it has special chars in it.
130 static std::string getLLVMName(const std::string &Name) {
131 assert(!Name.empty() && "Cannot get empty name!");
133 raw_string_ostream OS(result);
134 PrintLLVMName(OS, Name.c_str(), Name.length(), NoPrefix);
138 /// PrintLLVMName - Turn the specified name into an 'LLVM name', which is either
139 /// prefixed with % (if the string only contains simple characters) or is
140 /// surrounded with ""'s (if it has special chars in it). Print it out.
141 static void PrintLLVMName(raw_ostream &OS, const Value *V) {
142 PrintLLVMName(OS, V->getNameStart(), V->getNameLen(),
143 isa<GlobalValue>(V) ? GlobalPrefix : LocalPrefix);
148 //===----------------------------------------------------------------------===//
149 // SlotTracker Class: Enumerate slot numbers for unnamed values
150 //===----------------------------------------------------------------------===//
154 /// This class provides computation of slot numbers for LLVM Assembly writing.
158 /// ValueMap - A mapping of Values to slot numbers
159 typedef DenseMap<const Value*, unsigned> ValueMap;
162 /// TheModule - The module for which we are holding slot numbers
163 const Module* TheModule;
165 /// TheFunction - The function for which we are holding slot numbers
166 const Function* TheFunction;
167 bool FunctionProcessed;
169 /// mMap - The TypePlanes map for the module level data
173 /// fMap - The TypePlanes map for the function level data
178 /// Construct from a module
179 explicit SlotTracker(const Module *M);
180 /// Construct from a function, starting out in incorp state.
181 explicit SlotTracker(const Function *F);
183 /// Return the slot number of the specified value in it's type
184 /// plane. If something is not in the SlotTracker, return -1.
185 int getLocalSlot(const Value *V);
186 int getGlobalSlot(const GlobalValue *V);
188 /// If you'd like to deal with a function instead of just a module, use
189 /// this method to get its data into the SlotTracker.
190 void incorporateFunction(const Function *F) {
192 FunctionProcessed = false;
195 /// After calling incorporateFunction, use this method to remove the
196 /// most recently incorporated function from the SlotTracker. This
197 /// will reset the state of the machine back to just the module contents.
198 void purgeFunction();
200 // Implementation Details
202 /// This function does the actual initialization.
203 inline void initialize();
205 /// CreateModuleSlot - Insert the specified GlobalValue* into the slot table.
206 void CreateModuleSlot(const GlobalValue *V);
208 /// CreateFunctionSlot - Insert the specified Value* into the slot table.
209 void CreateFunctionSlot(const Value *V);
211 /// Add all of the module level global variables (and their initializers)
212 /// and function declarations, but not the contents of those functions.
213 void processModule();
215 /// Add all of the functions arguments, basic blocks, and instructions
216 void processFunction();
218 SlotTracker(const SlotTracker &); // DO NOT IMPLEMENT
219 void operator=(const SlotTracker &); // DO NOT IMPLEMENT
222 } // end anonymous namespace
225 static SlotTracker *createSlotTracker(const Value *V) {
226 if (const Argument *FA = dyn_cast<Argument>(V))
227 return new SlotTracker(FA->getParent());
229 if (const Instruction *I = dyn_cast<Instruction>(V))
230 return new SlotTracker(I->getParent()->getParent());
232 if (const BasicBlock *BB = dyn_cast<BasicBlock>(V))
233 return new SlotTracker(BB->getParent());
235 if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(V))
236 return new SlotTracker(GV->getParent());
238 if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(V))
239 return new SlotTracker(GA->getParent());
241 if (const Function *Func = dyn_cast<Function>(V))
242 return new SlotTracker(Func);
248 #define ST_DEBUG(X) cerr << X
253 // Module level constructor. Causes the contents of the Module (sans functions)
254 // to be added to the slot table.
255 SlotTracker::SlotTracker(const Module *M)
256 : TheModule(M), TheFunction(0), FunctionProcessed(false), mNext(0), fNext(0) {
259 // Function level constructor. Causes the contents of the Module and the one
260 // function provided to be added to the slot table.
261 SlotTracker::SlotTracker(const Function *F)
262 : TheModule(F ? F->getParent() : 0), TheFunction(F), FunctionProcessed(false),
266 inline void SlotTracker::initialize() {
269 TheModule = 0; ///< Prevent re-processing next time we're called.
272 if (TheFunction && !FunctionProcessed)
276 // Iterate through all the global variables, functions, and global
277 // variable initializers and create slots for them.
278 void SlotTracker::processModule() {
279 ST_DEBUG("begin processModule!\n");
281 // Add all of the unnamed global variables to the value table.
282 for (Module::const_global_iterator I = TheModule->global_begin(),
283 E = TheModule->global_end(); I != E; ++I)
287 // Add all the unnamed functions to the table.
288 for (Module::const_iterator I = TheModule->begin(), E = TheModule->end();
293 ST_DEBUG("end processModule!\n");
297 // Process the arguments, basic blocks, and instructions of a function.
298 void SlotTracker::processFunction() {
299 ST_DEBUG("begin processFunction!\n");
302 // Add all the function arguments with no names.
303 for(Function::const_arg_iterator AI = TheFunction->arg_begin(),
304 AE = TheFunction->arg_end(); AI != AE; ++AI)
306 CreateFunctionSlot(AI);
308 ST_DEBUG("Inserting Instructions:\n");
310 // Add all of the basic blocks and instructions with no names.
311 for (Function::const_iterator BB = TheFunction->begin(),
312 E = TheFunction->end(); BB != E; ++BB) {
314 CreateFunctionSlot(BB);
315 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I != E; ++I)
316 if (I->getType() != Type::VoidTy && !I->hasName())
317 CreateFunctionSlot(I);
320 FunctionProcessed = true;
322 ST_DEBUG("end processFunction!\n");
325 /// Clean up after incorporating a function. This is the only way to get out of
326 /// the function incorporation state that affects get*Slot/Create*Slot. Function
327 /// incorporation state is indicated by TheFunction != 0.
328 void SlotTracker::purgeFunction() {
329 ST_DEBUG("begin purgeFunction!\n");
330 fMap.clear(); // Simply discard the function level map
332 FunctionProcessed = false;
333 ST_DEBUG("end purgeFunction!\n");
336 /// getGlobalSlot - Get the slot number of a global value.
337 int SlotTracker::getGlobalSlot(const GlobalValue *V) {
338 // Check for uninitialized state and do lazy initialization.
341 // Find the type plane in the module map
342 ValueMap::iterator MI = mMap.find(V);
343 return MI == mMap.end() ? -1 : (int)MI->second;
347 /// getLocalSlot - Get the slot number for a value that is local to a function.
348 int SlotTracker::getLocalSlot(const Value *V) {
349 assert(!isa<Constant>(V) && "Can't get a constant or global slot with this!");
351 // Check for uninitialized state and do lazy initialization.
354 ValueMap::iterator FI = fMap.find(V);
355 return FI == fMap.end() ? -1 : (int)FI->second;
359 /// CreateModuleSlot - Insert the specified GlobalValue* into the slot table.
360 void SlotTracker::CreateModuleSlot(const GlobalValue *V) {
361 assert(V && "Can't insert a null Value into SlotTracker!");
362 assert(V->getType() != Type::VoidTy && "Doesn't need a slot!");
363 assert(!V->hasName() && "Doesn't need a slot!");
365 unsigned DestSlot = mNext++;
368 ST_DEBUG(" Inserting value [" << V->getType() << "] = " << V << " slot=" <<
370 // G = Global, F = Function, A = Alias, o = other
371 ST_DEBUG((isa<GlobalVariable>(V) ? 'G' :
372 (isa<Function>(V) ? 'F' :
373 (isa<GlobalAlias>(V) ? 'A' : 'o'))) << "]\n");
377 /// CreateSlot - Create a new slot for the specified value if it has no name.
378 void SlotTracker::CreateFunctionSlot(const Value *V) {
379 assert(V->getType() != Type::VoidTy && !V->hasName() &&
380 "Doesn't need a slot!");
382 unsigned DestSlot = fNext++;
385 // G = Global, F = Function, o = other
386 ST_DEBUG(" Inserting value [" << V->getType() << "] = " << V << " slot=" <<
387 DestSlot << " [o]\n");
392 //===----------------------------------------------------------------------===//
393 // AsmWriter Implementation
394 //===----------------------------------------------------------------------===//
396 static void WriteAsOperandInternal(raw_ostream &Out, const Value *V,
397 std::map<const Type *, std::string> &TypeTable,
398 SlotTracker *Machine);
402 /// fillTypeNameTable - If the module has a symbol table, take all global types
403 /// and stuff their names into the TypeNames map.
405 static void fillTypeNameTable(const Module *M,
406 std::map<const Type *, std::string> &TypeNames) {
408 const TypeSymbolTable &ST = M->getTypeSymbolTable();
409 TypeSymbolTable::const_iterator TI = ST.begin();
410 for (; TI != ST.end(); ++TI) {
411 // As a heuristic, don't insert pointer to primitive types, because
412 // they are used too often to have a single useful name.
414 const Type *Ty = cast<Type>(TI->second);
415 if (!isa<PointerType>(Ty) ||
416 !cast<PointerType>(Ty)->getElementType()->isPrimitiveType() ||
417 !cast<PointerType>(Ty)->getElementType()->isInteger() ||
418 isa<OpaqueType>(cast<PointerType>(Ty)->getElementType()))
419 TypeNames.insert(std::make_pair(Ty, '%' + getLLVMName(TI->first)));
425 static void calcTypeName(const Type *Ty,
426 std::vector<const Type *> &TypeStack,
427 std::map<const Type *, std::string> &TypeNames,
428 std::string &Result) {
429 if (Ty->isInteger() || (Ty->isPrimitiveType() && !isa<OpaqueType>(Ty))) {
430 Result += Ty->getDescription(); // Base case
434 // Check to see if the type is named.
435 std::map<const Type *, std::string>::iterator I = TypeNames.find(Ty);
436 if (I != TypeNames.end()) {
441 if (isa<OpaqueType>(Ty)) {
446 // Check to see if the Type is already on the stack...
447 unsigned Slot = 0, CurSize = TypeStack.size();
448 while (Slot < CurSize && TypeStack[Slot] != Ty) ++Slot; // Scan for type
450 // This is another base case for the recursion. In this case, we know
451 // that we have looped back to a type that we have previously visited.
452 // Generate the appropriate upreference to handle this.
453 if (Slot < CurSize) {
454 Result += "\\" + utostr(CurSize-Slot); // Here's the upreference
458 TypeStack.push_back(Ty); // Recursive case: Add us to the stack..
460 switch (Ty->getTypeID()) {
461 case Type::IntegerTyID: {
462 unsigned BitWidth = cast<IntegerType>(Ty)->getBitWidth();
463 Result += "i" + utostr(BitWidth);
466 case Type::FunctionTyID: {
467 const FunctionType *FTy = cast<FunctionType>(Ty);
468 calcTypeName(FTy->getReturnType(), TypeStack, TypeNames, Result);
470 for (FunctionType::param_iterator I = FTy->param_begin(),
471 E = FTy->param_end(); I != E; ++I) {
472 if (I != FTy->param_begin())
474 calcTypeName(*I, TypeStack, TypeNames, Result);
476 if (FTy->isVarArg()) {
477 if (FTy->getNumParams()) Result += ", ";
483 case Type::StructTyID: {
484 const StructType *STy = cast<StructType>(Ty);
488 for (StructType::element_iterator I = STy->element_begin(),
489 E = STy->element_end(); I != E; ++I) {
490 calcTypeName(*I, TypeStack, TypeNames, Result);
491 if (next(I) != STy->element_end())
500 case Type::PointerTyID: {
501 const PointerType *PTy = cast<PointerType>(Ty);
502 calcTypeName(PTy->getElementType(), TypeStack, TypeNames, Result);
503 if (unsigned AddressSpace = PTy->getAddressSpace())
504 Result += " addrspace(" + utostr(AddressSpace) + ")";
508 case Type::ArrayTyID: {
509 const ArrayType *ATy = cast<ArrayType>(Ty);
510 Result += "[" + utostr(ATy->getNumElements()) + " x ";
511 calcTypeName(ATy->getElementType(), TypeStack, TypeNames, Result);
515 case Type::VectorTyID: {
516 const VectorType *PTy = cast<VectorType>(Ty);
517 Result += "<" + utostr(PTy->getNumElements()) + " x ";
518 calcTypeName(PTy->getElementType(), TypeStack, TypeNames, Result);
522 case Type::OpaqueTyID:
526 Result += "<unrecognized-type>";
530 TypeStack.pop_back(); // Remove self from stack...
534 /// printTypeInt - The internal guts of printing out a type that has a
535 /// potentially named portion.
537 static void printTypeInt(raw_ostream &Out, const Type *Ty,
538 std::map<const Type *, std::string> &TypeNames) {
539 // Primitive types always print out their description, regardless of whether
540 // they have been named or not.
542 if (Ty->isInteger() || (Ty->isPrimitiveType() && !isa<OpaqueType>(Ty))) {
543 Out << Ty->getDescription();
547 // Check to see if the type is named.
548 std::map<const Type *, std::string>::iterator I = TypeNames.find(Ty);
549 if (I != TypeNames.end()) {
554 // Otherwise we have a type that has not been named but is a derived type.
555 // Carefully recurse the type hierarchy to print out any contained symbolic
558 std::vector<const Type *> TypeStack;
559 std::string TypeName;
560 calcTypeName(Ty, TypeStack, TypeNames, TypeName);
561 TypeNames.insert(std::make_pair(Ty, TypeName));//Cache type name for later use
566 /// WriteTypeSymbolic - This attempts to write the specified type as a symbolic
567 /// type, iff there is an entry in the modules symbol table for the specified
568 /// type or one of it's component types. This is slower than a simple x << Type
570 void llvm::WriteTypeSymbolic(std::ostream &Out, const Type *Ty,
572 raw_os_ostream RO(Out);
573 WriteTypeSymbolic(RO, Ty, M);
576 void llvm::WriteTypeSymbolic(raw_ostream &Out, const Type *Ty, const Module *M){
579 // If they want us to print out a type, but there is no context, we can't
580 // print it symbolically.
582 Out << Ty->getDescription();
584 std::map<const Type *, std::string> TypeNames;
585 fillTypeNameTable(M, TypeNames);
586 printTypeInt(Out, Ty, TypeNames);
590 static const char *getPredicateText(unsigned predicate) {
591 const char * pred = "unknown";
593 case FCmpInst::FCMP_FALSE: pred = "false"; break;
594 case FCmpInst::FCMP_OEQ: pred = "oeq"; break;
595 case FCmpInst::FCMP_OGT: pred = "ogt"; break;
596 case FCmpInst::FCMP_OGE: pred = "oge"; break;
597 case FCmpInst::FCMP_OLT: pred = "olt"; break;
598 case FCmpInst::FCMP_OLE: pred = "ole"; break;
599 case FCmpInst::FCMP_ONE: pred = "one"; break;
600 case FCmpInst::FCMP_ORD: pred = "ord"; break;
601 case FCmpInst::FCMP_UNO: pred = "uno"; break;
602 case FCmpInst::FCMP_UEQ: pred = "ueq"; break;
603 case FCmpInst::FCMP_UGT: pred = "ugt"; break;
604 case FCmpInst::FCMP_UGE: pred = "uge"; break;
605 case FCmpInst::FCMP_ULT: pred = "ult"; break;
606 case FCmpInst::FCMP_ULE: pred = "ule"; break;
607 case FCmpInst::FCMP_UNE: pred = "une"; break;
608 case FCmpInst::FCMP_TRUE: pred = "true"; break;
609 case ICmpInst::ICMP_EQ: pred = "eq"; break;
610 case ICmpInst::ICMP_NE: pred = "ne"; break;
611 case ICmpInst::ICMP_SGT: pred = "sgt"; break;
612 case ICmpInst::ICMP_SGE: pred = "sge"; break;
613 case ICmpInst::ICMP_SLT: pred = "slt"; break;
614 case ICmpInst::ICMP_SLE: pred = "sle"; break;
615 case ICmpInst::ICMP_UGT: pred = "ugt"; break;
616 case ICmpInst::ICMP_UGE: pred = "uge"; break;
617 case ICmpInst::ICMP_ULT: pred = "ult"; break;
618 case ICmpInst::ICMP_ULE: pred = "ule"; break;
623 static void WriteConstantInt(raw_ostream &Out, const Constant *CV,
624 std::map<const Type *, std::string> &TypeTable,
625 SlotTracker *Machine) {
626 if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV)) {
627 if (CI->getType() == Type::Int1Ty) {
628 Out << (CI->getZExtValue() ? "true" : "false");
631 Out << CI->getValue();
635 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CV)) {
636 if (&CFP->getValueAPF().getSemantics() == &APFloat::IEEEdouble ||
637 &CFP->getValueAPF().getSemantics() == &APFloat::IEEEsingle) {
638 // We would like to output the FP constant value in exponential notation,
639 // but we cannot do this if doing so will lose precision. Check here to
640 // make sure that we only output it in exponential format if we can parse
641 // the value back and get the same value.
644 bool isDouble = &CFP->getValueAPF().getSemantics()==&APFloat::IEEEdouble;
645 double Val = isDouble ? CFP->getValueAPF().convertToDouble() :
646 CFP->getValueAPF().convertToFloat();
647 std::string StrVal = ftostr(CFP->getValueAPF());
649 // Check to make sure that the stringized number is not some string like
650 // "Inf" or NaN, that atof will accept, but the lexer will not. Check
651 // that the string matches the "[-+]?[0-9]" regex.
653 if ((StrVal[0] >= '0' && StrVal[0] <= '9') ||
654 ((StrVal[0] == '-' || StrVal[0] == '+') &&
655 (StrVal[1] >= '0' && StrVal[1] <= '9'))) {
656 // Reparse stringized version!
657 if (atof(StrVal.c_str()) == Val) {
662 // Otherwise we could not reparse it to exactly the same value, so we must
663 // output the string in hexadecimal format! Note that loading and storing
664 // floating point types changes the bits of NaNs on some hosts, notably
665 // x86, so we must not use these types.
666 assert(sizeof(double) == sizeof(uint64_t) &&
667 "assuming that double is 64 bits!");
669 APFloat apf = CFP->getValueAPF();
670 // Floats are represented in ASCII IR as double, convert.
672 apf.convert(APFloat::IEEEdouble, APFloat::rmNearestTiesToEven,
675 utohex_buffer(uint64_t(apf.bitcastToAPInt().getZExtValue()),
680 // Some form of long double. These appear as a magic letter identifying
681 // the type, then a fixed number of hex digits.
683 if (&CFP->getValueAPF().getSemantics() == &APFloat::x87DoubleExtended)
685 else if (&CFP->getValueAPF().getSemantics() == &APFloat::IEEEquad)
687 else if (&CFP->getValueAPF().getSemantics() == &APFloat::PPCDoubleDouble)
690 assert(0 && "Unsupported floating point type");
691 // api needed to prevent premature destruction
692 APInt api = CFP->getValueAPF().bitcastToAPInt();
693 const uint64_t* p = api.getRawData();
696 int width = api.getBitWidth();
697 for (int j=0; j<width; j+=4, shiftcount-=4) {
698 unsigned int nibble = (word>>shiftcount) & 15;
700 Out << (unsigned char)(nibble + '0');
702 Out << (unsigned char)(nibble - 10 + 'A');
703 if (shiftcount == 0 && j+4 < width) {
707 shiftcount = width-j-4;
713 if (isa<ConstantAggregateZero>(CV)) {
714 Out << "zeroinitializer";
718 if (const ConstantArray *CA = dyn_cast<ConstantArray>(CV)) {
719 // As a special case, print the array as a string if it is an array of
720 // i8 with ConstantInt values.
722 const Type *ETy = CA->getType()->getElementType();
723 if (CA->isString()) {
725 PrintEscapedString(CA->getAsString(), Out);
727 } else { // Cannot output in string format...
729 if (CA->getNumOperands()) {
731 printTypeInt(Out, ETy, TypeTable);
733 WriteAsOperandInternal(Out, CA->getOperand(0),
735 for (unsigned i = 1, e = CA->getNumOperands(); i != e; ++i) {
737 printTypeInt(Out, ETy, TypeTable);
739 WriteAsOperandInternal(Out, CA->getOperand(i), TypeTable, Machine);
748 if (const ConstantStruct *CS = dyn_cast<ConstantStruct>(CV)) {
749 if (CS->getType()->isPacked())
752 unsigned N = CS->getNumOperands();
755 printTypeInt(Out, CS->getOperand(0)->getType(), TypeTable);
758 WriteAsOperandInternal(Out, CS->getOperand(0), TypeTable, Machine);
760 for (unsigned i = 1; i < N; i++) {
762 printTypeInt(Out, CS->getOperand(i)->getType(), TypeTable);
765 WriteAsOperandInternal(Out, CS->getOperand(i), TypeTable, Machine);
771 if (CS->getType()->isPacked())
776 if (const ConstantVector *CP = dyn_cast<ConstantVector>(CV)) {
777 const Type *ETy = CP->getType()->getElementType();
778 assert(CP->getNumOperands() > 0 &&
779 "Number of operands for a PackedConst must be > 0");
781 printTypeInt(Out, ETy, TypeTable);
783 WriteAsOperandInternal(Out, CP->getOperand(0), TypeTable, Machine);
784 for (unsigned i = 1, e = CP->getNumOperands(); i != e; ++i) {
786 printTypeInt(Out, ETy, TypeTable);
788 WriteAsOperandInternal(Out, CP->getOperand(i), TypeTable, Machine);
794 if (isa<ConstantPointerNull>(CV)) {
799 if (isa<UndefValue>(CV)) {
804 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV)) {
805 Out << CE->getOpcodeName();
807 Out << ' ' << getPredicateText(CE->getPredicate());
810 for (User::const_op_iterator OI=CE->op_begin(); OI != CE->op_end(); ++OI) {
811 printTypeInt(Out, (*OI)->getType(), TypeTable);
813 WriteAsOperandInternal(Out, *OI, TypeTable, Machine);
814 if (OI+1 != CE->op_end())
818 if (CE->hasIndices()) {
819 const SmallVector<unsigned, 4> &Indices = CE->getIndices();
820 for (unsigned i = 0, e = Indices.size(); i != e; ++i)
821 Out << ", " << Indices[i];
826 printTypeInt(Out, CE->getType(), TypeTable);
833 Out << "<placeholder or erroneous Constant>";
837 /// WriteAsOperand - Write the name of the specified value out to the specified
838 /// ostream. This can be useful when you just want to print int %reg126, not
839 /// the whole instruction that generated it.
841 static void WriteAsOperandInternal(raw_ostream &Out, const Value *V,
842 std::map<const Type*, std::string> &TypeTable,
843 SlotTracker *Machine) {
845 PrintLLVMName(Out, V);
849 const Constant *CV = dyn_cast<Constant>(V);
850 if (CV && !isa<GlobalValue>(CV)) {
851 WriteConstantInt(Out, CV, TypeTable, Machine);
855 if (const InlineAsm *IA = dyn_cast<InlineAsm>(V)) {
857 if (IA->hasSideEffects())
858 Out << "sideeffect ";
860 PrintEscapedString(IA->getAsmString(), Out);
862 PrintEscapedString(IA->getConstraintString(), Out);
870 if (const GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
871 Slot = Machine->getGlobalSlot(GV);
874 Slot = Machine->getLocalSlot(V);
877 Machine = createSlotTracker(V);
879 if (const GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
880 Slot = Machine->getGlobalSlot(GV);
883 Slot = Machine->getLocalSlot(V);
892 Out << Prefix << Slot;
897 /// WriteAsOperand - Write the name of the specified value out to the specified
898 /// ostream. This can be useful when you just want to print int %reg126, not
899 /// the whole instruction that generated it.
901 void llvm::WriteAsOperand(std::ostream &Out, const Value *V, bool PrintType,
902 const Module *Context) {
903 raw_os_ostream OS(Out);
904 WriteAsOperand(OS, V, PrintType, Context);
907 void llvm::WriteAsOperand(raw_ostream &Out, const Value *V, bool PrintType,
908 const Module *Context) {
909 std::map<const Type *, std::string> TypeNames;
910 if (Context == 0) Context = getModuleFromVal(V);
913 fillTypeNameTable(Context, TypeNames);
916 printTypeInt(Out, V->getType(), TypeNames);
920 WriteAsOperandInternal(Out, V, TypeNames, 0);
926 class AssemblyWriter {
928 SlotTracker &Machine;
929 const Module *TheModule;
930 std::map<const Type *, std::string> TypeNames;
931 AssemblyAnnotationWriter *AnnotationWriter;
933 inline AssemblyWriter(raw_ostream &o, SlotTracker &Mac, const Module *M,
934 AssemblyAnnotationWriter *AAW)
935 : Out(o), Machine(Mac), TheModule(M), AnnotationWriter(AAW) {
937 // If the module has a symbol table, take all global types and stuff their
938 // names into the TypeNames map.
940 fillTypeNameTable(M, TypeNames);
943 void write(const Module *M) { printModule(M); }
945 void write(const GlobalValue *G) {
946 if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(G))
948 else if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(G))
950 else if (const Function *F = dyn_cast<Function>(G))
953 assert(0 && "Unknown global");
956 void write(const BasicBlock *BB) { printBasicBlock(BB); }
957 void write(const Instruction *I) { printInstruction(*I); }
958 void write(const Type *Ty) { printType(Ty); }
960 void writeOperand(const Value *Op, bool PrintType);
961 void writeParamOperand(const Value *Operand, Attributes Attrs);
963 const Module* getModule() { return TheModule; }
966 void printModule(const Module *M);
967 void printTypeSymbolTable(const TypeSymbolTable &ST);
968 void printGlobal(const GlobalVariable *GV);
969 void printAlias(const GlobalAlias *GV);
970 void printFunction(const Function *F);
971 void printArgument(const Argument *FA, Attributes Attrs);
972 void printBasicBlock(const BasicBlock *BB);
973 void printInstruction(const Instruction &I);
975 // printType - Go to extreme measures to attempt to print out a short,
976 // symbolic version of a type name.
978 void printType(const Type *Ty) {
979 printTypeInt(Out, Ty, TypeNames);
982 // printTypeAtLeastOneLevel - Print out one level of the possibly complex type
983 // without considering any symbolic types that we may have equal to it.
985 void printTypeAtLeastOneLevel(const Type *Ty);
987 // printInfoComment - Print a little comment after the instruction indicating
988 // which slot it occupies.
989 void printInfoComment(const Value &V);
991 } // end of llvm namespace
993 /// printTypeAtLeastOneLevel - Print out one level of the possibly complex type
994 /// without considering any symbolic types that we may have equal to it.
996 void AssemblyWriter::printTypeAtLeastOneLevel(const Type *Ty) {
997 if (const IntegerType *ITy = dyn_cast<IntegerType>(Ty)) {
998 Out << "i" << utostr(ITy->getBitWidth());
1002 if (const FunctionType *FTy = dyn_cast<FunctionType>(Ty)) {
1003 printType(FTy->getReturnType());
1005 for (FunctionType::param_iterator I = FTy->param_begin(),
1006 E = FTy->param_end(); I != E; ++I) {
1007 if (I != FTy->param_begin())
1011 if (FTy->isVarArg()) {
1012 if (FTy->getNumParams()) Out << ", ";
1019 if (const StructType *STy = dyn_cast<StructType>(Ty)) {
1020 if (STy->isPacked())
1023 for (StructType::element_iterator I = STy->element_begin(),
1024 E = STy->element_end(); I != E; ++I) {
1025 if (I != STy->element_begin())
1030 if (STy->isPacked())
1035 if (const PointerType *PTy = dyn_cast<PointerType>(Ty)) {
1036 printType(PTy->getElementType());
1037 if (unsigned AddressSpace = PTy->getAddressSpace())
1038 Out << " addrspace(" << AddressSpace << ")";
1043 if (const ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
1044 Out << '[' << ATy->getNumElements() << " x ";
1045 printType(ATy->getElementType());
1050 if (const VectorType *PTy = dyn_cast<VectorType>(Ty)) {
1051 Out << '<' << PTy->getNumElements() << " x ";
1052 printType(PTy->getElementType());
1057 if (isa<OpaqueType>(Ty)) {
1062 if (!Ty->isPrimitiveType())
1063 Out << "<unknown derived type>";
1068 void AssemblyWriter::writeOperand(const Value *Operand, bool PrintType) {
1070 Out << "<null operand!>";
1073 printType(Operand->getType());
1076 WriteAsOperandInternal(Out, Operand, TypeNames, &Machine);
1080 void AssemblyWriter::writeParamOperand(const Value *Operand,
1083 Out << "<null operand!>";
1086 printType(Operand->getType());
1087 // Print parameter attributes list
1088 if (Attrs != Attribute::None)
1089 Out << ' ' << Attribute::getAsString(Attrs);
1091 // Print the operand
1092 WriteAsOperandInternal(Out, Operand, TypeNames, &Machine);
1096 void AssemblyWriter::printModule(const Module *M) {
1097 if (!M->getModuleIdentifier().empty() &&
1098 // Don't print the ID if it will start a new line (which would
1099 // require a comment char before it).
1100 M->getModuleIdentifier().find('\n') == std::string::npos)
1101 Out << "; ModuleID = '" << M->getModuleIdentifier() << "'\n";
1103 if (!M->getDataLayout().empty())
1104 Out << "target datalayout = \"" << M->getDataLayout() << "\"\n";
1105 if (!M->getTargetTriple().empty())
1106 Out << "target triple = \"" << M->getTargetTriple() << "\"\n";
1108 if (!M->getModuleInlineAsm().empty()) {
1109 // Split the string into lines, to make it easier to read the .ll file.
1110 std::string Asm = M->getModuleInlineAsm();
1112 size_t NewLine = Asm.find_first_of('\n', CurPos);
1113 while (NewLine != std::string::npos) {
1114 // We found a newline, print the portion of the asm string from the
1115 // last newline up to this newline.
1116 Out << "module asm \"";
1117 PrintEscapedString(std::string(Asm.begin()+CurPos, Asm.begin()+NewLine),
1121 NewLine = Asm.find_first_of('\n', CurPos);
1123 Out << "module asm \"";
1124 PrintEscapedString(std::string(Asm.begin()+CurPos, Asm.end()), Out);
1128 // Loop over the dependent libraries and emit them.
1129 Module::lib_iterator LI = M->lib_begin();
1130 Module::lib_iterator LE = M->lib_end();
1132 Out << "deplibs = [ ";
1134 Out << '"' << *LI << '"';
1142 // Loop over the symbol table, emitting all named constants.
1143 printTypeSymbolTable(M->getTypeSymbolTable());
1145 for (Module::const_global_iterator I = M->global_begin(), E = M->global_end();
1149 // Output all aliases.
1150 if (!M->alias_empty()) Out << "\n";
1151 for (Module::const_alias_iterator I = M->alias_begin(), E = M->alias_end();
1155 // Output all of the functions.
1156 for (Module::const_iterator I = M->begin(), E = M->end(); I != E; ++I)
1160 static void PrintLinkage(GlobalValue::LinkageTypes LT, raw_ostream &Out) {
1162 case GlobalValue::PrivateLinkage: Out << "private "; break;
1163 case GlobalValue::InternalLinkage: Out << "internal "; break;
1164 case GlobalValue::LinkOnceLinkage: Out << "linkonce "; break;
1165 case GlobalValue::WeakLinkage: Out << "weak "; break;
1166 case GlobalValue::CommonLinkage: Out << "common "; break;
1167 case GlobalValue::AppendingLinkage: Out << "appending "; break;
1168 case GlobalValue::DLLImportLinkage: Out << "dllimport "; break;
1169 case GlobalValue::DLLExportLinkage: Out << "dllexport "; break;
1170 case GlobalValue::ExternalWeakLinkage: Out << "extern_weak "; break;
1171 case GlobalValue::ExternalLinkage: break;
1172 case GlobalValue::GhostLinkage:
1173 Out << "GhostLinkage not allowed in AsmWriter!\n";
1179 static void PrintVisibility(GlobalValue::VisibilityTypes Vis,
1182 default: assert(0 && "Invalid visibility style!");
1183 case GlobalValue::DefaultVisibility: break;
1184 case GlobalValue::HiddenVisibility: Out << "hidden "; break;
1185 case GlobalValue::ProtectedVisibility: Out << "protected "; break;
1189 void AssemblyWriter::printGlobal(const GlobalVariable *GV) {
1190 if (GV->hasName()) {
1191 PrintLLVMName(Out, GV);
1195 if (!GV->hasInitializer() && GV->hasExternalLinkage())
1198 PrintLinkage(GV->getLinkage(), Out);
1199 PrintVisibility(GV->getVisibility(), Out);
1201 if (GV->isThreadLocal()) Out << "thread_local ";
1202 if (unsigned AddressSpace = GV->getType()->getAddressSpace())
1203 Out << "addrspace(" << AddressSpace << ") ";
1204 Out << (GV->isConstant() ? "constant " : "global ");
1205 printType(GV->getType()->getElementType());
1207 if (GV->hasInitializer()) {
1209 writeOperand(GV->getInitializer(), false);
1212 if (GV->hasSection())
1213 Out << ", section \"" << GV->getSection() << '"';
1214 if (GV->getAlignment())
1215 Out << ", align " << GV->getAlignment();
1217 printInfoComment(*GV);
1221 void AssemblyWriter::printAlias(const GlobalAlias *GA) {
1222 // Don't crash when dumping partially built GA
1224 Out << "<<nameless>> = ";
1226 PrintLLVMName(Out, GA);
1229 PrintVisibility(GA->getVisibility(), Out);
1233 PrintLinkage(GA->getLinkage(), Out);
1235 const Constant *Aliasee = GA->getAliasee();
1237 if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(Aliasee)) {
1238 printType(GV->getType());
1240 PrintLLVMName(Out, GV);
1241 } else if (const Function *F = dyn_cast<Function>(Aliasee)) {
1242 printType(F->getFunctionType());
1246 PrintLLVMName(Out, F);
1249 } else if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(Aliasee)) {
1250 printType(GA->getType());
1252 PrintLLVMName(Out, GA);
1254 const ConstantExpr *CE = 0;
1255 if ((CE = dyn_cast<ConstantExpr>(Aliasee)) &&
1256 (CE->getOpcode() == Instruction::BitCast)) {
1257 writeOperand(CE, false);
1259 assert(0 && "Unsupported aliasee");
1262 printInfoComment(*GA);
1266 void AssemblyWriter::printTypeSymbolTable(const TypeSymbolTable &ST) {
1268 for (TypeSymbolTable::const_iterator TI = ST.begin(), TE = ST.end();
1271 PrintLLVMName(Out, &TI->first[0], TI->first.size(), LocalPrefix);
1274 // Make sure we print out at least one level of the type structure, so
1275 // that we do not get %FILE = type %FILE
1277 printTypeAtLeastOneLevel(TI->second);
1282 /// printFunction - Print all aspects of a function.
1284 void AssemblyWriter::printFunction(const Function *F) {
1285 // Print out the return type and name.
1288 if (AnnotationWriter) AnnotationWriter->emitFunctionAnnot(F, Out);
1290 if (F->isDeclaration())
1295 PrintLinkage(F->getLinkage(), Out);
1296 PrintVisibility(F->getVisibility(), Out);
1298 // Print the calling convention.
1299 switch (F->getCallingConv()) {
1300 case CallingConv::C: break; // default
1301 case CallingConv::Fast: Out << "fastcc "; break;
1302 case CallingConv::Cold: Out << "coldcc "; break;
1303 case CallingConv::X86_StdCall: Out << "x86_stdcallcc "; break;
1304 case CallingConv::X86_FastCall: Out << "x86_fastcallcc "; break;
1305 default: Out << "cc" << F->getCallingConv() << " "; break;
1308 const FunctionType *FT = F->getFunctionType();
1309 const AttrListPtr &Attrs = F->getAttributes();
1310 Attributes RetAttrs = Attrs.getRetAttributes();
1311 if (RetAttrs != Attribute::None)
1312 Out << Attribute::getAsString(Attrs.getRetAttributes()) << ' ';
1313 printType(F->getReturnType());
1316 PrintLLVMName(Out, F);
1320 Machine.incorporateFunction(F);
1322 // Loop over the arguments, printing them...
1325 if (!F->isDeclaration()) {
1326 // If this isn't a declaration, print the argument names as well.
1327 for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
1329 // Insert commas as we go... the first arg doesn't get a comma
1330 if (I != F->arg_begin()) Out << ", ";
1331 printArgument(I, Attrs.getParamAttributes(Idx));
1335 // Otherwise, print the types from the function type.
1336 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
1337 // Insert commas as we go... the first arg doesn't get a comma
1341 printType(FT->getParamType(i));
1343 Attributes ArgAttrs = Attrs.getParamAttributes(i+1);
1344 if (ArgAttrs != Attribute::None)
1345 Out << ' ' << Attribute::getAsString(ArgAttrs);
1349 // Finish printing arguments...
1350 if (FT->isVarArg()) {
1351 if (FT->getNumParams()) Out << ", ";
1352 Out << "..."; // Output varargs portion of signature!
1355 Attributes FnAttrs = Attrs.getFnAttributes();
1356 if (FnAttrs != Attribute::None)
1357 Out << ' ' << Attribute::getAsString(Attrs.getFnAttributes());
1358 if (F->hasSection())
1359 Out << " section \"" << F->getSection() << '"';
1360 if (F->getAlignment())
1361 Out << " align " << F->getAlignment();
1363 Out << " gc \"" << F->getGC() << '"';
1364 if (F->isDeclaration()) {
1369 // Output all of its basic blocks... for the function
1370 for (Function::const_iterator I = F->begin(), E = F->end(); I != E; ++I)
1376 Machine.purgeFunction();
1379 /// printArgument - This member is called for every argument that is passed into
1380 /// the function. Simply print it out
1382 void AssemblyWriter::printArgument(const Argument *Arg,
1385 printType(Arg->getType());
1387 // Output parameter attributes list
1388 if (Attrs != Attribute::None)
1389 Out << ' ' << Attribute::getAsString(Attrs);
1391 // Output name, if available...
1392 if (Arg->hasName()) {
1394 PrintLLVMName(Out, Arg);
1398 /// printBasicBlock - This member is called for each basic block in a method.
1400 void AssemblyWriter::printBasicBlock(const BasicBlock *BB) {
1401 if (BB->hasName()) { // Print out the label if it exists...
1403 PrintLLVMName(Out, BB->getNameStart(), BB->getNameLen(), LabelPrefix);
1405 } else if (!BB->use_empty()) { // Don't print block # of no uses...
1406 Out << "\n; <label>:";
1407 int Slot = Machine.getLocalSlot(BB);
1414 if (BB->getParent() == 0)
1415 Out << "\t\t; Error: Block without parent!";
1416 else if (BB != &BB->getParent()->getEntryBlock()) { // Not the entry block?
1417 // Output predecessors for the block...
1419 pred_const_iterator PI = pred_begin(BB), PE = pred_end(BB);
1422 Out << " No predecessors!";
1425 writeOperand(*PI, false);
1426 for (++PI; PI != PE; ++PI) {
1428 writeOperand(*PI, false);
1435 if (AnnotationWriter) AnnotationWriter->emitBasicBlockStartAnnot(BB, Out);
1437 // Output all of the instructions in the basic block...
1438 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I != E; ++I)
1439 printInstruction(*I);
1441 if (AnnotationWriter) AnnotationWriter->emitBasicBlockEndAnnot(BB, Out);
1445 /// printInfoComment - Print a little comment after the instruction indicating
1446 /// which slot it occupies.
1448 void AssemblyWriter::printInfoComment(const Value &V) {
1449 if (V.getType() != Type::VoidTy) {
1451 printType(V.getType());
1454 if (!V.hasName() && !isa<Instruction>(V)) {
1456 if (const GlobalValue *GV = dyn_cast<GlobalValue>(&V))
1457 SlotNum = Machine.getGlobalSlot(GV);
1459 SlotNum = Machine.getLocalSlot(&V);
1463 Out << ':' << SlotNum; // Print out the def slot taken.
1465 Out << " [#uses=" << V.getNumUses() << ']'; // Output # uses
1469 // This member is called for each Instruction in a function..
1470 void AssemblyWriter::printInstruction(const Instruction &I) {
1471 if (AnnotationWriter) AnnotationWriter->emitInstructionAnnot(&I, Out);
1475 // Print out name if it exists...
1477 PrintLLVMName(Out, &I);
1479 } else if (I.getType() != Type::VoidTy) {
1480 // Print out the def slot taken.
1481 int SlotNum = Machine.getLocalSlot(&I);
1483 Out << "<badref> = ";
1485 Out << '%' << SlotNum << " = ";
1488 // If this is a volatile load or store, print out the volatile marker.
1489 if ((isa<LoadInst>(I) && cast<LoadInst>(I).isVolatile()) ||
1490 (isa<StoreInst>(I) && cast<StoreInst>(I).isVolatile())) {
1492 } else if (isa<CallInst>(I) && cast<CallInst>(I).isTailCall()) {
1493 // If this is a call, check if it's a tail call.
1497 // Print out the opcode...
1498 Out << I.getOpcodeName();
1500 // Print out the compare instruction predicates
1501 if (const CmpInst *CI = dyn_cast<CmpInst>(&I))
1502 Out << ' ' << getPredicateText(CI->getPredicate());
1504 // Print out the type of the operands...
1505 const Value *Operand = I.getNumOperands() ? I.getOperand(0) : 0;
1507 // Special case conditional branches to swizzle the condition out to the front
1508 if (isa<BranchInst>(I) && cast<BranchInst>(I).isConditional()) {
1509 BranchInst &BI(cast<BranchInst>(I));
1511 writeOperand(BI.getCondition(), true);
1513 writeOperand(BI.getSuccessor(0), true);
1515 writeOperand(BI.getSuccessor(1), true);
1517 } else if (isa<SwitchInst>(I)) {
1518 // Special case switch statement to get formatting nice and correct...
1520 writeOperand(Operand , true);
1522 writeOperand(I.getOperand(1), true);
1525 for (unsigned op = 2, Eop = I.getNumOperands(); op < Eop; op += 2) {
1527 writeOperand(I.getOperand(op ), true);
1529 writeOperand(I.getOperand(op+1), true);
1532 } else if (isa<PHINode>(I)) {
1534 printType(I.getType());
1537 for (unsigned op = 0, Eop = I.getNumOperands(); op < Eop; op += 2) {
1538 if (op) Out << ", ";
1540 writeOperand(I.getOperand(op ), false); Out << ", ";
1541 writeOperand(I.getOperand(op+1), false); Out << " ]";
1543 } else if (const ExtractValueInst *EVI = dyn_cast<ExtractValueInst>(&I)) {
1545 writeOperand(I.getOperand(0), true);
1546 for (const unsigned *i = EVI->idx_begin(), *e = EVI->idx_end(); i != e; ++i)
1548 } else if (const InsertValueInst *IVI = dyn_cast<InsertValueInst>(&I)) {
1550 writeOperand(I.getOperand(0), true); Out << ", ";
1551 writeOperand(I.getOperand(1), true);
1552 for (const unsigned *i = IVI->idx_begin(), *e = IVI->idx_end(); i != e; ++i)
1554 } else if (isa<ReturnInst>(I) && !Operand) {
1556 } else if (const CallInst *CI = dyn_cast<CallInst>(&I)) {
1557 // Print the calling convention being used.
1558 switch (CI->getCallingConv()) {
1559 case CallingConv::C: break; // default
1560 case CallingConv::Fast: Out << " fastcc"; break;
1561 case CallingConv::Cold: Out << " coldcc"; break;
1562 case CallingConv::X86_StdCall: Out << " x86_stdcallcc"; break;
1563 case CallingConv::X86_FastCall: Out << " x86_fastcallcc"; break;
1564 default: Out << " cc" << CI->getCallingConv(); break;
1567 const PointerType *PTy = cast<PointerType>(Operand->getType());
1568 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
1569 const Type *RetTy = FTy->getReturnType();
1570 const AttrListPtr &PAL = CI->getAttributes();
1572 if (PAL.getRetAttributes() != Attribute::None)
1573 Out << ' ' << Attribute::getAsString(PAL.getRetAttributes());
1575 // If possible, print out the short form of the call instruction. We can
1576 // only do this if the first argument is a pointer to a nonvararg function,
1577 // and if the return type is not a pointer to a function.
1580 if (!FTy->isVarArg() &&
1581 (!isa<PointerType>(RetTy) ||
1582 !isa<FunctionType>(cast<PointerType>(RetTy)->getElementType()))) {
1585 writeOperand(Operand, false);
1587 writeOperand(Operand, true);
1590 for (unsigned op = 1, Eop = I.getNumOperands(); op < Eop; ++op) {
1593 writeParamOperand(I.getOperand(op), PAL.getParamAttributes(op));
1596 if (PAL.getFnAttributes() != Attribute::None)
1597 Out << ' ' << Attribute::getAsString(PAL.getFnAttributes());
1598 } else if (const InvokeInst *II = dyn_cast<InvokeInst>(&I)) {
1599 const PointerType *PTy = cast<PointerType>(Operand->getType());
1600 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
1601 const Type *RetTy = FTy->getReturnType();
1602 const AttrListPtr &PAL = II->getAttributes();
1604 // Print the calling convention being used.
1605 switch (II->getCallingConv()) {
1606 case CallingConv::C: break; // default
1607 case CallingConv::Fast: Out << " fastcc"; break;
1608 case CallingConv::Cold: Out << " coldcc"; break;
1609 case CallingConv::X86_StdCall: Out << " x86_stdcallcc"; break;
1610 case CallingConv::X86_FastCall: Out << " x86_fastcallcc"; break;
1611 default: Out << " cc" << II->getCallingConv(); break;
1614 if (PAL.getRetAttributes() != Attribute::None)
1615 Out << ' ' << Attribute::getAsString(PAL.getRetAttributes());
1617 // If possible, print out the short form of the invoke instruction. We can
1618 // only do this if the first argument is a pointer to a nonvararg function,
1619 // and if the return type is not a pointer to a function.
1622 if (!FTy->isVarArg() &&
1623 (!isa<PointerType>(RetTy) ||
1624 !isa<FunctionType>(cast<PointerType>(RetTy)->getElementType()))) {
1627 writeOperand(Operand, false);
1629 writeOperand(Operand, true);
1632 for (unsigned op = 3, Eop = I.getNumOperands(); op < Eop; ++op) {
1635 writeParamOperand(I.getOperand(op), PAL.getParamAttributes(op-2));
1639 if (PAL.getFnAttributes() != Attribute::None)
1640 Out << ' ' << Attribute::getAsString(PAL.getFnAttributes());
1642 Out << "\n\t\t\tto ";
1643 writeOperand(II->getNormalDest(), true);
1645 writeOperand(II->getUnwindDest(), true);
1647 } else if (const AllocationInst *AI = dyn_cast<AllocationInst>(&I)) {
1649 printType(AI->getType()->getElementType());
1650 if (AI->isArrayAllocation()) {
1652 writeOperand(AI->getArraySize(), true);
1654 if (AI->getAlignment()) {
1655 Out << ", align " << AI->getAlignment();
1657 } else if (isa<CastInst>(I)) {
1660 writeOperand(Operand, true); // Work with broken code
1663 printType(I.getType());
1664 } else if (isa<VAArgInst>(I)) {
1667 writeOperand(Operand, true); // Work with broken code
1670 printType(I.getType());
1671 } else if (Operand) { // Print the normal way...
1673 // PrintAllTypes - Instructions who have operands of all the same type
1674 // omit the type from all but the first operand. If the instruction has
1675 // different type operands (for example br), then they are all printed.
1676 bool PrintAllTypes = false;
1677 const Type *TheType = Operand->getType();
1679 // Select, Store and ShuffleVector always print all types.
1680 if (isa<SelectInst>(I) || isa<StoreInst>(I) || isa<ShuffleVectorInst>(I)
1681 || isa<ReturnInst>(I)) {
1682 PrintAllTypes = true;
1684 for (unsigned i = 1, E = I.getNumOperands(); i != E; ++i) {
1685 Operand = I.getOperand(i);
1686 // note that Operand shouldn't be null, but the test helps make dump()
1687 // more tolerant of malformed IR
1688 if (Operand && Operand->getType() != TheType) {
1689 PrintAllTypes = true; // We have differing types! Print them all!
1695 if (!PrintAllTypes) {
1701 for (unsigned i = 0, E = I.getNumOperands(); i != E; ++i) {
1703 writeOperand(I.getOperand(i), PrintAllTypes);
1707 // Print post operand alignment for load/store
1708 if (isa<LoadInst>(I) && cast<LoadInst>(I).getAlignment()) {
1709 Out << ", align " << cast<LoadInst>(I).getAlignment();
1710 } else if (isa<StoreInst>(I) && cast<StoreInst>(I).getAlignment()) {
1711 Out << ", align " << cast<StoreInst>(I).getAlignment();
1714 printInfoComment(I);
1719 //===----------------------------------------------------------------------===//
1720 // External Interface declarations
1721 //===----------------------------------------------------------------------===//
1723 void Module::print(std::ostream &o, AssemblyAnnotationWriter *AAW) const {
1724 raw_os_ostream OS(o);
1727 void Module::print(raw_ostream &OS, AssemblyAnnotationWriter *AAW) const {
1728 SlotTracker SlotTable(this);
1729 AssemblyWriter W(OS, SlotTable, this, AAW);
1733 void Type::print(std::ostream &o) const {
1734 raw_os_ostream OS(o);
1738 void Type::print(raw_ostream &o) const {
1742 o << getDescription();
1745 void Value::print(raw_ostream &OS, AssemblyAnnotationWriter *AAW) const {
1747 OS << "printing a <null> value\n";
1751 if (const Instruction *I = dyn_cast<Instruction>(this)) {
1752 const Function *F = I->getParent() ? I->getParent()->getParent() : 0;
1753 SlotTracker SlotTable(F);
1754 AssemblyWriter W(OS, SlotTable, F ? F->getParent() : 0, AAW);
1756 } else if (const BasicBlock *BB = dyn_cast<BasicBlock>(this)) {
1757 SlotTracker SlotTable(BB->getParent());
1758 AssemblyWriter W(OS, SlotTable,
1759 BB->getParent() ? BB->getParent()->getParent() : 0, AAW);
1761 } else if (const GlobalValue *GV = dyn_cast<GlobalValue>(this)) {
1762 SlotTracker SlotTable(GV->getParent());
1763 AssemblyWriter W(OS, SlotTable, GV->getParent(), 0);
1765 } else if (const Constant *C = dyn_cast<Constant>(this)) {
1766 OS << C->getType()->getDescription() << ' ';
1767 std::map<const Type *, std::string> TypeTable;
1768 WriteConstantInt(OS, C, TypeTable, 0);
1769 } else if (const Argument *A = dyn_cast<Argument>(this)) {
1770 WriteAsOperand(OS, this, true,
1771 A->getParent() ? A->getParent()->getParent() : 0);
1772 } else if (isa<InlineAsm>(this)) {
1773 WriteAsOperand(OS, this, true, 0);
1775 assert(0 && "Unknown value to print out!");
1779 void Value::print(std::ostream &O, AssemblyAnnotationWriter *AAW) const {
1780 raw_os_ostream OS(O);
1784 // Value::dump - allow easy printing of Values from the debugger.
1785 void Value::dump() const { print(errs()); errs() << '\n'; errs().flush(); }
1787 // Type::dump - allow easy printing of Types from the debugger.
1788 void Type::dump() const { print(errs()); errs() << '\n'; errs().flush(); }
1790 // Type::dump - allow easy printing of Types from the debugger.
1791 // This one uses type names from the given context module
1792 void Type::dump(const Module *Context) const {
1793 WriteTypeSymbolic(errs(), this, Context);
1798 // Module::dump() - Allow printing of Modules from the debugger.
1799 void Module::dump() const { print(errs(), 0); errs().flush(); }