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/StringExtras.h"
31 #include "llvm/ADT/STLExtras.h"
32 #include "llvm/Support/CFG.h"
33 #include "llvm/Support/Debug.h"
34 #include "llvm/Support/Dwarf.h"
35 #include "llvm/Support/ErrorHandling.h"
36 #include "llvm/Support/MathExtras.h"
37 #include "llvm/Support/FormattedStream.h"
43 // Make virtual table appear in this compilation unit.
44 AssemblyAnnotationWriter::~AssemblyAnnotationWriter() {}
46 //===----------------------------------------------------------------------===//
48 //===----------------------------------------------------------------------===//
50 static const Module *getModuleFromVal(const Value *V) {
51 if (const Argument *MA = dyn_cast<Argument>(V))
52 return MA->getParent() ? MA->getParent()->getParent() : 0;
54 if (const BasicBlock *BB = dyn_cast<BasicBlock>(V))
55 return BB->getParent() ? BB->getParent()->getParent() : 0;
57 if (const Instruction *I = dyn_cast<Instruction>(V)) {
58 const Function *M = I->getParent() ? I->getParent()->getParent() : 0;
59 return M ? M->getParent() : 0;
62 if (const GlobalValue *GV = dyn_cast<GlobalValue>(V))
63 return GV->getParent();
64 if (const NamedMDNode *NMD = dyn_cast<NamedMDNode>(V))
65 return NMD->getParent();
69 // PrintEscapedString - Print each character of the specified string, escaping
70 // it if it is not printable or if it is an escape char.
71 static void PrintEscapedString(const StringRef &Name,
73 for (unsigned i = 0, e = Name.size(); i != e; ++i) {
74 unsigned char C = Name[i];
75 if (isprint(C) && C != '\\' && C != '"')
78 Out << '\\' << hexdigit(C >> 4) << hexdigit(C & 0x0F);
89 /// PrintLLVMName - Turn the specified name into an 'LLVM name', which is either
90 /// prefixed with % (if the string only contains simple characters) or is
91 /// surrounded with ""'s (if it has special chars in it). Print it out.
92 static void PrintLLVMName(raw_ostream &OS, const StringRef &Name,
94 assert(Name.data() && "Cannot get empty name!");
96 default: llvm_unreachable("Bad prefix!");
98 case GlobalPrefix: OS << '@'; break;
99 case LabelPrefix: break;
100 case LocalPrefix: OS << '%'; break;
103 // Scan the name to see if it needs quotes first.
104 bool NeedsQuotes = isdigit(Name[0]);
106 for (unsigned i = 0, e = Name.size(); i != e; ++i) {
108 if (!isalnum(C) && C != '-' && C != '.' && C != '_') {
115 // If we didn't need any quotes, just write out the name in one blast.
121 // Okay, we need quotes. Output the quotes and escape any scary characters as
124 PrintEscapedString(Name, OS);
128 /// PrintLLVMName - Turn the specified name into an 'LLVM name', which is either
129 /// prefixed with % (if the string only contains simple characters) or is
130 /// surrounded with ""'s (if it has special chars in it). Print it out.
131 static void PrintLLVMName(raw_ostream &OS, const Value *V) {
132 PrintLLVMName(OS, V->getName(),
133 isa<GlobalValue>(V) ? GlobalPrefix : LocalPrefix);
136 //===----------------------------------------------------------------------===//
137 // TypePrinting Class: Type printing machinery
138 //===----------------------------------------------------------------------===//
140 static DenseMap<const Type *, std::string> &getTypeNamesMap(void *M) {
141 return *static_cast<DenseMap<const Type *, std::string>*>(M);
144 void TypePrinting::clear() {
145 getTypeNamesMap(TypeNames).clear();
148 bool TypePrinting::hasTypeName(const Type *Ty) const {
149 return getTypeNamesMap(TypeNames).count(Ty);
152 void TypePrinting::addTypeName(const Type *Ty, const std::string &N) {
153 getTypeNamesMap(TypeNames).insert(std::make_pair(Ty, N));
157 TypePrinting::TypePrinting() {
158 TypeNames = new DenseMap<const Type *, std::string>();
161 TypePrinting::~TypePrinting() {
162 delete &getTypeNamesMap(TypeNames);
165 /// CalcTypeName - Write the specified type to the specified raw_ostream, making
166 /// use of type names or up references to shorten the type name where possible.
167 void TypePrinting::CalcTypeName(const Type *Ty,
168 SmallVectorImpl<const Type *> &TypeStack,
169 raw_ostream &OS, bool IgnoreTopLevelName) {
170 // Check to see if the type is named.
171 if (!IgnoreTopLevelName) {
172 DenseMap<const Type *, std::string> &TM = getTypeNamesMap(TypeNames);
173 DenseMap<const Type *, std::string>::iterator I = TM.find(Ty);
180 // Check to see if the Type is already on the stack...
181 unsigned Slot = 0, CurSize = TypeStack.size();
182 while (Slot < CurSize && TypeStack[Slot] != Ty) ++Slot; // Scan for type
184 // This is another base case for the recursion. In this case, we know
185 // that we have looped back to a type that we have previously visited.
186 // Generate the appropriate upreference to handle this.
187 if (Slot < CurSize) {
188 OS << '\\' << unsigned(CurSize-Slot); // Here's the upreference
192 TypeStack.push_back(Ty); // Recursive case: Add us to the stack..
194 switch (Ty->getTypeID()) {
195 case Type::VoidTyID: OS << "void"; break;
196 case Type::FloatTyID: OS << "float"; break;
197 case Type::DoubleTyID: OS << "double"; break;
198 case Type::X86_FP80TyID: OS << "x86_fp80"; break;
199 case Type::FP128TyID: OS << "fp128"; break;
200 case Type::PPC_FP128TyID: OS << "ppc_fp128"; break;
201 case Type::LabelTyID: OS << "label"; break;
202 case Type::MetadataTyID: OS << "metadata"; break;
203 case Type::IntegerTyID:
204 OS << 'i' << cast<IntegerType>(Ty)->getBitWidth();
207 case Type::FunctionTyID: {
208 const FunctionType *FTy = cast<FunctionType>(Ty);
209 CalcTypeName(FTy->getReturnType(), TypeStack, OS);
211 for (FunctionType::param_iterator I = FTy->param_begin(),
212 E = FTy->param_end(); I != E; ++I) {
213 if (I != FTy->param_begin())
215 CalcTypeName(*I, TypeStack, OS);
217 if (FTy->isVarArg()) {
218 if (FTy->getNumParams()) OS << ", ";
224 case Type::StructTyID: {
225 const StructType *STy = cast<StructType>(Ty);
229 for (StructType::element_iterator I = STy->element_begin(),
230 E = STy->element_end(); I != E; ++I) {
231 CalcTypeName(*I, TypeStack, OS);
232 if (next(I) != STy->element_end())
241 case Type::PointerTyID: {
242 const PointerType *PTy = cast<PointerType>(Ty);
243 CalcTypeName(PTy->getElementType(), TypeStack, OS);
244 if (unsigned AddressSpace = PTy->getAddressSpace())
245 OS << " addrspace(" << AddressSpace << ')';
249 case Type::ArrayTyID: {
250 const ArrayType *ATy = cast<ArrayType>(Ty);
251 OS << '[' << ATy->getNumElements() << " x ";
252 CalcTypeName(ATy->getElementType(), TypeStack, OS);
256 case Type::VectorTyID: {
257 const VectorType *PTy = cast<VectorType>(Ty);
258 OS << "<" << PTy->getNumElements() << " x ";
259 CalcTypeName(PTy->getElementType(), TypeStack, OS);
263 case Type::OpaqueTyID:
267 OS << "<unrecognized-type>";
271 TypeStack.pop_back(); // Remove self from stack.
274 /// printTypeInt - The internal guts of printing out a type that has a
275 /// potentially named portion.
277 void TypePrinting::print(const Type *Ty, raw_ostream &OS,
278 bool IgnoreTopLevelName) {
279 // Check to see if the type is named.
280 DenseMap<const Type*, std::string> &TM = getTypeNamesMap(TypeNames);
281 if (!IgnoreTopLevelName) {
282 DenseMap<const Type*, std::string>::iterator I = TM.find(Ty);
289 // Otherwise we have a type that has not been named but is a derived type.
290 // Carefully recurse the type hierarchy to print out any contained symbolic
292 SmallVector<const Type *, 16> TypeStack;
293 std::string TypeName;
295 raw_string_ostream TypeOS(TypeName);
296 CalcTypeName(Ty, TypeStack, TypeOS, IgnoreTopLevelName);
299 // Cache type name for later use.
300 if (!IgnoreTopLevelName)
301 TM.insert(std::make_pair(Ty, TypeOS.str()));
306 // To avoid walking constant expressions multiple times and other IR
307 // objects, we keep several helper maps.
308 DenseSet<const Value*> VisitedConstants;
309 DenseSet<const Type*> VisitedTypes;
312 std::vector<const Type*> &NumberedTypes;
314 TypeFinder(TypePrinting &tp, std::vector<const Type*> &numberedTypes)
315 : TP(tp), NumberedTypes(numberedTypes) {}
317 void Run(const Module &M) {
318 // Get types from the type symbol table. This gets opaque types referened
319 // only through derived named types.
320 const TypeSymbolTable &ST = M.getTypeSymbolTable();
321 for (TypeSymbolTable::const_iterator TI = ST.begin(), E = ST.end();
323 IncorporateType(TI->second);
325 // Get types from global variables.
326 for (Module::const_global_iterator I = M.global_begin(),
327 E = M.global_end(); I != E; ++I) {
328 IncorporateType(I->getType());
329 if (I->hasInitializer())
330 IncorporateValue(I->getInitializer());
333 // Get types from aliases.
334 for (Module::const_alias_iterator I = M.alias_begin(),
335 E = M.alias_end(); I != E; ++I) {
336 IncorporateType(I->getType());
337 IncorporateValue(I->getAliasee());
340 // Get types from functions.
341 for (Module::const_iterator FI = M.begin(), E = M.end(); FI != E; ++FI) {
342 IncorporateType(FI->getType());
344 for (Function::const_iterator BB = FI->begin(), E = FI->end();
346 for (BasicBlock::const_iterator II = BB->begin(),
347 E = BB->end(); II != E; ++II) {
348 const Instruction &I = *II;
349 // Incorporate the type of the instruction and all its operands.
350 IncorporateType(I.getType());
351 for (User::const_op_iterator OI = I.op_begin(), OE = I.op_end();
353 IncorporateValue(*OI);
359 void IncorporateType(const Type *Ty) {
360 // Check to see if we're already visited this type.
361 if (!VisitedTypes.insert(Ty).second)
364 // If this is a structure or opaque type, add a name for the type.
365 if (((isa<StructType>(Ty) && cast<StructType>(Ty)->getNumElements())
366 || isa<OpaqueType>(Ty)) && !TP.hasTypeName(Ty)) {
367 TP.addTypeName(Ty, "%"+utostr(unsigned(NumberedTypes.size())));
368 NumberedTypes.push_back(Ty);
371 // Recursively walk all contained types.
372 for (Type::subtype_iterator I = Ty->subtype_begin(),
373 E = Ty->subtype_end(); I != E; ++I)
377 /// IncorporateValue - This method is used to walk operand lists finding
378 /// types hiding in constant expressions and other operands that won't be
379 /// walked in other ways. GlobalValues, basic blocks, instructions, and
380 /// inst operands are all explicitly enumerated.
381 void IncorporateValue(const Value *V) {
382 if (V == 0 || !isa<Constant>(V) || isa<GlobalValue>(V)) return;
385 if (!VisitedConstants.insert(V).second)
389 IncorporateType(V->getType());
391 // Look in operands for types.
392 const Constant *C = cast<Constant>(V);
393 for (Constant::const_op_iterator I = C->op_begin(),
394 E = C->op_end(); I != E;++I)
395 IncorporateValue(*I);
398 } // end anonymous namespace
401 /// AddModuleTypesToPrinter - Add all of the symbolic type names for types in
402 /// the specified module to the TypePrinter and all numbered types to it and the
403 /// NumberedTypes table.
404 static void AddModuleTypesToPrinter(TypePrinting &TP,
405 std::vector<const Type*> &NumberedTypes,
409 // If the module has a symbol table, take all global types and stuff their
410 // names into the TypeNames map.
411 const TypeSymbolTable &ST = M->getTypeSymbolTable();
412 for (TypeSymbolTable::const_iterator TI = ST.begin(), E = ST.end();
414 const Type *Ty = cast<Type>(TI->second);
416 // As a heuristic, don't insert pointer to primitive types, because
417 // they are used too often to have a single useful name.
418 if (const PointerType *PTy = dyn_cast<PointerType>(Ty)) {
419 const Type *PETy = PTy->getElementType();
420 if ((PETy->isPrimitiveType() || PETy->isInteger()) &&
421 !isa<OpaqueType>(PETy))
425 // Likewise don't insert primitives either.
426 if (Ty->isInteger() || Ty->isPrimitiveType())
429 // Get the name as a string and insert it into TypeNames.
431 raw_string_ostream NameROS(NameStr);
432 formatted_raw_ostream NameOS(NameROS);
433 PrintLLVMName(NameOS, TI->first, LocalPrefix);
435 TP.addTypeName(Ty, NameStr);
438 // Walk the entire module to find references to unnamed structure and opaque
439 // types. This is required for correctness by opaque types (because multiple
440 // uses of an unnamed opaque type needs to be referred to by the same ID) and
441 // it shrinks complex recursive structure types substantially in some cases.
442 TypeFinder(TP, NumberedTypes).Run(*M);
446 /// WriteTypeSymbolic - This attempts to write the specified type as a symbolic
447 /// type, iff there is an entry in the modules symbol table for the specified
448 /// type or one of it's component types.
450 void llvm::WriteTypeSymbolic(raw_ostream &OS, const Type *Ty, const Module *M) {
451 TypePrinting Printer;
452 std::vector<const Type*> NumberedTypes;
453 AddModuleTypesToPrinter(Printer, NumberedTypes, M);
454 Printer.print(Ty, OS);
457 //===----------------------------------------------------------------------===//
458 // SlotTracker Class: Enumerate slot numbers for unnamed values
459 //===----------------------------------------------------------------------===//
463 /// This class provides computation of slot numbers for LLVM Assembly writing.
467 /// ValueMap - A mapping of Values to slot numbers.
468 typedef DenseMap<const Value*, unsigned> ValueMap;
471 /// TheModule - The module for which we are holding slot numbers.
472 const Module* TheModule;
474 /// TheFunction - The function for which we are holding slot numbers.
475 const Function* TheFunction;
476 bool FunctionProcessed;
478 /// mMap - The TypePlanes map for the module level data.
482 /// fMap - The TypePlanes map for the function level data.
486 /// mdnMap - Map for MDNodes.
487 DenseMap<const MDNode*, unsigned> mdnMap;
490 /// Construct from a module
491 explicit SlotTracker(const Module *M);
492 /// Construct from a function, starting out in incorp state.
493 explicit SlotTracker(const Function *F);
495 /// Return the slot number of the specified value in it's type
496 /// plane. If something is not in the SlotTracker, return -1.
497 int getLocalSlot(const Value *V);
498 int getGlobalSlot(const GlobalValue *V);
499 int getMetadataSlot(const MDNode *N);
501 /// If you'd like to deal with a function instead of just a module, use
502 /// this method to get its data into the SlotTracker.
503 void incorporateFunction(const Function *F) {
505 FunctionProcessed = false;
508 /// After calling incorporateFunction, use this method to remove the
509 /// most recently incorporated function from the SlotTracker. This
510 /// will reset the state of the machine back to just the module contents.
511 void purgeFunction();
513 /// MDNode map iterators.
514 typedef DenseMap<const MDNode*, unsigned>::iterator mdn_iterator;
515 mdn_iterator mdn_begin() { return mdnMap.begin(); }
516 mdn_iterator mdn_end() { return mdnMap.end(); }
517 unsigned mdn_size() const { return mdnMap.size(); }
518 bool mdn_empty() const { return mdnMap.empty(); }
520 /// This function does the actual initialization.
521 inline void initialize();
523 // Implementation Details
525 /// CreateModuleSlot - Insert the specified GlobalValue* into the slot table.
526 void CreateModuleSlot(const GlobalValue *V);
528 /// CreateMetadataSlot - Insert the specified MDNode* into the slot table.
529 void CreateMetadataSlot(const MDNode *N);
531 /// CreateFunctionSlot - Insert the specified Value* into the slot table.
532 void CreateFunctionSlot(const Value *V);
534 /// Add all of the module level global variables (and their initializers)
535 /// and function declarations, but not the contents of those functions.
536 void processModule();
538 /// Add all of the functions arguments, basic blocks, and instructions.
539 void processFunction();
541 SlotTracker(const SlotTracker &); // DO NOT IMPLEMENT
542 void operator=(const SlotTracker &); // DO NOT IMPLEMENT
545 } // end anonymous namespace
548 static SlotTracker *createSlotTracker(const Value *V) {
549 if (const Argument *FA = dyn_cast<Argument>(V))
550 return new SlotTracker(FA->getParent());
552 if (const Instruction *I = dyn_cast<Instruction>(V))
553 return new SlotTracker(I->getParent()->getParent());
555 if (const BasicBlock *BB = dyn_cast<BasicBlock>(V))
556 return new SlotTracker(BB->getParent());
558 if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(V))
559 return new SlotTracker(GV->getParent());
561 if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(V))
562 return new SlotTracker(GA->getParent());
564 if (const Function *Func = dyn_cast<Function>(V))
565 return new SlotTracker(Func);
571 #define ST_DEBUG(X) dbgs() << X
576 // Module level constructor. Causes the contents of the Module (sans functions)
577 // to be added to the slot table.
578 SlotTracker::SlotTracker(const Module *M)
579 : TheModule(M), TheFunction(0), FunctionProcessed(false),
580 mNext(0), fNext(0), mdnNext(0) {
583 // Function level constructor. Causes the contents of the Module and the one
584 // function provided to be added to the slot table.
585 SlotTracker::SlotTracker(const Function *F)
586 : TheModule(F ? F->getParent() : 0), TheFunction(F), FunctionProcessed(false),
587 mNext(0), fNext(0), mdnNext(0) {
590 inline void SlotTracker::initialize() {
593 TheModule = 0; ///< Prevent re-processing next time we're called.
596 if (TheFunction && !FunctionProcessed)
600 // Iterate through all the global variables, functions, and global
601 // variable initializers and create slots for them.
602 void SlotTracker::processModule() {
603 ST_DEBUG("begin processModule!\n");
605 // Add all of the unnamed global variables to the value table.
606 for (Module::const_global_iterator I = TheModule->global_begin(),
607 E = TheModule->global_end(); I != E; ++I) {
612 // Add metadata used by named metadata.
613 for (Module::const_named_metadata_iterator
614 I = TheModule->named_metadata_begin(),
615 E = TheModule->named_metadata_end(); I != E; ++I) {
616 const NamedMDNode *NMD = I;
617 for (unsigned i = 0, e = NMD->getNumOperands(); i != e; ++i) {
618 if (MDNode *MD = NMD->getOperand(i))
619 CreateMetadataSlot(MD);
623 // Add all the unnamed functions to the table.
624 for (Module::const_iterator I = TheModule->begin(), E = TheModule->end();
629 ST_DEBUG("end processModule!\n");
632 // Process the arguments, basic blocks, and instructions of a function.
633 void SlotTracker::processFunction() {
634 ST_DEBUG("begin processFunction!\n");
637 // Add all the function arguments with no names.
638 for(Function::const_arg_iterator AI = TheFunction->arg_begin(),
639 AE = TheFunction->arg_end(); AI != AE; ++AI)
641 CreateFunctionSlot(AI);
643 ST_DEBUG("Inserting Instructions:\n");
645 SmallVector<std::pair<unsigned, MDNode*>, 4> MDForInst;
647 // Add all of the basic blocks and instructions with no names.
648 for (Function::const_iterator BB = TheFunction->begin(),
649 E = TheFunction->end(); BB != E; ++BB) {
651 CreateFunctionSlot(BB);
653 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I != E;
655 if (!I->getType()->isVoidTy() && !I->hasName())
656 CreateFunctionSlot(I);
658 // Intrinsics can directly use metadata.
659 if (isa<IntrinsicInst>(I))
660 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
661 if (MDNode *N = dyn_cast_or_null<MDNode>(I->getOperand(i)))
662 CreateMetadataSlot(N);
664 // Process metadata attached with this instruction.
665 I->getAllMetadata(MDForInst);
666 for (unsigned i = 0, e = MDForInst.size(); i != e; ++i)
667 CreateMetadataSlot(MDForInst[i].second);
672 FunctionProcessed = true;
674 ST_DEBUG("end processFunction!\n");
677 /// Clean up after incorporating a function. This is the only way to get out of
678 /// the function incorporation state that affects get*Slot/Create*Slot. Function
679 /// incorporation state is indicated by TheFunction != 0.
680 void SlotTracker::purgeFunction() {
681 ST_DEBUG("begin purgeFunction!\n");
682 fMap.clear(); // Simply discard the function level map
684 FunctionProcessed = false;
685 ST_DEBUG("end purgeFunction!\n");
688 /// getGlobalSlot - Get the slot number of a global value.
689 int SlotTracker::getGlobalSlot(const GlobalValue *V) {
690 // Check for uninitialized state and do lazy initialization.
693 // Find the type plane in the module map
694 ValueMap::iterator MI = mMap.find(V);
695 return MI == mMap.end() ? -1 : (int)MI->second;
698 /// getMetadataSlot - Get the slot number of a MDNode.
699 int SlotTracker::getMetadataSlot(const MDNode *N) {
700 // Check for uninitialized state and do lazy initialization.
703 // Find the type plane in the module map
704 mdn_iterator MI = mdnMap.find(N);
705 return MI == mdnMap.end() ? -1 : (int)MI->second;
709 /// getLocalSlot - Get the slot number for a value that is local to a function.
710 int SlotTracker::getLocalSlot(const Value *V) {
711 assert(!isa<Constant>(V) && "Can't get a constant or global slot with this!");
713 // Check for uninitialized state and do lazy initialization.
716 ValueMap::iterator FI = fMap.find(V);
717 return FI == fMap.end() ? -1 : (int)FI->second;
721 /// CreateModuleSlot - Insert the specified GlobalValue* into the slot table.
722 void SlotTracker::CreateModuleSlot(const GlobalValue *V) {
723 assert(V && "Can't insert a null Value into SlotTracker!");
724 assert(!V->getType()->isVoidTy() && "Doesn't need a slot!");
725 assert(!V->hasName() && "Doesn't need a slot!");
727 unsigned DestSlot = mNext++;
730 ST_DEBUG(" Inserting value [" << V->getType() << "] = " << V << " slot=" <<
732 // G = Global, F = Function, A = Alias, o = other
733 ST_DEBUG((isa<GlobalVariable>(V) ? 'G' :
734 (isa<Function>(V) ? 'F' :
735 (isa<GlobalAlias>(V) ? 'A' : 'o'))) << "]\n");
738 /// CreateSlot - Create a new slot for the specified value if it has no name.
739 void SlotTracker::CreateFunctionSlot(const Value *V) {
740 assert(!V->getType()->isVoidTy() && !V->hasName() && "Doesn't need a slot!");
742 unsigned DestSlot = fNext++;
745 // G = Global, F = Function, o = other
746 ST_DEBUG(" Inserting value [" << V->getType() << "] = " << V << " slot=" <<
747 DestSlot << " [o]\n");
750 /// CreateModuleSlot - Insert the specified MDNode* into the slot table.
751 void SlotTracker::CreateMetadataSlot(const MDNode *N) {
752 assert(N && "Can't insert a null Value into SlotTracker!");
754 // Don't insert if N is a function-local metadata, these are always printed
756 if (N->isFunctionLocal())
759 mdn_iterator I = mdnMap.find(N);
760 if (I != mdnMap.end())
763 unsigned DestSlot = mdnNext++;
764 mdnMap[N] = DestSlot;
766 // Recursively add any MDNodes referenced by operands.
767 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
768 if (const MDNode *Op = dyn_cast_or_null<MDNode>(N->getOperand(i)))
769 CreateMetadataSlot(Op);
772 //===----------------------------------------------------------------------===//
773 // AsmWriter Implementation
774 //===----------------------------------------------------------------------===//
776 static void WriteAsOperandInternal(raw_ostream &Out, const Value *V,
777 TypePrinting *TypePrinter,
778 SlotTracker *Machine);
782 static const char *getPredicateText(unsigned predicate) {
783 const char * pred = "unknown";
785 case FCmpInst::FCMP_FALSE: pred = "false"; break;
786 case FCmpInst::FCMP_OEQ: pred = "oeq"; break;
787 case FCmpInst::FCMP_OGT: pred = "ogt"; break;
788 case FCmpInst::FCMP_OGE: pred = "oge"; break;
789 case FCmpInst::FCMP_OLT: pred = "olt"; break;
790 case FCmpInst::FCMP_OLE: pred = "ole"; break;
791 case FCmpInst::FCMP_ONE: pred = "one"; break;
792 case FCmpInst::FCMP_ORD: pred = "ord"; break;
793 case FCmpInst::FCMP_UNO: pred = "uno"; break;
794 case FCmpInst::FCMP_UEQ: pred = "ueq"; break;
795 case FCmpInst::FCMP_UGT: pred = "ugt"; break;
796 case FCmpInst::FCMP_UGE: pred = "uge"; break;
797 case FCmpInst::FCMP_ULT: pred = "ult"; break;
798 case FCmpInst::FCMP_ULE: pred = "ule"; break;
799 case FCmpInst::FCMP_UNE: pred = "une"; break;
800 case FCmpInst::FCMP_TRUE: pred = "true"; break;
801 case ICmpInst::ICMP_EQ: pred = "eq"; break;
802 case ICmpInst::ICMP_NE: pred = "ne"; break;
803 case ICmpInst::ICMP_SGT: pred = "sgt"; break;
804 case ICmpInst::ICMP_SGE: pred = "sge"; break;
805 case ICmpInst::ICMP_SLT: pred = "slt"; break;
806 case ICmpInst::ICMP_SLE: pred = "sle"; break;
807 case ICmpInst::ICMP_UGT: pred = "ugt"; break;
808 case ICmpInst::ICMP_UGE: pred = "uge"; break;
809 case ICmpInst::ICMP_ULT: pred = "ult"; break;
810 case ICmpInst::ICMP_ULE: pred = "ule"; break;
816 static void WriteOptimizationInfo(raw_ostream &Out, const User *U) {
817 if (const OverflowingBinaryOperator *OBO =
818 dyn_cast<OverflowingBinaryOperator>(U)) {
819 if (OBO->hasNoUnsignedWrap())
821 if (OBO->hasNoSignedWrap())
823 } else if (const SDivOperator *Div = dyn_cast<SDivOperator>(U)) {
826 } else if (const GEPOperator *GEP = dyn_cast<GEPOperator>(U)) {
827 if (GEP->isInBounds())
832 static void WriteConstantInt(raw_ostream &Out, const Constant *CV,
833 TypePrinting &TypePrinter, SlotTracker *Machine) {
834 if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV)) {
835 if (CI->getType()->isInteger(1)) {
836 Out << (CI->getZExtValue() ? "true" : "false");
839 Out << CI->getValue();
843 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CV)) {
844 if (&CFP->getValueAPF().getSemantics() == &APFloat::IEEEdouble ||
845 &CFP->getValueAPF().getSemantics() == &APFloat::IEEEsingle) {
846 // We would like to output the FP constant value in exponential notation,
847 // but we cannot do this if doing so will lose precision. Check here to
848 // make sure that we only output it in exponential format if we can parse
849 // the value back and get the same value.
852 bool isDouble = &CFP->getValueAPF().getSemantics()==&APFloat::IEEEdouble;
853 double Val = isDouble ? CFP->getValueAPF().convertToDouble() :
854 CFP->getValueAPF().convertToFloat();
855 std::string StrVal = ftostr(CFP->getValueAPF());
857 // Check to make sure that the stringized number is not some string like
858 // "Inf" or NaN, that atof will accept, but the lexer will not. Check
859 // that the string matches the "[-+]?[0-9]" regex.
861 if ((StrVal[0] >= '0' && StrVal[0] <= '9') ||
862 ((StrVal[0] == '-' || StrVal[0] == '+') &&
863 (StrVal[1] >= '0' && StrVal[1] <= '9'))) {
864 // Reparse stringized version!
865 if (atof(StrVal.c_str()) == Val) {
870 // Otherwise we could not reparse it to exactly the same value, so we must
871 // output the string in hexadecimal format! Note that loading and storing
872 // floating point types changes the bits of NaNs on some hosts, notably
873 // x86, so we must not use these types.
874 assert(sizeof(double) == sizeof(uint64_t) &&
875 "assuming that double is 64 bits!");
877 APFloat apf = CFP->getValueAPF();
878 // Floats are represented in ASCII IR as double, convert.
880 apf.convert(APFloat::IEEEdouble, APFloat::rmNearestTiesToEven,
883 utohex_buffer(uint64_t(apf.bitcastToAPInt().getZExtValue()),
888 // Some form of long double. These appear as a magic letter identifying
889 // the type, then a fixed number of hex digits.
891 if (&CFP->getValueAPF().getSemantics() == &APFloat::x87DoubleExtended) {
893 // api needed to prevent premature destruction
894 APInt api = CFP->getValueAPF().bitcastToAPInt();
895 const uint64_t* p = api.getRawData();
896 uint64_t word = p[1];
898 int width = api.getBitWidth();
899 for (int j=0; j<width; j+=4, shiftcount-=4) {
900 unsigned int nibble = (word>>shiftcount) & 15;
902 Out << (unsigned char)(nibble + '0');
904 Out << (unsigned char)(nibble - 10 + 'A');
905 if (shiftcount == 0 && j+4 < width) {
909 shiftcount = width-j-4;
913 } else if (&CFP->getValueAPF().getSemantics() == &APFloat::IEEEquad)
915 else if (&CFP->getValueAPF().getSemantics() == &APFloat::PPCDoubleDouble)
918 llvm_unreachable("Unsupported floating point type");
919 // api needed to prevent premature destruction
920 APInt api = CFP->getValueAPF().bitcastToAPInt();
921 const uint64_t* p = api.getRawData();
924 int width = api.getBitWidth();
925 for (int j=0; j<width; j+=4, shiftcount-=4) {
926 unsigned int nibble = (word>>shiftcount) & 15;
928 Out << (unsigned char)(nibble + '0');
930 Out << (unsigned char)(nibble - 10 + 'A');
931 if (shiftcount == 0 && j+4 < width) {
935 shiftcount = width-j-4;
941 if (isa<ConstantAggregateZero>(CV)) {
942 Out << "zeroinitializer";
946 if (const BlockAddress *BA = dyn_cast<BlockAddress>(CV)) {
947 Out << "blockaddress(";
948 WriteAsOperandInternal(Out, BA->getFunction(), &TypePrinter, Machine);
950 WriteAsOperandInternal(Out, BA->getBasicBlock(), &TypePrinter, Machine);
955 if (const ConstantArray *CA = dyn_cast<ConstantArray>(CV)) {
956 // As a special case, print the array as a string if it is an array of
957 // i8 with ConstantInt values.
959 const Type *ETy = CA->getType()->getElementType();
960 if (CA->isString()) {
962 PrintEscapedString(CA->getAsString(), Out);
964 } else { // Cannot output in string format...
966 if (CA->getNumOperands()) {
967 TypePrinter.print(ETy, Out);
969 WriteAsOperandInternal(Out, CA->getOperand(0),
970 &TypePrinter, Machine);
971 for (unsigned i = 1, e = CA->getNumOperands(); i != e; ++i) {
973 TypePrinter.print(ETy, Out);
975 WriteAsOperandInternal(Out, CA->getOperand(i), &TypePrinter, Machine);
983 if (const ConstantStruct *CS = dyn_cast<ConstantStruct>(CV)) {
984 if (CS->getType()->isPacked())
987 unsigned N = CS->getNumOperands();
990 TypePrinter.print(CS->getOperand(0)->getType(), Out);
993 WriteAsOperandInternal(Out, CS->getOperand(0), &TypePrinter, Machine);
995 for (unsigned i = 1; i < N; i++) {
997 TypePrinter.print(CS->getOperand(i)->getType(), Out);
1000 WriteAsOperandInternal(Out, CS->getOperand(i), &TypePrinter, Machine);
1006 if (CS->getType()->isPacked())
1011 if (const ConstantVector *CP = dyn_cast<ConstantVector>(CV)) {
1012 const Type *ETy = CP->getType()->getElementType();
1013 assert(CP->getNumOperands() > 0 &&
1014 "Number of operands for a PackedConst must be > 0");
1016 TypePrinter.print(ETy, Out);
1018 WriteAsOperandInternal(Out, CP->getOperand(0), &TypePrinter, Machine);
1019 for (unsigned i = 1, e = CP->getNumOperands(); i != e; ++i) {
1021 TypePrinter.print(ETy, Out);
1023 WriteAsOperandInternal(Out, CP->getOperand(i), &TypePrinter, Machine);
1029 if (isa<ConstantPointerNull>(CV)) {
1034 if (isa<UndefValue>(CV)) {
1039 if (const MDNode *Node = dyn_cast<MDNode>(CV)) {
1040 Out << "!" << Machine->getMetadataSlot(Node);
1044 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV)) {
1045 Out << CE->getOpcodeName();
1046 WriteOptimizationInfo(Out, CE);
1047 if (CE->isCompare())
1048 Out << ' ' << getPredicateText(CE->getPredicate());
1051 for (User::const_op_iterator OI=CE->op_begin(); OI != CE->op_end(); ++OI) {
1052 TypePrinter.print((*OI)->getType(), Out);
1054 WriteAsOperandInternal(Out, *OI, &TypePrinter, Machine);
1055 if (OI+1 != CE->op_end())
1059 if (CE->hasIndices()) {
1060 const SmallVector<unsigned, 4> &Indices = CE->getIndices();
1061 for (unsigned i = 0, e = Indices.size(); i != e; ++i)
1062 Out << ", " << Indices[i];
1067 TypePrinter.print(CE->getType(), Out);
1074 Out << "<placeholder or erroneous Constant>";
1077 static void WriteMDNodeBodyInternal(raw_ostream &Out, const MDNode *Node,
1078 TypePrinting *TypePrinter,
1079 SlotTracker *Machine) {
1081 for (unsigned mi = 0, me = Node->getNumOperands(); mi != me; ++mi) {
1082 const Value *V = Node->getOperand(mi);
1086 TypePrinter->print(V->getType(), Out);
1088 WriteAsOperandInternal(Out, Node->getOperand(mi),
1089 TypePrinter, Machine);
1099 /// WriteAsOperand - Write the name of the specified value out to the specified
1100 /// ostream. This can be useful when you just want to print int %reg126, not
1101 /// the whole instruction that generated it.
1103 static void WriteAsOperandInternal(raw_ostream &Out, const Value *V,
1104 TypePrinting *TypePrinter,
1105 SlotTracker *Machine) {
1107 PrintLLVMName(Out, V);
1111 const Constant *CV = dyn_cast<Constant>(V);
1112 if (CV && !isa<GlobalValue>(CV)) {
1113 assert(TypePrinter && "Constants require TypePrinting!");
1114 WriteConstantInt(Out, CV, *TypePrinter, Machine);
1118 if (const InlineAsm *IA = dyn_cast<InlineAsm>(V)) {
1120 if (IA->hasSideEffects())
1121 Out << "sideeffect ";
1122 if (IA->isAlignStack())
1123 Out << "alignstack ";
1125 PrintEscapedString(IA->getAsmString(), Out);
1127 PrintEscapedString(IA->getConstraintString(), Out);
1132 if (const MDNode *N = dyn_cast<MDNode>(V)) {
1133 if (N->isFunctionLocal()) {
1134 // Print metadata inline, not via slot reference number.
1135 WriteMDNodeBodyInternal(Out, N, TypePrinter, Machine);
1139 Out << '!' << Machine->getMetadataSlot(N);
1143 if (const MDString *MDS = dyn_cast<MDString>(V)) {
1145 PrintEscapedString(MDS->getString(), Out);
1150 if (V->getValueID() == Value::PseudoSourceValueVal ||
1151 V->getValueID() == Value::FixedStackPseudoSourceValueVal) {
1159 if (const GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
1160 Slot = Machine->getGlobalSlot(GV);
1163 Slot = Machine->getLocalSlot(V);
1166 Machine = createSlotTracker(V);
1168 if (const GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
1169 Slot = Machine->getGlobalSlot(GV);
1172 Slot = Machine->getLocalSlot(V);
1181 Out << Prefix << Slot;
1186 void llvm::WriteAsOperand(raw_ostream &Out, const Value *V,
1187 bool PrintType, const Module *Context) {
1189 // Fast path: Don't construct and populate a TypePrinting object if we
1190 // won't be needing any types printed.
1192 (!isa<Constant>(V) || V->hasName() || isa<GlobalValue>(V))) {
1193 WriteAsOperandInternal(Out, V, 0, 0);
1197 if (Context == 0) Context = getModuleFromVal(V);
1199 TypePrinting TypePrinter;
1200 std::vector<const Type*> NumberedTypes;
1201 AddModuleTypesToPrinter(TypePrinter, NumberedTypes, Context);
1203 TypePrinter.print(V->getType(), Out);
1207 WriteAsOperandInternal(Out, V, &TypePrinter, 0);
1212 class AssemblyWriter {
1213 formatted_raw_ostream &Out;
1214 SlotTracker &Machine;
1215 const Module *TheModule;
1216 TypePrinting TypePrinter;
1217 AssemblyAnnotationWriter *AnnotationWriter;
1218 std::vector<const Type*> NumberedTypes;
1219 SmallVector<StringRef, 8> MDNames;
1222 inline AssemblyWriter(formatted_raw_ostream &o, SlotTracker &Mac,
1224 AssemblyAnnotationWriter *AAW)
1225 : Out(o), Machine(Mac), TheModule(M), AnnotationWriter(AAW) {
1226 AddModuleTypesToPrinter(TypePrinter, NumberedTypes, M);
1228 M->getMDKindNames(MDNames);
1231 void printMDNodeBody(const MDNode *MD);
1232 void printNamedMDNode(const NamedMDNode *NMD);
1234 void printModule(const Module *M);
1236 void writeOperand(const Value *Op, bool PrintType);
1237 void writeParamOperand(const Value *Operand, Attributes Attrs);
1239 void writeAllMDNodes();
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);
1250 // printInfoComment - Print a little comment after the instruction indicating
1251 // which slot it occupies.
1252 void printInfoComment(const Value &V);
1254 } // end of anonymous namespace
1257 void AssemblyWriter::writeOperand(const Value *Operand, bool PrintType) {
1259 Out << "<null operand!>";
1263 TypePrinter.print(Operand->getType(), Out);
1266 WriteAsOperandInternal(Out, Operand, &TypePrinter, &Machine);
1269 void AssemblyWriter::writeParamOperand(const Value *Operand,
1272 Out << "<null operand!>";
1277 TypePrinter.print(Operand->getType(), Out);
1278 // Print parameter attributes list
1279 if (Attrs != Attribute::None)
1280 Out << ' ' << Attribute::getAsString(Attrs);
1282 // Print the operand
1283 WriteAsOperandInternal(Out, Operand, &TypePrinter, &Machine);
1286 void AssemblyWriter::printModule(const Module *M) {
1287 if (!M->getModuleIdentifier().empty() &&
1288 // Don't print the ID if it will start a new line (which would
1289 // require a comment char before it).
1290 M->getModuleIdentifier().find('\n') == std::string::npos)
1291 Out << "; ModuleID = '" << M->getModuleIdentifier() << "'\n";
1293 if (!M->getDataLayout().empty())
1294 Out << "target datalayout = \"" << M->getDataLayout() << "\"\n";
1295 if (!M->getTargetTriple().empty())
1296 Out << "target triple = \"" << M->getTargetTriple() << "\"\n";
1298 if (!M->getModuleInlineAsm().empty()) {
1299 // Split the string into lines, to make it easier to read the .ll file.
1300 std::string Asm = M->getModuleInlineAsm();
1302 size_t NewLine = Asm.find_first_of('\n', CurPos);
1304 while (NewLine != std::string::npos) {
1305 // We found a newline, print the portion of the asm string from the
1306 // last newline up to this newline.
1307 Out << "module asm \"";
1308 PrintEscapedString(std::string(Asm.begin()+CurPos, Asm.begin()+NewLine),
1312 NewLine = Asm.find_first_of('\n', CurPos);
1314 Out << "module asm \"";
1315 PrintEscapedString(std::string(Asm.begin()+CurPos, Asm.end()), Out);
1319 // Loop over the dependent libraries and emit them.
1320 Module::lib_iterator LI = M->lib_begin();
1321 Module::lib_iterator LE = M->lib_end();
1324 Out << "deplibs = [ ";
1326 Out << '"' << *LI << '"';
1334 // Loop over the symbol table, emitting all id'd types.
1335 if (!M->getTypeSymbolTable().empty() || !NumberedTypes.empty()) Out << '\n';
1336 printTypeSymbolTable(M->getTypeSymbolTable());
1338 // Output all globals.
1339 if (!M->global_empty()) Out << '\n';
1340 for (Module::const_global_iterator I = M->global_begin(), E = M->global_end();
1344 // Output all aliases.
1345 if (!M->alias_empty()) Out << "\n";
1346 for (Module::const_alias_iterator I = M->alias_begin(), E = M->alias_end();
1350 // Output all of the functions.
1351 for (Module::const_iterator I = M->begin(), E = M->end(); I != E; ++I)
1354 // Output named metadata.
1355 if (!M->named_metadata_empty()) Out << '\n';
1357 for (Module::const_named_metadata_iterator I = M->named_metadata_begin(),
1358 E = M->named_metadata_end(); I != E; ++I)
1359 printNamedMDNode(I);
1362 if (!Machine.mdn_empty()) {
1368 void AssemblyWriter::printNamedMDNode(const NamedMDNode *NMD) {
1369 Out << "!" << NMD->getName() << " = !{";
1370 for (unsigned i = 0, e = NMD->getNumOperands(); i != e; ++i) {
1372 if (MDNode *MD = NMD->getOperand(i))
1373 Out << '!' << Machine.getMetadataSlot(MD);
1381 static void PrintLinkage(GlobalValue::LinkageTypes LT,
1382 formatted_raw_ostream &Out) {
1384 case GlobalValue::ExternalLinkage: break;
1385 case GlobalValue::PrivateLinkage: Out << "private "; break;
1386 case GlobalValue::LinkerPrivateLinkage: Out << "linker_private "; break;
1387 case GlobalValue::InternalLinkage: Out << "internal "; break;
1388 case GlobalValue::LinkOnceAnyLinkage: Out << "linkonce "; break;
1389 case GlobalValue::LinkOnceODRLinkage: Out << "linkonce_odr "; break;
1390 case GlobalValue::WeakAnyLinkage: Out << "weak "; break;
1391 case GlobalValue::WeakODRLinkage: Out << "weak_odr "; break;
1392 case GlobalValue::CommonLinkage: Out << "common "; break;
1393 case GlobalValue::AppendingLinkage: Out << "appending "; break;
1394 case GlobalValue::DLLImportLinkage: Out << "dllimport "; break;
1395 case GlobalValue::DLLExportLinkage: Out << "dllexport "; break;
1396 case GlobalValue::ExternalWeakLinkage: Out << "extern_weak "; break;
1397 case GlobalValue::AvailableExternallyLinkage:
1398 Out << "available_externally ";
1400 // This is invalid syntax and just a debugging aid.
1401 case GlobalValue::GhostLinkage: Out << "ghost "; break;
1406 static void PrintVisibility(GlobalValue::VisibilityTypes Vis,
1407 formatted_raw_ostream &Out) {
1409 case GlobalValue::DefaultVisibility: break;
1410 case GlobalValue::HiddenVisibility: Out << "hidden "; break;
1411 case GlobalValue::ProtectedVisibility: Out << "protected "; break;
1415 void AssemblyWriter::printGlobal(const GlobalVariable *GV) {
1416 WriteAsOperandInternal(Out, GV, &TypePrinter, &Machine);
1419 if (!GV->hasInitializer() && GV->hasExternalLinkage())
1422 PrintLinkage(GV->getLinkage(), Out);
1423 PrintVisibility(GV->getVisibility(), Out);
1425 if (GV->isThreadLocal()) Out << "thread_local ";
1426 if (unsigned AddressSpace = GV->getType()->getAddressSpace())
1427 Out << "addrspace(" << AddressSpace << ") ";
1428 Out << (GV->isConstant() ? "constant " : "global ");
1429 TypePrinter.print(GV->getType()->getElementType(), Out);
1431 if (GV->hasInitializer()) {
1433 writeOperand(GV->getInitializer(), false);
1436 if (GV->hasSection())
1437 Out << ", section \"" << GV->getSection() << '"';
1438 if (GV->getAlignment())
1439 Out << ", align " << GV->getAlignment();
1441 printInfoComment(*GV);
1445 void AssemblyWriter::printAlias(const GlobalAlias *GA) {
1446 // Don't crash when dumping partially built GA
1448 Out << "<<nameless>> = ";
1450 PrintLLVMName(Out, GA);
1453 PrintVisibility(GA->getVisibility(), Out);
1457 PrintLinkage(GA->getLinkage(), Out);
1459 const Constant *Aliasee = GA->getAliasee();
1461 if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(Aliasee)) {
1462 TypePrinter.print(GV->getType(), Out);
1464 PrintLLVMName(Out, GV);
1465 } else if (const Function *F = dyn_cast<Function>(Aliasee)) {
1466 TypePrinter.print(F->getFunctionType(), Out);
1469 WriteAsOperandInternal(Out, F, &TypePrinter, &Machine);
1470 } else if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(Aliasee)) {
1471 TypePrinter.print(GA->getType(), Out);
1473 PrintLLVMName(Out, GA);
1475 const ConstantExpr *CE = cast<ConstantExpr>(Aliasee);
1476 // The only valid GEP is an all zero GEP.
1477 assert((CE->getOpcode() == Instruction::BitCast ||
1478 CE->getOpcode() == Instruction::GetElementPtr) &&
1479 "Unsupported aliasee");
1480 writeOperand(CE, false);
1483 printInfoComment(*GA);
1487 void AssemblyWriter::printTypeSymbolTable(const TypeSymbolTable &ST) {
1488 // Emit all numbered types.
1489 for (unsigned i = 0, e = NumberedTypes.size(); i != e; ++i) {
1490 Out << '%' << i << " = type ";
1492 // Make sure we print out at least one level of the type structure, so
1493 // that we do not get %2 = type %2
1494 TypePrinter.printAtLeastOneLevel(NumberedTypes[i], Out);
1498 // Print the named types.
1499 for (TypeSymbolTable::const_iterator TI = ST.begin(), TE = ST.end();
1501 PrintLLVMName(Out, TI->first, LocalPrefix);
1504 // Make sure we print out at least one level of the type structure, so
1505 // that we do not get %FILE = type %FILE
1506 TypePrinter.printAtLeastOneLevel(TI->second, Out);
1511 /// printFunction - Print all aspects of a function.
1513 void AssemblyWriter::printFunction(const Function *F) {
1514 // Print out the return type and name.
1517 if (AnnotationWriter) AnnotationWriter->emitFunctionAnnot(F, Out);
1519 if (F->isDeclaration())
1524 PrintLinkage(F->getLinkage(), Out);
1525 PrintVisibility(F->getVisibility(), Out);
1527 // Print the calling convention.
1528 switch (F->getCallingConv()) {
1529 case CallingConv::C: break; // default
1530 case CallingConv::Fast: Out << "fastcc "; break;
1531 case CallingConv::Cold: Out << "coldcc "; break;
1532 case CallingConv::X86_StdCall: Out << "x86_stdcallcc "; break;
1533 case CallingConv::X86_FastCall: Out << "x86_fastcallcc "; break;
1534 case CallingConv::ARM_APCS: Out << "arm_apcscc "; break;
1535 case CallingConv::ARM_AAPCS: Out << "arm_aapcscc "; break;
1536 case CallingConv::ARM_AAPCS_VFP:Out << "arm_aapcs_vfpcc "; break;
1537 case CallingConv::MSP430_INTR: Out << "msp430_intrcc "; break;
1538 default: Out << "cc" << F->getCallingConv() << " "; break;
1541 const FunctionType *FT = F->getFunctionType();
1542 const AttrListPtr &Attrs = F->getAttributes();
1543 Attributes RetAttrs = Attrs.getRetAttributes();
1544 if (RetAttrs != Attribute::None)
1545 Out << Attribute::getAsString(Attrs.getRetAttributes()) << ' ';
1546 TypePrinter.print(F->getReturnType(), Out);
1548 WriteAsOperandInternal(Out, F, &TypePrinter, &Machine);
1550 Machine.incorporateFunction(F);
1552 // Loop over the arguments, printing them...
1555 if (!F->isDeclaration()) {
1556 // If this isn't a declaration, print the argument names as well.
1557 for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
1559 // Insert commas as we go... the first arg doesn't get a comma
1560 if (I != F->arg_begin()) Out << ", ";
1561 printArgument(I, Attrs.getParamAttributes(Idx));
1565 // Otherwise, print the types from the function type.
1566 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
1567 // Insert commas as we go... the first arg doesn't get a comma
1571 TypePrinter.print(FT->getParamType(i), Out);
1573 Attributes ArgAttrs = Attrs.getParamAttributes(i+1);
1574 if (ArgAttrs != Attribute::None)
1575 Out << ' ' << Attribute::getAsString(ArgAttrs);
1579 // Finish printing arguments...
1580 if (FT->isVarArg()) {
1581 if (FT->getNumParams()) Out << ", ";
1582 Out << "..."; // Output varargs portion of signature!
1585 Attributes FnAttrs = Attrs.getFnAttributes();
1586 if (FnAttrs != Attribute::None)
1587 Out << ' ' << Attribute::getAsString(Attrs.getFnAttributes());
1588 if (F->hasSection())
1589 Out << " section \"" << F->getSection() << '"';
1590 if (F->getAlignment())
1591 Out << " align " << F->getAlignment();
1593 Out << " gc \"" << F->getGC() << '"';
1594 if (F->isDeclaration()) {
1599 // Output all of its basic blocks... for the function
1600 for (Function::const_iterator I = F->begin(), E = F->end(); I != E; ++I)
1606 Machine.purgeFunction();
1609 /// printArgument - This member is called for every argument that is passed into
1610 /// the function. Simply print it out
1612 void AssemblyWriter::printArgument(const Argument *Arg,
1615 TypePrinter.print(Arg->getType(), Out);
1617 // Output parameter attributes list
1618 if (Attrs != Attribute::None)
1619 Out << ' ' << Attribute::getAsString(Attrs);
1621 // Output name, if available...
1622 if (Arg->hasName()) {
1624 PrintLLVMName(Out, Arg);
1628 /// printBasicBlock - This member is called for each basic block in a method.
1630 void AssemblyWriter::printBasicBlock(const BasicBlock *BB) {
1631 if (BB->hasName()) { // Print out the label if it exists...
1633 PrintLLVMName(Out, BB->getName(), LabelPrefix);
1635 } else if (!BB->use_empty()) { // Don't print block # of no uses...
1636 Out << "\n; <label>:";
1637 int Slot = Machine.getLocalSlot(BB);
1644 if (BB->getParent() == 0) {
1645 Out.PadToColumn(50);
1646 Out << "; Error: Block without parent!";
1647 } else if (BB != &BB->getParent()->getEntryBlock()) { // Not the entry block?
1648 // Output predecessors for the block...
1649 Out.PadToColumn(50);
1651 pred_const_iterator PI = pred_begin(BB), PE = pred_end(BB);
1654 Out << " No predecessors!";
1657 writeOperand(*PI, false);
1658 for (++PI; PI != PE; ++PI) {
1660 writeOperand(*PI, false);
1667 if (AnnotationWriter) AnnotationWriter->emitBasicBlockStartAnnot(BB, Out);
1669 // Output all of the instructions in the basic block...
1670 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I != E; ++I) {
1671 printInstruction(*I);
1675 if (AnnotationWriter) AnnotationWriter->emitBasicBlockEndAnnot(BB, Out);
1679 /// printInfoComment - Print a little comment after the instruction indicating
1680 /// which slot it occupies.
1682 void AssemblyWriter::printInfoComment(const Value &V) {
1683 if (V.getType()->isVoidTy()) return;
1685 Out.PadToColumn(50);
1687 TypePrinter.print(V.getType(), Out);
1688 Out << "> [#uses=" << V.getNumUses() << ']'; // Output # uses
1691 // This member is called for each Instruction in a function..
1692 void AssemblyWriter::printInstruction(const Instruction &I) {
1693 if (AnnotationWriter) AnnotationWriter->emitInstructionAnnot(&I, Out);
1695 // Print out indentation for an instruction.
1698 // Print out name if it exists...
1700 PrintLLVMName(Out, &I);
1702 } else if (!I.getType()->isVoidTy()) {
1703 // Print out the def slot taken.
1704 int SlotNum = Machine.getLocalSlot(&I);
1706 Out << "<badref> = ";
1708 Out << '%' << SlotNum << " = ";
1711 // If this is a volatile load or store, print out the volatile marker.
1712 if ((isa<LoadInst>(I) && cast<LoadInst>(I).isVolatile()) ||
1713 (isa<StoreInst>(I) && cast<StoreInst>(I).isVolatile())) {
1715 } else if (isa<CallInst>(I) && cast<CallInst>(I).isTailCall()) {
1716 // If this is a call, check if it's a tail call.
1720 // Print out the opcode...
1721 Out << I.getOpcodeName();
1723 // Print out optimization information.
1724 WriteOptimizationInfo(Out, &I);
1726 // Print out the compare instruction predicates
1727 if (const CmpInst *CI = dyn_cast<CmpInst>(&I))
1728 Out << ' ' << getPredicateText(CI->getPredicate());
1730 // Print out the type of the operands...
1731 const Value *Operand = I.getNumOperands() ? I.getOperand(0) : 0;
1733 // Special case conditional branches to swizzle the condition out to the front
1734 if (isa<BranchInst>(I) && cast<BranchInst>(I).isConditional()) {
1735 BranchInst &BI(cast<BranchInst>(I));
1737 writeOperand(BI.getCondition(), true);
1739 writeOperand(BI.getSuccessor(0), true);
1741 writeOperand(BI.getSuccessor(1), true);
1743 } else if (isa<SwitchInst>(I)) {
1744 // Special case switch instruction to get formatting nice and correct.
1746 writeOperand(Operand , true);
1748 writeOperand(I.getOperand(1), true);
1751 for (unsigned op = 2, Eop = I.getNumOperands(); op < Eop; op += 2) {
1753 writeOperand(I.getOperand(op ), true);
1755 writeOperand(I.getOperand(op+1), true);
1758 } else if (isa<IndirectBrInst>(I)) {
1759 // Special case indirectbr instruction to get formatting nice and correct.
1761 writeOperand(Operand, true);
1764 for (unsigned i = 1, e = I.getNumOperands(); i != e; ++i) {
1767 writeOperand(I.getOperand(i), true);
1770 } else if (isa<PHINode>(I)) {
1772 TypePrinter.print(I.getType(), Out);
1775 for (unsigned op = 0, Eop = I.getNumOperands(); op < Eop; op += 2) {
1776 if (op) Out << ", ";
1778 writeOperand(I.getOperand(op ), false); Out << ", ";
1779 writeOperand(I.getOperand(op+1), false); Out << " ]";
1781 } else if (const ExtractValueInst *EVI = dyn_cast<ExtractValueInst>(&I)) {
1783 writeOperand(I.getOperand(0), true);
1784 for (const unsigned *i = EVI->idx_begin(), *e = EVI->idx_end(); i != e; ++i)
1786 } else if (const InsertValueInst *IVI = dyn_cast<InsertValueInst>(&I)) {
1788 writeOperand(I.getOperand(0), true); Out << ", ";
1789 writeOperand(I.getOperand(1), true);
1790 for (const unsigned *i = IVI->idx_begin(), *e = IVI->idx_end(); i != e; ++i)
1792 } else if (isa<ReturnInst>(I) && !Operand) {
1794 } else if (const CallInst *CI = dyn_cast<CallInst>(&I)) {
1795 // Print the calling convention being used.
1796 switch (CI->getCallingConv()) {
1797 case CallingConv::C: break; // default
1798 case CallingConv::Fast: Out << " fastcc"; break;
1799 case CallingConv::Cold: Out << " coldcc"; break;
1800 case CallingConv::X86_StdCall: Out << " x86_stdcallcc"; break;
1801 case CallingConv::X86_FastCall: Out << " x86_fastcallcc"; break;
1802 case CallingConv::ARM_APCS: Out << " arm_apcscc "; break;
1803 case CallingConv::ARM_AAPCS: Out << " arm_aapcscc "; break;
1804 case CallingConv::ARM_AAPCS_VFP:Out << " arm_aapcs_vfpcc "; break;
1805 case CallingConv::MSP430_INTR: Out << " msp430_intrcc "; break;
1806 default: Out << " cc" << CI->getCallingConv(); break;
1809 const PointerType *PTy = cast<PointerType>(Operand->getType());
1810 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
1811 const Type *RetTy = FTy->getReturnType();
1812 const AttrListPtr &PAL = CI->getAttributes();
1814 if (PAL.getRetAttributes() != Attribute::None)
1815 Out << ' ' << Attribute::getAsString(PAL.getRetAttributes());
1817 // If possible, print out the short form of the call instruction. We can
1818 // only do this if the first argument is a pointer to a nonvararg function,
1819 // and if the return type is not a pointer to a function.
1822 if (!FTy->isVarArg() &&
1823 (!isa<PointerType>(RetTy) ||
1824 !isa<FunctionType>(cast<PointerType>(RetTy)->getElementType()))) {
1825 TypePrinter.print(RetTy, Out);
1827 writeOperand(Operand, false);
1829 writeOperand(Operand, true);
1832 for (unsigned op = 1, Eop = I.getNumOperands(); op < Eop; ++op) {
1835 writeParamOperand(I.getOperand(op), PAL.getParamAttributes(op));
1838 if (PAL.getFnAttributes() != Attribute::None)
1839 Out << ' ' << Attribute::getAsString(PAL.getFnAttributes());
1840 } else if (const InvokeInst *II = dyn_cast<InvokeInst>(&I)) {
1841 const PointerType *PTy = cast<PointerType>(Operand->getType());
1842 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
1843 const Type *RetTy = FTy->getReturnType();
1844 const AttrListPtr &PAL = II->getAttributes();
1846 // Print the calling convention being used.
1847 switch (II->getCallingConv()) {
1848 case CallingConv::C: break; // default
1849 case CallingConv::Fast: Out << " fastcc"; break;
1850 case CallingConv::Cold: Out << " coldcc"; break;
1851 case CallingConv::X86_StdCall: Out << " x86_stdcallcc"; break;
1852 case CallingConv::X86_FastCall: Out << " x86_fastcallcc"; break;
1853 case CallingConv::ARM_APCS: Out << " arm_apcscc "; break;
1854 case CallingConv::ARM_AAPCS: Out << " arm_aapcscc "; break;
1855 case CallingConv::ARM_AAPCS_VFP:Out << " arm_aapcs_vfpcc "; break;
1856 case CallingConv::MSP430_INTR: Out << " msp430_intrcc "; break;
1857 default: Out << " cc" << II->getCallingConv(); break;
1860 if (PAL.getRetAttributes() != Attribute::None)
1861 Out << ' ' << Attribute::getAsString(PAL.getRetAttributes());
1863 // If possible, print out the short form of the invoke instruction. We can
1864 // only do this if the first argument is a pointer to a nonvararg function,
1865 // and if the return type is not a pointer to a function.
1868 if (!FTy->isVarArg() &&
1869 (!isa<PointerType>(RetTy) ||
1870 !isa<FunctionType>(cast<PointerType>(RetTy)->getElementType()))) {
1871 TypePrinter.print(RetTy, Out);
1873 writeOperand(Operand, false);
1875 writeOperand(Operand, true);
1878 for (unsigned op = 3, Eop = I.getNumOperands(); op < Eop; ++op) {
1881 writeParamOperand(I.getOperand(op), PAL.getParamAttributes(op-2));
1885 if (PAL.getFnAttributes() != Attribute::None)
1886 Out << ' ' << Attribute::getAsString(PAL.getFnAttributes());
1889 writeOperand(II->getNormalDest(), true);
1891 writeOperand(II->getUnwindDest(), true);
1893 } else if (const AllocaInst *AI = dyn_cast<AllocaInst>(&I)) {
1895 TypePrinter.print(AI->getType()->getElementType(), Out);
1896 if (!AI->getArraySize() || AI->isArrayAllocation()) {
1898 writeOperand(AI->getArraySize(), true);
1900 if (AI->getAlignment()) {
1901 Out << ", align " << AI->getAlignment();
1903 } else if (isa<CastInst>(I)) {
1906 writeOperand(Operand, true); // Work with broken code
1909 TypePrinter.print(I.getType(), Out);
1910 } else if (isa<VAArgInst>(I)) {
1913 writeOperand(Operand, true); // Work with broken code
1916 TypePrinter.print(I.getType(), Out);
1917 } else if (Operand) { // Print the normal way.
1919 // PrintAllTypes - Instructions who have operands of all the same type
1920 // omit the type from all but the first operand. If the instruction has
1921 // different type operands (for example br), then they are all printed.
1922 bool PrintAllTypes = false;
1923 const Type *TheType = Operand->getType();
1925 // Select, Store and ShuffleVector always print all types.
1926 if (isa<SelectInst>(I) || isa<StoreInst>(I) || isa<ShuffleVectorInst>(I)
1927 || isa<ReturnInst>(I)) {
1928 PrintAllTypes = true;
1930 for (unsigned i = 1, E = I.getNumOperands(); i != E; ++i) {
1931 Operand = I.getOperand(i);
1932 // note that Operand shouldn't be null, but the test helps make dump()
1933 // more tolerant of malformed IR
1934 if (Operand && Operand->getType() != TheType) {
1935 PrintAllTypes = true; // We have differing types! Print them all!
1941 if (!PrintAllTypes) {
1943 TypePrinter.print(TheType, Out);
1947 for (unsigned i = 0, E = I.getNumOperands(); i != E; ++i) {
1949 writeOperand(I.getOperand(i), PrintAllTypes);
1953 // Print post operand alignment for load/store.
1954 if (isa<LoadInst>(I) && cast<LoadInst>(I).getAlignment()) {
1955 Out << ", align " << cast<LoadInst>(I).getAlignment();
1956 } else if (isa<StoreInst>(I) && cast<StoreInst>(I).getAlignment()) {
1957 Out << ", align " << cast<StoreInst>(I).getAlignment();
1960 // Print Metadata info.
1961 if (!MDNames.empty()) {
1962 SmallVector<std::pair<unsigned, MDNode*>, 4> InstMD;
1963 I.getAllMetadata(InstMD);
1964 for (unsigned i = 0, e = InstMD.size(); i != e; ++i)
1965 Out << ", !" << MDNames[InstMD[i].first]
1966 << " !" << Machine.getMetadataSlot(InstMD[i].second);
1968 printInfoComment(I);
1971 static void WriteMDNodeComment(const MDNode *Node,
1972 formatted_raw_ostream &Out) {
1973 if (Node->getNumOperands() < 1)
1975 ConstantInt *CI = dyn_cast_or_null<ConstantInt>(Node->getOperand(0));
1977 unsigned Val = CI->getZExtValue();
1978 unsigned Tag = Val & ~LLVMDebugVersionMask;
1979 if (Val < LLVMDebugVersion)
1982 Out.PadToColumn(50);
1983 if (Tag == dwarf::DW_TAG_auto_variable)
1984 Out << "; [ DW_TAG_auto_variable ]";
1985 else if (Tag == dwarf::DW_TAG_arg_variable)
1986 Out << "; [ DW_TAG_arg_variable ]";
1987 else if (Tag == dwarf::DW_TAG_return_variable)
1988 Out << "; [ DW_TAG_return_variable ]";
1989 else if (Tag == dwarf::DW_TAG_vector_type)
1990 Out << "; [ DW_TAG_vector_type ]";
1991 else if (Tag == dwarf::DW_TAG_user_base)
1992 Out << "; [ DW_TAG_user_base ]";
1993 else if (const char *TagName = dwarf::TagString(Tag))
1994 Out << "; [ " << TagName << " ]";
1997 void AssemblyWriter::writeAllMDNodes() {
1998 SmallVector<const MDNode *, 16> Nodes;
1999 Nodes.resize(Machine.mdn_size());
2000 for (SlotTracker::mdn_iterator I = Machine.mdn_begin(), E = Machine.mdn_end();
2002 Nodes[I->second] = cast<MDNode>(I->first);
2004 for (unsigned i = 0, e = Nodes.size(); i != e; ++i) {
2005 Out << '!' << i << " = metadata ";
2006 printMDNodeBody(Nodes[i]);
2010 void AssemblyWriter::printMDNodeBody(const MDNode *Node) {
2011 WriteMDNodeBodyInternal(Out, Node, &TypePrinter, &Machine);
2012 WriteMDNodeComment(Node, Out);
2016 //===----------------------------------------------------------------------===//
2017 // External Interface declarations
2018 //===----------------------------------------------------------------------===//
2020 void Module::print(raw_ostream &ROS, AssemblyAnnotationWriter *AAW) const {
2021 SlotTracker SlotTable(this);
2022 formatted_raw_ostream OS(ROS);
2023 AssemblyWriter W(OS, SlotTable, this, AAW);
2024 W.printModule(this);
2027 void Type::print(raw_ostream &OS) const {
2029 OS << "<null Type>";
2032 TypePrinting().print(this, OS);
2035 void Value::print(raw_ostream &ROS, AssemblyAnnotationWriter *AAW) const {
2037 ROS << "printing a <null> value\n";
2040 formatted_raw_ostream OS(ROS);
2041 if (const Instruction *I = dyn_cast<Instruction>(this)) {
2042 const Function *F = I->getParent() ? I->getParent()->getParent() : 0;
2043 SlotTracker SlotTable(F);
2044 AssemblyWriter W(OS, SlotTable, getModuleFromVal(I), AAW);
2045 W.printInstruction(*I);
2046 } else if (const BasicBlock *BB = dyn_cast<BasicBlock>(this)) {
2047 SlotTracker SlotTable(BB->getParent());
2048 AssemblyWriter W(OS, SlotTable, getModuleFromVal(BB), AAW);
2049 W.printBasicBlock(BB);
2050 } else if (const GlobalValue *GV = dyn_cast<GlobalValue>(this)) {
2051 SlotTracker SlotTable(GV->getParent());
2052 AssemblyWriter W(OS, SlotTable, GV->getParent(), AAW);
2053 if (const GlobalVariable *V = dyn_cast<GlobalVariable>(GV))
2055 else if (const Function *F = dyn_cast<Function>(GV))
2058 W.printAlias(cast<GlobalAlias>(GV));
2059 } else if (const MDNode *N = dyn_cast<MDNode>(this)) {
2060 SlotTracker SlotTable((Function*)0);
2061 AssemblyWriter W(OS, SlotTable, 0, AAW);
2062 W.printMDNodeBody(N);
2063 } else if (const NamedMDNode *N = dyn_cast<NamedMDNode>(this)) {
2064 SlotTracker SlotTable(N->getParent());
2065 AssemblyWriter W(OS, SlotTable, N->getParent(), AAW);
2066 W.printNamedMDNode(N);
2067 } else if (const Constant *C = dyn_cast<Constant>(this)) {
2068 TypePrinting TypePrinter;
2069 TypePrinter.print(C->getType(), OS);
2071 WriteConstantInt(OS, C, TypePrinter, 0);
2072 } else if (isa<InlineAsm>(this) || isa<MDString>(this) ||
2073 isa<Argument>(this)) {
2074 WriteAsOperand(OS, this, true, 0);
2076 // Otherwise we don't know what it is. Call the virtual function to
2077 // allow a subclass to print itself.
2082 // Value::printCustom - subclasses should override this to implement printing.
2083 void Value::printCustom(raw_ostream &OS) const {
2084 llvm_unreachable("Unknown value to print out!");
2087 // Value::dump - allow easy printing of Values from the debugger.
2088 void Value::dump() const { print(dbgs()); dbgs() << '\n'; }
2090 // Type::dump - allow easy printing of Types from the debugger.
2091 // This one uses type names from the given context module
2092 void Type::dump(const Module *Context) const {
2093 WriteTypeSymbolic(dbgs(), this, Context);
2097 // Type::dump - allow easy printing of Types from the debugger.
2098 void Type::dump() const { dump(0); }
2100 // Module::dump() - Allow printing of Modules from the debugger.
2101 void Module::dump() const { print(dbgs(), 0); }