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/AssemblyAnnotationWriter.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"
44 // Make virtual table appear in this compilation unit.
45 AssemblyAnnotationWriter::~AssemblyAnnotationWriter() {}
47 //===----------------------------------------------------------------------===//
49 //===----------------------------------------------------------------------===//
51 static const Module *getModuleFromVal(const Value *V) {
52 if (const Argument *MA = dyn_cast<Argument>(V))
53 return MA->getParent() ? MA->getParent()->getParent() : 0;
55 if (const BasicBlock *BB = dyn_cast<BasicBlock>(V))
56 return BB->getParent() ? BB->getParent()->getParent() : 0;
58 if (const Instruction *I = dyn_cast<Instruction>(V)) {
59 const Function *M = I->getParent() ? I->getParent()->getParent() : 0;
60 return M ? M->getParent() : 0;
63 if (const GlobalValue *GV = dyn_cast<GlobalValue>(V))
64 return GV->getParent();
68 // PrintEscapedString - Print each character of the specified string, escaping
69 // it if it is not printable or if it is an escape char.
70 static void PrintEscapedString(StringRef Name, raw_ostream &Out) {
71 for (unsigned i = 0, e = Name.size(); i != e; ++i) {
72 unsigned char C = Name[i];
73 if (isprint(C) && C != '\\' && C != '"')
76 Out << '\\' << hexdigit(C >> 4) << hexdigit(C & 0x0F);
87 /// PrintLLVMName - Turn the specified name into an 'LLVM name', which is either
88 /// prefixed with % (if the string only contains simple characters) or is
89 /// surrounded with ""'s (if it has special chars in it). Print it out.
90 static void PrintLLVMName(raw_ostream &OS, StringRef Name, PrefixType Prefix) {
91 assert(Name.data() && "Cannot get empty name!");
93 default: llvm_unreachable("Bad prefix!");
95 case GlobalPrefix: OS << '@'; break;
96 case LabelPrefix: break;
97 case LocalPrefix: OS << '%'; break;
100 // Scan the name to see if it needs quotes first.
101 bool NeedsQuotes = isdigit(Name[0]);
103 for (unsigned i = 0, e = Name.size(); i != e; ++i) {
105 if (!isalnum(C) && C != '-' && C != '.' && C != '_') {
112 // If we didn't need any quotes, just write out the name in one blast.
118 // Okay, we need quotes. Output the quotes and escape any scary characters as
121 PrintEscapedString(Name, OS);
125 /// PrintLLVMName - Turn the specified name into an 'LLVM name', which is either
126 /// prefixed with % (if the string only contains simple characters) or is
127 /// surrounded with ""'s (if it has special chars in it). Print it out.
128 static void PrintLLVMName(raw_ostream &OS, const Value *V) {
129 PrintLLVMName(OS, V->getName(),
130 isa<GlobalValue>(V) ? GlobalPrefix : LocalPrefix);
133 //===----------------------------------------------------------------------===//
134 // TypePrinting Class: Type printing machinery
135 //===----------------------------------------------------------------------===//
137 static DenseMap<const Type *, std::string> &getTypeNamesMap(void *M) {
138 return *static_cast<DenseMap<const Type *, std::string>*>(M);
141 void TypePrinting::clear() {
142 getTypeNamesMap(TypeNames).clear();
145 bool TypePrinting::hasTypeName(const Type *Ty) const {
146 return getTypeNamesMap(TypeNames).count(Ty);
149 void TypePrinting::addTypeName(const Type *Ty, const std::string &N) {
150 getTypeNamesMap(TypeNames).insert(std::make_pair(Ty, N));
154 TypePrinting::TypePrinting() {
155 TypeNames = new DenseMap<const Type *, std::string>();
158 TypePrinting::~TypePrinting() {
159 delete &getTypeNamesMap(TypeNames);
162 /// CalcTypeName - Write the specified type to the specified raw_ostream, making
163 /// use of type names or up references to shorten the type name where possible.
164 void TypePrinting::CalcTypeName(const Type *Ty,
165 SmallVectorImpl<const Type *> &TypeStack,
166 raw_ostream &OS, bool IgnoreTopLevelName) {
167 // Check to see if the type is named.
168 if (!IgnoreTopLevelName) {
169 DenseMap<const Type *, std::string> &TM = getTypeNamesMap(TypeNames);
170 DenseMap<const Type *, std::string>::iterator I = TM.find(Ty);
177 // Check to see if the Type is already on the stack...
178 unsigned Slot = 0, CurSize = TypeStack.size();
179 while (Slot < CurSize && TypeStack[Slot] != Ty) ++Slot; // Scan for type
181 // This is another base case for the recursion. In this case, we know
182 // that we have looped back to a type that we have previously visited.
183 // Generate the appropriate upreference to handle this.
184 if (Slot < CurSize) {
185 OS << '\\' << unsigned(CurSize-Slot); // Here's the upreference
189 TypeStack.push_back(Ty); // Recursive case: Add us to the stack..
191 switch (Ty->getTypeID()) {
192 case Type::VoidTyID: OS << "void"; break;
193 case Type::FloatTyID: OS << "float"; break;
194 case Type::DoubleTyID: OS << "double"; break;
195 case Type::X86_FP80TyID: OS << "x86_fp80"; break;
196 case Type::FP128TyID: OS << "fp128"; break;
197 case Type::PPC_FP128TyID: OS << "ppc_fp128"; break;
198 case Type::LabelTyID: OS << "label"; break;
199 case Type::MetadataTyID: OS << "metadata"; break;
200 case Type::X86_MMXTyID: OS << "x86_mmx"; break;
201 case Type::IntegerTyID:
202 OS << 'i' << cast<IntegerType>(Ty)->getBitWidth();
205 case Type::FunctionTyID: {
206 const FunctionType *FTy = cast<FunctionType>(Ty);
207 CalcTypeName(FTy->getReturnType(), TypeStack, OS);
209 for (FunctionType::param_iterator I = FTy->param_begin(),
210 E = FTy->param_end(); I != E; ++I) {
211 if (I != FTy->param_begin())
213 CalcTypeName(*I, TypeStack, OS);
215 if (FTy->isVarArg()) {
216 if (FTy->getNumParams()) OS << ", ";
222 case Type::StructTyID: {
223 const StructType *STy = cast<StructType>(Ty);
227 for (StructType::element_iterator I = STy->element_begin(),
228 E = STy->element_end(); I != E; ++I) {
230 CalcTypeName(*I, TypeStack, OS);
231 if (llvm::next(I) == STy->element_end())
241 case Type::PointerTyID: {
242 const PointerType *PTy = cast<PointerType>(Ty);
243 CalcTypeName(PTy->getElementType(), TypeStack, OS);
244 if (unsigned AddressSpace = PTy->getAddressSpace())
245 OS << " addrspace(" << AddressSpace << ')';
249 case Type::ArrayTyID: {
250 const ArrayType *ATy = cast<ArrayType>(Ty);
251 OS << '[' << ATy->getNumElements() << " x ";
252 CalcTypeName(ATy->getElementType(), TypeStack, OS);
256 case Type::VectorTyID: {
257 const VectorType *PTy = cast<VectorType>(Ty);
258 OS << "<" << PTy->getNumElements() << " x ";
259 CalcTypeName(PTy->getElementType(), TypeStack, OS);
263 case Type::OpaqueTyID:
267 OS << "<unrecognized-type>";
271 TypeStack.pop_back(); // Remove self from stack.
274 /// printTypeInt - The internal guts of printing out a type that has a
275 /// potentially named portion.
277 void TypePrinting::print(const Type *Ty, raw_ostream &OS,
278 bool IgnoreTopLevelName) {
279 // Check to see if the type is named.
280 DenseMap<const Type*, std::string> &TM = getTypeNamesMap(TypeNames);
281 if (!IgnoreTopLevelName) {
282 DenseMap<const Type*, std::string>::iterator I = TM.find(Ty);
289 // Otherwise we have a type that has not been named but is a derived type.
290 // Carefully recurse the type hierarchy to print out any contained symbolic
292 SmallVector<const Type *, 16> TypeStack;
293 std::string TypeName;
295 raw_string_ostream TypeOS(TypeName);
296 CalcTypeName(Ty, TypeStack, TypeOS, IgnoreTopLevelName);
299 // Cache type name for later use.
300 if (!IgnoreTopLevelName)
301 TM.insert(std::make_pair(Ty, TypeOS.str()));
306 // To avoid walking constant expressions multiple times and other IR
307 // objects, we keep several helper maps.
308 DenseSet<const Value*> VisitedConstants;
309 DenseSet<const Type*> VisitedTypes;
312 std::vector<const Type*> &NumberedTypes;
314 TypeFinder(TypePrinting &tp, std::vector<const Type*> &numberedTypes)
315 : TP(tp), NumberedTypes(numberedTypes) {}
317 void Run(const Module &M) {
318 // Get types from the type symbol table. This gets opaque types referened
319 // only through derived named types.
320 const TypeSymbolTable &ST = M.getTypeSymbolTable();
321 for (TypeSymbolTable::const_iterator TI = ST.begin(), E = ST.end();
323 IncorporateType(TI->second);
325 // Get types from global variables.
326 for (Module::const_global_iterator I = M.global_begin(),
327 E = M.global_end(); I != E; ++I) {
328 IncorporateType(I->getType());
329 if (I->hasInitializer())
330 IncorporateValue(I->getInitializer());
333 // Get types from aliases.
334 for (Module::const_alias_iterator I = M.alias_begin(),
335 E = M.alias_end(); I != E; ++I) {
336 IncorporateType(I->getType());
337 IncorporateValue(I->getAliasee());
340 // Get types from functions.
341 for (Module::const_iterator FI = M.begin(), E = M.end(); FI != E; ++FI) {
342 IncorporateType(FI->getType());
344 for (Function::const_iterator BB = FI->begin(), E = FI->end();
346 for (BasicBlock::const_iterator II = BB->begin(),
347 E = BB->end(); II != E; ++II) {
348 const Instruction &I = *II;
349 // Incorporate the type of the instruction and all its operands.
350 IncorporateType(I.getType());
351 for (User::const_op_iterator OI = I.op_begin(), OE = I.op_end();
353 IncorporateValue(*OI);
359 void IncorporateType(const Type *Ty) {
360 // Check to see if we're already visited this type.
361 if (!VisitedTypes.insert(Ty).second)
364 // If this is a structure or opaque type, add a name for the type.
365 if (((Ty->isStructTy() && cast<StructType>(Ty)->getNumElements())
366 || Ty->isOpaqueTy()) && !TP.hasTypeName(Ty)) {
367 TP.addTypeName(Ty, "%"+utostr(unsigned(NumberedTypes.size())));
368 NumberedTypes.push_back(Ty);
371 // Recursively walk all contained types.
372 for (Type::subtype_iterator I = Ty->subtype_begin(),
373 E = Ty->subtype_end(); I != E; ++I)
377 /// IncorporateValue - This method is used to walk operand lists finding
378 /// types hiding in constant expressions and other operands that won't be
379 /// walked in other ways. GlobalValues, basic blocks, instructions, and
380 /// inst operands are all explicitly enumerated.
381 void IncorporateValue(const Value *V) {
382 if (V == 0 || !isa<Constant>(V) || isa<GlobalValue>(V)) return;
385 if (!VisitedConstants.insert(V).second)
389 IncorporateType(V->getType());
391 // Look in operands for types.
392 const Constant *C = cast<Constant>(V);
393 for (Constant::const_op_iterator I = C->op_begin(),
394 E = C->op_end(); I != E;++I)
395 IncorporateValue(*I);
398 } // end anonymous namespace
401 /// AddModuleTypesToPrinter - Add all of the symbolic type names for types in
402 /// the specified module to the TypePrinter and all numbered types to it and the
403 /// NumberedTypes table.
404 static void AddModuleTypesToPrinter(TypePrinting &TP,
405 std::vector<const Type*> &NumberedTypes,
409 // If the module has a symbol table, take all global types and stuff their
410 // names into the TypeNames map.
411 const TypeSymbolTable &ST = M->getTypeSymbolTable();
412 for (TypeSymbolTable::const_iterator TI = ST.begin(), E = ST.end();
414 const Type *Ty = cast<Type>(TI->second);
416 // As a heuristic, don't insert pointer to primitive types, because
417 // they are used too often to have a single useful name.
418 if (const PointerType *PTy = dyn_cast<PointerType>(Ty)) {
419 const Type *PETy = PTy->getElementType();
420 if ((PETy->isPrimitiveType() || PETy->isIntegerTy()) &&
425 // Likewise don't insert primitives either.
426 if (Ty->isIntegerTy() || Ty->isPrimitiveType())
429 // Get the name as a string and insert it into TypeNames.
431 raw_string_ostream NameROS(NameStr);
432 formatted_raw_ostream NameOS(NameROS);
433 PrintLLVMName(NameOS, TI->first, LocalPrefix);
435 TP.addTypeName(Ty, NameStr);
438 // Walk the entire module to find references to unnamed structure and opaque
439 // types. This is required for correctness by opaque types (because multiple
440 // uses of an unnamed opaque type needs to be referred to by the same ID) and
441 // it shrinks complex recursive structure types substantially in some cases.
442 TypeFinder(TP, NumberedTypes).Run(*M);
446 /// WriteTypeSymbolic - This attempts to write the specified type as a symbolic
447 /// type, iff there is an entry in the modules symbol table for the specified
448 /// type or one of it's component types.
450 void llvm::WriteTypeSymbolic(raw_ostream &OS, const Type *Ty, const Module *M) {
451 TypePrinting Printer;
452 std::vector<const Type*> NumberedTypes;
453 AddModuleTypesToPrinter(Printer, NumberedTypes, M);
454 Printer.print(Ty, OS);
457 //===----------------------------------------------------------------------===//
458 // SlotTracker Class: Enumerate slot numbers for unnamed values
459 //===----------------------------------------------------------------------===//
463 /// This class provides computation of slot numbers for LLVM Assembly writing.
467 /// ValueMap - A mapping of Values to slot numbers.
468 typedef DenseMap<const Value*, unsigned> ValueMap;
471 /// TheModule - The module for which we are holding slot numbers.
472 const Module* TheModule;
474 /// TheFunction - The function for which we are holding slot numbers.
475 const Function* TheFunction;
476 bool FunctionProcessed;
478 /// mMap - The TypePlanes map for the module level data.
482 /// fMap - The TypePlanes map for the function level data.
486 /// mdnMap - Map for MDNodes.
487 DenseMap<const MDNode*, unsigned> mdnMap;
490 /// Construct from a module
491 explicit SlotTracker(const Module *M);
492 /// Construct from a function, starting out in incorp state.
493 explicit SlotTracker(const Function *F);
495 /// Return the slot number of the specified value in it's type
496 /// plane. If something is not in the SlotTracker, return -1.
497 int getLocalSlot(const Value *V);
498 int getGlobalSlot(const GlobalValue *V);
499 int getMetadataSlot(const MDNode *N);
501 /// If you'd like to deal with a function instead of just a module, use
502 /// this method to get its data into the SlotTracker.
503 void incorporateFunction(const Function *F) {
505 FunctionProcessed = false;
508 /// After calling incorporateFunction, use this method to remove the
509 /// most recently incorporated function from the SlotTracker. This
510 /// will reset the state of the machine back to just the module contents.
511 void purgeFunction();
513 /// MDNode map iterators.
514 typedef DenseMap<const MDNode*, unsigned>::iterator mdn_iterator;
515 mdn_iterator mdn_begin() { return mdnMap.begin(); }
516 mdn_iterator mdn_end() { return mdnMap.end(); }
517 unsigned mdn_size() const { return mdnMap.size(); }
518 bool mdn_empty() const { return mdnMap.empty(); }
520 /// This function does the actual initialization.
521 inline void initialize();
523 // Implementation Details
525 /// CreateModuleSlot - Insert the specified GlobalValue* into the slot table.
526 void CreateModuleSlot(const GlobalValue *V);
528 /// CreateMetadataSlot - Insert the specified MDNode* into the slot table.
529 void CreateMetadataSlot(const MDNode *N);
531 /// CreateFunctionSlot - Insert the specified Value* into the slot table.
532 void CreateFunctionSlot(const Value *V);
534 /// Add all of the module level global variables (and their initializers)
535 /// and function declarations, but not the contents of those functions.
536 void processModule();
538 /// Add all of the functions arguments, basic blocks, and instructions.
539 void processFunction();
541 SlotTracker(const SlotTracker &); // DO NOT IMPLEMENT
542 void operator=(const SlotTracker &); // DO NOT IMPLEMENT
545 } // end anonymous namespace
548 static SlotTracker *createSlotTracker(const Value *V) {
549 if (const Argument *FA = dyn_cast<Argument>(V))
550 return new SlotTracker(FA->getParent());
552 if (const Instruction *I = dyn_cast<Instruction>(V))
553 return new SlotTracker(I->getParent()->getParent());
555 if (const BasicBlock *BB = dyn_cast<BasicBlock>(V))
556 return new SlotTracker(BB->getParent());
558 if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(V))
559 return new SlotTracker(GV->getParent());
561 if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(V))
562 return new SlotTracker(GA->getParent());
564 if (const Function *Func = dyn_cast<Function>(V))
565 return new SlotTracker(Func);
567 if (const MDNode *MD = dyn_cast<MDNode>(V)) {
568 if (!MD->isFunctionLocal())
569 return new SlotTracker(MD->getFunction());
571 return new SlotTracker((Function *)0);
578 #define ST_DEBUG(X) dbgs() << X
583 // Module level constructor. Causes the contents of the Module (sans functions)
584 // to be added to the slot table.
585 SlotTracker::SlotTracker(const Module *M)
586 : TheModule(M), TheFunction(0), FunctionProcessed(false),
587 mNext(0), fNext(0), mdnNext(0) {
590 // Function level constructor. Causes the contents of the Module and the one
591 // function provided to be added to the slot table.
592 SlotTracker::SlotTracker(const Function *F)
593 : TheModule(F ? F->getParent() : 0), TheFunction(F), FunctionProcessed(false),
594 mNext(0), fNext(0), mdnNext(0) {
597 inline void SlotTracker::initialize() {
600 TheModule = 0; ///< Prevent re-processing next time we're called.
603 if (TheFunction && !FunctionProcessed)
607 // Iterate through all the global variables, functions, and global
608 // variable initializers and create slots for them.
609 void SlotTracker::processModule() {
610 ST_DEBUG("begin processModule!\n");
612 // Add all of the unnamed global variables to the value table.
613 for (Module::const_global_iterator I = TheModule->global_begin(),
614 E = TheModule->global_end(); I != E; ++I) {
619 // Add metadata used by named metadata.
620 for (Module::const_named_metadata_iterator
621 I = TheModule->named_metadata_begin(),
622 E = TheModule->named_metadata_end(); I != E; ++I) {
623 const NamedMDNode *NMD = I;
624 for (unsigned i = 0, e = NMD->getNumOperands(); i != e; ++i)
625 CreateMetadataSlot(NMD->getOperand(i));
628 // Add all the unnamed functions to the table.
629 for (Module::const_iterator I = TheModule->begin(), E = TheModule->end();
634 ST_DEBUG("end processModule!\n");
637 // Process the arguments, basic blocks, and instructions of a function.
638 void SlotTracker::processFunction() {
639 ST_DEBUG("begin processFunction!\n");
642 // Add all the function arguments with no names.
643 for(Function::const_arg_iterator AI = TheFunction->arg_begin(),
644 AE = TheFunction->arg_end(); AI != AE; ++AI)
646 CreateFunctionSlot(AI);
648 ST_DEBUG("Inserting Instructions:\n");
650 SmallVector<std::pair<unsigned, MDNode*>, 4> MDForInst;
652 // Add all of the basic blocks and instructions with no names.
653 for (Function::const_iterator BB = TheFunction->begin(),
654 E = TheFunction->end(); BB != E; ++BB) {
656 CreateFunctionSlot(BB);
658 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I != E;
660 if (!I->getType()->isVoidTy() && !I->hasName())
661 CreateFunctionSlot(I);
663 // Intrinsics can directly use metadata. We allow direct calls to any
664 // llvm.foo function here, because the target may not be linked into the
666 if (const CallInst *CI = dyn_cast<CallInst>(I)) {
667 if (Function *F = CI->getCalledFunction())
668 if (F->getName().startswith("llvm."))
669 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
670 if (MDNode *N = dyn_cast_or_null<MDNode>(I->getOperand(i)))
671 CreateMetadataSlot(N);
674 // Process metadata attached with this instruction.
675 I->getAllMetadata(MDForInst);
676 for (unsigned i = 0, e = MDForInst.size(); i != e; ++i)
677 CreateMetadataSlot(MDForInst[i].second);
682 FunctionProcessed = true;
684 ST_DEBUG("end processFunction!\n");
687 /// Clean up after incorporating a function. This is the only way to get out of
688 /// the function incorporation state that affects get*Slot/Create*Slot. Function
689 /// incorporation state is indicated by TheFunction != 0.
690 void SlotTracker::purgeFunction() {
691 ST_DEBUG("begin purgeFunction!\n");
692 fMap.clear(); // Simply discard the function level map
694 FunctionProcessed = false;
695 ST_DEBUG("end purgeFunction!\n");
698 /// getGlobalSlot - Get the slot number of a global value.
699 int SlotTracker::getGlobalSlot(const GlobalValue *V) {
700 // Check for uninitialized state and do lazy initialization.
703 // Find the type plane in the module map
704 ValueMap::iterator MI = mMap.find(V);
705 return MI == mMap.end() ? -1 : (int)MI->second;
708 /// getMetadataSlot - Get the slot number of a MDNode.
709 int SlotTracker::getMetadataSlot(const MDNode *N) {
710 // Check for uninitialized state and do lazy initialization.
713 // Find the type plane in the module map
714 mdn_iterator MI = mdnMap.find(N);
715 return MI == mdnMap.end() ? -1 : (int)MI->second;
719 /// getLocalSlot - Get the slot number for a value that is local to a function.
720 int SlotTracker::getLocalSlot(const Value *V) {
721 assert(!isa<Constant>(V) && "Can't get a constant or global slot with this!");
723 // Check for uninitialized state and do lazy initialization.
726 ValueMap::iterator FI = fMap.find(V);
727 return FI == fMap.end() ? -1 : (int)FI->second;
731 /// CreateModuleSlot - Insert the specified GlobalValue* into the slot table.
732 void SlotTracker::CreateModuleSlot(const GlobalValue *V) {
733 assert(V && "Can't insert a null Value into SlotTracker!");
734 assert(!V->getType()->isVoidTy() && "Doesn't need a slot!");
735 assert(!V->hasName() && "Doesn't need a slot!");
737 unsigned DestSlot = mNext++;
740 ST_DEBUG(" Inserting value [" << V->getType() << "] = " << V << " slot=" <<
742 // G = Global, F = Function, A = Alias, o = other
743 ST_DEBUG((isa<GlobalVariable>(V) ? 'G' :
744 (isa<Function>(V) ? 'F' :
745 (isa<GlobalAlias>(V) ? 'A' : 'o'))) << "]\n");
748 /// CreateSlot - Create a new slot for the specified value if it has no name.
749 void SlotTracker::CreateFunctionSlot(const Value *V) {
750 assert(!V->getType()->isVoidTy() && !V->hasName() && "Doesn't need a slot!");
752 unsigned DestSlot = fNext++;
755 // G = Global, F = Function, o = other
756 ST_DEBUG(" Inserting value [" << V->getType() << "] = " << V << " slot=" <<
757 DestSlot << " [o]\n");
760 /// CreateModuleSlot - Insert the specified MDNode* into the slot table.
761 void SlotTracker::CreateMetadataSlot(const MDNode *N) {
762 assert(N && "Can't insert a null Value into SlotTracker!");
764 // Don't insert if N is a function-local metadata, these are always printed
766 if (!N->isFunctionLocal()) {
767 mdn_iterator I = mdnMap.find(N);
768 if (I != mdnMap.end())
771 unsigned DestSlot = mdnNext++;
772 mdnMap[N] = DestSlot;
775 // Recursively add any MDNodes referenced by operands.
776 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
777 if (const MDNode *Op = dyn_cast_or_null<MDNode>(N->getOperand(i)))
778 CreateMetadataSlot(Op);
781 //===----------------------------------------------------------------------===//
782 // AsmWriter Implementation
783 //===----------------------------------------------------------------------===//
785 static void WriteAsOperandInternal(raw_ostream &Out, const Value *V,
786 TypePrinting *TypePrinter,
787 SlotTracker *Machine,
788 const Module *Context);
792 static const char *getPredicateText(unsigned predicate) {
793 const char * pred = "unknown";
795 case FCmpInst::FCMP_FALSE: pred = "false"; break;
796 case FCmpInst::FCMP_OEQ: pred = "oeq"; break;
797 case FCmpInst::FCMP_OGT: pred = "ogt"; break;
798 case FCmpInst::FCMP_OGE: pred = "oge"; break;
799 case FCmpInst::FCMP_OLT: pred = "olt"; break;
800 case FCmpInst::FCMP_OLE: pred = "ole"; break;
801 case FCmpInst::FCMP_ONE: pred = "one"; break;
802 case FCmpInst::FCMP_ORD: pred = "ord"; break;
803 case FCmpInst::FCMP_UNO: pred = "uno"; break;
804 case FCmpInst::FCMP_UEQ: pred = "ueq"; break;
805 case FCmpInst::FCMP_UGT: pred = "ugt"; break;
806 case FCmpInst::FCMP_UGE: pred = "uge"; break;
807 case FCmpInst::FCMP_ULT: pred = "ult"; break;
808 case FCmpInst::FCMP_ULE: pred = "ule"; break;
809 case FCmpInst::FCMP_UNE: pred = "une"; break;
810 case FCmpInst::FCMP_TRUE: pred = "true"; break;
811 case ICmpInst::ICMP_EQ: pred = "eq"; break;
812 case ICmpInst::ICMP_NE: pred = "ne"; break;
813 case ICmpInst::ICMP_SGT: pred = "sgt"; break;
814 case ICmpInst::ICMP_SGE: pred = "sge"; break;
815 case ICmpInst::ICMP_SLT: pred = "slt"; break;
816 case ICmpInst::ICMP_SLE: pred = "sle"; break;
817 case ICmpInst::ICMP_UGT: pred = "ugt"; break;
818 case ICmpInst::ICMP_UGE: pred = "uge"; break;
819 case ICmpInst::ICMP_ULT: pred = "ult"; break;
820 case ICmpInst::ICMP_ULE: pred = "ule"; break;
826 static void WriteOptimizationInfo(raw_ostream &Out, const User *U) {
827 if (const OverflowingBinaryOperator *OBO =
828 dyn_cast<OverflowingBinaryOperator>(U)) {
829 if (OBO->hasNoUnsignedWrap())
831 if (OBO->hasNoSignedWrap())
833 } else if (const PossiblyExactOperator *Div =
834 dyn_cast<PossiblyExactOperator>(U)) {
837 } else if (const GEPOperator *GEP = dyn_cast<GEPOperator>(U)) {
838 if (GEP->isInBounds())
843 static void WriteConstantInternal(raw_ostream &Out, const Constant *CV,
844 TypePrinting &TypePrinter,
845 SlotTracker *Machine,
846 const Module *Context) {
847 if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV)) {
848 if (CI->getType()->isIntegerTy(1)) {
849 Out << (CI->getZExtValue() ? "true" : "false");
852 Out << CI->getValue();
856 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CV)) {
857 if (&CFP->getValueAPF().getSemantics() == &APFloat::IEEEdouble ||
858 &CFP->getValueAPF().getSemantics() == &APFloat::IEEEsingle) {
859 // We would like to output the FP constant value in exponential notation,
860 // but we cannot do this if doing so will lose precision. Check here to
861 // make sure that we only output it in exponential format if we can parse
862 // the value back and get the same value.
865 bool isDouble = &CFP->getValueAPF().getSemantics()==&APFloat::IEEEdouble;
866 double Val = isDouble ? CFP->getValueAPF().convertToDouble() :
867 CFP->getValueAPF().convertToFloat();
868 SmallString<128> StrVal;
869 raw_svector_ostream(StrVal) << Val;
871 // Check to make sure that the stringized number is not some string like
872 // "Inf" or NaN, that atof will accept, but the lexer will not. Check
873 // that the string matches the "[-+]?[0-9]" regex.
875 if ((StrVal[0] >= '0' && StrVal[0] <= '9') ||
876 ((StrVal[0] == '-' || StrVal[0] == '+') &&
877 (StrVal[1] >= '0' && StrVal[1] <= '9'))) {
878 // Reparse stringized version!
879 if (atof(StrVal.c_str()) == Val) {
884 // Otherwise we could not reparse it to exactly the same value, so we must
885 // output the string in hexadecimal format! Note that loading and storing
886 // floating point types changes the bits of NaNs on some hosts, notably
887 // x86, so we must not use these types.
888 assert(sizeof(double) == sizeof(uint64_t) &&
889 "assuming that double is 64 bits!");
891 APFloat apf = CFP->getValueAPF();
892 // Floats are represented in ASCII IR as double, convert.
894 apf.convert(APFloat::IEEEdouble, APFloat::rmNearestTiesToEven,
897 utohex_buffer(uint64_t(apf.bitcastToAPInt().getZExtValue()),
902 // Some form of long double. These appear as a magic letter identifying
903 // the type, then a fixed number of hex digits.
905 if (&CFP->getValueAPF().getSemantics() == &APFloat::x87DoubleExtended) {
907 // api needed to prevent premature destruction
908 APInt api = CFP->getValueAPF().bitcastToAPInt();
909 const uint64_t* p = api.getRawData();
910 uint64_t word = p[1];
912 int width = api.getBitWidth();
913 for (int j=0; j<width; j+=4, shiftcount-=4) {
914 unsigned int nibble = (word>>shiftcount) & 15;
916 Out << (unsigned char)(nibble + '0');
918 Out << (unsigned char)(nibble - 10 + 'A');
919 if (shiftcount == 0 && j+4 < width) {
923 shiftcount = width-j-4;
927 } else if (&CFP->getValueAPF().getSemantics() == &APFloat::IEEEquad)
929 else if (&CFP->getValueAPF().getSemantics() == &APFloat::PPCDoubleDouble)
932 llvm_unreachable("Unsupported floating point type");
933 // api needed to prevent premature destruction
934 APInt api = CFP->getValueAPF().bitcastToAPInt();
935 const uint64_t* p = api.getRawData();
938 int width = api.getBitWidth();
939 for (int j=0; j<width; j+=4, shiftcount-=4) {
940 unsigned int nibble = (word>>shiftcount) & 15;
942 Out << (unsigned char)(nibble + '0');
944 Out << (unsigned char)(nibble - 10 + 'A');
945 if (shiftcount == 0 && j+4 < width) {
949 shiftcount = width-j-4;
955 if (isa<ConstantAggregateZero>(CV)) {
956 Out << "zeroinitializer";
960 if (const BlockAddress *BA = dyn_cast<BlockAddress>(CV)) {
961 Out << "blockaddress(";
962 WriteAsOperandInternal(Out, BA->getFunction(), &TypePrinter, Machine,
965 WriteAsOperandInternal(Out, BA->getBasicBlock(), &TypePrinter, Machine,
971 if (const ConstantArray *CA = dyn_cast<ConstantArray>(CV)) {
972 // As a special case, print the array as a string if it is an array of
973 // i8 with ConstantInt values.
975 const Type *ETy = CA->getType()->getElementType();
976 if (CA->isString()) {
978 PrintEscapedString(CA->getAsString(), Out);
980 } else { // Cannot output in string format...
982 if (CA->getNumOperands()) {
983 TypePrinter.print(ETy, Out);
985 WriteAsOperandInternal(Out, CA->getOperand(0),
986 &TypePrinter, Machine,
988 for (unsigned i = 1, e = CA->getNumOperands(); i != e; ++i) {
990 TypePrinter.print(ETy, Out);
992 WriteAsOperandInternal(Out, CA->getOperand(i), &TypePrinter, Machine,
1001 if (const ConstantStruct *CS = dyn_cast<ConstantStruct>(CV)) {
1002 if (CS->getType()->isPacked())
1005 unsigned N = CS->getNumOperands();
1008 TypePrinter.print(CS->getOperand(0)->getType(), Out);
1011 WriteAsOperandInternal(Out, CS->getOperand(0), &TypePrinter, Machine,
1014 for (unsigned i = 1; i < N; i++) {
1016 TypePrinter.print(CS->getOperand(i)->getType(), Out);
1019 WriteAsOperandInternal(Out, CS->getOperand(i), &TypePrinter, Machine,
1026 if (CS->getType()->isPacked())
1031 if (const ConstantVector *CP = dyn_cast<ConstantVector>(CV)) {
1032 const Type *ETy = CP->getType()->getElementType();
1033 assert(CP->getNumOperands() > 0 &&
1034 "Number of operands for a PackedConst must be > 0");
1036 TypePrinter.print(ETy, Out);
1038 WriteAsOperandInternal(Out, CP->getOperand(0), &TypePrinter, Machine,
1040 for (unsigned i = 1, e = CP->getNumOperands(); i != e; ++i) {
1042 TypePrinter.print(ETy, Out);
1044 WriteAsOperandInternal(Out, CP->getOperand(i), &TypePrinter, Machine,
1051 if (isa<ConstantPointerNull>(CV)) {
1056 if (isa<UndefValue>(CV)) {
1061 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV)) {
1062 Out << CE->getOpcodeName();
1063 WriteOptimizationInfo(Out, CE);
1064 if (CE->isCompare())
1065 Out << ' ' << getPredicateText(CE->getPredicate());
1068 for (User::const_op_iterator OI=CE->op_begin(); OI != CE->op_end(); ++OI) {
1069 TypePrinter.print((*OI)->getType(), Out);
1071 WriteAsOperandInternal(Out, *OI, &TypePrinter, Machine, Context);
1072 if (OI+1 != CE->op_end())
1076 if (CE->hasIndices()) {
1077 ArrayRef<unsigned> Indices = CE->getIndices();
1078 for (unsigned i = 0, e = Indices.size(); i != e; ++i)
1079 Out << ", " << Indices[i];
1084 TypePrinter.print(CE->getType(), Out);
1091 Out << "<placeholder or erroneous Constant>";
1094 static void WriteMDNodeBodyInternal(raw_ostream &Out, const MDNode *Node,
1095 TypePrinting *TypePrinter,
1096 SlotTracker *Machine,
1097 const Module *Context) {
1099 for (unsigned mi = 0, me = Node->getNumOperands(); mi != me; ++mi) {
1100 const Value *V = Node->getOperand(mi);
1104 TypePrinter->print(V->getType(), Out);
1106 WriteAsOperandInternal(Out, Node->getOperand(mi),
1107 TypePrinter, Machine, Context);
1117 /// WriteAsOperand - Write the name of the specified value out to the specified
1118 /// ostream. This can be useful when you just want to print int %reg126, not
1119 /// the whole instruction that generated it.
1121 static void WriteAsOperandInternal(raw_ostream &Out, const Value *V,
1122 TypePrinting *TypePrinter,
1123 SlotTracker *Machine,
1124 const Module *Context) {
1126 PrintLLVMName(Out, V);
1130 const Constant *CV = dyn_cast<Constant>(V);
1131 if (CV && !isa<GlobalValue>(CV)) {
1132 assert(TypePrinter && "Constants require TypePrinting!");
1133 WriteConstantInternal(Out, CV, *TypePrinter, Machine, Context);
1137 if (const InlineAsm *IA = dyn_cast<InlineAsm>(V)) {
1139 if (IA->hasSideEffects())
1140 Out << "sideeffect ";
1141 if (IA->isAlignStack())
1142 Out << "alignstack ";
1144 PrintEscapedString(IA->getAsmString(), Out);
1146 PrintEscapedString(IA->getConstraintString(), Out);
1151 if (const MDNode *N = dyn_cast<MDNode>(V)) {
1152 if (N->isFunctionLocal()) {
1153 // Print metadata inline, not via slot reference number.
1154 WriteMDNodeBodyInternal(Out, N, TypePrinter, Machine, Context);
1159 if (N->isFunctionLocal())
1160 Machine = new SlotTracker(N->getFunction());
1162 Machine = new SlotTracker(Context);
1164 int Slot = Machine->getMetadataSlot(N);
1172 if (const MDString *MDS = dyn_cast<MDString>(V)) {
1174 PrintEscapedString(MDS->getString(), Out);
1179 if (V->getValueID() == Value::PseudoSourceValueVal ||
1180 V->getValueID() == Value::FixedStackPseudoSourceValueVal) {
1188 if (const GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
1189 Slot = Machine->getGlobalSlot(GV);
1192 Slot = Machine->getLocalSlot(V);
1195 Machine = createSlotTracker(V);
1197 if (const GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
1198 Slot = Machine->getGlobalSlot(GV);
1201 Slot = Machine->getLocalSlot(V);
1210 Out << Prefix << Slot;
1215 void llvm::WriteAsOperand(raw_ostream &Out, const Value *V,
1216 bool PrintType, const Module *Context) {
1218 // Fast path: Don't construct and populate a TypePrinting object if we
1219 // won't be needing any types printed.
1221 ((!isa<Constant>(V) && !isa<MDNode>(V)) ||
1222 V->hasName() || isa<GlobalValue>(V))) {
1223 WriteAsOperandInternal(Out, V, 0, 0, Context);
1227 if (Context == 0) Context = getModuleFromVal(V);
1229 TypePrinting TypePrinter;
1230 std::vector<const Type*> NumberedTypes;
1231 AddModuleTypesToPrinter(TypePrinter, NumberedTypes, Context);
1233 TypePrinter.print(V->getType(), Out);
1237 WriteAsOperandInternal(Out, V, &TypePrinter, 0, Context);
1242 class AssemblyWriter {
1243 formatted_raw_ostream &Out;
1244 SlotTracker &Machine;
1245 const Module *TheModule;
1246 TypePrinting TypePrinter;
1247 AssemblyAnnotationWriter *AnnotationWriter;
1248 std::vector<const Type*> NumberedTypes;
1251 inline AssemblyWriter(formatted_raw_ostream &o, SlotTracker &Mac,
1253 AssemblyAnnotationWriter *AAW)
1254 : Out(o), Machine(Mac), TheModule(M), AnnotationWriter(AAW) {
1255 AddModuleTypesToPrinter(TypePrinter, NumberedTypes, M);
1258 void printMDNodeBody(const MDNode *MD);
1259 void printNamedMDNode(const NamedMDNode *NMD);
1261 void printModule(const Module *M);
1263 void writeOperand(const Value *Op, bool PrintType);
1264 void writeParamOperand(const Value *Operand, Attributes Attrs);
1266 void writeAllMDNodes();
1268 void printTypeSymbolTable(const TypeSymbolTable &ST);
1269 void printGlobal(const GlobalVariable *GV);
1270 void printAlias(const GlobalAlias *GV);
1271 void printFunction(const Function *F);
1272 void printArgument(const Argument *FA, Attributes Attrs);
1273 void printBasicBlock(const BasicBlock *BB);
1274 void printInstruction(const Instruction &I);
1277 // printInfoComment - Print a little comment after the instruction indicating
1278 // which slot it occupies.
1279 void printInfoComment(const Value &V);
1281 } // end of anonymous namespace
1283 void AssemblyWriter::writeOperand(const Value *Operand, bool PrintType) {
1285 Out << "<null operand!>";
1289 TypePrinter.print(Operand->getType(), Out);
1292 WriteAsOperandInternal(Out, Operand, &TypePrinter, &Machine, TheModule);
1295 void AssemblyWriter::writeParamOperand(const Value *Operand,
1298 Out << "<null operand!>";
1303 TypePrinter.print(Operand->getType(), Out);
1304 // Print parameter attributes list
1305 if (Attrs != Attribute::None)
1306 Out << ' ' << Attribute::getAsString(Attrs);
1308 // Print the operand
1309 WriteAsOperandInternal(Out, Operand, &TypePrinter, &Machine, TheModule);
1312 void AssemblyWriter::printModule(const Module *M) {
1313 if (!M->getModuleIdentifier().empty() &&
1314 // Don't print the ID if it will start a new line (which would
1315 // require a comment char before it).
1316 M->getModuleIdentifier().find('\n') == std::string::npos)
1317 Out << "; ModuleID = '" << M->getModuleIdentifier() << "'\n";
1319 if (!M->getDataLayout().empty())
1320 Out << "target datalayout = \"" << M->getDataLayout() << "\"\n";
1321 if (!M->getTargetTriple().empty())
1322 Out << "target triple = \"" << M->getTargetTriple() << "\"\n";
1324 if (!M->getModuleInlineAsm().empty()) {
1325 // Split the string into lines, to make it easier to read the .ll file.
1326 std::string Asm = M->getModuleInlineAsm();
1328 size_t NewLine = Asm.find_first_of('\n', CurPos);
1330 while (NewLine != std::string::npos) {
1331 // We found a newline, print the portion of the asm string from the
1332 // last newline up to this newline.
1333 Out << "module asm \"";
1334 PrintEscapedString(std::string(Asm.begin()+CurPos, Asm.begin()+NewLine),
1338 NewLine = Asm.find_first_of('\n', CurPos);
1340 std::string rest(Asm.begin()+CurPos, Asm.end());
1341 if (!rest.empty()) {
1342 Out << "module asm \"";
1343 PrintEscapedString(rest, Out);
1348 // Loop over the dependent libraries and emit them.
1349 Module::lib_iterator LI = M->lib_begin();
1350 Module::lib_iterator LE = M->lib_end();
1353 Out << "deplibs = [ ";
1355 Out << '"' << *LI << '"';
1363 // Loop over the symbol table, emitting all id'd types.
1364 if (!M->getTypeSymbolTable().empty() || !NumberedTypes.empty()) Out << '\n';
1365 printTypeSymbolTable(M->getTypeSymbolTable());
1367 // Output all globals.
1368 if (!M->global_empty()) Out << '\n';
1369 for (Module::const_global_iterator I = M->global_begin(), E = M->global_end();
1373 // Output all aliases.
1374 if (!M->alias_empty()) Out << "\n";
1375 for (Module::const_alias_iterator I = M->alias_begin(), E = M->alias_end();
1379 // Output all of the functions.
1380 for (Module::const_iterator I = M->begin(), E = M->end(); I != E; ++I)
1383 // Output named metadata.
1384 if (!M->named_metadata_empty()) Out << '\n';
1386 for (Module::const_named_metadata_iterator I = M->named_metadata_begin(),
1387 E = M->named_metadata_end(); I != E; ++I)
1388 printNamedMDNode(I);
1391 if (!Machine.mdn_empty()) {
1397 void AssemblyWriter::printNamedMDNode(const NamedMDNode *NMD) {
1398 Out << "!" << NMD->getName() << " = !{";
1399 for (unsigned i = 0, e = NMD->getNumOperands(); i != e; ++i) {
1401 int Slot = Machine.getMetadataSlot(NMD->getOperand(i));
1411 static void PrintLinkage(GlobalValue::LinkageTypes LT,
1412 formatted_raw_ostream &Out) {
1414 case GlobalValue::ExternalLinkage: break;
1415 case GlobalValue::PrivateLinkage: Out << "private "; break;
1416 case GlobalValue::LinkerPrivateLinkage: Out << "linker_private "; break;
1417 case GlobalValue::LinkerPrivateWeakLinkage:
1418 Out << "linker_private_weak ";
1420 case GlobalValue::LinkerPrivateWeakDefAutoLinkage:
1421 Out << "linker_private_weak_def_auto ";
1423 case GlobalValue::InternalLinkage: Out << "internal "; break;
1424 case GlobalValue::LinkOnceAnyLinkage: Out << "linkonce "; break;
1425 case GlobalValue::LinkOnceODRLinkage: Out << "linkonce_odr "; break;
1426 case GlobalValue::WeakAnyLinkage: Out << "weak "; break;
1427 case GlobalValue::WeakODRLinkage: Out << "weak_odr "; break;
1428 case GlobalValue::CommonLinkage: Out << "common "; break;
1429 case GlobalValue::AppendingLinkage: Out << "appending "; break;
1430 case GlobalValue::DLLImportLinkage: Out << "dllimport "; break;
1431 case GlobalValue::DLLExportLinkage: Out << "dllexport "; break;
1432 case GlobalValue::ExternalWeakLinkage: Out << "extern_weak "; break;
1433 case GlobalValue::AvailableExternallyLinkage:
1434 Out << "available_externally ";
1440 static void PrintVisibility(GlobalValue::VisibilityTypes Vis,
1441 formatted_raw_ostream &Out) {
1443 case GlobalValue::DefaultVisibility: break;
1444 case GlobalValue::HiddenVisibility: Out << "hidden "; break;
1445 case GlobalValue::ProtectedVisibility: Out << "protected "; break;
1449 void AssemblyWriter::printGlobal(const GlobalVariable *GV) {
1450 if (GV->isMaterializable())
1451 Out << "; Materializable\n";
1453 WriteAsOperandInternal(Out, GV, &TypePrinter, &Machine, GV->getParent());
1456 if (!GV->hasInitializer() && GV->hasExternalLinkage())
1459 PrintLinkage(GV->getLinkage(), Out);
1460 PrintVisibility(GV->getVisibility(), Out);
1462 if (GV->isThreadLocal()) Out << "thread_local ";
1463 if (unsigned AddressSpace = GV->getType()->getAddressSpace())
1464 Out << "addrspace(" << AddressSpace << ") ";
1465 if (GV->hasUnnamedAddr()) Out << "unnamed_addr ";
1466 Out << (GV->isConstant() ? "constant " : "global ");
1467 TypePrinter.print(GV->getType()->getElementType(), Out);
1469 if (GV->hasInitializer()) {
1471 writeOperand(GV->getInitializer(), false);
1474 if (GV->hasSection()) {
1475 Out << ", section \"";
1476 PrintEscapedString(GV->getSection(), Out);
1479 if (GV->getAlignment())
1480 Out << ", align " << GV->getAlignment();
1482 printInfoComment(*GV);
1486 void AssemblyWriter::printAlias(const GlobalAlias *GA) {
1487 if (GA->isMaterializable())
1488 Out << "; Materializable\n";
1490 // Don't crash when dumping partially built GA
1492 Out << "<<nameless>> = ";
1494 PrintLLVMName(Out, GA);
1497 PrintVisibility(GA->getVisibility(), Out);
1501 PrintLinkage(GA->getLinkage(), Out);
1503 const Constant *Aliasee = GA->getAliasee();
1505 if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(Aliasee)) {
1506 TypePrinter.print(GV->getType(), Out);
1508 PrintLLVMName(Out, GV);
1509 } else if (const Function *F = dyn_cast<Function>(Aliasee)) {
1510 TypePrinter.print(F->getFunctionType(), Out);
1513 WriteAsOperandInternal(Out, F, &TypePrinter, &Machine, F->getParent());
1514 } else if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(Aliasee)) {
1515 TypePrinter.print(GA->getType(), Out);
1517 PrintLLVMName(Out, GA);
1519 const ConstantExpr *CE = cast<ConstantExpr>(Aliasee);
1520 // The only valid GEP is an all zero GEP.
1521 assert((CE->getOpcode() == Instruction::BitCast ||
1522 CE->getOpcode() == Instruction::GetElementPtr) &&
1523 "Unsupported aliasee");
1524 writeOperand(CE, false);
1527 printInfoComment(*GA);
1531 void AssemblyWriter::printTypeSymbolTable(const TypeSymbolTable &ST) {
1532 // Emit all numbered types.
1533 for (unsigned i = 0, e = NumberedTypes.size(); i != e; ++i) {
1534 Out << '%' << i << " = type ";
1536 // Make sure we print out at least one level of the type structure, so
1537 // that we do not get %2 = type %2
1538 TypePrinter.printAtLeastOneLevel(NumberedTypes[i], Out);
1542 // Print the named types.
1543 for (TypeSymbolTable::const_iterator TI = ST.begin(), TE = ST.end();
1545 PrintLLVMName(Out, TI->first, LocalPrefix);
1548 // Make sure we print out at least one level of the type structure, so
1549 // that we do not get %FILE = type %FILE
1550 TypePrinter.printAtLeastOneLevel(TI->second, Out);
1555 /// printFunction - Print all aspects of a function.
1557 void AssemblyWriter::printFunction(const Function *F) {
1558 // Print out the return type and name.
1561 if (AnnotationWriter) AnnotationWriter->emitFunctionAnnot(F, Out);
1563 if (F->isMaterializable())
1564 Out << "; Materializable\n";
1566 if (F->isDeclaration())
1571 PrintLinkage(F->getLinkage(), Out);
1572 PrintVisibility(F->getVisibility(), Out);
1574 // Print the calling convention.
1575 switch (F->getCallingConv()) {
1576 case CallingConv::C: break; // default
1577 case CallingConv::Fast: Out << "fastcc "; break;
1578 case CallingConv::Cold: Out << "coldcc "; break;
1579 case CallingConv::X86_StdCall: Out << "x86_stdcallcc "; break;
1580 case CallingConv::X86_FastCall: Out << "x86_fastcallcc "; break;
1581 case CallingConv::X86_ThisCall: Out << "x86_thiscallcc "; break;
1582 case CallingConv::ARM_APCS: Out << "arm_apcscc "; break;
1583 case CallingConv::ARM_AAPCS: Out << "arm_aapcscc "; break;
1584 case CallingConv::ARM_AAPCS_VFP:Out << "arm_aapcs_vfpcc "; break;
1585 case CallingConv::MSP430_INTR: Out << "msp430_intrcc "; break;
1586 case CallingConv::PTX_Kernel: Out << "ptx_kernel "; break;
1587 case CallingConv::PTX_Device: Out << "ptx_device "; break;
1588 default: Out << "cc" << F->getCallingConv() << " "; break;
1591 const FunctionType *FT = F->getFunctionType();
1592 const AttrListPtr &Attrs = F->getAttributes();
1593 Attributes RetAttrs = Attrs.getRetAttributes();
1594 if (RetAttrs != Attribute::None)
1595 Out << Attribute::getAsString(Attrs.getRetAttributes()) << ' ';
1596 TypePrinter.print(F->getReturnType(), Out);
1598 WriteAsOperandInternal(Out, F, &TypePrinter, &Machine, F->getParent());
1600 Machine.incorporateFunction(F);
1602 // Loop over the arguments, printing them...
1605 if (!F->isDeclaration()) {
1606 // If this isn't a declaration, print the argument names as well.
1607 for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
1609 // Insert commas as we go... the first arg doesn't get a comma
1610 if (I != F->arg_begin()) Out << ", ";
1611 printArgument(I, Attrs.getParamAttributes(Idx));
1615 // Otherwise, print the types from the function type.
1616 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
1617 // Insert commas as we go... the first arg doesn't get a comma
1621 TypePrinter.print(FT->getParamType(i), Out);
1623 Attributes ArgAttrs = Attrs.getParamAttributes(i+1);
1624 if (ArgAttrs != Attribute::None)
1625 Out << ' ' << Attribute::getAsString(ArgAttrs);
1629 // Finish printing arguments...
1630 if (FT->isVarArg()) {
1631 if (FT->getNumParams()) Out << ", ";
1632 Out << "..."; // Output varargs portion of signature!
1635 if (F->hasUnnamedAddr())
1636 Out << " unnamed_addr";
1637 Attributes FnAttrs = Attrs.getFnAttributes();
1638 if (FnAttrs != Attribute::None)
1639 Out << ' ' << Attribute::getAsString(Attrs.getFnAttributes());
1640 if (F->hasSection()) {
1641 Out << " section \"";
1642 PrintEscapedString(F->getSection(), Out);
1645 if (F->getAlignment())
1646 Out << " align " << F->getAlignment();
1648 Out << " gc \"" << F->getGC() << '"';
1649 if (F->isDeclaration()) {
1653 // Output all of the function's basic blocks.
1654 for (Function::const_iterator I = F->begin(), E = F->end(); I != E; ++I)
1660 Machine.purgeFunction();
1663 /// printArgument - This member is called for every argument that is passed into
1664 /// the function. Simply print it out
1666 void AssemblyWriter::printArgument(const Argument *Arg,
1669 TypePrinter.print(Arg->getType(), Out);
1671 // Output parameter attributes list
1672 if (Attrs != Attribute::None)
1673 Out << ' ' << Attribute::getAsString(Attrs);
1675 // Output name, if available...
1676 if (Arg->hasName()) {
1678 PrintLLVMName(Out, Arg);
1682 /// printBasicBlock - This member is called for each basic block in a method.
1684 void AssemblyWriter::printBasicBlock(const BasicBlock *BB) {
1685 if (BB->hasName()) { // Print out the label if it exists...
1687 PrintLLVMName(Out, BB->getName(), LabelPrefix);
1689 } else if (!BB->use_empty()) { // Don't print block # of no uses...
1690 Out << "\n; <label>:";
1691 int Slot = Machine.getLocalSlot(BB);
1698 if (BB->getParent() == 0) {
1699 Out.PadToColumn(50);
1700 Out << "; Error: Block without parent!";
1701 } else if (BB != &BB->getParent()->getEntryBlock()) { // Not the entry block?
1702 // Output predecessors for the block.
1703 Out.PadToColumn(50);
1705 const_pred_iterator PI = pred_begin(BB), PE = pred_end(BB);
1708 Out << " No predecessors!";
1711 writeOperand(*PI, false);
1712 for (++PI; PI != PE; ++PI) {
1714 writeOperand(*PI, false);
1721 if (AnnotationWriter) AnnotationWriter->emitBasicBlockStartAnnot(BB, Out);
1723 // Output all of the instructions in the basic block...
1724 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I != E; ++I) {
1725 printInstruction(*I);
1729 if (AnnotationWriter) AnnotationWriter->emitBasicBlockEndAnnot(BB, Out);
1732 /// printInfoComment - Print a little comment after the instruction indicating
1733 /// which slot it occupies.
1735 void AssemblyWriter::printInfoComment(const Value &V) {
1736 if (AnnotationWriter) {
1737 AnnotationWriter->printInfoComment(V, Out);
1742 // This member is called for each Instruction in a function..
1743 void AssemblyWriter::printInstruction(const Instruction &I) {
1744 if (AnnotationWriter) AnnotationWriter->emitInstructionAnnot(&I, Out);
1746 // Print out indentation for an instruction.
1749 // Print out name if it exists...
1751 PrintLLVMName(Out, &I);
1753 } else if (!I.getType()->isVoidTy()) {
1754 // Print out the def slot taken.
1755 int SlotNum = Machine.getLocalSlot(&I);
1757 Out << "<badref> = ";
1759 Out << '%' << SlotNum << " = ";
1762 // If this is a volatile load or store, print out the volatile marker.
1763 if ((isa<LoadInst>(I) && cast<LoadInst>(I).isVolatile()) ||
1764 (isa<StoreInst>(I) && cast<StoreInst>(I).isVolatile())) {
1766 } else if (isa<CallInst>(I) && cast<CallInst>(I).isTailCall()) {
1767 // If this is a call, check if it's a tail call.
1771 // Print out the opcode...
1772 Out << I.getOpcodeName();
1774 // Print out optimization information.
1775 WriteOptimizationInfo(Out, &I);
1777 // Print out the compare instruction predicates
1778 if (const CmpInst *CI = dyn_cast<CmpInst>(&I))
1779 Out << ' ' << getPredicateText(CI->getPredicate());
1781 // Print out the type of the operands...
1782 const Value *Operand = I.getNumOperands() ? I.getOperand(0) : 0;
1784 // Special case conditional branches to swizzle the condition out to the front
1785 if (isa<BranchInst>(I) && cast<BranchInst>(I).isConditional()) {
1786 BranchInst &BI(cast<BranchInst>(I));
1788 writeOperand(BI.getCondition(), true);
1790 writeOperand(BI.getSuccessor(0), true);
1792 writeOperand(BI.getSuccessor(1), true);
1794 } else if (isa<SwitchInst>(I)) {
1795 // Special case switch instruction to get formatting nice and correct.
1797 writeOperand(Operand , true);
1799 writeOperand(I.getOperand(1), true);
1802 for (unsigned op = 2, Eop = I.getNumOperands(); op < Eop; op += 2) {
1804 writeOperand(I.getOperand(op ), true);
1806 writeOperand(I.getOperand(op+1), true);
1809 } else if (isa<IndirectBrInst>(I)) {
1810 // Special case indirectbr instruction to get formatting nice and correct.
1812 writeOperand(Operand, true);
1815 for (unsigned i = 1, e = I.getNumOperands(); i != e; ++i) {
1818 writeOperand(I.getOperand(i), true);
1821 } else if (isa<PHINode>(I)) {
1823 TypePrinter.print(I.getType(), Out);
1826 for (unsigned op = 0, Eop = I.getNumOperands(); op < Eop; op += 2) {
1827 if (op) Out << ", ";
1829 writeOperand(I.getOperand(op ), false); Out << ", ";
1830 writeOperand(I.getOperand(op+1), false); Out << " ]";
1832 } else if (const ExtractValueInst *EVI = dyn_cast<ExtractValueInst>(&I)) {
1834 writeOperand(I.getOperand(0), true);
1835 for (const unsigned *i = EVI->idx_begin(), *e = EVI->idx_end(); i != e; ++i)
1837 } else if (const InsertValueInst *IVI = dyn_cast<InsertValueInst>(&I)) {
1839 writeOperand(I.getOperand(0), true); Out << ", ";
1840 writeOperand(I.getOperand(1), true);
1841 for (const unsigned *i = IVI->idx_begin(), *e = IVI->idx_end(); i != e; ++i)
1843 } else if (isa<ReturnInst>(I) && !Operand) {
1845 } else if (const CallInst *CI = dyn_cast<CallInst>(&I)) {
1846 // Print the calling convention being used.
1847 switch (CI->getCallingConv()) {
1848 case CallingConv::C: break; // default
1849 case CallingConv::Fast: Out << " fastcc"; break;
1850 case CallingConv::Cold: Out << " coldcc"; break;
1851 case CallingConv::X86_StdCall: Out << " x86_stdcallcc"; break;
1852 case CallingConv::X86_FastCall: Out << " x86_fastcallcc"; break;
1853 case CallingConv::X86_ThisCall: Out << " x86_thiscallcc"; break;
1854 case CallingConv::ARM_APCS: Out << " arm_apcscc "; break;
1855 case CallingConv::ARM_AAPCS: Out << " arm_aapcscc "; break;
1856 case CallingConv::ARM_AAPCS_VFP:Out << " arm_aapcs_vfpcc "; break;
1857 case CallingConv::MSP430_INTR: Out << " msp430_intrcc "; break;
1858 case CallingConv::PTX_Kernel: Out << " ptx_kernel"; break;
1859 case CallingConv::PTX_Device: Out << " ptx_device"; break;
1860 default: Out << " cc" << CI->getCallingConv(); break;
1863 Operand = CI->getCalledValue();
1864 const PointerType *PTy = cast<PointerType>(Operand->getType());
1865 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
1866 const Type *RetTy = FTy->getReturnType();
1867 const AttrListPtr &PAL = CI->getAttributes();
1869 if (PAL.getRetAttributes() != Attribute::None)
1870 Out << ' ' << Attribute::getAsString(PAL.getRetAttributes());
1872 // If possible, print out the short form of the call instruction. We can
1873 // only do this if the first argument is a pointer to a nonvararg function,
1874 // and if the return type is not a pointer to a function.
1877 if (!FTy->isVarArg() &&
1878 (!RetTy->isPointerTy() ||
1879 !cast<PointerType>(RetTy)->getElementType()->isFunctionTy())) {
1880 TypePrinter.print(RetTy, Out);
1882 writeOperand(Operand, false);
1884 writeOperand(Operand, true);
1887 for (unsigned op = 0, Eop = CI->getNumArgOperands(); op < Eop; ++op) {
1890 writeParamOperand(CI->getArgOperand(op), PAL.getParamAttributes(op + 1));
1893 if (PAL.getFnAttributes() != Attribute::None)
1894 Out << ' ' << Attribute::getAsString(PAL.getFnAttributes());
1895 } else if (const InvokeInst *II = dyn_cast<InvokeInst>(&I)) {
1896 Operand = II->getCalledValue();
1897 const PointerType *PTy = cast<PointerType>(Operand->getType());
1898 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
1899 const Type *RetTy = FTy->getReturnType();
1900 const AttrListPtr &PAL = II->getAttributes();
1902 // Print the calling convention being used.
1903 switch (II->getCallingConv()) {
1904 case CallingConv::C: break; // default
1905 case CallingConv::Fast: Out << " fastcc"; break;
1906 case CallingConv::Cold: Out << " coldcc"; break;
1907 case CallingConv::X86_StdCall: Out << " x86_stdcallcc"; break;
1908 case CallingConv::X86_FastCall: Out << " x86_fastcallcc"; break;
1909 case CallingConv::X86_ThisCall: Out << " x86_thiscallcc"; break;
1910 case CallingConv::ARM_APCS: Out << " arm_apcscc "; break;
1911 case CallingConv::ARM_AAPCS: Out << " arm_aapcscc "; break;
1912 case CallingConv::ARM_AAPCS_VFP:Out << " arm_aapcs_vfpcc "; break;
1913 case CallingConv::MSP430_INTR: Out << " msp430_intrcc "; break;
1914 case CallingConv::PTX_Kernel: Out << " ptx_kernel"; break;
1915 case CallingConv::PTX_Device: Out << " ptx_device"; break;
1916 default: Out << " cc" << II->getCallingConv(); break;
1919 if (PAL.getRetAttributes() != Attribute::None)
1920 Out << ' ' << Attribute::getAsString(PAL.getRetAttributes());
1922 // If possible, print out the short form of the invoke instruction. We can
1923 // only do this if the first argument is a pointer to a nonvararg function,
1924 // and if the return type is not a pointer to a function.
1927 if (!FTy->isVarArg() &&
1928 (!RetTy->isPointerTy() ||
1929 !cast<PointerType>(RetTy)->getElementType()->isFunctionTy())) {
1930 TypePrinter.print(RetTy, Out);
1932 writeOperand(Operand, false);
1934 writeOperand(Operand, true);
1937 for (unsigned op = 0, Eop = II->getNumArgOperands(); op < Eop; ++op) {
1940 writeParamOperand(II->getArgOperand(op), PAL.getParamAttributes(op + 1));
1944 if (PAL.getFnAttributes() != Attribute::None)
1945 Out << ' ' << Attribute::getAsString(PAL.getFnAttributes());
1948 writeOperand(II->getNormalDest(), true);
1950 writeOperand(II->getUnwindDest(), true);
1952 } else if (const AllocaInst *AI = dyn_cast<AllocaInst>(&I)) {
1954 TypePrinter.print(AI->getType()->getElementType(), Out);
1955 if (!AI->getArraySize() || AI->isArrayAllocation()) {
1957 writeOperand(AI->getArraySize(), true);
1959 if (AI->getAlignment()) {
1960 Out << ", align " << AI->getAlignment();
1962 } else if (isa<CastInst>(I)) {
1965 writeOperand(Operand, true); // Work with broken code
1968 TypePrinter.print(I.getType(), Out);
1969 } else if (isa<VAArgInst>(I)) {
1972 writeOperand(Operand, true); // Work with broken code
1975 TypePrinter.print(I.getType(), Out);
1976 } else if (Operand) { // Print the normal way.
1978 // PrintAllTypes - Instructions who have operands of all the same type
1979 // omit the type from all but the first operand. If the instruction has
1980 // different type operands (for example br), then they are all printed.
1981 bool PrintAllTypes = false;
1982 const Type *TheType = Operand->getType();
1984 // Select, Store and ShuffleVector always print all types.
1985 if (isa<SelectInst>(I) || isa<StoreInst>(I) || isa<ShuffleVectorInst>(I)
1986 || isa<ReturnInst>(I)) {
1987 PrintAllTypes = true;
1989 for (unsigned i = 1, E = I.getNumOperands(); i != E; ++i) {
1990 Operand = I.getOperand(i);
1991 // note that Operand shouldn't be null, but the test helps make dump()
1992 // more tolerant of malformed IR
1993 if (Operand && Operand->getType() != TheType) {
1994 PrintAllTypes = true; // We have differing types! Print them all!
2000 if (!PrintAllTypes) {
2002 TypePrinter.print(TheType, Out);
2006 for (unsigned i = 0, E = I.getNumOperands(); i != E; ++i) {
2008 writeOperand(I.getOperand(i), PrintAllTypes);
2012 // Print post operand alignment for load/store.
2013 if (isa<LoadInst>(I) && cast<LoadInst>(I).getAlignment()) {
2014 Out << ", align " << cast<LoadInst>(I).getAlignment();
2015 } else if (isa<StoreInst>(I) && cast<StoreInst>(I).getAlignment()) {
2016 Out << ", align " << cast<StoreInst>(I).getAlignment();
2019 // Print Metadata info.
2020 SmallVector<std::pair<unsigned, MDNode*>, 4> InstMD;
2021 I.getAllMetadata(InstMD);
2022 if (!InstMD.empty()) {
2023 SmallVector<StringRef, 8> MDNames;
2024 I.getType()->getContext().getMDKindNames(MDNames);
2025 for (unsigned i = 0, e = InstMD.size(); i != e; ++i) {
2026 unsigned Kind = InstMD[i].first;
2027 if (Kind < MDNames.size()) {
2028 Out << ", !" << MDNames[Kind];
2030 Out << ", !<unknown kind #" << Kind << ">";
2033 WriteAsOperandInternal(Out, InstMD[i].second, &TypePrinter, &Machine,
2037 printInfoComment(I);
2040 static void WriteMDNodeComment(const MDNode *Node,
2041 formatted_raw_ostream &Out) {
2042 if (Node->getNumOperands() < 1)
2044 ConstantInt *CI = dyn_cast_or_null<ConstantInt>(Node->getOperand(0));
2046 APInt Val = CI->getValue();
2047 APInt Tag = Val & ~APInt(Val.getBitWidth(), LLVMDebugVersionMask);
2048 if (Val.ult(LLVMDebugVersion))
2051 Out.PadToColumn(50);
2052 if (Tag == dwarf::DW_TAG_user_base)
2053 Out << "; [ DW_TAG_user_base ]";
2054 else if (Tag.isIntN(32)) {
2055 if (const char *TagName = dwarf::TagString(Tag.getZExtValue()))
2056 Out << "; [ " << TagName << " ]";
2060 void AssemblyWriter::writeAllMDNodes() {
2061 SmallVector<const MDNode *, 16> Nodes;
2062 Nodes.resize(Machine.mdn_size());
2063 for (SlotTracker::mdn_iterator I = Machine.mdn_begin(), E = Machine.mdn_end();
2065 Nodes[I->second] = cast<MDNode>(I->first);
2067 for (unsigned i = 0, e = Nodes.size(); i != e; ++i) {
2068 Out << '!' << i << " = metadata ";
2069 printMDNodeBody(Nodes[i]);
2073 void AssemblyWriter::printMDNodeBody(const MDNode *Node) {
2074 WriteMDNodeBodyInternal(Out, Node, &TypePrinter, &Machine, TheModule);
2075 WriteMDNodeComment(Node, Out);
2079 //===----------------------------------------------------------------------===//
2080 // External Interface declarations
2081 //===----------------------------------------------------------------------===//
2083 void Module::print(raw_ostream &ROS, AssemblyAnnotationWriter *AAW) const {
2084 SlotTracker SlotTable(this);
2085 formatted_raw_ostream OS(ROS);
2086 AssemblyWriter W(OS, SlotTable, this, AAW);
2087 W.printModule(this);
2090 void NamedMDNode::print(raw_ostream &ROS, AssemblyAnnotationWriter *AAW) const {
2091 SlotTracker SlotTable(getParent());
2092 formatted_raw_ostream OS(ROS);
2093 AssemblyWriter W(OS, SlotTable, getParent(), AAW);
2094 W.printNamedMDNode(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 ? F->getParent() : 0, AAW);
2133 W.printMDNodeBody(N);
2134 } else if (const Constant *C = dyn_cast<Constant>(this)) {
2135 TypePrinting TypePrinter;
2136 TypePrinter.print(C->getType(), OS);
2138 WriteConstantInternal(OS, C, TypePrinter, 0, 0);
2139 } else if (isa<InlineAsm>(this) || isa<MDString>(this) ||
2140 isa<Argument>(this)) {
2141 WriteAsOperand(OS, this, true, 0);
2143 // Otherwise we don't know what it is. Call the virtual function to
2144 // allow a subclass to print itself.
2149 // Value::printCustom - subclasses should override this to implement printing.
2150 void Value::printCustom(raw_ostream &OS) const {
2151 llvm_unreachable("Unknown value to print out!");
2154 // Value::dump - allow easy printing of Values from the debugger.
2155 void Value::dump() const { print(dbgs()); dbgs() << '\n'; }
2157 // Type::dump - allow easy printing of Types from the debugger.
2158 // This one uses type names from the given context module
2159 void Type::dump(const Module *Context) const {
2160 WriteTypeSymbolic(dbgs(), this, Context);
2164 // Type::dump - allow easy printing of Types from the debugger.
2165 void Type::dump() const { dump(0); }
2167 // Module::dump() - Allow printing of Modules from the debugger.
2168 void Module::dump() const { print(dbgs(), 0); }