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/IntrinsicInst.h"
25 #include "llvm/Operator.h"
26 #include "llvm/Module.h"
27 #include "llvm/ValueSymbolTable.h"
28 #include "llvm/TypeSymbolTable.h"
29 #include "llvm/ADT/DenseSet.h"
30 #include "llvm/ADT/SmallString.h"
31 #include "llvm/ADT/StringExtras.h"
32 #include "llvm/ADT/STLExtras.h"
33 #include "llvm/Support/CFG.h"
34 #include "llvm/Support/Debug.h"
35 #include "llvm/Support/Dwarf.h"
36 #include "llvm/Support/ErrorHandling.h"
37 #include "llvm/Support/MathExtras.h"
38 #include "llvm/Support/FormattedStream.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();
65 if (const NamedMDNode *NMD = dyn_cast<NamedMDNode>(V))
66 return NMD->getParent();
70 // PrintEscapedString - Print each character of the specified string, escaping
71 // it if it is not printable or if it is an escape char.
72 static void PrintEscapedString(const StringRef &Name,
74 for (unsigned i = 0, e = Name.size(); i != e; ++i) {
75 unsigned char C = Name[i];
76 if (isprint(C) && C != '\\' && C != '"')
79 Out << '\\' << hexdigit(C >> 4) << hexdigit(C & 0x0F);
90 /// PrintLLVMName - Turn the specified name into an 'LLVM name', which is either
91 /// prefixed with % (if the string only contains simple characters) or is
92 /// surrounded with ""'s (if it has special chars in it). Print it out.
93 static void PrintLLVMName(raw_ostream &OS, const StringRef &Name,
95 assert(Name.data() && "Cannot get empty name!");
97 default: llvm_unreachable("Bad prefix!");
99 case GlobalPrefix: OS << '@'; break;
100 case LabelPrefix: break;
101 case LocalPrefix: OS << '%'; break;
104 // Scan the name to see if it needs quotes first.
105 bool NeedsQuotes = isdigit(Name[0]);
107 for (unsigned i = 0, e = Name.size(); i != e; ++i) {
109 if (!isalnum(C) && C != '-' && C != '.' && C != '_') {
116 // If we didn't need any quotes, just write out the name in one blast.
122 // Okay, we need quotes. Output the quotes and escape any scary characters as
125 PrintEscapedString(Name, OS);
129 /// PrintLLVMName - Turn the specified name into an 'LLVM name', which is either
130 /// prefixed with % (if the string only contains simple characters) or is
131 /// surrounded with ""'s (if it has special chars in it). Print it out.
132 static void PrintLLVMName(raw_ostream &OS, const Value *V) {
133 PrintLLVMName(OS, V->getName(),
134 isa<GlobalValue>(V) ? GlobalPrefix : LocalPrefix);
137 //===----------------------------------------------------------------------===//
138 // TypePrinting Class: Type printing machinery
139 //===----------------------------------------------------------------------===//
141 static DenseMap<const Type *, std::string> &getTypeNamesMap(void *M) {
142 return *static_cast<DenseMap<const Type *, std::string>*>(M);
145 void TypePrinting::clear() {
146 getTypeNamesMap(TypeNames).clear();
149 bool TypePrinting::hasTypeName(const Type *Ty) const {
150 return getTypeNamesMap(TypeNames).count(Ty);
153 void TypePrinting::addTypeName(const Type *Ty, const std::string &N) {
154 getTypeNamesMap(TypeNames).insert(std::make_pair(Ty, N));
158 TypePrinting::TypePrinting() {
159 TypeNames = new DenseMap<const Type *, std::string>();
162 TypePrinting::~TypePrinting() {
163 delete &getTypeNamesMap(TypeNames);
166 /// CalcTypeName - Write the specified type to the specified raw_ostream, making
167 /// use of type names or up references to shorten the type name where possible.
168 void TypePrinting::CalcTypeName(const Type *Ty,
169 SmallVectorImpl<const Type *> &TypeStack,
170 raw_ostream &OS, bool IgnoreTopLevelName) {
171 // Check to see if the type is named.
172 if (!IgnoreTopLevelName) {
173 DenseMap<const Type *, std::string> &TM = getTypeNamesMap(TypeNames);
174 DenseMap<const Type *, std::string>::iterator I = TM.find(Ty);
181 // Check to see if the Type is already on the stack...
182 unsigned Slot = 0, CurSize = TypeStack.size();
183 while (Slot < CurSize && TypeStack[Slot] != Ty) ++Slot; // Scan for type
185 // This is another base case for the recursion. In this case, we know
186 // that we have looped back to a type that we have previously visited.
187 // Generate the appropriate upreference to handle this.
188 if (Slot < CurSize) {
189 OS << '\\' << unsigned(CurSize-Slot); // Here's the upreference
193 TypeStack.push_back(Ty); // Recursive case: Add us to the stack..
195 switch (Ty->getTypeID()) {
196 case Type::VoidTyID: OS << "void"; break;
197 case Type::FloatTyID: OS << "float"; break;
198 case Type::DoubleTyID: OS << "double"; break;
199 case Type::X86_FP80TyID: OS << "x86_fp80"; break;
200 case Type::FP128TyID: OS << "fp128"; break;
201 case Type::PPC_FP128TyID: OS << "ppc_fp128"; break;
202 case Type::LabelTyID: OS << "label"; break;
203 case Type::MetadataTyID: OS << "metadata"; break;
204 case Type::IntegerTyID:
205 OS << 'i' << cast<IntegerType>(Ty)->getBitWidth();
208 case Type::FunctionTyID: {
209 const FunctionType *FTy = cast<FunctionType>(Ty);
210 CalcTypeName(FTy->getReturnType(), TypeStack, OS);
212 for (FunctionType::param_iterator I = FTy->param_begin(),
213 E = FTy->param_end(); I != E; ++I) {
214 if (I != FTy->param_begin())
216 CalcTypeName(*I, TypeStack, OS);
218 if (FTy->isVarArg()) {
219 if (FTy->getNumParams()) OS << ", ";
225 case Type::StructTyID: {
226 const StructType *STy = cast<StructType>(Ty);
230 for (StructType::element_iterator I = STy->element_begin(),
231 E = STy->element_end(); I != E; ++I) {
232 CalcTypeName(*I, TypeStack, OS);
233 if (next(I) != STy->element_end())
242 case Type::UnionTyID: {
243 const UnionType *UTy = cast<UnionType>(Ty);
245 for (StructType::element_iterator I = UTy->element_begin(),
246 E = UTy->element_end(); I != E; ++I) {
247 CalcTypeName(*I, TypeStack, OS);
248 if (next(I) != UTy->element_end())
255 case Type::PointerTyID: {
256 const PointerType *PTy = cast<PointerType>(Ty);
257 CalcTypeName(PTy->getElementType(), TypeStack, OS);
258 if (unsigned AddressSpace = PTy->getAddressSpace())
259 OS << " addrspace(" << AddressSpace << ')';
263 case Type::ArrayTyID: {
264 const ArrayType *ATy = cast<ArrayType>(Ty);
265 OS << '[' << ATy->getNumElements() << " x ";
266 CalcTypeName(ATy->getElementType(), TypeStack, OS);
270 case Type::VectorTyID: {
271 const VectorType *PTy = cast<VectorType>(Ty);
272 OS << "<" << PTy->getNumElements() << " x ";
273 CalcTypeName(PTy->getElementType(), TypeStack, OS);
277 case Type::OpaqueTyID:
281 OS << "<unrecognized-type>";
285 TypeStack.pop_back(); // Remove self from stack.
288 /// printTypeInt - The internal guts of printing out a type that has a
289 /// potentially named portion.
291 void TypePrinting::print(const Type *Ty, raw_ostream &OS,
292 bool IgnoreTopLevelName) {
293 // Check to see if the type is named.
294 DenseMap<const Type*, std::string> &TM = getTypeNamesMap(TypeNames);
295 if (!IgnoreTopLevelName) {
296 DenseMap<const Type*, std::string>::iterator I = TM.find(Ty);
303 // Otherwise we have a type that has not been named but is a derived type.
304 // Carefully recurse the type hierarchy to print out any contained symbolic
306 SmallVector<const Type *, 16> TypeStack;
307 std::string TypeName;
309 raw_string_ostream TypeOS(TypeName);
310 CalcTypeName(Ty, TypeStack, TypeOS, IgnoreTopLevelName);
313 // Cache type name for later use.
314 if (!IgnoreTopLevelName)
315 TM.insert(std::make_pair(Ty, TypeOS.str()));
320 // To avoid walking constant expressions multiple times and other IR
321 // objects, we keep several helper maps.
322 DenseSet<const Value*> VisitedConstants;
323 DenseSet<const Type*> VisitedTypes;
326 std::vector<const Type*> &NumberedTypes;
328 TypeFinder(TypePrinting &tp, std::vector<const Type*> &numberedTypes)
329 : TP(tp), NumberedTypes(numberedTypes) {}
331 void Run(const Module &M) {
332 // Get types from the type symbol table. This gets opaque types referened
333 // only through derived named types.
334 const TypeSymbolTable &ST = M.getTypeSymbolTable();
335 for (TypeSymbolTable::const_iterator TI = ST.begin(), E = ST.end();
337 IncorporateType(TI->second);
339 // Get types from global variables.
340 for (Module::const_global_iterator I = M.global_begin(),
341 E = M.global_end(); I != E; ++I) {
342 IncorporateType(I->getType());
343 if (I->hasInitializer())
344 IncorporateValue(I->getInitializer());
347 // Get types from aliases.
348 for (Module::const_alias_iterator I = M.alias_begin(),
349 E = M.alias_end(); I != E; ++I) {
350 IncorporateType(I->getType());
351 IncorporateValue(I->getAliasee());
354 // Get types from functions.
355 for (Module::const_iterator FI = M.begin(), E = M.end(); FI != E; ++FI) {
356 IncorporateType(FI->getType());
358 for (Function::const_iterator BB = FI->begin(), E = FI->end();
360 for (BasicBlock::const_iterator II = BB->begin(),
361 E = BB->end(); II != E; ++II) {
362 const Instruction &I = *II;
363 // Incorporate the type of the instruction and all its operands.
364 IncorporateType(I.getType());
365 for (User::const_op_iterator OI = I.op_begin(), OE = I.op_end();
367 IncorporateValue(*OI);
373 void IncorporateType(const Type *Ty) {
374 // Check to see if we're already visited this type.
375 if (!VisitedTypes.insert(Ty).second)
378 // If this is a structure or opaque type, add a name for the type.
379 if (((Ty->isStructTy() && cast<StructType>(Ty)->getNumElements())
380 || isa<OpaqueType>(Ty)) && !TP.hasTypeName(Ty)) {
381 TP.addTypeName(Ty, "%"+utostr(unsigned(NumberedTypes.size())));
382 NumberedTypes.push_back(Ty);
385 // Recursively walk all contained types.
386 for (Type::subtype_iterator I = Ty->subtype_begin(),
387 E = Ty->subtype_end(); I != E; ++I)
391 /// IncorporateValue - This method is used to walk operand lists finding
392 /// types hiding in constant expressions and other operands that won't be
393 /// walked in other ways. GlobalValues, basic blocks, instructions, and
394 /// inst operands are all explicitly enumerated.
395 void IncorporateValue(const Value *V) {
396 if (V == 0 || !isa<Constant>(V) || isa<GlobalValue>(V)) return;
399 if (!VisitedConstants.insert(V).second)
403 IncorporateType(V->getType());
405 // Look in operands for types.
406 const Constant *C = cast<Constant>(V);
407 for (Constant::const_op_iterator I = C->op_begin(),
408 E = C->op_end(); I != E;++I)
409 IncorporateValue(*I);
412 } // end anonymous namespace
415 /// AddModuleTypesToPrinter - Add all of the symbolic type names for types in
416 /// the specified module to the TypePrinter and all numbered types to it and the
417 /// NumberedTypes table.
418 static void AddModuleTypesToPrinter(TypePrinting &TP,
419 std::vector<const Type*> &NumberedTypes,
423 // If the module has a symbol table, take all global types and stuff their
424 // names into the TypeNames map.
425 const TypeSymbolTable &ST = M->getTypeSymbolTable();
426 for (TypeSymbolTable::const_iterator TI = ST.begin(), E = ST.end();
428 const Type *Ty = cast<Type>(TI->second);
430 // As a heuristic, don't insert pointer to primitive types, because
431 // they are used too often to have a single useful name.
432 if (const PointerType *PTy = dyn_cast<PointerType>(Ty)) {
433 const Type *PETy = PTy->getElementType();
434 if ((PETy->isPrimitiveType() || PETy->isIntegerTy()) &&
435 !isa<OpaqueType>(PETy))
439 // Likewise don't insert primitives either.
440 if (Ty->isIntegerTy() || Ty->isPrimitiveType())
443 // Get the name as a string and insert it into TypeNames.
445 raw_string_ostream NameROS(NameStr);
446 formatted_raw_ostream NameOS(NameROS);
447 PrintLLVMName(NameOS, TI->first, LocalPrefix);
449 TP.addTypeName(Ty, NameStr);
452 // Walk the entire module to find references to unnamed structure and opaque
453 // types. This is required for correctness by opaque types (because multiple
454 // uses of an unnamed opaque type needs to be referred to by the same ID) and
455 // it shrinks complex recursive structure types substantially in some cases.
456 TypeFinder(TP, NumberedTypes).Run(*M);
460 /// WriteTypeSymbolic - This attempts to write the specified type as a symbolic
461 /// type, iff there is an entry in the modules symbol table for the specified
462 /// type or one of it's component types.
464 void llvm::WriteTypeSymbolic(raw_ostream &OS, const Type *Ty, const Module *M) {
465 TypePrinting Printer;
466 std::vector<const Type*> NumberedTypes;
467 AddModuleTypesToPrinter(Printer, NumberedTypes, M);
468 Printer.print(Ty, OS);
471 //===----------------------------------------------------------------------===//
472 // SlotTracker Class: Enumerate slot numbers for unnamed values
473 //===----------------------------------------------------------------------===//
477 /// This class provides computation of slot numbers for LLVM Assembly writing.
481 /// ValueMap - A mapping of Values to slot numbers.
482 typedef DenseMap<const Value*, unsigned> ValueMap;
485 /// TheModule - The module for which we are holding slot numbers.
486 const Module* TheModule;
488 /// TheFunction - The function for which we are holding slot numbers.
489 const Function* TheFunction;
490 bool FunctionProcessed;
492 /// mMap - The TypePlanes map for the module level data.
496 /// fMap - The TypePlanes map for the function level data.
500 /// mdnMap - Map for MDNodes.
501 DenseMap<const MDNode*, unsigned> mdnMap;
504 /// Construct from a module
505 explicit SlotTracker(const Module *M);
506 /// Construct from a function, starting out in incorp state.
507 explicit SlotTracker(const Function *F);
509 /// Return the slot number of the specified value in it's type
510 /// plane. If something is not in the SlotTracker, return -1.
511 int getLocalSlot(const Value *V);
512 int getGlobalSlot(const GlobalValue *V);
513 int getMetadataSlot(const MDNode *N);
515 /// If you'd like to deal with a function instead of just a module, use
516 /// this method to get its data into the SlotTracker.
517 void incorporateFunction(const Function *F) {
519 FunctionProcessed = false;
522 /// After calling incorporateFunction, use this method to remove the
523 /// most recently incorporated function from the SlotTracker. This
524 /// will reset the state of the machine back to just the module contents.
525 void purgeFunction();
527 /// MDNode map iterators.
528 typedef DenseMap<const MDNode*, unsigned>::iterator mdn_iterator;
529 mdn_iterator mdn_begin() { return mdnMap.begin(); }
530 mdn_iterator mdn_end() { return mdnMap.end(); }
531 unsigned mdn_size() const { return mdnMap.size(); }
532 bool mdn_empty() const { return mdnMap.empty(); }
534 /// This function does the actual initialization.
535 inline void initialize();
537 // Implementation Details
539 /// CreateModuleSlot - Insert the specified GlobalValue* into the slot table.
540 void CreateModuleSlot(const GlobalValue *V);
542 /// CreateMetadataSlot - Insert the specified MDNode* into the slot table.
543 void CreateMetadataSlot(const MDNode *N);
545 /// CreateFunctionSlot - Insert the specified Value* into the slot table.
546 void CreateFunctionSlot(const Value *V);
548 /// Add all of the module level global variables (and their initializers)
549 /// and function declarations, but not the contents of those functions.
550 void processModule();
552 /// Add all of the functions arguments, basic blocks, and instructions.
553 void processFunction();
555 SlotTracker(const SlotTracker &); // DO NOT IMPLEMENT
556 void operator=(const SlotTracker &); // DO NOT IMPLEMENT
559 } // end anonymous namespace
562 static SlotTracker *createSlotTracker(const Value *V) {
563 if (const Argument *FA = dyn_cast<Argument>(V))
564 return new SlotTracker(FA->getParent());
566 if (const Instruction *I = dyn_cast<Instruction>(V))
567 return new SlotTracker(I->getParent()->getParent());
569 if (const BasicBlock *BB = dyn_cast<BasicBlock>(V))
570 return new SlotTracker(BB->getParent());
572 if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(V))
573 return new SlotTracker(GV->getParent());
575 if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(V))
576 return new SlotTracker(GA->getParent());
578 if (const Function *Func = dyn_cast<Function>(V))
579 return new SlotTracker(Func);
582 return new SlotTracker((Function *)0);
588 #define ST_DEBUG(X) dbgs() << X
593 // Module level constructor. Causes the contents of the Module (sans functions)
594 // to be added to the slot table.
595 SlotTracker::SlotTracker(const Module *M)
596 : TheModule(M), TheFunction(0), FunctionProcessed(false),
597 mNext(0), fNext(0), mdnNext(0) {
600 // Function level constructor. Causes the contents of the Module and the one
601 // function provided to be added to the slot table.
602 SlotTracker::SlotTracker(const Function *F)
603 : TheModule(F ? F->getParent() : 0), TheFunction(F), FunctionProcessed(false),
604 mNext(0), fNext(0), mdnNext(0) {
607 inline void SlotTracker::initialize() {
610 TheModule = 0; ///< Prevent re-processing next time we're called.
613 if (TheFunction && !FunctionProcessed)
617 // Iterate through all the global variables, functions, and global
618 // variable initializers and create slots for them.
619 void SlotTracker::processModule() {
620 ST_DEBUG("begin processModule!\n");
622 // Add all of the unnamed global variables to the value table.
623 for (Module::const_global_iterator I = TheModule->global_begin(),
624 E = TheModule->global_end(); I != E; ++I) {
629 // Add metadata used by named metadata.
630 for (Module::const_named_metadata_iterator
631 I = TheModule->named_metadata_begin(),
632 E = TheModule->named_metadata_end(); I != E; ++I) {
633 const NamedMDNode *NMD = I;
634 for (unsigned i = 0, e = NMD->getNumOperands(); i != e; ++i) {
635 if (MDNode *MD = NMD->getOperand(i))
636 CreateMetadataSlot(MD);
640 // Add all the unnamed functions to the table.
641 for (Module::const_iterator I = TheModule->begin(), E = TheModule->end();
646 ST_DEBUG("end processModule!\n");
649 // Process the arguments, basic blocks, and instructions of a function.
650 void SlotTracker::processFunction() {
651 ST_DEBUG("begin processFunction!\n");
654 // Add all the function arguments with no names.
655 for(Function::const_arg_iterator AI = TheFunction->arg_begin(),
656 AE = TheFunction->arg_end(); AI != AE; ++AI)
658 CreateFunctionSlot(AI);
660 ST_DEBUG("Inserting Instructions:\n");
662 SmallVector<std::pair<unsigned, MDNode*>, 4> MDForInst;
664 // Add all of the basic blocks and instructions with no names.
665 for (Function::const_iterator BB = TheFunction->begin(),
666 E = TheFunction->end(); BB != E; ++BB) {
668 CreateFunctionSlot(BB);
670 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I != E;
672 if (!I->getType()->isVoidTy() && !I->hasName())
673 CreateFunctionSlot(I);
675 // Intrinsics can directly use metadata.
676 if (isa<IntrinsicInst>(I))
677 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
678 if (MDNode *N = dyn_cast_or_null<MDNode>(I->getOperand(i)))
679 CreateMetadataSlot(N);
681 // Process metadata attached with this instruction.
682 I->getAllMetadata(MDForInst);
683 for (unsigned i = 0, e = MDForInst.size(); i != e; ++i)
684 CreateMetadataSlot(MDForInst[i].second);
689 FunctionProcessed = true;
691 ST_DEBUG("end processFunction!\n");
694 /// Clean up after incorporating a function. This is the only way to get out of
695 /// the function incorporation state that affects get*Slot/Create*Slot. Function
696 /// incorporation state is indicated by TheFunction != 0.
697 void SlotTracker::purgeFunction() {
698 ST_DEBUG("begin purgeFunction!\n");
699 fMap.clear(); // Simply discard the function level map
701 FunctionProcessed = false;
702 ST_DEBUG("end purgeFunction!\n");
705 /// getGlobalSlot - Get the slot number of a global value.
706 int SlotTracker::getGlobalSlot(const GlobalValue *V) {
707 // Check for uninitialized state and do lazy initialization.
710 // Find the type plane in the module map
711 ValueMap::iterator MI = mMap.find(V);
712 return MI == mMap.end() ? -1 : (int)MI->second;
715 /// getMetadataSlot - Get the slot number of a MDNode.
716 int SlotTracker::getMetadataSlot(const MDNode *N) {
717 // Check for uninitialized state and do lazy initialization.
720 // Find the type plane in the module map
721 mdn_iterator MI = mdnMap.find(N);
722 return MI == mdnMap.end() ? -1 : (int)MI->second;
726 /// getLocalSlot - Get the slot number for a value that is local to a function.
727 int SlotTracker::getLocalSlot(const Value *V) {
728 assert(!isa<Constant>(V) && "Can't get a constant or global slot with this!");
730 // Check for uninitialized state and do lazy initialization.
733 ValueMap::iterator FI = fMap.find(V);
734 return FI == fMap.end() ? -1 : (int)FI->second;
738 /// CreateModuleSlot - Insert the specified GlobalValue* into the slot table.
739 void SlotTracker::CreateModuleSlot(const GlobalValue *V) {
740 assert(V && "Can't insert a null Value into SlotTracker!");
741 assert(!V->getType()->isVoidTy() && "Doesn't need a slot!");
742 assert(!V->hasName() && "Doesn't need a slot!");
744 unsigned DestSlot = mNext++;
747 ST_DEBUG(" Inserting value [" << V->getType() << "] = " << V << " slot=" <<
749 // G = Global, F = Function, A = Alias, o = other
750 ST_DEBUG((isa<GlobalVariable>(V) ? 'G' :
751 (isa<Function>(V) ? 'F' :
752 (isa<GlobalAlias>(V) ? 'A' : 'o'))) << "]\n");
755 /// CreateSlot - Create a new slot for the specified value if it has no name.
756 void SlotTracker::CreateFunctionSlot(const Value *V) {
757 assert(!V->getType()->isVoidTy() && !V->hasName() && "Doesn't need a slot!");
759 unsigned DestSlot = fNext++;
762 // G = Global, F = Function, o = other
763 ST_DEBUG(" Inserting value [" << V->getType() << "] = " << V << " slot=" <<
764 DestSlot << " [o]\n");
767 /// CreateModuleSlot - Insert the specified MDNode* into the slot table.
768 void SlotTracker::CreateMetadataSlot(const MDNode *N) {
769 assert(N && "Can't insert a null Value into SlotTracker!");
771 // Don't insert if N is a function-local metadata, these are always printed
773 if (N->isFunctionLocal())
776 mdn_iterator I = mdnMap.find(N);
777 if (I != mdnMap.end())
780 unsigned DestSlot = mdnNext++;
781 mdnMap[N] = DestSlot;
783 // Recursively add any MDNodes referenced by operands.
784 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
785 if (const MDNode *Op = dyn_cast_or_null<MDNode>(N->getOperand(i)))
786 CreateMetadataSlot(Op);
789 //===----------------------------------------------------------------------===//
790 // AsmWriter Implementation
791 //===----------------------------------------------------------------------===//
793 static void WriteAsOperandInternal(raw_ostream &Out, const Value *V,
794 TypePrinting *TypePrinter,
795 SlotTracker *Machine);
799 static const char *getPredicateText(unsigned predicate) {
800 const char * pred = "unknown";
802 case FCmpInst::FCMP_FALSE: pred = "false"; break;
803 case FCmpInst::FCMP_OEQ: pred = "oeq"; break;
804 case FCmpInst::FCMP_OGT: pred = "ogt"; break;
805 case FCmpInst::FCMP_OGE: pred = "oge"; break;
806 case FCmpInst::FCMP_OLT: pred = "olt"; break;
807 case FCmpInst::FCMP_OLE: pred = "ole"; break;
808 case FCmpInst::FCMP_ONE: pred = "one"; break;
809 case FCmpInst::FCMP_ORD: pred = "ord"; break;
810 case FCmpInst::FCMP_UNO: pred = "uno"; break;
811 case FCmpInst::FCMP_UEQ: pred = "ueq"; break;
812 case FCmpInst::FCMP_UGT: pred = "ugt"; break;
813 case FCmpInst::FCMP_UGE: pred = "uge"; break;
814 case FCmpInst::FCMP_ULT: pred = "ult"; break;
815 case FCmpInst::FCMP_ULE: pred = "ule"; break;
816 case FCmpInst::FCMP_UNE: pred = "une"; break;
817 case FCmpInst::FCMP_TRUE: pred = "true"; break;
818 case ICmpInst::ICMP_EQ: pred = "eq"; break;
819 case ICmpInst::ICMP_NE: pred = "ne"; break;
820 case ICmpInst::ICMP_SGT: pred = "sgt"; break;
821 case ICmpInst::ICMP_SGE: pred = "sge"; break;
822 case ICmpInst::ICMP_SLT: pred = "slt"; break;
823 case ICmpInst::ICMP_SLE: pred = "sle"; break;
824 case ICmpInst::ICMP_UGT: pred = "ugt"; break;
825 case ICmpInst::ICMP_UGE: pred = "uge"; break;
826 case ICmpInst::ICMP_ULT: pred = "ult"; break;
827 case ICmpInst::ICMP_ULE: pred = "ule"; break;
833 static void WriteOptimizationInfo(raw_ostream &Out, const User *U) {
834 if (const OverflowingBinaryOperator *OBO =
835 dyn_cast<OverflowingBinaryOperator>(U)) {
836 if (OBO->hasNoUnsignedWrap())
838 if (OBO->hasNoSignedWrap())
840 } else if (const SDivOperator *Div = dyn_cast<SDivOperator>(U)) {
843 } else if (const GEPOperator *GEP = dyn_cast<GEPOperator>(U)) {
844 if (GEP->isInBounds())
849 static void WriteConstantInt(raw_ostream &Out, const Constant *CV,
850 TypePrinting &TypePrinter, SlotTracker *Machine) {
851 if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV)) {
852 if (CI->getType()->isIntegerTy(1)) {
853 Out << (CI->getZExtValue() ? "true" : "false");
856 Out << CI->getValue();
860 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CV)) {
861 if (&CFP->getValueAPF().getSemantics() == &APFloat::IEEEdouble ||
862 &CFP->getValueAPF().getSemantics() == &APFloat::IEEEsingle) {
863 // We would like to output the FP constant value in exponential notation,
864 // but we cannot do this if doing so will lose precision. Check here to
865 // make sure that we only output it in exponential format if we can parse
866 // the value back and get the same value.
869 bool isDouble = &CFP->getValueAPF().getSemantics()==&APFloat::IEEEdouble;
870 double Val = isDouble ? CFP->getValueAPF().convertToDouble() :
871 CFP->getValueAPF().convertToFloat();
872 SmallString<128> StrVal;
873 raw_svector_ostream(StrVal) << Val;
875 // Check to make sure that the stringized number is not some string like
876 // "Inf" or NaN, that atof will accept, but the lexer will not. Check
877 // that the string matches the "[-+]?[0-9]" regex.
879 if ((StrVal[0] >= '0' && StrVal[0] <= '9') ||
880 ((StrVal[0] == '-' || StrVal[0] == '+') &&
881 (StrVal[1] >= '0' && StrVal[1] <= '9'))) {
882 // Reparse stringized version!
883 if (atof(StrVal.c_str()) == Val) {
888 // Otherwise we could not reparse it to exactly the same value, so we must
889 // output the string in hexadecimal format! Note that loading and storing
890 // floating point types changes the bits of NaNs on some hosts, notably
891 // x86, so we must not use these types.
892 assert(sizeof(double) == sizeof(uint64_t) &&
893 "assuming that double is 64 bits!");
895 APFloat apf = CFP->getValueAPF();
896 // Floats are represented in ASCII IR as double, convert.
898 apf.convert(APFloat::IEEEdouble, APFloat::rmNearestTiesToEven,
901 utohex_buffer(uint64_t(apf.bitcastToAPInt().getZExtValue()),
906 // Some form of long double. These appear as a magic letter identifying
907 // the type, then a fixed number of hex digits.
909 if (&CFP->getValueAPF().getSemantics() == &APFloat::x87DoubleExtended) {
911 // api needed to prevent premature destruction
912 APInt api = CFP->getValueAPF().bitcastToAPInt();
913 const uint64_t* p = api.getRawData();
914 uint64_t word = p[1];
916 int width = api.getBitWidth();
917 for (int j=0; j<width; j+=4, shiftcount-=4) {
918 unsigned int nibble = (word>>shiftcount) & 15;
920 Out << (unsigned char)(nibble + '0');
922 Out << (unsigned char)(nibble - 10 + 'A');
923 if (shiftcount == 0 && j+4 < width) {
927 shiftcount = width-j-4;
931 } else if (&CFP->getValueAPF().getSemantics() == &APFloat::IEEEquad)
933 else if (&CFP->getValueAPF().getSemantics() == &APFloat::PPCDoubleDouble)
936 llvm_unreachable("Unsupported floating point type");
937 // api needed to prevent premature destruction
938 APInt api = CFP->getValueAPF().bitcastToAPInt();
939 const uint64_t* p = api.getRawData();
942 int width = api.getBitWidth();
943 for (int j=0; j<width; j+=4, shiftcount-=4) {
944 unsigned int nibble = (word>>shiftcount) & 15;
946 Out << (unsigned char)(nibble + '0');
948 Out << (unsigned char)(nibble - 10 + 'A');
949 if (shiftcount == 0 && j+4 < width) {
953 shiftcount = width-j-4;
959 if (isa<ConstantAggregateZero>(CV)) {
960 Out << "zeroinitializer";
964 if (const BlockAddress *BA = dyn_cast<BlockAddress>(CV)) {
965 Out << "blockaddress(";
966 WriteAsOperandInternal(Out, BA->getFunction(), &TypePrinter, Machine);
968 WriteAsOperandInternal(Out, BA->getBasicBlock(), &TypePrinter, Machine);
973 if (const ConstantArray *CA = dyn_cast<ConstantArray>(CV)) {
974 // As a special case, print the array as a string if it is an array of
975 // i8 with ConstantInt values.
977 const Type *ETy = CA->getType()->getElementType();
978 if (CA->isString()) {
980 PrintEscapedString(CA->getAsString(), Out);
982 } else { // Cannot output in string format...
984 if (CA->getNumOperands()) {
985 TypePrinter.print(ETy, Out);
987 WriteAsOperandInternal(Out, CA->getOperand(0),
988 &TypePrinter, Machine);
989 for (unsigned i = 1, e = CA->getNumOperands(); i != e; ++i) {
991 TypePrinter.print(ETy, Out);
993 WriteAsOperandInternal(Out, CA->getOperand(i), &TypePrinter, Machine);
1001 if (const ConstantStruct *CS = dyn_cast<ConstantStruct>(CV)) {
1002 if (CS->getType()->isPacked())
1005 unsigned N = CS->getNumOperands();
1008 TypePrinter.print(CS->getOperand(0)->getType(), Out);
1011 WriteAsOperandInternal(Out, CS->getOperand(0), &TypePrinter, Machine);
1013 for (unsigned i = 1; i < N; i++) {
1015 TypePrinter.print(CS->getOperand(i)->getType(), Out);
1018 WriteAsOperandInternal(Out, CS->getOperand(i), &TypePrinter, Machine);
1024 if (CS->getType()->isPacked())
1029 if (const ConstantVector *CP = dyn_cast<ConstantVector>(CV)) {
1030 const Type *ETy = CP->getType()->getElementType();
1031 assert(CP->getNumOperands() > 0 &&
1032 "Number of operands for a PackedConst must be > 0");
1034 TypePrinter.print(ETy, Out);
1036 WriteAsOperandInternal(Out, CP->getOperand(0), &TypePrinter, Machine);
1037 for (unsigned i = 1, e = CP->getNumOperands(); i != e; ++i) {
1039 TypePrinter.print(ETy, Out);
1041 WriteAsOperandInternal(Out, CP->getOperand(i), &TypePrinter, Machine);
1047 if (isa<ConstantPointerNull>(CV)) {
1052 if (isa<UndefValue>(CV)) {
1057 if (const MDNode *Node = dyn_cast<MDNode>(CV)) {
1058 Out << "!" << Machine->getMetadataSlot(Node);
1062 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV)) {
1063 Out << CE->getOpcodeName();
1064 WriteOptimizationInfo(Out, CE);
1065 if (CE->isCompare())
1066 Out << ' ' << getPredicateText(CE->getPredicate());
1069 for (User::const_op_iterator OI=CE->op_begin(); OI != CE->op_end(); ++OI) {
1070 TypePrinter.print((*OI)->getType(), Out);
1072 WriteAsOperandInternal(Out, *OI, &TypePrinter, Machine);
1073 if (OI+1 != CE->op_end())
1077 if (CE->hasIndices()) {
1078 const SmallVector<unsigned, 4> &Indices = CE->getIndices();
1079 for (unsigned i = 0, e = Indices.size(); i != e; ++i)
1080 Out << ", " << Indices[i];
1085 TypePrinter.print(CE->getType(), Out);
1092 Out << "<placeholder or erroneous Constant>";
1095 static void WriteMDNodeBodyInternal(raw_ostream &Out, const MDNode *Node,
1096 TypePrinting *TypePrinter,
1097 SlotTracker *Machine) {
1099 for (unsigned mi = 0, me = Node->getNumOperands(); mi != me; ++mi) {
1100 const Value *V = Node->getOperand(mi);
1104 TypePrinter->print(V->getType(), Out);
1106 WriteAsOperandInternal(Out, Node->getOperand(mi),
1107 TypePrinter, Machine);
1117 /// WriteAsOperand - Write the name of the specified value out to the specified
1118 /// ostream. This can be useful when you just want to print int %reg126, not
1119 /// the whole instruction that generated it.
1121 static void WriteAsOperandInternal(raw_ostream &Out, const Value *V,
1122 TypePrinting *TypePrinter,
1123 SlotTracker *Machine) {
1125 PrintLLVMName(Out, V);
1129 const Constant *CV = dyn_cast<Constant>(V);
1130 if (CV && !isa<GlobalValue>(CV)) {
1131 assert(TypePrinter && "Constants require TypePrinting!");
1132 WriteConstantInt(Out, CV, *TypePrinter, Machine);
1136 if (const InlineAsm *IA = dyn_cast<InlineAsm>(V)) {
1138 if (IA->hasSideEffects())
1139 Out << "sideeffect ";
1140 if (IA->isAlignStack())
1141 Out << "alignstack ";
1143 PrintEscapedString(IA->getAsmString(), Out);
1145 PrintEscapedString(IA->getConstraintString(), Out);
1150 if (const MDNode *N = dyn_cast<MDNode>(V)) {
1151 if (N->isFunctionLocal()) {
1152 // Print metadata inline, not via slot reference number.
1153 WriteMDNodeBodyInternal(Out, N, TypePrinter, Machine);
1158 Machine = createSlotTracker(V);
1159 Out << '!' << Machine->getMetadataSlot(N);
1163 if (const MDString *MDS = dyn_cast<MDString>(V)) {
1165 PrintEscapedString(MDS->getString(), Out);
1170 if (V->getValueID() == Value::PseudoSourceValueVal ||
1171 V->getValueID() == Value::FixedStackPseudoSourceValueVal) {
1179 if (const GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
1180 Slot = Machine->getGlobalSlot(GV);
1183 Slot = Machine->getLocalSlot(V);
1186 Machine = createSlotTracker(V);
1188 if (const GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
1189 Slot = Machine->getGlobalSlot(GV);
1192 Slot = Machine->getLocalSlot(V);
1201 Out << Prefix << Slot;
1206 void llvm::WriteAsOperand(raw_ostream &Out, const Value *V,
1207 bool PrintType, const Module *Context) {
1209 // Fast path: Don't construct and populate a TypePrinting object if we
1210 // won't be needing any types printed.
1212 (!isa<Constant>(V) || V->hasName() || isa<GlobalValue>(V))) {
1213 WriteAsOperandInternal(Out, V, 0, 0);
1217 if (Context == 0) Context = getModuleFromVal(V);
1219 TypePrinting TypePrinter;
1220 std::vector<const Type*> NumberedTypes;
1221 AddModuleTypesToPrinter(TypePrinter, NumberedTypes, Context);
1223 TypePrinter.print(V->getType(), Out);
1227 WriteAsOperandInternal(Out, V, &TypePrinter, 0);
1232 class AssemblyWriter {
1233 formatted_raw_ostream &Out;
1234 SlotTracker &Machine;
1235 const Module *TheModule;
1236 TypePrinting TypePrinter;
1237 AssemblyAnnotationWriter *AnnotationWriter;
1238 std::vector<const Type*> NumberedTypes;
1239 SmallVector<StringRef, 8> MDNames;
1242 inline AssemblyWriter(formatted_raw_ostream &o, SlotTracker &Mac,
1244 AssemblyAnnotationWriter *AAW)
1245 : Out(o), Machine(Mac), TheModule(M), AnnotationWriter(AAW) {
1246 AddModuleTypesToPrinter(TypePrinter, NumberedTypes, M);
1248 M->getMDKindNames(MDNames);
1251 void printMDNodeBody(const MDNode *MD);
1252 void printNamedMDNode(const NamedMDNode *NMD);
1254 void printModule(const Module *M);
1256 void writeOperand(const Value *Op, bool PrintType);
1257 void writeParamOperand(const Value *Operand, Attributes Attrs);
1259 void writeAllMDNodes();
1261 void printTypeSymbolTable(const TypeSymbolTable &ST);
1262 void printGlobal(const GlobalVariable *GV);
1263 void printAlias(const GlobalAlias *GV);
1264 void printFunction(const Function *F);
1265 void printArgument(const Argument *FA, Attributes Attrs);
1266 void printBasicBlock(const BasicBlock *BB);
1267 void printInstruction(const Instruction &I);
1270 // printInfoComment - Print a little comment after the instruction indicating
1271 // which slot it occupies.
1272 void printInfoComment(const Value &V);
1274 } // end of anonymous namespace
1276 void AssemblyWriter::writeOperand(const Value *Operand, bool PrintType) {
1278 Out << "<null operand!>";
1282 TypePrinter.print(Operand->getType(), Out);
1285 WriteAsOperandInternal(Out, Operand, &TypePrinter, &Machine);
1288 void AssemblyWriter::writeParamOperand(const Value *Operand,
1291 Out << "<null operand!>";
1296 TypePrinter.print(Operand->getType(), Out);
1297 // Print parameter attributes list
1298 if (Attrs != Attribute::None)
1299 Out << ' ' << Attribute::getAsString(Attrs);
1301 // Print the operand
1302 WriteAsOperandInternal(Out, Operand, &TypePrinter, &Machine);
1305 void AssemblyWriter::printModule(const Module *M) {
1306 if (!M->getModuleIdentifier().empty() &&
1307 // Don't print the ID if it will start a new line (which would
1308 // require a comment char before it).
1309 M->getModuleIdentifier().find('\n') == std::string::npos)
1310 Out << "; ModuleID = '" << M->getModuleIdentifier() << "'\n";
1312 if (!M->getDataLayout().empty())
1313 Out << "target datalayout = \"" << M->getDataLayout() << "\"\n";
1314 if (!M->getTargetTriple().empty())
1315 Out << "target triple = \"" << M->getTargetTriple() << "\"\n";
1317 if (!M->getModuleInlineAsm().empty()) {
1318 // Split the string into lines, to make it easier to read the .ll file.
1319 std::string Asm = M->getModuleInlineAsm();
1321 size_t NewLine = Asm.find_first_of('\n', CurPos);
1323 while (NewLine != std::string::npos) {
1324 // We found a newline, print the portion of the asm string from the
1325 // last newline up to this newline.
1326 Out << "module asm \"";
1327 PrintEscapedString(std::string(Asm.begin()+CurPos, Asm.begin()+NewLine),
1331 NewLine = Asm.find_first_of('\n', CurPos);
1333 Out << "module asm \"";
1334 PrintEscapedString(std::string(Asm.begin()+CurPos, Asm.end()), Out);
1338 // Loop over the dependent libraries and emit them.
1339 Module::lib_iterator LI = M->lib_begin();
1340 Module::lib_iterator LE = M->lib_end();
1343 Out << "deplibs = [ ";
1345 Out << '"' << *LI << '"';
1353 // Loop over the symbol table, emitting all id'd types.
1354 if (!M->getTypeSymbolTable().empty() || !NumberedTypes.empty()) Out << '\n';
1355 printTypeSymbolTable(M->getTypeSymbolTable());
1357 // Output all globals.
1358 if (!M->global_empty()) Out << '\n';
1359 for (Module::const_global_iterator I = M->global_begin(), E = M->global_end();
1363 // Output all aliases.
1364 if (!M->alias_empty()) Out << "\n";
1365 for (Module::const_alias_iterator I = M->alias_begin(), E = M->alias_end();
1369 // Output all of the functions.
1370 for (Module::const_iterator I = M->begin(), E = M->end(); I != E; ++I)
1373 // Output named metadata.
1374 if (!M->named_metadata_empty()) Out << '\n';
1376 for (Module::const_named_metadata_iterator I = M->named_metadata_begin(),
1377 E = M->named_metadata_end(); I != E; ++I)
1378 printNamedMDNode(I);
1381 if (!Machine.mdn_empty()) {
1387 void AssemblyWriter::printNamedMDNode(const NamedMDNode *NMD) {
1388 Out << "!" << NMD->getName() << " = !{";
1389 for (unsigned i = 0, e = NMD->getNumOperands(); i != e; ++i) {
1391 if (MDNode *MD = NMD->getOperand(i))
1392 Out << '!' << Machine.getMetadataSlot(MD);
1400 static void PrintLinkage(GlobalValue::LinkageTypes LT,
1401 formatted_raw_ostream &Out) {
1403 case GlobalValue::ExternalLinkage: break;
1404 case GlobalValue::PrivateLinkage: Out << "private "; break;
1405 case GlobalValue::LinkerPrivateLinkage: Out << "linker_private "; break;
1406 case GlobalValue::InternalLinkage: Out << "internal "; break;
1407 case GlobalValue::LinkOnceAnyLinkage: Out << "linkonce "; break;
1408 case GlobalValue::LinkOnceODRLinkage: Out << "linkonce_odr "; break;
1409 case GlobalValue::WeakAnyLinkage: Out << "weak "; break;
1410 case GlobalValue::WeakODRLinkage: Out << "weak_odr "; break;
1411 case GlobalValue::CommonLinkage: Out << "common "; break;
1412 case GlobalValue::AppendingLinkage: Out << "appending "; break;
1413 case GlobalValue::DLLImportLinkage: Out << "dllimport "; break;
1414 case GlobalValue::DLLExportLinkage: Out << "dllexport "; break;
1415 case GlobalValue::ExternalWeakLinkage: Out << "extern_weak "; break;
1416 case GlobalValue::AvailableExternallyLinkage:
1417 Out << "available_externally ";
1423 static void PrintVisibility(GlobalValue::VisibilityTypes Vis,
1424 formatted_raw_ostream &Out) {
1426 case GlobalValue::DefaultVisibility: break;
1427 case GlobalValue::HiddenVisibility: Out << "hidden "; break;
1428 case GlobalValue::ProtectedVisibility: Out << "protected "; break;
1432 void AssemblyWriter::printGlobal(const GlobalVariable *GV) {
1433 if (GV->isMaterializable())
1434 Out << "; Materializable\n";
1436 WriteAsOperandInternal(Out, GV, &TypePrinter, &Machine);
1439 if (!GV->hasInitializer() && GV->hasExternalLinkage())
1442 PrintLinkage(GV->getLinkage(), Out);
1443 PrintVisibility(GV->getVisibility(), Out);
1445 if (GV->isThreadLocal()) Out << "thread_local ";
1446 if (unsigned AddressSpace = GV->getType()->getAddressSpace())
1447 Out << "addrspace(" << AddressSpace << ") ";
1448 Out << (GV->isConstant() ? "constant " : "global ");
1449 TypePrinter.print(GV->getType()->getElementType(), Out);
1451 if (GV->hasInitializer()) {
1453 writeOperand(GV->getInitializer(), false);
1456 if (GV->hasSection())
1457 Out << ", section \"" << GV->getSection() << '"';
1458 if (GV->getAlignment())
1459 Out << ", align " << GV->getAlignment();
1461 printInfoComment(*GV);
1465 void AssemblyWriter::printAlias(const GlobalAlias *GA) {
1466 if (GA->isMaterializable())
1467 Out << "; Materializable\n";
1469 // Don't crash when dumping partially built GA
1471 Out << "<<nameless>> = ";
1473 PrintLLVMName(Out, GA);
1476 PrintVisibility(GA->getVisibility(), Out);
1480 PrintLinkage(GA->getLinkage(), Out);
1482 const Constant *Aliasee = GA->getAliasee();
1484 if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(Aliasee)) {
1485 TypePrinter.print(GV->getType(), Out);
1487 PrintLLVMName(Out, GV);
1488 } else if (const Function *F = dyn_cast<Function>(Aliasee)) {
1489 TypePrinter.print(F->getFunctionType(), Out);
1492 WriteAsOperandInternal(Out, F, &TypePrinter, &Machine);
1493 } else if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(Aliasee)) {
1494 TypePrinter.print(GA->getType(), Out);
1496 PrintLLVMName(Out, GA);
1498 const ConstantExpr *CE = cast<ConstantExpr>(Aliasee);
1499 // The only valid GEP is an all zero GEP.
1500 assert((CE->getOpcode() == Instruction::BitCast ||
1501 CE->getOpcode() == Instruction::GetElementPtr) &&
1502 "Unsupported aliasee");
1503 writeOperand(CE, false);
1506 printInfoComment(*GA);
1510 void AssemblyWriter::printTypeSymbolTable(const TypeSymbolTable &ST) {
1511 // Emit all numbered types.
1512 for (unsigned i = 0, e = NumberedTypes.size(); i != e; ++i) {
1513 Out << '%' << i << " = type ";
1515 // Make sure we print out at least one level of the type structure, so
1516 // that we do not get %2 = type %2
1517 TypePrinter.printAtLeastOneLevel(NumberedTypes[i], Out);
1521 // Print the named types.
1522 for (TypeSymbolTable::const_iterator TI = ST.begin(), TE = ST.end();
1524 PrintLLVMName(Out, TI->first, LocalPrefix);
1527 // Make sure we print out at least one level of the type structure, so
1528 // that we do not get %FILE = type %FILE
1529 TypePrinter.printAtLeastOneLevel(TI->second, Out);
1534 /// printFunction - Print all aspects of a function.
1536 void AssemblyWriter::printFunction(const Function *F) {
1537 // Print out the return type and name.
1540 if (AnnotationWriter) AnnotationWriter->emitFunctionAnnot(F, Out);
1542 if (F->isMaterializable())
1543 Out << "; Materializable\n";
1545 if (F->isDeclaration())
1550 PrintLinkage(F->getLinkage(), Out);
1551 PrintVisibility(F->getVisibility(), Out);
1553 // Print the calling convention.
1554 switch (F->getCallingConv()) {
1555 case CallingConv::C: break; // default
1556 case CallingConv::Fast: Out << "fastcc "; break;
1557 case CallingConv::Cold: Out << "coldcc "; break;
1558 case CallingConv::X86_StdCall: Out << "x86_stdcallcc "; break;
1559 case CallingConv::X86_FastCall: Out << "x86_fastcallcc "; break;
1560 case CallingConv::ARM_APCS: Out << "arm_apcscc "; break;
1561 case CallingConv::ARM_AAPCS: Out << "arm_aapcscc "; break;
1562 case CallingConv::ARM_AAPCS_VFP:Out << "arm_aapcs_vfpcc "; break;
1563 case CallingConv::MSP430_INTR: Out << "msp430_intrcc "; break;
1564 default: Out << "cc" << F->getCallingConv() << " "; break;
1567 const FunctionType *FT = F->getFunctionType();
1568 const AttrListPtr &Attrs = F->getAttributes();
1569 Attributes RetAttrs = Attrs.getRetAttributes();
1570 if (RetAttrs != Attribute::None)
1571 Out << Attribute::getAsString(Attrs.getRetAttributes()) << ' ';
1572 TypePrinter.print(F->getReturnType(), Out);
1574 WriteAsOperandInternal(Out, F, &TypePrinter, &Machine);
1576 Machine.incorporateFunction(F);
1578 // Loop over the arguments, printing them...
1581 if (!F->isDeclaration()) {
1582 // If this isn't a declaration, print the argument names as well.
1583 for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
1585 // Insert commas as we go... the first arg doesn't get a comma
1586 if (I != F->arg_begin()) Out << ", ";
1587 printArgument(I, Attrs.getParamAttributes(Idx));
1591 // Otherwise, print the types from the function type.
1592 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
1593 // Insert commas as we go... the first arg doesn't get a comma
1597 TypePrinter.print(FT->getParamType(i), Out);
1599 Attributes ArgAttrs = Attrs.getParamAttributes(i+1);
1600 if (ArgAttrs != Attribute::None)
1601 Out << ' ' << Attribute::getAsString(ArgAttrs);
1605 // Finish printing arguments...
1606 if (FT->isVarArg()) {
1607 if (FT->getNumParams()) Out << ", ";
1608 Out << "..."; // Output varargs portion of signature!
1611 Attributes FnAttrs = Attrs.getFnAttributes();
1612 if (FnAttrs != Attribute::None)
1613 Out << ' ' << Attribute::getAsString(Attrs.getFnAttributes());
1614 if (F->hasSection())
1615 Out << " section \"" << F->getSection() << '"';
1616 if (F->getAlignment())
1617 Out << " align " << F->getAlignment();
1619 Out << " gc \"" << F->getGC() << '"';
1620 if (F->isDeclaration()) {
1625 // Output all of its basic blocks... for the function
1626 for (Function::const_iterator I = F->begin(), E = F->end(); I != E; ++I)
1632 Machine.purgeFunction();
1635 /// printArgument - This member is called for every argument that is passed into
1636 /// the function. Simply print it out
1638 void AssemblyWriter::printArgument(const Argument *Arg,
1641 TypePrinter.print(Arg->getType(), Out);
1643 // Output parameter attributes list
1644 if (Attrs != Attribute::None)
1645 Out << ' ' << Attribute::getAsString(Attrs);
1647 // Output name, if available...
1648 if (Arg->hasName()) {
1650 PrintLLVMName(Out, Arg);
1654 /// printBasicBlock - This member is called for each basic block in a method.
1656 void AssemblyWriter::printBasicBlock(const BasicBlock *BB) {
1657 if (BB->hasName()) { // Print out the label if it exists...
1659 PrintLLVMName(Out, BB->getName(), LabelPrefix);
1661 } else if (!BB->use_empty()) { // Don't print block # of no uses...
1662 Out << "\n; <label>:";
1663 int Slot = Machine.getLocalSlot(BB);
1670 if (BB->getParent() == 0) {
1671 Out.PadToColumn(50);
1672 Out << "; Error: Block without parent!";
1673 } else if (BB != &BB->getParent()->getEntryBlock()) { // Not the entry block?
1674 // Output predecessors for the block...
1675 Out.PadToColumn(50);
1677 pred_const_iterator PI = pred_begin(BB), PE = pred_end(BB);
1680 Out << " No predecessors!";
1683 writeOperand(*PI, false);
1684 for (++PI; PI != PE; ++PI) {
1686 writeOperand(*PI, false);
1693 if (AnnotationWriter) AnnotationWriter->emitBasicBlockStartAnnot(BB, Out);
1695 // Output all of the instructions in the basic block...
1696 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I != E; ++I) {
1697 printInstruction(*I);
1701 if (AnnotationWriter) AnnotationWriter->emitBasicBlockEndAnnot(BB, Out);
1704 /// printInfoComment - Print a little comment after the instruction indicating
1705 /// which slot it occupies.
1707 void AssemblyWriter::printInfoComment(const Value &V) {
1708 if (AnnotationWriter) {
1709 AnnotationWriter->printInfoComment(V, Out);
1713 if (V.getType()->isVoidTy()) return;
1715 Out.PadToColumn(50);
1717 TypePrinter.print(V.getType(), Out);
1718 Out << "> [#uses=" << V.getNumUses() << ']'; // Output # uses
1721 // This member is called for each Instruction in a function..
1722 void AssemblyWriter::printInstruction(const Instruction &I) {
1723 if (AnnotationWriter) AnnotationWriter->emitInstructionAnnot(&I, Out);
1725 // Print out indentation for an instruction.
1728 // Print out name if it exists...
1730 PrintLLVMName(Out, &I);
1732 } else if (!I.getType()->isVoidTy()) {
1733 // Print out the def slot taken.
1734 int SlotNum = Machine.getLocalSlot(&I);
1736 Out << "<badref> = ";
1738 Out << '%' << SlotNum << " = ";
1741 // If this is a volatile load or store, print out the volatile marker.
1742 if ((isa<LoadInst>(I) && cast<LoadInst>(I).isVolatile()) ||
1743 (isa<StoreInst>(I) && cast<StoreInst>(I).isVolatile())) {
1745 } else if (isa<CallInst>(I) && cast<CallInst>(I).isTailCall()) {
1746 // If this is a call, check if it's a tail call.
1750 // Print out the opcode...
1751 Out << I.getOpcodeName();
1753 // Print out optimization information.
1754 WriteOptimizationInfo(Out, &I);
1756 // Print out the compare instruction predicates
1757 if (const CmpInst *CI = dyn_cast<CmpInst>(&I))
1758 Out << ' ' << getPredicateText(CI->getPredicate());
1760 // Print out the type of the operands...
1761 const Value *Operand = I.getNumOperands() ? I.getOperand(0) : 0;
1763 // Special case conditional branches to swizzle the condition out to the front
1764 if (isa<BranchInst>(I) && cast<BranchInst>(I).isConditional()) {
1765 BranchInst &BI(cast<BranchInst>(I));
1767 writeOperand(BI.getCondition(), true);
1769 writeOperand(BI.getSuccessor(0), true);
1771 writeOperand(BI.getSuccessor(1), true);
1773 } else if (isa<SwitchInst>(I)) {
1774 // Special case switch instruction to get formatting nice and correct.
1776 writeOperand(Operand , true);
1778 writeOperand(I.getOperand(1), true);
1781 for (unsigned op = 2, Eop = I.getNumOperands(); op < Eop; op += 2) {
1783 writeOperand(I.getOperand(op ), true);
1785 writeOperand(I.getOperand(op+1), true);
1788 } else if (isa<IndirectBrInst>(I)) {
1789 // Special case indirectbr instruction to get formatting nice and correct.
1791 writeOperand(Operand, true);
1794 for (unsigned i = 1, e = I.getNumOperands(); i != e; ++i) {
1797 writeOperand(I.getOperand(i), true);
1800 } else if (isa<PHINode>(I)) {
1802 TypePrinter.print(I.getType(), Out);
1805 for (unsigned op = 0, Eop = I.getNumOperands(); op < Eop; op += 2) {
1806 if (op) Out << ", ";
1808 writeOperand(I.getOperand(op ), false); Out << ", ";
1809 writeOperand(I.getOperand(op+1), false); Out << " ]";
1811 } else if (const ExtractValueInst *EVI = dyn_cast<ExtractValueInst>(&I)) {
1813 writeOperand(I.getOperand(0), true);
1814 for (const unsigned *i = EVI->idx_begin(), *e = EVI->idx_end(); i != e; ++i)
1816 } else if (const InsertValueInst *IVI = dyn_cast<InsertValueInst>(&I)) {
1818 writeOperand(I.getOperand(0), true); Out << ", ";
1819 writeOperand(I.getOperand(1), true);
1820 for (const unsigned *i = IVI->idx_begin(), *e = IVI->idx_end(); i != e; ++i)
1822 } else if (isa<ReturnInst>(I) && !Operand) {
1824 } else if (const CallInst *CI = dyn_cast<CallInst>(&I)) {
1825 // Print the calling convention being used.
1826 switch (CI->getCallingConv()) {
1827 case CallingConv::C: break; // default
1828 case CallingConv::Fast: Out << " fastcc"; break;
1829 case CallingConv::Cold: Out << " coldcc"; break;
1830 case CallingConv::X86_StdCall: Out << " x86_stdcallcc"; break;
1831 case CallingConv::X86_FastCall: Out << " x86_fastcallcc"; break;
1832 case CallingConv::ARM_APCS: Out << " arm_apcscc "; break;
1833 case CallingConv::ARM_AAPCS: Out << " arm_aapcscc "; break;
1834 case CallingConv::ARM_AAPCS_VFP:Out << " arm_aapcs_vfpcc "; break;
1835 case CallingConv::MSP430_INTR: Out << " msp430_intrcc "; break;
1836 default: Out << " cc" << CI->getCallingConv(); break;
1839 const PointerType *PTy = cast<PointerType>(Operand->getType());
1840 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
1841 const Type *RetTy = FTy->getReturnType();
1842 const AttrListPtr &PAL = CI->getAttributes();
1844 if (PAL.getRetAttributes() != Attribute::None)
1845 Out << ' ' << Attribute::getAsString(PAL.getRetAttributes());
1847 // If possible, print out the short form of the call instruction. We can
1848 // only do this if the first argument is a pointer to a nonvararg function,
1849 // and if the return type is not a pointer to a function.
1852 if (!FTy->isVarArg() &&
1853 (!RetTy->isPointerTy() ||
1854 !cast<PointerType>(RetTy)->getElementType()->isFunctionTy())) {
1855 TypePrinter.print(RetTy, Out);
1857 writeOperand(Operand, false);
1859 writeOperand(Operand, true);
1862 for (unsigned op = 1, Eop = I.getNumOperands(); op < Eop; ++op) {
1865 writeParamOperand(I.getOperand(op), PAL.getParamAttributes(op));
1868 if (PAL.getFnAttributes() != Attribute::None)
1869 Out << ' ' << Attribute::getAsString(PAL.getFnAttributes());
1870 } else if (const InvokeInst *II = dyn_cast<InvokeInst>(&I)) {
1871 const PointerType *PTy = cast<PointerType>(Operand->getType());
1872 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
1873 const Type *RetTy = FTy->getReturnType();
1874 const AttrListPtr &PAL = II->getAttributes();
1876 // Print the calling convention being used.
1877 switch (II->getCallingConv()) {
1878 case CallingConv::C: break; // default
1879 case CallingConv::Fast: Out << " fastcc"; break;
1880 case CallingConv::Cold: Out << " coldcc"; break;
1881 case CallingConv::X86_StdCall: Out << " x86_stdcallcc"; break;
1882 case CallingConv::X86_FastCall: Out << " x86_fastcallcc"; break;
1883 case CallingConv::ARM_APCS: Out << " arm_apcscc "; break;
1884 case CallingConv::ARM_AAPCS: Out << " arm_aapcscc "; break;
1885 case CallingConv::ARM_AAPCS_VFP:Out << " arm_aapcs_vfpcc "; break;
1886 case CallingConv::MSP430_INTR: Out << " msp430_intrcc "; break;
1887 default: Out << " cc" << II->getCallingConv(); break;
1890 if (PAL.getRetAttributes() != Attribute::None)
1891 Out << ' ' << Attribute::getAsString(PAL.getRetAttributes());
1893 // If possible, print out the short form of the invoke instruction. We can
1894 // only do this if the first argument is a pointer to a nonvararg function,
1895 // and if the return type is not a pointer to a function.
1898 if (!FTy->isVarArg() &&
1899 (!RetTy->isPointerTy() ||
1900 !cast<PointerType>(RetTy)->getElementType()->isFunctionTy())) {
1901 TypePrinter.print(RetTy, Out);
1903 writeOperand(Operand, false);
1905 writeOperand(Operand, true);
1908 for (unsigned op = 3, Eop = I.getNumOperands(); op < Eop; ++op) {
1911 writeParamOperand(I.getOperand(op), PAL.getParamAttributes(op-2));
1915 if (PAL.getFnAttributes() != Attribute::None)
1916 Out << ' ' << Attribute::getAsString(PAL.getFnAttributes());
1919 writeOperand(II->getNormalDest(), true);
1921 writeOperand(II->getUnwindDest(), true);
1923 } else if (const AllocaInst *AI = dyn_cast<AllocaInst>(&I)) {
1925 TypePrinter.print(AI->getType()->getElementType(), Out);
1926 if (!AI->getArraySize() || AI->isArrayAllocation()) {
1928 writeOperand(AI->getArraySize(), true);
1930 if (AI->getAlignment()) {
1931 Out << ", align " << AI->getAlignment();
1933 } else if (isa<CastInst>(I)) {
1936 writeOperand(Operand, true); // Work with broken code
1939 TypePrinter.print(I.getType(), Out);
1940 } else if (isa<VAArgInst>(I)) {
1943 writeOperand(Operand, true); // Work with broken code
1946 TypePrinter.print(I.getType(), Out);
1947 } else if (Operand) { // Print the normal way.
1949 // PrintAllTypes - Instructions who have operands of all the same type
1950 // omit the type from all but the first operand. If the instruction has
1951 // different type operands (for example br), then they are all printed.
1952 bool PrintAllTypes = false;
1953 const Type *TheType = Operand->getType();
1955 // Select, Store and ShuffleVector always print all types.
1956 if (isa<SelectInst>(I) || isa<StoreInst>(I) || isa<ShuffleVectorInst>(I)
1957 || isa<ReturnInst>(I)) {
1958 PrintAllTypes = true;
1960 for (unsigned i = 1, E = I.getNumOperands(); i != E; ++i) {
1961 Operand = I.getOperand(i);
1962 // note that Operand shouldn't be null, but the test helps make dump()
1963 // more tolerant of malformed IR
1964 if (Operand && Operand->getType() != TheType) {
1965 PrintAllTypes = true; // We have differing types! Print them all!
1971 if (!PrintAllTypes) {
1973 TypePrinter.print(TheType, Out);
1977 for (unsigned i = 0, E = I.getNumOperands(); i != E; ++i) {
1979 writeOperand(I.getOperand(i), PrintAllTypes);
1983 // Print post operand alignment for load/store.
1984 if (isa<LoadInst>(I) && cast<LoadInst>(I).getAlignment()) {
1985 Out << ", align " << cast<LoadInst>(I).getAlignment();
1986 } else if (isa<StoreInst>(I) && cast<StoreInst>(I).getAlignment()) {
1987 Out << ", align " << cast<StoreInst>(I).getAlignment();
1990 // Print Metadata info.
1991 if (!MDNames.empty()) {
1992 SmallVector<std::pair<unsigned, MDNode*>, 4> InstMD;
1993 I.getAllMetadata(InstMD);
1994 for (unsigned i = 0, e = InstMD.size(); i != e; ++i)
1995 Out << ", !" << MDNames[InstMD[i].first]
1996 << " !" << Machine.getMetadataSlot(InstMD[i].second);
1998 printInfoComment(I);
2001 static void WriteMDNodeComment(const MDNode *Node,
2002 formatted_raw_ostream &Out) {
2003 if (Node->getNumOperands() < 1)
2005 ConstantInt *CI = dyn_cast_or_null<ConstantInt>(Node->getOperand(0));
2007 unsigned Val = CI->getZExtValue();
2008 unsigned Tag = Val & ~LLVMDebugVersionMask;
2009 if (Val < LLVMDebugVersion)
2012 Out.PadToColumn(50);
2013 if (Tag == dwarf::DW_TAG_auto_variable)
2014 Out << "; [ DW_TAG_auto_variable ]";
2015 else if (Tag == dwarf::DW_TAG_arg_variable)
2016 Out << "; [ DW_TAG_arg_variable ]";
2017 else if (Tag == dwarf::DW_TAG_return_variable)
2018 Out << "; [ DW_TAG_return_variable ]";
2019 else if (Tag == dwarf::DW_TAG_vector_type)
2020 Out << "; [ DW_TAG_vector_type ]";
2021 else if (Tag == dwarf::DW_TAG_user_base)
2022 Out << "; [ DW_TAG_user_base ]";
2023 else if (const char *TagName = dwarf::TagString(Tag))
2024 Out << "; [ " << TagName << " ]";
2027 void AssemblyWriter::writeAllMDNodes() {
2028 SmallVector<const MDNode *, 16> Nodes;
2029 Nodes.resize(Machine.mdn_size());
2030 for (SlotTracker::mdn_iterator I = Machine.mdn_begin(), E = Machine.mdn_end();
2032 Nodes[I->second] = cast<MDNode>(I->first);
2034 for (unsigned i = 0, e = Nodes.size(); i != e; ++i) {
2035 Out << '!' << i << " = metadata ";
2036 printMDNodeBody(Nodes[i]);
2040 void AssemblyWriter::printMDNodeBody(const MDNode *Node) {
2041 WriteMDNodeBodyInternal(Out, Node, &TypePrinter, &Machine);
2042 WriteMDNodeComment(Node, Out);
2046 //===----------------------------------------------------------------------===//
2047 // External Interface declarations
2048 //===----------------------------------------------------------------------===//
2050 void Module::print(raw_ostream &ROS, AssemblyAnnotationWriter *AAW) const {
2051 SlotTracker SlotTable(this);
2052 formatted_raw_ostream OS(ROS);
2053 AssemblyWriter W(OS, SlotTable, this, AAW);
2054 W.printModule(this);
2057 void Type::print(raw_ostream &OS) const {
2059 OS << "<null Type>";
2062 TypePrinting().print(this, OS);
2065 void Value::print(raw_ostream &ROS, AssemblyAnnotationWriter *AAW) const {
2067 ROS << "printing a <null> value\n";
2070 formatted_raw_ostream OS(ROS);
2071 if (const Instruction *I = dyn_cast<Instruction>(this)) {
2072 const Function *F = I->getParent() ? I->getParent()->getParent() : 0;
2073 SlotTracker SlotTable(F);
2074 AssemblyWriter W(OS, SlotTable, getModuleFromVal(I), AAW);
2075 W.printInstruction(*I);
2076 } else if (const BasicBlock *BB = dyn_cast<BasicBlock>(this)) {
2077 SlotTracker SlotTable(BB->getParent());
2078 AssemblyWriter W(OS, SlotTable, getModuleFromVal(BB), AAW);
2079 W.printBasicBlock(BB);
2080 } else if (const GlobalValue *GV = dyn_cast<GlobalValue>(this)) {
2081 SlotTracker SlotTable(GV->getParent());
2082 AssemblyWriter W(OS, SlotTable, GV->getParent(), AAW);
2083 if (const GlobalVariable *V = dyn_cast<GlobalVariable>(GV))
2085 else if (const Function *F = dyn_cast<Function>(GV))
2088 W.printAlias(cast<GlobalAlias>(GV));
2089 } else if (const MDNode *N = dyn_cast<MDNode>(this)) {
2090 const Function *F = N->getFunction();
2091 SlotTracker SlotTable(F);
2092 AssemblyWriter W(OS, SlotTable, F ? getModuleFromVal(F) : 0, AAW);
2093 W.printMDNodeBody(N);
2094 } else if (const NamedMDNode *N = dyn_cast<NamedMDNode>(this)) {
2095 SlotTracker SlotTable(N->getParent());
2096 AssemblyWriter W(OS, SlotTable, N->getParent(), AAW);
2097 W.printNamedMDNode(N);
2098 } else if (const Constant *C = dyn_cast<Constant>(this)) {
2099 TypePrinting TypePrinter;
2100 TypePrinter.print(C->getType(), OS);
2102 WriteConstantInt(OS, C, TypePrinter, 0);
2103 } else if (isa<InlineAsm>(this) || isa<MDString>(this) ||
2104 isa<Argument>(this)) {
2105 WriteAsOperand(OS, this, true, 0);
2107 // Otherwise we don't know what it is. Call the virtual function to
2108 // allow a subclass to print itself.
2113 // Value::printCustom - subclasses should override this to implement printing.
2114 void Value::printCustom(raw_ostream &OS) const {
2115 llvm_unreachable("Unknown value to print out!");
2118 // Value::dump - allow easy printing of Values from the debugger.
2119 void Value::dump() const { print(dbgs()); dbgs() << '\n'; }
2121 // Type::dump - allow easy printing of Types from the debugger.
2122 // This one uses type names from the given context module
2123 void Type::dump(const Module *Context) const {
2124 WriteTypeSymbolic(dbgs(), this, Context);
2128 // Type::dump - allow easy printing of Types from the debugger.
2129 void Type::dump() const { dump(0); }
2131 // Module::dump() - Allow printing of Modules from the debugger.
2132 void Module::dump() const { print(dbgs(), 0); }