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
1263 void AssemblyWriter::writeOperand(const Value *Operand, bool PrintType) {
1265 Out << "<null operand!>";
1269 TypePrinter.print(Operand->getType(), Out);
1272 WriteAsOperandInternal(Out, Operand, &TypePrinter, &Machine);
1275 void AssemblyWriter::writeParamOperand(const Value *Operand,
1278 Out << "<null operand!>";
1283 TypePrinter.print(Operand->getType(), Out);
1284 // Print parameter attributes list
1285 if (Attrs != Attribute::None)
1286 Out << ' ' << Attribute::getAsString(Attrs);
1288 // Print the operand
1289 WriteAsOperandInternal(Out, Operand, &TypePrinter, &Machine);
1292 void AssemblyWriter::printModule(const Module *M) {
1293 if (!M->getModuleIdentifier().empty() &&
1294 // Don't print the ID if it will start a new line (which would
1295 // require a comment char before it).
1296 M->getModuleIdentifier().find('\n') == std::string::npos)
1297 Out << "; ModuleID = '" << M->getModuleIdentifier() << "'\n";
1299 if (!M->getDataLayout().empty())
1300 Out << "target datalayout = \"" << M->getDataLayout() << "\"\n";
1301 if (!M->getTargetTriple().empty())
1302 Out << "target triple = \"" << M->getTargetTriple() << "\"\n";
1304 if (!M->getModuleInlineAsm().empty()) {
1305 // Split the string into lines, to make it easier to read the .ll file.
1306 std::string Asm = M->getModuleInlineAsm();
1308 size_t NewLine = Asm.find_first_of('\n', CurPos);
1310 while (NewLine != std::string::npos) {
1311 // We found a newline, print the portion of the asm string from the
1312 // last newline up to this newline.
1313 Out << "module asm \"";
1314 PrintEscapedString(std::string(Asm.begin()+CurPos, Asm.begin()+NewLine),
1318 NewLine = Asm.find_first_of('\n', CurPos);
1320 Out << "module asm \"";
1321 PrintEscapedString(std::string(Asm.begin()+CurPos, Asm.end()), Out);
1325 // Loop over the dependent libraries and emit them.
1326 Module::lib_iterator LI = M->lib_begin();
1327 Module::lib_iterator LE = M->lib_end();
1330 Out << "deplibs = [ ";
1332 Out << '"' << *LI << '"';
1340 // Loop over the symbol table, emitting all id'd types.
1341 if (!M->getTypeSymbolTable().empty() || !NumberedTypes.empty()) Out << '\n';
1342 printTypeSymbolTable(M->getTypeSymbolTable());
1344 // Output all globals.
1345 if (!M->global_empty()) Out << '\n';
1346 for (Module::const_global_iterator I = M->global_begin(), E = M->global_end();
1350 // Output all aliases.
1351 if (!M->alias_empty()) Out << "\n";
1352 for (Module::const_alias_iterator I = M->alias_begin(), E = M->alias_end();
1356 // Output all of the functions.
1357 for (Module::const_iterator I = M->begin(), E = M->end(); I != E; ++I)
1360 // Output named metadata.
1361 if (!M->named_metadata_empty()) Out << '\n';
1363 for (Module::const_named_metadata_iterator I = M->named_metadata_begin(),
1364 E = M->named_metadata_end(); I != E; ++I)
1365 printNamedMDNode(I);
1368 if (!Machine.mdn_empty()) {
1374 void AssemblyWriter::printNamedMDNode(const NamedMDNode *NMD) {
1375 Out << "!" << NMD->getName() << " = !{";
1376 for (unsigned i = 0, e = NMD->getNumOperands(); i != e; ++i) {
1378 if (MDNode *MD = NMD->getOperand(i))
1379 Out << '!' << Machine.getMetadataSlot(MD);
1387 static void PrintLinkage(GlobalValue::LinkageTypes LT,
1388 formatted_raw_ostream &Out) {
1390 case GlobalValue::ExternalLinkage: break;
1391 case GlobalValue::PrivateLinkage: Out << "private "; break;
1392 case GlobalValue::LinkerPrivateLinkage: Out << "linker_private "; break;
1393 case GlobalValue::InternalLinkage: Out << "internal "; break;
1394 case GlobalValue::LinkOnceAnyLinkage: Out << "linkonce "; break;
1395 case GlobalValue::LinkOnceODRLinkage: Out << "linkonce_odr "; break;
1396 case GlobalValue::WeakAnyLinkage: Out << "weak "; break;
1397 case GlobalValue::WeakODRLinkage: Out << "weak_odr "; break;
1398 case GlobalValue::CommonLinkage: Out << "common "; break;
1399 case GlobalValue::AppendingLinkage: Out << "appending "; break;
1400 case GlobalValue::DLLImportLinkage: Out << "dllimport "; break;
1401 case GlobalValue::DLLExportLinkage: Out << "dllexport "; break;
1402 case GlobalValue::ExternalWeakLinkage: Out << "extern_weak "; break;
1403 case GlobalValue::AvailableExternallyLinkage:
1404 Out << "available_externally ";
1410 static void PrintVisibility(GlobalValue::VisibilityTypes Vis,
1411 formatted_raw_ostream &Out) {
1413 case GlobalValue::DefaultVisibility: break;
1414 case GlobalValue::HiddenVisibility: Out << "hidden "; break;
1415 case GlobalValue::ProtectedVisibility: Out << "protected "; break;
1419 void AssemblyWriter::printGlobal(const GlobalVariable *GV) {
1420 if (GV->isMaterializable())
1421 Out << "; Materializable\n";
1423 WriteAsOperandInternal(Out, GV, &TypePrinter, &Machine);
1426 if (!GV->hasInitializer() && GV->hasExternalLinkage())
1429 PrintLinkage(GV->getLinkage(), Out);
1430 PrintVisibility(GV->getVisibility(), Out);
1432 if (GV->isThreadLocal()) Out << "thread_local ";
1433 if (unsigned AddressSpace = GV->getType()->getAddressSpace())
1434 Out << "addrspace(" << AddressSpace << ") ";
1435 Out << (GV->isConstant() ? "constant " : "global ");
1436 TypePrinter.print(GV->getType()->getElementType(), Out);
1438 if (GV->hasInitializer()) {
1440 writeOperand(GV->getInitializer(), false);
1443 if (GV->hasSection())
1444 Out << ", section \"" << GV->getSection() << '"';
1445 if (GV->getAlignment())
1446 Out << ", align " << GV->getAlignment();
1448 printInfoComment(*GV);
1452 void AssemblyWriter::printAlias(const GlobalAlias *GA) {
1453 if (GA->isMaterializable())
1454 Out << "; Materializable\n";
1456 // Don't crash when dumping partially built GA
1458 Out << "<<nameless>> = ";
1460 PrintLLVMName(Out, GA);
1463 PrintVisibility(GA->getVisibility(), Out);
1467 PrintLinkage(GA->getLinkage(), Out);
1469 const Constant *Aliasee = GA->getAliasee();
1471 if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(Aliasee)) {
1472 TypePrinter.print(GV->getType(), Out);
1474 PrintLLVMName(Out, GV);
1475 } else if (const Function *F = dyn_cast<Function>(Aliasee)) {
1476 TypePrinter.print(F->getFunctionType(), Out);
1479 WriteAsOperandInternal(Out, F, &TypePrinter, &Machine);
1480 } else if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(Aliasee)) {
1481 TypePrinter.print(GA->getType(), Out);
1483 PrintLLVMName(Out, GA);
1485 const ConstantExpr *CE = cast<ConstantExpr>(Aliasee);
1486 // The only valid GEP is an all zero GEP.
1487 assert((CE->getOpcode() == Instruction::BitCast ||
1488 CE->getOpcode() == Instruction::GetElementPtr) &&
1489 "Unsupported aliasee");
1490 writeOperand(CE, false);
1493 printInfoComment(*GA);
1497 void AssemblyWriter::printTypeSymbolTable(const TypeSymbolTable &ST) {
1498 // Emit all numbered types.
1499 for (unsigned i = 0, e = NumberedTypes.size(); i != e; ++i) {
1500 Out << '%' << i << " = type ";
1502 // Make sure we print out at least one level of the type structure, so
1503 // that we do not get %2 = type %2
1504 TypePrinter.printAtLeastOneLevel(NumberedTypes[i], Out);
1508 // Print the named types.
1509 for (TypeSymbolTable::const_iterator TI = ST.begin(), TE = ST.end();
1511 PrintLLVMName(Out, TI->first, LocalPrefix);
1514 // Make sure we print out at least one level of the type structure, so
1515 // that we do not get %FILE = type %FILE
1516 TypePrinter.printAtLeastOneLevel(TI->second, Out);
1521 /// printFunction - Print all aspects of a function.
1523 void AssemblyWriter::printFunction(const Function *F) {
1524 // Print out the return type and name.
1527 if (AnnotationWriter) AnnotationWriter->emitFunctionAnnot(F, Out);
1529 if (F->isMaterializable())
1530 Out << "; Materializable\n";
1532 if (F->isDeclaration())
1537 PrintLinkage(F->getLinkage(), Out);
1538 PrintVisibility(F->getVisibility(), Out);
1540 // Print the calling convention.
1541 switch (F->getCallingConv()) {
1542 case CallingConv::C: break; // default
1543 case CallingConv::Fast: Out << "fastcc "; break;
1544 case CallingConv::Cold: Out << "coldcc "; break;
1545 case CallingConv::X86_StdCall: Out << "x86_stdcallcc "; break;
1546 case CallingConv::X86_FastCall: Out << "x86_fastcallcc "; break;
1547 case CallingConv::ARM_APCS: Out << "arm_apcscc "; break;
1548 case CallingConv::ARM_AAPCS: Out << "arm_aapcscc "; break;
1549 case CallingConv::ARM_AAPCS_VFP:Out << "arm_aapcs_vfpcc "; break;
1550 case CallingConv::MSP430_INTR: Out << "msp430_intrcc "; break;
1551 default: Out << "cc" << F->getCallingConv() << " "; break;
1554 const FunctionType *FT = F->getFunctionType();
1555 const AttrListPtr &Attrs = F->getAttributes();
1556 Attributes RetAttrs = Attrs.getRetAttributes();
1557 if (RetAttrs != Attribute::None)
1558 Out << Attribute::getAsString(Attrs.getRetAttributes()) << ' ';
1559 TypePrinter.print(F->getReturnType(), Out);
1561 WriteAsOperandInternal(Out, F, &TypePrinter, &Machine);
1563 Machine.incorporateFunction(F);
1565 // Loop over the arguments, printing them...
1568 if (!F->isDeclaration()) {
1569 // If this isn't a declaration, print the argument names as well.
1570 for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
1572 // Insert commas as we go... the first arg doesn't get a comma
1573 if (I != F->arg_begin()) Out << ", ";
1574 printArgument(I, Attrs.getParamAttributes(Idx));
1578 // Otherwise, print the types from the function type.
1579 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
1580 // Insert commas as we go... the first arg doesn't get a comma
1584 TypePrinter.print(FT->getParamType(i), Out);
1586 Attributes ArgAttrs = Attrs.getParamAttributes(i+1);
1587 if (ArgAttrs != Attribute::None)
1588 Out << ' ' << Attribute::getAsString(ArgAttrs);
1592 // Finish printing arguments...
1593 if (FT->isVarArg()) {
1594 if (FT->getNumParams()) Out << ", ";
1595 Out << "..."; // Output varargs portion of signature!
1598 Attributes FnAttrs = Attrs.getFnAttributes();
1599 if (FnAttrs != Attribute::None)
1600 Out << ' ' << Attribute::getAsString(Attrs.getFnAttributes());
1601 if (F->hasSection())
1602 Out << " section \"" << F->getSection() << '"';
1603 if (F->getAlignment())
1604 Out << " align " << F->getAlignment();
1606 Out << " gc \"" << F->getGC() << '"';
1607 if (F->isDeclaration()) {
1612 // Output all of its basic blocks... for the function
1613 for (Function::const_iterator I = F->begin(), E = F->end(); I != E; ++I)
1619 Machine.purgeFunction();
1622 /// printArgument - This member is called for every argument that is passed into
1623 /// the function. Simply print it out
1625 void AssemblyWriter::printArgument(const Argument *Arg,
1628 TypePrinter.print(Arg->getType(), Out);
1630 // Output parameter attributes list
1631 if (Attrs != Attribute::None)
1632 Out << ' ' << Attribute::getAsString(Attrs);
1634 // Output name, if available...
1635 if (Arg->hasName()) {
1637 PrintLLVMName(Out, Arg);
1641 /// printBasicBlock - This member is called for each basic block in a method.
1643 void AssemblyWriter::printBasicBlock(const BasicBlock *BB) {
1644 if (BB->hasName()) { // Print out the label if it exists...
1646 PrintLLVMName(Out, BB->getName(), LabelPrefix);
1648 } else if (!BB->use_empty()) { // Don't print block # of no uses...
1649 Out << "\n; <label>:";
1650 int Slot = Machine.getLocalSlot(BB);
1657 if (BB->getParent() == 0) {
1658 Out.PadToColumn(50);
1659 Out << "; Error: Block without parent!";
1660 } else if (BB != &BB->getParent()->getEntryBlock()) { // Not the entry block?
1661 // Output predecessors for the block...
1662 Out.PadToColumn(50);
1664 pred_const_iterator PI = pred_begin(BB), PE = pred_end(BB);
1667 Out << " No predecessors!";
1670 writeOperand(*PI, false);
1671 for (++PI; PI != PE; ++PI) {
1673 writeOperand(*PI, false);
1680 if (AnnotationWriter) AnnotationWriter->emitBasicBlockStartAnnot(BB, Out);
1682 // Output all of the instructions in the basic block...
1683 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I != E; ++I) {
1684 printInstruction(*I);
1688 if (AnnotationWriter) AnnotationWriter->emitBasicBlockEndAnnot(BB, Out);
1691 /// printInfoComment - Print a little comment after the instruction indicating
1692 /// which slot it occupies.
1694 void AssemblyWriter::printInfoComment(const Value &V) {
1695 if (AnnotationWriter) {
1696 AnnotationWriter->printInfoComment(V, Out);
1700 if (V.getType()->isVoidTy()) return;
1702 Out.PadToColumn(50);
1704 TypePrinter.print(V.getType(), Out);
1705 Out << "> [#uses=" << V.getNumUses() << ']'; // Output # uses
1708 // This member is called for each Instruction in a function..
1709 void AssemblyWriter::printInstruction(const Instruction &I) {
1710 if (AnnotationWriter) AnnotationWriter->emitInstructionAnnot(&I, Out);
1712 // Print out indentation for an instruction.
1715 // Print out name if it exists...
1717 PrintLLVMName(Out, &I);
1719 } else if (!I.getType()->isVoidTy()) {
1720 // Print out the def slot taken.
1721 int SlotNum = Machine.getLocalSlot(&I);
1723 Out << "<badref> = ";
1725 Out << '%' << SlotNum << " = ";
1728 // If this is a volatile load or store, print out the volatile marker.
1729 if ((isa<LoadInst>(I) && cast<LoadInst>(I).isVolatile()) ||
1730 (isa<StoreInst>(I) && cast<StoreInst>(I).isVolatile())) {
1732 } else if (isa<CallInst>(I) && cast<CallInst>(I).isTailCall()) {
1733 // If this is a call, check if it's a tail call.
1737 // Print out the opcode...
1738 Out << I.getOpcodeName();
1740 // Print out optimization information.
1741 WriteOptimizationInfo(Out, &I);
1743 // Print out the compare instruction predicates
1744 if (const CmpInst *CI = dyn_cast<CmpInst>(&I))
1745 Out << ' ' << getPredicateText(CI->getPredicate());
1747 // Print out the type of the operands...
1748 const Value *Operand = I.getNumOperands() ? I.getOperand(0) : 0;
1750 // Special case conditional branches to swizzle the condition out to the front
1751 if (isa<BranchInst>(I) && cast<BranchInst>(I).isConditional()) {
1752 BranchInst &BI(cast<BranchInst>(I));
1754 writeOperand(BI.getCondition(), true);
1756 writeOperand(BI.getSuccessor(0), true);
1758 writeOperand(BI.getSuccessor(1), true);
1760 } else if (isa<SwitchInst>(I)) {
1761 // Special case switch instruction to get formatting nice and correct.
1763 writeOperand(Operand , true);
1765 writeOperand(I.getOperand(1), true);
1768 for (unsigned op = 2, Eop = I.getNumOperands(); op < Eop; op += 2) {
1770 writeOperand(I.getOperand(op ), true);
1772 writeOperand(I.getOperand(op+1), true);
1775 } else if (isa<IndirectBrInst>(I)) {
1776 // Special case indirectbr instruction to get formatting nice and correct.
1778 writeOperand(Operand, true);
1781 for (unsigned i = 1, e = I.getNumOperands(); i != e; ++i) {
1784 writeOperand(I.getOperand(i), true);
1787 } else if (isa<PHINode>(I)) {
1789 TypePrinter.print(I.getType(), Out);
1792 for (unsigned op = 0, Eop = I.getNumOperands(); op < Eop; op += 2) {
1793 if (op) Out << ", ";
1795 writeOperand(I.getOperand(op ), false); Out << ", ";
1796 writeOperand(I.getOperand(op+1), false); Out << " ]";
1798 } else if (const ExtractValueInst *EVI = dyn_cast<ExtractValueInst>(&I)) {
1800 writeOperand(I.getOperand(0), true);
1801 for (const unsigned *i = EVI->idx_begin(), *e = EVI->idx_end(); i != e; ++i)
1803 } else if (const InsertValueInst *IVI = dyn_cast<InsertValueInst>(&I)) {
1805 writeOperand(I.getOperand(0), true); Out << ", ";
1806 writeOperand(I.getOperand(1), true);
1807 for (const unsigned *i = IVI->idx_begin(), *e = IVI->idx_end(); i != e; ++i)
1809 } else if (isa<ReturnInst>(I) && !Operand) {
1811 } else if (const CallInst *CI = dyn_cast<CallInst>(&I)) {
1812 // Print the calling convention being used.
1813 switch (CI->getCallingConv()) {
1814 case CallingConv::C: break; // default
1815 case CallingConv::Fast: Out << " fastcc"; break;
1816 case CallingConv::Cold: Out << " coldcc"; break;
1817 case CallingConv::X86_StdCall: Out << " x86_stdcallcc"; break;
1818 case CallingConv::X86_FastCall: Out << " x86_fastcallcc"; break;
1819 case CallingConv::ARM_APCS: Out << " arm_apcscc "; break;
1820 case CallingConv::ARM_AAPCS: Out << " arm_aapcscc "; break;
1821 case CallingConv::ARM_AAPCS_VFP:Out << " arm_aapcs_vfpcc "; break;
1822 case CallingConv::MSP430_INTR: Out << " msp430_intrcc "; break;
1823 default: Out << " cc" << CI->getCallingConv(); break;
1826 const PointerType *PTy = cast<PointerType>(Operand->getType());
1827 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
1828 const Type *RetTy = FTy->getReturnType();
1829 const AttrListPtr &PAL = CI->getAttributes();
1831 if (PAL.getRetAttributes() != Attribute::None)
1832 Out << ' ' << Attribute::getAsString(PAL.getRetAttributes());
1834 // If possible, print out the short form of the call instruction. We can
1835 // only do this if the first argument is a pointer to a nonvararg function,
1836 // and if the return type is not a pointer to a function.
1839 if (!FTy->isVarArg() &&
1840 (!isa<PointerType>(RetTy) ||
1841 !isa<FunctionType>(cast<PointerType>(RetTy)->getElementType()))) {
1842 TypePrinter.print(RetTy, Out);
1844 writeOperand(Operand, false);
1846 writeOperand(Operand, true);
1849 for (unsigned op = 1, Eop = I.getNumOperands(); op < Eop; ++op) {
1852 writeParamOperand(I.getOperand(op), PAL.getParamAttributes(op));
1855 if (PAL.getFnAttributes() != Attribute::None)
1856 Out << ' ' << Attribute::getAsString(PAL.getFnAttributes());
1857 } else if (const InvokeInst *II = dyn_cast<InvokeInst>(&I)) {
1858 const PointerType *PTy = cast<PointerType>(Operand->getType());
1859 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
1860 const Type *RetTy = FTy->getReturnType();
1861 const AttrListPtr &PAL = II->getAttributes();
1863 // Print the calling convention being used.
1864 switch (II->getCallingConv()) {
1865 case CallingConv::C: break; // default
1866 case CallingConv::Fast: Out << " fastcc"; break;
1867 case CallingConv::Cold: Out << " coldcc"; break;
1868 case CallingConv::X86_StdCall: Out << " x86_stdcallcc"; break;
1869 case CallingConv::X86_FastCall: Out << " x86_fastcallcc"; break;
1870 case CallingConv::ARM_APCS: Out << " arm_apcscc "; break;
1871 case CallingConv::ARM_AAPCS: Out << " arm_aapcscc "; break;
1872 case CallingConv::ARM_AAPCS_VFP:Out << " arm_aapcs_vfpcc "; break;
1873 case CallingConv::MSP430_INTR: Out << " msp430_intrcc "; break;
1874 default: Out << " cc" << II->getCallingConv(); break;
1877 if (PAL.getRetAttributes() != Attribute::None)
1878 Out << ' ' << Attribute::getAsString(PAL.getRetAttributes());
1880 // If possible, print out the short form of the invoke instruction. We can
1881 // only do this if the first argument is a pointer to a nonvararg function,
1882 // and if the return type is not a pointer to a function.
1885 if (!FTy->isVarArg() &&
1886 (!isa<PointerType>(RetTy) ||
1887 !isa<FunctionType>(cast<PointerType>(RetTy)->getElementType()))) {
1888 TypePrinter.print(RetTy, Out);
1890 writeOperand(Operand, false);
1892 writeOperand(Operand, true);
1895 for (unsigned op = 3, Eop = I.getNumOperands(); op < Eop; ++op) {
1898 writeParamOperand(I.getOperand(op), PAL.getParamAttributes(op-2));
1902 if (PAL.getFnAttributes() != Attribute::None)
1903 Out << ' ' << Attribute::getAsString(PAL.getFnAttributes());
1906 writeOperand(II->getNormalDest(), true);
1908 writeOperand(II->getUnwindDest(), true);
1910 } else if (const AllocaInst *AI = dyn_cast<AllocaInst>(&I)) {
1912 TypePrinter.print(AI->getType()->getElementType(), Out);
1913 if (!AI->getArraySize() || AI->isArrayAllocation()) {
1915 writeOperand(AI->getArraySize(), true);
1917 if (AI->getAlignment()) {
1918 Out << ", align " << AI->getAlignment();
1920 } else if (isa<CastInst>(I)) {
1923 writeOperand(Operand, true); // Work with broken code
1926 TypePrinter.print(I.getType(), Out);
1927 } else if (isa<VAArgInst>(I)) {
1930 writeOperand(Operand, true); // Work with broken code
1933 TypePrinter.print(I.getType(), Out);
1934 } else if (Operand) { // Print the normal way.
1936 // PrintAllTypes - Instructions who have operands of all the same type
1937 // omit the type from all but the first operand. If the instruction has
1938 // different type operands (for example br), then they are all printed.
1939 bool PrintAllTypes = false;
1940 const Type *TheType = Operand->getType();
1942 // Select, Store and ShuffleVector always print all types.
1943 if (isa<SelectInst>(I) || isa<StoreInst>(I) || isa<ShuffleVectorInst>(I)
1944 || isa<ReturnInst>(I)) {
1945 PrintAllTypes = true;
1947 for (unsigned i = 1, E = I.getNumOperands(); i != E; ++i) {
1948 Operand = I.getOperand(i);
1949 // note that Operand shouldn't be null, but the test helps make dump()
1950 // more tolerant of malformed IR
1951 if (Operand && Operand->getType() != TheType) {
1952 PrintAllTypes = true; // We have differing types! Print them all!
1958 if (!PrintAllTypes) {
1960 TypePrinter.print(TheType, Out);
1964 for (unsigned i = 0, E = I.getNumOperands(); i != E; ++i) {
1966 writeOperand(I.getOperand(i), PrintAllTypes);
1970 // Print post operand alignment for load/store.
1971 if (isa<LoadInst>(I) && cast<LoadInst>(I).getAlignment()) {
1972 Out << ", align " << cast<LoadInst>(I).getAlignment();
1973 } else if (isa<StoreInst>(I) && cast<StoreInst>(I).getAlignment()) {
1974 Out << ", align " << cast<StoreInst>(I).getAlignment();
1977 // Print Metadata info.
1978 if (!MDNames.empty()) {
1979 SmallVector<std::pair<unsigned, MDNode*>, 4> InstMD;
1980 I.getAllMetadata(InstMD);
1981 for (unsigned i = 0, e = InstMD.size(); i != e; ++i)
1982 Out << ", !" << MDNames[InstMD[i].first]
1983 << " !" << Machine.getMetadataSlot(InstMD[i].second);
1985 printInfoComment(I);
1988 static void WriteMDNodeComment(const MDNode *Node,
1989 formatted_raw_ostream &Out) {
1990 if (Node->getNumOperands() < 1)
1992 ConstantInt *CI = dyn_cast_or_null<ConstantInt>(Node->getOperand(0));
1994 unsigned Val = CI->getZExtValue();
1995 unsigned Tag = Val & ~LLVMDebugVersionMask;
1996 if (Val < LLVMDebugVersion)
1999 Out.PadToColumn(50);
2000 if (Tag == dwarf::DW_TAG_auto_variable)
2001 Out << "; [ DW_TAG_auto_variable ]";
2002 else if (Tag == dwarf::DW_TAG_arg_variable)
2003 Out << "; [ DW_TAG_arg_variable ]";
2004 else if (Tag == dwarf::DW_TAG_return_variable)
2005 Out << "; [ DW_TAG_return_variable ]";
2006 else if (Tag == dwarf::DW_TAG_vector_type)
2007 Out << "; [ DW_TAG_vector_type ]";
2008 else if (Tag == dwarf::DW_TAG_user_base)
2009 Out << "; [ DW_TAG_user_base ]";
2010 else if (const char *TagName = dwarf::TagString(Tag))
2011 Out << "; [ " << TagName << " ]";
2014 void AssemblyWriter::writeAllMDNodes() {
2015 SmallVector<const MDNode *, 16> Nodes;
2016 Nodes.resize(Machine.mdn_size());
2017 for (SlotTracker::mdn_iterator I = Machine.mdn_begin(), E = Machine.mdn_end();
2019 Nodes[I->second] = cast<MDNode>(I->first);
2021 for (unsigned i = 0, e = Nodes.size(); i != e; ++i) {
2022 Out << '!' << i << " = metadata ";
2023 printMDNodeBody(Nodes[i]);
2027 void AssemblyWriter::printMDNodeBody(const MDNode *Node) {
2028 WriteMDNodeBodyInternal(Out, Node, &TypePrinter, &Machine);
2029 WriteMDNodeComment(Node, Out);
2033 //===----------------------------------------------------------------------===//
2034 // External Interface declarations
2035 //===----------------------------------------------------------------------===//
2037 void Module::print(raw_ostream &ROS, AssemblyAnnotationWriter *AAW) const {
2038 SlotTracker SlotTable(this);
2039 formatted_raw_ostream OS(ROS);
2040 AssemblyWriter W(OS, SlotTable, this, AAW);
2041 W.printModule(this);
2044 void Type::print(raw_ostream &OS) const {
2046 OS << "<null Type>";
2049 TypePrinting().print(this, OS);
2052 void Value::print(raw_ostream &ROS, AssemblyAnnotationWriter *AAW) const {
2054 ROS << "printing a <null> value\n";
2057 formatted_raw_ostream OS(ROS);
2058 if (const Instruction *I = dyn_cast<Instruction>(this)) {
2059 const Function *F = I->getParent() ? I->getParent()->getParent() : 0;
2060 SlotTracker SlotTable(F);
2061 AssemblyWriter W(OS, SlotTable, getModuleFromVal(I), AAW);
2062 W.printInstruction(*I);
2063 } else if (const BasicBlock *BB = dyn_cast<BasicBlock>(this)) {
2064 SlotTracker SlotTable(BB->getParent());
2065 AssemblyWriter W(OS, SlotTable, getModuleFromVal(BB), AAW);
2066 W.printBasicBlock(BB);
2067 } else if (const GlobalValue *GV = dyn_cast<GlobalValue>(this)) {
2068 SlotTracker SlotTable(GV->getParent());
2069 AssemblyWriter W(OS, SlotTable, GV->getParent(), AAW);
2070 if (const GlobalVariable *V = dyn_cast<GlobalVariable>(GV))
2072 else if (const Function *F = dyn_cast<Function>(GV))
2075 W.printAlias(cast<GlobalAlias>(GV));
2076 } else if (const MDNode *N = dyn_cast<MDNode>(this)) {
2077 const Function *F = N->getFunction();
2078 SlotTracker SlotTable(F);
2079 AssemblyWriter W(OS, SlotTable, F ? getModuleFromVal(F) : 0, AAW);
2080 W.printMDNodeBody(N);
2081 } else if (const NamedMDNode *N = dyn_cast<NamedMDNode>(this)) {
2082 SlotTracker SlotTable(N->getParent());
2083 AssemblyWriter W(OS, SlotTable, N->getParent(), AAW);
2084 W.printNamedMDNode(N);
2085 } else if (const Constant *C = dyn_cast<Constant>(this)) {
2086 TypePrinting TypePrinter;
2087 TypePrinter.print(C->getType(), OS);
2089 WriteConstantInt(OS, C, TypePrinter, 0);
2090 } else if (isa<InlineAsm>(this) || isa<MDString>(this) ||
2091 isa<Argument>(this)) {
2092 WriteAsOperand(OS, this, true, 0);
2094 // Otherwise we don't know what it is. Call the virtual function to
2095 // allow a subclass to print itself.
2100 // Value::printCustom - subclasses should override this to implement printing.
2101 void Value::printCustom(raw_ostream &OS) const {
2102 llvm_unreachable("Unknown value to print out!");
2105 // Value::dump - allow easy printing of Values from the debugger.
2106 void Value::dump() const { print(dbgs()); dbgs() << '\n'; }
2108 // Type::dump - allow easy printing of Types from the debugger.
2109 // This one uses type names from the given context module
2110 void Type::dump(const Module *Context) const {
2111 WriteTypeSymbolic(dbgs(), this, Context);
2115 // Type::dump - allow easy printing of Types from the debugger.
2116 void Type::dump() const { dump(0); }
2118 // Module::dump() - Allow printing of Modules from the debugger.
2119 void Module::dump() const { print(dbgs(), 0); }