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/MDNode.h"
27 #include "llvm/Module.h"
28 #include "llvm/ValueSymbolTable.h"
29 #include "llvm/TypeSymbolTable.h"
30 #include "llvm/ADT/DenseSet.h"
31 #include "llvm/ADT/StringExtras.h"
32 #include "llvm/ADT/STLExtras.h"
33 #include "llvm/Support/CFG.h"
34 #include "llvm/Support/MathExtras.h"
35 #include "llvm/Support/raw_ostream.h"
40 // Make virtual table appear in this compilation unit.
41 AssemblyAnnotationWriter::~AssemblyAnnotationWriter() {}
43 //===----------------------------------------------------------------------===//
45 //===----------------------------------------------------------------------===//
47 static const Module *getModuleFromVal(const Value *V) {
48 if (const Argument *MA = dyn_cast<Argument>(V))
49 return MA->getParent() ? MA->getParent()->getParent() : 0;
51 if (const BasicBlock *BB = dyn_cast<BasicBlock>(V))
52 return BB->getParent() ? BB->getParent()->getParent() : 0;
54 if (const Instruction *I = dyn_cast<Instruction>(V)) {
55 const Function *M = I->getParent() ? I->getParent()->getParent() : 0;
56 return M ? M->getParent() : 0;
59 if (const GlobalValue *GV = dyn_cast<GlobalValue>(V))
60 return GV->getParent();
64 // PrintEscapedString - Print each character of the specified string, escaping
65 // it if it is not printable or if it is an escape char.
66 static void PrintEscapedString(const char *Str, unsigned Length,
68 for (unsigned i = 0; i != Length; ++i) {
69 unsigned char C = Str[i];
70 if (isprint(C) && C != '\\' && C != '"')
73 Out << '\\' << hexdigit(C >> 4) << hexdigit(C & 0x0F);
77 // PrintEscapedString - Print each character of the specified string, escaping
78 // it if it is not printable or if it is an escape char.
79 static void PrintEscapedString(const std::string &Str, raw_ostream &Out) {
80 PrintEscapedString(Str.c_str(), Str.size(), Out);
90 /// PrintLLVMName - Turn the specified name into an 'LLVM name', which is either
91 /// prefixed with % (if the string only contains simple characters) or is
92 /// surrounded with ""'s (if it has special chars in it). Print it out.
93 static void PrintLLVMName(raw_ostream &OS, const char *NameStr,
94 unsigned NameLen, PrefixType Prefix) {
95 assert(NameStr && "Cannot get empty name!");
97 default: assert(0 && "Bad prefix!");
99 case GlobalPrefix: OS << '@'; break;
100 case LabelPrefix: break;
101 case LocalPrefix: OS << '%'; break;
104 // Scan the name to see if it needs quotes first.
105 bool NeedsQuotes = isdigit(NameStr[0]);
107 for (unsigned i = 0; i != NameLen; ++i) {
109 if (!isalnum(C) && C != '-' && C != '.' && C != '_') {
116 // If we didn't need any quotes, just write out the name in one blast.
118 OS.write(NameStr, NameLen);
122 // Okay, we need quotes. Output the quotes and escape any scary characters as
125 PrintEscapedString(NameStr, NameLen, OS);
129 /// PrintLLVMName - Turn the specified name into an 'LLVM name', which is either
130 /// prefixed with % (if the string only contains simple characters) or is
131 /// surrounded with ""'s (if it has special chars in it). Print it out.
132 static void PrintLLVMName(raw_ostream &OS, const Value *V) {
133 PrintLLVMName(OS, V->getNameStart(), V->getNameLen(),
134 isa<GlobalValue>(V) ? GlobalPrefix : LocalPrefix);
137 //===----------------------------------------------------------------------===//
138 // TypePrinting Class: Type printing machinery
139 //===----------------------------------------------------------------------===//
141 static DenseMap<const Type *, std::string> &getTypeNamesMap(void *M) {
142 return *static_cast<DenseMap<const Type *, std::string>*>(M);
145 void TypePrinting::clear() {
146 getTypeNamesMap(TypeNames).clear();
149 bool TypePrinting::hasTypeName(const Type *Ty) const {
150 return getTypeNamesMap(TypeNames).count(Ty);
153 void TypePrinting::addTypeName(const Type *Ty, const std::string &N) {
154 getTypeNamesMap(TypeNames).insert(std::make_pair(Ty, N));
158 TypePrinting::TypePrinting() {
159 TypeNames = new DenseMap<const Type *, std::string>();
162 TypePrinting::~TypePrinting() {
163 delete &getTypeNamesMap(TypeNames);
166 /// CalcTypeName - Write the specified type to the specified raw_ostream, making
167 /// use of type names or up references to shorten the type name where possible.
168 void TypePrinting::CalcTypeName(const Type *Ty,
169 SmallVectorImpl<const Type *> &TypeStack,
170 raw_ostream &OS, bool IgnoreTopLevelName) {
171 // Check to see if the type is named.
172 if (!IgnoreTopLevelName) {
173 DenseMap<const Type *, std::string> &TM = getTypeNamesMap(TypeNames);
174 DenseMap<const Type *, std::string>::iterator I = TM.find(Ty);
181 // Check to see if the Type is already on the stack...
182 unsigned Slot = 0, CurSize = TypeStack.size();
183 while (Slot < CurSize && TypeStack[Slot] != Ty) ++Slot; // Scan for type
185 // This is another base case for the recursion. In this case, we know
186 // that we have looped back to a type that we have previously visited.
187 // Generate the appropriate upreference to handle this.
188 if (Slot < CurSize) {
189 OS << '\\' << unsigned(CurSize-Slot); // Here's the upreference
193 TypeStack.push_back(Ty); // Recursive case: Add us to the stack..
195 switch (Ty->getTypeID()) {
196 case Type::VoidTyID: OS << "void"; break;
197 case Type::FloatTyID: OS << "float"; break;
198 case Type::DoubleTyID: OS << "double"; break;
199 case Type::X86_FP80TyID: OS << "x86_fp80"; break;
200 case Type::FP128TyID: OS << "fp128"; break;
201 case Type::PPC_FP128TyID: OS << "ppc_fp128"; break;
202 case Type::LabelTyID: OS << "label"; break;
203 case Type::MetadataTyID: OS << "metadata"; break;
204 case Type::IntegerTyID:
205 OS << 'i' << cast<IntegerType>(Ty)->getBitWidth();
208 case Type::FunctionTyID: {
209 const FunctionType *FTy = cast<FunctionType>(Ty);
210 CalcTypeName(FTy->getReturnType(), TypeStack, OS);
212 for (FunctionType::param_iterator I = FTy->param_begin(),
213 E = FTy->param_end(); I != E; ++I) {
214 if (I != FTy->param_begin())
216 CalcTypeName(*I, TypeStack, OS);
218 if (FTy->isVarArg()) {
219 if (FTy->getNumParams()) OS << ", ";
225 case Type::StructTyID: {
226 const StructType *STy = cast<StructType>(Ty);
230 for (StructType::element_iterator I = STy->element_begin(),
231 E = STy->element_end(); I != E; ++I) {
232 CalcTypeName(*I, TypeStack, OS);
233 if (next(I) != STy->element_end())
242 case Type::PointerTyID: {
243 const PointerType *PTy = cast<PointerType>(Ty);
244 CalcTypeName(PTy->getElementType(), TypeStack, OS);
245 if (unsigned AddressSpace = PTy->getAddressSpace())
246 OS << " addrspace(" << AddressSpace << ')';
250 case Type::ArrayTyID: {
251 const ArrayType *ATy = cast<ArrayType>(Ty);
252 OS << '[' << ATy->getNumElements() << " x ";
253 CalcTypeName(ATy->getElementType(), TypeStack, OS);
257 case Type::VectorTyID: {
258 const VectorType *PTy = cast<VectorType>(Ty);
259 OS << "<" << PTy->getNumElements() << " x ";
260 CalcTypeName(PTy->getElementType(), TypeStack, OS);
264 case Type::OpaqueTyID:
268 OS << "<unrecognized-type>";
272 TypeStack.pop_back(); // Remove self from stack.
275 /// printTypeInt - The internal guts of printing out a type that has a
276 /// potentially named portion.
278 void TypePrinting::print(const Type *Ty, raw_ostream &OS,
279 bool IgnoreTopLevelName) {
280 // Check to see if the type is named.
281 DenseMap<const Type*, std::string> &TM = getTypeNamesMap(TypeNames);
282 if (!IgnoreTopLevelName) {
283 DenseMap<const Type*, std::string>::iterator I = TM.find(Ty);
290 // Otherwise we have a type that has not been named but is a derived type.
291 // Carefully recurse the type hierarchy to print out any contained symbolic
293 SmallVector<const Type *, 16> TypeStack;
294 std::string TypeName;
296 raw_string_ostream TypeOS(TypeName);
297 CalcTypeName(Ty, TypeStack, TypeOS, IgnoreTopLevelName);
300 // Cache type name for later use.
301 if (!IgnoreTopLevelName)
302 TM.insert(std::make_pair(Ty, TypeOS.str()));
307 // To avoid walking constant expressions multiple times and other IR
308 // objects, we keep several helper maps.
309 DenseSet<const Value*> VisitedConstants;
310 DenseSet<const Type*> VisitedTypes;
313 std::vector<const Type*> &NumberedTypes;
315 TypeFinder(TypePrinting &tp, std::vector<const Type*> &numberedTypes)
316 : TP(tp), NumberedTypes(numberedTypes) {}
318 void Run(const Module &M) {
319 // Get types from the type symbol table. This gets opaque types referened
320 // only through derived named types.
321 const TypeSymbolTable &ST = M.getTypeSymbolTable();
322 for (TypeSymbolTable::const_iterator TI = ST.begin(), E = ST.end();
324 IncorporateType(TI->second);
326 // Get types from global variables.
327 for (Module::const_global_iterator I = M.global_begin(),
328 E = M.global_end(); I != E; ++I) {
329 IncorporateType(I->getType());
330 if (I->hasInitializer())
331 IncorporateValue(I->getInitializer());
334 // Get types from aliases.
335 for (Module::const_alias_iterator I = M.alias_begin(),
336 E = M.alias_end(); I != E; ++I) {
337 IncorporateType(I->getType());
338 IncorporateValue(I->getAliasee());
341 // Get types from functions.
342 for (Module::const_iterator FI = M.begin(), E = M.end(); FI != E; ++FI) {
343 IncorporateType(FI->getType());
345 for (Function::const_iterator BB = FI->begin(), E = FI->end();
347 for (BasicBlock::const_iterator II = BB->begin(),
348 E = BB->end(); II != E; ++II) {
349 const Instruction &I = *II;
350 // Incorporate the type of the instruction and all its operands.
351 IncorporateType(I.getType());
352 for (User::const_op_iterator OI = I.op_begin(), OE = I.op_end();
354 IncorporateValue(*OI);
360 void IncorporateType(const Type *Ty) {
361 // Check to see if we're already visited this type.
362 if (!VisitedTypes.insert(Ty).second)
365 // If this is a structure or opaque type, add a name for the type.
366 if (((isa<StructType>(Ty) && cast<StructType>(Ty)->getNumElements())
367 || isa<OpaqueType>(Ty)) && !TP.hasTypeName(Ty)) {
368 TP.addTypeName(Ty, "%"+utostr(unsigned(NumberedTypes.size())));
369 NumberedTypes.push_back(Ty);
372 // Recursively walk all contained types.
373 for (Type::subtype_iterator I = Ty->subtype_begin(),
374 E = Ty->subtype_end(); I != E; ++I)
378 /// IncorporateValue - This method is used to walk operand lists finding
379 /// types hiding in constant expressions and other operands that won't be
380 /// walked in other ways. GlobalValues, basic blocks, instructions, and
381 /// inst operands are all explicitly enumerated.
382 void IncorporateValue(const Value *V) {
383 if (V == 0 || !isa<Constant>(V) || isa<GlobalValue>(V)) return;
386 if (!VisitedConstants.insert(V).second)
390 IncorporateType(V->getType());
392 // Look in operands for types.
393 const Constant *C = cast<Constant>(V);
394 for (Constant::const_op_iterator I = C->op_begin(),
395 E = C->op_end(); I != E;++I)
396 IncorporateValue(*I);
399 } // end anonymous namespace
402 /// AddModuleTypesToPrinter - Add all of the symbolic type names for types in
403 /// the specified module to the TypePrinter and all numbered types to it and the
404 /// NumberedTypes table.
405 static void AddModuleTypesToPrinter(TypePrinting &TP,
406 std::vector<const Type*> &NumberedTypes,
410 // If the module has a symbol table, take all global types and stuff their
411 // names into the TypeNames map.
412 const TypeSymbolTable &ST = M->getTypeSymbolTable();
413 for (TypeSymbolTable::const_iterator TI = ST.begin(), E = ST.end();
415 const Type *Ty = cast<Type>(TI->second);
417 // As a heuristic, don't insert pointer to primitive types, because
418 // they are used too often to have a single useful name.
419 if (const PointerType *PTy = dyn_cast<PointerType>(Ty)) {
420 const Type *PETy = PTy->getElementType();
421 if ((PETy->isPrimitiveType() || PETy->isInteger()) &&
422 !isa<OpaqueType>(PETy))
426 // Likewise don't insert primitives either.
427 if (Ty->isInteger() || Ty->isPrimitiveType())
430 // Get the name as a string and insert it into TypeNames.
432 raw_string_ostream NameOS(NameStr);
433 PrintLLVMName(NameOS, TI->first.c_str(), TI->first.length(), LocalPrefix);
434 TP.addTypeName(Ty, NameOS.str());
437 // Walk the entire module to find references to unnamed structure and opaque
438 // types. This is required for correctness by opaque types (because multiple
439 // uses of an unnamed opaque type needs to be referred to by the same ID) and
440 // it shrinks complex recursive structure types substantially in some cases.
441 TypeFinder(TP, NumberedTypes).Run(*M);
445 /// WriteTypeSymbolic - This attempts to write the specified type as a symbolic
446 /// type, iff there is an entry in the modules symbol table for the specified
447 /// type or one of it's component types.
449 void llvm::WriteTypeSymbolic(raw_ostream &OS, const Type *Ty, const Module *M) {
450 TypePrinting Printer;
451 std::vector<const Type*> NumberedTypes;
452 AddModuleTypesToPrinter(Printer, NumberedTypes, M);
453 Printer.print(Ty, OS);
456 //===----------------------------------------------------------------------===//
457 // SlotTracker Class: Enumerate slot numbers for unnamed values
458 //===----------------------------------------------------------------------===//
462 /// This class provides computation of slot numbers for LLVM Assembly writing.
466 /// ValueMap - A mapping of Values to slot numbers
467 typedef DenseMap<const Value*, unsigned> ValueMap;
470 /// TheModule - The module for which we are holding slot numbers
471 const Module* TheModule;
473 /// TheFunction - The function for which we are holding slot numbers
474 const Function* TheFunction;
475 bool FunctionProcessed;
477 /// mMap - The TypePlanes map for the module level data
481 /// fMap - The TypePlanes map for the function level data
486 /// Construct from a module
487 explicit SlotTracker(const Module *M);
488 /// Construct from a function, starting out in incorp state.
489 explicit SlotTracker(const Function *F);
491 /// Return the slot number of the specified value in it's type
492 /// plane. If something is not in the SlotTracker, return -1.
493 int getLocalSlot(const Value *V);
494 int getGlobalSlot(const GlobalValue *V);
496 /// If you'd like to deal with a function instead of just a module, use
497 /// this method to get its data into the SlotTracker.
498 void incorporateFunction(const Function *F) {
500 FunctionProcessed = false;
503 /// After calling incorporateFunction, use this method to remove the
504 /// most recently incorporated function from the SlotTracker. This
505 /// will reset the state of the machine back to just the module contents.
506 void purgeFunction();
508 // Implementation Details
510 /// This function does the actual initialization.
511 inline void initialize();
513 /// CreateModuleSlot - Insert the specified GlobalValue* into the slot table.
514 void CreateModuleSlot(const GlobalValue *V);
516 /// CreateFunctionSlot - Insert the specified Value* into the slot table.
517 void CreateFunctionSlot(const Value *V);
519 /// Add all of the module level global variables (and their initializers)
520 /// and function declarations, but not the contents of those functions.
521 void processModule();
523 /// Add all of the functions arguments, basic blocks, and instructions
524 void processFunction();
526 SlotTracker(const SlotTracker &); // DO NOT IMPLEMENT
527 void operator=(const SlotTracker &); // DO NOT IMPLEMENT
530 } // end anonymous namespace
533 static SlotTracker *createSlotTracker(const Value *V) {
534 if (const Argument *FA = dyn_cast<Argument>(V))
535 return new SlotTracker(FA->getParent());
537 if (const Instruction *I = dyn_cast<Instruction>(V))
538 return new SlotTracker(I->getParent()->getParent());
540 if (const BasicBlock *BB = dyn_cast<BasicBlock>(V))
541 return new SlotTracker(BB->getParent());
543 if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(V))
544 return new SlotTracker(GV->getParent());
546 if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(V))
547 return new SlotTracker(GA->getParent());
549 if (const Function *Func = dyn_cast<Function>(V))
550 return new SlotTracker(Func);
556 #define ST_DEBUG(X) cerr << X
561 // Module level constructor. Causes the contents of the Module (sans functions)
562 // to be added to the slot table.
563 SlotTracker::SlotTracker(const Module *M)
564 : TheModule(M), TheFunction(0), FunctionProcessed(false), mNext(0), fNext(0) {
567 // Function level constructor. Causes the contents of the Module and the one
568 // function provided to be added to the slot table.
569 SlotTracker::SlotTracker(const Function *F)
570 : TheModule(F ? F->getParent() : 0), TheFunction(F), FunctionProcessed(false),
574 inline void SlotTracker::initialize() {
577 TheModule = 0; ///< Prevent re-processing next time we're called.
580 if (TheFunction && !FunctionProcessed)
584 // Iterate through all the global variables, functions, and global
585 // variable initializers and create slots for them.
586 void SlotTracker::processModule() {
587 ST_DEBUG("begin processModule!\n");
589 // Add all of the unnamed global variables to the value table.
590 for (Module::const_global_iterator I = TheModule->global_begin(),
591 E = TheModule->global_end(); I != E; ++I)
595 // Add all the unnamed functions to the table.
596 for (Module::const_iterator I = TheModule->begin(), E = TheModule->end();
601 ST_DEBUG("end processModule!\n");
605 // Process the arguments, basic blocks, and instructions of a function.
606 void SlotTracker::processFunction() {
607 ST_DEBUG("begin processFunction!\n");
610 // Add all the function arguments with no names.
611 for(Function::const_arg_iterator AI = TheFunction->arg_begin(),
612 AE = TheFunction->arg_end(); AI != AE; ++AI)
614 CreateFunctionSlot(AI);
616 ST_DEBUG("Inserting Instructions:\n");
618 // Add all of the basic blocks and instructions with no names.
619 for (Function::const_iterator BB = TheFunction->begin(),
620 E = TheFunction->end(); BB != E; ++BB) {
622 CreateFunctionSlot(BB);
623 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I != E; ++I)
624 if (I->getType() != Type::VoidTy && !I->hasName())
625 CreateFunctionSlot(I);
628 FunctionProcessed = true;
630 ST_DEBUG("end processFunction!\n");
633 /// Clean up after incorporating a function. This is the only way to get out of
634 /// the function incorporation state that affects get*Slot/Create*Slot. Function
635 /// incorporation state is indicated by TheFunction != 0.
636 void SlotTracker::purgeFunction() {
637 ST_DEBUG("begin purgeFunction!\n");
638 fMap.clear(); // Simply discard the function level map
640 FunctionProcessed = false;
641 ST_DEBUG("end purgeFunction!\n");
644 /// getGlobalSlot - Get the slot number of a global value.
645 int SlotTracker::getGlobalSlot(const GlobalValue *V) {
646 // Check for uninitialized state and do lazy initialization.
649 // Find the type plane in the module map
650 ValueMap::iterator MI = mMap.find(V);
651 return MI == mMap.end() ? -1 : (int)MI->second;
655 /// getLocalSlot - Get the slot number for a value that is local to a function.
656 int SlotTracker::getLocalSlot(const Value *V) {
657 assert(!isa<Constant>(V) && "Can't get a constant or global slot with this!");
659 // Check for uninitialized state and do lazy initialization.
662 ValueMap::iterator FI = fMap.find(V);
663 return FI == fMap.end() ? -1 : (int)FI->second;
667 /// CreateModuleSlot - Insert the specified GlobalValue* into the slot table.
668 void SlotTracker::CreateModuleSlot(const GlobalValue *V) {
669 assert(V && "Can't insert a null Value into SlotTracker!");
670 assert(V->getType() != Type::VoidTy && "Doesn't need a slot!");
671 assert(!V->hasName() && "Doesn't need a slot!");
673 unsigned DestSlot = mNext++;
676 ST_DEBUG(" Inserting value [" << V->getType() << "] = " << V << " slot=" <<
678 // G = Global, F = Function, A = Alias, o = other
679 ST_DEBUG((isa<GlobalVariable>(V) ? 'G' :
680 (isa<Function>(V) ? 'F' :
681 (isa<GlobalAlias>(V) ? 'A' : 'o'))) << "]\n");
685 /// CreateSlot - Create a new slot for the specified value if it has no name.
686 void SlotTracker::CreateFunctionSlot(const Value *V) {
687 assert(V->getType() != Type::VoidTy && !V->hasName() &&
688 "Doesn't need a slot!");
690 unsigned DestSlot = fNext++;
693 // G = Global, F = Function, o = other
694 ST_DEBUG(" Inserting value [" << V->getType() << "] = " << V << " slot=" <<
695 DestSlot << " [o]\n");
700 //===----------------------------------------------------------------------===//
701 // AsmWriter Implementation
702 //===----------------------------------------------------------------------===//
704 static void WriteAsOperandInternal(raw_ostream &Out, const Value *V,
705 TypePrinting &TypePrinter,
706 SlotTracker *Machine);
710 static const char *getPredicateText(unsigned predicate) {
711 const char * pred = "unknown";
713 case FCmpInst::FCMP_FALSE: pred = "false"; break;
714 case FCmpInst::FCMP_OEQ: pred = "oeq"; break;
715 case FCmpInst::FCMP_OGT: pred = "ogt"; break;
716 case FCmpInst::FCMP_OGE: pred = "oge"; break;
717 case FCmpInst::FCMP_OLT: pred = "olt"; break;
718 case FCmpInst::FCMP_OLE: pred = "ole"; break;
719 case FCmpInst::FCMP_ONE: pred = "one"; break;
720 case FCmpInst::FCMP_ORD: pred = "ord"; break;
721 case FCmpInst::FCMP_UNO: pred = "uno"; break;
722 case FCmpInst::FCMP_UEQ: pred = "ueq"; break;
723 case FCmpInst::FCMP_UGT: pred = "ugt"; break;
724 case FCmpInst::FCMP_UGE: pred = "uge"; break;
725 case FCmpInst::FCMP_ULT: pred = "ult"; break;
726 case FCmpInst::FCMP_ULE: pred = "ule"; break;
727 case FCmpInst::FCMP_UNE: pred = "une"; break;
728 case FCmpInst::FCMP_TRUE: pred = "true"; break;
729 case ICmpInst::ICMP_EQ: pred = "eq"; break;
730 case ICmpInst::ICMP_NE: pred = "ne"; break;
731 case ICmpInst::ICMP_SGT: pred = "sgt"; break;
732 case ICmpInst::ICMP_SGE: pred = "sge"; break;
733 case ICmpInst::ICMP_SLT: pred = "slt"; break;
734 case ICmpInst::ICMP_SLE: pred = "sle"; break;
735 case ICmpInst::ICMP_UGT: pred = "ugt"; break;
736 case ICmpInst::ICMP_UGE: pred = "uge"; break;
737 case ICmpInst::ICMP_ULT: pred = "ult"; break;
738 case ICmpInst::ICMP_ULE: pred = "ule"; break;
743 static void WriteConstantInt(raw_ostream &Out, const Constant *CV,
744 TypePrinting &TypePrinter, SlotTracker *Machine) {
745 if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV)) {
746 if (CI->getType() == Type::Int1Ty) {
747 Out << (CI->getZExtValue() ? "true" : "false");
750 Out << CI->getValue();
754 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CV)) {
755 if (&CFP->getValueAPF().getSemantics() == &APFloat::IEEEdouble ||
756 &CFP->getValueAPF().getSemantics() == &APFloat::IEEEsingle) {
757 // We would like to output the FP constant value in exponential notation,
758 // but we cannot do this if doing so will lose precision. Check here to
759 // make sure that we only output it in exponential format if we can parse
760 // the value back and get the same value.
763 bool isDouble = &CFP->getValueAPF().getSemantics()==&APFloat::IEEEdouble;
764 double Val = isDouble ? CFP->getValueAPF().convertToDouble() :
765 CFP->getValueAPF().convertToFloat();
766 std::string StrVal = ftostr(CFP->getValueAPF());
768 // Check to make sure that the stringized number is not some string like
769 // "Inf" or NaN, that atof will accept, but the lexer will not. Check
770 // that the string matches the "[-+]?[0-9]" regex.
772 if ((StrVal[0] >= '0' && StrVal[0] <= '9') ||
773 ((StrVal[0] == '-' || StrVal[0] == '+') &&
774 (StrVal[1] >= '0' && StrVal[1] <= '9'))) {
775 // Reparse stringized version!
776 if (atof(StrVal.c_str()) == Val) {
781 // Otherwise we could not reparse it to exactly the same value, so we must
782 // output the string in hexadecimal format! Note that loading and storing
783 // floating point types changes the bits of NaNs on some hosts, notably
784 // x86, so we must not use these types.
785 assert(sizeof(double) == sizeof(uint64_t) &&
786 "assuming that double is 64 bits!");
788 APFloat apf = CFP->getValueAPF();
789 // Floats are represented in ASCII IR as double, convert.
791 apf.convert(APFloat::IEEEdouble, APFloat::rmNearestTiesToEven,
794 utohex_buffer(uint64_t(apf.bitcastToAPInt().getZExtValue()),
799 // Some form of long double. These appear as a magic letter identifying
800 // the type, then a fixed number of hex digits.
802 if (&CFP->getValueAPF().getSemantics() == &APFloat::x87DoubleExtended) {
804 // api needed to prevent premature destruction
805 APInt api = CFP->getValueAPF().bitcastToAPInt();
806 const uint64_t* p = api.getRawData();
807 uint64_t word = p[1];
809 int width = api.getBitWidth();
810 for (int j=0; j<width; j+=4, shiftcount-=4) {
811 unsigned int nibble = (word>>shiftcount) & 15;
813 Out << (unsigned char)(nibble + '0');
815 Out << (unsigned char)(nibble - 10 + 'A');
816 if (shiftcount == 0 && j+4 < width) {
820 shiftcount = width-j-4;
824 } else if (&CFP->getValueAPF().getSemantics() == &APFloat::IEEEquad)
826 else if (&CFP->getValueAPF().getSemantics() == &APFloat::PPCDoubleDouble)
829 assert(0 && "Unsupported floating point type");
830 // api needed to prevent premature destruction
831 APInt api = CFP->getValueAPF().bitcastToAPInt();
832 const uint64_t* p = api.getRawData();
835 int width = api.getBitWidth();
836 for (int j=0; j<width; j+=4, shiftcount-=4) {
837 unsigned int nibble = (word>>shiftcount) & 15;
839 Out << (unsigned char)(nibble + '0');
841 Out << (unsigned char)(nibble - 10 + 'A');
842 if (shiftcount == 0 && j+4 < width) {
846 shiftcount = width-j-4;
852 if (isa<ConstantAggregateZero>(CV)) {
853 Out << "zeroinitializer";
857 if (const ConstantArray *CA = dyn_cast<ConstantArray>(CV)) {
858 // As a special case, print the array as a string if it is an array of
859 // i8 with ConstantInt values.
861 const Type *ETy = CA->getType()->getElementType();
862 if (CA->isString()) {
864 PrintEscapedString(CA->getAsString(), Out);
866 } else { // Cannot output in string format...
868 if (CA->getNumOperands()) {
869 TypePrinter.print(ETy, Out);
871 WriteAsOperandInternal(Out, CA->getOperand(0),
872 TypePrinter, Machine);
873 for (unsigned i = 1, e = CA->getNumOperands(); i != e; ++i) {
875 TypePrinter.print(ETy, Out);
877 WriteAsOperandInternal(Out, CA->getOperand(i), TypePrinter, Machine);
885 if (const ConstantStruct *CS = dyn_cast<ConstantStruct>(CV)) {
886 if (CS->getType()->isPacked())
889 unsigned N = CS->getNumOperands();
892 TypePrinter.print(CS->getOperand(0)->getType(), Out);
895 WriteAsOperandInternal(Out, CS->getOperand(0), TypePrinter, Machine);
897 for (unsigned i = 1; i < N; i++) {
899 TypePrinter.print(CS->getOperand(i)->getType(), Out);
902 WriteAsOperandInternal(Out, CS->getOperand(i), TypePrinter, Machine);
908 if (CS->getType()->isPacked())
913 if (const ConstantVector *CP = dyn_cast<ConstantVector>(CV)) {
914 const Type *ETy = CP->getType()->getElementType();
915 assert(CP->getNumOperands() > 0 &&
916 "Number of operands for a PackedConst must be > 0");
918 TypePrinter.print(ETy, Out);
920 WriteAsOperandInternal(Out, CP->getOperand(0), TypePrinter, Machine);
921 for (unsigned i = 1, e = CP->getNumOperands(); i != e; ++i) {
923 TypePrinter.print(ETy, Out);
925 WriteAsOperandInternal(Out, CP->getOperand(i), TypePrinter, Machine);
931 if (isa<ConstantPointerNull>(CV)) {
936 if (isa<UndefValue>(CV)) {
941 if (const MDString *S = dyn_cast<MDString>(CV)) {
943 PrintEscapedString(S->begin(), S->size(), Out);
948 if (const MDNode *N = dyn_cast<MDNode>(CV)) {
950 for (MDNode::const_elem_iterator I = N->elem_begin(), E = N->elem_end();
955 TypePrinter.print((*I)->getType(), Out);
957 WriteAsOperandInternal(Out, *I, TypePrinter, Machine);
967 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV)) {
968 Out << CE->getOpcodeName();
970 Out << ' ' << getPredicateText(CE->getPredicate());
973 for (User::const_op_iterator OI=CE->op_begin(); OI != CE->op_end(); ++OI) {
974 TypePrinter.print((*OI)->getType(), Out);
976 WriteAsOperandInternal(Out, *OI, TypePrinter, Machine);
977 if (OI+1 != CE->op_end())
981 if (CE->hasIndices()) {
982 const SmallVector<unsigned, 4> &Indices = CE->getIndices();
983 for (unsigned i = 0, e = Indices.size(); i != e; ++i)
984 Out << ", " << Indices[i];
989 TypePrinter.print(CE->getType(), Out);
996 Out << "<placeholder or erroneous Constant>";
1000 /// WriteAsOperand - Write the name of the specified value out to the specified
1001 /// ostream. This can be useful when you just want to print int %reg126, not
1002 /// the whole instruction that generated it.
1004 static void WriteAsOperandInternal(raw_ostream &Out, const Value *V,
1005 TypePrinting &TypePrinter,
1006 SlotTracker *Machine) {
1008 PrintLLVMName(Out, V);
1012 const Constant *CV = dyn_cast<Constant>(V);
1013 if (CV && !isa<GlobalValue>(CV)) {
1014 WriteConstantInt(Out, CV, TypePrinter, Machine);
1018 if (const InlineAsm *IA = dyn_cast<InlineAsm>(V)) {
1020 if (IA->hasSideEffects())
1021 Out << "sideeffect ";
1023 PrintEscapedString(IA->getAsmString(), Out);
1025 PrintEscapedString(IA->getConstraintString(), Out);
1033 if (const GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
1034 Slot = Machine->getGlobalSlot(GV);
1037 Slot = Machine->getLocalSlot(V);
1040 Machine = createSlotTracker(V);
1042 if (const GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
1043 Slot = Machine->getGlobalSlot(GV);
1046 Slot = Machine->getLocalSlot(V);
1055 Out << Prefix << Slot;
1060 /// WriteAsOperand - Write the name of the specified value out to the specified
1061 /// ostream. This can be useful when you just want to print int %reg126, not
1062 /// the whole instruction that generated it.
1064 void llvm::WriteAsOperand(std::ostream &Out, const Value *V, bool PrintType,
1065 const Module *Context) {
1066 raw_os_ostream OS(Out);
1067 WriteAsOperand(OS, V, PrintType, Context);
1070 void llvm::WriteAsOperand(raw_ostream &Out, const Value *V, bool PrintType,
1071 const Module *Context) {
1072 if (Context == 0) Context = getModuleFromVal(V);
1074 TypePrinting TypePrinter;
1075 std::vector<const Type*> NumberedTypes;
1076 AddModuleTypesToPrinter(TypePrinter, NumberedTypes, Context);
1078 TypePrinter.print(V->getType(), Out);
1082 WriteAsOperandInternal(Out, V, TypePrinter, 0);
1088 class AssemblyWriter {
1090 SlotTracker &Machine;
1091 const Module *TheModule;
1092 TypePrinting TypePrinter;
1093 AssemblyAnnotationWriter *AnnotationWriter;
1094 std::vector<const Type*> NumberedTypes;
1096 inline AssemblyWriter(raw_ostream &o, SlotTracker &Mac, const Module *M,
1097 AssemblyAnnotationWriter *AAW)
1098 : Out(o), Machine(Mac), TheModule(M), AnnotationWriter(AAW) {
1099 AddModuleTypesToPrinter(TypePrinter, NumberedTypes, M);
1102 void write(const Module *M) { printModule(M); }
1104 void write(const GlobalValue *G) {
1105 if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(G))
1107 else if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(G))
1109 else if (const Function *F = dyn_cast<Function>(G))
1112 assert(0 && "Unknown global");
1115 void write(const BasicBlock *BB) { printBasicBlock(BB); }
1116 void write(const Instruction *I) { printInstruction(*I); }
1118 void writeOperand(const Value *Op, bool PrintType);
1119 void writeParamOperand(const Value *Operand, Attributes Attrs);
1121 const Module* getModule() { return TheModule; }
1124 void printModule(const Module *M);
1125 void printTypeSymbolTable(const TypeSymbolTable &ST);
1126 void printGlobal(const GlobalVariable *GV);
1127 void printAlias(const GlobalAlias *GV);
1128 void printFunction(const Function *F);
1129 void printArgument(const Argument *FA, Attributes Attrs);
1130 void printBasicBlock(const BasicBlock *BB);
1131 void printInstruction(const Instruction &I);
1133 // printInfoComment - Print a little comment after the instruction indicating
1134 // which slot it occupies.
1135 void printInfoComment(const Value &V);
1137 } // end of anonymous namespace
1140 void AssemblyWriter::writeOperand(const Value *Operand, bool PrintType) {
1142 Out << "<null operand!>";
1145 TypePrinter.print(Operand->getType(), Out);
1148 WriteAsOperandInternal(Out, Operand, TypePrinter, &Machine);
1152 void AssemblyWriter::writeParamOperand(const Value *Operand,
1155 Out << "<null operand!>";
1158 TypePrinter.print(Operand->getType(), Out);
1159 // Print parameter attributes list
1160 if (Attrs != Attribute::None)
1161 Out << ' ' << Attribute::getAsString(Attrs);
1163 // Print the operand
1164 WriteAsOperandInternal(Out, Operand, TypePrinter, &Machine);
1168 void AssemblyWriter::printModule(const Module *M) {
1169 if (!M->getModuleIdentifier().empty() &&
1170 // Don't print the ID if it will start a new line (which would
1171 // require a comment char before it).
1172 M->getModuleIdentifier().find('\n') == std::string::npos)
1173 Out << "; ModuleID = '" << M->getModuleIdentifier() << "'\n";
1175 if (!M->getDataLayout().empty())
1176 Out << "target datalayout = \"" << M->getDataLayout() << "\"\n";
1177 if (!M->getTargetTriple().empty())
1178 Out << "target triple = \"" << M->getTargetTriple() << "\"\n";
1180 if (!M->getModuleInlineAsm().empty()) {
1181 // Split the string into lines, to make it easier to read the .ll file.
1182 std::string Asm = M->getModuleInlineAsm();
1184 size_t NewLine = Asm.find_first_of('\n', CurPos);
1185 while (NewLine != std::string::npos) {
1186 // We found a newline, print the portion of the asm string from the
1187 // last newline up to this newline.
1188 Out << "module asm \"";
1189 PrintEscapedString(std::string(Asm.begin()+CurPos, Asm.begin()+NewLine),
1193 NewLine = Asm.find_first_of('\n', CurPos);
1195 Out << "module asm \"";
1196 PrintEscapedString(std::string(Asm.begin()+CurPos, Asm.end()), Out);
1200 // Loop over the dependent libraries and emit them.
1201 Module::lib_iterator LI = M->lib_begin();
1202 Module::lib_iterator LE = M->lib_end();
1204 Out << "deplibs = [ ";
1206 Out << '"' << *LI << '"';
1214 // Loop over the symbol table, emitting all id'd types.
1215 printTypeSymbolTable(M->getTypeSymbolTable());
1217 for (Module::const_global_iterator I = M->global_begin(), E = M->global_end();
1221 // Output all aliases.
1222 if (!M->alias_empty()) Out << "\n";
1223 for (Module::const_alias_iterator I = M->alias_begin(), E = M->alias_end();
1227 // Output all of the functions.
1228 for (Module::const_iterator I = M->begin(), E = M->end(); I != E; ++I)
1232 static void PrintLinkage(GlobalValue::LinkageTypes LT, raw_ostream &Out) {
1234 case GlobalValue::PrivateLinkage: Out << "private "; break;
1235 case GlobalValue::InternalLinkage: Out << "internal "; break;
1236 case GlobalValue::AvailableExternallyLinkage:
1237 Out << "available_externally ";
1239 case GlobalValue::LinkOnceAnyLinkage: Out << "linkonce "; break;
1240 case GlobalValue::LinkOnceODRLinkage: Out << "linkonce_odr "; break;
1241 case GlobalValue::WeakAnyLinkage: Out << "weak "; break;
1242 case GlobalValue::WeakODRLinkage: Out << "weak_odr "; break;
1243 case GlobalValue::CommonLinkage: Out << "common "; break;
1244 case GlobalValue::AppendingLinkage: Out << "appending "; break;
1245 case GlobalValue::DLLImportLinkage: Out << "dllimport "; break;
1246 case GlobalValue::DLLExportLinkage: Out << "dllexport "; break;
1247 case GlobalValue::ExternalWeakLinkage: Out << "extern_weak "; break;
1248 case GlobalValue::ExternalLinkage: break;
1249 case GlobalValue::GhostLinkage:
1250 Out << "GhostLinkage not allowed in AsmWriter!\n";
1256 static void PrintVisibility(GlobalValue::VisibilityTypes Vis,
1259 default: assert(0 && "Invalid visibility style!");
1260 case GlobalValue::DefaultVisibility: break;
1261 case GlobalValue::HiddenVisibility: Out << "hidden "; break;
1262 case GlobalValue::ProtectedVisibility: Out << "protected "; break;
1266 void AssemblyWriter::printGlobal(const GlobalVariable *GV) {
1267 if (GV->hasName()) {
1268 PrintLLVMName(Out, GV);
1272 if (!GV->hasInitializer() && GV->hasExternalLinkage())
1275 PrintLinkage(GV->getLinkage(), Out);
1276 PrintVisibility(GV->getVisibility(), Out);
1278 if (GV->isThreadLocal()) Out << "thread_local ";
1279 if (unsigned AddressSpace = GV->getType()->getAddressSpace())
1280 Out << "addrspace(" << AddressSpace << ") ";
1281 Out << (GV->isConstant() ? "constant " : "global ");
1282 TypePrinter.print(GV->getType()->getElementType(), Out);
1284 if (GV->hasInitializer()) {
1286 writeOperand(GV->getInitializer(), false);
1289 if (GV->hasSection())
1290 Out << ", section \"" << GV->getSection() << '"';
1291 if (GV->getAlignment())
1292 Out << ", align " << GV->getAlignment();
1294 printInfoComment(*GV);
1298 void AssemblyWriter::printAlias(const GlobalAlias *GA) {
1299 // Don't crash when dumping partially built GA
1301 Out << "<<nameless>> = ";
1303 PrintLLVMName(Out, GA);
1306 PrintVisibility(GA->getVisibility(), Out);
1310 PrintLinkage(GA->getLinkage(), Out);
1312 const Constant *Aliasee = GA->getAliasee();
1314 if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(Aliasee)) {
1315 TypePrinter.print(GV->getType(), Out);
1317 PrintLLVMName(Out, GV);
1318 } else if (const Function *F = dyn_cast<Function>(Aliasee)) {
1319 TypePrinter.print(F->getFunctionType(), Out);
1322 WriteAsOperandInternal(Out, F, TypePrinter, &Machine);
1323 } else if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(Aliasee)) {
1324 TypePrinter.print(GA->getType(), Out);
1326 PrintLLVMName(Out, GA);
1328 const ConstantExpr *CE = cast<ConstantExpr>(Aliasee);
1329 // The only valid GEP is an all zero GEP.
1330 assert((CE->getOpcode() == Instruction::BitCast ||
1331 CE->getOpcode() == Instruction::GetElementPtr) &&
1332 "Unsupported aliasee");
1333 writeOperand(CE, false);
1336 printInfoComment(*GA);
1340 void AssemblyWriter::printTypeSymbolTable(const TypeSymbolTable &ST) {
1341 // Emit all numbered types.
1342 for (unsigned i = 0, e = NumberedTypes.size(); i != e; ++i) {
1345 // Make sure we print out at least one level of the type structure, so
1346 // that we do not get %2 = type %2
1347 TypePrinter.printAtLeastOneLevel(NumberedTypes[i], Out);
1348 Out << "\t\t; type %" << i << '\n';
1351 // Print the named types.
1352 for (TypeSymbolTable::const_iterator TI = ST.begin(), TE = ST.end();
1355 PrintLLVMName(Out, &TI->first[0], TI->first.size(), LocalPrefix);
1358 // Make sure we print out at least one level of the type structure, so
1359 // that we do not get %FILE = type %FILE
1360 TypePrinter.printAtLeastOneLevel(TI->second, Out);
1365 /// printFunction - Print all aspects of a function.
1367 void AssemblyWriter::printFunction(const Function *F) {
1368 // Print out the return type and name.
1371 if (AnnotationWriter) AnnotationWriter->emitFunctionAnnot(F, Out);
1373 if (F->isDeclaration())
1378 PrintLinkage(F->getLinkage(), Out);
1379 PrintVisibility(F->getVisibility(), Out);
1381 // Print the calling convention.
1382 switch (F->getCallingConv()) {
1383 case CallingConv::C: break; // default
1384 case CallingConv::Fast: Out << "fastcc "; break;
1385 case CallingConv::Cold: Out << "coldcc "; break;
1386 case CallingConv::X86_StdCall: Out << "x86_stdcallcc "; break;
1387 case CallingConv::X86_FastCall: Out << "x86_fastcallcc "; break;
1388 case CallingConv::ARM_APCS: Out << "arm_apcscc "; break;
1389 case CallingConv::ARM_AAPCS: Out << "arm_aapcscc "; break;
1390 case CallingConv::ARM_AAPCS_VFP:Out << "arm_aapcs_vfpcc "; break;
1391 default: Out << "cc" << F->getCallingConv() << " "; break;
1394 const FunctionType *FT = F->getFunctionType();
1395 const AttrListPtr &Attrs = F->getAttributes();
1396 Attributes RetAttrs = Attrs.getRetAttributes();
1397 if (RetAttrs != Attribute::None)
1398 Out << Attribute::getAsString(Attrs.getRetAttributes()) << ' ';
1399 TypePrinter.print(F->getReturnType(), Out);
1401 WriteAsOperandInternal(Out, F, TypePrinter, &Machine);
1403 Machine.incorporateFunction(F);
1405 // Loop over the arguments, printing them...
1408 if (!F->isDeclaration()) {
1409 // If this isn't a declaration, print the argument names as well.
1410 for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
1412 // Insert commas as we go... the first arg doesn't get a comma
1413 if (I != F->arg_begin()) Out << ", ";
1414 printArgument(I, Attrs.getParamAttributes(Idx));
1418 // Otherwise, print the types from the function type.
1419 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
1420 // Insert commas as we go... the first arg doesn't get a comma
1424 TypePrinter.print(FT->getParamType(i), Out);
1426 Attributes ArgAttrs = Attrs.getParamAttributes(i+1);
1427 if (ArgAttrs != Attribute::None)
1428 Out << ' ' << Attribute::getAsString(ArgAttrs);
1432 // Finish printing arguments...
1433 if (FT->isVarArg()) {
1434 if (FT->getNumParams()) Out << ", ";
1435 Out << "..."; // Output varargs portion of signature!
1438 Attributes FnAttrs = Attrs.getFnAttributes();
1439 if (FnAttrs != Attribute::None)
1440 Out << ' ' << Attribute::getAsString(Attrs.getFnAttributes());
1441 if (F->hasSection())
1442 Out << " section \"" << F->getSection() << '"';
1443 if (F->getAlignment())
1444 Out << " align " << F->getAlignment();
1446 Out << " gc \"" << F->getGC() << '"';
1447 if (F->isDeclaration()) {
1452 // Output all of its basic blocks... for the function
1453 for (Function::const_iterator I = F->begin(), E = F->end(); I != E; ++I)
1459 Machine.purgeFunction();
1462 /// printArgument - This member is called for every argument that is passed into
1463 /// the function. Simply print it out
1465 void AssemblyWriter::printArgument(const Argument *Arg,
1468 TypePrinter.print(Arg->getType(), Out);
1470 // Output parameter attributes list
1471 if (Attrs != Attribute::None)
1472 Out << ' ' << Attribute::getAsString(Attrs);
1474 // Output name, if available...
1475 if (Arg->hasName()) {
1477 PrintLLVMName(Out, Arg);
1481 /// printBasicBlock - This member is called for each basic block in a method.
1483 void AssemblyWriter::printBasicBlock(const BasicBlock *BB) {
1484 if (BB->hasName()) { // Print out the label if it exists...
1486 PrintLLVMName(Out, BB->getNameStart(), BB->getNameLen(), LabelPrefix);
1488 } else if (!BB->use_empty()) { // Don't print block # of no uses...
1489 Out << "\n; <label>:";
1490 int Slot = Machine.getLocalSlot(BB);
1497 if (BB->getParent() == 0)
1498 Out << "\t\t; Error: Block without parent!";
1499 else if (BB != &BB->getParent()->getEntryBlock()) { // Not the entry block?
1500 // Output predecessors for the block...
1502 pred_const_iterator PI = pred_begin(BB), PE = pred_end(BB);
1505 Out << " No predecessors!";
1508 writeOperand(*PI, false);
1509 for (++PI; PI != PE; ++PI) {
1511 writeOperand(*PI, false);
1518 if (AnnotationWriter) AnnotationWriter->emitBasicBlockStartAnnot(BB, Out);
1520 // Output all of the instructions in the basic block...
1521 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I != E; ++I)
1522 printInstruction(*I);
1524 if (AnnotationWriter) AnnotationWriter->emitBasicBlockEndAnnot(BB, Out);
1528 /// printInfoComment - Print a little comment after the instruction indicating
1529 /// which slot it occupies.
1531 void AssemblyWriter::printInfoComment(const Value &V) {
1532 if (V.getType() != Type::VoidTy) {
1534 TypePrinter.print(V.getType(), Out);
1537 if (!V.hasName() && !isa<Instruction>(V)) {
1539 if (const GlobalValue *GV = dyn_cast<GlobalValue>(&V))
1540 SlotNum = Machine.getGlobalSlot(GV);
1542 SlotNum = Machine.getLocalSlot(&V);
1546 Out << ':' << SlotNum; // Print out the def slot taken.
1548 Out << " [#uses=" << V.getNumUses() << ']'; // Output # uses
1552 // This member is called for each Instruction in a function..
1553 void AssemblyWriter::printInstruction(const Instruction &I) {
1554 if (AnnotationWriter) AnnotationWriter->emitInstructionAnnot(&I, Out);
1558 // Print out name if it exists...
1560 PrintLLVMName(Out, &I);
1562 } else if (I.getType() != Type::VoidTy) {
1563 // Print out the def slot taken.
1564 int SlotNum = Machine.getLocalSlot(&I);
1566 Out << "<badref> = ";
1568 Out << '%' << SlotNum << " = ";
1571 // If this is a volatile load or store, print out the volatile marker.
1572 if ((isa<LoadInst>(I) && cast<LoadInst>(I).isVolatile()) ||
1573 (isa<StoreInst>(I) && cast<StoreInst>(I).isVolatile())) {
1575 } else if (isa<CallInst>(I) && cast<CallInst>(I).isTailCall()) {
1576 // If this is a call, check if it's a tail call.
1580 // Print out the opcode...
1581 Out << I.getOpcodeName();
1583 // Print out the compare instruction predicates
1584 if (const CmpInst *CI = dyn_cast<CmpInst>(&I))
1585 Out << ' ' << getPredicateText(CI->getPredicate());
1587 // Print out the type of the operands...
1588 const Value *Operand = I.getNumOperands() ? I.getOperand(0) : 0;
1590 // Special case conditional branches to swizzle the condition out to the front
1591 if (isa<BranchInst>(I) && cast<BranchInst>(I).isConditional()) {
1592 BranchInst &BI(cast<BranchInst>(I));
1594 writeOperand(BI.getCondition(), true);
1596 writeOperand(BI.getSuccessor(0), true);
1598 writeOperand(BI.getSuccessor(1), true);
1600 } else if (isa<SwitchInst>(I)) {
1601 // Special case switch statement to get formatting nice and correct...
1603 writeOperand(Operand , true);
1605 writeOperand(I.getOperand(1), true);
1608 for (unsigned op = 2, Eop = I.getNumOperands(); op < Eop; op += 2) {
1610 writeOperand(I.getOperand(op ), true);
1612 writeOperand(I.getOperand(op+1), true);
1615 } else if (isa<PHINode>(I)) {
1617 TypePrinter.print(I.getType(), Out);
1620 for (unsigned op = 0, Eop = I.getNumOperands(); op < Eop; op += 2) {
1621 if (op) Out << ", ";
1623 writeOperand(I.getOperand(op ), false); Out << ", ";
1624 writeOperand(I.getOperand(op+1), false); Out << " ]";
1626 } else if (const ExtractValueInst *EVI = dyn_cast<ExtractValueInst>(&I)) {
1628 writeOperand(I.getOperand(0), true);
1629 for (const unsigned *i = EVI->idx_begin(), *e = EVI->idx_end(); i != e; ++i)
1631 } else if (const InsertValueInst *IVI = dyn_cast<InsertValueInst>(&I)) {
1633 writeOperand(I.getOperand(0), true); Out << ", ";
1634 writeOperand(I.getOperand(1), true);
1635 for (const unsigned *i = IVI->idx_begin(), *e = IVI->idx_end(); i != e; ++i)
1637 } else if (isa<ReturnInst>(I) && !Operand) {
1639 } else if (const CallInst *CI = dyn_cast<CallInst>(&I)) {
1640 // Print the calling convention being used.
1641 switch (CI->getCallingConv()) {
1642 case CallingConv::C: break; // default
1643 case CallingConv::Fast: Out << " fastcc"; break;
1644 case CallingConv::Cold: Out << " coldcc"; break;
1645 case CallingConv::X86_StdCall: Out << " x86_stdcallcc"; break;
1646 case CallingConv::X86_FastCall: Out << " x86_fastcallcc"; break;
1647 case CallingConv::ARM_APCS: Out << " arm_apcscc "; break;
1648 case CallingConv::ARM_AAPCS: Out << " arm_aapcscc "; break;
1649 case CallingConv::ARM_AAPCS_VFP:Out << " arm_aapcs_vfpcc "; break;
1650 default: Out << " cc" << CI->getCallingConv(); break;
1653 const PointerType *PTy = cast<PointerType>(Operand->getType());
1654 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
1655 const Type *RetTy = FTy->getReturnType();
1656 const AttrListPtr &PAL = CI->getAttributes();
1658 if (PAL.getRetAttributes() != Attribute::None)
1659 Out << ' ' << Attribute::getAsString(PAL.getRetAttributes());
1661 // If possible, print out the short form of the call instruction. We can
1662 // only do this if the first argument is a pointer to a nonvararg function,
1663 // and if the return type is not a pointer to a function.
1666 if (!FTy->isVarArg() &&
1667 (!isa<PointerType>(RetTy) ||
1668 !isa<FunctionType>(cast<PointerType>(RetTy)->getElementType()))) {
1669 TypePrinter.print(RetTy, Out);
1671 writeOperand(Operand, false);
1673 writeOperand(Operand, true);
1676 for (unsigned op = 1, Eop = I.getNumOperands(); op < Eop; ++op) {
1679 writeParamOperand(I.getOperand(op), PAL.getParamAttributes(op));
1682 if (PAL.getFnAttributes() != Attribute::None)
1683 Out << ' ' << Attribute::getAsString(PAL.getFnAttributes());
1684 } else if (const InvokeInst *II = dyn_cast<InvokeInst>(&I)) {
1685 const PointerType *PTy = cast<PointerType>(Operand->getType());
1686 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
1687 const Type *RetTy = FTy->getReturnType();
1688 const AttrListPtr &PAL = II->getAttributes();
1690 // Print the calling convention being used.
1691 switch (II->getCallingConv()) {
1692 case CallingConv::C: break; // default
1693 case CallingConv::Fast: Out << " fastcc"; break;
1694 case CallingConv::Cold: Out << " coldcc"; break;
1695 case CallingConv::X86_StdCall: Out << " x86_stdcallcc"; break;
1696 case CallingConv::X86_FastCall: Out << " x86_fastcallcc"; break;
1697 case CallingConv::ARM_APCS: Out << " arm_apcscc "; break;
1698 case CallingConv::ARM_AAPCS: Out << " arm_aapcscc "; break;
1699 case CallingConv::ARM_AAPCS_VFP:Out << " arm_aapcs_vfpcc "; break;
1700 default: Out << " cc" << II->getCallingConv(); break;
1703 if (PAL.getRetAttributes() != Attribute::None)
1704 Out << ' ' << Attribute::getAsString(PAL.getRetAttributes());
1706 // If possible, print out the short form of the invoke instruction. We can
1707 // only do this if the first argument is a pointer to a nonvararg function,
1708 // and if the return type is not a pointer to a function.
1711 if (!FTy->isVarArg() &&
1712 (!isa<PointerType>(RetTy) ||
1713 !isa<FunctionType>(cast<PointerType>(RetTy)->getElementType()))) {
1714 TypePrinter.print(RetTy, Out);
1716 writeOperand(Operand, false);
1718 writeOperand(Operand, true);
1721 for (unsigned op = 3, Eop = I.getNumOperands(); op < Eop; ++op) {
1724 writeParamOperand(I.getOperand(op), PAL.getParamAttributes(op-2));
1728 if (PAL.getFnAttributes() != Attribute::None)
1729 Out << ' ' << Attribute::getAsString(PAL.getFnAttributes());
1731 Out << "\n\t\t\tto ";
1732 writeOperand(II->getNormalDest(), true);
1734 writeOperand(II->getUnwindDest(), true);
1736 } else if (const AllocationInst *AI = dyn_cast<AllocationInst>(&I)) {
1738 TypePrinter.print(AI->getType()->getElementType(), Out);
1739 if (AI->isArrayAllocation()) {
1741 writeOperand(AI->getArraySize(), true);
1743 if (AI->getAlignment()) {
1744 Out << ", align " << AI->getAlignment();
1746 } else if (isa<CastInst>(I)) {
1749 writeOperand(Operand, true); // Work with broken code
1752 TypePrinter.print(I.getType(), Out);
1753 } else if (isa<VAArgInst>(I)) {
1756 writeOperand(Operand, true); // Work with broken code
1759 TypePrinter.print(I.getType(), Out);
1760 } else if (Operand) { // Print the normal way.
1762 // PrintAllTypes - Instructions who have operands of all the same type
1763 // omit the type from all but the first operand. If the instruction has
1764 // different type operands (for example br), then they are all printed.
1765 bool PrintAllTypes = false;
1766 const Type *TheType = Operand->getType();
1768 // Select, Store and ShuffleVector always print all types.
1769 if (isa<SelectInst>(I) || isa<StoreInst>(I) || isa<ShuffleVectorInst>(I)
1770 || isa<ReturnInst>(I)) {
1771 PrintAllTypes = true;
1773 for (unsigned i = 1, E = I.getNumOperands(); i != E; ++i) {
1774 Operand = I.getOperand(i);
1775 // note that Operand shouldn't be null, but the test helps make dump()
1776 // more tolerant of malformed IR
1777 if (Operand && Operand->getType() != TheType) {
1778 PrintAllTypes = true; // We have differing types! Print them all!
1784 if (!PrintAllTypes) {
1786 TypePrinter.print(TheType, Out);
1790 for (unsigned i = 0, E = I.getNumOperands(); i != E; ++i) {
1792 writeOperand(I.getOperand(i), PrintAllTypes);
1796 // Print post operand alignment for load/store
1797 if (isa<LoadInst>(I) && cast<LoadInst>(I).getAlignment()) {
1798 Out << ", align " << cast<LoadInst>(I).getAlignment();
1799 } else if (isa<StoreInst>(I) && cast<StoreInst>(I).getAlignment()) {
1800 Out << ", align " << cast<StoreInst>(I).getAlignment();
1803 printInfoComment(I);
1808 //===----------------------------------------------------------------------===//
1809 // External Interface declarations
1810 //===----------------------------------------------------------------------===//
1812 void Module::print(std::ostream &o, AssemblyAnnotationWriter *AAW) const {
1813 raw_os_ostream OS(o);
1816 void Module::print(raw_ostream &OS, AssemblyAnnotationWriter *AAW) const {
1817 SlotTracker SlotTable(this);
1818 AssemblyWriter W(OS, SlotTable, this, AAW);
1822 void Type::print(std::ostream &o) const {
1823 raw_os_ostream OS(o);
1827 void Type::print(raw_ostream &OS) const {
1829 OS << "<null Type>";
1832 TypePrinting().print(this, OS);
1835 void Value::print(raw_ostream &OS, AssemblyAnnotationWriter *AAW) const {
1837 OS << "printing a <null> value\n";
1841 if (const Instruction *I = dyn_cast<Instruction>(this)) {
1842 const Function *F = I->getParent() ? I->getParent()->getParent() : 0;
1843 SlotTracker SlotTable(F);
1844 AssemblyWriter W(OS, SlotTable, F ? F->getParent() : 0, AAW);
1846 } else if (const BasicBlock *BB = dyn_cast<BasicBlock>(this)) {
1847 SlotTracker SlotTable(BB->getParent());
1848 AssemblyWriter W(OS, SlotTable,
1849 BB->getParent() ? BB->getParent()->getParent() : 0, AAW);
1851 } else if (const GlobalValue *GV = dyn_cast<GlobalValue>(this)) {
1852 SlotTracker SlotTable(GV->getParent());
1853 AssemblyWriter W(OS, SlotTable, GV->getParent(), AAW);
1855 } else if (const Constant *C = dyn_cast<Constant>(this)) {
1856 TypePrinting TypePrinter;
1857 TypePrinter.print(C->getType(), OS);
1859 WriteConstantInt(OS, C, TypePrinter, 0);
1860 } else if (const Argument *A = dyn_cast<Argument>(this)) {
1861 WriteAsOperand(OS, this, true,
1862 A->getParent() ? A->getParent()->getParent() : 0);
1863 } else if (isa<InlineAsm>(this)) {
1864 WriteAsOperand(OS, this, true, 0);
1866 assert(0 && "Unknown value to print out!");
1870 void Value::print(std::ostream &O, AssemblyAnnotationWriter *AAW) const {
1871 raw_os_ostream OS(O);
1875 // Value::dump - allow easy printing of Values from the debugger.
1876 void Value::dump() const { print(errs()); errs() << '\n'; }
1878 // Type::dump - allow easy printing of Types from the debugger.
1879 // This one uses type names from the given context module
1880 void Type::dump(const Module *Context) const {
1881 WriteTypeSymbolic(errs(), this, Context);
1885 // Type::dump - allow easy printing of Types from the debugger.
1886 void Type::dump() const { dump(0); }
1888 // Module::dump() - Allow printing of Modules from the debugger.
1889 void Module::dump() const { print(errs(), 0); }