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(const StringRef &Name,
75 for (unsigned i = 0, e = Name.size(); i != e; ++i) {
76 unsigned char C = Name[i];
77 if (isprint(C) && C != '\\' && C != '"')
80 Out << '\\' << hexdigit(C >> 4) << hexdigit(C & 0x0F);
91 /// PrintLLVMName - Turn the specified name into an 'LLVM name', which is either
92 /// prefixed with % (if the string only contains simple characters) or is
93 /// surrounded with ""'s (if it has special chars in it). Print it out.
94 static void PrintLLVMName(raw_ostream &OS, const StringRef &Name,
96 assert(Name.data() && "Cannot get empty name!");
98 default: llvm_unreachable("Bad prefix!");
100 case GlobalPrefix: OS << '@'; break;
101 case LabelPrefix: break;
102 case LocalPrefix: OS << '%'; break;
105 // Scan the name to see if it needs quotes first.
106 bool NeedsQuotes = isdigit(Name[0]);
108 for (unsigned i = 0, e = Name.size(); i != e; ++i) {
110 if (!isalnum(C) && C != '-' && C != '.' && C != '_') {
117 // If we didn't need any quotes, just write out the name in one blast.
123 // Okay, we need quotes. Output the quotes and escape any scary characters as
126 PrintEscapedString(Name, OS);
130 /// PrintLLVMName - Turn the specified name into an 'LLVM name', which is either
131 /// prefixed with % (if the string only contains simple characters) or is
132 /// surrounded with ""'s (if it has special chars in it). Print it out.
133 static void PrintLLVMName(raw_ostream &OS, const Value *V) {
134 PrintLLVMName(OS, V->getName(),
135 isa<GlobalValue>(V) ? GlobalPrefix : LocalPrefix);
138 //===----------------------------------------------------------------------===//
139 // TypePrinting Class: Type printing machinery
140 //===----------------------------------------------------------------------===//
142 static DenseMap<const Type *, std::string> &getTypeNamesMap(void *M) {
143 return *static_cast<DenseMap<const Type *, std::string>*>(M);
146 void TypePrinting::clear() {
147 getTypeNamesMap(TypeNames).clear();
150 bool TypePrinting::hasTypeName(const Type *Ty) const {
151 return getTypeNamesMap(TypeNames).count(Ty);
154 void TypePrinting::addTypeName(const Type *Ty, const std::string &N) {
155 getTypeNamesMap(TypeNames).insert(std::make_pair(Ty, N));
159 TypePrinting::TypePrinting() {
160 TypeNames = new DenseMap<const Type *, std::string>();
163 TypePrinting::~TypePrinting() {
164 delete &getTypeNamesMap(TypeNames);
167 /// CalcTypeName - Write the specified type to the specified raw_ostream, making
168 /// use of type names or up references to shorten the type name where possible.
169 void TypePrinting::CalcTypeName(const Type *Ty,
170 SmallVectorImpl<const Type *> &TypeStack,
171 raw_ostream &OS, bool IgnoreTopLevelName) {
172 // Check to see if the type is named.
173 if (!IgnoreTopLevelName) {
174 DenseMap<const Type *, std::string> &TM = getTypeNamesMap(TypeNames);
175 DenseMap<const Type *, std::string>::iterator I = TM.find(Ty);
182 // Check to see if the Type is already on the stack...
183 unsigned Slot = 0, CurSize = TypeStack.size();
184 while (Slot < CurSize && TypeStack[Slot] != Ty) ++Slot; // Scan for type
186 // This is another base case for the recursion. In this case, we know
187 // that we have looped back to a type that we have previously visited.
188 // Generate the appropriate upreference to handle this.
189 if (Slot < CurSize) {
190 OS << '\\' << unsigned(CurSize-Slot); // Here's the upreference
194 TypeStack.push_back(Ty); // Recursive case: Add us to the stack..
196 switch (Ty->getTypeID()) {
197 case Type::VoidTyID: OS << "void"; break;
198 case Type::FloatTyID: OS << "float"; break;
199 case Type::DoubleTyID: OS << "double"; break;
200 case Type::X86_FP80TyID: OS << "x86_fp80"; break;
201 case Type::FP128TyID: OS << "fp128"; break;
202 case Type::PPC_FP128TyID: OS << "ppc_fp128"; break;
203 case Type::LabelTyID: OS << "label"; break;
204 case Type::MetadataTyID: OS << "metadata"; break;
205 case Type::IntegerTyID:
206 OS << 'i' << cast<IntegerType>(Ty)->getBitWidth();
209 case Type::FunctionTyID: {
210 const FunctionType *FTy = cast<FunctionType>(Ty);
211 CalcTypeName(FTy->getReturnType(), TypeStack, OS);
213 for (FunctionType::param_iterator I = FTy->param_begin(),
214 E = FTy->param_end(); I != E; ++I) {
215 if (I != FTy->param_begin())
217 CalcTypeName(*I, TypeStack, OS);
219 if (FTy->isVarArg()) {
220 if (FTy->getNumParams()) OS << ", ";
226 case Type::StructTyID: {
227 const StructType *STy = cast<StructType>(Ty);
231 for (StructType::element_iterator I = STy->element_begin(),
232 E = STy->element_end(); I != E; ++I) {
234 CalcTypeName(*I, TypeStack, OS);
235 if (next(I) == STy->element_end())
245 case Type::UnionTyID: {
246 const UnionType *UTy = cast<UnionType>(Ty);
248 for (StructType::element_iterator I = UTy->element_begin(),
249 E = UTy->element_end(); I != E; ++I) {
251 CalcTypeName(*I, TypeStack, OS);
252 if (next(I) == UTy->element_end())
260 case Type::PointerTyID: {
261 const PointerType *PTy = cast<PointerType>(Ty);
262 CalcTypeName(PTy->getElementType(), TypeStack, OS);
263 if (unsigned AddressSpace = PTy->getAddressSpace())
264 OS << " addrspace(" << AddressSpace << ')';
268 case Type::ArrayTyID: {
269 const ArrayType *ATy = cast<ArrayType>(Ty);
270 OS << '[' << ATy->getNumElements() << " x ";
271 CalcTypeName(ATy->getElementType(), TypeStack, OS);
275 case Type::VectorTyID: {
276 const VectorType *PTy = cast<VectorType>(Ty);
277 OS << "<" << PTy->getNumElements() << " x ";
278 CalcTypeName(PTy->getElementType(), TypeStack, OS);
282 case Type::OpaqueTyID:
286 OS << "<unrecognized-type>";
290 TypeStack.pop_back(); // Remove self from stack.
293 /// printTypeInt - The internal guts of printing out a type that has a
294 /// potentially named portion.
296 void TypePrinting::print(const Type *Ty, raw_ostream &OS,
297 bool IgnoreTopLevelName) {
298 // Check to see if the type is named.
299 DenseMap<const Type*, std::string> &TM = getTypeNamesMap(TypeNames);
300 if (!IgnoreTopLevelName) {
301 DenseMap<const Type*, std::string>::iterator I = TM.find(Ty);
308 // Otherwise we have a type that has not been named but is a derived type.
309 // Carefully recurse the type hierarchy to print out any contained symbolic
311 SmallVector<const Type *, 16> TypeStack;
312 std::string TypeName;
314 raw_string_ostream TypeOS(TypeName);
315 CalcTypeName(Ty, TypeStack, TypeOS, IgnoreTopLevelName);
318 // Cache type name for later use.
319 if (!IgnoreTopLevelName)
320 TM.insert(std::make_pair(Ty, TypeOS.str()));
325 // To avoid walking constant expressions multiple times and other IR
326 // objects, we keep several helper maps.
327 DenseSet<const Value*> VisitedConstants;
328 DenseSet<const Type*> VisitedTypes;
331 std::vector<const Type*> &NumberedTypes;
333 TypeFinder(TypePrinting &tp, std::vector<const Type*> &numberedTypes)
334 : TP(tp), NumberedTypes(numberedTypes) {}
336 void Run(const Module &M) {
337 // Get types from the type symbol table. This gets opaque types referened
338 // only through derived named types.
339 const TypeSymbolTable &ST = M.getTypeSymbolTable();
340 for (TypeSymbolTable::const_iterator TI = ST.begin(), E = ST.end();
342 IncorporateType(TI->second);
344 // Get types from global variables.
345 for (Module::const_global_iterator I = M.global_begin(),
346 E = M.global_end(); I != E; ++I) {
347 IncorporateType(I->getType());
348 if (I->hasInitializer())
349 IncorporateValue(I->getInitializer());
352 // Get types from aliases.
353 for (Module::const_alias_iterator I = M.alias_begin(),
354 E = M.alias_end(); I != E; ++I) {
355 IncorporateType(I->getType());
356 IncorporateValue(I->getAliasee());
359 // Get types from functions.
360 for (Module::const_iterator FI = M.begin(), E = M.end(); FI != E; ++FI) {
361 IncorporateType(FI->getType());
363 for (Function::const_iterator BB = FI->begin(), E = FI->end();
365 for (BasicBlock::const_iterator II = BB->begin(),
366 E = BB->end(); II != E; ++II) {
367 const Instruction &I = *II;
368 // Incorporate the type of the instruction and all its operands.
369 IncorporateType(I.getType());
370 for (User::const_op_iterator OI = I.op_begin(), OE = I.op_end();
372 IncorporateValue(*OI);
378 void IncorporateType(const Type *Ty) {
379 // Check to see if we're already visited this type.
380 if (!VisitedTypes.insert(Ty).second)
383 // If this is a structure or opaque type, add a name for the type.
384 if (((Ty->isStructTy() && cast<StructType>(Ty)->getNumElements())
385 || Ty->isOpaqueTy()) && !TP.hasTypeName(Ty)) {
386 TP.addTypeName(Ty, "%"+utostr(unsigned(NumberedTypes.size())));
387 NumberedTypes.push_back(Ty);
390 // Recursively walk all contained types.
391 for (Type::subtype_iterator I = Ty->subtype_begin(),
392 E = Ty->subtype_end(); I != E; ++I)
396 /// IncorporateValue - This method is used to walk operand lists finding
397 /// types hiding in constant expressions and other operands that won't be
398 /// walked in other ways. GlobalValues, basic blocks, instructions, and
399 /// inst operands are all explicitly enumerated.
400 void IncorporateValue(const Value *V) {
401 if (V == 0 || !isa<Constant>(V) || isa<GlobalValue>(V)) return;
404 if (!VisitedConstants.insert(V).second)
408 IncorporateType(V->getType());
410 // Look in operands for types.
411 const Constant *C = cast<Constant>(V);
412 for (Constant::const_op_iterator I = C->op_begin(),
413 E = C->op_end(); I != E;++I)
414 IncorporateValue(*I);
417 } // end anonymous namespace
420 /// AddModuleTypesToPrinter - Add all of the symbolic type names for types in
421 /// the specified module to the TypePrinter and all numbered types to it and the
422 /// NumberedTypes table.
423 static void AddModuleTypesToPrinter(TypePrinting &TP,
424 std::vector<const Type*> &NumberedTypes,
428 // If the module has a symbol table, take all global types and stuff their
429 // names into the TypeNames map.
430 const TypeSymbolTable &ST = M->getTypeSymbolTable();
431 for (TypeSymbolTable::const_iterator TI = ST.begin(), E = ST.end();
433 const Type *Ty = cast<Type>(TI->second);
435 // As a heuristic, don't insert pointer to primitive types, because
436 // they are used too often to have a single useful name.
437 if (const PointerType *PTy = dyn_cast<PointerType>(Ty)) {
438 const Type *PETy = PTy->getElementType();
439 if ((PETy->isPrimitiveType() || PETy->isIntegerTy()) &&
444 // Likewise don't insert primitives either.
445 if (Ty->isIntegerTy() || Ty->isPrimitiveType())
448 // Get the name as a string and insert it into TypeNames.
450 raw_string_ostream NameROS(NameStr);
451 formatted_raw_ostream NameOS(NameROS);
452 PrintLLVMName(NameOS, TI->first, LocalPrefix);
454 TP.addTypeName(Ty, NameStr);
457 // Walk the entire module to find references to unnamed structure and opaque
458 // types. This is required for correctness by opaque types (because multiple
459 // uses of an unnamed opaque type needs to be referred to by the same ID) and
460 // it shrinks complex recursive structure types substantially in some cases.
461 TypeFinder(TP, NumberedTypes).Run(*M);
465 /// WriteTypeSymbolic - This attempts to write the specified type as a symbolic
466 /// type, iff there is an entry in the modules symbol table for the specified
467 /// type or one of it's component types.
469 void llvm::WriteTypeSymbolic(raw_ostream &OS, const Type *Ty, const Module *M) {
470 TypePrinting Printer;
471 std::vector<const Type*> NumberedTypes;
472 AddModuleTypesToPrinter(Printer, NumberedTypes, M);
473 Printer.print(Ty, OS);
476 //===----------------------------------------------------------------------===//
477 // SlotTracker Class: Enumerate slot numbers for unnamed values
478 //===----------------------------------------------------------------------===//
482 /// This class provides computation of slot numbers for LLVM Assembly writing.
486 /// ValueMap - A mapping of Values to slot numbers.
487 typedef DenseMap<const Value*, unsigned> ValueMap;
490 /// TheModule - The module for which we are holding slot numbers.
491 const Module* TheModule;
493 /// TheFunction - The function for which we are holding slot numbers.
494 const Function* TheFunction;
495 bool FunctionProcessed;
497 /// mMap - The TypePlanes map for the module level data.
501 /// fMap - The TypePlanes map for the function level data.
505 /// mdnMap - Map for MDNodes.
506 DenseMap<const MDNode*, unsigned> mdnMap;
509 /// Construct from a module
510 explicit SlotTracker(const Module *M);
511 /// Construct from a function, starting out in incorp state.
512 explicit SlotTracker(const Function *F);
514 /// Return the slot number of the specified value in it's type
515 /// plane. If something is not in the SlotTracker, return -1.
516 int getLocalSlot(const Value *V);
517 int getGlobalSlot(const GlobalValue *V);
518 int getMetadataSlot(const MDNode *N);
520 /// If you'd like to deal with a function instead of just a module, use
521 /// this method to get its data into the SlotTracker.
522 void incorporateFunction(const Function *F) {
524 FunctionProcessed = false;
527 /// After calling incorporateFunction, use this method to remove the
528 /// most recently incorporated function from the SlotTracker. This
529 /// will reset the state of the machine back to just the module contents.
530 void purgeFunction();
532 /// MDNode map iterators.
533 typedef DenseMap<const MDNode*, unsigned>::iterator mdn_iterator;
534 mdn_iterator mdn_begin() { return mdnMap.begin(); }
535 mdn_iterator mdn_end() { return mdnMap.end(); }
536 unsigned mdn_size() const { return mdnMap.size(); }
537 bool mdn_empty() const { return mdnMap.empty(); }
539 /// This function does the actual initialization.
540 inline void initialize();
542 // Implementation Details
544 /// CreateModuleSlot - Insert the specified GlobalValue* into the slot table.
545 void CreateModuleSlot(const GlobalValue *V);
547 /// CreateMetadataSlot - Insert the specified MDNode* into the slot table.
548 void CreateMetadataSlot(const MDNode *N);
550 /// CreateFunctionSlot - Insert the specified Value* into the slot table.
551 void CreateFunctionSlot(const Value *V);
553 /// Add all of the module level global variables (and their initializers)
554 /// and function declarations, but not the contents of those functions.
555 void processModule();
557 /// Add all of the functions arguments, basic blocks, and instructions.
558 void processFunction();
560 SlotTracker(const SlotTracker &); // DO NOT IMPLEMENT
561 void operator=(const SlotTracker &); // DO NOT IMPLEMENT
564 } // end anonymous namespace
567 static SlotTracker *createSlotTracker(const Value *V) {
568 if (const Argument *FA = dyn_cast<Argument>(V))
569 return new SlotTracker(FA->getParent());
571 if (const Instruction *I = dyn_cast<Instruction>(V))
572 return new SlotTracker(I->getParent()->getParent());
574 if (const BasicBlock *BB = dyn_cast<BasicBlock>(V))
575 return new SlotTracker(BB->getParent());
577 if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(V))
578 return new SlotTracker(GV->getParent());
580 if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(V))
581 return new SlotTracker(GA->getParent());
583 if (const Function *Func = dyn_cast<Function>(V))
584 return new SlotTracker(Func);
587 return new SlotTracker((Function *)0);
593 #define ST_DEBUG(X) dbgs() << X
598 // Module level constructor. Causes the contents of the Module (sans functions)
599 // to be added to the slot table.
600 SlotTracker::SlotTracker(const Module *M)
601 : TheModule(M), TheFunction(0), FunctionProcessed(false),
602 mNext(0), fNext(0), mdnNext(0) {
605 // Function level constructor. Causes the contents of the Module and the one
606 // function provided to be added to the slot table.
607 SlotTracker::SlotTracker(const Function *F)
608 : TheModule(F ? F->getParent() : 0), TheFunction(F), FunctionProcessed(false),
609 mNext(0), fNext(0), mdnNext(0) {
612 inline void SlotTracker::initialize() {
615 TheModule = 0; ///< Prevent re-processing next time we're called.
618 if (TheFunction && !FunctionProcessed)
622 // Iterate through all the global variables, functions, and global
623 // variable initializers and create slots for them.
624 void SlotTracker::processModule() {
625 ST_DEBUG("begin processModule!\n");
627 // Add all of the unnamed global variables to the value table.
628 for (Module::const_global_iterator I = TheModule->global_begin(),
629 E = TheModule->global_end(); I != E; ++I) {
634 // Add metadata used by named metadata.
635 for (Module::const_named_metadata_iterator
636 I = TheModule->named_metadata_begin(),
637 E = TheModule->named_metadata_end(); I != E; ++I) {
638 const NamedMDNode *NMD = I;
639 for (unsigned i = 0, e = NMD->getNumOperands(); i != e; ++i) {
640 if (MDNode *MD = NMD->getOperand(i))
641 CreateMetadataSlot(MD);
645 // Add all the unnamed functions to the table.
646 for (Module::const_iterator I = TheModule->begin(), E = TheModule->end();
651 ST_DEBUG("end processModule!\n");
654 // Process the arguments, basic blocks, and instructions of a function.
655 void SlotTracker::processFunction() {
656 ST_DEBUG("begin processFunction!\n");
659 // Add all the function arguments with no names.
660 for(Function::const_arg_iterator AI = TheFunction->arg_begin(),
661 AE = TheFunction->arg_end(); AI != AE; ++AI)
663 CreateFunctionSlot(AI);
665 ST_DEBUG("Inserting Instructions:\n");
667 SmallVector<std::pair<unsigned, MDNode*>, 4> MDForInst;
669 // Add all of the basic blocks and instructions with no names.
670 for (Function::const_iterator BB = TheFunction->begin(),
671 E = TheFunction->end(); BB != E; ++BB) {
673 CreateFunctionSlot(BB);
675 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I != E;
677 if (!I->getType()->isVoidTy() && !I->hasName())
678 CreateFunctionSlot(I);
680 // Intrinsics can directly use metadata. We allow direct calls to any
681 // llvm.foo function here, because the target may not be linked into the
683 if (const CallInst *CI = dyn_cast<CallInst>(I)) {
684 if (Function *F = CI->getCalledFunction())
685 if (F->getName().startswith("llvm."))
686 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
687 if (MDNode *N = dyn_cast_or_null<MDNode>(I->getOperand(i)))
688 CreateMetadataSlot(N);
691 // Process metadata attached with this instruction.
692 I->getAllMetadata(MDForInst);
693 for (unsigned i = 0, e = MDForInst.size(); i != e; ++i)
694 CreateMetadataSlot(MDForInst[i].second);
699 FunctionProcessed = true;
701 ST_DEBUG("end processFunction!\n");
704 /// Clean up after incorporating a function. This is the only way to get out of
705 /// the function incorporation state that affects get*Slot/Create*Slot. Function
706 /// incorporation state is indicated by TheFunction != 0.
707 void SlotTracker::purgeFunction() {
708 ST_DEBUG("begin purgeFunction!\n");
709 fMap.clear(); // Simply discard the function level map
711 FunctionProcessed = false;
712 ST_DEBUG("end purgeFunction!\n");
715 /// getGlobalSlot - Get the slot number of a global value.
716 int SlotTracker::getGlobalSlot(const GlobalValue *V) {
717 // Check for uninitialized state and do lazy initialization.
720 // Find the type plane in the module map
721 ValueMap::iterator MI = mMap.find(V);
722 return MI == mMap.end() ? -1 : (int)MI->second;
725 /// getMetadataSlot - Get the slot number of a MDNode.
726 int SlotTracker::getMetadataSlot(const MDNode *N) {
727 // Check for uninitialized state and do lazy initialization.
730 // Find the type plane in the module map
731 mdn_iterator MI = mdnMap.find(N);
732 return MI == mdnMap.end() ? -1 : (int)MI->second;
736 /// getLocalSlot - Get the slot number for a value that is local to a function.
737 int SlotTracker::getLocalSlot(const Value *V) {
738 assert(!isa<Constant>(V) && "Can't get a constant or global slot with this!");
740 // Check for uninitialized state and do lazy initialization.
743 ValueMap::iterator FI = fMap.find(V);
744 return FI == fMap.end() ? -1 : (int)FI->second;
748 /// CreateModuleSlot - Insert the specified GlobalValue* into the slot table.
749 void SlotTracker::CreateModuleSlot(const GlobalValue *V) {
750 assert(V && "Can't insert a null Value into SlotTracker!");
751 assert(!V->getType()->isVoidTy() && "Doesn't need a slot!");
752 assert(!V->hasName() && "Doesn't need a slot!");
754 unsigned DestSlot = mNext++;
757 ST_DEBUG(" Inserting value [" << V->getType() << "] = " << V << " slot=" <<
759 // G = Global, F = Function, A = Alias, o = other
760 ST_DEBUG((isa<GlobalVariable>(V) ? 'G' :
761 (isa<Function>(V) ? 'F' :
762 (isa<GlobalAlias>(V) ? 'A' : 'o'))) << "]\n");
765 /// CreateSlot - Create a new slot for the specified value if it has no name.
766 void SlotTracker::CreateFunctionSlot(const Value *V) {
767 assert(!V->getType()->isVoidTy() && !V->hasName() && "Doesn't need a slot!");
769 unsigned DestSlot = fNext++;
772 // G = Global, F = Function, o = other
773 ST_DEBUG(" Inserting value [" << V->getType() << "] = " << V << " slot=" <<
774 DestSlot << " [o]\n");
777 /// CreateModuleSlot - Insert the specified MDNode* into the slot table.
778 void SlotTracker::CreateMetadataSlot(const MDNode *N) {
779 assert(N && "Can't insert a null Value into SlotTracker!");
781 // Don't insert if N is a function-local metadata, these are always printed
783 if (N->isFunctionLocal())
786 mdn_iterator I = mdnMap.find(N);
787 if (I != mdnMap.end())
790 unsigned DestSlot = mdnNext++;
791 mdnMap[N] = DestSlot;
793 // Recursively add any MDNodes referenced by operands.
794 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
795 if (const MDNode *Op = dyn_cast_or_null<MDNode>(N->getOperand(i)))
796 CreateMetadataSlot(Op);
799 //===----------------------------------------------------------------------===//
800 // AsmWriter Implementation
801 //===----------------------------------------------------------------------===//
803 static void WriteAsOperandInternal(raw_ostream &Out, const Value *V,
804 TypePrinting *TypePrinter,
805 SlotTracker *Machine);
809 static const char *getPredicateText(unsigned predicate) {
810 const char * pred = "unknown";
812 case FCmpInst::FCMP_FALSE: pred = "false"; break;
813 case FCmpInst::FCMP_OEQ: pred = "oeq"; break;
814 case FCmpInst::FCMP_OGT: pred = "ogt"; break;
815 case FCmpInst::FCMP_OGE: pred = "oge"; break;
816 case FCmpInst::FCMP_OLT: pred = "olt"; break;
817 case FCmpInst::FCMP_OLE: pred = "ole"; break;
818 case FCmpInst::FCMP_ONE: pred = "one"; break;
819 case FCmpInst::FCMP_ORD: pred = "ord"; break;
820 case FCmpInst::FCMP_UNO: pred = "uno"; break;
821 case FCmpInst::FCMP_UEQ: pred = "ueq"; break;
822 case FCmpInst::FCMP_UGT: pred = "ugt"; break;
823 case FCmpInst::FCMP_UGE: pred = "uge"; break;
824 case FCmpInst::FCMP_ULT: pred = "ult"; break;
825 case FCmpInst::FCMP_ULE: pred = "ule"; break;
826 case FCmpInst::FCMP_UNE: pred = "une"; break;
827 case FCmpInst::FCMP_TRUE: pred = "true"; break;
828 case ICmpInst::ICMP_EQ: pred = "eq"; break;
829 case ICmpInst::ICMP_NE: pred = "ne"; break;
830 case ICmpInst::ICMP_SGT: pred = "sgt"; break;
831 case ICmpInst::ICMP_SGE: pred = "sge"; break;
832 case ICmpInst::ICMP_SLT: pred = "slt"; break;
833 case ICmpInst::ICMP_SLE: pred = "sle"; break;
834 case ICmpInst::ICMP_UGT: pred = "ugt"; break;
835 case ICmpInst::ICMP_UGE: pred = "uge"; break;
836 case ICmpInst::ICMP_ULT: pred = "ult"; break;
837 case ICmpInst::ICMP_ULE: pred = "ule"; break;
843 static void WriteOptimizationInfo(raw_ostream &Out, const User *U) {
844 if (const OverflowingBinaryOperator *OBO =
845 dyn_cast<OverflowingBinaryOperator>(U)) {
846 if (OBO->hasNoUnsignedWrap())
848 if (OBO->hasNoSignedWrap())
850 } else if (const SDivOperator *Div = dyn_cast<SDivOperator>(U)) {
853 } else if (const GEPOperator *GEP = dyn_cast<GEPOperator>(U)) {
854 if (GEP->isInBounds())
859 static void WriteConstantInt(raw_ostream &Out, const Constant *CV,
860 TypePrinting &TypePrinter, 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 WriteConstantInt(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 \"" << GV->getSection() << '"';
1477 if (GV->getAlignment())
1478 Out << ", align " << GV->getAlignment();
1480 printInfoComment(*GV);
1484 void AssemblyWriter::printAlias(const GlobalAlias *GA) {
1485 if (GA->isMaterializable())
1486 Out << "; Materializable\n";
1488 // Don't crash when dumping partially built GA
1490 Out << "<<nameless>> = ";
1492 PrintLLVMName(Out, GA);
1495 PrintVisibility(GA->getVisibility(), Out);
1499 PrintLinkage(GA->getLinkage(), Out);
1501 const Constant *Aliasee = GA->getAliasee();
1503 if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(Aliasee)) {
1504 TypePrinter.print(GV->getType(), Out);
1506 PrintLLVMName(Out, GV);
1507 } else if (const Function *F = dyn_cast<Function>(Aliasee)) {
1508 TypePrinter.print(F->getFunctionType(), Out);
1511 WriteAsOperandInternal(Out, F, &TypePrinter, &Machine);
1512 } else if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(Aliasee)) {
1513 TypePrinter.print(GA->getType(), Out);
1515 PrintLLVMName(Out, GA);
1517 const ConstantExpr *CE = cast<ConstantExpr>(Aliasee);
1518 // The only valid GEP is an all zero GEP.
1519 assert((CE->getOpcode() == Instruction::BitCast ||
1520 CE->getOpcode() == Instruction::GetElementPtr) &&
1521 "Unsupported aliasee");
1522 writeOperand(CE, false);
1525 printInfoComment(*GA);
1529 void AssemblyWriter::printTypeSymbolTable(const TypeSymbolTable &ST) {
1530 // Emit all numbered types.
1531 for (unsigned i = 0, e = NumberedTypes.size(); i != e; ++i) {
1532 Out << '%' << i << " = type ";
1534 // Make sure we print out at least one level of the type structure, so
1535 // that we do not get %2 = type %2
1536 TypePrinter.printAtLeastOneLevel(NumberedTypes[i], Out);
1540 // Print the named types.
1541 for (TypeSymbolTable::const_iterator TI = ST.begin(), TE = ST.end();
1543 PrintLLVMName(Out, TI->first, LocalPrefix);
1546 // Make sure we print out at least one level of the type structure, so
1547 // that we do not get %FILE = type %FILE
1548 TypePrinter.printAtLeastOneLevel(TI->second, Out);
1553 /// printFunction - Print all aspects of a function.
1555 void AssemblyWriter::printFunction(const Function *F) {
1556 // Print out the return type and name.
1559 if (AnnotationWriter) AnnotationWriter->emitFunctionAnnot(F, Out);
1561 if (F->isMaterializable())
1562 Out << "; Materializable\n";
1564 if (F->isDeclaration())
1569 PrintLinkage(F->getLinkage(), Out);
1570 PrintVisibility(F->getVisibility(), Out);
1572 // Print the calling convention.
1573 switch (F->getCallingConv()) {
1574 case CallingConv::C: break; // default
1575 case CallingConv::Fast: Out << "fastcc "; break;
1576 case CallingConv::Cold: Out << "coldcc "; break;
1577 case CallingConv::X86_StdCall: Out << "x86_stdcallcc "; break;
1578 case CallingConv::X86_FastCall: Out << "x86_fastcallcc "; break;
1579 case CallingConv::X86_ThisCall: Out << "x86_thiscallcc "; break;
1580 case CallingConv::ARM_APCS: Out << "arm_apcscc "; break;
1581 case CallingConv::ARM_AAPCS: Out << "arm_aapcscc "; break;
1582 case CallingConv::ARM_AAPCS_VFP:Out << "arm_aapcs_vfpcc "; break;
1583 case CallingConv::MSP430_INTR: Out << "msp430_intrcc "; break;
1584 default: Out << "cc" << F->getCallingConv() << " "; break;
1587 const FunctionType *FT = F->getFunctionType();
1588 const AttrListPtr &Attrs = F->getAttributes();
1589 Attributes RetAttrs = Attrs.getRetAttributes();
1590 if (RetAttrs != Attribute::None)
1591 Out << Attribute::getAsString(Attrs.getRetAttributes()) << ' ';
1592 TypePrinter.print(F->getReturnType(), Out);
1594 WriteAsOperandInternal(Out, F, &TypePrinter, &Machine);
1596 Machine.incorporateFunction(F);
1598 // Loop over the arguments, printing them...
1601 if (!F->isDeclaration()) {
1602 // If this isn't a declaration, print the argument names as well.
1603 for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
1605 // Insert commas as we go... the first arg doesn't get a comma
1606 if (I != F->arg_begin()) Out << ", ";
1607 printArgument(I, Attrs.getParamAttributes(Idx));
1611 // Otherwise, print the types from the function type.
1612 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
1613 // Insert commas as we go... the first arg doesn't get a comma
1617 TypePrinter.print(FT->getParamType(i), Out);
1619 Attributes ArgAttrs = Attrs.getParamAttributes(i+1);
1620 if (ArgAttrs != Attribute::None)
1621 Out << ' ' << Attribute::getAsString(ArgAttrs);
1625 // Finish printing arguments...
1626 if (FT->isVarArg()) {
1627 if (FT->getNumParams()) Out << ", ";
1628 Out << "..."; // Output varargs portion of signature!
1631 Attributes FnAttrs = Attrs.getFnAttributes();
1632 if (FnAttrs != Attribute::None)
1633 Out << ' ' << Attribute::getAsString(Attrs.getFnAttributes());
1634 if (F->hasSection())
1635 Out << " section \"" << F->getSection() << '"';
1636 if (F->getAlignment())
1637 Out << " align " << F->getAlignment();
1639 Out << " gc \"" << F->getGC() << '"';
1640 if (F->isDeclaration()) {
1645 // Output all of its basic blocks... for the function
1646 for (Function::const_iterator I = F->begin(), E = F->end(); I != E; ++I)
1652 Machine.purgeFunction();
1655 /// printArgument - This member is called for every argument that is passed into
1656 /// the function. Simply print it out
1658 void AssemblyWriter::printArgument(const Argument *Arg,
1661 TypePrinter.print(Arg->getType(), Out);
1663 // Output parameter attributes list
1664 if (Attrs != Attribute::None)
1665 Out << ' ' << Attribute::getAsString(Attrs);
1667 // Output name, if available...
1668 if (Arg->hasName()) {
1670 PrintLLVMName(Out, Arg);
1674 /// printBasicBlock - This member is called for each basic block in a method.
1676 void AssemblyWriter::printBasicBlock(const BasicBlock *BB) {
1677 if (BB->hasName()) { // Print out the label if it exists...
1679 PrintLLVMName(Out, BB->getName(), LabelPrefix);
1681 } else if (!BB->use_empty()) { // Don't print block # of no uses...
1682 Out << "\n; <label>:";
1683 int Slot = Machine.getLocalSlot(BB);
1690 if (BB->getParent() == 0) {
1691 Out.PadToColumn(50);
1692 Out << "; Error: Block without parent!";
1693 } else if (BB != &BB->getParent()->getEntryBlock()) { // Not the entry block?
1694 // Output predecessors for the block...
1695 Out.PadToColumn(50);
1697 const_pred_iterator PI = pred_begin(BB), PE = pred_end(BB);
1700 Out << " No predecessors!";
1703 writeOperand(*PI, false);
1704 for (++PI; PI != PE; ++PI) {
1706 writeOperand(*PI, false);
1713 if (AnnotationWriter) AnnotationWriter->emitBasicBlockStartAnnot(BB, Out);
1715 // Output all of the instructions in the basic block...
1716 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I != E; ++I) {
1717 printInstruction(*I);
1721 if (AnnotationWriter) AnnotationWriter->emitBasicBlockEndAnnot(BB, Out);
1724 /// printInfoComment - Print a little comment after the instruction indicating
1725 /// which slot it occupies.
1727 void AssemblyWriter::printInfoComment(const Value &V) {
1728 if (AnnotationWriter) {
1729 AnnotationWriter->printInfoComment(V, Out);
1733 if (V.getType()->isVoidTy()) return;
1735 Out.PadToColumn(50);
1737 TypePrinter.print(V.getType(), Out);
1738 Out << "> [#uses=" << V.getNumUses() << ']'; // Output # uses
1741 // This member is called for each Instruction in a function..
1742 void AssemblyWriter::printInstruction(const Instruction &I) {
1743 if (AnnotationWriter) AnnotationWriter->emitInstructionAnnot(&I, Out);
1745 // Print out indentation for an instruction.
1748 // Print out name if it exists...
1750 PrintLLVMName(Out, &I);
1752 } else if (!I.getType()->isVoidTy()) {
1753 // Print out the def slot taken.
1754 int SlotNum = Machine.getLocalSlot(&I);
1756 Out << "<badref> = ";
1758 Out << '%' << SlotNum << " = ";
1761 // If this is a volatile load or store, print out the volatile marker.
1762 if ((isa<LoadInst>(I) && cast<LoadInst>(I).isVolatile()) ||
1763 (isa<StoreInst>(I) && cast<StoreInst>(I).isVolatile())) {
1765 } else if (isa<CallInst>(I) && cast<CallInst>(I).isTailCall()) {
1766 // If this is a call, check if it's a tail call.
1770 // Print out the opcode...
1771 Out << I.getOpcodeName();
1773 // Print out optimization information.
1774 WriteOptimizationInfo(Out, &I);
1776 // Print out the compare instruction predicates
1777 if (const CmpInst *CI = dyn_cast<CmpInst>(&I))
1778 Out << ' ' << getPredicateText(CI->getPredicate());
1780 // Print out the type of the operands...
1781 const Value *Operand = I.getNumOperands() ? I.getOperand(0) : 0;
1783 // Special case conditional branches to swizzle the condition out to the front
1784 if (isa<BranchInst>(I) && cast<BranchInst>(I).isConditional()) {
1785 BranchInst &BI(cast<BranchInst>(I));
1787 writeOperand(BI.getCondition(), true);
1789 writeOperand(BI.getSuccessor(0), true);
1791 writeOperand(BI.getSuccessor(1), true);
1793 } else if (isa<SwitchInst>(I)) {
1794 // Special case switch instruction to get formatting nice and correct.
1796 writeOperand(Operand , true);
1798 writeOperand(I.getOperand(1), true);
1801 for (unsigned op = 2, Eop = I.getNumOperands(); op < Eop; op += 2) {
1803 writeOperand(I.getOperand(op ), true);
1805 writeOperand(I.getOperand(op+1), true);
1808 } else if (isa<IndirectBrInst>(I)) {
1809 // Special case indirectbr instruction to get formatting nice and correct.
1811 writeOperand(Operand, true);
1814 for (unsigned i = 1, e = I.getNumOperands(); i != e; ++i) {
1817 writeOperand(I.getOperand(i), true);
1820 } else if (isa<PHINode>(I)) {
1822 TypePrinter.print(I.getType(), Out);
1825 for (unsigned op = 0, Eop = I.getNumOperands(); op < Eop; op += 2) {
1826 if (op) Out << ", ";
1828 writeOperand(I.getOperand(op ), false); Out << ", ";
1829 writeOperand(I.getOperand(op+1), false); Out << " ]";
1831 } else if (const ExtractValueInst *EVI = dyn_cast<ExtractValueInst>(&I)) {
1833 writeOperand(I.getOperand(0), true);
1834 for (const unsigned *i = EVI->idx_begin(), *e = EVI->idx_end(); i != e; ++i)
1836 } else if (const InsertValueInst *IVI = dyn_cast<InsertValueInst>(&I)) {
1838 writeOperand(I.getOperand(0), true); Out << ", ";
1839 writeOperand(I.getOperand(1), true);
1840 for (const unsigned *i = IVI->idx_begin(), *e = IVI->idx_end(); i != e; ++i)
1842 } else if (isa<ReturnInst>(I) && !Operand) {
1844 } else if (const CallInst *CI = dyn_cast<CallInst>(&I)) {
1845 // Print the calling convention being used.
1846 switch (CI->getCallingConv()) {
1847 case CallingConv::C: break; // default
1848 case CallingConv::Fast: Out << " fastcc"; break;
1849 case CallingConv::Cold: Out << " coldcc"; break;
1850 case CallingConv::X86_StdCall: Out << " x86_stdcallcc"; break;
1851 case CallingConv::X86_FastCall: Out << " x86_fastcallcc"; break;
1852 case CallingConv::X86_ThisCall: Out << " x86_thiscallcc"; break;
1853 case CallingConv::ARM_APCS: Out << " arm_apcscc "; break;
1854 case CallingConv::ARM_AAPCS: Out << " arm_aapcscc "; break;
1855 case CallingConv::ARM_AAPCS_VFP:Out << " arm_aapcs_vfpcc "; break;
1856 case CallingConv::MSP430_INTR: Out << " msp430_intrcc "; break;
1857 default: Out << " cc" << CI->getCallingConv(); break;
1860 Operand = CI->getCalledValue();
1861 const PointerType *PTy = cast<PointerType>(Operand->getType());
1862 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
1863 const Type *RetTy = FTy->getReturnType();
1864 const AttrListPtr &PAL = CI->getAttributes();
1866 if (PAL.getRetAttributes() != Attribute::None)
1867 Out << ' ' << Attribute::getAsString(PAL.getRetAttributes());
1869 // If possible, print out the short form of the call instruction. We can
1870 // only do this if the first argument is a pointer to a nonvararg function,
1871 // and if the return type is not a pointer to a function.
1874 if (!FTy->isVarArg() &&
1875 (!RetTy->isPointerTy() ||
1876 !cast<PointerType>(RetTy)->getElementType()->isFunctionTy())) {
1877 TypePrinter.print(RetTy, Out);
1879 writeOperand(Operand, false);
1881 writeOperand(Operand, true);
1884 for (unsigned op = 0, Eop = CI->getNumArgOperands(); op < Eop; ++op) {
1887 writeParamOperand(CI->getArgOperand(op), PAL.getParamAttributes(op + 1));
1890 if (PAL.getFnAttributes() != Attribute::None)
1891 Out << ' ' << Attribute::getAsString(PAL.getFnAttributes());
1892 } else if (const InvokeInst *II = dyn_cast<InvokeInst>(&I)) {
1893 Operand = II->getCalledValue();
1894 const PointerType *PTy = cast<PointerType>(Operand->getType());
1895 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
1896 const Type *RetTy = FTy->getReturnType();
1897 const AttrListPtr &PAL = II->getAttributes();
1899 // Print the calling convention being used.
1900 switch (II->getCallingConv()) {
1901 case CallingConv::C: break; // default
1902 case CallingConv::Fast: Out << " fastcc"; break;
1903 case CallingConv::Cold: Out << " coldcc"; break;
1904 case CallingConv::X86_StdCall: Out << " x86_stdcallcc"; break;
1905 case CallingConv::X86_FastCall: Out << " x86_fastcallcc"; break;
1906 case CallingConv::X86_ThisCall: Out << " x86_thiscallcc"; break;
1907 case CallingConv::ARM_APCS: Out << " arm_apcscc "; break;
1908 case CallingConv::ARM_AAPCS: Out << " arm_aapcscc "; break;
1909 case CallingConv::ARM_AAPCS_VFP:Out << " arm_aapcs_vfpcc "; break;
1910 case CallingConv::MSP430_INTR: Out << " msp430_intrcc "; break;
1911 default: Out << " cc" << II->getCallingConv(); break;
1914 if (PAL.getRetAttributes() != Attribute::None)
1915 Out << ' ' << Attribute::getAsString(PAL.getRetAttributes());
1917 // If possible, print out the short form of the invoke instruction. We can
1918 // only do this if the first argument is a pointer to a nonvararg function,
1919 // and if the return type is not a pointer to a function.
1922 if (!FTy->isVarArg() &&
1923 (!RetTy->isPointerTy() ||
1924 !cast<PointerType>(RetTy)->getElementType()->isFunctionTy())) {
1925 TypePrinter.print(RetTy, Out);
1927 writeOperand(Operand, false);
1929 writeOperand(Operand, true);
1932 for (unsigned op = 0, Eop = II->getNumArgOperands(); op < Eop; ++op) {
1935 writeParamOperand(II->getArgOperand(op), PAL.getParamAttributes(op + 1));
1939 if (PAL.getFnAttributes() != Attribute::None)
1940 Out << ' ' << Attribute::getAsString(PAL.getFnAttributes());
1943 writeOperand(II->getNormalDest(), true);
1945 writeOperand(II->getUnwindDest(), true);
1947 } else if (const AllocaInst *AI = dyn_cast<AllocaInst>(&I)) {
1949 TypePrinter.print(AI->getType()->getElementType(), Out);
1950 if (!AI->getArraySize() || AI->isArrayAllocation()) {
1952 writeOperand(AI->getArraySize(), true);
1954 if (AI->getAlignment()) {
1955 Out << ", align " << AI->getAlignment();
1957 } else if (isa<CastInst>(I)) {
1960 writeOperand(Operand, true); // Work with broken code
1963 TypePrinter.print(I.getType(), Out);
1964 } else if (isa<VAArgInst>(I)) {
1967 writeOperand(Operand, true); // Work with broken code
1970 TypePrinter.print(I.getType(), Out);
1971 } else if (Operand) { // Print the normal way.
1973 // PrintAllTypes - Instructions who have operands of all the same type
1974 // omit the type from all but the first operand. If the instruction has
1975 // different type operands (for example br), then they are all printed.
1976 bool PrintAllTypes = false;
1977 const Type *TheType = Operand->getType();
1979 // Select, Store and ShuffleVector always print all types.
1980 if (isa<SelectInst>(I) || isa<StoreInst>(I) || isa<ShuffleVectorInst>(I)
1981 || isa<ReturnInst>(I)) {
1982 PrintAllTypes = true;
1984 for (unsigned i = 1, E = I.getNumOperands(); i != E; ++i) {
1985 Operand = I.getOperand(i);
1986 // note that Operand shouldn't be null, but the test helps make dump()
1987 // more tolerant of malformed IR
1988 if (Operand && Operand->getType() != TheType) {
1989 PrintAllTypes = true; // We have differing types! Print them all!
1995 if (!PrintAllTypes) {
1997 TypePrinter.print(TheType, Out);
2001 for (unsigned i = 0, E = I.getNumOperands(); i != E; ++i) {
2003 writeOperand(I.getOperand(i), PrintAllTypes);
2007 // Print post operand alignment for load/store.
2008 if (isa<LoadInst>(I) && cast<LoadInst>(I).getAlignment()) {
2009 Out << ", align " << cast<LoadInst>(I).getAlignment();
2010 } else if (isa<StoreInst>(I) && cast<StoreInst>(I).getAlignment()) {
2011 Out << ", align " << cast<StoreInst>(I).getAlignment();
2014 // Print Metadata info.
2015 SmallVector<std::pair<unsigned, MDNode*>, 4> InstMD;
2016 I.getAllMetadata(InstMD);
2017 if (!InstMD.empty()) {
2018 SmallVector<StringRef, 8> MDNames;
2019 I.getType()->getContext().getMDKindNames(MDNames);
2020 for (unsigned i = 0, e = InstMD.size(); i != e; ++i) {
2021 unsigned Kind = InstMD[i].first;
2022 if (Kind < MDNames.size()) {
2023 Out << ", !" << MDNames[Kind];
2025 Out << ", !<unknown kind #" << Kind << ">";
2027 Out << " !" << Machine.getMetadataSlot(InstMD[i].second);
2030 printInfoComment(I);
2033 static void WriteMDNodeComment(const MDNode *Node,
2034 formatted_raw_ostream &Out) {
2035 if (Node->getNumOperands() < 1)
2037 ConstantInt *CI = dyn_cast_or_null<ConstantInt>(Node->getOperand(0));
2039 APInt Val = CI->getValue();
2040 APInt Tag = Val & ~APInt(Val.getBitWidth(), LLVMDebugVersionMask);
2041 if (Val.ult(LLVMDebugVersion))
2044 Out.PadToColumn(50);
2045 if (Tag == dwarf::DW_TAG_auto_variable)
2046 Out << "; [ DW_TAG_auto_variable ]";
2047 else if (Tag == dwarf::DW_TAG_arg_variable)
2048 Out << "; [ DW_TAG_arg_variable ]";
2049 else if (Tag == dwarf::DW_TAG_return_variable)
2050 Out << "; [ DW_TAG_return_variable ]";
2051 else if (Tag == dwarf::DW_TAG_vector_type)
2052 Out << "; [ DW_TAG_vector_type ]";
2053 else if (Tag == dwarf::DW_TAG_user_base)
2054 Out << "; [ DW_TAG_user_base ]";
2055 else if (Tag.isIntN(32)) {
2056 if (const char *TagName = dwarf::TagString(Tag.getZExtValue()))
2057 Out << "; [ " << TagName << " ]";
2061 void AssemblyWriter::writeAllMDNodes() {
2062 SmallVector<const MDNode *, 16> Nodes;
2063 Nodes.resize(Machine.mdn_size());
2064 for (SlotTracker::mdn_iterator I = Machine.mdn_begin(), E = Machine.mdn_end();
2066 Nodes[I->second] = cast<MDNode>(I->first);
2068 for (unsigned i = 0, e = Nodes.size(); i != e; ++i) {
2069 Out << '!' << i << " = metadata ";
2070 printMDNodeBody(Nodes[i]);
2074 void AssemblyWriter::printMDNodeBody(const MDNode *Node) {
2075 WriteMDNodeBodyInternal(Out, Node, &TypePrinter, &Machine);
2076 WriteMDNodeComment(Node, Out);
2080 //===----------------------------------------------------------------------===//
2081 // External Interface declarations
2082 //===----------------------------------------------------------------------===//
2084 void Module::print(raw_ostream &ROS, AssemblyAnnotationWriter *AAW) const {
2085 SlotTracker SlotTable(this);
2086 formatted_raw_ostream OS(ROS);
2087 AssemblyWriter W(OS, SlotTable, this, AAW);
2088 W.printModule(this);
2091 void Type::print(raw_ostream &OS) const {
2093 OS << "<null Type>";
2096 TypePrinting().print(this, OS);
2099 void Value::print(raw_ostream &ROS, AssemblyAnnotationWriter *AAW) const {
2101 ROS << "printing a <null> value\n";
2104 formatted_raw_ostream OS(ROS);
2105 if (const Instruction *I = dyn_cast<Instruction>(this)) {
2106 const Function *F = I->getParent() ? I->getParent()->getParent() : 0;
2107 SlotTracker SlotTable(F);
2108 AssemblyWriter W(OS, SlotTable, getModuleFromVal(I), AAW);
2109 W.printInstruction(*I);
2110 } else if (const BasicBlock *BB = dyn_cast<BasicBlock>(this)) {
2111 SlotTracker SlotTable(BB->getParent());
2112 AssemblyWriter W(OS, SlotTable, getModuleFromVal(BB), AAW);
2113 W.printBasicBlock(BB);
2114 } else if (const GlobalValue *GV = dyn_cast<GlobalValue>(this)) {
2115 SlotTracker SlotTable(GV->getParent());
2116 AssemblyWriter W(OS, SlotTable, GV->getParent(), AAW);
2117 if (const GlobalVariable *V = dyn_cast<GlobalVariable>(GV))
2119 else if (const Function *F = dyn_cast<Function>(GV))
2122 W.printAlias(cast<GlobalAlias>(GV));
2123 } else if (const MDNode *N = dyn_cast<MDNode>(this)) {
2124 const Function *F = N->getFunction();
2125 SlotTracker SlotTable(F);
2126 AssemblyWriter W(OS, SlotTable, F ? getModuleFromVal(F) : 0, AAW);
2127 W.printMDNodeBody(N);
2128 } else if (const NamedMDNode *N = dyn_cast<NamedMDNode>(this)) {
2129 SlotTracker SlotTable(N->getParent());
2130 AssemblyWriter W(OS, SlotTable, N->getParent(), AAW);
2131 W.printNamedMDNode(N);
2132 } else if (const Constant *C = dyn_cast<Constant>(this)) {
2133 TypePrinting TypePrinter;
2134 TypePrinter.print(C->getType(), OS);
2136 WriteConstantInt(OS, C, TypePrinter, 0);
2137 } else if (isa<InlineAsm>(this) || isa<MDString>(this) ||
2138 isa<Argument>(this)) {
2139 WriteAsOperand(OS, this, true, 0);
2141 // Otherwise we don't know what it is. Call the virtual function to
2142 // allow a subclass to print itself.
2147 // Value::printCustom - subclasses should override this to implement printing.
2148 void Value::printCustom(raw_ostream &OS) const {
2149 llvm_unreachable("Unknown value to print out!");
2152 // Value::dump - allow easy printing of Values from the debugger.
2153 void Value::dump() const { print(dbgs()); dbgs() << '\n'; }
2155 // Type::dump - allow easy printing of Types from the debugger.
2156 // This one uses type names from the given context module
2157 void Type::dump(const Module *Context) const {
2158 WriteTypeSymbolic(dbgs(), this, Context);
2162 // Type::dump - allow easy printing of Types from the debugger.
2163 void Type::dump() const { dump(0); }
2165 // Module::dump() - Allow printing of Modules from the debugger.
2166 void Module::dump() const { print(dbgs(), 0); }