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/Operator.h"
27 #include "llvm/MDNode.h"
28 #include "llvm/Module.h"
29 #include "llvm/ValueSymbolTable.h"
30 #include "llvm/TypeSymbolTable.h"
31 #include "llvm/ADT/DenseSet.h"
32 #include "llvm/ADT/StringExtras.h"
33 #include "llvm/ADT/STLExtras.h"
34 #include "llvm/Support/CFG.h"
35 #include "llvm/Support/ErrorHandling.h"
36 #include "llvm/Support/MathExtras.h"
37 #include "llvm/Support/Streams.h"
38 #include "llvm/Support/raw_ostream.h"
44 // Make virtual table appear in this compilation unit.
45 AssemblyAnnotationWriter::~AssemblyAnnotationWriter() {}
47 //===----------------------------------------------------------------------===//
49 //===----------------------------------------------------------------------===//
51 static const Module *getModuleFromVal(const Value *V) {
52 if (const Argument *MA = dyn_cast<Argument>(V))
53 return MA->getParent() ? MA->getParent()->getParent() : 0;
55 if (const BasicBlock *BB = dyn_cast<BasicBlock>(V))
56 return BB->getParent() ? BB->getParent()->getParent() : 0;
58 if (const Instruction *I = dyn_cast<Instruction>(V)) {
59 const Function *M = I->getParent() ? I->getParent()->getParent() : 0;
60 return M ? M->getParent() : 0;
63 if (const GlobalValue *GV = dyn_cast<GlobalValue>(V))
64 return GV->getParent();
68 // PrintEscapedString - Print each character of the specified string, escaping
69 // it if it is not printable or if it is an escape char.
70 static void PrintEscapedString(const char *Str, unsigned Length,
72 for (unsigned i = 0; i != Length; ++i) {
73 unsigned char C = Str[i];
74 if (isprint(C) && C != '\\' && C != '"')
77 Out << '\\' << hexdigit(C >> 4) << hexdigit(C & 0x0F);
81 // PrintEscapedString - Print each character of the specified string, escaping
82 // it if it is not printable or if it is an escape char.
83 static void PrintEscapedString(const std::string &Str, raw_ostream &Out) {
84 PrintEscapedString(Str.c_str(), Str.size(), Out);
94 /// PrintLLVMName - Turn the specified name into an 'LLVM name', which is either
95 /// prefixed with % (if the string only contains simple characters) or is
96 /// surrounded with ""'s (if it has special chars in it). Print it out.
97 static void PrintLLVMName(raw_ostream &OS, const char *NameStr,
98 unsigned NameLen, PrefixType Prefix) {
99 assert(NameStr && "Cannot get empty name!");
101 default: llvm_unreachable("Bad prefix!");
102 case NoPrefix: break;
103 case GlobalPrefix: OS << '@'; break;
104 case LabelPrefix: break;
105 case LocalPrefix: OS << '%'; break;
108 // Scan the name to see if it needs quotes first.
109 bool NeedsQuotes = isdigit(NameStr[0]);
111 for (unsigned i = 0; i != NameLen; ++i) {
113 if (!isalnum(C) && C != '-' && C != '.' && C != '_') {
120 // If we didn't need any quotes, just write out the name in one blast.
122 OS.write(NameStr, NameLen);
126 // Okay, we need quotes. Output the quotes and escape any scary characters as
129 PrintEscapedString(NameStr, NameLen, OS);
133 /// PrintLLVMName - Turn the specified name into an 'LLVM name', which is either
134 /// prefixed with % (if the string only contains simple characters) or is
135 /// surrounded with ""'s (if it has special chars in it). Print it out.
136 static void PrintLLVMName(raw_ostream &OS, const Value *V) {
137 PrintLLVMName(OS, V->getNameStart(), V->getNameLen(),
138 isa<GlobalValue>(V) ? GlobalPrefix : LocalPrefix);
141 //===----------------------------------------------------------------------===//
142 // TypePrinting Class: Type printing machinery
143 //===----------------------------------------------------------------------===//
145 static DenseMap<const Type *, std::string> &getTypeNamesMap(void *M) {
146 return *static_cast<DenseMap<const Type *, std::string>*>(M);
149 void TypePrinting::clear() {
150 getTypeNamesMap(TypeNames).clear();
153 bool TypePrinting::hasTypeName(const Type *Ty) const {
154 return getTypeNamesMap(TypeNames).count(Ty);
157 void TypePrinting::addTypeName(const Type *Ty, const std::string &N) {
158 getTypeNamesMap(TypeNames).insert(std::make_pair(Ty, N));
162 TypePrinting::TypePrinting() {
163 TypeNames = new DenseMap<const Type *, std::string>();
166 TypePrinting::~TypePrinting() {
167 delete &getTypeNamesMap(TypeNames);
170 /// CalcTypeName - Write the specified type to the specified raw_ostream, making
171 /// use of type names or up references to shorten the type name where possible.
172 void TypePrinting::CalcTypeName(const Type *Ty,
173 SmallVectorImpl<const Type *> &TypeStack,
174 raw_ostream &OS, bool IgnoreTopLevelName) {
175 // Check to see if the type is named.
176 if (!IgnoreTopLevelName) {
177 DenseMap<const Type *, std::string> &TM = getTypeNamesMap(TypeNames);
178 DenseMap<const Type *, std::string>::iterator I = TM.find(Ty);
185 // Check to see if the Type is already on the stack...
186 unsigned Slot = 0, CurSize = TypeStack.size();
187 while (Slot < CurSize && TypeStack[Slot] != Ty) ++Slot; // Scan for type
189 // This is another base case for the recursion. In this case, we know
190 // that we have looped back to a type that we have previously visited.
191 // Generate the appropriate upreference to handle this.
192 if (Slot < CurSize) {
193 OS << '\\' << unsigned(CurSize-Slot); // Here's the upreference
197 TypeStack.push_back(Ty); // Recursive case: Add us to the stack..
199 switch (Ty->getTypeID()) {
200 case Type::VoidTyID: OS << "void"; break;
201 case Type::FloatTyID: OS << "float"; break;
202 case Type::DoubleTyID: OS << "double"; break;
203 case Type::X86_FP80TyID: OS << "x86_fp80"; break;
204 case Type::FP128TyID: OS << "fp128"; break;
205 case Type::PPC_FP128TyID: OS << "ppc_fp128"; break;
206 case Type::LabelTyID: OS << "label"; break;
207 case Type::MetadataTyID: OS << "metadata"; break;
208 case Type::IntegerTyID:
209 OS << 'i' << cast<IntegerType>(Ty)->getBitWidth();
212 case Type::FunctionTyID: {
213 const FunctionType *FTy = cast<FunctionType>(Ty);
214 CalcTypeName(FTy->getReturnType(), TypeStack, OS);
216 for (FunctionType::param_iterator I = FTy->param_begin(),
217 E = FTy->param_end(); I != E; ++I) {
218 if (I != FTy->param_begin())
220 CalcTypeName(*I, TypeStack, OS);
222 if (FTy->isVarArg()) {
223 if (FTy->getNumParams()) OS << ", ";
229 case Type::StructTyID: {
230 const StructType *STy = cast<StructType>(Ty);
234 for (StructType::element_iterator I = STy->element_begin(),
235 E = STy->element_end(); I != E; ++I) {
236 CalcTypeName(*I, TypeStack, OS);
237 if (next(I) != STy->element_end())
246 case Type::PointerTyID: {
247 const PointerType *PTy = cast<PointerType>(Ty);
248 CalcTypeName(PTy->getElementType(), TypeStack, OS);
249 if (unsigned AddressSpace = PTy->getAddressSpace())
250 OS << " addrspace(" << AddressSpace << ')';
254 case Type::ArrayTyID: {
255 const ArrayType *ATy = cast<ArrayType>(Ty);
256 OS << '[' << ATy->getNumElements() << " x ";
257 CalcTypeName(ATy->getElementType(), TypeStack, OS);
261 case Type::VectorTyID: {
262 const VectorType *PTy = cast<VectorType>(Ty);
263 OS << "<" << PTy->getNumElements() << " x ";
264 CalcTypeName(PTy->getElementType(), TypeStack, OS);
268 case Type::OpaqueTyID:
272 OS << "<unrecognized-type>";
276 TypeStack.pop_back(); // Remove self from stack.
279 /// printTypeInt - The internal guts of printing out a type that has a
280 /// potentially named portion.
282 void TypePrinting::print(const Type *Ty, raw_ostream &OS,
283 bool IgnoreTopLevelName) {
284 // Check to see if the type is named.
285 DenseMap<const Type*, std::string> &TM = getTypeNamesMap(TypeNames);
286 if (!IgnoreTopLevelName) {
287 DenseMap<const Type*, std::string>::iterator I = TM.find(Ty);
294 // Otherwise we have a type that has not been named but is a derived type.
295 // Carefully recurse the type hierarchy to print out any contained symbolic
297 SmallVector<const Type *, 16> TypeStack;
298 std::string TypeName;
300 raw_string_ostream TypeOS(TypeName);
301 CalcTypeName(Ty, TypeStack, TypeOS, IgnoreTopLevelName);
304 // Cache type name for later use.
305 if (!IgnoreTopLevelName)
306 TM.insert(std::make_pair(Ty, TypeOS.str()));
311 // To avoid walking constant expressions multiple times and other IR
312 // objects, we keep several helper maps.
313 DenseSet<const Value*> VisitedConstants;
314 DenseSet<const Type*> VisitedTypes;
317 std::vector<const Type*> &NumberedTypes;
319 TypeFinder(TypePrinting &tp, std::vector<const Type*> &numberedTypes)
320 : TP(tp), NumberedTypes(numberedTypes) {}
322 void Run(const Module &M) {
323 // Get types from the type symbol table. This gets opaque types referened
324 // only through derived named types.
325 const TypeSymbolTable &ST = M.getTypeSymbolTable();
326 for (TypeSymbolTable::const_iterator TI = ST.begin(), E = ST.end();
328 IncorporateType(TI->second);
330 // Get types from global variables.
331 for (Module::const_global_iterator I = M.global_begin(),
332 E = M.global_end(); I != E; ++I) {
333 IncorporateType(I->getType());
334 if (I->hasInitializer())
335 IncorporateValue(I->getInitializer());
338 // Get types from aliases.
339 for (Module::const_alias_iterator I = M.alias_begin(),
340 E = M.alias_end(); I != E; ++I) {
341 IncorporateType(I->getType());
342 IncorporateValue(I->getAliasee());
345 // Get types from functions.
346 for (Module::const_iterator FI = M.begin(), E = M.end(); FI != E; ++FI) {
347 IncorporateType(FI->getType());
349 for (Function::const_iterator BB = FI->begin(), E = FI->end();
351 for (BasicBlock::const_iterator II = BB->begin(),
352 E = BB->end(); II != E; ++II) {
353 const Instruction &I = *II;
354 // Incorporate the type of the instruction and all its operands.
355 IncorporateType(I.getType());
356 for (User::const_op_iterator OI = I.op_begin(), OE = I.op_end();
358 IncorporateValue(*OI);
364 void IncorporateType(const Type *Ty) {
365 // Check to see if we're already visited this type.
366 if (!VisitedTypes.insert(Ty).second)
369 // If this is a structure or opaque type, add a name for the type.
370 if (((isa<StructType>(Ty) && cast<StructType>(Ty)->getNumElements())
371 || isa<OpaqueType>(Ty)) && !TP.hasTypeName(Ty)) {
372 TP.addTypeName(Ty, "%"+utostr(unsigned(NumberedTypes.size())));
373 NumberedTypes.push_back(Ty);
376 // Recursively walk all contained types.
377 for (Type::subtype_iterator I = Ty->subtype_begin(),
378 E = Ty->subtype_end(); I != E; ++I)
382 /// IncorporateValue - This method is used to walk operand lists finding
383 /// types hiding in constant expressions and other operands that won't be
384 /// walked in other ways. GlobalValues, basic blocks, instructions, and
385 /// inst operands are all explicitly enumerated.
386 void IncorporateValue(const Value *V) {
387 if (V == 0 || !isa<Constant>(V) || isa<GlobalValue>(V)) return;
390 if (!VisitedConstants.insert(V).second)
394 IncorporateType(V->getType());
396 // Look in operands for types.
397 const Constant *C = cast<Constant>(V);
398 for (Constant::const_op_iterator I = C->op_begin(),
399 E = C->op_end(); I != E;++I)
400 IncorporateValue(*I);
403 } // end anonymous namespace
406 /// AddModuleTypesToPrinter - Add all of the symbolic type names for types in
407 /// the specified module to the TypePrinter and all numbered types to it and the
408 /// NumberedTypes table.
409 static void AddModuleTypesToPrinter(TypePrinting &TP,
410 std::vector<const Type*> &NumberedTypes,
414 // If the module has a symbol table, take all global types and stuff their
415 // names into the TypeNames map.
416 const TypeSymbolTable &ST = M->getTypeSymbolTable();
417 for (TypeSymbolTable::const_iterator TI = ST.begin(), E = ST.end();
419 const Type *Ty = cast<Type>(TI->second);
421 // As a heuristic, don't insert pointer to primitive types, because
422 // they are used too often to have a single useful name.
423 if (const PointerType *PTy = dyn_cast<PointerType>(Ty)) {
424 const Type *PETy = PTy->getElementType();
425 if ((PETy->isPrimitiveType() || PETy->isInteger()) &&
426 !isa<OpaqueType>(PETy))
430 // Likewise don't insert primitives either.
431 if (Ty->isInteger() || Ty->isPrimitiveType())
434 // Get the name as a string and insert it into TypeNames.
436 raw_string_ostream NameOS(NameStr);
437 PrintLLVMName(NameOS, TI->first.c_str(), TI->first.length(), LocalPrefix);
438 TP.addTypeName(Ty, NameOS.str());
441 // Walk the entire module to find references to unnamed structure and opaque
442 // types. This is required for correctness by opaque types (because multiple
443 // uses of an unnamed opaque type needs to be referred to by the same ID) and
444 // it shrinks complex recursive structure types substantially in some cases.
445 TypeFinder(TP, NumberedTypes).Run(*M);
449 /// WriteTypeSymbolic - This attempts to write the specified type as a symbolic
450 /// type, iff there is an entry in the modules symbol table for the specified
451 /// type or one of it's component types.
453 void llvm::WriteTypeSymbolic(raw_ostream &OS, const Type *Ty, const Module *M) {
454 TypePrinting Printer;
455 std::vector<const Type*> NumberedTypes;
456 AddModuleTypesToPrinter(Printer, NumberedTypes, M);
457 Printer.print(Ty, OS);
460 //===----------------------------------------------------------------------===//
461 // SlotTracker Class: Enumerate slot numbers for unnamed values
462 //===----------------------------------------------------------------------===//
466 /// This class provides computation of slot numbers for LLVM Assembly writing.
470 /// ValueMap - A mapping of Values to slot numbers.
471 typedef DenseMap<const Value*, unsigned> ValueMap;
474 /// TheModule - The module for which we are holding slot numbers.
475 const Module* TheModule;
477 /// TheFunction - The function for which we are holding slot numbers.
478 const Function* TheFunction;
479 bool FunctionProcessed;
481 /// TheMDNode - The MDNode for which we are holding slot numbers.
482 const MDNode *TheMDNode;
484 /// mMap - The TypePlanes map for the module level data.
488 /// fMap - The TypePlanes map for the function level data.
492 /// mdnMap - Map for MDNodes.
496 /// Construct from a module
497 explicit SlotTracker(const Module *M);
498 /// Construct from a function, starting out in incorp state.
499 explicit SlotTracker(const Function *F);
500 /// Construct from a mdnode.
501 explicit SlotTracker(const MDNode *N);
503 /// Return the slot number of the specified value in it's type
504 /// plane. If something is not in the SlotTracker, return -1.
505 int getLocalSlot(const Value *V);
506 int getGlobalSlot(const GlobalValue *V);
507 int getMetadataSlot(const MDNode *N);
509 /// If you'd like to deal with a function instead of just a module, use
510 /// this method to get its data into the SlotTracker.
511 void incorporateFunction(const Function *F) {
513 FunctionProcessed = false;
516 /// After calling incorporateFunction, use this method to remove the
517 /// most recently incorporated function from the SlotTracker. This
518 /// will reset the state of the machine back to just the module contents.
519 void purgeFunction();
521 /// MDNode map iterators.
522 ValueMap::iterator mdnBegin() { return mdnMap.begin(); }
523 ValueMap::iterator mdnEnd() { return mdnMap.end(); }
524 unsigned mdnSize() { return mdnMap.size(); }
526 /// This function does the actual initialization.
527 inline void initialize();
529 // Implementation Details
531 /// CreateModuleSlot - Insert the specified GlobalValue* into the slot table.
532 void CreateModuleSlot(const GlobalValue *V);
534 /// CreateMetadataSlot - Insert the specified MDNode* into the slot table.
535 void CreateMetadataSlot(const MDNode *N);
537 /// CreateFunctionSlot - Insert the specified Value* into the slot table.
538 void CreateFunctionSlot(const Value *V);
540 /// Add all of the module level global variables (and their initializers)
541 /// and function declarations, but not the contents of those functions.
542 void processModule();
544 /// Add all of the functions arguments, basic blocks, and instructions.
545 void processFunction();
547 /// Add all MDNode operands.
548 void processMDNode();
550 SlotTracker(const SlotTracker &); // DO NOT IMPLEMENT
551 void operator=(const SlotTracker &); // DO NOT IMPLEMENT
554 } // end anonymous namespace
557 static SlotTracker *createSlotTracker(const Value *V) {
558 if (const Argument *FA = dyn_cast<Argument>(V))
559 return new SlotTracker(FA->getParent());
561 if (const Instruction *I = dyn_cast<Instruction>(V))
562 return new SlotTracker(I->getParent()->getParent());
564 if (const BasicBlock *BB = dyn_cast<BasicBlock>(V))
565 return new SlotTracker(BB->getParent());
567 if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(V))
568 return new SlotTracker(GV->getParent());
570 if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(V))
571 return new SlotTracker(GA->getParent());
573 if (const Function *Func = dyn_cast<Function>(V))
574 return new SlotTracker(Func);
580 #define ST_DEBUG(X) cerr << X
585 // Module level constructor. Causes the contents of the Module (sans functions)
586 // to be added to the slot table.
587 SlotTracker::SlotTracker(const Module *M)
588 : TheModule(M), TheFunction(0), FunctionProcessed(false), TheMDNode(0),
589 mNext(0), fNext(0), mdnNext(0) {
592 // Function level constructor. Causes the contents of the Module and the one
593 // function provided to be added to the slot table.
594 SlotTracker::SlotTracker(const Function *F)
595 : TheModule(F ? F->getParent() : 0), TheFunction(F), FunctionProcessed(false),
596 TheMDNode(0), mNext(0), fNext(0) {
599 // Constructor to handle single MDNode.
600 SlotTracker::SlotTracker(const MDNode *C)
601 : TheModule(0), TheFunction(0), FunctionProcessed(false), TheMDNode(C),
602 mNext(0), fNext(0), mdnNext(0) {
605 inline void SlotTracker::initialize() {
608 TheModule = 0; ///< Prevent re-processing next time we're called.
611 if (TheFunction && !FunctionProcessed)
618 // Iterate through all the global variables, functions, and global
619 // variable initializers and create slots for them.
620 void SlotTracker::processModule() {
621 ST_DEBUG("begin processModule!\n");
623 // Add all of the unnamed global variables to the value table.
624 for (Module::const_global_iterator I = TheModule->global_begin(),
625 E = TheModule->global_end(); I != E; ++I) {
628 if (I->hasInitializer()) {
629 if (MDNode *N = dyn_cast<MDNode>(I->getInitializer()))
630 CreateMetadataSlot(N);
634 // Add all the unnamed functions to the table.
635 for (Module::const_iterator I = TheModule->begin(), E = TheModule->end();
640 ST_DEBUG("end processModule!\n");
643 // Process the arguments, basic blocks, and instructions of a function.
644 void SlotTracker::processFunction() {
645 ST_DEBUG("begin processFunction!\n");
648 // Add all the function arguments with no names.
649 for(Function::const_arg_iterator AI = TheFunction->arg_begin(),
650 AE = TheFunction->arg_end(); AI != AE; ++AI)
652 CreateFunctionSlot(AI);
654 ST_DEBUG("Inserting Instructions:\n");
656 // Add all of the basic blocks and instructions with no names.
657 for (Function::const_iterator BB = TheFunction->begin(),
658 E = TheFunction->end(); BB != E; ++BB) {
660 CreateFunctionSlot(BB);
661 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I != E;
663 if (I->getType() != Type::VoidTy && !I->hasName())
664 CreateFunctionSlot(I);
665 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
666 if (MDNode *N = dyn_cast<MDNode>(I->getOperand(i)))
667 CreateMetadataSlot(N);
671 FunctionProcessed = true;
673 ST_DEBUG("end processFunction!\n");
676 /// processMDNode - Process TheMDNode.
677 void SlotTracker::processMDNode() {
678 ST_DEBUG("begin processMDNode!\n");
680 CreateMetadataSlot(TheMDNode);
682 ST_DEBUG("end processMDNode!\n");
685 /// Clean up after incorporating a function. This is the only way to get out of
686 /// the function incorporation state that affects get*Slot/Create*Slot. Function
687 /// incorporation state is indicated by TheFunction != 0.
688 void SlotTracker::purgeFunction() {
689 ST_DEBUG("begin purgeFunction!\n");
690 fMap.clear(); // Simply discard the function level map
692 FunctionProcessed = false;
693 ST_DEBUG("end purgeFunction!\n");
696 /// getGlobalSlot - Get the slot number of a global value.
697 int SlotTracker::getGlobalSlot(const GlobalValue *V) {
698 // Check for uninitialized state and do lazy initialization.
701 // Find the type plane in the module map
702 ValueMap::iterator MI = mMap.find(V);
703 return MI == mMap.end() ? -1 : (int)MI->second;
706 /// getGlobalSlot - Get the slot number of a MDNode.
707 int SlotTracker::getMetadataSlot(const MDNode *N) {
708 // Check for uninitialized state and do lazy initialization.
711 // Find the type plane in the module map
712 ValueMap::iterator MI = mdnMap.find(N);
713 return MI == mdnMap.end() ? -1 : (int)MI->second;
717 /// getLocalSlot - Get the slot number for a value that is local to a function.
718 int SlotTracker::getLocalSlot(const Value *V) {
719 assert(!isa<Constant>(V) && "Can't get a constant or global slot with this!");
721 // Check for uninitialized state and do lazy initialization.
724 ValueMap::iterator FI = fMap.find(V);
725 return FI == fMap.end() ? -1 : (int)FI->second;
729 /// CreateModuleSlot - Insert the specified GlobalValue* into the slot table.
730 void SlotTracker::CreateModuleSlot(const GlobalValue *V) {
731 assert(V && "Can't insert a null Value into SlotTracker!");
732 assert(V->getType() != Type::VoidTy && "Doesn't need a slot!");
733 assert(!V->hasName() && "Doesn't need a slot!");
735 unsigned DestSlot = mNext++;
738 ST_DEBUG(" Inserting value [" << V->getType() << "] = " << V << " slot=" <<
740 // G = Global, F = Function, A = Alias, o = other
741 ST_DEBUG((isa<GlobalVariable>(V) ? 'G' :
742 (isa<Function>(V) ? 'F' :
743 (isa<GlobalAlias>(V) ? 'A' : 'o'))) << "]\n");
746 /// CreateSlot - Create a new slot for the specified value if it has no name.
747 void SlotTracker::CreateFunctionSlot(const Value *V) {
748 assert(V->getType() != Type::VoidTy && !V->hasName() &&
749 "Doesn't need a slot!");
751 unsigned DestSlot = fNext++;
754 // G = Global, F = Function, o = other
755 ST_DEBUG(" Inserting value [" << V->getType() << "] = " << V << " slot=" <<
756 DestSlot << " [o]\n");
759 /// CreateModuleSlot - Insert the specified MDNode* into the slot table.
760 void SlotTracker::CreateMetadataSlot(const MDNode *N) {
761 assert(N && "Can't insert a null Value into SlotTracker!");
763 ValueMap::iterator I = mdnMap.find(N);
764 if (I != mdnMap.end())
767 unsigned DestSlot = mdnNext++;
768 mdnMap[N] = DestSlot;
770 for (MDNode::const_elem_iterator MDI = N->elem_begin(),
771 MDE = N->elem_end(); MDI != MDE; ++MDI) {
772 const Value *TV = *MDI;
774 if (const MDNode *N2 = dyn_cast<MDNode>(TV))
775 CreateMetadataSlot(N2);
779 //===----------------------------------------------------------------------===//
780 // AsmWriter Implementation
781 //===----------------------------------------------------------------------===//
783 static void WriteAsOperandInternal(raw_ostream &Out, const Value *V,
784 TypePrinting &TypePrinter,
785 SlotTracker *Machine);
789 static const char *getPredicateText(unsigned predicate) {
790 const char * pred = "unknown";
792 case FCmpInst::FCMP_FALSE: pred = "false"; break;
793 case FCmpInst::FCMP_OEQ: pred = "oeq"; break;
794 case FCmpInst::FCMP_OGT: pred = "ogt"; break;
795 case FCmpInst::FCMP_OGE: pred = "oge"; break;
796 case FCmpInst::FCMP_OLT: pred = "olt"; break;
797 case FCmpInst::FCMP_OLE: pred = "ole"; break;
798 case FCmpInst::FCMP_ONE: pred = "one"; break;
799 case FCmpInst::FCMP_ORD: pred = "ord"; break;
800 case FCmpInst::FCMP_UNO: pred = "uno"; break;
801 case FCmpInst::FCMP_UEQ: pred = "ueq"; break;
802 case FCmpInst::FCMP_UGT: pred = "ugt"; break;
803 case FCmpInst::FCMP_UGE: pred = "uge"; break;
804 case FCmpInst::FCMP_ULT: pred = "ult"; break;
805 case FCmpInst::FCMP_ULE: pred = "ule"; break;
806 case FCmpInst::FCMP_UNE: pred = "une"; break;
807 case FCmpInst::FCMP_TRUE: pred = "true"; break;
808 case ICmpInst::ICMP_EQ: pred = "eq"; break;
809 case ICmpInst::ICMP_NE: pred = "ne"; break;
810 case ICmpInst::ICMP_SGT: pred = "sgt"; break;
811 case ICmpInst::ICMP_SGE: pred = "sge"; break;
812 case ICmpInst::ICMP_SLT: pred = "slt"; break;
813 case ICmpInst::ICMP_SLE: pred = "sle"; break;
814 case ICmpInst::ICMP_UGT: pred = "ugt"; break;
815 case ICmpInst::ICMP_UGE: pred = "uge"; break;
816 case ICmpInst::ICMP_ULT: pred = "ult"; break;
817 case ICmpInst::ICMP_ULE: pred = "ule"; break;
822 static void WriteMDNodes(raw_ostream &Out, TypePrinting &TypePrinter,
823 SlotTracker &Machine) {
824 SmallVector<const MDNode *, 16> Nodes;
825 Nodes.resize(Machine.mdnSize());
826 for (SlotTracker::ValueMap::iterator I =
827 Machine.mdnBegin(), E = Machine.mdnEnd(); I != E; ++I)
828 Nodes[I->second] = cast<MDNode>(I->first);
830 for (unsigned i = 0, e = Nodes.size(); i != e; ++i) {
831 Out << '!' << i << " = metadata ";
832 const MDNode *Node = Nodes[i];
834 for (MDNode::const_elem_iterator NI = Node->elem_begin(),
835 NE = Node->elem_end(); NI != NE;) {
836 const Value *V = *NI;
839 else if (const MDNode *N = dyn_cast<MDNode>(V)) {
841 Out << '!' << Machine.getMetadataSlot(N);
844 TypePrinter.print((*NI)->getType(), Out);
846 WriteAsOperandInternal(Out, *NI, TypePrinter, &Machine);
855 static void WriteOptimizationInfo(raw_ostream &Out, const User *U) {
856 if (const OverflowingBinaryOperator *OBO =
857 dyn_cast<OverflowingBinaryOperator>(U)) {
858 if (OBO->hasNoUnsignedOverflow())
860 if (OBO->hasNoSignedOverflow())
862 } else if (const SDivOperator *Div = dyn_cast<SDivOperator>(U)) {
868 static void WriteConstantInt(raw_ostream &Out, const Constant *CV,
869 TypePrinting &TypePrinter, SlotTracker *Machine) {
870 if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV)) {
871 if (CI->getType() == Type::Int1Ty) {
872 Out << (CI->getZExtValue() ? "true" : "false");
875 Out << CI->getValue();
879 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CV)) {
880 if (&CFP->getValueAPF().getSemantics() == &APFloat::IEEEdouble ||
881 &CFP->getValueAPF().getSemantics() == &APFloat::IEEEsingle) {
882 // We would like to output the FP constant value in exponential notation,
883 // but we cannot do this if doing so will lose precision. Check here to
884 // make sure that we only output it in exponential format if we can parse
885 // the value back and get the same value.
888 bool isDouble = &CFP->getValueAPF().getSemantics()==&APFloat::IEEEdouble;
889 double Val = isDouble ? CFP->getValueAPF().convertToDouble() :
890 CFP->getValueAPF().convertToFloat();
891 std::string StrVal = ftostr(CFP->getValueAPF());
893 // Check to make sure that the stringized number is not some string like
894 // "Inf" or NaN, that atof will accept, but the lexer will not. Check
895 // that the string matches the "[-+]?[0-9]" regex.
897 if ((StrVal[0] >= '0' && StrVal[0] <= '9') ||
898 ((StrVal[0] == '-' || StrVal[0] == '+') &&
899 (StrVal[1] >= '0' && StrVal[1] <= '9'))) {
900 // Reparse stringized version!
901 if (atof(StrVal.c_str()) == Val) {
906 // Otherwise we could not reparse it to exactly the same value, so we must
907 // output the string in hexadecimal format! Note that loading and storing
908 // floating point types changes the bits of NaNs on some hosts, notably
909 // x86, so we must not use these types.
910 assert(sizeof(double) == sizeof(uint64_t) &&
911 "assuming that double is 64 bits!");
913 APFloat apf = CFP->getValueAPF();
914 // Floats are represented in ASCII IR as double, convert.
916 apf.convert(APFloat::IEEEdouble, APFloat::rmNearestTiesToEven,
919 utohex_buffer(uint64_t(apf.bitcastToAPInt().getZExtValue()),
924 // Some form of long double. These appear as a magic letter identifying
925 // the type, then a fixed number of hex digits.
927 if (&CFP->getValueAPF().getSemantics() == &APFloat::x87DoubleExtended) {
929 // api needed to prevent premature destruction
930 APInt api = CFP->getValueAPF().bitcastToAPInt();
931 const uint64_t* p = api.getRawData();
932 uint64_t word = p[1];
934 int width = api.getBitWidth();
935 for (int j=0; j<width; j+=4, shiftcount-=4) {
936 unsigned int nibble = (word>>shiftcount) & 15;
938 Out << (unsigned char)(nibble + '0');
940 Out << (unsigned char)(nibble - 10 + 'A');
941 if (shiftcount == 0 && j+4 < width) {
945 shiftcount = width-j-4;
949 } else if (&CFP->getValueAPF().getSemantics() == &APFloat::IEEEquad)
951 else if (&CFP->getValueAPF().getSemantics() == &APFloat::PPCDoubleDouble)
954 llvm_unreachable("Unsupported floating point type");
955 // api needed to prevent premature destruction
956 APInt api = CFP->getValueAPF().bitcastToAPInt();
957 const uint64_t* p = api.getRawData();
960 int width = api.getBitWidth();
961 for (int j=0; j<width; j+=4, shiftcount-=4) {
962 unsigned int nibble = (word>>shiftcount) & 15;
964 Out << (unsigned char)(nibble + '0');
966 Out << (unsigned char)(nibble - 10 + 'A');
967 if (shiftcount == 0 && j+4 < width) {
971 shiftcount = width-j-4;
977 if (isa<ConstantAggregateZero>(CV)) {
978 Out << "zeroinitializer";
982 if (const ConstantArray *CA = dyn_cast<ConstantArray>(CV)) {
983 // As a special case, print the array as a string if it is an array of
984 // i8 with ConstantInt values.
986 const Type *ETy = CA->getType()->getElementType();
987 if (CA->isString()) {
989 PrintEscapedString(CA->getAsString(), Out);
991 } else { // Cannot output in string format...
993 if (CA->getNumOperands()) {
994 TypePrinter.print(ETy, Out);
996 WriteAsOperandInternal(Out, CA->getOperand(0),
997 TypePrinter, Machine);
998 for (unsigned i = 1, e = CA->getNumOperands(); i != e; ++i) {
1000 TypePrinter.print(ETy, Out);
1002 WriteAsOperandInternal(Out, CA->getOperand(i), TypePrinter, Machine);
1010 if (const ConstantStruct *CS = dyn_cast<ConstantStruct>(CV)) {
1011 if (CS->getType()->isPacked())
1014 unsigned N = CS->getNumOperands();
1017 TypePrinter.print(CS->getOperand(0)->getType(), Out);
1020 WriteAsOperandInternal(Out, CS->getOperand(0), TypePrinter, Machine);
1022 for (unsigned i = 1; i < N; i++) {
1024 TypePrinter.print(CS->getOperand(i)->getType(), Out);
1027 WriteAsOperandInternal(Out, CS->getOperand(i), TypePrinter, Machine);
1033 if (CS->getType()->isPacked())
1038 if (const ConstantVector *CP = dyn_cast<ConstantVector>(CV)) {
1039 const Type *ETy = CP->getType()->getElementType();
1040 assert(CP->getNumOperands() > 0 &&
1041 "Number of operands for a PackedConst must be > 0");
1043 TypePrinter.print(ETy, Out);
1045 WriteAsOperandInternal(Out, CP->getOperand(0), TypePrinter, Machine);
1046 for (unsigned i = 1, e = CP->getNumOperands(); i != e; ++i) {
1048 TypePrinter.print(ETy, Out);
1050 WriteAsOperandInternal(Out, CP->getOperand(i), TypePrinter, Machine);
1056 if (isa<ConstantPointerNull>(CV)) {
1061 if (isa<UndefValue>(CV)) {
1066 if (const MDString *S = dyn_cast<MDString>(CV)) {
1068 PrintEscapedString(S->begin(), S->size(), Out);
1073 if (const MDNode *Node = dyn_cast<MDNode>(CV)) {
1074 Out << "!" << Machine->getMetadataSlot(Node);
1078 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV)) {
1079 WriteOptimizationInfo(Out, CE);
1080 Out << CE->getOpcodeName();
1081 if (CE->isCompare())
1082 Out << ' ' << getPredicateText(CE->getPredicate());
1085 for (User::const_op_iterator OI=CE->op_begin(); OI != CE->op_end(); ++OI) {
1086 TypePrinter.print((*OI)->getType(), Out);
1088 WriteAsOperandInternal(Out, *OI, TypePrinter, Machine);
1089 if (OI+1 != CE->op_end())
1093 if (CE->hasIndices()) {
1094 const SmallVector<unsigned, 4> &Indices = CE->getIndices();
1095 for (unsigned i = 0, e = Indices.size(); i != e; ++i)
1096 Out << ", " << Indices[i];
1101 TypePrinter.print(CE->getType(), Out);
1108 Out << "<placeholder or erroneous Constant>";
1112 /// WriteAsOperand - Write the name of the specified value out to the specified
1113 /// ostream. This can be useful when you just want to print int %reg126, not
1114 /// the whole instruction that generated it.
1116 static void WriteAsOperandInternal(raw_ostream &Out, const Value *V,
1117 TypePrinting &TypePrinter,
1118 SlotTracker *Machine) {
1120 PrintLLVMName(Out, V);
1124 const Constant *CV = dyn_cast<Constant>(V);
1125 if (CV && !isa<GlobalValue>(CV)) {
1126 WriteConstantInt(Out, CV, TypePrinter, Machine);
1130 if (const InlineAsm *IA = dyn_cast<InlineAsm>(V)) {
1132 if (IA->hasSideEffects())
1133 Out << "sideeffect ";
1135 PrintEscapedString(IA->getAsmString(), Out);
1137 PrintEscapedString(IA->getConstraintString(), Out);
1145 if (const GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
1146 Slot = Machine->getGlobalSlot(GV);
1149 Slot = Machine->getLocalSlot(V);
1152 Machine = createSlotTracker(V);
1154 if (const GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
1155 Slot = Machine->getGlobalSlot(GV);
1158 Slot = Machine->getLocalSlot(V);
1167 Out << Prefix << Slot;
1172 /// WriteAsOperand - Write the name of the specified value out to the specified
1173 /// ostream. This can be useful when you just want to print int %reg126, not
1174 /// the whole instruction that generated it.
1176 void llvm::WriteAsOperand(std::ostream &Out, const Value *V, bool PrintType,
1177 const Module *Context) {
1178 raw_os_ostream OS(Out);
1179 WriteAsOperand(OS, V, PrintType, Context);
1182 void llvm::WriteAsOperand(raw_ostream &Out, const Value *V, bool PrintType,
1183 const Module *Context) {
1184 if (Context == 0) Context = getModuleFromVal(V);
1186 TypePrinting TypePrinter;
1187 std::vector<const Type*> NumberedTypes;
1188 AddModuleTypesToPrinter(TypePrinter, NumberedTypes, Context);
1190 TypePrinter.print(V->getType(), Out);
1194 WriteAsOperandInternal(Out, V, TypePrinter, 0);
1200 class AssemblyWriter {
1202 SlotTracker &Machine;
1203 const Module *TheModule;
1204 TypePrinting TypePrinter;
1205 AssemblyAnnotationWriter *AnnotationWriter;
1206 std::vector<const Type*> NumberedTypes;
1208 // Each MDNode is assigned unique MetadataIDNo.
1209 std::map<const MDNode *, unsigned> MDNodes;
1210 unsigned MetadataIDNo;
1212 inline AssemblyWriter(raw_ostream &o, SlotTracker &Mac, const Module *M,
1213 AssemblyAnnotationWriter *AAW)
1214 : Out(o), Machine(Mac), TheModule(M), AnnotationWriter(AAW), MetadataIDNo(0) {
1215 AddModuleTypesToPrinter(TypePrinter, NumberedTypes, M);
1218 void write(const Module *M) { printModule(M); }
1220 void write(const GlobalValue *G) {
1221 if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(G))
1223 else if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(G))
1225 else if (const Function *F = dyn_cast<Function>(G))
1228 llvm_unreachable("Unknown global");
1231 void write(const BasicBlock *BB) { printBasicBlock(BB); }
1232 void write(const Instruction *I) { printInstruction(*I); }
1234 void writeOperand(const Value *Op, bool PrintType);
1235 void writeParamOperand(const Value *Operand, Attributes Attrs);
1237 const Module* getModule() { return TheModule; }
1240 void printModule(const Module *M);
1241 void printTypeSymbolTable(const TypeSymbolTable &ST);
1242 void printGlobal(const GlobalVariable *GV);
1243 void printAlias(const GlobalAlias *GV);
1244 void printFunction(const Function *F);
1245 void printArgument(const Argument *FA, Attributes Attrs);
1246 void printBasicBlock(const BasicBlock *BB);
1247 void printInstruction(const Instruction &I);
1249 // printInfoComment - Print a little comment after the instruction indicating
1250 // which slot it occupies.
1251 void printInfoComment(const Value &V);
1253 } // end of anonymous namespace
1256 void AssemblyWriter::writeOperand(const Value *Operand, bool PrintType) {
1258 Out << "<null operand!>";
1261 TypePrinter.print(Operand->getType(), Out);
1264 WriteAsOperandInternal(Out, Operand, TypePrinter, &Machine);
1268 void AssemblyWriter::writeParamOperand(const Value *Operand,
1271 Out << "<null operand!>";
1274 TypePrinter.print(Operand->getType(), Out);
1275 // Print parameter attributes list
1276 if (Attrs != Attribute::None)
1277 Out << ' ' << Attribute::getAsString(Attrs);
1279 // Print the operand
1280 WriteAsOperandInternal(Out, Operand, TypePrinter, &Machine);
1284 void AssemblyWriter::printModule(const Module *M) {
1285 if (!M->getModuleIdentifier().empty() &&
1286 // Don't print the ID if it will start a new line (which would
1287 // require a comment char before it).
1288 M->getModuleIdentifier().find('\n') == std::string::npos)
1289 Out << "; ModuleID = '" << M->getModuleIdentifier() << "'\n";
1291 if (!M->getDataLayout().empty())
1292 Out << "target datalayout = \"" << M->getDataLayout() << "\"\n";
1293 if (!M->getTargetTriple().empty())
1294 Out << "target triple = \"" << M->getTargetTriple() << "\"\n";
1296 if (!M->getModuleInlineAsm().empty()) {
1297 // Split the string into lines, to make it easier to read the .ll file.
1298 std::string Asm = M->getModuleInlineAsm();
1300 size_t NewLine = Asm.find_first_of('\n', CurPos);
1301 while (NewLine != std::string::npos) {
1302 // We found a newline, print the portion of the asm string from the
1303 // last newline up to this newline.
1304 Out << "module asm \"";
1305 PrintEscapedString(std::string(Asm.begin()+CurPos, Asm.begin()+NewLine),
1309 NewLine = Asm.find_first_of('\n', CurPos);
1311 Out << "module asm \"";
1312 PrintEscapedString(std::string(Asm.begin()+CurPos, Asm.end()), Out);
1316 // Loop over the dependent libraries and emit them.
1317 Module::lib_iterator LI = M->lib_begin();
1318 Module::lib_iterator LE = M->lib_end();
1320 Out << "deplibs = [ ";
1322 Out << '"' << *LI << '"';
1330 // Loop over the symbol table, emitting all id'd types.
1331 printTypeSymbolTable(M->getTypeSymbolTable());
1333 for (Module::const_global_iterator I = M->global_begin(), E = M->global_end();
1337 // Output all aliases.
1338 if (!M->alias_empty()) Out << "\n";
1339 for (Module::const_alias_iterator I = M->alias_begin(), E = M->alias_end();
1343 // Output all of the functions.
1344 for (Module::const_iterator I = M->begin(), E = M->end(); I != E; ++I)
1347 WriteMDNodes(Out, TypePrinter, Machine);
1350 static void PrintLinkage(GlobalValue::LinkageTypes LT, raw_ostream &Out) {
1352 case GlobalValue::ExternalLinkage: break;
1353 case GlobalValue::PrivateLinkage: Out << "private "; break;
1354 case GlobalValue::LinkerPrivateLinkage: Out << "linker_private "; break;
1355 case GlobalValue::InternalLinkage: Out << "internal "; break;
1356 case GlobalValue::LinkOnceAnyLinkage: Out << "linkonce "; break;
1357 case GlobalValue::LinkOnceODRLinkage: Out << "linkonce_odr "; break;
1358 case GlobalValue::WeakAnyLinkage: Out << "weak "; break;
1359 case GlobalValue::WeakODRLinkage: Out << "weak_odr "; break;
1360 case GlobalValue::CommonLinkage: Out << "common "; break;
1361 case GlobalValue::AppendingLinkage: Out << "appending "; break;
1362 case GlobalValue::DLLImportLinkage: Out << "dllimport "; break;
1363 case GlobalValue::DLLExportLinkage: Out << "dllexport "; break;
1364 case GlobalValue::ExternalWeakLinkage: Out << "extern_weak "; break;
1365 case GlobalValue::AvailableExternallyLinkage:
1366 Out << "available_externally ";
1368 case GlobalValue::GhostLinkage:
1369 llvm_unreachable("GhostLinkage not allowed in AsmWriter!");
1374 static void PrintVisibility(GlobalValue::VisibilityTypes Vis,
1377 default: llvm_unreachable("Invalid visibility style!");
1378 case GlobalValue::DefaultVisibility: break;
1379 case GlobalValue::HiddenVisibility: Out << "hidden "; break;
1380 case GlobalValue::ProtectedVisibility: Out << "protected "; break;
1384 void AssemblyWriter::printGlobal(const GlobalVariable *GV) {
1385 if (GV->hasName()) {
1386 PrintLLVMName(Out, GV);
1390 if (!GV->hasInitializer() && GV->hasExternalLinkage())
1393 PrintLinkage(GV->getLinkage(), Out);
1394 PrintVisibility(GV->getVisibility(), Out);
1396 if (GV->isThreadLocal()) Out << "thread_local ";
1397 if (unsigned AddressSpace = GV->getType()->getAddressSpace())
1398 Out << "addrspace(" << AddressSpace << ") ";
1399 Out << (GV->isConstant() ? "constant " : "global ");
1400 TypePrinter.print(GV->getType()->getElementType(), Out);
1402 if (GV->hasInitializer()) {
1404 writeOperand(GV->getInitializer(), false);
1407 if (GV->hasSection())
1408 Out << ", section \"" << GV->getSection() << '"';
1409 if (GV->getAlignment())
1410 Out << ", align " << GV->getAlignment();
1412 printInfoComment(*GV);
1416 void AssemblyWriter::printAlias(const GlobalAlias *GA) {
1417 // Don't crash when dumping partially built GA
1419 Out << "<<nameless>> = ";
1421 PrintLLVMName(Out, GA);
1424 PrintVisibility(GA->getVisibility(), Out);
1428 PrintLinkage(GA->getLinkage(), Out);
1430 const Constant *Aliasee = GA->getAliasee();
1432 if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(Aliasee)) {
1433 TypePrinter.print(GV->getType(), Out);
1435 PrintLLVMName(Out, GV);
1436 } else if (const Function *F = dyn_cast<Function>(Aliasee)) {
1437 TypePrinter.print(F->getFunctionType(), Out);
1440 WriteAsOperandInternal(Out, F, TypePrinter, &Machine);
1441 } else if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(Aliasee)) {
1442 TypePrinter.print(GA->getType(), Out);
1444 PrintLLVMName(Out, GA);
1446 const ConstantExpr *CE = cast<ConstantExpr>(Aliasee);
1447 // The only valid GEP is an all zero GEP.
1448 assert((CE->getOpcode() == Instruction::BitCast ||
1449 CE->getOpcode() == Instruction::GetElementPtr) &&
1450 "Unsupported aliasee");
1451 writeOperand(CE, false);
1454 printInfoComment(*GA);
1458 void AssemblyWriter::printTypeSymbolTable(const TypeSymbolTable &ST) {
1459 // Emit all numbered types.
1460 for (unsigned i = 0, e = NumberedTypes.size(); i != e; ++i) {
1463 // Make sure we print out at least one level of the type structure, so
1464 // that we do not get %2 = type %2
1465 TypePrinter.printAtLeastOneLevel(NumberedTypes[i], Out);
1466 Out << "\t\t; type %" << i << '\n';
1469 // Print the named types.
1470 for (TypeSymbolTable::const_iterator TI = ST.begin(), TE = ST.end();
1473 PrintLLVMName(Out, &TI->first[0], TI->first.size(), LocalPrefix);
1476 // Make sure we print out at least one level of the type structure, so
1477 // that we do not get %FILE = type %FILE
1478 TypePrinter.printAtLeastOneLevel(TI->second, Out);
1483 /// printFunction - Print all aspects of a function.
1485 void AssemblyWriter::printFunction(const Function *F) {
1486 // Print out the return type and name.
1489 if (AnnotationWriter) AnnotationWriter->emitFunctionAnnot(F, Out);
1491 if (F->isDeclaration())
1496 PrintLinkage(F->getLinkage(), Out);
1497 PrintVisibility(F->getVisibility(), Out);
1499 // Print the calling convention.
1500 switch (F->getCallingConv()) {
1501 case CallingConv::C: break; // default
1502 case CallingConv::Fast: Out << "fastcc "; break;
1503 case CallingConv::Cold: Out << "coldcc "; break;
1504 case CallingConv::X86_StdCall: Out << "x86_stdcallcc "; break;
1505 case CallingConv::X86_FastCall: Out << "x86_fastcallcc "; break;
1506 case CallingConv::ARM_APCS: Out << "arm_apcscc "; break;
1507 case CallingConv::ARM_AAPCS: Out << "arm_aapcscc "; break;
1508 case CallingConv::ARM_AAPCS_VFP:Out << "arm_aapcs_vfpcc "; break;
1509 default: Out << "cc" << F->getCallingConv() << " "; break;
1512 const FunctionType *FT = F->getFunctionType();
1513 const AttrListPtr &Attrs = F->getAttributes();
1514 Attributes RetAttrs = Attrs.getRetAttributes();
1515 if (RetAttrs != Attribute::None)
1516 Out << Attribute::getAsString(Attrs.getRetAttributes()) << ' ';
1517 TypePrinter.print(F->getReturnType(), Out);
1519 WriteAsOperandInternal(Out, F, TypePrinter, &Machine);
1521 Machine.incorporateFunction(F);
1523 // Loop over the arguments, printing them...
1526 if (!F->isDeclaration()) {
1527 // If this isn't a declaration, print the argument names as well.
1528 for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
1530 // Insert commas as we go... the first arg doesn't get a comma
1531 if (I != F->arg_begin()) Out << ", ";
1532 printArgument(I, Attrs.getParamAttributes(Idx));
1536 // Otherwise, print the types from the function type.
1537 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
1538 // Insert commas as we go... the first arg doesn't get a comma
1542 TypePrinter.print(FT->getParamType(i), Out);
1544 Attributes ArgAttrs = Attrs.getParamAttributes(i+1);
1545 if (ArgAttrs != Attribute::None)
1546 Out << ' ' << Attribute::getAsString(ArgAttrs);
1550 // Finish printing arguments...
1551 if (FT->isVarArg()) {
1552 if (FT->getNumParams()) Out << ", ";
1553 Out << "..."; // Output varargs portion of signature!
1556 Attributes FnAttrs = Attrs.getFnAttributes();
1557 if (FnAttrs != Attribute::None)
1558 Out << ' ' << Attribute::getAsString(Attrs.getFnAttributes());
1559 if (F->hasSection())
1560 Out << " section \"" << F->getSection() << '"';
1561 if (F->getAlignment())
1562 Out << " align " << F->getAlignment();
1564 Out << " gc \"" << F->getGC() << '"';
1565 if (F->isDeclaration()) {
1570 // Output all of its basic blocks... for the function
1571 for (Function::const_iterator I = F->begin(), E = F->end(); I != E; ++I)
1577 Machine.purgeFunction();
1580 /// printArgument - This member is called for every argument that is passed into
1581 /// the function. Simply print it out
1583 void AssemblyWriter::printArgument(const Argument *Arg,
1586 TypePrinter.print(Arg->getType(), Out);
1588 // Output parameter attributes list
1589 if (Attrs != Attribute::None)
1590 Out << ' ' << Attribute::getAsString(Attrs);
1592 // Output name, if available...
1593 if (Arg->hasName()) {
1595 PrintLLVMName(Out, Arg);
1599 /// printBasicBlock - This member is called for each basic block in a method.
1601 void AssemblyWriter::printBasicBlock(const BasicBlock *BB) {
1602 if (BB->hasName()) { // Print out the label if it exists...
1604 PrintLLVMName(Out, BB->getNameStart(), BB->getNameLen(), LabelPrefix);
1606 } else if (!BB->use_empty()) { // Don't print block # of no uses...
1607 Out << "\n; <label>:";
1608 int Slot = Machine.getLocalSlot(BB);
1615 if (BB->getParent() == 0)
1616 Out << "\t\t; Error: Block without parent!";
1617 else if (BB != &BB->getParent()->getEntryBlock()) { // Not the entry block?
1618 // Output predecessors for the block...
1620 pred_const_iterator PI = pred_begin(BB), PE = pred_end(BB);
1623 Out << " No predecessors!";
1626 writeOperand(*PI, false);
1627 for (++PI; PI != PE; ++PI) {
1629 writeOperand(*PI, false);
1636 if (AnnotationWriter) AnnotationWriter->emitBasicBlockStartAnnot(BB, Out);
1638 // Output all of the instructions in the basic block...
1639 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I != E; ++I) {
1640 printInstruction(*I);
1644 if (AnnotationWriter) AnnotationWriter->emitBasicBlockEndAnnot(BB, Out);
1648 /// printInfoComment - Print a little comment after the instruction indicating
1649 /// which slot it occupies.
1651 void AssemblyWriter::printInfoComment(const Value &V) {
1652 if (V.getType() != Type::VoidTy) {
1654 TypePrinter.print(V.getType(), Out);
1657 if (!V.hasName() && !isa<Instruction>(V)) {
1659 if (const GlobalValue *GV = dyn_cast<GlobalValue>(&V))
1660 SlotNum = Machine.getGlobalSlot(GV);
1662 SlotNum = Machine.getLocalSlot(&V);
1666 Out << ':' << SlotNum; // Print out the def slot taken.
1668 Out << " [#uses=" << V.getNumUses() << ']'; // Output # uses
1672 // This member is called for each Instruction in a function..
1673 void AssemblyWriter::printInstruction(const Instruction &I) {
1674 if (AnnotationWriter) AnnotationWriter->emitInstructionAnnot(&I, Out);
1678 // Print out name if it exists...
1680 PrintLLVMName(Out, &I);
1682 } else if (I.getType() != Type::VoidTy) {
1683 // Print out the def slot taken.
1684 int SlotNum = Machine.getLocalSlot(&I);
1686 Out << "<badref> = ";
1688 Out << '%' << SlotNum << " = ";
1691 // If this is a volatile load or store, print out the volatile marker.
1692 if ((isa<LoadInst>(I) && cast<LoadInst>(I).isVolatile()) ||
1693 (isa<StoreInst>(I) && cast<StoreInst>(I).isVolatile())) {
1695 } else if (isa<CallInst>(I) && cast<CallInst>(I).isTailCall()) {
1696 // If this is a call, check if it's a tail call.
1700 // Print out optimization information.
1701 WriteOptimizationInfo(Out, &I);
1703 // Print out the opcode...
1704 Out << I.getOpcodeName();
1706 // Print out the compare instruction predicates
1707 if (const CmpInst *CI = dyn_cast<CmpInst>(&I))
1708 Out << ' ' << getPredicateText(CI->getPredicate());
1710 // Print out the type of the operands...
1711 const Value *Operand = I.getNumOperands() ? I.getOperand(0) : 0;
1713 // Special case conditional branches to swizzle the condition out to the front
1714 if (isa<BranchInst>(I) && cast<BranchInst>(I).isConditional()) {
1715 BranchInst &BI(cast<BranchInst>(I));
1717 writeOperand(BI.getCondition(), true);
1719 writeOperand(BI.getSuccessor(0), true);
1721 writeOperand(BI.getSuccessor(1), true);
1723 } else if (isa<SwitchInst>(I)) {
1724 // Special case switch statement to get formatting nice and correct...
1726 writeOperand(Operand , true);
1728 writeOperand(I.getOperand(1), true);
1731 for (unsigned op = 2, Eop = I.getNumOperands(); op < Eop; op += 2) {
1733 writeOperand(I.getOperand(op ), true);
1735 writeOperand(I.getOperand(op+1), true);
1738 } else if (isa<PHINode>(I)) {
1740 TypePrinter.print(I.getType(), Out);
1743 for (unsigned op = 0, Eop = I.getNumOperands(); op < Eop; op += 2) {
1744 if (op) Out << ", ";
1746 writeOperand(I.getOperand(op ), false); Out << ", ";
1747 writeOperand(I.getOperand(op+1), false); Out << " ]";
1749 } else if (const ExtractValueInst *EVI = dyn_cast<ExtractValueInst>(&I)) {
1751 writeOperand(I.getOperand(0), true);
1752 for (const unsigned *i = EVI->idx_begin(), *e = EVI->idx_end(); i != e; ++i)
1754 } else if (const InsertValueInst *IVI = dyn_cast<InsertValueInst>(&I)) {
1756 writeOperand(I.getOperand(0), true); Out << ", ";
1757 writeOperand(I.getOperand(1), true);
1758 for (const unsigned *i = IVI->idx_begin(), *e = IVI->idx_end(); i != e; ++i)
1760 } else if (isa<ReturnInst>(I) && !Operand) {
1762 } else if (const CallInst *CI = dyn_cast<CallInst>(&I)) {
1763 // Print the calling convention being used.
1764 switch (CI->getCallingConv()) {
1765 case CallingConv::C: break; // default
1766 case CallingConv::Fast: Out << " fastcc"; break;
1767 case CallingConv::Cold: Out << " coldcc"; break;
1768 case CallingConv::X86_StdCall: Out << " x86_stdcallcc"; break;
1769 case CallingConv::X86_FastCall: Out << " x86_fastcallcc"; break;
1770 case CallingConv::ARM_APCS: Out << " arm_apcscc "; break;
1771 case CallingConv::ARM_AAPCS: Out << " arm_aapcscc "; break;
1772 case CallingConv::ARM_AAPCS_VFP:Out << " arm_aapcs_vfpcc "; break;
1773 default: Out << " cc" << CI->getCallingConv(); break;
1776 const PointerType *PTy = cast<PointerType>(Operand->getType());
1777 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
1778 const Type *RetTy = FTy->getReturnType();
1779 const AttrListPtr &PAL = CI->getAttributes();
1781 if (PAL.getRetAttributes() != Attribute::None)
1782 Out << ' ' << Attribute::getAsString(PAL.getRetAttributes());
1784 // If possible, print out the short form of the call instruction. We can
1785 // only do this if the first argument is a pointer to a nonvararg function,
1786 // and if the return type is not a pointer to a function.
1789 if (!FTy->isVarArg() &&
1790 (!isa<PointerType>(RetTy) ||
1791 !isa<FunctionType>(cast<PointerType>(RetTy)->getElementType()))) {
1792 TypePrinter.print(RetTy, Out);
1794 writeOperand(Operand, false);
1796 writeOperand(Operand, true);
1799 for (unsigned op = 1, Eop = I.getNumOperands(); op < Eop; ++op) {
1802 writeParamOperand(I.getOperand(op), PAL.getParamAttributes(op));
1805 if (PAL.getFnAttributes() != Attribute::None)
1806 Out << ' ' << Attribute::getAsString(PAL.getFnAttributes());
1807 } else if (const InvokeInst *II = dyn_cast<InvokeInst>(&I)) {
1808 const PointerType *PTy = cast<PointerType>(Operand->getType());
1809 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
1810 const Type *RetTy = FTy->getReturnType();
1811 const AttrListPtr &PAL = II->getAttributes();
1813 // Print the calling convention being used.
1814 switch (II->getCallingConv()) {
1815 case CallingConv::C: break; // default
1816 case CallingConv::Fast: Out << " fastcc"; break;
1817 case CallingConv::Cold: Out << " coldcc"; break;
1818 case CallingConv::X86_StdCall: Out << " x86_stdcallcc"; break;
1819 case CallingConv::X86_FastCall: Out << " x86_fastcallcc"; break;
1820 case CallingConv::ARM_APCS: Out << " arm_apcscc "; break;
1821 case CallingConv::ARM_AAPCS: Out << " arm_aapcscc "; break;
1822 case CallingConv::ARM_AAPCS_VFP:Out << " arm_aapcs_vfpcc "; break;
1823 default: Out << " cc" << II->getCallingConv(); break;
1826 if (PAL.getRetAttributes() != Attribute::None)
1827 Out << ' ' << Attribute::getAsString(PAL.getRetAttributes());
1829 // If possible, print out the short form of the invoke instruction. We can
1830 // only do this if the first argument is a pointer to a nonvararg function,
1831 // and if the return type is not a pointer to a function.
1834 if (!FTy->isVarArg() &&
1835 (!isa<PointerType>(RetTy) ||
1836 !isa<FunctionType>(cast<PointerType>(RetTy)->getElementType()))) {
1837 TypePrinter.print(RetTy, Out);
1839 writeOperand(Operand, false);
1841 writeOperand(Operand, true);
1844 for (unsigned op = 3, Eop = I.getNumOperands(); op < Eop; ++op) {
1847 writeParamOperand(I.getOperand(op), PAL.getParamAttributes(op-2));
1851 if (PAL.getFnAttributes() != Attribute::None)
1852 Out << ' ' << Attribute::getAsString(PAL.getFnAttributes());
1854 Out << "\n\t\t\tto ";
1855 writeOperand(II->getNormalDest(), true);
1857 writeOperand(II->getUnwindDest(), true);
1859 } else if (const AllocationInst *AI = dyn_cast<AllocationInst>(&I)) {
1861 TypePrinter.print(AI->getType()->getElementType(), Out);
1862 if (AI->isArrayAllocation()) {
1864 writeOperand(AI->getArraySize(), true);
1866 if (AI->getAlignment()) {
1867 Out << ", align " << AI->getAlignment();
1869 } else if (isa<CastInst>(I)) {
1872 writeOperand(Operand, true); // Work with broken code
1875 TypePrinter.print(I.getType(), Out);
1876 } else if (isa<VAArgInst>(I)) {
1879 writeOperand(Operand, true); // Work with broken code
1882 TypePrinter.print(I.getType(), Out);
1883 } else if (Operand) { // Print the normal way.
1885 // PrintAllTypes - Instructions who have operands of all the same type
1886 // omit the type from all but the first operand. If the instruction has
1887 // different type operands (for example br), then they are all printed.
1888 bool PrintAllTypes = false;
1889 const Type *TheType = Operand->getType();
1891 // Select, Store and ShuffleVector always print all types.
1892 if (isa<SelectInst>(I) || isa<StoreInst>(I) || isa<ShuffleVectorInst>(I)
1893 || isa<ReturnInst>(I)) {
1894 PrintAllTypes = true;
1896 for (unsigned i = 1, E = I.getNumOperands(); i != E; ++i) {
1897 Operand = I.getOperand(i);
1898 // note that Operand shouldn't be null, but the test helps make dump()
1899 // more tolerant of malformed IR
1900 if (Operand && Operand->getType() != TheType) {
1901 PrintAllTypes = true; // We have differing types! Print them all!
1907 if (!PrintAllTypes) {
1909 TypePrinter.print(TheType, Out);
1913 for (unsigned i = 0, E = I.getNumOperands(); i != E; ++i) {
1915 writeOperand(I.getOperand(i), PrintAllTypes);
1919 // Print post operand alignment for load/store
1920 if (isa<LoadInst>(I) && cast<LoadInst>(I).getAlignment()) {
1921 Out << ", align " << cast<LoadInst>(I).getAlignment();
1922 } else if (isa<StoreInst>(I) && cast<StoreInst>(I).getAlignment()) {
1923 Out << ", align " << cast<StoreInst>(I).getAlignment();
1926 printInfoComment(I);
1930 //===----------------------------------------------------------------------===//
1931 // External Interface declarations
1932 //===----------------------------------------------------------------------===//
1934 void Module::print(std::ostream &o, AssemblyAnnotationWriter *AAW) const {
1935 raw_os_ostream OS(o);
1938 void Module::print(raw_ostream &OS, AssemblyAnnotationWriter *AAW) const {
1939 SlotTracker SlotTable(this);
1940 AssemblyWriter W(OS, SlotTable, this, AAW);
1944 void Type::print(std::ostream &o) const {
1945 raw_os_ostream OS(o);
1949 void Type::print(raw_ostream &OS) const {
1951 OS << "<null Type>";
1954 TypePrinting().print(this, OS);
1957 void Value::print(raw_ostream &OS, AssemblyAnnotationWriter *AAW) const {
1959 OS << "printing a <null> value\n";
1962 if (const Instruction *I = dyn_cast<Instruction>(this)) {
1963 const Function *F = I->getParent() ? I->getParent()->getParent() : 0;
1964 SlotTracker SlotTable(F);
1965 AssemblyWriter W(OS, SlotTable, F ? F->getParent() : 0, AAW);
1967 } else if (const BasicBlock *BB = dyn_cast<BasicBlock>(this)) {
1968 SlotTracker SlotTable(BB->getParent());
1969 AssemblyWriter W(OS, SlotTable,
1970 BB->getParent() ? BB->getParent()->getParent() : 0, AAW);
1972 } else if (const GlobalValue *GV = dyn_cast<GlobalValue>(this)) {
1973 SlotTracker SlotTable(GV->getParent());
1974 AssemblyWriter W(OS, SlotTable, GV->getParent(), AAW);
1976 } else if (const MDNode *N = dyn_cast<MDNode>(this)) {
1977 SlotTracker SlotTable(N);
1978 TypePrinting TypePrinter;
1979 SlotTable.initialize();
1980 WriteMDNodes(OS, TypePrinter, SlotTable);
1981 } else if (const Constant *C = dyn_cast<Constant>(this)) {
1982 TypePrinting TypePrinter;
1983 TypePrinter.print(C->getType(), OS);
1985 WriteConstantInt(OS, C, TypePrinter, 0);
1986 } else if (const Argument *A = dyn_cast<Argument>(this)) {
1987 WriteAsOperand(OS, this, true,
1988 A->getParent() ? A->getParent()->getParent() : 0);
1989 } else if (isa<InlineAsm>(this)) {
1990 WriteAsOperand(OS, this, true, 0);
1992 llvm_unreachable("Unknown value to print out!");
1996 void Value::print(std::ostream &O, AssemblyAnnotationWriter *AAW) const {
1997 raw_os_ostream OS(O);
2001 // Value::dump - allow easy printing of Values from the debugger.
2002 void Value::dump() const { print(errs()); errs() << '\n'; }
2004 // Type::dump - allow easy printing of Types from the debugger.
2005 // This one uses type names from the given context module
2006 void Type::dump(const Module *Context) const {
2007 WriteTypeSymbolic(errs(), this, Context);
2011 // Type::dump - allow easy printing of Types from the debugger.
2012 void Type::dump() const { dump(0); }
2014 // Module::dump() - Allow printing of Modules from the debugger.
2015 void Module::dump() const { print(errs(), 0); }