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/ErrorHandling.h"
35 #include "llvm/Support/MathExtras.h"
36 #include "llvm/Support/raw_ostream.h"
42 // Make virtual table appear in this compilation unit.
43 AssemblyAnnotationWriter::~AssemblyAnnotationWriter() {}
45 //===----------------------------------------------------------------------===//
47 //===----------------------------------------------------------------------===//
49 static const Module *getModuleFromVal(const Value *V) {
50 if (const Argument *MA = dyn_cast<Argument>(V))
51 return MA->getParent() ? MA->getParent()->getParent() : 0;
53 if (const BasicBlock *BB = dyn_cast<BasicBlock>(V))
54 return BB->getParent() ? BB->getParent()->getParent() : 0;
56 if (const Instruction *I = dyn_cast<Instruction>(V)) {
57 const Function *M = I->getParent() ? I->getParent()->getParent() : 0;
58 return M ? M->getParent() : 0;
61 if (const GlobalValue *GV = dyn_cast<GlobalValue>(V))
62 return GV->getParent();
66 // PrintEscapedString - Print each character of the specified string, escaping
67 // it if it is not printable or if it is an escape char.
68 static void PrintEscapedString(const char *Str, unsigned Length,
70 for (unsigned i = 0; i != Length; ++i) {
71 unsigned char C = Str[i];
72 if (isprint(C) && C != '\\' && C != '"')
75 Out << '\\' << hexdigit(C >> 4) << hexdigit(C & 0x0F);
79 // PrintEscapedString - Print each character of the specified string, escaping
80 // it if it is not printable or if it is an escape char.
81 static void PrintEscapedString(const std::string &Str, raw_ostream &Out) {
82 PrintEscapedString(Str.c_str(), Str.size(), Out);
92 /// PrintLLVMName - Turn the specified name into an 'LLVM name', which is either
93 /// prefixed with % (if the string only contains simple characters) or is
94 /// surrounded with ""'s (if it has special chars in it). Print it out.
95 static void PrintLLVMName(raw_ostream &OS, const char *NameStr,
96 unsigned NameLen, PrefixType Prefix) {
97 assert(NameStr && "Cannot get empty name!");
99 default: assert(0 && "Bad prefix!");
100 case NoPrefix: break;
101 case GlobalPrefix: OS << '@'; break;
102 case LabelPrefix: break;
103 case LocalPrefix: OS << '%'; break;
106 // Scan the name to see if it needs quotes first.
107 bool NeedsQuotes = isdigit(NameStr[0]);
109 for (unsigned i = 0; i != NameLen; ++i) {
111 if (!isalnum(C) && C != '-' && C != '.' && C != '_') {
118 // If we didn't need any quotes, just write out the name in one blast.
120 OS.write(NameStr, NameLen);
124 // Okay, we need quotes. Output the quotes and escape any scary characters as
127 PrintEscapedString(NameStr, NameLen, OS);
131 /// PrintLLVMName - Turn the specified name into an 'LLVM name', which is either
132 /// prefixed with % (if the string only contains simple characters) or is
133 /// surrounded with ""'s (if it has special chars in it). Print it out.
134 static void PrintLLVMName(raw_ostream &OS, const Value *V) {
135 PrintLLVMName(OS, V->getNameStart(), V->getNameLen(),
136 isa<GlobalValue>(V) ? GlobalPrefix : LocalPrefix);
139 //===----------------------------------------------------------------------===//
140 // TypePrinting Class: Type printing machinery
141 //===----------------------------------------------------------------------===//
143 static DenseMap<const Type *, std::string> &getTypeNamesMap(void *M) {
144 return *static_cast<DenseMap<const Type *, std::string>*>(M);
147 void TypePrinting::clear() {
148 getTypeNamesMap(TypeNames).clear();
151 bool TypePrinting::hasTypeName(const Type *Ty) const {
152 return getTypeNamesMap(TypeNames).count(Ty);
155 void TypePrinting::addTypeName(const Type *Ty, const std::string &N) {
156 getTypeNamesMap(TypeNames).insert(std::make_pair(Ty, N));
160 TypePrinting::TypePrinting() {
161 TypeNames = new DenseMap<const Type *, std::string>();
164 TypePrinting::~TypePrinting() {
165 delete &getTypeNamesMap(TypeNames);
168 /// CalcTypeName - Write the specified type to the specified raw_ostream, making
169 /// use of type names or up references to shorten the type name where possible.
170 void TypePrinting::CalcTypeName(const Type *Ty,
171 SmallVectorImpl<const Type *> &TypeStack,
172 raw_ostream &OS, bool IgnoreTopLevelName) {
173 // Check to see if the type is named.
174 if (!IgnoreTopLevelName) {
175 DenseMap<const Type *, std::string> &TM = getTypeNamesMap(TypeNames);
176 DenseMap<const Type *, std::string>::iterator I = TM.find(Ty);
183 // Check to see if the Type is already on the stack...
184 unsigned Slot = 0, CurSize = TypeStack.size();
185 while (Slot < CurSize && TypeStack[Slot] != Ty) ++Slot; // Scan for type
187 // This is another base case for the recursion. In this case, we know
188 // that we have looped back to a type that we have previously visited.
189 // Generate the appropriate upreference to handle this.
190 if (Slot < CurSize) {
191 OS << '\\' << unsigned(CurSize-Slot); // Here's the upreference
195 TypeStack.push_back(Ty); // Recursive case: Add us to the stack..
197 switch (Ty->getTypeID()) {
198 case Type::VoidTyID: OS << "void"; break;
199 case Type::FloatTyID: OS << "float"; break;
200 case Type::DoubleTyID: OS << "double"; break;
201 case Type::X86_FP80TyID: OS << "x86_fp80"; break;
202 case Type::FP128TyID: OS << "fp128"; break;
203 case Type::PPC_FP128TyID: OS << "ppc_fp128"; break;
204 case Type::LabelTyID: OS << "label"; break;
205 case Type::MetadataTyID: OS << "metadata"; break;
206 case Type::IntegerTyID:
207 OS << 'i' << cast<IntegerType>(Ty)->getBitWidth();
210 case Type::FunctionTyID: {
211 const FunctionType *FTy = cast<FunctionType>(Ty);
212 CalcTypeName(FTy->getReturnType(), TypeStack, OS);
214 for (FunctionType::param_iterator I = FTy->param_begin(),
215 E = FTy->param_end(); I != E; ++I) {
216 if (I != FTy->param_begin())
218 CalcTypeName(*I, TypeStack, OS);
220 if (FTy->isVarArg()) {
221 if (FTy->getNumParams()) OS << ", ";
227 case Type::StructTyID: {
228 const StructType *STy = cast<StructType>(Ty);
232 for (StructType::element_iterator I = STy->element_begin(),
233 E = STy->element_end(); I != E; ++I) {
234 CalcTypeName(*I, TypeStack, OS);
235 if (next(I) != STy->element_end())
244 case Type::PointerTyID: {
245 const PointerType *PTy = cast<PointerType>(Ty);
246 CalcTypeName(PTy->getElementType(), TypeStack, OS);
247 if (unsigned AddressSpace = PTy->getAddressSpace())
248 OS << " addrspace(" << AddressSpace << ')';
252 case Type::ArrayTyID: {
253 const ArrayType *ATy = cast<ArrayType>(Ty);
254 OS << '[' << ATy->getNumElements() << " x ";
255 CalcTypeName(ATy->getElementType(), TypeStack, OS);
259 case Type::VectorTyID: {
260 const VectorType *PTy = cast<VectorType>(Ty);
261 OS << "<" << PTy->getNumElements() << " x ";
262 CalcTypeName(PTy->getElementType(), TypeStack, OS);
266 case Type::OpaqueTyID:
270 OS << "<unrecognized-type>";
274 TypeStack.pop_back(); // Remove self from stack.
277 /// printTypeInt - The internal guts of printing out a type that has a
278 /// potentially named portion.
280 void TypePrinting::print(const Type *Ty, raw_ostream &OS,
281 bool IgnoreTopLevelName) {
282 // Check to see if the type is named.
283 DenseMap<const Type*, std::string> &TM = getTypeNamesMap(TypeNames);
284 if (!IgnoreTopLevelName) {
285 DenseMap<const Type*, std::string>::iterator I = TM.find(Ty);
292 // Otherwise we have a type that has not been named but is a derived type.
293 // Carefully recurse the type hierarchy to print out any contained symbolic
295 SmallVector<const Type *, 16> TypeStack;
296 std::string TypeName;
298 raw_string_ostream TypeOS(TypeName);
299 CalcTypeName(Ty, TypeStack, TypeOS, IgnoreTopLevelName);
302 // Cache type name for later use.
303 if (!IgnoreTopLevelName)
304 TM.insert(std::make_pair(Ty, TypeOS.str()));
309 // To avoid walking constant expressions multiple times and other IR
310 // objects, we keep several helper maps.
311 DenseSet<const Value*> VisitedConstants;
312 DenseSet<const Type*> VisitedTypes;
315 std::vector<const Type*> &NumberedTypes;
317 TypeFinder(TypePrinting &tp, std::vector<const Type*> &numberedTypes)
318 : TP(tp), NumberedTypes(numberedTypes) {}
320 void Run(const Module &M) {
321 // Get types from the type symbol table. This gets opaque types referened
322 // only through derived named types.
323 const TypeSymbolTable &ST = M.getTypeSymbolTable();
324 for (TypeSymbolTable::const_iterator TI = ST.begin(), E = ST.end();
326 IncorporateType(TI->second);
328 // Get types from global variables.
329 for (Module::const_global_iterator I = M.global_begin(),
330 E = M.global_end(); I != E; ++I) {
331 IncorporateType(I->getType());
332 if (I->hasInitializer())
333 IncorporateValue(I->getInitializer());
336 // Get types from aliases.
337 for (Module::const_alias_iterator I = M.alias_begin(),
338 E = M.alias_end(); I != E; ++I) {
339 IncorporateType(I->getType());
340 IncorporateValue(I->getAliasee());
343 // Get types from functions.
344 for (Module::const_iterator FI = M.begin(), E = M.end(); FI != E; ++FI) {
345 IncorporateType(FI->getType());
347 for (Function::const_iterator BB = FI->begin(), E = FI->end();
349 for (BasicBlock::const_iterator II = BB->begin(),
350 E = BB->end(); II != E; ++II) {
351 const Instruction &I = *II;
352 // Incorporate the type of the instruction and all its operands.
353 IncorporateType(I.getType());
354 for (User::const_op_iterator OI = I.op_begin(), OE = I.op_end();
356 IncorporateValue(*OI);
362 void IncorporateType(const Type *Ty) {
363 // Check to see if we're already visited this type.
364 if (!VisitedTypes.insert(Ty).second)
367 // If this is a structure or opaque type, add a name for the type.
368 if (((isa<StructType>(Ty) && cast<StructType>(Ty)->getNumElements())
369 || isa<OpaqueType>(Ty)) && !TP.hasTypeName(Ty)) {
370 TP.addTypeName(Ty, "%"+utostr(unsigned(NumberedTypes.size())));
371 NumberedTypes.push_back(Ty);
374 // Recursively walk all contained types.
375 for (Type::subtype_iterator I = Ty->subtype_begin(),
376 E = Ty->subtype_end(); I != E; ++I)
380 /// IncorporateValue - This method is used to walk operand lists finding
381 /// types hiding in constant expressions and other operands that won't be
382 /// walked in other ways. GlobalValues, basic blocks, instructions, and
383 /// inst operands are all explicitly enumerated.
384 void IncorporateValue(const Value *V) {
385 if (V == 0 || !isa<Constant>(V) || isa<GlobalValue>(V)) return;
388 if (!VisitedConstants.insert(V).second)
392 IncorporateType(V->getType());
394 // Look in operands for types.
395 const Constant *C = cast<Constant>(V);
396 for (Constant::const_op_iterator I = C->op_begin(),
397 E = C->op_end(); I != E;++I)
398 IncorporateValue(*I);
401 } // end anonymous namespace
404 /// AddModuleTypesToPrinter - Add all of the symbolic type names for types in
405 /// the specified module to the TypePrinter and all numbered types to it and the
406 /// NumberedTypes table.
407 static void AddModuleTypesToPrinter(TypePrinting &TP,
408 std::vector<const Type*> &NumberedTypes,
412 // If the module has a symbol table, take all global types and stuff their
413 // names into the TypeNames map.
414 const TypeSymbolTable &ST = M->getTypeSymbolTable();
415 for (TypeSymbolTable::const_iterator TI = ST.begin(), E = ST.end();
417 const Type *Ty = cast<Type>(TI->second);
419 // As a heuristic, don't insert pointer to primitive types, because
420 // they are used too often to have a single useful name.
421 if (const PointerType *PTy = dyn_cast<PointerType>(Ty)) {
422 const Type *PETy = PTy->getElementType();
423 if ((PETy->isPrimitiveType() || PETy->isInteger()) &&
424 !isa<OpaqueType>(PETy))
428 // Likewise don't insert primitives either.
429 if (Ty->isInteger() || Ty->isPrimitiveType())
432 // Get the name as a string and insert it into TypeNames.
434 raw_string_ostream NameOS(NameStr);
435 PrintLLVMName(NameOS, TI->first.c_str(), TI->first.length(), LocalPrefix);
436 TP.addTypeName(Ty, NameOS.str());
439 // Walk the entire module to find references to unnamed structure and opaque
440 // types. This is required for correctness by opaque types (because multiple
441 // uses of an unnamed opaque type needs to be referred to by the same ID) and
442 // it shrinks complex recursive structure types substantially in some cases.
443 TypeFinder(TP, NumberedTypes).Run(*M);
447 /// WriteTypeSymbolic - This attempts to write the specified type as a symbolic
448 /// type, iff there is an entry in the modules symbol table for the specified
449 /// type or one of it's component types.
451 void llvm::WriteTypeSymbolic(raw_ostream &OS, const Type *Ty, const Module *M) {
452 TypePrinting Printer;
453 std::vector<const Type*> NumberedTypes;
454 AddModuleTypesToPrinter(Printer, NumberedTypes, M);
455 Printer.print(Ty, OS);
458 //===----------------------------------------------------------------------===//
459 // SlotTracker Class: Enumerate slot numbers for unnamed values
460 //===----------------------------------------------------------------------===//
464 /// This class provides computation of slot numbers for LLVM Assembly writing.
468 /// ValueMap - A mapping of Values to slot numbers
469 typedef DenseMap<const Value*, unsigned> ValueMap;
472 /// TheModule - The module for which we are holding slot numbers
473 const Module* TheModule;
475 /// TheFunction - The function for which we are holding slot numbers
476 const Function* TheFunction;
477 bool FunctionProcessed;
479 /// mMap - The TypePlanes map for the module level data
483 /// fMap - The TypePlanes map for the function level data
488 /// Construct from a module
489 explicit SlotTracker(const Module *M);
490 /// Construct from a function, starting out in incorp state.
491 explicit SlotTracker(const Function *F);
493 /// Return the slot number of the specified value in it's type
494 /// plane. If something is not in the SlotTracker, return -1.
495 int getLocalSlot(const Value *V);
496 int getGlobalSlot(const GlobalValue *V);
498 /// If you'd like to deal with a function instead of just a module, use
499 /// this method to get its data into the SlotTracker.
500 void incorporateFunction(const Function *F) {
502 FunctionProcessed = false;
505 /// After calling incorporateFunction, use this method to remove the
506 /// most recently incorporated function from the SlotTracker. This
507 /// will reset the state of the machine back to just the module contents.
508 void purgeFunction();
510 // Implementation Details
512 /// This function does the actual initialization.
513 inline void initialize();
515 /// CreateModuleSlot - Insert the specified GlobalValue* into the slot table.
516 void CreateModuleSlot(const GlobalValue *V);
518 /// CreateFunctionSlot - Insert the specified Value* into the slot table.
519 void CreateFunctionSlot(const Value *V);
521 /// Add all of the module level global variables (and their initializers)
522 /// and function declarations, but not the contents of those functions.
523 void processModule();
525 /// Add all of the functions arguments, basic blocks, and instructions
526 void processFunction();
528 SlotTracker(const SlotTracker &); // DO NOT IMPLEMENT
529 void operator=(const SlotTracker &); // DO NOT IMPLEMENT
532 } // end anonymous namespace
535 static SlotTracker *createSlotTracker(const Value *V) {
536 if (const Argument *FA = dyn_cast<Argument>(V))
537 return new SlotTracker(FA->getParent());
539 if (const Instruction *I = dyn_cast<Instruction>(V))
540 return new SlotTracker(I->getParent()->getParent());
542 if (const BasicBlock *BB = dyn_cast<BasicBlock>(V))
543 return new SlotTracker(BB->getParent());
545 if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(V))
546 return new SlotTracker(GV->getParent());
548 if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(V))
549 return new SlotTracker(GA->getParent());
551 if (const Function *Func = dyn_cast<Function>(V))
552 return new SlotTracker(Func);
558 #define ST_DEBUG(X) cerr << X
563 // Module level constructor. Causes the contents of the Module (sans functions)
564 // to be added to the slot table.
565 SlotTracker::SlotTracker(const Module *M)
566 : TheModule(M), TheFunction(0), FunctionProcessed(false), mNext(0), fNext(0) {
569 // Function level constructor. Causes the contents of the Module and the one
570 // function provided to be added to the slot table.
571 SlotTracker::SlotTracker(const Function *F)
572 : TheModule(F ? F->getParent() : 0), TheFunction(F), FunctionProcessed(false),
576 inline void SlotTracker::initialize() {
579 TheModule = 0; ///< Prevent re-processing next time we're called.
582 if (TheFunction && !FunctionProcessed)
586 // Iterate through all the global variables, functions, and global
587 // variable initializers and create slots for them.
588 void SlotTracker::processModule() {
589 ST_DEBUG("begin processModule!\n");
591 // Add all of the unnamed global variables to the value table.
592 for (Module::const_global_iterator I = TheModule->global_begin(),
593 E = TheModule->global_end(); I != E; ++I)
597 // Add all the unnamed functions to the table.
598 for (Module::const_iterator I = TheModule->begin(), E = TheModule->end();
603 ST_DEBUG("end processModule!\n");
607 // Process the arguments, basic blocks, and instructions of a function.
608 void SlotTracker::processFunction() {
609 ST_DEBUG("begin processFunction!\n");
612 // Add all the function arguments with no names.
613 for(Function::const_arg_iterator AI = TheFunction->arg_begin(),
614 AE = TheFunction->arg_end(); AI != AE; ++AI)
616 CreateFunctionSlot(AI);
618 ST_DEBUG("Inserting Instructions:\n");
620 // Add all of the basic blocks and instructions with no names.
621 for (Function::const_iterator BB = TheFunction->begin(),
622 E = TheFunction->end(); BB != E; ++BB) {
624 CreateFunctionSlot(BB);
625 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I != E; ++I)
626 if (I->getType() != Type::VoidTy && !I->hasName())
627 CreateFunctionSlot(I);
630 FunctionProcessed = true;
632 ST_DEBUG("end processFunction!\n");
635 /// Clean up after incorporating a function. This is the only way to get out of
636 /// the function incorporation state that affects get*Slot/Create*Slot. Function
637 /// incorporation state is indicated by TheFunction != 0.
638 void SlotTracker::purgeFunction() {
639 ST_DEBUG("begin purgeFunction!\n");
640 fMap.clear(); // Simply discard the function level map
642 FunctionProcessed = false;
643 ST_DEBUG("end purgeFunction!\n");
646 /// getGlobalSlot - Get the slot number of a global value.
647 int SlotTracker::getGlobalSlot(const GlobalValue *V) {
648 // Check for uninitialized state and do lazy initialization.
651 // Find the type plane in the module map
652 ValueMap::iterator MI = mMap.find(V);
653 return MI == mMap.end() ? -1 : (int)MI->second;
657 /// getLocalSlot - Get the slot number for a value that is local to a function.
658 int SlotTracker::getLocalSlot(const Value *V) {
659 assert(!isa<Constant>(V) && "Can't get a constant or global slot with this!");
661 // Check for uninitialized state and do lazy initialization.
664 ValueMap::iterator FI = fMap.find(V);
665 return FI == fMap.end() ? -1 : (int)FI->second;
669 /// CreateModuleSlot - Insert the specified GlobalValue* into the slot table.
670 void SlotTracker::CreateModuleSlot(const GlobalValue *V) {
671 assert(V && "Can't insert a null Value into SlotTracker!");
672 assert(V->getType() != Type::VoidTy && "Doesn't need a slot!");
673 assert(!V->hasName() && "Doesn't need a slot!");
675 unsigned DestSlot = mNext++;
678 ST_DEBUG(" Inserting value [" << V->getType() << "] = " << V << " slot=" <<
680 // G = Global, F = Function, A = Alias, o = other
681 ST_DEBUG((isa<GlobalVariable>(V) ? 'G' :
682 (isa<Function>(V) ? 'F' :
683 (isa<GlobalAlias>(V) ? 'A' : 'o'))) << "]\n");
687 /// CreateSlot - Create a new slot for the specified value if it has no name.
688 void SlotTracker::CreateFunctionSlot(const Value *V) {
689 assert(V->getType() != Type::VoidTy && !V->hasName() &&
690 "Doesn't need a slot!");
692 unsigned DestSlot = fNext++;
695 // G = Global, F = Function, o = other
696 ST_DEBUG(" Inserting value [" << V->getType() << "] = " << V << " slot=" <<
697 DestSlot << " [o]\n");
702 //===----------------------------------------------------------------------===//
703 // AsmWriter Implementation
704 //===----------------------------------------------------------------------===//
706 static void WriteAsOperandInternal(raw_ostream &Out, const Value *V,
707 TypePrinting &TypePrinter,
708 SlotTracker *Machine);
712 static const char *getPredicateText(unsigned predicate) {
713 const char * pred = "unknown";
715 case FCmpInst::FCMP_FALSE: pred = "false"; break;
716 case FCmpInst::FCMP_OEQ: pred = "oeq"; break;
717 case FCmpInst::FCMP_OGT: pred = "ogt"; break;
718 case FCmpInst::FCMP_OGE: pred = "oge"; break;
719 case FCmpInst::FCMP_OLT: pred = "olt"; break;
720 case FCmpInst::FCMP_OLE: pred = "ole"; break;
721 case FCmpInst::FCMP_ONE: pred = "one"; break;
722 case FCmpInst::FCMP_ORD: pred = "ord"; break;
723 case FCmpInst::FCMP_UNO: pred = "uno"; break;
724 case FCmpInst::FCMP_UEQ: pred = "ueq"; break;
725 case FCmpInst::FCMP_UGT: pred = "ugt"; break;
726 case FCmpInst::FCMP_UGE: pred = "uge"; break;
727 case FCmpInst::FCMP_ULT: pred = "ult"; break;
728 case FCmpInst::FCMP_ULE: pred = "ule"; break;
729 case FCmpInst::FCMP_UNE: pred = "une"; break;
730 case FCmpInst::FCMP_TRUE: pred = "true"; break;
731 case ICmpInst::ICMP_EQ: pred = "eq"; break;
732 case ICmpInst::ICMP_NE: pred = "ne"; break;
733 case ICmpInst::ICMP_SGT: pred = "sgt"; break;
734 case ICmpInst::ICMP_SGE: pred = "sge"; break;
735 case ICmpInst::ICMP_SLT: pred = "slt"; break;
736 case ICmpInst::ICMP_SLE: pred = "sle"; break;
737 case ICmpInst::ICMP_UGT: pred = "ugt"; break;
738 case ICmpInst::ICMP_UGE: pred = "uge"; break;
739 case ICmpInst::ICMP_ULT: pred = "ult"; break;
740 case ICmpInst::ICMP_ULE: pred = "ule"; break;
745 static void WriteConstantInt(raw_ostream &Out, const Constant *CV,
746 TypePrinting &TypePrinter, SlotTracker *Machine) {
747 if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV)) {
748 if (CI->getType() == Type::Int1Ty) {
749 Out << (CI->getZExtValue() ? "true" : "false");
752 Out << CI->getValue();
756 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CV)) {
757 if (&CFP->getValueAPF().getSemantics() == &APFloat::IEEEdouble ||
758 &CFP->getValueAPF().getSemantics() == &APFloat::IEEEsingle) {
759 // We would like to output the FP constant value in exponential notation,
760 // but we cannot do this if doing so will lose precision. Check here to
761 // make sure that we only output it in exponential format if we can parse
762 // the value back and get the same value.
765 bool isDouble = &CFP->getValueAPF().getSemantics()==&APFloat::IEEEdouble;
766 double Val = isDouble ? CFP->getValueAPF().convertToDouble() :
767 CFP->getValueAPF().convertToFloat();
768 std::string StrVal = ftostr(CFP->getValueAPF());
770 // Check to make sure that the stringized number is not some string like
771 // "Inf" or NaN, that atof will accept, but the lexer will not. Check
772 // that the string matches the "[-+]?[0-9]" regex.
774 if ((StrVal[0] >= '0' && StrVal[0] <= '9') ||
775 ((StrVal[0] == '-' || StrVal[0] == '+') &&
776 (StrVal[1] >= '0' && StrVal[1] <= '9'))) {
777 // Reparse stringized version!
778 if (atof(StrVal.c_str()) == Val) {
783 // Otherwise we could not reparse it to exactly the same value, so we must
784 // output the string in hexadecimal format! Note that loading and storing
785 // floating point types changes the bits of NaNs on some hosts, notably
786 // x86, so we must not use these types.
787 assert(sizeof(double) == sizeof(uint64_t) &&
788 "assuming that double is 64 bits!");
790 APFloat apf = CFP->getValueAPF();
791 // Floats are represented in ASCII IR as double, convert.
793 apf.convert(APFloat::IEEEdouble, APFloat::rmNearestTiesToEven,
796 utohex_buffer(uint64_t(apf.bitcastToAPInt().getZExtValue()),
801 // Some form of long double. These appear as a magic letter identifying
802 // the type, then a fixed number of hex digits.
804 if (&CFP->getValueAPF().getSemantics() == &APFloat::x87DoubleExtended) {
806 // api needed to prevent premature destruction
807 APInt api = CFP->getValueAPF().bitcastToAPInt();
808 const uint64_t* p = api.getRawData();
809 uint64_t word = p[1];
811 int width = api.getBitWidth();
812 for (int j=0; j<width; j+=4, shiftcount-=4) {
813 unsigned int nibble = (word>>shiftcount) & 15;
815 Out << (unsigned char)(nibble + '0');
817 Out << (unsigned char)(nibble - 10 + 'A');
818 if (shiftcount == 0 && j+4 < width) {
822 shiftcount = width-j-4;
826 } else if (&CFP->getValueAPF().getSemantics() == &APFloat::IEEEquad)
828 else if (&CFP->getValueAPF().getSemantics() == &APFloat::PPCDoubleDouble)
831 assert(0 && "Unsupported floating point type");
832 // api needed to prevent premature destruction
833 APInt api = CFP->getValueAPF().bitcastToAPInt();
834 const uint64_t* p = api.getRawData();
837 int width = api.getBitWidth();
838 for (int j=0; j<width; j+=4, shiftcount-=4) {
839 unsigned int nibble = (word>>shiftcount) & 15;
841 Out << (unsigned char)(nibble + '0');
843 Out << (unsigned char)(nibble - 10 + 'A');
844 if (shiftcount == 0 && j+4 < width) {
848 shiftcount = width-j-4;
854 if (isa<ConstantAggregateZero>(CV)) {
855 Out << "zeroinitializer";
859 if (const ConstantArray *CA = dyn_cast<ConstantArray>(CV)) {
860 // As a special case, print the array as a string if it is an array of
861 // i8 with ConstantInt values.
863 const Type *ETy = CA->getType()->getElementType();
864 if (CA->isString()) {
866 PrintEscapedString(CA->getAsString(), Out);
868 } else { // Cannot output in string format...
870 if (CA->getNumOperands()) {
871 TypePrinter.print(ETy, Out);
873 WriteAsOperandInternal(Out, CA->getOperand(0),
874 TypePrinter, Machine);
875 for (unsigned i = 1, e = CA->getNumOperands(); i != e; ++i) {
877 TypePrinter.print(ETy, Out);
879 WriteAsOperandInternal(Out, CA->getOperand(i), TypePrinter, Machine);
887 if (const ConstantStruct *CS = dyn_cast<ConstantStruct>(CV)) {
888 if (CS->getType()->isPacked())
891 unsigned N = CS->getNumOperands();
894 TypePrinter.print(CS->getOperand(0)->getType(), Out);
897 WriteAsOperandInternal(Out, CS->getOperand(0), TypePrinter, Machine);
899 for (unsigned i = 1; i < N; i++) {
901 TypePrinter.print(CS->getOperand(i)->getType(), Out);
904 WriteAsOperandInternal(Out, CS->getOperand(i), TypePrinter, Machine);
910 if (CS->getType()->isPacked())
915 if (const ConstantVector *CP = dyn_cast<ConstantVector>(CV)) {
916 const Type *ETy = CP->getType()->getElementType();
917 assert(CP->getNumOperands() > 0 &&
918 "Number of operands for a PackedConst must be > 0");
920 TypePrinter.print(ETy, Out);
922 WriteAsOperandInternal(Out, CP->getOperand(0), TypePrinter, Machine);
923 for (unsigned i = 1, e = CP->getNumOperands(); i != e; ++i) {
925 TypePrinter.print(ETy, Out);
927 WriteAsOperandInternal(Out, CP->getOperand(i), TypePrinter, Machine);
933 if (isa<ConstantPointerNull>(CV)) {
938 if (isa<UndefValue>(CV)) {
943 if (const MDString *S = dyn_cast<MDString>(CV)) {
945 PrintEscapedString(S->begin(), S->size(), Out);
950 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV)) {
951 Out << CE->getOpcodeName();
953 Out << ' ' << getPredicateText(CE->getPredicate());
956 for (User::const_op_iterator OI=CE->op_begin(); OI != CE->op_end(); ++OI) {
957 TypePrinter.print((*OI)->getType(), Out);
959 WriteAsOperandInternal(Out, *OI, TypePrinter, Machine);
960 if (OI+1 != CE->op_end())
964 if (CE->hasIndices()) {
965 const SmallVector<unsigned, 4> &Indices = CE->getIndices();
966 for (unsigned i = 0, e = Indices.size(); i != e; ++i)
967 Out << ", " << Indices[i];
972 TypePrinter.print(CE->getType(), Out);
979 Out << "<placeholder or erroneous Constant>";
983 /// WriteAsOperand - Write the name of the specified value out to the specified
984 /// ostream. This can be useful when you just want to print int %reg126, not
985 /// the whole instruction that generated it.
987 static void WriteAsOperandInternal(raw_ostream &Out, const Value *V,
988 TypePrinting &TypePrinter,
989 SlotTracker *Machine) {
991 PrintLLVMName(Out, V);
995 const Constant *CV = dyn_cast<Constant>(V);
996 if (CV && !isa<GlobalValue>(CV)) {
997 WriteConstantInt(Out, CV, TypePrinter, Machine);
1001 if (const InlineAsm *IA = dyn_cast<InlineAsm>(V)) {
1003 if (IA->hasSideEffects())
1004 Out << "sideeffect ";
1006 PrintEscapedString(IA->getAsmString(), Out);
1008 PrintEscapedString(IA->getConstraintString(), Out);
1016 if (const GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
1017 Slot = Machine->getGlobalSlot(GV);
1020 Slot = Machine->getLocalSlot(V);
1023 Machine = createSlotTracker(V);
1025 if (const GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
1026 Slot = Machine->getGlobalSlot(GV);
1029 Slot = Machine->getLocalSlot(V);
1038 Out << Prefix << Slot;
1043 /// WriteAsOperand - Write the name of the specified value out to the specified
1044 /// ostream. This can be useful when you just want to print int %reg126, not
1045 /// the whole instruction that generated it.
1047 void llvm::WriteAsOperand(std::ostream &Out, const Value *V, bool PrintType,
1048 const Module *Context) {
1049 raw_os_ostream OS(Out);
1050 WriteAsOperand(OS, V, PrintType, Context);
1053 void llvm::WriteAsOperand(raw_ostream &Out, const Value *V, bool PrintType,
1054 const Module *Context) {
1055 if (Context == 0) Context = getModuleFromVal(V);
1057 TypePrinting TypePrinter;
1058 std::vector<const Type*> NumberedTypes;
1059 AddModuleTypesToPrinter(TypePrinter, NumberedTypes, Context);
1061 TypePrinter.print(V->getType(), Out);
1065 WriteAsOperandInternal(Out, V, TypePrinter, 0);
1071 class AssemblyWriter {
1073 SlotTracker &Machine;
1074 const Module *TheModule;
1075 TypePrinting TypePrinter;
1076 AssemblyAnnotationWriter *AnnotationWriter;
1077 std::vector<const Type*> NumberedTypes;
1079 // Each MDNode is assigned unique MetadataIDNo.
1080 std::map<const MDNode *, unsigned> MDNodes;
1081 unsigned MetadataIDNo;
1083 inline AssemblyWriter(raw_ostream &o, SlotTracker &Mac, const Module *M,
1084 AssemblyAnnotationWriter *AAW)
1085 : Out(o), Machine(Mac), TheModule(M), AnnotationWriter(AAW), MetadataIDNo(0) {
1086 AddModuleTypesToPrinter(TypePrinter, NumberedTypes, M);
1089 void write(const Module *M) { printModule(M); }
1091 void write(const GlobalValue *G) {
1092 if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(G))
1094 else if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(G))
1096 else if (const Function *F = dyn_cast<Function>(G))
1099 assert(0 && "Unknown global");
1102 void write(const BasicBlock *BB) { printBasicBlock(BB); }
1103 void write(const Instruction *I) { printInstruction(*I); }
1105 void writeOperand(const Value *Op, bool PrintType);
1106 void writeParamOperand(const Value *Operand, Attributes Attrs);
1107 void printMDNode(const MDNode *Node, bool StandAlone);
1109 const Module* getModule() { return TheModule; }
1112 void printModule(const Module *M);
1113 void printTypeSymbolTable(const TypeSymbolTable &ST);
1114 void printGlobal(const GlobalVariable *GV);
1115 void printAlias(const GlobalAlias *GV);
1116 void printFunction(const Function *F);
1117 void printArgument(const Argument *FA, Attributes Attrs);
1118 void printBasicBlock(const BasicBlock *BB);
1119 void printInstruction(const Instruction &I);
1121 // printInfoComment - Print a little comment after the instruction indicating
1122 // which slot it occupies.
1123 void printInfoComment(const Value &V);
1125 } // end of anonymous namespace
1128 void AssemblyWriter::writeOperand(const Value *Operand, bool PrintType) {
1130 Out << "<null operand!>";
1133 TypePrinter.print(Operand->getType(), Out);
1136 WriteAsOperandInternal(Out, Operand, TypePrinter, &Machine);
1140 void AssemblyWriter::writeParamOperand(const Value *Operand,
1143 Out << "<null operand!>";
1146 TypePrinter.print(Operand->getType(), Out);
1147 // Print parameter attributes list
1148 if (Attrs != Attribute::None)
1149 Out << ' ' << Attribute::getAsString(Attrs);
1151 // Print the operand
1152 WriteAsOperandInternal(Out, Operand, TypePrinter, &Machine);
1156 void AssemblyWriter::printModule(const Module *M) {
1157 if (!M->getModuleIdentifier().empty() &&
1158 // Don't print the ID if it will start a new line (which would
1159 // require a comment char before it).
1160 M->getModuleIdentifier().find('\n') == std::string::npos)
1161 Out << "; ModuleID = '" << M->getModuleIdentifier() << "'\n";
1163 if (!M->getDataLayout().empty())
1164 Out << "target datalayout = \"" << M->getDataLayout() << "\"\n";
1165 if (!M->getTargetTriple().empty())
1166 Out << "target triple = \"" << M->getTargetTriple() << "\"\n";
1168 if (!M->getModuleInlineAsm().empty()) {
1169 // Split the string into lines, to make it easier to read the .ll file.
1170 std::string Asm = M->getModuleInlineAsm();
1172 size_t NewLine = Asm.find_first_of('\n', CurPos);
1173 while (NewLine != std::string::npos) {
1174 // We found a newline, print the portion of the asm string from the
1175 // last newline up to this newline.
1176 Out << "module asm \"";
1177 PrintEscapedString(std::string(Asm.begin()+CurPos, Asm.begin()+NewLine),
1181 NewLine = Asm.find_first_of('\n', CurPos);
1183 Out << "module asm \"";
1184 PrintEscapedString(std::string(Asm.begin()+CurPos, Asm.end()), Out);
1188 // Loop over the dependent libraries and emit them.
1189 Module::lib_iterator LI = M->lib_begin();
1190 Module::lib_iterator LE = M->lib_end();
1192 Out << "deplibs = [ ";
1194 Out << '"' << *LI << '"';
1202 // Loop over the symbol table, emitting all id'd types.
1203 printTypeSymbolTable(M->getTypeSymbolTable());
1205 for (Module::const_global_iterator I = M->global_begin(), E = M->global_end();
1209 // Output all aliases.
1210 if (!M->alias_empty()) Out << "\n";
1211 for (Module::const_alias_iterator I = M->alias_begin(), E = M->alias_end();
1215 // Output all of the functions.
1216 for (Module::const_iterator I = M->begin(), E = M->end(); I != E; ++I)
1220 static void PrintLinkage(GlobalValue::LinkageTypes LT, raw_ostream &Out) {
1222 case GlobalValue::PrivateLinkage: Out << "private "; break;
1223 case GlobalValue::InternalLinkage: Out << "internal "; break;
1224 case GlobalValue::AvailableExternallyLinkage:
1225 Out << "available_externally ";
1227 case GlobalValue::LinkOnceAnyLinkage: Out << "linkonce "; break;
1228 case GlobalValue::LinkOnceODRLinkage: Out << "linkonce_odr "; break;
1229 case GlobalValue::WeakAnyLinkage: Out << "weak "; break;
1230 case GlobalValue::WeakODRLinkage: Out << "weak_odr "; break;
1231 case GlobalValue::CommonLinkage: Out << "common "; break;
1232 case GlobalValue::AppendingLinkage: Out << "appending "; break;
1233 case GlobalValue::DLLImportLinkage: Out << "dllimport "; break;
1234 case GlobalValue::DLLExportLinkage: Out << "dllexport "; break;
1235 case GlobalValue::ExternalWeakLinkage: Out << "extern_weak "; break;
1236 case GlobalValue::ExternalLinkage: break;
1237 case GlobalValue::GhostLinkage:
1238 llvm_report_error("GhostLinkage not allowed in AsmWriter!");
1243 static void PrintVisibility(GlobalValue::VisibilityTypes Vis,
1246 default: assert(0 && "Invalid visibility style!");
1247 case GlobalValue::DefaultVisibility: break;
1248 case GlobalValue::HiddenVisibility: Out << "hidden "; break;
1249 case GlobalValue::ProtectedVisibility: Out << "protected "; break;
1253 void AssemblyWriter::printGlobal(const GlobalVariable *GV) {
1254 if (GV->hasInitializer())
1255 // If GV is initialized using Metadata then separate out metadata
1256 // operands used by the initializer. Note, MDNodes are not cyclic.
1257 if (MDNode *N = dyn_cast<MDNode>(GV->getInitializer())) {
1258 SmallVector<const MDNode *, 4> WorkList;
1259 // Collect MDNodes used by the initializer.
1260 for (MDNode::const_elem_iterator I = N->elem_begin(), E = N->elem_end();
1262 const Value *TV = *I;
1264 if (const MDNode *NN = dyn_cast<MDNode>(TV))
1265 WorkList.push_back(NN);
1268 // Print MDNodes used by the initializer.
1269 while (!WorkList.empty()) {
1270 const MDNode *N = WorkList.back(); WorkList.pop_back();
1271 printMDNode(N, true);
1276 if (GV->hasName()) {
1277 PrintLLVMName(Out, GV);
1281 if (!GV->hasInitializer() && GV->hasExternalLinkage())
1284 PrintLinkage(GV->getLinkage(), Out);
1285 PrintVisibility(GV->getVisibility(), Out);
1287 if (GV->isThreadLocal()) Out << "thread_local ";
1288 if (unsigned AddressSpace = GV->getType()->getAddressSpace())
1289 Out << "addrspace(" << AddressSpace << ") ";
1290 Out << (GV->isConstant() ? "constant " : "global ");
1291 TypePrinter.print(GV->getType()->getElementType(), Out);
1293 if (GV->hasInitializer()) {
1295 if (MDNode *N = dyn_cast<MDNode>(GV->getInitializer()))
1296 printMDNode(N, false);
1298 writeOperand(GV->getInitializer(), false);
1301 if (GV->hasSection())
1302 Out << ", section \"" << GV->getSection() << '"';
1303 if (GV->getAlignment())
1304 Out << ", align " << GV->getAlignment();
1306 printInfoComment(*GV);
1310 void AssemblyWriter::printMDNode(const MDNode *Node,
1312 std::map<const MDNode *, unsigned>::iterator MI = MDNodes.find(Node);
1313 // If this node is already printed then just refer it using its Metadata
1315 if (MI != MDNodes.end()) {
1317 Out << "!" << MI->second;
1322 // Print standalone MDNode.
1324 Out << "!" << MetadataIDNo << " = ";
1325 Out << "constant metadata ";
1329 for (MDNode::const_elem_iterator I = Node->elem_begin(), E = Node->elem_end();
1331 const Value *TV = *I;
1334 else if (const MDNode *N = dyn_cast<MDNode>(TV)) {
1335 TypePrinter.print(N->getType(), Out);
1337 printMDNode(N, StandAlone);
1342 writeOperand(*I, true);
1348 MDNodes[Node] = MetadataIDNo++;
1351 void AssemblyWriter::printAlias(const GlobalAlias *GA) {
1352 // Don't crash when dumping partially built GA
1354 Out << "<<nameless>> = ";
1356 PrintLLVMName(Out, GA);
1359 PrintVisibility(GA->getVisibility(), Out);
1363 PrintLinkage(GA->getLinkage(), Out);
1365 const Constant *Aliasee = GA->getAliasee();
1367 if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(Aliasee)) {
1368 TypePrinter.print(GV->getType(), Out);
1370 PrintLLVMName(Out, GV);
1371 } else if (const Function *F = dyn_cast<Function>(Aliasee)) {
1372 TypePrinter.print(F->getFunctionType(), Out);
1375 WriteAsOperandInternal(Out, F, TypePrinter, &Machine);
1376 } else if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(Aliasee)) {
1377 TypePrinter.print(GA->getType(), Out);
1379 PrintLLVMName(Out, GA);
1381 const ConstantExpr *CE = cast<ConstantExpr>(Aliasee);
1382 // The only valid GEP is an all zero GEP.
1383 assert((CE->getOpcode() == Instruction::BitCast ||
1384 CE->getOpcode() == Instruction::GetElementPtr) &&
1385 "Unsupported aliasee");
1386 writeOperand(CE, false);
1389 printInfoComment(*GA);
1393 void AssemblyWriter::printTypeSymbolTable(const TypeSymbolTable &ST) {
1394 // Emit all numbered types.
1395 for (unsigned i = 0, e = NumberedTypes.size(); i != e; ++i) {
1398 // Make sure we print out at least one level of the type structure, so
1399 // that we do not get %2 = type %2
1400 TypePrinter.printAtLeastOneLevel(NumberedTypes[i], Out);
1401 Out << "\t\t; type %" << i << '\n';
1404 // Print the named types.
1405 for (TypeSymbolTable::const_iterator TI = ST.begin(), TE = ST.end();
1408 PrintLLVMName(Out, &TI->first[0], TI->first.size(), LocalPrefix);
1411 // Make sure we print out at least one level of the type structure, so
1412 // that we do not get %FILE = type %FILE
1413 TypePrinter.printAtLeastOneLevel(TI->second, Out);
1418 /// printFunction - Print all aspects of a function.
1420 void AssemblyWriter::printFunction(const Function *F) {
1421 // Print out the return type and name.
1424 if (AnnotationWriter) AnnotationWriter->emitFunctionAnnot(F, Out);
1426 if (F->isDeclaration())
1431 PrintLinkage(F->getLinkage(), Out);
1432 PrintVisibility(F->getVisibility(), Out);
1434 // Print the calling convention.
1435 switch (F->getCallingConv()) {
1436 case CallingConv::C: break; // default
1437 case CallingConv::Fast: Out << "fastcc "; break;
1438 case CallingConv::Cold: Out << "coldcc "; break;
1439 case CallingConv::X86_StdCall: Out << "x86_stdcallcc "; break;
1440 case CallingConv::X86_FastCall: Out << "x86_fastcallcc "; break;
1441 case CallingConv::ARM_APCS: Out << "arm_apcscc "; break;
1442 case CallingConv::ARM_AAPCS: Out << "arm_aapcscc "; break;
1443 case CallingConv::ARM_AAPCS_VFP:Out << "arm_aapcs_vfpcc "; break;
1444 default: Out << "cc" << F->getCallingConv() << " "; break;
1447 const FunctionType *FT = F->getFunctionType();
1448 const AttrListPtr &Attrs = F->getAttributes();
1449 Attributes RetAttrs = Attrs.getRetAttributes();
1450 if (RetAttrs != Attribute::None)
1451 Out << Attribute::getAsString(Attrs.getRetAttributes()) << ' ';
1452 TypePrinter.print(F->getReturnType(), Out);
1454 WriteAsOperandInternal(Out, F, TypePrinter, &Machine);
1456 Machine.incorporateFunction(F);
1458 // Loop over the arguments, printing them...
1461 if (!F->isDeclaration()) {
1462 // If this isn't a declaration, print the argument names as well.
1463 for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
1465 // Insert commas as we go... the first arg doesn't get a comma
1466 if (I != F->arg_begin()) Out << ", ";
1467 printArgument(I, Attrs.getParamAttributes(Idx));
1471 // Otherwise, print the types from the function type.
1472 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
1473 // Insert commas as we go... the first arg doesn't get a comma
1477 TypePrinter.print(FT->getParamType(i), Out);
1479 Attributes ArgAttrs = Attrs.getParamAttributes(i+1);
1480 if (ArgAttrs != Attribute::None)
1481 Out << ' ' << Attribute::getAsString(ArgAttrs);
1485 // Finish printing arguments...
1486 if (FT->isVarArg()) {
1487 if (FT->getNumParams()) Out << ", ";
1488 Out << "..."; // Output varargs portion of signature!
1491 Attributes FnAttrs = Attrs.getFnAttributes();
1492 if (FnAttrs != Attribute::None)
1493 Out << ' ' << Attribute::getAsString(Attrs.getFnAttributes());
1494 if (F->hasSection())
1495 Out << " section \"" << F->getSection() << '"';
1496 if (F->getAlignment())
1497 Out << " align " << F->getAlignment();
1499 Out << " gc \"" << F->getGC() << '"';
1500 if (F->isDeclaration()) {
1505 // Output all of its basic blocks... for the function
1506 for (Function::const_iterator I = F->begin(), E = F->end(); I != E; ++I)
1512 Machine.purgeFunction();
1515 /// printArgument - This member is called for every argument that is passed into
1516 /// the function. Simply print it out
1518 void AssemblyWriter::printArgument(const Argument *Arg,
1521 TypePrinter.print(Arg->getType(), Out);
1523 // Output parameter attributes list
1524 if (Attrs != Attribute::None)
1525 Out << ' ' << Attribute::getAsString(Attrs);
1527 // Output name, if available...
1528 if (Arg->hasName()) {
1530 PrintLLVMName(Out, Arg);
1534 /// printBasicBlock - This member is called for each basic block in a method.
1536 void AssemblyWriter::printBasicBlock(const BasicBlock *BB) {
1537 if (BB->hasName()) { // Print out the label if it exists...
1539 PrintLLVMName(Out, BB->getNameStart(), BB->getNameLen(), LabelPrefix);
1541 } else if (!BB->use_empty()) { // Don't print block # of no uses...
1542 Out << "\n; <label>:";
1543 int Slot = Machine.getLocalSlot(BB);
1550 if (BB->getParent() == 0)
1551 Out << "\t\t; Error: Block without parent!";
1552 else if (BB != &BB->getParent()->getEntryBlock()) { // Not the entry block?
1553 // Output predecessors for the block...
1555 pred_const_iterator PI = pred_begin(BB), PE = pred_end(BB);
1558 Out << " No predecessors!";
1561 writeOperand(*PI, false);
1562 for (++PI; PI != PE; ++PI) {
1564 writeOperand(*PI, false);
1571 if (AnnotationWriter) AnnotationWriter->emitBasicBlockStartAnnot(BB, Out);
1573 // Output all of the instructions in the basic block...
1574 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I != E; ++I)
1575 printInstruction(*I);
1577 if (AnnotationWriter) AnnotationWriter->emitBasicBlockEndAnnot(BB, Out);
1581 /// printInfoComment - Print a little comment after the instruction indicating
1582 /// which slot it occupies.
1584 void AssemblyWriter::printInfoComment(const Value &V) {
1585 if (V.getType() != Type::VoidTy) {
1587 TypePrinter.print(V.getType(), Out);
1590 if (!V.hasName() && !isa<Instruction>(V)) {
1592 if (const GlobalValue *GV = dyn_cast<GlobalValue>(&V))
1593 SlotNum = Machine.getGlobalSlot(GV);
1595 SlotNum = Machine.getLocalSlot(&V);
1599 Out << ':' << SlotNum; // Print out the def slot taken.
1601 Out << " [#uses=" << V.getNumUses() << ']'; // Output # uses
1605 // This member is called for each Instruction in a function..
1606 void AssemblyWriter::printInstruction(const Instruction &I) {
1607 if (AnnotationWriter) AnnotationWriter->emitInstructionAnnot(&I, Out);
1611 // Print out name if it exists...
1613 PrintLLVMName(Out, &I);
1615 } else if (I.getType() != Type::VoidTy) {
1616 // Print out the def slot taken.
1617 int SlotNum = Machine.getLocalSlot(&I);
1619 Out << "<badref> = ";
1621 Out << '%' << SlotNum << " = ";
1624 // If this is a volatile load or store, print out the volatile marker.
1625 if ((isa<LoadInst>(I) && cast<LoadInst>(I).isVolatile()) ||
1626 (isa<StoreInst>(I) && cast<StoreInst>(I).isVolatile())) {
1628 } else if (isa<CallInst>(I) && cast<CallInst>(I).isTailCall()) {
1629 // If this is a call, check if it's a tail call.
1633 // Print out the opcode...
1634 Out << I.getOpcodeName();
1636 // Print out the compare instruction predicates
1637 if (const CmpInst *CI = dyn_cast<CmpInst>(&I))
1638 Out << ' ' << getPredicateText(CI->getPredicate());
1640 // Print out the type of the operands...
1641 const Value *Operand = I.getNumOperands() ? I.getOperand(0) : 0;
1643 // Special case conditional branches to swizzle the condition out to the front
1644 if (isa<BranchInst>(I) && cast<BranchInst>(I).isConditional()) {
1645 BranchInst &BI(cast<BranchInst>(I));
1647 writeOperand(BI.getCondition(), true);
1649 writeOperand(BI.getSuccessor(0), true);
1651 writeOperand(BI.getSuccessor(1), true);
1653 } else if (isa<SwitchInst>(I)) {
1654 // Special case switch statement to get formatting nice and correct...
1656 writeOperand(Operand , true);
1658 writeOperand(I.getOperand(1), true);
1661 for (unsigned op = 2, Eop = I.getNumOperands(); op < Eop; op += 2) {
1663 writeOperand(I.getOperand(op ), true);
1665 writeOperand(I.getOperand(op+1), true);
1668 } else if (isa<PHINode>(I)) {
1670 TypePrinter.print(I.getType(), Out);
1673 for (unsigned op = 0, Eop = I.getNumOperands(); op < Eop; op += 2) {
1674 if (op) Out << ", ";
1676 writeOperand(I.getOperand(op ), false); Out << ", ";
1677 writeOperand(I.getOperand(op+1), false); Out << " ]";
1679 } else if (const ExtractValueInst *EVI = dyn_cast<ExtractValueInst>(&I)) {
1681 writeOperand(I.getOperand(0), true);
1682 for (const unsigned *i = EVI->idx_begin(), *e = EVI->idx_end(); i != e; ++i)
1684 } else if (const InsertValueInst *IVI = dyn_cast<InsertValueInst>(&I)) {
1686 writeOperand(I.getOperand(0), true); Out << ", ";
1687 writeOperand(I.getOperand(1), true);
1688 for (const unsigned *i = IVI->idx_begin(), *e = IVI->idx_end(); i != e; ++i)
1690 } else if (isa<ReturnInst>(I) && !Operand) {
1692 } else if (const CallInst *CI = dyn_cast<CallInst>(&I)) {
1693 // Print the calling convention being used.
1694 switch (CI->getCallingConv()) {
1695 case CallingConv::C: break; // default
1696 case CallingConv::Fast: Out << " fastcc"; break;
1697 case CallingConv::Cold: Out << " coldcc"; break;
1698 case CallingConv::X86_StdCall: Out << " x86_stdcallcc"; break;
1699 case CallingConv::X86_FastCall: Out << " x86_fastcallcc"; break;
1700 case CallingConv::ARM_APCS: Out << " arm_apcscc "; break;
1701 case CallingConv::ARM_AAPCS: Out << " arm_aapcscc "; break;
1702 case CallingConv::ARM_AAPCS_VFP:Out << " arm_aapcs_vfpcc "; break;
1703 default: Out << " cc" << CI->getCallingConv(); break;
1706 const PointerType *PTy = cast<PointerType>(Operand->getType());
1707 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
1708 const Type *RetTy = FTy->getReturnType();
1709 const AttrListPtr &PAL = CI->getAttributes();
1711 if (PAL.getRetAttributes() != Attribute::None)
1712 Out << ' ' << Attribute::getAsString(PAL.getRetAttributes());
1714 // If possible, print out the short form of the call instruction. We can
1715 // only do this if the first argument is a pointer to a nonvararg function,
1716 // and if the return type is not a pointer to a function.
1719 if (!FTy->isVarArg() &&
1720 (!isa<PointerType>(RetTy) ||
1721 !isa<FunctionType>(cast<PointerType>(RetTy)->getElementType()))) {
1722 TypePrinter.print(RetTy, Out);
1724 writeOperand(Operand, false);
1726 writeOperand(Operand, true);
1729 for (unsigned op = 1, Eop = I.getNumOperands(); op < Eop; ++op) {
1732 writeParamOperand(I.getOperand(op), PAL.getParamAttributes(op));
1735 if (PAL.getFnAttributes() != Attribute::None)
1736 Out << ' ' << Attribute::getAsString(PAL.getFnAttributes());
1737 } else if (const InvokeInst *II = dyn_cast<InvokeInst>(&I)) {
1738 const PointerType *PTy = cast<PointerType>(Operand->getType());
1739 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
1740 const Type *RetTy = FTy->getReturnType();
1741 const AttrListPtr &PAL = II->getAttributes();
1743 // Print the calling convention being used.
1744 switch (II->getCallingConv()) {
1745 case CallingConv::C: break; // default
1746 case CallingConv::Fast: Out << " fastcc"; break;
1747 case CallingConv::Cold: Out << " coldcc"; break;
1748 case CallingConv::X86_StdCall: Out << " x86_stdcallcc"; break;
1749 case CallingConv::X86_FastCall: Out << " x86_fastcallcc"; break;
1750 case CallingConv::ARM_APCS: Out << " arm_apcscc "; break;
1751 case CallingConv::ARM_AAPCS: Out << " arm_aapcscc "; break;
1752 case CallingConv::ARM_AAPCS_VFP:Out << " arm_aapcs_vfpcc "; break;
1753 default: Out << " cc" << II->getCallingConv(); break;
1756 if (PAL.getRetAttributes() != Attribute::None)
1757 Out << ' ' << Attribute::getAsString(PAL.getRetAttributes());
1759 // If possible, print out the short form of the invoke instruction. We can
1760 // only do this if the first argument is a pointer to a nonvararg function,
1761 // and if the return type is not a pointer to a function.
1764 if (!FTy->isVarArg() &&
1765 (!isa<PointerType>(RetTy) ||
1766 !isa<FunctionType>(cast<PointerType>(RetTy)->getElementType()))) {
1767 TypePrinter.print(RetTy, Out);
1769 writeOperand(Operand, false);
1771 writeOperand(Operand, true);
1774 for (unsigned op = 3, Eop = I.getNumOperands(); op < Eop; ++op) {
1777 writeParamOperand(I.getOperand(op), PAL.getParamAttributes(op-2));
1781 if (PAL.getFnAttributes() != Attribute::None)
1782 Out << ' ' << Attribute::getAsString(PAL.getFnAttributes());
1784 Out << "\n\t\t\tto ";
1785 writeOperand(II->getNormalDest(), true);
1787 writeOperand(II->getUnwindDest(), true);
1789 } else if (const AllocationInst *AI = dyn_cast<AllocationInst>(&I)) {
1791 TypePrinter.print(AI->getType()->getElementType(), Out);
1792 if (AI->isArrayAllocation()) {
1794 writeOperand(AI->getArraySize(), true);
1796 if (AI->getAlignment()) {
1797 Out << ", align " << AI->getAlignment();
1799 } else if (isa<CastInst>(I)) {
1802 writeOperand(Operand, true); // Work with broken code
1805 TypePrinter.print(I.getType(), Out);
1806 } else if (isa<VAArgInst>(I)) {
1809 writeOperand(Operand, true); // Work with broken code
1812 TypePrinter.print(I.getType(), Out);
1813 } else if (Operand) { // Print the normal way.
1815 // PrintAllTypes - Instructions who have operands of all the same type
1816 // omit the type from all but the first operand. If the instruction has
1817 // different type operands (for example br), then they are all printed.
1818 bool PrintAllTypes = false;
1819 const Type *TheType = Operand->getType();
1821 // Select, Store and ShuffleVector always print all types.
1822 if (isa<SelectInst>(I) || isa<StoreInst>(I) || isa<ShuffleVectorInst>(I)
1823 || isa<ReturnInst>(I)) {
1824 PrintAllTypes = true;
1826 for (unsigned i = 1, E = I.getNumOperands(); i != E; ++i) {
1827 Operand = I.getOperand(i);
1828 // note that Operand shouldn't be null, but the test helps make dump()
1829 // more tolerant of malformed IR
1830 if (Operand && Operand->getType() != TheType) {
1831 PrintAllTypes = true; // We have differing types! Print them all!
1837 if (!PrintAllTypes) {
1839 TypePrinter.print(TheType, Out);
1843 for (unsigned i = 0, E = I.getNumOperands(); i != E; ++i) {
1845 writeOperand(I.getOperand(i), PrintAllTypes);
1849 // Print post operand alignment for load/store
1850 if (isa<LoadInst>(I) && cast<LoadInst>(I).getAlignment()) {
1851 Out << ", align " << cast<LoadInst>(I).getAlignment();
1852 } else if (isa<StoreInst>(I) && cast<StoreInst>(I).getAlignment()) {
1853 Out << ", align " << cast<StoreInst>(I).getAlignment();
1856 printInfoComment(I);
1861 //===----------------------------------------------------------------------===//
1862 // External Interface declarations
1863 //===----------------------------------------------------------------------===//
1865 void Module::print(std::ostream &o, AssemblyAnnotationWriter *AAW) const {
1866 raw_os_ostream OS(o);
1869 void Module::print(raw_ostream &OS, AssemblyAnnotationWriter *AAW) const {
1870 SlotTracker SlotTable(this);
1871 AssemblyWriter W(OS, SlotTable, this, AAW);
1875 void Type::print(std::ostream &o) const {
1876 raw_os_ostream OS(o);
1880 void Type::print(raw_ostream &OS) const {
1882 OS << "<null Type>";
1885 TypePrinting().print(this, OS);
1888 void Value::print(raw_ostream &OS, AssemblyAnnotationWriter *AAW) const {
1890 OS << "printing a <null> value\n";
1894 if (const Instruction *I = dyn_cast<Instruction>(this)) {
1895 const Function *F = I->getParent() ? I->getParent()->getParent() : 0;
1896 SlotTracker SlotTable(F);
1897 AssemblyWriter W(OS, SlotTable, F ? F->getParent() : 0, AAW);
1899 } else if (const BasicBlock *BB = dyn_cast<BasicBlock>(this)) {
1900 SlotTracker SlotTable(BB->getParent());
1901 AssemblyWriter W(OS, SlotTable,
1902 BB->getParent() ? BB->getParent()->getParent() : 0, AAW);
1904 } else if (const GlobalValue *GV = dyn_cast<GlobalValue>(this)) {
1905 SlotTracker SlotTable(GV->getParent());
1906 AssemblyWriter W(OS, SlotTable, GV->getParent(), AAW);
1908 } else if (const MDNode *N = dyn_cast<MDNode>(this)) {
1909 TypePrinting TypePrinter;
1910 TypePrinter.print(N->getType(), OS);
1912 // FIXME: Do we need a slot tracker for metadata ?
1913 SlotTracker SlotTable((const Function *)NULL);
1914 AssemblyWriter W(OS, SlotTable, NULL, AAW);
1915 W.printMDNode(N, false);
1916 } else if (const Constant *C = dyn_cast<Constant>(this)) {
1917 TypePrinting TypePrinter;
1918 TypePrinter.print(C->getType(), OS);
1920 WriteConstantInt(OS, C, TypePrinter, 0);
1921 } else if (const Argument *A = dyn_cast<Argument>(this)) {
1922 WriteAsOperand(OS, this, true,
1923 A->getParent() ? A->getParent()->getParent() : 0);
1924 } else if (isa<InlineAsm>(this)) {
1925 WriteAsOperand(OS, this, true, 0);
1927 assert(0 && "Unknown value to print out!");
1931 void Value::print(std::ostream &O, AssemblyAnnotationWriter *AAW) const {
1932 raw_os_ostream OS(O);
1936 // Value::dump - allow easy printing of Values from the debugger.
1937 void Value::dump() const { print(errs()); errs() << '\n'; }
1939 // Type::dump - allow easy printing of Types from the debugger.
1940 // This one uses type names from the given context module
1941 void Type::dump(const Module *Context) const {
1942 WriteTypeSymbolic(errs(), this, Context);
1946 // Type::dump - allow easy printing of Types from the debugger.
1947 void Type::dump() const { dump(0); }
1949 // Module::dump() - Allow printing of Modules from the debugger.
1950 void Module::dump() const { print(errs(), 0); }