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/LLVMContext.h"
21 #include "llvm/CallingConv.h"
22 #include "llvm/Constants.h"
23 #include "llvm/DerivedTypes.h"
24 #include "llvm/InlineAsm.h"
25 #include "llvm/IntrinsicInst.h"
26 #include "llvm/Operator.h"
27 #include "llvm/Module.h"
28 #include "llvm/ValueSymbolTable.h"
29 #include "llvm/TypeSymbolTable.h"
30 #include "llvm/ADT/DenseSet.h"
31 #include "llvm/ADT/SmallString.h"
32 #include "llvm/ADT/StringExtras.h"
33 #include "llvm/ADT/STLExtras.h"
34 #include "llvm/Support/CFG.h"
35 #include "llvm/Support/Debug.h"
36 #include "llvm/Support/Dwarf.h"
37 #include "llvm/Support/ErrorHandling.h"
38 #include "llvm/Support/MathExtras.h"
39 #include "llvm/Support/FormattedStream.h"
45 // Make virtual table appear in this compilation unit.
46 AssemblyAnnotationWriter::~AssemblyAnnotationWriter() {}
48 //===----------------------------------------------------------------------===//
50 //===----------------------------------------------------------------------===//
52 static const Module *getModuleFromVal(const Value *V) {
53 if (const Argument *MA = dyn_cast<Argument>(V))
54 return MA->getParent() ? MA->getParent()->getParent() : 0;
56 if (const BasicBlock *BB = dyn_cast<BasicBlock>(V))
57 return BB->getParent() ? BB->getParent()->getParent() : 0;
59 if (const Instruction *I = dyn_cast<Instruction>(V)) {
60 const Function *M = I->getParent() ? I->getParent()->getParent() : 0;
61 return M ? M->getParent() : 0;
64 if (const GlobalValue *GV = dyn_cast<GlobalValue>(V))
65 return GV->getParent();
66 if (const NamedMDNode *NMD = dyn_cast<NamedMDNode>(V))
67 return NMD->getParent();
71 // PrintEscapedString - Print each character of the specified string, escaping
72 // it if it is not printable or if it is an escape char.
73 static void PrintEscapedString(StringRef Name, raw_ostream &Out) {
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) {
233 CalcTypeName(*I, TypeStack, OS);
234 if (next(I) == STy->element_end())
244 case Type::UnionTyID: {
245 const UnionType *UTy = cast<UnionType>(Ty);
247 for (StructType::element_iterator I = UTy->element_begin(),
248 E = UTy->element_end(); I != E; ++I) {
250 CalcTypeName(*I, TypeStack, OS);
251 if (next(I) == UTy->element_end())
259 case Type::PointerTyID: {
260 const PointerType *PTy = cast<PointerType>(Ty);
261 CalcTypeName(PTy->getElementType(), TypeStack, OS);
262 if (unsigned AddressSpace = PTy->getAddressSpace())
263 OS << " addrspace(" << AddressSpace << ')';
267 case Type::ArrayTyID: {
268 const ArrayType *ATy = cast<ArrayType>(Ty);
269 OS << '[' << ATy->getNumElements() << " x ";
270 CalcTypeName(ATy->getElementType(), TypeStack, OS);
274 case Type::VectorTyID: {
275 const VectorType *PTy = cast<VectorType>(Ty);
276 OS << "<" << PTy->getNumElements() << " x ";
277 CalcTypeName(PTy->getElementType(), TypeStack, OS);
281 case Type::OpaqueTyID:
285 OS << "<unrecognized-type>";
289 TypeStack.pop_back(); // Remove self from stack.
292 /// printTypeInt - The internal guts of printing out a type that has a
293 /// potentially named portion.
295 void TypePrinting::print(const Type *Ty, raw_ostream &OS,
296 bool IgnoreTopLevelName) {
297 // Check to see if the type is named.
298 DenseMap<const Type*, std::string> &TM = getTypeNamesMap(TypeNames);
299 if (!IgnoreTopLevelName) {
300 DenseMap<const Type*, std::string>::iterator I = TM.find(Ty);
307 // Otherwise we have a type that has not been named but is a derived type.
308 // Carefully recurse the type hierarchy to print out any contained symbolic
310 SmallVector<const Type *, 16> TypeStack;
311 std::string TypeName;
313 raw_string_ostream TypeOS(TypeName);
314 CalcTypeName(Ty, TypeStack, TypeOS, IgnoreTopLevelName);
317 // Cache type name for later use.
318 if (!IgnoreTopLevelName)
319 TM.insert(std::make_pair(Ty, TypeOS.str()));
324 // To avoid walking constant expressions multiple times and other IR
325 // objects, we keep several helper maps.
326 DenseSet<const Value*> VisitedConstants;
327 DenseSet<const Type*> VisitedTypes;
330 std::vector<const Type*> &NumberedTypes;
332 TypeFinder(TypePrinting &tp, std::vector<const Type*> &numberedTypes)
333 : TP(tp), NumberedTypes(numberedTypes) {}
335 void Run(const Module &M) {
336 // Get types from the type symbol table. This gets opaque types referened
337 // only through derived named types.
338 const TypeSymbolTable &ST = M.getTypeSymbolTable();
339 for (TypeSymbolTable::const_iterator TI = ST.begin(), E = ST.end();
341 IncorporateType(TI->second);
343 // Get types from global variables.
344 for (Module::const_global_iterator I = M.global_begin(),
345 E = M.global_end(); I != E; ++I) {
346 IncorporateType(I->getType());
347 if (I->hasInitializer())
348 IncorporateValue(I->getInitializer());
351 // Get types from aliases.
352 for (Module::const_alias_iterator I = M.alias_begin(),
353 E = M.alias_end(); I != E; ++I) {
354 IncorporateType(I->getType());
355 IncorporateValue(I->getAliasee());
358 // Get types from functions.
359 for (Module::const_iterator FI = M.begin(), E = M.end(); FI != E; ++FI) {
360 IncorporateType(FI->getType());
362 for (Function::const_iterator BB = FI->begin(), E = FI->end();
364 for (BasicBlock::const_iterator II = BB->begin(),
365 E = BB->end(); II != E; ++II) {
366 const Instruction &I = *II;
367 // Incorporate the type of the instruction and all its operands.
368 IncorporateType(I.getType());
369 for (User::const_op_iterator OI = I.op_begin(), OE = I.op_end();
371 IncorporateValue(*OI);
377 void IncorporateType(const Type *Ty) {
378 // Check to see if we're already visited this type.
379 if (!VisitedTypes.insert(Ty).second)
382 // If this is a structure or opaque type, add a name for the type.
383 if (((Ty->isStructTy() && cast<StructType>(Ty)->getNumElements())
384 || Ty->isOpaqueTy()) && !TP.hasTypeName(Ty)) {
385 TP.addTypeName(Ty, "%"+utostr(unsigned(NumberedTypes.size())));
386 NumberedTypes.push_back(Ty);
389 // Recursively walk all contained types.
390 for (Type::subtype_iterator I = Ty->subtype_begin(),
391 E = Ty->subtype_end(); I != E; ++I)
395 /// IncorporateValue - This method is used to walk operand lists finding
396 /// types hiding in constant expressions and other operands that won't be
397 /// walked in other ways. GlobalValues, basic blocks, instructions, and
398 /// inst operands are all explicitly enumerated.
399 void IncorporateValue(const Value *V) {
400 if (V == 0 || !isa<Constant>(V) || isa<GlobalValue>(V)) return;
403 if (!VisitedConstants.insert(V).second)
407 IncorporateType(V->getType());
409 // Look in operands for types.
410 const Constant *C = cast<Constant>(V);
411 for (Constant::const_op_iterator I = C->op_begin(),
412 E = C->op_end(); I != E;++I)
413 IncorporateValue(*I);
416 } // end anonymous namespace
419 /// AddModuleTypesToPrinter - Add all of the symbolic type names for types in
420 /// the specified module to the TypePrinter and all numbered types to it and the
421 /// NumberedTypes table.
422 static void AddModuleTypesToPrinter(TypePrinting &TP,
423 std::vector<const Type*> &NumberedTypes,
427 // If the module has a symbol table, take all global types and stuff their
428 // names into the TypeNames map.
429 const TypeSymbolTable &ST = M->getTypeSymbolTable();
430 for (TypeSymbolTable::const_iterator TI = ST.begin(), E = ST.end();
432 const Type *Ty = cast<Type>(TI->second);
434 // As a heuristic, don't insert pointer to primitive types, because
435 // they are used too often to have a single useful name.
436 if (const PointerType *PTy = dyn_cast<PointerType>(Ty)) {
437 const Type *PETy = PTy->getElementType();
438 if ((PETy->isPrimitiveType() || PETy->isIntegerTy()) &&
443 // Likewise don't insert primitives either.
444 if (Ty->isIntegerTy() || Ty->isPrimitiveType())
447 // Get the name as a string and insert it into TypeNames.
449 raw_string_ostream NameROS(NameStr);
450 formatted_raw_ostream NameOS(NameROS);
451 PrintLLVMName(NameOS, TI->first, LocalPrefix);
453 TP.addTypeName(Ty, NameStr);
456 // Walk the entire module to find references to unnamed structure and opaque
457 // types. This is required for correctness by opaque types (because multiple
458 // uses of an unnamed opaque type needs to be referred to by the same ID) and
459 // it shrinks complex recursive structure types substantially in some cases.
460 TypeFinder(TP, NumberedTypes).Run(*M);
464 /// WriteTypeSymbolic - This attempts to write the specified type as a symbolic
465 /// type, iff there is an entry in the modules symbol table for the specified
466 /// type or one of it's component types.
468 void llvm::WriteTypeSymbolic(raw_ostream &OS, const Type *Ty, const Module *M) {
469 TypePrinting Printer;
470 std::vector<const Type*> NumberedTypes;
471 AddModuleTypesToPrinter(Printer, NumberedTypes, M);
472 Printer.print(Ty, OS);
475 //===----------------------------------------------------------------------===//
476 // SlotTracker Class: Enumerate slot numbers for unnamed values
477 //===----------------------------------------------------------------------===//
481 /// This class provides computation of slot numbers for LLVM Assembly writing.
485 /// ValueMap - A mapping of Values to slot numbers.
486 typedef DenseMap<const Value*, unsigned> ValueMap;
489 /// TheModule - The module for which we are holding slot numbers.
490 const Module* TheModule;
492 /// TheFunction - The function for which we are holding slot numbers.
493 const Function* TheFunction;
494 bool FunctionProcessed;
496 /// mMap - The TypePlanes map for the module level data.
500 /// fMap - The TypePlanes map for the function level data.
504 /// mdnMap - Map for MDNodes.
505 DenseMap<const MDNode*, unsigned> mdnMap;
508 /// Construct from a module
509 explicit SlotTracker(const Module *M);
510 /// Construct from a function, starting out in incorp state.
511 explicit SlotTracker(const Function *F);
513 /// Return the slot number of the specified value in it's type
514 /// plane. If something is not in the SlotTracker, return -1.
515 int getLocalSlot(const Value *V);
516 int getGlobalSlot(const GlobalValue *V);
517 int getMetadataSlot(const MDNode *N);
519 /// If you'd like to deal with a function instead of just a module, use
520 /// this method to get its data into the SlotTracker.
521 void incorporateFunction(const Function *F) {
523 FunctionProcessed = false;
526 /// After calling incorporateFunction, use this method to remove the
527 /// most recently incorporated function from the SlotTracker. This
528 /// will reset the state of the machine back to just the module contents.
529 void purgeFunction();
531 /// MDNode map iterators.
532 typedef DenseMap<const MDNode*, unsigned>::iterator mdn_iterator;
533 mdn_iterator mdn_begin() { return mdnMap.begin(); }
534 mdn_iterator mdn_end() { return mdnMap.end(); }
535 unsigned mdn_size() const { return mdnMap.size(); }
536 bool mdn_empty() const { return mdnMap.empty(); }
538 /// This function does the actual initialization.
539 inline void initialize();
541 // Implementation Details
543 /// CreateModuleSlot - Insert the specified GlobalValue* into the slot table.
544 void CreateModuleSlot(const GlobalValue *V);
546 /// CreateMetadataSlot - Insert the specified MDNode* into the slot table.
547 void CreateMetadataSlot(const MDNode *N);
549 /// CreateFunctionSlot - Insert the specified Value* into the slot table.
550 void CreateFunctionSlot(const Value *V);
552 /// Add all of the module level global variables (and their initializers)
553 /// and function declarations, but not the contents of those functions.
554 void processModule();
556 /// Add all of the functions arguments, basic blocks, and instructions.
557 void processFunction();
559 SlotTracker(const SlotTracker &); // DO NOT IMPLEMENT
560 void operator=(const SlotTracker &); // DO NOT IMPLEMENT
563 } // end anonymous namespace
566 static SlotTracker *createSlotTracker(const Value *V) {
567 if (const Argument *FA = dyn_cast<Argument>(V))
568 return new SlotTracker(FA->getParent());
570 if (const Instruction *I = dyn_cast<Instruction>(V))
571 return new SlotTracker(I->getParent()->getParent());
573 if (const BasicBlock *BB = dyn_cast<BasicBlock>(V))
574 return new SlotTracker(BB->getParent());
576 if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(V))
577 return new SlotTracker(GV->getParent());
579 if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(V))
580 return new SlotTracker(GA->getParent());
582 if (const Function *Func = dyn_cast<Function>(V))
583 return new SlotTracker(Func);
586 return new SlotTracker((Function *)0);
592 #define ST_DEBUG(X) dbgs() << X
597 // Module level constructor. Causes the contents of the Module (sans functions)
598 // to be added to the slot table.
599 SlotTracker::SlotTracker(const Module *M)
600 : TheModule(M), TheFunction(0), FunctionProcessed(false),
601 mNext(0), fNext(0), mdnNext(0) {
604 // Function level constructor. Causes the contents of the Module and the one
605 // function provided to be added to the slot table.
606 SlotTracker::SlotTracker(const Function *F)
607 : TheModule(F ? F->getParent() : 0), TheFunction(F), FunctionProcessed(false),
608 mNext(0), fNext(0), mdnNext(0) {
611 inline void SlotTracker::initialize() {
614 TheModule = 0; ///< Prevent re-processing next time we're called.
617 if (TheFunction && !FunctionProcessed)
621 // Iterate through all the global variables, functions, and global
622 // variable initializers and create slots for them.
623 void SlotTracker::processModule() {
624 ST_DEBUG("begin processModule!\n");
626 // Add all of the unnamed global variables to the value table.
627 for (Module::const_global_iterator I = TheModule->global_begin(),
628 E = TheModule->global_end(); I != E; ++I) {
633 // Add metadata used by named metadata.
634 for (Module::const_named_metadata_iterator
635 I = TheModule->named_metadata_begin(),
636 E = TheModule->named_metadata_end(); I != E; ++I) {
637 const NamedMDNode *NMD = I;
638 for (unsigned i = 0, e = NMD->getNumOperands(); i != e; ++i) {
639 if (MDNode *MD = NMD->getOperand(i))
640 CreateMetadataSlot(MD);
644 // Add all the unnamed functions to the table.
645 for (Module::const_iterator I = TheModule->begin(), E = TheModule->end();
650 ST_DEBUG("end processModule!\n");
653 // Process the arguments, basic blocks, and instructions of a function.
654 void SlotTracker::processFunction() {
655 ST_DEBUG("begin processFunction!\n");
658 // Add all the function arguments with no names.
659 for(Function::const_arg_iterator AI = TheFunction->arg_begin(),
660 AE = TheFunction->arg_end(); AI != AE; ++AI)
662 CreateFunctionSlot(AI);
664 ST_DEBUG("Inserting Instructions:\n");
666 SmallVector<std::pair<unsigned, MDNode*>, 4> MDForInst;
668 // Add all of the basic blocks and instructions with no names.
669 for (Function::const_iterator BB = TheFunction->begin(),
670 E = TheFunction->end(); BB != E; ++BB) {
672 CreateFunctionSlot(BB);
674 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I != E;
676 if (!I->getType()->isVoidTy() && !I->hasName())
677 CreateFunctionSlot(I);
679 // Intrinsics can directly use metadata. We allow direct calls to any
680 // llvm.foo function here, because the target may not be linked into the
682 if (const CallInst *CI = dyn_cast<CallInst>(I)) {
683 if (Function *F = CI->getCalledFunction())
684 if (F->getName().startswith("llvm."))
685 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
686 if (MDNode *N = dyn_cast_or_null<MDNode>(I->getOperand(i)))
687 CreateMetadataSlot(N);
690 // Process metadata attached with this instruction.
691 I->getAllMetadata(MDForInst);
692 for (unsigned i = 0, e = MDForInst.size(); i != e; ++i)
693 CreateMetadataSlot(MDForInst[i].second);
698 FunctionProcessed = true;
700 ST_DEBUG("end processFunction!\n");
703 /// Clean up after incorporating a function. This is the only way to get out of
704 /// the function incorporation state that affects get*Slot/Create*Slot. Function
705 /// incorporation state is indicated by TheFunction != 0.
706 void SlotTracker::purgeFunction() {
707 ST_DEBUG("begin purgeFunction!\n");
708 fMap.clear(); // Simply discard the function level map
710 FunctionProcessed = false;
711 ST_DEBUG("end purgeFunction!\n");
714 /// getGlobalSlot - Get the slot number of a global value.
715 int SlotTracker::getGlobalSlot(const GlobalValue *V) {
716 // Check for uninitialized state and do lazy initialization.
719 // Find the type plane in the module map
720 ValueMap::iterator MI = mMap.find(V);
721 return MI == mMap.end() ? -1 : (int)MI->second;
724 /// getMetadataSlot - Get the slot number of a MDNode.
725 int SlotTracker::getMetadataSlot(const MDNode *N) {
726 // Check for uninitialized state and do lazy initialization.
729 // Find the type plane in the module map
730 mdn_iterator MI = mdnMap.find(N);
731 return MI == mdnMap.end() ? -1 : (int)MI->second;
735 /// getLocalSlot - Get the slot number for a value that is local to a function.
736 int SlotTracker::getLocalSlot(const Value *V) {
737 assert(!isa<Constant>(V) && "Can't get a constant or global slot with this!");
739 // Check for uninitialized state and do lazy initialization.
742 ValueMap::iterator FI = fMap.find(V);
743 return FI == fMap.end() ? -1 : (int)FI->second;
747 /// CreateModuleSlot - Insert the specified GlobalValue* into the slot table.
748 void SlotTracker::CreateModuleSlot(const GlobalValue *V) {
749 assert(V && "Can't insert a null Value into SlotTracker!");
750 assert(!V->getType()->isVoidTy() && "Doesn't need a slot!");
751 assert(!V->hasName() && "Doesn't need a slot!");
753 unsigned DestSlot = mNext++;
756 ST_DEBUG(" Inserting value [" << V->getType() << "] = " << V << " slot=" <<
758 // G = Global, F = Function, A = Alias, o = other
759 ST_DEBUG((isa<GlobalVariable>(V) ? 'G' :
760 (isa<Function>(V) ? 'F' :
761 (isa<GlobalAlias>(V) ? 'A' : 'o'))) << "]\n");
764 /// CreateSlot - Create a new slot for the specified value if it has no name.
765 void SlotTracker::CreateFunctionSlot(const Value *V) {
766 assert(!V->getType()->isVoidTy() && !V->hasName() && "Doesn't need a slot!");
768 unsigned DestSlot = fNext++;
771 // G = Global, F = Function, o = other
772 ST_DEBUG(" Inserting value [" << V->getType() << "] = " << V << " slot=" <<
773 DestSlot << " [o]\n");
776 /// CreateModuleSlot - Insert the specified MDNode* into the slot table.
777 void SlotTracker::CreateMetadataSlot(const MDNode *N) {
778 assert(N && "Can't insert a null Value into SlotTracker!");
780 // Don't insert if N is a function-local metadata, these are always printed
782 if (N->isFunctionLocal())
785 mdn_iterator I = mdnMap.find(N);
786 if (I != mdnMap.end())
789 unsigned DestSlot = mdnNext++;
790 mdnMap[N] = DestSlot;
792 // Recursively add any MDNodes referenced by operands.
793 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
794 if (const MDNode *Op = dyn_cast_or_null<MDNode>(N->getOperand(i)))
795 CreateMetadataSlot(Op);
798 //===----------------------------------------------------------------------===//
799 // AsmWriter Implementation
800 //===----------------------------------------------------------------------===//
802 static void WriteAsOperandInternal(raw_ostream &Out, const Value *V,
803 TypePrinting *TypePrinter,
804 SlotTracker *Machine);
808 static const char *getPredicateText(unsigned predicate) {
809 const char * pred = "unknown";
811 case FCmpInst::FCMP_FALSE: pred = "false"; break;
812 case FCmpInst::FCMP_OEQ: pred = "oeq"; break;
813 case FCmpInst::FCMP_OGT: pred = "ogt"; break;
814 case FCmpInst::FCMP_OGE: pred = "oge"; break;
815 case FCmpInst::FCMP_OLT: pred = "olt"; break;
816 case FCmpInst::FCMP_OLE: pred = "ole"; break;
817 case FCmpInst::FCMP_ONE: pred = "one"; break;
818 case FCmpInst::FCMP_ORD: pred = "ord"; break;
819 case FCmpInst::FCMP_UNO: pred = "uno"; break;
820 case FCmpInst::FCMP_UEQ: pred = "ueq"; break;
821 case FCmpInst::FCMP_UGT: pred = "ugt"; break;
822 case FCmpInst::FCMP_UGE: pred = "uge"; break;
823 case FCmpInst::FCMP_ULT: pred = "ult"; break;
824 case FCmpInst::FCMP_ULE: pred = "ule"; break;
825 case FCmpInst::FCMP_UNE: pred = "une"; break;
826 case FCmpInst::FCMP_TRUE: pred = "true"; break;
827 case ICmpInst::ICMP_EQ: pred = "eq"; break;
828 case ICmpInst::ICMP_NE: pred = "ne"; break;
829 case ICmpInst::ICMP_SGT: pred = "sgt"; break;
830 case ICmpInst::ICMP_SGE: pred = "sge"; break;
831 case ICmpInst::ICMP_SLT: pred = "slt"; break;
832 case ICmpInst::ICMP_SLE: pred = "sle"; break;
833 case ICmpInst::ICMP_UGT: pred = "ugt"; break;
834 case ICmpInst::ICMP_UGE: pred = "uge"; break;
835 case ICmpInst::ICMP_ULT: pred = "ult"; break;
836 case ICmpInst::ICMP_ULE: pred = "ule"; break;
842 static void WriteOptimizationInfo(raw_ostream &Out, const User *U) {
843 if (const OverflowingBinaryOperator *OBO =
844 dyn_cast<OverflowingBinaryOperator>(U)) {
845 if (OBO->hasNoUnsignedWrap())
847 if (OBO->hasNoSignedWrap())
849 } else if (const SDivOperator *Div = dyn_cast<SDivOperator>(U)) {
852 } else if (const GEPOperator *GEP = dyn_cast<GEPOperator>(U)) {
853 if (GEP->isInBounds())
858 static void WriteConstantInternal(raw_ostream &Out, const Constant *CV,
859 TypePrinting &TypePrinter,
860 SlotTracker *Machine) {
861 if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV)) {
862 if (CI->getType()->isIntegerTy(1)) {
863 Out << (CI->getZExtValue() ? "true" : "false");
866 Out << CI->getValue();
870 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CV)) {
871 if (&CFP->getValueAPF().getSemantics() == &APFloat::IEEEdouble ||
872 &CFP->getValueAPF().getSemantics() == &APFloat::IEEEsingle) {
873 // We would like to output the FP constant value in exponential notation,
874 // but we cannot do this if doing so will lose precision. Check here to
875 // make sure that we only output it in exponential format if we can parse
876 // the value back and get the same value.
879 bool isDouble = &CFP->getValueAPF().getSemantics()==&APFloat::IEEEdouble;
880 double Val = isDouble ? CFP->getValueAPF().convertToDouble() :
881 CFP->getValueAPF().convertToFloat();
882 SmallString<128> StrVal;
883 raw_svector_ostream(StrVal) << Val;
885 // Check to make sure that the stringized number is not some string like
886 // "Inf" or NaN, that atof will accept, but the lexer will not. Check
887 // that the string matches the "[-+]?[0-9]" regex.
889 if ((StrVal[0] >= '0' && StrVal[0] <= '9') ||
890 ((StrVal[0] == '-' || StrVal[0] == '+') &&
891 (StrVal[1] >= '0' && StrVal[1] <= '9'))) {
892 // Reparse stringized version!
893 if (atof(StrVal.c_str()) == Val) {
898 // Otherwise we could not reparse it to exactly the same value, so we must
899 // output the string in hexadecimal format! Note that loading and storing
900 // floating point types changes the bits of NaNs on some hosts, notably
901 // x86, so we must not use these types.
902 assert(sizeof(double) == sizeof(uint64_t) &&
903 "assuming that double is 64 bits!");
905 APFloat apf = CFP->getValueAPF();
906 // Floats are represented in ASCII IR as double, convert.
908 apf.convert(APFloat::IEEEdouble, APFloat::rmNearestTiesToEven,
911 utohex_buffer(uint64_t(apf.bitcastToAPInt().getZExtValue()),
916 // Some form of long double. These appear as a magic letter identifying
917 // the type, then a fixed number of hex digits.
919 if (&CFP->getValueAPF().getSemantics() == &APFloat::x87DoubleExtended) {
921 // api needed to prevent premature destruction
922 APInt api = CFP->getValueAPF().bitcastToAPInt();
923 const uint64_t* p = api.getRawData();
924 uint64_t word = p[1];
926 int width = api.getBitWidth();
927 for (int j=0; j<width; j+=4, shiftcount-=4) {
928 unsigned int nibble = (word>>shiftcount) & 15;
930 Out << (unsigned char)(nibble + '0');
932 Out << (unsigned char)(nibble - 10 + 'A');
933 if (shiftcount == 0 && j+4 < width) {
937 shiftcount = width-j-4;
941 } else if (&CFP->getValueAPF().getSemantics() == &APFloat::IEEEquad)
943 else if (&CFP->getValueAPF().getSemantics() == &APFloat::PPCDoubleDouble)
946 llvm_unreachable("Unsupported floating point type");
947 // api needed to prevent premature destruction
948 APInt api = CFP->getValueAPF().bitcastToAPInt();
949 const uint64_t* p = api.getRawData();
952 int width = api.getBitWidth();
953 for (int j=0; j<width; j+=4, shiftcount-=4) {
954 unsigned int nibble = (word>>shiftcount) & 15;
956 Out << (unsigned char)(nibble + '0');
958 Out << (unsigned char)(nibble - 10 + 'A');
959 if (shiftcount == 0 && j+4 < width) {
963 shiftcount = width-j-4;
969 if (isa<ConstantAggregateZero>(CV)) {
970 Out << "zeroinitializer";
974 if (const BlockAddress *BA = dyn_cast<BlockAddress>(CV)) {
975 Out << "blockaddress(";
976 WriteAsOperandInternal(Out, BA->getFunction(), &TypePrinter, Machine);
978 WriteAsOperandInternal(Out, BA->getBasicBlock(), &TypePrinter, Machine);
983 if (const ConstantArray *CA = dyn_cast<ConstantArray>(CV)) {
984 // As a special case, print the array as a string if it is an array of
985 // i8 with ConstantInt values.
987 const Type *ETy = CA->getType()->getElementType();
988 if (CA->isString()) {
990 PrintEscapedString(CA->getAsString(), Out);
992 } else { // Cannot output in string format...
994 if (CA->getNumOperands()) {
995 TypePrinter.print(ETy, Out);
997 WriteAsOperandInternal(Out, CA->getOperand(0),
998 &TypePrinter, Machine);
999 for (unsigned i = 1, e = CA->getNumOperands(); i != e; ++i) {
1001 TypePrinter.print(ETy, Out);
1003 WriteAsOperandInternal(Out, CA->getOperand(i), &TypePrinter, Machine);
1011 if (const ConstantStruct *CS = dyn_cast<ConstantStruct>(CV)) {
1012 if (CS->getType()->isPacked())
1015 unsigned N = CS->getNumOperands();
1018 TypePrinter.print(CS->getOperand(0)->getType(), Out);
1021 WriteAsOperandInternal(Out, CS->getOperand(0), &TypePrinter, Machine);
1023 for (unsigned i = 1; i < N; i++) {
1025 TypePrinter.print(CS->getOperand(i)->getType(), Out);
1028 WriteAsOperandInternal(Out, CS->getOperand(i), &TypePrinter, Machine);
1034 if (CS->getType()->isPacked())
1039 if (const ConstantUnion *CU = dyn_cast<ConstantUnion>(CV)) {
1041 TypePrinter.print(CU->getOperand(0)->getType(), Out);
1043 WriteAsOperandInternal(Out, CU->getOperand(0), &TypePrinter, Machine);
1048 if (const ConstantVector *CP = dyn_cast<ConstantVector>(CV)) {
1049 const Type *ETy = CP->getType()->getElementType();
1050 assert(CP->getNumOperands() > 0 &&
1051 "Number of operands for a PackedConst must be > 0");
1053 TypePrinter.print(ETy, Out);
1055 WriteAsOperandInternal(Out, CP->getOperand(0), &TypePrinter, Machine);
1056 for (unsigned i = 1, e = CP->getNumOperands(); i != e; ++i) {
1058 TypePrinter.print(ETy, Out);
1060 WriteAsOperandInternal(Out, CP->getOperand(i), &TypePrinter, Machine);
1066 if (isa<ConstantPointerNull>(CV)) {
1071 if (isa<UndefValue>(CV)) {
1076 if (const MDNode *Node = dyn_cast<MDNode>(CV)) {
1077 Out << "!" << Machine->getMetadataSlot(Node);
1081 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV)) {
1082 Out << CE->getOpcodeName();
1083 WriteOptimizationInfo(Out, CE);
1084 if (CE->isCompare())
1085 Out << ' ' << getPredicateText(CE->getPredicate());
1088 for (User::const_op_iterator OI=CE->op_begin(); OI != CE->op_end(); ++OI) {
1089 TypePrinter.print((*OI)->getType(), Out);
1091 WriteAsOperandInternal(Out, *OI, &TypePrinter, Machine);
1092 if (OI+1 != CE->op_end())
1096 if (CE->hasIndices()) {
1097 const SmallVector<unsigned, 4> &Indices = CE->getIndices();
1098 for (unsigned i = 0, e = Indices.size(); i != e; ++i)
1099 Out << ", " << Indices[i];
1104 TypePrinter.print(CE->getType(), Out);
1111 Out << "<placeholder or erroneous Constant>";
1114 static void WriteMDNodeBodyInternal(raw_ostream &Out, const MDNode *Node,
1115 TypePrinting *TypePrinter,
1116 SlotTracker *Machine) {
1118 for (unsigned mi = 0, me = Node->getNumOperands(); mi != me; ++mi) {
1119 const Value *V = Node->getOperand(mi);
1123 TypePrinter->print(V->getType(), Out);
1125 WriteAsOperandInternal(Out, Node->getOperand(mi),
1126 TypePrinter, Machine);
1136 /// WriteAsOperand - Write the name of the specified value out to the specified
1137 /// ostream. This can be useful when you just want to print int %reg126, not
1138 /// the whole instruction that generated it.
1140 static void WriteAsOperandInternal(raw_ostream &Out, const Value *V,
1141 TypePrinting *TypePrinter,
1142 SlotTracker *Machine) {
1144 PrintLLVMName(Out, V);
1148 const Constant *CV = dyn_cast<Constant>(V);
1149 if (CV && !isa<GlobalValue>(CV)) {
1150 assert(TypePrinter && "Constants require TypePrinting!");
1151 WriteConstantInternal(Out, CV, *TypePrinter, Machine);
1155 if (const InlineAsm *IA = dyn_cast<InlineAsm>(V)) {
1157 if (IA->hasSideEffects())
1158 Out << "sideeffect ";
1159 if (IA->isAlignStack())
1160 Out << "alignstack ";
1162 PrintEscapedString(IA->getAsmString(), Out);
1164 PrintEscapedString(IA->getConstraintString(), Out);
1169 if (const MDNode *N = dyn_cast<MDNode>(V)) {
1170 if (N->isFunctionLocal()) {
1171 // Print metadata inline, not via slot reference number.
1172 WriteMDNodeBodyInternal(Out, N, TypePrinter, Machine);
1177 Machine = createSlotTracker(V);
1178 Out << '!' << Machine->getMetadataSlot(N);
1182 if (const MDString *MDS = dyn_cast<MDString>(V)) {
1184 PrintEscapedString(MDS->getString(), Out);
1189 if (V->getValueID() == Value::PseudoSourceValueVal ||
1190 V->getValueID() == Value::FixedStackPseudoSourceValueVal) {
1198 if (const GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
1199 Slot = Machine->getGlobalSlot(GV);
1202 Slot = Machine->getLocalSlot(V);
1205 Machine = createSlotTracker(V);
1207 if (const GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
1208 Slot = Machine->getGlobalSlot(GV);
1211 Slot = Machine->getLocalSlot(V);
1220 Out << Prefix << Slot;
1225 void llvm::WriteAsOperand(raw_ostream &Out, const Value *V,
1226 bool PrintType, const Module *Context) {
1228 // Fast path: Don't construct and populate a TypePrinting object if we
1229 // won't be needing any types printed.
1231 (!isa<Constant>(V) || V->hasName() || isa<GlobalValue>(V))) {
1232 WriteAsOperandInternal(Out, V, 0, 0);
1236 if (Context == 0) Context = getModuleFromVal(V);
1238 TypePrinting TypePrinter;
1239 std::vector<const Type*> NumberedTypes;
1240 AddModuleTypesToPrinter(TypePrinter, NumberedTypes, Context);
1242 TypePrinter.print(V->getType(), Out);
1246 WriteAsOperandInternal(Out, V, &TypePrinter, 0);
1251 class AssemblyWriter {
1252 formatted_raw_ostream &Out;
1253 SlotTracker &Machine;
1254 const Module *TheModule;
1255 TypePrinting TypePrinter;
1256 AssemblyAnnotationWriter *AnnotationWriter;
1257 std::vector<const Type*> NumberedTypes;
1260 inline AssemblyWriter(formatted_raw_ostream &o, SlotTracker &Mac,
1262 AssemblyAnnotationWriter *AAW)
1263 : Out(o), Machine(Mac), TheModule(M), AnnotationWriter(AAW) {
1264 AddModuleTypesToPrinter(TypePrinter, NumberedTypes, M);
1267 void printMDNodeBody(const MDNode *MD);
1268 void printNamedMDNode(const NamedMDNode *NMD);
1270 void printModule(const Module *M);
1272 void writeOperand(const Value *Op, bool PrintType);
1273 void writeParamOperand(const Value *Operand, Attributes Attrs);
1275 void writeAllMDNodes();
1277 void printTypeSymbolTable(const TypeSymbolTable &ST);
1278 void printGlobal(const GlobalVariable *GV);
1279 void printAlias(const GlobalAlias *GV);
1280 void printFunction(const Function *F);
1281 void printArgument(const Argument *FA, Attributes Attrs);
1282 void printBasicBlock(const BasicBlock *BB);
1283 void printInstruction(const Instruction &I);
1286 // printInfoComment - Print a little comment after the instruction indicating
1287 // which slot it occupies.
1288 void printInfoComment(const Value &V);
1290 } // end of anonymous namespace
1292 void AssemblyWriter::writeOperand(const Value *Operand, bool PrintType) {
1294 Out << "<null operand!>";
1298 TypePrinter.print(Operand->getType(), Out);
1301 WriteAsOperandInternal(Out, Operand, &TypePrinter, &Machine);
1304 void AssemblyWriter::writeParamOperand(const Value *Operand,
1307 Out << "<null operand!>";
1312 TypePrinter.print(Operand->getType(), Out);
1313 // Print parameter attributes list
1314 if (Attrs != Attribute::None)
1315 Out << ' ' << Attribute::getAsString(Attrs);
1317 // Print the operand
1318 WriteAsOperandInternal(Out, Operand, &TypePrinter, &Machine);
1321 void AssemblyWriter::printModule(const Module *M) {
1322 if (!M->getModuleIdentifier().empty() &&
1323 // Don't print the ID if it will start a new line (which would
1324 // require a comment char before it).
1325 M->getModuleIdentifier().find('\n') == std::string::npos)
1326 Out << "; ModuleID = '" << M->getModuleIdentifier() << "'\n";
1328 if (!M->getDataLayout().empty())
1329 Out << "target datalayout = \"" << M->getDataLayout() << "\"\n";
1330 if (!M->getTargetTriple().empty())
1331 Out << "target triple = \"" << M->getTargetTriple() << "\"\n";
1333 if (!M->getModuleInlineAsm().empty()) {
1334 // Split the string into lines, to make it easier to read the .ll file.
1335 std::string Asm = M->getModuleInlineAsm();
1337 size_t NewLine = Asm.find_first_of('\n', CurPos);
1339 while (NewLine != std::string::npos) {
1340 // We found a newline, print the portion of the asm string from the
1341 // last newline up to this newline.
1342 Out << "module asm \"";
1343 PrintEscapedString(std::string(Asm.begin()+CurPos, Asm.begin()+NewLine),
1347 NewLine = Asm.find_first_of('\n', CurPos);
1349 Out << "module asm \"";
1350 PrintEscapedString(std::string(Asm.begin()+CurPos, Asm.end()), Out);
1354 // Loop over the dependent libraries and emit them.
1355 Module::lib_iterator LI = M->lib_begin();
1356 Module::lib_iterator LE = M->lib_end();
1359 Out << "deplibs = [ ";
1361 Out << '"' << *LI << '"';
1369 // Loop over the symbol table, emitting all id'd types.
1370 if (!M->getTypeSymbolTable().empty() || !NumberedTypes.empty()) Out << '\n';
1371 printTypeSymbolTable(M->getTypeSymbolTable());
1373 // Output all globals.
1374 if (!M->global_empty()) Out << '\n';
1375 for (Module::const_global_iterator I = M->global_begin(), E = M->global_end();
1379 // Output all aliases.
1380 if (!M->alias_empty()) Out << "\n";
1381 for (Module::const_alias_iterator I = M->alias_begin(), E = M->alias_end();
1385 // Output all of the functions.
1386 for (Module::const_iterator I = M->begin(), E = M->end(); I != E; ++I)
1389 // Output named metadata.
1390 if (!M->named_metadata_empty()) Out << '\n';
1392 for (Module::const_named_metadata_iterator I = M->named_metadata_begin(),
1393 E = M->named_metadata_end(); I != E; ++I)
1394 printNamedMDNode(I);
1397 if (!Machine.mdn_empty()) {
1403 void AssemblyWriter::printNamedMDNode(const NamedMDNode *NMD) {
1404 Out << "!" << NMD->getName() << " = !{";
1405 for (unsigned i = 0, e = NMD->getNumOperands(); i != e; ++i) {
1407 if (MDNode *MD = NMD->getOperand(i))
1408 Out << '!' << Machine.getMetadataSlot(MD);
1416 static void PrintLinkage(GlobalValue::LinkageTypes LT,
1417 formatted_raw_ostream &Out) {
1419 case GlobalValue::ExternalLinkage: break;
1420 case GlobalValue::PrivateLinkage: Out << "private "; break;
1421 case GlobalValue::LinkerPrivateLinkage: Out << "linker_private "; break;
1422 case GlobalValue::LinkerPrivateWeakLinkage:
1423 Out << "linker_private_weak ";
1425 case GlobalValue::InternalLinkage: Out << "internal "; break;
1426 case GlobalValue::LinkOnceAnyLinkage: Out << "linkonce "; break;
1427 case GlobalValue::LinkOnceODRLinkage: Out << "linkonce_odr "; break;
1428 case GlobalValue::WeakAnyLinkage: Out << "weak "; break;
1429 case GlobalValue::WeakODRLinkage: Out << "weak_odr "; break;
1430 case GlobalValue::CommonLinkage: Out << "common "; break;
1431 case GlobalValue::AppendingLinkage: Out << "appending "; break;
1432 case GlobalValue::DLLImportLinkage: Out << "dllimport "; break;
1433 case GlobalValue::DLLExportLinkage: Out << "dllexport "; break;
1434 case GlobalValue::ExternalWeakLinkage: Out << "extern_weak "; break;
1435 case GlobalValue::AvailableExternallyLinkage:
1436 Out << "available_externally ";
1442 static void PrintVisibility(GlobalValue::VisibilityTypes Vis,
1443 formatted_raw_ostream &Out) {
1445 case GlobalValue::DefaultVisibility: break;
1446 case GlobalValue::HiddenVisibility: Out << "hidden "; break;
1447 case GlobalValue::ProtectedVisibility: Out << "protected "; break;
1451 void AssemblyWriter::printGlobal(const GlobalVariable *GV) {
1452 if (GV->isMaterializable())
1453 Out << "; Materializable\n";
1455 WriteAsOperandInternal(Out, GV, &TypePrinter, &Machine);
1458 if (!GV->hasInitializer() && GV->hasExternalLinkage())
1461 PrintLinkage(GV->getLinkage(), Out);
1462 PrintVisibility(GV->getVisibility(), Out);
1464 if (GV->isThreadLocal()) Out << "thread_local ";
1465 if (unsigned AddressSpace = GV->getType()->getAddressSpace())
1466 Out << "addrspace(" << AddressSpace << ") ";
1467 Out << (GV->isConstant() ? "constant " : "global ");
1468 TypePrinter.print(GV->getType()->getElementType(), Out);
1470 if (GV->hasInitializer()) {
1472 writeOperand(GV->getInitializer(), false);
1475 if (GV->hasSection()) {
1476 Out << ", section \"";
1477 PrintEscapedString(GV->getSection(), Out);
1480 if (GV->getAlignment())
1481 Out << ", align " << GV->getAlignment();
1483 printInfoComment(*GV);
1487 void AssemblyWriter::printAlias(const GlobalAlias *GA) {
1488 if (GA->isMaterializable())
1489 Out << "; Materializable\n";
1491 // Don't crash when dumping partially built GA
1493 Out << "<<nameless>> = ";
1495 PrintLLVMName(Out, GA);
1498 PrintVisibility(GA->getVisibility(), Out);
1502 PrintLinkage(GA->getLinkage(), Out);
1504 const Constant *Aliasee = GA->getAliasee();
1506 if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(Aliasee)) {
1507 TypePrinter.print(GV->getType(), Out);
1509 PrintLLVMName(Out, GV);
1510 } else if (const Function *F = dyn_cast<Function>(Aliasee)) {
1511 TypePrinter.print(F->getFunctionType(), Out);
1514 WriteAsOperandInternal(Out, F, &TypePrinter, &Machine);
1515 } else if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(Aliasee)) {
1516 TypePrinter.print(GA->getType(), Out);
1518 PrintLLVMName(Out, GA);
1520 const ConstantExpr *CE = cast<ConstantExpr>(Aliasee);
1521 // The only valid GEP is an all zero GEP.
1522 assert((CE->getOpcode() == Instruction::BitCast ||
1523 CE->getOpcode() == Instruction::GetElementPtr) &&
1524 "Unsupported aliasee");
1525 writeOperand(CE, false);
1528 printInfoComment(*GA);
1532 void AssemblyWriter::printTypeSymbolTable(const TypeSymbolTable &ST) {
1533 // Emit all numbered types.
1534 for (unsigned i = 0, e = NumberedTypes.size(); i != e; ++i) {
1535 Out << '%' << i << " = type ";
1537 // Make sure we print out at least one level of the type structure, so
1538 // that we do not get %2 = type %2
1539 TypePrinter.printAtLeastOneLevel(NumberedTypes[i], Out);
1543 // Print the named types.
1544 for (TypeSymbolTable::const_iterator TI = ST.begin(), TE = ST.end();
1546 PrintLLVMName(Out, TI->first, LocalPrefix);
1549 // Make sure we print out at least one level of the type structure, so
1550 // that we do not get %FILE = type %FILE
1551 TypePrinter.printAtLeastOneLevel(TI->second, Out);
1556 /// printFunction - Print all aspects of a function.
1558 void AssemblyWriter::printFunction(const Function *F) {
1559 // Print out the return type and name.
1562 if (AnnotationWriter) AnnotationWriter->emitFunctionAnnot(F, Out);
1564 if (F->isMaterializable())
1565 Out << "; Materializable\n";
1567 if (F->isDeclaration())
1572 PrintLinkage(F->getLinkage(), Out);
1573 PrintVisibility(F->getVisibility(), Out);
1575 // Print the calling convention.
1576 switch (F->getCallingConv()) {
1577 case CallingConv::C: break; // default
1578 case CallingConv::Fast: Out << "fastcc "; break;
1579 case CallingConv::Cold: Out << "coldcc "; break;
1580 case CallingConv::X86_StdCall: Out << "x86_stdcallcc "; break;
1581 case CallingConv::X86_FastCall: Out << "x86_fastcallcc "; break;
1582 case CallingConv::X86_ThisCall: Out << "x86_thiscallcc "; break;
1583 case CallingConv::ARM_APCS: Out << "arm_apcscc "; break;
1584 case CallingConv::ARM_AAPCS: Out << "arm_aapcscc "; break;
1585 case CallingConv::ARM_AAPCS_VFP:Out << "arm_aapcs_vfpcc "; break;
1586 case CallingConv::MSP430_INTR: Out << "msp430_intrcc "; break;
1587 default: Out << "cc" << F->getCallingConv() << " "; break;
1590 const FunctionType *FT = F->getFunctionType();
1591 const AttrListPtr &Attrs = F->getAttributes();
1592 Attributes RetAttrs = Attrs.getRetAttributes();
1593 if (RetAttrs != Attribute::None)
1594 Out << Attribute::getAsString(Attrs.getRetAttributes()) << ' ';
1595 TypePrinter.print(F->getReturnType(), Out);
1597 WriteAsOperandInternal(Out, F, &TypePrinter, &Machine);
1599 Machine.incorporateFunction(F);
1601 // Loop over the arguments, printing them...
1604 if (!F->isDeclaration()) {
1605 // If this isn't a declaration, print the argument names as well.
1606 for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
1608 // Insert commas as we go... the first arg doesn't get a comma
1609 if (I != F->arg_begin()) Out << ", ";
1610 printArgument(I, Attrs.getParamAttributes(Idx));
1614 // Otherwise, print the types from the function type.
1615 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
1616 // Insert commas as we go... the first arg doesn't get a comma
1620 TypePrinter.print(FT->getParamType(i), Out);
1622 Attributes ArgAttrs = Attrs.getParamAttributes(i+1);
1623 if (ArgAttrs != Attribute::None)
1624 Out << ' ' << Attribute::getAsString(ArgAttrs);
1628 // Finish printing arguments...
1629 if (FT->isVarArg()) {
1630 if (FT->getNumParams()) Out << ", ";
1631 Out << "..."; // Output varargs portion of signature!
1634 Attributes FnAttrs = Attrs.getFnAttributes();
1635 if (FnAttrs != Attribute::None)
1636 Out << ' ' << Attribute::getAsString(Attrs.getFnAttributes());
1637 if (F->hasSection()) {
1638 Out << " section \"";
1639 PrintEscapedString(F->getSection(), Out);
1642 if (F->getAlignment())
1643 Out << " align " << F->getAlignment();
1645 Out << " gc \"" << F->getGC() << '"';
1646 if (F->isDeclaration()) {
1651 // Output all of its basic blocks... for the function
1652 for (Function::const_iterator I = F->begin(), E = F->end(); I != E; ++I)
1658 Machine.purgeFunction();
1661 /// printArgument - This member is called for every argument that is passed into
1662 /// the function. Simply print it out
1664 void AssemblyWriter::printArgument(const Argument *Arg,
1667 TypePrinter.print(Arg->getType(), Out);
1669 // Output parameter attributes list
1670 if (Attrs != Attribute::None)
1671 Out << ' ' << Attribute::getAsString(Attrs);
1673 // Output name, if available...
1674 if (Arg->hasName()) {
1676 PrintLLVMName(Out, Arg);
1680 /// printBasicBlock - This member is called for each basic block in a method.
1682 void AssemblyWriter::printBasicBlock(const BasicBlock *BB) {
1683 if (BB->hasName()) { // Print out the label if it exists...
1685 PrintLLVMName(Out, BB->getName(), LabelPrefix);
1687 } else if (!BB->use_empty()) { // Don't print block # of no uses...
1688 Out << "\n; <label>:";
1689 int Slot = Machine.getLocalSlot(BB);
1696 if (BB->getParent() == 0) {
1697 Out.PadToColumn(50);
1698 Out << "; Error: Block without parent!";
1699 } else if (BB != &BB->getParent()->getEntryBlock()) { // Not the entry block?
1700 // Output predecessors for the block...
1701 Out.PadToColumn(50);
1703 const_pred_iterator PI = pred_begin(BB), PE = pred_end(BB);
1706 Out << " No predecessors!";
1709 writeOperand(*PI, false);
1710 for (++PI; PI != PE; ++PI) {
1712 writeOperand(*PI, false);
1719 if (AnnotationWriter) AnnotationWriter->emitBasicBlockStartAnnot(BB, Out);
1721 // Output all of the instructions in the basic block...
1722 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I != E; ++I) {
1723 printInstruction(*I);
1727 if (AnnotationWriter) AnnotationWriter->emitBasicBlockEndAnnot(BB, Out);
1730 /// printInfoComment - Print a little comment after the instruction indicating
1731 /// which slot it occupies.
1733 void AssemblyWriter::printInfoComment(const Value &V) {
1734 if (AnnotationWriter) {
1735 AnnotationWriter->printInfoComment(V, Out);
1739 if (V.getType()->isVoidTy()) return;
1741 Out.PadToColumn(50);
1743 TypePrinter.print(V.getType(), Out);
1744 Out << "> [#uses=" << V.getNumUses() << ']'; // Output # uses
1747 // This member is called for each Instruction in a function..
1748 void AssemblyWriter::printInstruction(const Instruction &I) {
1749 if (AnnotationWriter) AnnotationWriter->emitInstructionAnnot(&I, Out);
1751 // Print out indentation for an instruction.
1754 // Print out name if it exists...
1756 PrintLLVMName(Out, &I);
1758 } else if (!I.getType()->isVoidTy()) {
1759 // Print out the def slot taken.
1760 int SlotNum = Machine.getLocalSlot(&I);
1762 Out << "<badref> = ";
1764 Out << '%' << SlotNum << " = ";
1767 // If this is a volatile load or store, print out the volatile marker.
1768 if ((isa<LoadInst>(I) && cast<LoadInst>(I).isVolatile()) ||
1769 (isa<StoreInst>(I) && cast<StoreInst>(I).isVolatile())) {
1771 } else if (isa<CallInst>(I) && cast<CallInst>(I).isTailCall()) {
1772 // If this is a call, check if it's a tail call.
1776 // Print out the opcode...
1777 Out << I.getOpcodeName();
1779 // Print out optimization information.
1780 WriteOptimizationInfo(Out, &I);
1782 // Print out the compare instruction predicates
1783 if (const CmpInst *CI = dyn_cast<CmpInst>(&I))
1784 Out << ' ' << getPredicateText(CI->getPredicate());
1786 // Print out the type of the operands...
1787 const Value *Operand = I.getNumOperands() ? I.getOperand(0) : 0;
1789 // Special case conditional branches to swizzle the condition out to the front
1790 if (isa<BranchInst>(I) && cast<BranchInst>(I).isConditional()) {
1791 BranchInst &BI(cast<BranchInst>(I));
1793 writeOperand(BI.getCondition(), true);
1795 writeOperand(BI.getSuccessor(0), true);
1797 writeOperand(BI.getSuccessor(1), true);
1799 } else if (isa<SwitchInst>(I)) {
1800 // Special case switch instruction to get formatting nice and correct.
1802 writeOperand(Operand , true);
1804 writeOperand(I.getOperand(1), true);
1807 for (unsigned op = 2, Eop = I.getNumOperands(); op < Eop; op += 2) {
1809 writeOperand(I.getOperand(op ), true);
1811 writeOperand(I.getOperand(op+1), true);
1814 } else if (isa<IndirectBrInst>(I)) {
1815 // Special case indirectbr instruction to get formatting nice and correct.
1817 writeOperand(Operand, true);
1820 for (unsigned i = 1, e = I.getNumOperands(); i != e; ++i) {
1823 writeOperand(I.getOperand(i), true);
1826 } else if (isa<PHINode>(I)) {
1828 TypePrinter.print(I.getType(), Out);
1831 for (unsigned op = 0, Eop = I.getNumOperands(); op < Eop; op += 2) {
1832 if (op) Out << ", ";
1834 writeOperand(I.getOperand(op ), false); Out << ", ";
1835 writeOperand(I.getOperand(op+1), false); Out << " ]";
1837 } else if (const ExtractValueInst *EVI = dyn_cast<ExtractValueInst>(&I)) {
1839 writeOperand(I.getOperand(0), true);
1840 for (const unsigned *i = EVI->idx_begin(), *e = EVI->idx_end(); i != e; ++i)
1842 } else if (const InsertValueInst *IVI = dyn_cast<InsertValueInst>(&I)) {
1844 writeOperand(I.getOperand(0), true); Out << ", ";
1845 writeOperand(I.getOperand(1), true);
1846 for (const unsigned *i = IVI->idx_begin(), *e = IVI->idx_end(); i != e; ++i)
1848 } else if (isa<ReturnInst>(I) && !Operand) {
1850 } else if (const CallInst *CI = dyn_cast<CallInst>(&I)) {
1851 // Print the calling convention being used.
1852 switch (CI->getCallingConv()) {
1853 case CallingConv::C: break; // default
1854 case CallingConv::Fast: Out << " fastcc"; break;
1855 case CallingConv::Cold: Out << " coldcc"; break;
1856 case CallingConv::X86_StdCall: Out << " x86_stdcallcc"; break;
1857 case CallingConv::X86_FastCall: Out << " x86_fastcallcc"; break;
1858 case CallingConv::X86_ThisCall: Out << " x86_thiscallcc"; break;
1859 case CallingConv::ARM_APCS: Out << " arm_apcscc "; break;
1860 case CallingConv::ARM_AAPCS: Out << " arm_aapcscc "; break;
1861 case CallingConv::ARM_AAPCS_VFP:Out << " arm_aapcs_vfpcc "; break;
1862 case CallingConv::MSP430_INTR: Out << " msp430_intrcc "; break;
1863 default: Out << " cc" << CI->getCallingConv(); break;
1866 Operand = CI->getCalledValue();
1867 const PointerType *PTy = cast<PointerType>(Operand->getType());
1868 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
1869 const Type *RetTy = FTy->getReturnType();
1870 const AttrListPtr &PAL = CI->getAttributes();
1872 if (PAL.getRetAttributes() != Attribute::None)
1873 Out << ' ' << Attribute::getAsString(PAL.getRetAttributes());
1875 // If possible, print out the short form of the call instruction. We can
1876 // only do this if the first argument is a pointer to a nonvararg function,
1877 // and if the return type is not a pointer to a function.
1880 if (!FTy->isVarArg() &&
1881 (!RetTy->isPointerTy() ||
1882 !cast<PointerType>(RetTy)->getElementType()->isFunctionTy())) {
1883 TypePrinter.print(RetTy, Out);
1885 writeOperand(Operand, false);
1887 writeOperand(Operand, true);
1890 for (unsigned op = 0, Eop = CI->getNumArgOperands(); op < Eop; ++op) {
1893 writeParamOperand(CI->getArgOperand(op), PAL.getParamAttributes(op + 1));
1896 if (PAL.getFnAttributes() != Attribute::None)
1897 Out << ' ' << Attribute::getAsString(PAL.getFnAttributes());
1898 } else if (const InvokeInst *II = dyn_cast<InvokeInst>(&I)) {
1899 Operand = II->getCalledValue();
1900 const PointerType *PTy = cast<PointerType>(Operand->getType());
1901 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
1902 const Type *RetTy = FTy->getReturnType();
1903 const AttrListPtr &PAL = II->getAttributes();
1905 // Print the calling convention being used.
1906 switch (II->getCallingConv()) {
1907 case CallingConv::C: break; // default
1908 case CallingConv::Fast: Out << " fastcc"; break;
1909 case CallingConv::Cold: Out << " coldcc"; break;
1910 case CallingConv::X86_StdCall: Out << " x86_stdcallcc"; break;
1911 case CallingConv::X86_FastCall: Out << " x86_fastcallcc"; break;
1912 case CallingConv::X86_ThisCall: Out << " x86_thiscallcc"; break;
1913 case CallingConv::ARM_APCS: Out << " arm_apcscc "; break;
1914 case CallingConv::ARM_AAPCS: Out << " arm_aapcscc "; break;
1915 case CallingConv::ARM_AAPCS_VFP:Out << " arm_aapcs_vfpcc "; break;
1916 case CallingConv::MSP430_INTR: Out << " msp430_intrcc "; break;
1917 default: Out << " cc" << II->getCallingConv(); break;
1920 if (PAL.getRetAttributes() != Attribute::None)
1921 Out << ' ' << Attribute::getAsString(PAL.getRetAttributes());
1923 // If possible, print out the short form of the invoke instruction. We can
1924 // only do this if the first argument is a pointer to a nonvararg function,
1925 // and if the return type is not a pointer to a function.
1928 if (!FTy->isVarArg() &&
1929 (!RetTy->isPointerTy() ||
1930 !cast<PointerType>(RetTy)->getElementType()->isFunctionTy())) {
1931 TypePrinter.print(RetTy, Out);
1933 writeOperand(Operand, false);
1935 writeOperand(Operand, true);
1938 for (unsigned op = 0, Eop = II->getNumArgOperands(); op < Eop; ++op) {
1941 writeParamOperand(II->getArgOperand(op), PAL.getParamAttributes(op + 1));
1945 if (PAL.getFnAttributes() != Attribute::None)
1946 Out << ' ' << Attribute::getAsString(PAL.getFnAttributes());
1949 writeOperand(II->getNormalDest(), true);
1951 writeOperand(II->getUnwindDest(), true);
1953 } else if (const AllocaInst *AI = dyn_cast<AllocaInst>(&I)) {
1955 TypePrinter.print(AI->getType()->getElementType(), Out);
1956 if (!AI->getArraySize() || AI->isArrayAllocation()) {
1958 writeOperand(AI->getArraySize(), true);
1960 if (AI->getAlignment()) {
1961 Out << ", align " << AI->getAlignment();
1963 } else if (isa<CastInst>(I)) {
1966 writeOperand(Operand, true); // Work with broken code
1969 TypePrinter.print(I.getType(), Out);
1970 } else if (isa<VAArgInst>(I)) {
1973 writeOperand(Operand, true); // Work with broken code
1976 TypePrinter.print(I.getType(), Out);
1977 } else if (Operand) { // Print the normal way.
1979 // PrintAllTypes - Instructions who have operands of all the same type
1980 // omit the type from all but the first operand. If the instruction has
1981 // different type operands (for example br), then they are all printed.
1982 bool PrintAllTypes = false;
1983 const Type *TheType = Operand->getType();
1985 // Select, Store and ShuffleVector always print all types.
1986 if (isa<SelectInst>(I) || isa<StoreInst>(I) || isa<ShuffleVectorInst>(I)
1987 || isa<ReturnInst>(I)) {
1988 PrintAllTypes = true;
1990 for (unsigned i = 1, E = I.getNumOperands(); i != E; ++i) {
1991 Operand = I.getOperand(i);
1992 // note that Operand shouldn't be null, but the test helps make dump()
1993 // more tolerant of malformed IR
1994 if (Operand && Operand->getType() != TheType) {
1995 PrintAllTypes = true; // We have differing types! Print them all!
2001 if (!PrintAllTypes) {
2003 TypePrinter.print(TheType, Out);
2007 for (unsigned i = 0, E = I.getNumOperands(); i != E; ++i) {
2009 writeOperand(I.getOperand(i), PrintAllTypes);
2013 // Print post operand alignment for load/store.
2014 if (isa<LoadInst>(I) && cast<LoadInst>(I).getAlignment()) {
2015 Out << ", align " << cast<LoadInst>(I).getAlignment();
2016 } else if (isa<StoreInst>(I) && cast<StoreInst>(I).getAlignment()) {
2017 Out << ", align " << cast<StoreInst>(I).getAlignment();
2020 // Print Metadata info.
2021 SmallVector<std::pair<unsigned, MDNode*>, 4> InstMD;
2022 I.getAllMetadata(InstMD);
2023 if (!InstMD.empty()) {
2024 SmallVector<StringRef, 8> MDNames;
2025 I.getType()->getContext().getMDKindNames(MDNames);
2026 for (unsigned i = 0, e = InstMD.size(); i != e; ++i) {
2027 unsigned Kind = InstMD[i].first;
2028 if (Kind < MDNames.size()) {
2029 Out << ", !" << MDNames[Kind];
2031 Out << ", !<unknown kind #" << Kind << ">";
2033 Out << " !" << Machine.getMetadataSlot(InstMD[i].second);
2036 printInfoComment(I);
2039 static void WriteMDNodeComment(const MDNode *Node,
2040 formatted_raw_ostream &Out) {
2041 if (Node->getNumOperands() < 1)
2043 ConstantInt *CI = dyn_cast_or_null<ConstantInt>(Node->getOperand(0));
2045 APInt Val = CI->getValue();
2046 APInt Tag = Val & ~APInt(Val.getBitWidth(), LLVMDebugVersionMask);
2047 if (Val.ult(LLVMDebugVersion))
2050 Out.PadToColumn(50);
2051 if (Tag == dwarf::DW_TAG_auto_variable)
2052 Out << "; [ DW_TAG_auto_variable ]";
2053 else if (Tag == dwarf::DW_TAG_arg_variable)
2054 Out << "; [ DW_TAG_arg_variable ]";
2055 else if (Tag == dwarf::DW_TAG_return_variable)
2056 Out << "; [ DW_TAG_return_variable ]";
2057 else if (Tag == dwarf::DW_TAG_vector_type)
2058 Out << "; [ DW_TAG_vector_type ]";
2059 else if (Tag == dwarf::DW_TAG_user_base)
2060 Out << "; [ DW_TAG_user_base ]";
2061 else if (Tag.isIntN(32)) {
2062 if (const char *TagName = dwarf::TagString(Tag.getZExtValue()))
2063 Out << "; [ " << TagName << " ]";
2067 void AssemblyWriter::writeAllMDNodes() {
2068 SmallVector<const MDNode *, 16> Nodes;
2069 Nodes.resize(Machine.mdn_size());
2070 for (SlotTracker::mdn_iterator I = Machine.mdn_begin(), E = Machine.mdn_end();
2072 Nodes[I->second] = cast<MDNode>(I->first);
2074 for (unsigned i = 0, e = Nodes.size(); i != e; ++i) {
2075 Out << '!' << i << " = metadata ";
2076 printMDNodeBody(Nodes[i]);
2080 void AssemblyWriter::printMDNodeBody(const MDNode *Node) {
2081 WriteMDNodeBodyInternal(Out, Node, &TypePrinter, &Machine);
2082 WriteMDNodeComment(Node, Out);
2086 //===----------------------------------------------------------------------===//
2087 // External Interface declarations
2088 //===----------------------------------------------------------------------===//
2090 void Module::print(raw_ostream &ROS, AssemblyAnnotationWriter *AAW) const {
2091 SlotTracker SlotTable(this);
2092 formatted_raw_ostream OS(ROS);
2093 AssemblyWriter W(OS, SlotTable, this, AAW);
2094 W.printModule(this);
2097 void Type::print(raw_ostream &OS) const {
2099 OS << "<null Type>";
2102 TypePrinting().print(this, OS);
2105 void Value::print(raw_ostream &ROS, AssemblyAnnotationWriter *AAW) const {
2107 ROS << "printing a <null> value\n";
2110 formatted_raw_ostream OS(ROS);
2111 if (const Instruction *I = dyn_cast<Instruction>(this)) {
2112 const Function *F = I->getParent() ? I->getParent()->getParent() : 0;
2113 SlotTracker SlotTable(F);
2114 AssemblyWriter W(OS, SlotTable, getModuleFromVal(I), AAW);
2115 W.printInstruction(*I);
2116 } else if (const BasicBlock *BB = dyn_cast<BasicBlock>(this)) {
2117 SlotTracker SlotTable(BB->getParent());
2118 AssemblyWriter W(OS, SlotTable, getModuleFromVal(BB), AAW);
2119 W.printBasicBlock(BB);
2120 } else if (const GlobalValue *GV = dyn_cast<GlobalValue>(this)) {
2121 SlotTracker SlotTable(GV->getParent());
2122 AssemblyWriter W(OS, SlotTable, GV->getParent(), AAW);
2123 if (const GlobalVariable *V = dyn_cast<GlobalVariable>(GV))
2125 else if (const Function *F = dyn_cast<Function>(GV))
2128 W.printAlias(cast<GlobalAlias>(GV));
2129 } else if (const MDNode *N = dyn_cast<MDNode>(this)) {
2130 const Function *F = N->getFunction();
2131 SlotTracker SlotTable(F);
2132 AssemblyWriter W(OS, SlotTable, F ? getModuleFromVal(F) : 0, AAW);
2133 W.printMDNodeBody(N);
2134 } else if (const NamedMDNode *N = dyn_cast<NamedMDNode>(this)) {
2135 SlotTracker SlotTable(N->getParent());
2136 AssemblyWriter W(OS, SlotTable, N->getParent(), AAW);
2137 W.printNamedMDNode(N);
2138 } else if (const Constant *C = dyn_cast<Constant>(this)) {
2139 TypePrinting TypePrinter;
2140 TypePrinter.print(C->getType(), OS);
2142 WriteConstantInternal(OS, C, TypePrinter, 0);
2143 } else if (isa<InlineAsm>(this) || isa<MDString>(this) ||
2144 isa<Argument>(this)) {
2145 WriteAsOperand(OS, this, true, 0);
2147 // Otherwise we don't know what it is. Call the virtual function to
2148 // allow a subclass to print itself.
2153 // Value::printCustom - subclasses should override this to implement printing.
2154 void Value::printCustom(raw_ostream &OS) const {
2155 llvm_unreachable("Unknown value to print out!");
2158 // Value::dump - allow easy printing of Values from the debugger.
2159 void Value::dump() const { print(dbgs()); dbgs() << '\n'; }
2161 // Type::dump - allow easy printing of Types from the debugger.
2162 // This one uses type names from the given context module
2163 void Type::dump(const Module *Context) const {
2164 WriteTypeSymbolic(dbgs(), this, Context);
2168 // Type::dump - allow easy printing of Types from the debugger.
2169 void Type::dump() const { dump(0); }
2171 // Module::dump() - Allow printing of Modules from the debugger.
2172 void Module::dump() const { print(dbgs(), 0); }