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::PointerTyID: {
243 const PointerType *PTy = cast<PointerType>(Ty);
244 CalcTypeName(PTy->getElementType(), TypeStack, OS);
245 if (unsigned AddressSpace = PTy->getAddressSpace())
246 OS << " addrspace(" << AddressSpace << ')';
250 case Type::ArrayTyID: {
251 const ArrayType *ATy = cast<ArrayType>(Ty);
252 OS << '[' << ATy->getNumElements() << " x ";
253 CalcTypeName(ATy->getElementType(), TypeStack, OS);
257 case Type::VectorTyID: {
258 const VectorType *PTy = cast<VectorType>(Ty);
259 OS << "<" << PTy->getNumElements() << " x ";
260 CalcTypeName(PTy->getElementType(), TypeStack, OS);
264 case Type::OpaqueTyID:
268 OS << "<unrecognized-type>";
272 TypeStack.pop_back(); // Remove self from stack.
275 /// printTypeInt - The internal guts of printing out a type that has a
276 /// potentially named portion.
278 void TypePrinting::print(const Type *Ty, raw_ostream &OS,
279 bool IgnoreTopLevelName) {
280 // Check to see if the type is named.
281 DenseMap<const Type*, std::string> &TM = getTypeNamesMap(TypeNames);
282 if (!IgnoreTopLevelName) {
283 DenseMap<const Type*, std::string>::iterator I = TM.find(Ty);
290 // Otherwise we have a type that has not been named but is a derived type.
291 // Carefully recurse the type hierarchy to print out any contained symbolic
293 SmallVector<const Type *, 16> TypeStack;
294 std::string TypeName;
296 raw_string_ostream TypeOS(TypeName);
297 CalcTypeName(Ty, TypeStack, TypeOS, IgnoreTopLevelName);
300 // Cache type name for later use.
301 if (!IgnoreTopLevelName)
302 TM.insert(std::make_pair(Ty, TypeOS.str()));
307 // To avoid walking constant expressions multiple times and other IR
308 // objects, we keep several helper maps.
309 DenseSet<const Value*> VisitedConstants;
310 DenseSet<const Type*> VisitedTypes;
313 std::vector<const Type*> &NumberedTypes;
315 TypeFinder(TypePrinting &tp, std::vector<const Type*> &numberedTypes)
316 : TP(tp), NumberedTypes(numberedTypes) {}
318 void Run(const Module &M) {
319 // Get types from the type symbol table. This gets opaque types referened
320 // only through derived named types.
321 const TypeSymbolTable &ST = M.getTypeSymbolTable();
322 for (TypeSymbolTable::const_iterator TI = ST.begin(), E = ST.end();
324 IncorporateType(TI->second);
326 // Get types from global variables.
327 for (Module::const_global_iterator I = M.global_begin(),
328 E = M.global_end(); I != E; ++I) {
329 IncorporateType(I->getType());
330 if (I->hasInitializer())
331 IncorporateValue(I->getInitializer());
334 // Get types from aliases.
335 for (Module::const_alias_iterator I = M.alias_begin(),
336 E = M.alias_end(); I != E; ++I) {
337 IncorporateType(I->getType());
338 IncorporateValue(I->getAliasee());
341 // Get types from functions.
342 for (Module::const_iterator FI = M.begin(), E = M.end(); FI != E; ++FI) {
343 IncorporateType(FI->getType());
345 for (Function::const_iterator BB = FI->begin(), E = FI->end();
347 for (BasicBlock::const_iterator II = BB->begin(),
348 E = BB->end(); II != E; ++II) {
349 const Instruction &I = *II;
350 // Incorporate the type of the instruction and all its operands.
351 IncorporateType(I.getType());
352 for (User::const_op_iterator OI = I.op_begin(), OE = I.op_end();
354 IncorporateValue(*OI);
360 void IncorporateType(const Type *Ty) {
361 // Check to see if we're already visited this type.
362 if (!VisitedTypes.insert(Ty).second)
365 // If this is a structure or opaque type, add a name for the type.
366 if (((isa<StructType>(Ty) && cast<StructType>(Ty)->getNumElements())
367 || isa<OpaqueType>(Ty)) && !TP.hasTypeName(Ty)) {
368 TP.addTypeName(Ty, "%"+utostr(unsigned(NumberedTypes.size())));
369 NumberedTypes.push_back(Ty);
372 // Recursively walk all contained types.
373 for (Type::subtype_iterator I = Ty->subtype_begin(),
374 E = Ty->subtype_end(); I != E; ++I)
378 /// IncorporateValue - This method is used to walk operand lists finding
379 /// types hiding in constant expressions and other operands that won't be
380 /// walked in other ways. GlobalValues, basic blocks, instructions, and
381 /// inst operands are all explicitly enumerated.
382 void IncorporateValue(const Value *V) {
383 if (V == 0 || !isa<Constant>(V) || isa<GlobalValue>(V)) return;
386 if (!VisitedConstants.insert(V).second)
390 IncorporateType(V->getType());
392 // Look in operands for types.
393 const Constant *C = cast<Constant>(V);
394 for (Constant::const_op_iterator I = C->op_begin(),
395 E = C->op_end(); I != E;++I)
396 IncorporateValue(*I);
399 } // end anonymous namespace
402 /// AddModuleTypesToPrinter - Add all of the symbolic type names for types in
403 /// the specified module to the TypePrinter and all numbered types to it and the
404 /// NumberedTypes table.
405 static void AddModuleTypesToPrinter(TypePrinting &TP,
406 std::vector<const Type*> &NumberedTypes,
410 // If the module has a symbol table, take all global types and stuff their
411 // names into the TypeNames map.
412 const TypeSymbolTable &ST = M->getTypeSymbolTable();
413 for (TypeSymbolTable::const_iterator TI = ST.begin(), E = ST.end();
415 const Type *Ty = cast<Type>(TI->second);
417 // As a heuristic, don't insert pointer to primitive types, because
418 // they are used too often to have a single useful name.
419 if (const PointerType *PTy = dyn_cast<PointerType>(Ty)) {
420 const Type *PETy = PTy->getElementType();
421 if ((PETy->isPrimitiveType() || PETy->isInteger()) &&
422 !isa<OpaqueType>(PETy))
426 // Likewise don't insert primitives either.
427 if (Ty->isInteger() || Ty->isPrimitiveType())
430 // Get the name as a string and insert it into TypeNames.
432 raw_string_ostream NameROS(NameStr);
433 formatted_raw_ostream NameOS(NameROS);
434 PrintLLVMName(NameOS, TI->first, LocalPrefix);
436 TP.addTypeName(Ty, NameStr);
439 // Walk the entire module to find references to unnamed structure and opaque
440 // types. This is required for correctness by opaque types (because multiple
441 // uses of an unnamed opaque type needs to be referred to by the same ID) and
442 // it shrinks complex recursive structure types substantially in some cases.
443 TypeFinder(TP, NumberedTypes).Run(*M);
447 /// WriteTypeSymbolic - This attempts to write the specified type as a symbolic
448 /// type, iff there is an entry in the modules symbol table for the specified
449 /// type or one of it's component types.
451 void llvm::WriteTypeSymbolic(raw_ostream &OS, const Type *Ty, const Module *M) {
452 TypePrinting Printer;
453 std::vector<const Type*> NumberedTypes;
454 AddModuleTypesToPrinter(Printer, NumberedTypes, M);
455 Printer.print(Ty, OS);
458 //===----------------------------------------------------------------------===//
459 // SlotTracker Class: Enumerate slot numbers for unnamed values
460 //===----------------------------------------------------------------------===//
464 /// This class provides computation of slot numbers for LLVM Assembly writing.
468 /// ValueMap - A mapping of Values to slot numbers.
469 typedef DenseMap<const Value*, unsigned> ValueMap;
472 /// TheModule - The module for which we are holding slot numbers.
473 const Module* TheModule;
475 /// TheFunction - The function for which we are holding slot numbers.
476 const Function* TheFunction;
477 bool FunctionProcessed;
479 /// mMap - The TypePlanes map for the module level data.
483 /// fMap - The TypePlanes map for the function level data.
487 /// mdnMap - Map for MDNodes.
488 DenseMap<const MDNode*, unsigned> mdnMap;
491 /// Construct from a module
492 explicit SlotTracker(const Module *M);
493 /// Construct from a function, starting out in incorp state.
494 explicit SlotTracker(const Function *F);
496 /// Return the slot number of the specified value in it's type
497 /// plane. If something is not in the SlotTracker, return -1.
498 int getLocalSlot(const Value *V);
499 int getGlobalSlot(const GlobalValue *V);
500 int getMetadataSlot(const MDNode *N);
502 /// If you'd like to deal with a function instead of just a module, use
503 /// this method to get its data into the SlotTracker.
504 void incorporateFunction(const Function *F) {
506 FunctionProcessed = false;
509 /// After calling incorporateFunction, use this method to remove the
510 /// most recently incorporated function from the SlotTracker. This
511 /// will reset the state of the machine back to just the module contents.
512 void purgeFunction();
514 /// MDNode map iterators.
515 typedef DenseMap<const MDNode*, unsigned>::iterator mdn_iterator;
516 mdn_iterator mdn_begin() { return mdnMap.begin(); }
517 mdn_iterator mdn_end() { return mdnMap.end(); }
518 unsigned mdn_size() const { return mdnMap.size(); }
519 bool mdn_empty() const { return mdnMap.empty(); }
521 /// This function does the actual initialization.
522 inline void initialize();
524 // Implementation Details
526 /// CreateModuleSlot - Insert the specified GlobalValue* into the slot table.
527 void CreateModuleSlot(const GlobalValue *V);
529 /// CreateMetadataSlot - Insert the specified MDNode* into the slot table.
530 void CreateMetadataSlot(const MDNode *N);
532 /// CreateFunctionSlot - Insert the specified Value* into the slot table.
533 void CreateFunctionSlot(const Value *V);
535 /// Add all of the module level global variables (and their initializers)
536 /// and function declarations, but not the contents of those functions.
537 void processModule();
539 /// Add all of the functions arguments, basic blocks, and instructions.
540 void processFunction();
542 SlotTracker(const SlotTracker &); // DO NOT IMPLEMENT
543 void operator=(const SlotTracker &); // DO NOT IMPLEMENT
546 } // end anonymous namespace
549 static SlotTracker *createSlotTracker(const Value *V) {
550 if (const Argument *FA = dyn_cast<Argument>(V))
551 return new SlotTracker(FA->getParent());
553 if (const Instruction *I = dyn_cast<Instruction>(V))
554 return new SlotTracker(I->getParent()->getParent());
556 if (const BasicBlock *BB = dyn_cast<BasicBlock>(V))
557 return new SlotTracker(BB->getParent());
559 if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(V))
560 return new SlotTracker(GV->getParent());
562 if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(V))
563 return new SlotTracker(GA->getParent());
565 if (const Function *Func = dyn_cast<Function>(V))
566 return new SlotTracker(Func);
569 return new SlotTracker((Function *)0);
575 #define ST_DEBUG(X) dbgs() << X
580 // Module level constructor. Causes the contents of the Module (sans functions)
581 // to be added to the slot table.
582 SlotTracker::SlotTracker(const Module *M)
583 : TheModule(M), TheFunction(0), FunctionProcessed(false),
584 mNext(0), fNext(0), mdnNext(0) {
587 // Function level constructor. Causes the contents of the Module and the one
588 // function provided to be added to the slot table.
589 SlotTracker::SlotTracker(const Function *F)
590 : TheModule(F ? F->getParent() : 0), TheFunction(F), FunctionProcessed(false),
591 mNext(0), fNext(0), mdnNext(0) {
594 inline void SlotTracker::initialize() {
597 TheModule = 0; ///< Prevent re-processing next time we're called.
600 if (TheFunction && !FunctionProcessed)
604 // Iterate through all the global variables, functions, and global
605 // variable initializers and create slots for them.
606 void SlotTracker::processModule() {
607 ST_DEBUG("begin processModule!\n");
609 // Add all of the unnamed global variables to the value table.
610 for (Module::const_global_iterator I = TheModule->global_begin(),
611 E = TheModule->global_end(); I != E; ++I) {
616 // Add metadata used by named metadata.
617 for (Module::const_named_metadata_iterator
618 I = TheModule->named_metadata_begin(),
619 E = TheModule->named_metadata_end(); I != E; ++I) {
620 const NamedMDNode *NMD = I;
621 for (unsigned i = 0, e = NMD->getNumOperands(); i != e; ++i) {
622 if (MDNode *MD = NMD->getOperand(i))
623 CreateMetadataSlot(MD);
627 // Add all the unnamed functions to the table.
628 for (Module::const_iterator I = TheModule->begin(), E = TheModule->end();
633 ST_DEBUG("end processModule!\n");
636 // Process the arguments, basic blocks, and instructions of a function.
637 void SlotTracker::processFunction() {
638 ST_DEBUG("begin processFunction!\n");
641 // Add all the function arguments with no names.
642 for(Function::const_arg_iterator AI = TheFunction->arg_begin(),
643 AE = TheFunction->arg_end(); AI != AE; ++AI)
645 CreateFunctionSlot(AI);
647 ST_DEBUG("Inserting Instructions:\n");
649 SmallVector<std::pair<unsigned, MDNode*>, 4> MDForInst;
651 // Add all of the basic blocks and instructions with no names.
652 for (Function::const_iterator BB = TheFunction->begin(),
653 E = TheFunction->end(); BB != E; ++BB) {
655 CreateFunctionSlot(BB);
657 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I != E;
659 if (!I->getType()->isVoidTy() && !I->hasName())
660 CreateFunctionSlot(I);
662 // Intrinsics can directly use metadata.
663 if (isa<IntrinsicInst>(I))
664 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
665 if (MDNode *N = dyn_cast_or_null<MDNode>(I->getOperand(i)))
666 CreateMetadataSlot(N);
668 // Process metadata attached with this instruction.
669 I->getAllMetadata(MDForInst);
670 for (unsigned i = 0, e = MDForInst.size(); i != e; ++i)
671 CreateMetadataSlot(MDForInst[i].second);
676 FunctionProcessed = true;
678 ST_DEBUG("end processFunction!\n");
681 /// Clean up after incorporating a function. This is the only way to get out of
682 /// the function incorporation state that affects get*Slot/Create*Slot. Function
683 /// incorporation state is indicated by TheFunction != 0.
684 void SlotTracker::purgeFunction() {
685 ST_DEBUG("begin purgeFunction!\n");
686 fMap.clear(); // Simply discard the function level map
688 FunctionProcessed = false;
689 ST_DEBUG("end purgeFunction!\n");
692 /// getGlobalSlot - Get the slot number of a global value.
693 int SlotTracker::getGlobalSlot(const GlobalValue *V) {
694 // Check for uninitialized state and do lazy initialization.
697 // Find the type plane in the module map
698 ValueMap::iterator MI = mMap.find(V);
699 return MI == mMap.end() ? -1 : (int)MI->second;
702 /// getMetadataSlot - Get the slot number of a MDNode.
703 int SlotTracker::getMetadataSlot(const MDNode *N) {
704 // Check for uninitialized state and do lazy initialization.
707 // Find the type plane in the module map
708 mdn_iterator MI = mdnMap.find(N);
709 return MI == mdnMap.end() ? -1 : (int)MI->second;
713 /// getLocalSlot - Get the slot number for a value that is local to a function.
714 int SlotTracker::getLocalSlot(const Value *V) {
715 assert(!isa<Constant>(V) && "Can't get a constant or global slot with this!");
717 // Check for uninitialized state and do lazy initialization.
720 ValueMap::iterator FI = fMap.find(V);
721 return FI == fMap.end() ? -1 : (int)FI->second;
725 /// CreateModuleSlot - Insert the specified GlobalValue* into the slot table.
726 void SlotTracker::CreateModuleSlot(const GlobalValue *V) {
727 assert(V && "Can't insert a null Value into SlotTracker!");
728 assert(!V->getType()->isVoidTy() && "Doesn't need a slot!");
729 assert(!V->hasName() && "Doesn't need a slot!");
731 unsigned DestSlot = mNext++;
734 ST_DEBUG(" Inserting value [" << V->getType() << "] = " << V << " slot=" <<
736 // G = Global, F = Function, A = Alias, o = other
737 ST_DEBUG((isa<GlobalVariable>(V) ? 'G' :
738 (isa<Function>(V) ? 'F' :
739 (isa<GlobalAlias>(V) ? 'A' : 'o'))) << "]\n");
742 /// CreateSlot - Create a new slot for the specified value if it has no name.
743 void SlotTracker::CreateFunctionSlot(const Value *V) {
744 assert(!V->getType()->isVoidTy() && !V->hasName() && "Doesn't need a slot!");
746 unsigned DestSlot = fNext++;
749 // G = Global, F = Function, o = other
750 ST_DEBUG(" Inserting value [" << V->getType() << "] = " << V << " slot=" <<
751 DestSlot << " [o]\n");
754 /// CreateModuleSlot - Insert the specified MDNode* into the slot table.
755 void SlotTracker::CreateMetadataSlot(const MDNode *N) {
756 assert(N && "Can't insert a null Value into SlotTracker!");
758 // Don't insert if N is a function-local metadata, these are always printed
760 if (N->isFunctionLocal())
763 mdn_iterator I = mdnMap.find(N);
764 if (I != mdnMap.end())
767 unsigned DestSlot = mdnNext++;
768 mdnMap[N] = DestSlot;
770 // Recursively add any MDNodes referenced by operands.
771 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
772 if (const MDNode *Op = dyn_cast_or_null<MDNode>(N->getOperand(i)))
773 CreateMetadataSlot(Op);
776 //===----------------------------------------------------------------------===//
777 // AsmWriter Implementation
778 //===----------------------------------------------------------------------===//
780 static void WriteAsOperandInternal(raw_ostream &Out, const Value *V,
781 TypePrinting *TypePrinter,
782 SlotTracker *Machine);
786 static const char *getPredicateText(unsigned predicate) {
787 const char * pred = "unknown";
789 case FCmpInst::FCMP_FALSE: pred = "false"; break;
790 case FCmpInst::FCMP_OEQ: pred = "oeq"; break;
791 case FCmpInst::FCMP_OGT: pred = "ogt"; break;
792 case FCmpInst::FCMP_OGE: pred = "oge"; break;
793 case FCmpInst::FCMP_OLT: pred = "olt"; break;
794 case FCmpInst::FCMP_OLE: pred = "ole"; break;
795 case FCmpInst::FCMP_ONE: pred = "one"; break;
796 case FCmpInst::FCMP_ORD: pred = "ord"; break;
797 case FCmpInst::FCMP_UNO: pred = "uno"; break;
798 case FCmpInst::FCMP_UEQ: pred = "ueq"; break;
799 case FCmpInst::FCMP_UGT: pred = "ugt"; break;
800 case FCmpInst::FCMP_UGE: pred = "uge"; break;
801 case FCmpInst::FCMP_ULT: pred = "ult"; break;
802 case FCmpInst::FCMP_ULE: pred = "ule"; break;
803 case FCmpInst::FCMP_UNE: pred = "une"; break;
804 case FCmpInst::FCMP_TRUE: pred = "true"; break;
805 case ICmpInst::ICMP_EQ: pred = "eq"; break;
806 case ICmpInst::ICMP_NE: pred = "ne"; break;
807 case ICmpInst::ICMP_SGT: pred = "sgt"; break;
808 case ICmpInst::ICMP_SGE: pred = "sge"; break;
809 case ICmpInst::ICMP_SLT: pred = "slt"; break;
810 case ICmpInst::ICMP_SLE: pred = "sle"; break;
811 case ICmpInst::ICMP_UGT: pred = "ugt"; break;
812 case ICmpInst::ICMP_UGE: pred = "uge"; break;
813 case ICmpInst::ICMP_ULT: pred = "ult"; break;
814 case ICmpInst::ICMP_ULE: pred = "ule"; break;
820 static void WriteOptimizationInfo(raw_ostream &Out, const User *U) {
821 if (const OverflowingBinaryOperator *OBO =
822 dyn_cast<OverflowingBinaryOperator>(U)) {
823 if (OBO->hasNoUnsignedWrap())
825 if (OBO->hasNoSignedWrap())
827 } else if (const SDivOperator *Div = dyn_cast<SDivOperator>(U)) {
830 } else if (const GEPOperator *GEP = dyn_cast<GEPOperator>(U)) {
831 if (GEP->isInBounds())
836 static void WriteConstantInt(raw_ostream &Out, const Constant *CV,
837 TypePrinting &TypePrinter, SlotTracker *Machine) {
838 if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV)) {
839 if (CI->getType()->isInteger(1)) {
840 Out << (CI->getZExtValue() ? "true" : "false");
843 Out << CI->getValue();
847 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CV)) {
848 if (&CFP->getValueAPF().getSemantics() == &APFloat::IEEEdouble ||
849 &CFP->getValueAPF().getSemantics() == &APFloat::IEEEsingle) {
850 // We would like to output the FP constant value in exponential notation,
851 // but we cannot do this if doing so will lose precision. Check here to
852 // make sure that we only output it in exponential format if we can parse
853 // the value back and get the same value.
856 bool isDouble = &CFP->getValueAPF().getSemantics()==&APFloat::IEEEdouble;
857 double Val = isDouble ? CFP->getValueAPF().convertToDouble() :
858 CFP->getValueAPF().convertToFloat();
859 SmallString<128> StrVal;
860 raw_svector_ostream(StrVal) << Val;
862 // Check to make sure that the stringized number is not some string like
863 // "Inf" or NaN, that atof will accept, but the lexer will not. Check
864 // that the string matches the "[-+]?[0-9]" regex.
866 if ((StrVal[0] >= '0' && StrVal[0] <= '9') ||
867 ((StrVal[0] == '-' || StrVal[0] == '+') &&
868 (StrVal[1] >= '0' && StrVal[1] <= '9'))) {
869 // Reparse stringized version!
870 if (atof(StrVal.c_str()) == Val) {
875 // Otherwise we could not reparse it to exactly the same value, so we must
876 // output the string in hexadecimal format! Note that loading and storing
877 // floating point types changes the bits of NaNs on some hosts, notably
878 // x86, so we must not use these types.
879 assert(sizeof(double) == sizeof(uint64_t) &&
880 "assuming that double is 64 bits!");
882 APFloat apf = CFP->getValueAPF();
883 // Floats are represented in ASCII IR as double, convert.
885 apf.convert(APFloat::IEEEdouble, APFloat::rmNearestTiesToEven,
888 utohex_buffer(uint64_t(apf.bitcastToAPInt().getZExtValue()),
893 // Some form of long double. These appear as a magic letter identifying
894 // the type, then a fixed number of hex digits.
896 if (&CFP->getValueAPF().getSemantics() == &APFloat::x87DoubleExtended) {
898 // api needed to prevent premature destruction
899 APInt api = CFP->getValueAPF().bitcastToAPInt();
900 const uint64_t* p = api.getRawData();
901 uint64_t word = p[1];
903 int width = api.getBitWidth();
904 for (int j=0; j<width; j+=4, shiftcount-=4) {
905 unsigned int nibble = (word>>shiftcount) & 15;
907 Out << (unsigned char)(nibble + '0');
909 Out << (unsigned char)(nibble - 10 + 'A');
910 if (shiftcount == 0 && j+4 < width) {
914 shiftcount = width-j-4;
918 } else if (&CFP->getValueAPF().getSemantics() == &APFloat::IEEEquad)
920 else if (&CFP->getValueAPF().getSemantics() == &APFloat::PPCDoubleDouble)
923 llvm_unreachable("Unsupported floating point type");
924 // api needed to prevent premature destruction
925 APInt api = CFP->getValueAPF().bitcastToAPInt();
926 const uint64_t* p = api.getRawData();
929 int width = api.getBitWidth();
930 for (int j=0; j<width; j+=4, shiftcount-=4) {
931 unsigned int nibble = (word>>shiftcount) & 15;
933 Out << (unsigned char)(nibble + '0');
935 Out << (unsigned char)(nibble - 10 + 'A');
936 if (shiftcount == 0 && j+4 < width) {
940 shiftcount = width-j-4;
946 if (isa<ConstantAggregateZero>(CV)) {
947 Out << "zeroinitializer";
951 if (const BlockAddress *BA = dyn_cast<BlockAddress>(CV)) {
952 Out << "blockaddress(";
953 WriteAsOperandInternal(Out, BA->getFunction(), &TypePrinter, Machine);
955 WriteAsOperandInternal(Out, BA->getBasicBlock(), &TypePrinter, Machine);
960 if (const ConstantArray *CA = dyn_cast<ConstantArray>(CV)) {
961 // As a special case, print the array as a string if it is an array of
962 // i8 with ConstantInt values.
964 const Type *ETy = CA->getType()->getElementType();
965 if (CA->isString()) {
967 PrintEscapedString(CA->getAsString(), Out);
969 } else { // Cannot output in string format...
971 if (CA->getNumOperands()) {
972 TypePrinter.print(ETy, Out);
974 WriteAsOperandInternal(Out, CA->getOperand(0),
975 &TypePrinter, Machine);
976 for (unsigned i = 1, e = CA->getNumOperands(); i != e; ++i) {
978 TypePrinter.print(ETy, Out);
980 WriteAsOperandInternal(Out, CA->getOperand(i), &TypePrinter, Machine);
988 if (const ConstantStruct *CS = dyn_cast<ConstantStruct>(CV)) {
989 if (CS->getType()->isPacked())
992 unsigned N = CS->getNumOperands();
995 TypePrinter.print(CS->getOperand(0)->getType(), Out);
998 WriteAsOperandInternal(Out, CS->getOperand(0), &TypePrinter, Machine);
1000 for (unsigned i = 1; i < N; i++) {
1002 TypePrinter.print(CS->getOperand(i)->getType(), Out);
1005 WriteAsOperandInternal(Out, CS->getOperand(i), &TypePrinter, Machine);
1011 if (CS->getType()->isPacked())
1016 if (const ConstantVector *CP = dyn_cast<ConstantVector>(CV)) {
1017 const Type *ETy = CP->getType()->getElementType();
1018 assert(CP->getNumOperands() > 0 &&
1019 "Number of operands for a PackedConst must be > 0");
1021 TypePrinter.print(ETy, Out);
1023 WriteAsOperandInternal(Out, CP->getOperand(0), &TypePrinter, Machine);
1024 for (unsigned i = 1, e = CP->getNumOperands(); i != e; ++i) {
1026 TypePrinter.print(ETy, Out);
1028 WriteAsOperandInternal(Out, CP->getOperand(i), &TypePrinter, Machine);
1034 if (isa<ConstantPointerNull>(CV)) {
1039 if (isa<UndefValue>(CV)) {
1044 if (const MDNode *Node = dyn_cast<MDNode>(CV)) {
1045 Out << "!" << Machine->getMetadataSlot(Node);
1049 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV)) {
1050 Out << CE->getOpcodeName();
1051 WriteOptimizationInfo(Out, CE);
1052 if (CE->isCompare())
1053 Out << ' ' << getPredicateText(CE->getPredicate());
1056 for (User::const_op_iterator OI=CE->op_begin(); OI != CE->op_end(); ++OI) {
1057 TypePrinter.print((*OI)->getType(), Out);
1059 WriteAsOperandInternal(Out, *OI, &TypePrinter, Machine);
1060 if (OI+1 != CE->op_end())
1064 if (CE->hasIndices()) {
1065 const SmallVector<unsigned, 4> &Indices = CE->getIndices();
1066 for (unsigned i = 0, e = Indices.size(); i != e; ++i)
1067 Out << ", " << Indices[i];
1072 TypePrinter.print(CE->getType(), Out);
1079 Out << "<placeholder or erroneous Constant>";
1082 static void WriteMDNodeBodyInternal(raw_ostream &Out, const MDNode *Node,
1083 TypePrinting *TypePrinter,
1084 SlotTracker *Machine) {
1086 for (unsigned mi = 0, me = Node->getNumOperands(); mi != me; ++mi) {
1087 const Value *V = Node->getOperand(mi);
1091 TypePrinter->print(V->getType(), Out);
1093 WriteAsOperandInternal(Out, Node->getOperand(mi),
1094 TypePrinter, Machine);
1104 /// WriteAsOperand - Write the name of the specified value out to the specified
1105 /// ostream. This can be useful when you just want to print int %reg126, not
1106 /// the whole instruction that generated it.
1108 static void WriteAsOperandInternal(raw_ostream &Out, const Value *V,
1109 TypePrinting *TypePrinter,
1110 SlotTracker *Machine) {
1112 PrintLLVMName(Out, V);
1116 const Constant *CV = dyn_cast<Constant>(V);
1117 if (CV && !isa<GlobalValue>(CV)) {
1118 assert(TypePrinter && "Constants require TypePrinting!");
1119 WriteConstantInt(Out, CV, *TypePrinter, Machine);
1123 if (const InlineAsm *IA = dyn_cast<InlineAsm>(V)) {
1125 if (IA->hasSideEffects())
1126 Out << "sideeffect ";
1127 if (IA->isAlignStack())
1128 Out << "alignstack ";
1130 PrintEscapedString(IA->getAsmString(), Out);
1132 PrintEscapedString(IA->getConstraintString(), Out);
1137 if (const MDNode *N = dyn_cast<MDNode>(V)) {
1138 if (N->isFunctionLocal()) {
1139 // Print metadata inline, not via slot reference number.
1140 WriteMDNodeBodyInternal(Out, N, TypePrinter, Machine);
1145 Machine = createSlotTracker(V);
1146 Out << '!' << Machine->getMetadataSlot(N);
1150 if (const MDString *MDS = dyn_cast<MDString>(V)) {
1152 PrintEscapedString(MDS->getString(), Out);
1157 if (V->getValueID() == Value::PseudoSourceValueVal ||
1158 V->getValueID() == Value::FixedStackPseudoSourceValueVal) {
1166 if (const GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
1167 Slot = Machine->getGlobalSlot(GV);
1170 Slot = Machine->getLocalSlot(V);
1173 Machine = createSlotTracker(V);
1175 if (const GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
1176 Slot = Machine->getGlobalSlot(GV);
1179 Slot = Machine->getLocalSlot(V);
1188 Out << Prefix << Slot;
1193 void llvm::WriteAsOperand(raw_ostream &Out, const Value *V,
1194 bool PrintType, const Module *Context) {
1196 // Fast path: Don't construct and populate a TypePrinting object if we
1197 // won't be needing any types printed.
1199 (!isa<Constant>(V) || V->hasName() || isa<GlobalValue>(V))) {
1200 WriteAsOperandInternal(Out, V, 0, 0);
1204 if (Context == 0) Context = getModuleFromVal(V);
1206 TypePrinting TypePrinter;
1207 std::vector<const Type*> NumberedTypes;
1208 AddModuleTypesToPrinter(TypePrinter, NumberedTypes, Context);
1210 TypePrinter.print(V->getType(), Out);
1214 WriteAsOperandInternal(Out, V, &TypePrinter, 0);
1219 class AssemblyWriter {
1220 formatted_raw_ostream &Out;
1221 SlotTracker &Machine;
1222 const Module *TheModule;
1223 TypePrinting TypePrinter;
1224 AssemblyAnnotationWriter *AnnotationWriter;
1225 std::vector<const Type*> NumberedTypes;
1226 SmallVector<StringRef, 8> MDNames;
1229 inline AssemblyWriter(formatted_raw_ostream &o, SlotTracker &Mac,
1231 AssemblyAnnotationWriter *AAW)
1232 : Out(o), Machine(Mac), TheModule(M), AnnotationWriter(AAW) {
1233 AddModuleTypesToPrinter(TypePrinter, NumberedTypes, M);
1235 M->getMDKindNames(MDNames);
1238 void printMDNodeBody(const MDNode *MD);
1239 void printNamedMDNode(const NamedMDNode *NMD);
1241 void printModule(const Module *M);
1243 void writeOperand(const Value *Op, bool PrintType);
1244 void writeParamOperand(const Value *Operand, Attributes Attrs);
1246 void writeAllMDNodes();
1248 void printTypeSymbolTable(const TypeSymbolTable &ST);
1249 void printGlobal(const GlobalVariable *GV);
1250 void printAlias(const GlobalAlias *GV);
1251 void printFunction(const Function *F);
1252 void printArgument(const Argument *FA, Attributes Attrs);
1253 void printBasicBlock(const BasicBlock *BB);
1254 void printInstruction(const Instruction &I);
1257 // printInfoComment - Print a little comment after the instruction indicating
1258 // which slot it occupies.
1259 void printInfoComment(const Value &V);
1261 } // end of anonymous namespace
1264 void AssemblyWriter::writeOperand(const Value *Operand, bool PrintType) {
1266 Out << "<null operand!>";
1270 TypePrinter.print(Operand->getType(), Out);
1273 WriteAsOperandInternal(Out, Operand, &TypePrinter, &Machine);
1276 void AssemblyWriter::writeParamOperand(const Value *Operand,
1279 Out << "<null operand!>";
1284 TypePrinter.print(Operand->getType(), Out);
1285 // Print parameter attributes list
1286 if (Attrs != Attribute::None)
1287 Out << ' ' << Attribute::getAsString(Attrs);
1289 // Print the operand
1290 WriteAsOperandInternal(Out, Operand, &TypePrinter, &Machine);
1293 void AssemblyWriter::printModule(const Module *M) {
1294 if (!M->getModuleIdentifier().empty() &&
1295 // Don't print the ID if it will start a new line (which would
1296 // require a comment char before it).
1297 M->getModuleIdentifier().find('\n') == std::string::npos)
1298 Out << "; ModuleID = '" << M->getModuleIdentifier() << "'\n";
1300 if (!M->getDataLayout().empty())
1301 Out << "target datalayout = \"" << M->getDataLayout() << "\"\n";
1302 if (!M->getTargetTriple().empty())
1303 Out << "target triple = \"" << M->getTargetTriple() << "\"\n";
1305 if (!M->getModuleInlineAsm().empty()) {
1306 // Split the string into lines, to make it easier to read the .ll file.
1307 std::string Asm = M->getModuleInlineAsm();
1309 size_t NewLine = Asm.find_first_of('\n', CurPos);
1311 while (NewLine != std::string::npos) {
1312 // We found a newline, print the portion of the asm string from the
1313 // last newline up to this newline.
1314 Out << "module asm \"";
1315 PrintEscapedString(std::string(Asm.begin()+CurPos, Asm.begin()+NewLine),
1319 NewLine = Asm.find_first_of('\n', CurPos);
1321 Out << "module asm \"";
1322 PrintEscapedString(std::string(Asm.begin()+CurPos, Asm.end()), Out);
1326 // Loop over the dependent libraries and emit them.
1327 Module::lib_iterator LI = M->lib_begin();
1328 Module::lib_iterator LE = M->lib_end();
1331 Out << "deplibs = [ ";
1333 Out << '"' << *LI << '"';
1341 // Loop over the symbol table, emitting all id'd types.
1342 if (!M->getTypeSymbolTable().empty() || !NumberedTypes.empty()) Out << '\n';
1343 printTypeSymbolTable(M->getTypeSymbolTable());
1345 // Output all globals.
1346 if (!M->global_empty()) Out << '\n';
1347 for (Module::const_global_iterator I = M->global_begin(), E = M->global_end();
1351 // Output all aliases.
1352 if (!M->alias_empty()) Out << "\n";
1353 for (Module::const_alias_iterator I = M->alias_begin(), E = M->alias_end();
1357 // Output all of the functions.
1358 for (Module::const_iterator I = M->begin(), E = M->end(); I != E; ++I)
1361 // Output named metadata.
1362 if (!M->named_metadata_empty()) Out << '\n';
1364 for (Module::const_named_metadata_iterator I = M->named_metadata_begin(),
1365 E = M->named_metadata_end(); I != E; ++I)
1366 printNamedMDNode(I);
1369 if (!Machine.mdn_empty()) {
1375 void AssemblyWriter::printNamedMDNode(const NamedMDNode *NMD) {
1376 Out << "!" << NMD->getName() << " = !{";
1377 for (unsigned i = 0, e = NMD->getNumOperands(); i != e; ++i) {
1379 if (MDNode *MD = NMD->getOperand(i))
1380 Out << '!' << Machine.getMetadataSlot(MD);
1388 static void PrintLinkage(GlobalValue::LinkageTypes LT,
1389 formatted_raw_ostream &Out) {
1391 case GlobalValue::ExternalLinkage: break;
1392 case GlobalValue::PrivateLinkage: Out << "private "; break;
1393 case GlobalValue::LinkerPrivateLinkage: Out << "linker_private "; break;
1394 case GlobalValue::InternalLinkage: Out << "internal "; break;
1395 case GlobalValue::LinkOnceAnyLinkage: Out << "linkonce "; break;
1396 case GlobalValue::LinkOnceODRLinkage: Out << "linkonce_odr "; break;
1397 case GlobalValue::WeakAnyLinkage: Out << "weak "; break;
1398 case GlobalValue::WeakODRLinkage: Out << "weak_odr "; break;
1399 case GlobalValue::CommonLinkage: Out << "common "; break;
1400 case GlobalValue::AppendingLinkage: Out << "appending "; break;
1401 case GlobalValue::DLLImportLinkage: Out << "dllimport "; break;
1402 case GlobalValue::DLLExportLinkage: Out << "dllexport "; break;
1403 case GlobalValue::ExternalWeakLinkage: Out << "extern_weak "; break;
1404 case GlobalValue::AvailableExternallyLinkage:
1405 Out << "available_externally ";
1411 static void PrintVisibility(GlobalValue::VisibilityTypes Vis,
1412 formatted_raw_ostream &Out) {
1414 case GlobalValue::DefaultVisibility: break;
1415 case GlobalValue::HiddenVisibility: Out << "hidden "; break;
1416 case GlobalValue::ProtectedVisibility: Out << "protected "; break;
1420 void AssemblyWriter::printGlobal(const GlobalVariable *GV) {
1421 if (GV->isMaterializable())
1422 Out << "; Materializable\n";
1424 WriteAsOperandInternal(Out, GV, &TypePrinter, &Machine);
1427 if (!GV->hasInitializer() && GV->hasExternalLinkage())
1430 PrintLinkage(GV->getLinkage(), Out);
1431 PrintVisibility(GV->getVisibility(), Out);
1433 if (GV->isThreadLocal()) Out << "thread_local ";
1434 if (unsigned AddressSpace = GV->getType()->getAddressSpace())
1435 Out << "addrspace(" << AddressSpace << ") ";
1436 Out << (GV->isConstant() ? "constant " : "global ");
1437 TypePrinter.print(GV->getType()->getElementType(), Out);
1439 if (GV->hasInitializer()) {
1441 writeOperand(GV->getInitializer(), false);
1444 if (GV->hasSection())
1445 Out << ", section \"" << GV->getSection() << '"';
1446 if (GV->getAlignment())
1447 Out << ", align " << GV->getAlignment();
1449 printInfoComment(*GV);
1453 void AssemblyWriter::printAlias(const GlobalAlias *GA) {
1454 if (GA->isMaterializable())
1455 Out << "; Materializable\n";
1457 // Don't crash when dumping partially built GA
1459 Out << "<<nameless>> = ";
1461 PrintLLVMName(Out, GA);
1464 PrintVisibility(GA->getVisibility(), Out);
1468 PrintLinkage(GA->getLinkage(), Out);
1470 const Constant *Aliasee = GA->getAliasee();
1472 if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(Aliasee)) {
1473 TypePrinter.print(GV->getType(), Out);
1475 PrintLLVMName(Out, GV);
1476 } else if (const Function *F = dyn_cast<Function>(Aliasee)) {
1477 TypePrinter.print(F->getFunctionType(), Out);
1480 WriteAsOperandInternal(Out, F, &TypePrinter, &Machine);
1481 } else if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(Aliasee)) {
1482 TypePrinter.print(GA->getType(), Out);
1484 PrintLLVMName(Out, GA);
1486 const ConstantExpr *CE = cast<ConstantExpr>(Aliasee);
1487 // The only valid GEP is an all zero GEP.
1488 assert((CE->getOpcode() == Instruction::BitCast ||
1489 CE->getOpcode() == Instruction::GetElementPtr) &&
1490 "Unsupported aliasee");
1491 writeOperand(CE, false);
1494 printInfoComment(*GA);
1498 void AssemblyWriter::printTypeSymbolTable(const TypeSymbolTable &ST) {
1499 // Emit all numbered types.
1500 for (unsigned i = 0, e = NumberedTypes.size(); i != e; ++i) {
1501 Out << '%' << i << " = type ";
1503 // Make sure we print out at least one level of the type structure, so
1504 // that we do not get %2 = type %2
1505 TypePrinter.printAtLeastOneLevel(NumberedTypes[i], Out);
1509 // Print the named types.
1510 for (TypeSymbolTable::const_iterator TI = ST.begin(), TE = ST.end();
1512 PrintLLVMName(Out, TI->first, LocalPrefix);
1515 // Make sure we print out at least one level of the type structure, so
1516 // that we do not get %FILE = type %FILE
1517 TypePrinter.printAtLeastOneLevel(TI->second, Out);
1522 /// printFunction - Print all aspects of a function.
1524 void AssemblyWriter::printFunction(const Function *F) {
1525 // Print out the return type and name.
1528 if (AnnotationWriter) AnnotationWriter->emitFunctionAnnot(F, Out);
1530 if (F->isMaterializable())
1531 Out << "; Materializable\n";
1533 if (F->isDeclaration())
1538 PrintLinkage(F->getLinkage(), Out);
1539 PrintVisibility(F->getVisibility(), Out);
1541 // Print the calling convention.
1542 switch (F->getCallingConv()) {
1543 case CallingConv::C: break; // default
1544 case CallingConv::Fast: Out << "fastcc "; break;
1545 case CallingConv::Cold: Out << "coldcc "; break;
1546 case CallingConv::X86_StdCall: Out << "x86_stdcallcc "; break;
1547 case CallingConv::X86_FastCall: Out << "x86_fastcallcc "; break;
1548 case CallingConv::ARM_APCS: Out << "arm_apcscc "; break;
1549 case CallingConv::ARM_AAPCS: Out << "arm_aapcscc "; break;
1550 case CallingConv::ARM_AAPCS_VFP:Out << "arm_aapcs_vfpcc "; break;
1551 case CallingConv::MSP430_INTR: Out << "msp430_intrcc "; break;
1552 default: Out << "cc" << F->getCallingConv() << " "; break;
1555 const FunctionType *FT = F->getFunctionType();
1556 const AttrListPtr &Attrs = F->getAttributes();
1557 Attributes RetAttrs = Attrs.getRetAttributes();
1558 if (RetAttrs != Attribute::None)
1559 Out << Attribute::getAsString(Attrs.getRetAttributes()) << ' ';
1560 TypePrinter.print(F->getReturnType(), Out);
1562 WriteAsOperandInternal(Out, F, &TypePrinter, &Machine);
1564 Machine.incorporateFunction(F);
1566 // Loop over the arguments, printing them...
1569 if (!F->isDeclaration()) {
1570 // If this isn't a declaration, print the argument names as well.
1571 for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
1573 // Insert commas as we go... the first arg doesn't get a comma
1574 if (I != F->arg_begin()) Out << ", ";
1575 printArgument(I, Attrs.getParamAttributes(Idx));
1579 // Otherwise, print the types from the function type.
1580 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
1581 // Insert commas as we go... the first arg doesn't get a comma
1585 TypePrinter.print(FT->getParamType(i), Out);
1587 Attributes ArgAttrs = Attrs.getParamAttributes(i+1);
1588 if (ArgAttrs != Attribute::None)
1589 Out << ' ' << Attribute::getAsString(ArgAttrs);
1593 // Finish printing arguments...
1594 if (FT->isVarArg()) {
1595 if (FT->getNumParams()) Out << ", ";
1596 Out << "..."; // Output varargs portion of signature!
1599 Attributes FnAttrs = Attrs.getFnAttributes();
1600 if (FnAttrs != Attribute::None)
1601 Out << ' ' << Attribute::getAsString(Attrs.getFnAttributes());
1602 if (F->hasSection())
1603 Out << " section \"" << F->getSection() << '"';
1604 if (F->getAlignment())
1605 Out << " align " << F->getAlignment();
1607 Out << " gc \"" << F->getGC() << '"';
1608 if (F->isDeclaration()) {
1613 // Output all of its basic blocks... for the function
1614 for (Function::const_iterator I = F->begin(), E = F->end(); I != E; ++I)
1620 Machine.purgeFunction();
1623 /// printArgument - This member is called for every argument that is passed into
1624 /// the function. Simply print it out
1626 void AssemblyWriter::printArgument(const Argument *Arg,
1629 TypePrinter.print(Arg->getType(), Out);
1631 // Output parameter attributes list
1632 if (Attrs != Attribute::None)
1633 Out << ' ' << Attribute::getAsString(Attrs);
1635 // Output name, if available...
1636 if (Arg->hasName()) {
1638 PrintLLVMName(Out, Arg);
1642 /// printBasicBlock - This member is called for each basic block in a method.
1644 void AssemblyWriter::printBasicBlock(const BasicBlock *BB) {
1645 if (BB->hasName()) { // Print out the label if it exists...
1647 PrintLLVMName(Out, BB->getName(), LabelPrefix);
1649 } else if (!BB->use_empty()) { // Don't print block # of no uses...
1650 Out << "\n; <label>:";
1651 int Slot = Machine.getLocalSlot(BB);
1658 if (BB->getParent() == 0) {
1659 Out.PadToColumn(50);
1660 Out << "; Error: Block without parent!";
1661 } else if (BB != &BB->getParent()->getEntryBlock()) { // Not the entry block?
1662 // Output predecessors for the block...
1663 Out.PadToColumn(50);
1665 pred_const_iterator PI = pred_begin(BB), PE = pred_end(BB);
1668 Out << " No predecessors!";
1671 writeOperand(*PI, false);
1672 for (++PI; PI != PE; ++PI) {
1674 writeOperand(*PI, false);
1681 if (AnnotationWriter) AnnotationWriter->emitBasicBlockStartAnnot(BB, Out);
1683 // Output all of the instructions in the basic block...
1684 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I != E; ++I) {
1685 printInstruction(*I);
1689 if (AnnotationWriter) AnnotationWriter->emitBasicBlockEndAnnot(BB, Out);
1693 /// printInfoComment - Print a little comment after the instruction indicating
1694 /// which slot it occupies.
1696 void AssemblyWriter::printInfoComment(const Value &V) {
1697 if (V.getType()->isVoidTy()) return;
1699 Out.PadToColumn(50);
1701 TypePrinter.print(V.getType(), Out);
1702 Out << "> [#uses=" << V.getNumUses() << ']'; // Output # uses
1705 // This member is called for each Instruction in a function..
1706 void AssemblyWriter::printInstruction(const Instruction &I) {
1707 if (AnnotationWriter) AnnotationWriter->emitInstructionAnnot(&I, Out);
1709 // Print out indentation for an instruction.
1712 // Print out name if it exists...
1714 PrintLLVMName(Out, &I);
1716 } else if (!I.getType()->isVoidTy()) {
1717 // Print out the def slot taken.
1718 int SlotNum = Machine.getLocalSlot(&I);
1720 Out << "<badref> = ";
1722 Out << '%' << SlotNum << " = ";
1725 // If this is a volatile load or store, print out the volatile marker.
1726 if ((isa<LoadInst>(I) && cast<LoadInst>(I).isVolatile()) ||
1727 (isa<StoreInst>(I) && cast<StoreInst>(I).isVolatile())) {
1729 } else if (isa<CallInst>(I) && cast<CallInst>(I).isTailCall()) {
1730 // If this is a call, check if it's a tail call.
1734 // Print out the opcode...
1735 Out << I.getOpcodeName();
1737 // Print out optimization information.
1738 WriteOptimizationInfo(Out, &I);
1740 // Print out the compare instruction predicates
1741 if (const CmpInst *CI = dyn_cast<CmpInst>(&I))
1742 Out << ' ' << getPredicateText(CI->getPredicate());
1744 // Print out the type of the operands...
1745 const Value *Operand = I.getNumOperands() ? I.getOperand(0) : 0;
1747 // Special case conditional branches to swizzle the condition out to the front
1748 if (isa<BranchInst>(I) && cast<BranchInst>(I).isConditional()) {
1749 BranchInst &BI(cast<BranchInst>(I));
1751 writeOperand(BI.getCondition(), true);
1753 writeOperand(BI.getSuccessor(0), true);
1755 writeOperand(BI.getSuccessor(1), true);
1757 } else if (isa<SwitchInst>(I)) {
1758 // Special case switch instruction to get formatting nice and correct.
1760 writeOperand(Operand , true);
1762 writeOperand(I.getOperand(1), true);
1765 for (unsigned op = 2, Eop = I.getNumOperands(); op < Eop; op += 2) {
1767 writeOperand(I.getOperand(op ), true);
1769 writeOperand(I.getOperand(op+1), true);
1772 } else if (isa<IndirectBrInst>(I)) {
1773 // Special case indirectbr instruction to get formatting nice and correct.
1775 writeOperand(Operand, true);
1778 for (unsigned i = 1, e = I.getNumOperands(); i != e; ++i) {
1781 writeOperand(I.getOperand(i), true);
1784 } else if (isa<PHINode>(I)) {
1786 TypePrinter.print(I.getType(), Out);
1789 for (unsigned op = 0, Eop = I.getNumOperands(); op < Eop; op += 2) {
1790 if (op) Out << ", ";
1792 writeOperand(I.getOperand(op ), false); Out << ", ";
1793 writeOperand(I.getOperand(op+1), false); Out << " ]";
1795 } else if (const ExtractValueInst *EVI = dyn_cast<ExtractValueInst>(&I)) {
1797 writeOperand(I.getOperand(0), true);
1798 for (const unsigned *i = EVI->idx_begin(), *e = EVI->idx_end(); i != e; ++i)
1800 } else if (const InsertValueInst *IVI = dyn_cast<InsertValueInst>(&I)) {
1802 writeOperand(I.getOperand(0), true); Out << ", ";
1803 writeOperand(I.getOperand(1), true);
1804 for (const unsigned *i = IVI->idx_begin(), *e = IVI->idx_end(); i != e; ++i)
1806 } else if (isa<ReturnInst>(I) && !Operand) {
1808 } else if (const CallInst *CI = dyn_cast<CallInst>(&I)) {
1809 // Print the calling convention being used.
1810 switch (CI->getCallingConv()) {
1811 case CallingConv::C: break; // default
1812 case CallingConv::Fast: Out << " fastcc"; break;
1813 case CallingConv::Cold: Out << " coldcc"; break;
1814 case CallingConv::X86_StdCall: Out << " x86_stdcallcc"; break;
1815 case CallingConv::X86_FastCall: Out << " x86_fastcallcc"; break;
1816 case CallingConv::ARM_APCS: Out << " arm_apcscc "; break;
1817 case CallingConv::ARM_AAPCS: Out << " arm_aapcscc "; break;
1818 case CallingConv::ARM_AAPCS_VFP:Out << " arm_aapcs_vfpcc "; break;
1819 case CallingConv::MSP430_INTR: Out << " msp430_intrcc "; break;
1820 default: Out << " cc" << CI->getCallingConv(); break;
1823 const PointerType *PTy = cast<PointerType>(Operand->getType());
1824 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
1825 const Type *RetTy = FTy->getReturnType();
1826 const AttrListPtr &PAL = CI->getAttributes();
1828 if (PAL.getRetAttributes() != Attribute::None)
1829 Out << ' ' << Attribute::getAsString(PAL.getRetAttributes());
1831 // If possible, print out the short form of the call instruction. We can
1832 // only do this if the first argument is a pointer to a nonvararg function,
1833 // and if the return type is not a pointer to a function.
1836 if (!FTy->isVarArg() &&
1837 (!isa<PointerType>(RetTy) ||
1838 !isa<FunctionType>(cast<PointerType>(RetTy)->getElementType()))) {
1839 TypePrinter.print(RetTy, Out);
1841 writeOperand(Operand, false);
1843 writeOperand(Operand, true);
1846 for (unsigned op = 1, Eop = I.getNumOperands(); op < Eop; ++op) {
1849 writeParamOperand(I.getOperand(op), PAL.getParamAttributes(op));
1852 if (PAL.getFnAttributes() != Attribute::None)
1853 Out << ' ' << Attribute::getAsString(PAL.getFnAttributes());
1854 } else if (const InvokeInst *II = dyn_cast<InvokeInst>(&I)) {
1855 const PointerType *PTy = cast<PointerType>(Operand->getType());
1856 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
1857 const Type *RetTy = FTy->getReturnType();
1858 const AttrListPtr &PAL = II->getAttributes();
1860 // Print the calling convention being used.
1861 switch (II->getCallingConv()) {
1862 case CallingConv::C: break; // default
1863 case CallingConv::Fast: Out << " fastcc"; break;
1864 case CallingConv::Cold: Out << " coldcc"; break;
1865 case CallingConv::X86_StdCall: Out << " x86_stdcallcc"; break;
1866 case CallingConv::X86_FastCall: Out << " x86_fastcallcc"; break;
1867 case CallingConv::ARM_APCS: Out << " arm_apcscc "; break;
1868 case CallingConv::ARM_AAPCS: Out << " arm_aapcscc "; break;
1869 case CallingConv::ARM_AAPCS_VFP:Out << " arm_aapcs_vfpcc "; break;
1870 case CallingConv::MSP430_INTR: Out << " msp430_intrcc "; break;
1871 default: Out << " cc" << II->getCallingConv(); break;
1874 if (PAL.getRetAttributes() != Attribute::None)
1875 Out << ' ' << Attribute::getAsString(PAL.getRetAttributes());
1877 // If possible, print out the short form of the invoke instruction. We can
1878 // only do this if the first argument is a pointer to a nonvararg function,
1879 // and if the return type is not a pointer to a function.
1882 if (!FTy->isVarArg() &&
1883 (!isa<PointerType>(RetTy) ||
1884 !isa<FunctionType>(cast<PointerType>(RetTy)->getElementType()))) {
1885 TypePrinter.print(RetTy, Out);
1887 writeOperand(Operand, false);
1889 writeOperand(Operand, true);
1892 for (unsigned op = 3, Eop = I.getNumOperands(); op < Eop; ++op) {
1895 writeParamOperand(I.getOperand(op), PAL.getParamAttributes(op-2));
1899 if (PAL.getFnAttributes() != Attribute::None)
1900 Out << ' ' << Attribute::getAsString(PAL.getFnAttributes());
1903 writeOperand(II->getNormalDest(), true);
1905 writeOperand(II->getUnwindDest(), true);
1907 } else if (const AllocaInst *AI = dyn_cast<AllocaInst>(&I)) {
1909 TypePrinter.print(AI->getType()->getElementType(), Out);
1910 if (!AI->getArraySize() || AI->isArrayAllocation()) {
1912 writeOperand(AI->getArraySize(), true);
1914 if (AI->getAlignment()) {
1915 Out << ", align " << AI->getAlignment();
1917 } else if (isa<CastInst>(I)) {
1920 writeOperand(Operand, true); // Work with broken code
1923 TypePrinter.print(I.getType(), Out);
1924 } else if (isa<VAArgInst>(I)) {
1927 writeOperand(Operand, true); // Work with broken code
1930 TypePrinter.print(I.getType(), Out);
1931 } else if (Operand) { // Print the normal way.
1933 // PrintAllTypes - Instructions who have operands of all the same type
1934 // omit the type from all but the first operand. If the instruction has
1935 // different type operands (for example br), then they are all printed.
1936 bool PrintAllTypes = false;
1937 const Type *TheType = Operand->getType();
1939 // Select, Store and ShuffleVector always print all types.
1940 if (isa<SelectInst>(I) || isa<StoreInst>(I) || isa<ShuffleVectorInst>(I)
1941 || isa<ReturnInst>(I)) {
1942 PrintAllTypes = true;
1944 for (unsigned i = 1, E = I.getNumOperands(); i != E; ++i) {
1945 Operand = I.getOperand(i);
1946 // note that Operand shouldn't be null, but the test helps make dump()
1947 // more tolerant of malformed IR
1948 if (Operand && Operand->getType() != TheType) {
1949 PrintAllTypes = true; // We have differing types! Print them all!
1955 if (!PrintAllTypes) {
1957 TypePrinter.print(TheType, Out);
1961 for (unsigned i = 0, E = I.getNumOperands(); i != E; ++i) {
1963 writeOperand(I.getOperand(i), PrintAllTypes);
1967 // Print post operand alignment for load/store.
1968 if (isa<LoadInst>(I) && cast<LoadInst>(I).getAlignment()) {
1969 Out << ", align " << cast<LoadInst>(I).getAlignment();
1970 } else if (isa<StoreInst>(I) && cast<StoreInst>(I).getAlignment()) {
1971 Out << ", align " << cast<StoreInst>(I).getAlignment();
1974 // Print Metadata info.
1975 if (!MDNames.empty()) {
1976 SmallVector<std::pair<unsigned, MDNode*>, 4> InstMD;
1977 I.getAllMetadata(InstMD);
1978 for (unsigned i = 0, e = InstMD.size(); i != e; ++i)
1979 Out << ", !" << MDNames[InstMD[i].first]
1980 << " !" << Machine.getMetadataSlot(InstMD[i].second);
1982 printInfoComment(I);
1985 static void WriteMDNodeComment(const MDNode *Node,
1986 formatted_raw_ostream &Out) {
1987 if (Node->getNumOperands() < 1)
1989 ConstantInt *CI = dyn_cast_or_null<ConstantInt>(Node->getOperand(0));
1991 unsigned Val = CI->getZExtValue();
1992 unsigned Tag = Val & ~LLVMDebugVersionMask;
1993 if (Val < LLVMDebugVersion)
1996 Out.PadToColumn(50);
1997 if (Tag == dwarf::DW_TAG_auto_variable)
1998 Out << "; [ DW_TAG_auto_variable ]";
1999 else if (Tag == dwarf::DW_TAG_arg_variable)
2000 Out << "; [ DW_TAG_arg_variable ]";
2001 else if (Tag == dwarf::DW_TAG_return_variable)
2002 Out << "; [ DW_TAG_return_variable ]";
2003 else if (Tag == dwarf::DW_TAG_vector_type)
2004 Out << "; [ DW_TAG_vector_type ]";
2005 else if (Tag == dwarf::DW_TAG_user_base)
2006 Out << "; [ DW_TAG_user_base ]";
2007 else if (const char *TagName = dwarf::TagString(Tag))
2008 Out << "; [ " << TagName << " ]";
2011 void AssemblyWriter::writeAllMDNodes() {
2012 SmallVector<const MDNode *, 16> Nodes;
2013 Nodes.resize(Machine.mdn_size());
2014 for (SlotTracker::mdn_iterator I = Machine.mdn_begin(), E = Machine.mdn_end();
2016 Nodes[I->second] = cast<MDNode>(I->first);
2018 for (unsigned i = 0, e = Nodes.size(); i != e; ++i) {
2019 Out << '!' << i << " = metadata ";
2020 printMDNodeBody(Nodes[i]);
2024 void AssemblyWriter::printMDNodeBody(const MDNode *Node) {
2025 WriteMDNodeBodyInternal(Out, Node, &TypePrinter, &Machine);
2026 WriteMDNodeComment(Node, Out);
2030 //===----------------------------------------------------------------------===//
2031 // External Interface declarations
2032 //===----------------------------------------------------------------------===//
2034 void Module::print(raw_ostream &ROS, AssemblyAnnotationWriter *AAW) const {
2035 SlotTracker SlotTable(this);
2036 formatted_raw_ostream OS(ROS);
2037 AssemblyWriter W(OS, SlotTable, this, AAW);
2038 W.printModule(this);
2041 void Type::print(raw_ostream &OS) const {
2043 OS << "<null Type>";
2046 TypePrinting().print(this, OS);
2049 void Value::print(raw_ostream &ROS, AssemblyAnnotationWriter *AAW) const {
2051 ROS << "printing a <null> value\n";
2054 formatted_raw_ostream OS(ROS);
2055 if (const Instruction *I = dyn_cast<Instruction>(this)) {
2056 const Function *F = I->getParent() ? I->getParent()->getParent() : 0;
2057 SlotTracker SlotTable(F);
2058 AssemblyWriter W(OS, SlotTable, getModuleFromVal(I), AAW);
2059 W.printInstruction(*I);
2060 } else if (const BasicBlock *BB = dyn_cast<BasicBlock>(this)) {
2061 SlotTracker SlotTable(BB->getParent());
2062 AssemblyWriter W(OS, SlotTable, getModuleFromVal(BB), AAW);
2063 W.printBasicBlock(BB);
2064 } else if (const GlobalValue *GV = dyn_cast<GlobalValue>(this)) {
2065 SlotTracker SlotTable(GV->getParent());
2066 AssemblyWriter W(OS, SlotTable, GV->getParent(), AAW);
2067 if (const GlobalVariable *V = dyn_cast<GlobalVariable>(GV))
2069 else if (const Function *F = dyn_cast<Function>(GV))
2072 W.printAlias(cast<GlobalAlias>(GV));
2073 } else if (const MDNode *N = dyn_cast<MDNode>(this)) {
2074 const Function *F = N->getFunction();
2075 SlotTracker SlotTable(F);
2076 AssemblyWriter W(OS, SlotTable, F ? getModuleFromVal(F) : 0, AAW);
2077 W.printMDNodeBody(N);
2078 } else if (const NamedMDNode *N = dyn_cast<NamedMDNode>(this)) {
2079 SlotTracker SlotTable(N->getParent());
2080 AssemblyWriter W(OS, SlotTable, N->getParent(), AAW);
2081 W.printNamedMDNode(N);
2082 } else if (const Constant *C = dyn_cast<Constant>(this)) {
2083 TypePrinting TypePrinter;
2084 TypePrinter.print(C->getType(), OS);
2086 WriteConstantInt(OS, C, TypePrinter, 0);
2087 } else if (isa<InlineAsm>(this) || isa<MDString>(this) ||
2088 isa<Argument>(this)) {
2089 WriteAsOperand(OS, this, true, 0);
2091 // Otherwise we don't know what it is. Call the virtual function to
2092 // allow a subclass to print itself.
2097 // Value::printCustom - subclasses should override this to implement printing.
2098 void Value::printCustom(raw_ostream &OS) const {
2099 llvm_unreachable("Unknown value to print out!");
2102 // Value::dump - allow easy printing of Values from the debugger.
2103 void Value::dump() const { print(dbgs()); dbgs() << '\n'; }
2105 // Type::dump - allow easy printing of Types from the debugger.
2106 // This one uses type names from the given context module
2107 void Type::dump(const Module *Context) const {
2108 WriteTypeSymbolic(dbgs(), this, Context);
2112 // Type::dump - allow easy printing of Types from the debugger.
2113 void Type::dump() const { dump(0); }
2115 // Module::dump() - Allow printing of Modules from the debugger.
2116 void Module::dump() const { print(dbgs(), 0); }