1 //===-- AsmWriter.cpp - Printing LLVM as an assembly file -----------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This library implements the functionality defined in llvm/Assembly/Writer.h
12 // Note that these routines must be extremely tolerant of various errors in the
13 // LLVM code, because it can be used for debugging transformations.
15 //===----------------------------------------------------------------------===//
17 #include "llvm/Assembly/Writer.h"
18 #include "llvm/Assembly/PrintModulePass.h"
19 #include "llvm/Assembly/AsmAnnotationWriter.h"
20 #include "llvm/CallingConv.h"
21 #include "llvm/Constants.h"
22 #include "llvm/DerivedTypes.h"
23 #include "llvm/InlineAsm.h"
24 #include "llvm/Instruction.h"
25 #include "llvm/Instructions.h"
26 #include "llvm/Operator.h"
27 #include "llvm/MDNode.h"
28 #include "llvm/Module.h"
29 #include "llvm/ValueSymbolTable.h"
30 #include "llvm/TypeSymbolTable.h"
31 #include "llvm/ADT/DenseSet.h"
32 #include "llvm/ADT/StringExtras.h"
33 #include "llvm/ADT/STLExtras.h"
34 #include "llvm/Support/CFG.h"
35 #include "llvm/Support/ErrorHandling.h"
36 #include "llvm/Support/MathExtras.h"
37 #include "llvm/Support/raw_ostream.h"
43 // Make virtual table appear in this compilation unit.
44 AssemblyAnnotationWriter::~AssemblyAnnotationWriter() {}
46 //===----------------------------------------------------------------------===//
48 //===----------------------------------------------------------------------===//
50 static const Module *getModuleFromVal(const Value *V) {
51 if (const Argument *MA = dyn_cast<Argument>(V))
52 return MA->getParent() ? MA->getParent()->getParent() : 0;
54 if (const BasicBlock *BB = dyn_cast<BasicBlock>(V))
55 return BB->getParent() ? BB->getParent()->getParent() : 0;
57 if (const Instruction *I = dyn_cast<Instruction>(V)) {
58 const Function *M = I->getParent() ? I->getParent()->getParent() : 0;
59 return M ? M->getParent() : 0;
62 if (const GlobalValue *GV = dyn_cast<GlobalValue>(V))
63 return GV->getParent();
67 // PrintEscapedString - Print each character of the specified string, escaping
68 // it if it is not printable or if it is an escape char.
69 static void PrintEscapedString(const StringRef &Name, raw_ostream &Out) {
70 for (unsigned i = 0, e = Name.size(); i != e; ++i) {
71 unsigned char C = Name[i];
72 if (isprint(C) && C != '\\' && C != '"')
75 Out << '\\' << hexdigit(C >> 4) << hexdigit(C & 0x0F);
86 /// PrintLLVMName - Turn the specified name into an 'LLVM name', which is either
87 /// prefixed with % (if the string only contains simple characters) or is
88 /// surrounded with ""'s (if it has special chars in it). Print it out.
89 static void PrintLLVMName(raw_ostream &OS, const StringRef &Name,
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::IntegerTyID:
201 OS << 'i' << cast<IntegerType>(Ty)->getBitWidth();
204 case Type::FunctionTyID: {
205 const FunctionType *FTy = cast<FunctionType>(Ty);
206 CalcTypeName(FTy->getReturnType(), TypeStack, OS);
208 for (FunctionType::param_iterator I = FTy->param_begin(),
209 E = FTy->param_end(); I != E; ++I) {
210 if (I != FTy->param_begin())
212 CalcTypeName(*I, TypeStack, OS);
214 if (FTy->isVarArg()) {
215 if (FTy->getNumParams()) OS << ", ";
221 case Type::StructTyID: {
222 const StructType *STy = cast<StructType>(Ty);
226 for (StructType::element_iterator I = STy->element_begin(),
227 E = STy->element_end(); I != E; ++I) {
228 CalcTypeName(*I, TypeStack, OS);
229 if (next(I) != STy->element_end())
238 case Type::PointerTyID: {
239 const PointerType *PTy = cast<PointerType>(Ty);
240 CalcTypeName(PTy->getElementType(), TypeStack, OS);
241 if (unsigned AddressSpace = PTy->getAddressSpace())
242 OS << " addrspace(" << AddressSpace << ')';
246 case Type::ArrayTyID: {
247 const ArrayType *ATy = cast<ArrayType>(Ty);
248 OS << '[' << ATy->getNumElements() << " x ";
249 CalcTypeName(ATy->getElementType(), TypeStack, OS);
253 case Type::VectorTyID: {
254 const VectorType *PTy = cast<VectorType>(Ty);
255 OS << "<" << PTy->getNumElements() << " x ";
256 CalcTypeName(PTy->getElementType(), TypeStack, OS);
260 case Type::OpaqueTyID:
264 OS << "<unrecognized-type>";
268 TypeStack.pop_back(); // Remove self from stack.
271 /// printTypeInt - The internal guts of printing out a type that has a
272 /// potentially named portion.
274 void TypePrinting::print(const Type *Ty, raw_ostream &OS,
275 bool IgnoreTopLevelName) {
276 // Check to see if the type is named.
277 DenseMap<const Type*, std::string> &TM = getTypeNamesMap(TypeNames);
278 if (!IgnoreTopLevelName) {
279 DenseMap<const Type*, std::string>::iterator I = TM.find(Ty);
286 // Otherwise we have a type that has not been named but is a derived type.
287 // Carefully recurse the type hierarchy to print out any contained symbolic
289 SmallVector<const Type *, 16> TypeStack;
290 std::string TypeName;
292 raw_string_ostream TypeOS(TypeName);
293 CalcTypeName(Ty, TypeStack, TypeOS, IgnoreTopLevelName);
296 // Cache type name for later use.
297 if (!IgnoreTopLevelName)
298 TM.insert(std::make_pair(Ty, TypeOS.str()));
303 // To avoid walking constant expressions multiple times and other IR
304 // objects, we keep several helper maps.
305 DenseSet<const Value*> VisitedConstants;
306 DenseSet<const Type*> VisitedTypes;
309 std::vector<const Type*> &NumberedTypes;
311 TypeFinder(TypePrinting &tp, std::vector<const Type*> &numberedTypes)
312 : TP(tp), NumberedTypes(numberedTypes) {}
314 void Run(const Module &M) {
315 // Get types from the type symbol table. This gets opaque types referened
316 // only through derived named types.
317 const TypeSymbolTable &ST = M.getTypeSymbolTable();
318 for (TypeSymbolTable::const_iterator TI = ST.begin(), E = ST.end();
320 IncorporateType(TI->second);
322 // Get types from global variables.
323 for (Module::const_global_iterator I = M.global_begin(),
324 E = M.global_end(); I != E; ++I) {
325 IncorporateType(I->getType());
326 if (I->hasInitializer())
327 IncorporateValue(I->getInitializer());
330 // Get types from aliases.
331 for (Module::const_alias_iterator I = M.alias_begin(),
332 E = M.alias_end(); I != E; ++I) {
333 IncorporateType(I->getType());
334 IncorporateValue(I->getAliasee());
337 // Get types from functions.
338 for (Module::const_iterator FI = M.begin(), E = M.end(); FI != E; ++FI) {
339 IncorporateType(FI->getType());
341 for (Function::const_iterator BB = FI->begin(), E = FI->end();
343 for (BasicBlock::const_iterator II = BB->begin(),
344 E = BB->end(); II != E; ++II) {
345 const Instruction &I = *II;
346 // Incorporate the type of the instruction and all its operands.
347 IncorporateType(I.getType());
348 for (User::const_op_iterator OI = I.op_begin(), OE = I.op_end();
350 IncorporateValue(*OI);
356 void IncorporateType(const Type *Ty) {
357 // Check to see if we're already visited this type.
358 if (!VisitedTypes.insert(Ty).second)
361 // If this is a structure or opaque type, add a name for the type.
362 if (((isa<StructType>(Ty) && cast<StructType>(Ty)->getNumElements())
363 || isa<OpaqueType>(Ty)) && !TP.hasTypeName(Ty)) {
364 TP.addTypeName(Ty, "%"+utostr(unsigned(NumberedTypes.size())));
365 NumberedTypes.push_back(Ty);
368 // Recursively walk all contained types.
369 for (Type::subtype_iterator I = Ty->subtype_begin(),
370 E = Ty->subtype_end(); I != E; ++I)
374 /// IncorporateValue - This method is used to walk operand lists finding
375 /// types hiding in constant expressions and other operands that won't be
376 /// walked in other ways. GlobalValues, basic blocks, instructions, and
377 /// inst operands are all explicitly enumerated.
378 void IncorporateValue(const Value *V) {
379 if (V == 0 || !isa<Constant>(V) || isa<GlobalValue>(V)) return;
382 if (!VisitedConstants.insert(V).second)
386 IncorporateType(V->getType());
388 // Look in operands for types.
389 const Constant *C = cast<Constant>(V);
390 for (Constant::const_op_iterator I = C->op_begin(),
391 E = C->op_end(); I != E;++I)
392 IncorporateValue(*I);
395 } // end anonymous namespace
398 /// AddModuleTypesToPrinter - Add all of the symbolic type names for types in
399 /// the specified module to the TypePrinter and all numbered types to it and the
400 /// NumberedTypes table.
401 static void AddModuleTypesToPrinter(TypePrinting &TP,
402 std::vector<const Type*> &NumberedTypes,
406 // If the module has a symbol table, take all global types and stuff their
407 // names into the TypeNames map.
408 const TypeSymbolTable &ST = M->getTypeSymbolTable();
409 for (TypeSymbolTable::const_iterator TI = ST.begin(), E = ST.end();
411 const Type *Ty = cast<Type>(TI->second);
413 // As a heuristic, don't insert pointer to primitive types, because
414 // they are used too often to have a single useful name.
415 if (const PointerType *PTy = dyn_cast<PointerType>(Ty)) {
416 const Type *PETy = PTy->getElementType();
417 if ((PETy->isPrimitiveType() || PETy->isInteger()) &&
418 !isa<OpaqueType>(PETy))
422 // Likewise don't insert primitives either.
423 if (Ty->isInteger() || Ty->isPrimitiveType())
426 // Get the name as a string and insert it into TypeNames.
428 raw_string_ostream NameOS(NameStr);
429 PrintLLVMName(NameOS, TI->first, LocalPrefix);
430 TP.addTypeName(Ty, NameOS.str());
433 // Walk the entire module to find references to unnamed structure and opaque
434 // types. This is required for correctness by opaque types (because multiple
435 // uses of an unnamed opaque type needs to be referred to by the same ID) and
436 // it shrinks complex recursive structure types substantially in some cases.
437 TypeFinder(TP, NumberedTypes).Run(*M);
441 /// WriteTypeSymbolic - This attempts to write the specified type as a symbolic
442 /// type, iff there is an entry in the modules symbol table for the specified
443 /// type or one of it's component types.
445 void llvm::WriteTypeSymbolic(raw_ostream &OS, const Type *Ty, const Module *M) {
446 TypePrinting Printer;
447 std::vector<const Type*> NumberedTypes;
448 AddModuleTypesToPrinter(Printer, NumberedTypes, M);
449 Printer.print(Ty, OS);
452 //===----------------------------------------------------------------------===//
453 // SlotTracker Class: Enumerate slot numbers for unnamed values
454 //===----------------------------------------------------------------------===//
458 /// This class provides computation of slot numbers for LLVM Assembly writing.
462 /// ValueMap - A mapping of Values to slot numbers.
463 typedef DenseMap<const Value*, unsigned> ValueMap;
466 /// TheModule - The module for which we are holding slot numbers.
467 const Module* TheModule;
469 /// TheFunction - The function for which we are holding slot numbers.
470 const Function* TheFunction;
471 bool FunctionProcessed;
473 /// TheMDNode - The MDNode for which we are holding slot numbers.
474 const MDNode *TheMDNode;
476 /// mMap - The TypePlanes map for the module level data.
480 /// fMap - The TypePlanes map for the function level data.
484 /// mdnMap - Map for MDNodes.
488 /// Construct from a module
489 explicit SlotTracker(const Module *M);
490 /// Construct from a function, starting out in incorp state.
491 explicit SlotTracker(const Function *F);
492 /// Construct from a mdnode.
493 explicit SlotTracker(const MDNode *N);
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 ValueMap::iterator mdnBegin() { return mdnMap.begin(); }
515 ValueMap::iterator mdnEnd() { return mdnMap.end(); }
516 unsigned mdnSize() { return mdnMap.size(); }
518 /// This function does the actual initialization.
519 inline void initialize();
521 // Implementation Details
523 /// CreateModuleSlot - Insert the specified GlobalValue* into the slot table.
524 void CreateModuleSlot(const GlobalValue *V);
526 /// CreateMetadataSlot - Insert the specified MDNode* into the slot table.
527 void CreateMetadataSlot(const MDNode *N);
529 /// CreateFunctionSlot - Insert the specified Value* into the slot table.
530 void CreateFunctionSlot(const Value *V);
532 /// Add all of the module level global variables (and their initializers)
533 /// and function declarations, but not the contents of those functions.
534 void processModule();
536 /// Add all of the functions arguments, basic blocks, and instructions.
537 void processFunction();
539 /// Add all MDNode operands.
540 void processMDNode();
542 SlotTracker(const SlotTracker &); // DO NOT IMPLEMENT
543 void operator=(const SlotTracker &); // DO NOT IMPLEMENT
546 } // end anonymous namespace
549 static SlotTracker *createSlotTracker(const Value *V) {
550 if (const Argument *FA = dyn_cast<Argument>(V))
551 return new SlotTracker(FA->getParent());
553 if (const Instruction *I = dyn_cast<Instruction>(V))
554 return new SlotTracker(I->getParent()->getParent());
556 if (const BasicBlock *BB = dyn_cast<BasicBlock>(V))
557 return new SlotTracker(BB->getParent());
559 if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(V))
560 return new SlotTracker(GV->getParent());
562 if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(V))
563 return new SlotTracker(GA->getParent());
565 if (const Function *Func = dyn_cast<Function>(V))
566 return new SlotTracker(Func);
572 #define ST_DEBUG(X) errs() << X
577 // Module level constructor. Causes the contents of the Module (sans functions)
578 // to be added to the slot table.
579 SlotTracker::SlotTracker(const Module *M)
580 : TheModule(M), TheFunction(0), FunctionProcessed(false), TheMDNode(0),
581 mNext(0), fNext(0), mdnNext(0) {
584 // Function level constructor. Causes the contents of the Module and the one
585 // function provided to be added to the slot table.
586 SlotTracker::SlotTracker(const Function *F)
587 : TheModule(F ? F->getParent() : 0), TheFunction(F), FunctionProcessed(false),
588 TheMDNode(0), mNext(0), fNext(0), mdnNext(0) {
591 // Constructor to handle single MDNode.
592 SlotTracker::SlotTracker(const MDNode *C)
593 : TheModule(0), TheFunction(0), FunctionProcessed(false), TheMDNode(C),
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)
610 // Iterate through all the global variables, functions, and global
611 // variable initializers and create slots for them.
612 void SlotTracker::processModule() {
613 ST_DEBUG("begin processModule!\n");
615 // Add all of the unnamed global variables to the value table.
616 for (Module::const_global_iterator I = TheModule->global_begin(),
617 E = TheModule->global_end(); I != E; ++I) {
620 if (I->hasInitializer()) {
621 if (MDNode *N = dyn_cast<MDNode>(I->getInitializer()))
622 CreateMetadataSlot(N);
626 // Add all the unnamed functions to the table.
627 for (Module::const_iterator I = TheModule->begin(), E = TheModule->end();
632 ST_DEBUG("end processModule!\n");
635 // Process the arguments, basic blocks, and instructions of a function.
636 void SlotTracker::processFunction() {
637 ST_DEBUG("begin processFunction!\n");
640 // Add all the function arguments with no names.
641 for(Function::const_arg_iterator AI = TheFunction->arg_begin(),
642 AE = TheFunction->arg_end(); AI != AE; ++AI)
644 CreateFunctionSlot(AI);
646 ST_DEBUG("Inserting Instructions:\n");
648 // Add all of the basic blocks and instructions with no names.
649 for (Function::const_iterator BB = TheFunction->begin(),
650 E = TheFunction->end(); BB != E; ++BB) {
652 CreateFunctionSlot(BB);
653 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I != E;
655 if (I->getType() != Type::VoidTy && !I->hasName())
656 CreateFunctionSlot(I);
657 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
658 if (MDNode *N = dyn_cast<MDNode>(I->getOperand(i)))
659 CreateMetadataSlot(N);
663 FunctionProcessed = true;
665 ST_DEBUG("end processFunction!\n");
668 /// processMDNode - Process TheMDNode.
669 void SlotTracker::processMDNode() {
670 ST_DEBUG("begin processMDNode!\n");
672 CreateMetadataSlot(TheMDNode);
674 ST_DEBUG("end processMDNode!\n");
677 /// Clean up after incorporating a function. This is the only way to get out of
678 /// the function incorporation state that affects get*Slot/Create*Slot. Function
679 /// incorporation state is indicated by TheFunction != 0.
680 void SlotTracker::purgeFunction() {
681 ST_DEBUG("begin purgeFunction!\n");
682 fMap.clear(); // Simply discard the function level map
684 FunctionProcessed = false;
685 ST_DEBUG("end purgeFunction!\n");
688 /// getGlobalSlot - Get the slot number of a global value.
689 int SlotTracker::getGlobalSlot(const GlobalValue *V) {
690 // Check for uninitialized state and do lazy initialization.
693 // Find the type plane in the module map
694 ValueMap::iterator MI = mMap.find(V);
695 return MI == mMap.end() ? -1 : (int)MI->second;
698 /// getGlobalSlot - Get the slot number of a MDNode.
699 int SlotTracker::getMetadataSlot(const MDNode *N) {
700 // Check for uninitialized state and do lazy initialization.
703 // Find the type plane in the module map
704 ValueMap::iterator MI = mdnMap.find(N);
705 return MI == mdnMap.end() ? -1 : (int)MI->second;
709 /// getLocalSlot - Get the slot number for a value that is local to a function.
710 int SlotTracker::getLocalSlot(const Value *V) {
711 assert(!isa<Constant>(V) && "Can't get a constant or global slot with this!");
713 // Check for uninitialized state and do lazy initialization.
716 ValueMap::iterator FI = fMap.find(V);
717 return FI == fMap.end() ? -1 : (int)FI->second;
721 /// CreateModuleSlot - Insert the specified GlobalValue* into the slot table.
722 void SlotTracker::CreateModuleSlot(const GlobalValue *V) {
723 assert(V && "Can't insert a null Value into SlotTracker!");
724 assert(V->getType() != Type::VoidTy && "Doesn't need a slot!");
725 assert(!V->hasName() && "Doesn't need a slot!");
727 unsigned DestSlot = mNext++;
730 ST_DEBUG(" Inserting value [" << V->getType() << "] = " << V << " slot=" <<
732 // G = Global, F = Function, A = Alias, o = other
733 ST_DEBUG((isa<GlobalVariable>(V) ? 'G' :
734 (isa<Function>(V) ? 'F' :
735 (isa<GlobalAlias>(V) ? 'A' : 'o'))) << "]\n");
738 /// CreateSlot - Create a new slot for the specified value if it has no name.
739 void SlotTracker::CreateFunctionSlot(const Value *V) {
740 assert(V->getType() != Type::VoidTy && !V->hasName() &&
741 "Doesn't need a slot!");
743 unsigned DestSlot = fNext++;
746 // G = Global, F = Function, o = other
747 ST_DEBUG(" Inserting value [" << V->getType() << "] = " << V << " slot=" <<
748 DestSlot << " [o]\n");
751 /// CreateModuleSlot - Insert the specified MDNode* into the slot table.
752 void SlotTracker::CreateMetadataSlot(const MDNode *N) {
753 assert(N && "Can't insert a null Value into SlotTracker!");
755 ValueMap::iterator I = mdnMap.find(N);
756 if (I != mdnMap.end())
759 unsigned DestSlot = mdnNext++;
760 mdnMap[N] = DestSlot;
762 for (MDNode::const_elem_iterator MDI = N->elem_begin(),
763 MDE = N->elem_end(); MDI != MDE; ++MDI) {
764 const Value *TV = *MDI;
766 if (const MDNode *N2 = dyn_cast<MDNode>(TV))
767 CreateMetadataSlot(N2);
771 //===----------------------------------------------------------------------===//
772 // AsmWriter Implementation
773 //===----------------------------------------------------------------------===//
775 static void WriteAsOperandInternal(raw_ostream &Out, const Value *V,
776 TypePrinting &TypePrinter,
777 SlotTracker *Machine);
781 static const char *getPredicateText(unsigned predicate) {
782 const char * pred = "unknown";
784 case FCmpInst::FCMP_FALSE: pred = "false"; break;
785 case FCmpInst::FCMP_OEQ: pred = "oeq"; break;
786 case FCmpInst::FCMP_OGT: pred = "ogt"; break;
787 case FCmpInst::FCMP_OGE: pred = "oge"; break;
788 case FCmpInst::FCMP_OLT: pred = "olt"; break;
789 case FCmpInst::FCMP_OLE: pred = "ole"; break;
790 case FCmpInst::FCMP_ONE: pred = "one"; break;
791 case FCmpInst::FCMP_ORD: pred = "ord"; break;
792 case FCmpInst::FCMP_UNO: pred = "uno"; break;
793 case FCmpInst::FCMP_UEQ: pred = "ueq"; break;
794 case FCmpInst::FCMP_UGT: pred = "ugt"; break;
795 case FCmpInst::FCMP_UGE: pred = "uge"; break;
796 case FCmpInst::FCMP_ULT: pred = "ult"; break;
797 case FCmpInst::FCMP_ULE: pred = "ule"; break;
798 case FCmpInst::FCMP_UNE: pred = "une"; break;
799 case FCmpInst::FCMP_TRUE: pred = "true"; break;
800 case ICmpInst::ICMP_EQ: pred = "eq"; break;
801 case ICmpInst::ICMP_NE: pred = "ne"; break;
802 case ICmpInst::ICMP_SGT: pred = "sgt"; break;
803 case ICmpInst::ICMP_SGE: pred = "sge"; break;
804 case ICmpInst::ICMP_SLT: pred = "slt"; break;
805 case ICmpInst::ICMP_SLE: pred = "sle"; break;
806 case ICmpInst::ICMP_UGT: pred = "ugt"; break;
807 case ICmpInst::ICMP_UGE: pred = "uge"; break;
808 case ICmpInst::ICMP_ULT: pred = "ult"; break;
809 case ICmpInst::ICMP_ULE: pred = "ule"; break;
814 static void WriteMDNodes(raw_ostream &Out, TypePrinting &TypePrinter,
815 SlotTracker &Machine) {
816 SmallVector<const MDNode *, 16> Nodes;
817 Nodes.resize(Machine.mdnSize());
818 for (SlotTracker::ValueMap::iterator I =
819 Machine.mdnBegin(), E = Machine.mdnEnd(); I != E; ++I)
820 Nodes[I->second] = cast<MDNode>(I->first);
822 for (unsigned i = 0, e = Nodes.size(); i != e; ++i) {
823 Out << '!' << i << " = metadata ";
824 const MDNode *Node = Nodes[i];
826 for (MDNode::const_elem_iterator NI = Node->elem_begin(),
827 NE = Node->elem_end(); NI != NE;) {
828 const Value *V = *NI;
831 else if (const MDNode *N = dyn_cast<MDNode>(V)) {
833 Out << '!' << Machine.getMetadataSlot(N);
836 TypePrinter.print((*NI)->getType(), Out);
838 WriteAsOperandInternal(Out, *NI, TypePrinter, &Machine);
847 static void WriteOptimizationInfo(raw_ostream &Out, const User *U) {
848 if (const OverflowingBinaryOperator *OBO =
849 dyn_cast<OverflowingBinaryOperator>(U)) {
850 if (OBO->hasNoUnsignedOverflow())
852 if (OBO->hasNoSignedOverflow())
854 } else if (const SDivOperator *Div = dyn_cast<SDivOperator>(U)) {
860 static void WriteConstantInt(raw_ostream &Out, const Constant *CV,
861 TypePrinting &TypePrinter, SlotTracker *Machine) {
862 if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV)) {
863 if (CI->getType() == Type::Int1Ty) {
864 Out << (CI->getZExtValue() ? "true" : "false");
867 Out << CI->getValue();
871 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CV)) {
872 if (&CFP->getValueAPF().getSemantics() == &APFloat::IEEEdouble ||
873 &CFP->getValueAPF().getSemantics() == &APFloat::IEEEsingle) {
874 // We would like to output the FP constant value in exponential notation,
875 // but we cannot do this if doing so will lose precision. Check here to
876 // make sure that we only output it in exponential format if we can parse
877 // the value back and get the same value.
880 bool isDouble = &CFP->getValueAPF().getSemantics()==&APFloat::IEEEdouble;
881 double Val = isDouble ? CFP->getValueAPF().convertToDouble() :
882 CFP->getValueAPF().convertToFloat();
883 std::string StrVal = ftostr(CFP->getValueAPF());
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 ConstantArray *CA = dyn_cast<ConstantArray>(CV)) {
975 // As a special case, print the array as a string if it is an array of
976 // i8 with ConstantInt values.
978 const Type *ETy = CA->getType()->getElementType();
979 if (CA->isString()) {
981 PrintEscapedString(CA->getAsString(), Out);
983 } else { // Cannot output in string format...
985 if (CA->getNumOperands()) {
986 TypePrinter.print(ETy, Out);
988 WriteAsOperandInternal(Out, CA->getOperand(0),
989 TypePrinter, Machine);
990 for (unsigned i = 1, e = CA->getNumOperands(); i != e; ++i) {
992 TypePrinter.print(ETy, Out);
994 WriteAsOperandInternal(Out, CA->getOperand(i), TypePrinter, Machine);
1002 if (const ConstantStruct *CS = dyn_cast<ConstantStruct>(CV)) {
1003 if (CS->getType()->isPacked())
1006 unsigned N = CS->getNumOperands();
1009 TypePrinter.print(CS->getOperand(0)->getType(), Out);
1012 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);
1025 if (CS->getType()->isPacked())
1030 if (const ConstantVector *CP = dyn_cast<ConstantVector>(CV)) {
1031 const Type *ETy = CP->getType()->getElementType();
1032 assert(CP->getNumOperands() > 0 &&
1033 "Number of operands for a PackedConst must be > 0");
1035 TypePrinter.print(ETy, Out);
1037 WriteAsOperandInternal(Out, CP->getOperand(0), TypePrinter, Machine);
1038 for (unsigned i = 1, e = CP->getNumOperands(); i != e; ++i) {
1040 TypePrinter.print(ETy, Out);
1042 WriteAsOperandInternal(Out, CP->getOperand(i), TypePrinter, Machine);
1048 if (isa<ConstantPointerNull>(CV)) {
1053 if (isa<UndefValue>(CV)) {
1058 if (const MDNode *Node = dyn_cast<MDNode>(CV)) {
1059 Out << "!" << Machine->getMetadataSlot(Node);
1063 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV)) {
1064 Out << CE->getOpcodeName();
1065 WriteOptimizationInfo(Out, CE);
1066 if (CE->isCompare())
1067 Out << ' ' << getPredicateText(CE->getPredicate());
1070 for (User::const_op_iterator OI=CE->op_begin(); OI != CE->op_end(); ++OI) {
1071 TypePrinter.print((*OI)->getType(), Out);
1073 WriteAsOperandInternal(Out, *OI, TypePrinter, Machine);
1074 if (OI+1 != CE->op_end())
1078 if (CE->hasIndices()) {
1079 const SmallVector<unsigned, 4> &Indices = CE->getIndices();
1080 for (unsigned i = 0, e = Indices.size(); i != e; ++i)
1081 Out << ", " << Indices[i];
1086 TypePrinter.print(CE->getType(), Out);
1093 Out << "<placeholder or erroneous Constant>";
1097 /// WriteAsOperand - Write the name of the specified value out to the specified
1098 /// ostream. This can be useful when you just want to print int %reg126, not
1099 /// the whole instruction that generated it.
1101 static void WriteAsOperandInternal(raw_ostream &Out, const Value *V,
1102 TypePrinting &TypePrinter,
1103 SlotTracker *Machine) {
1105 PrintLLVMName(Out, V);
1109 const Constant *CV = dyn_cast<Constant>(V);
1110 if (CV && !isa<GlobalValue>(CV)) {
1111 WriteConstantInt(Out, CV, TypePrinter, Machine);
1115 if (const InlineAsm *IA = dyn_cast<InlineAsm>(V)) {
1117 if (IA->hasSideEffects())
1118 Out << "sideeffect ";
1120 PrintEscapedString(IA->getAsmString(), Out);
1122 PrintEscapedString(IA->getConstraintString(), Out);
1127 if (const MDNode *N = dyn_cast<MDNode>(V)) {
1128 Out << '!' << Machine->getMetadataSlot(N);
1132 if (const MDString *MDS = dyn_cast<MDString>(V)) {
1134 PrintEscapedString(MDS->getString(), Out);
1142 if (const GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
1143 Slot = Machine->getGlobalSlot(GV);
1146 Slot = Machine->getLocalSlot(V);
1149 Machine = createSlotTracker(V);
1151 if (const GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
1152 Slot = Machine->getGlobalSlot(GV);
1155 Slot = Machine->getLocalSlot(V);
1164 Out << Prefix << Slot;
1169 /// WriteAsOperand - Write the name of the specified value out to the specified
1170 /// ostream. This can be useful when you just want to print int %reg126, not
1171 /// the whole instruction that generated it.
1173 void llvm::WriteAsOperand(std::ostream &Out, const Value *V, bool PrintType,
1174 const Module *Context) {
1175 raw_os_ostream OS(Out);
1176 WriteAsOperand(OS, V, PrintType, Context);
1179 void llvm::WriteAsOperand(raw_ostream &Out, const Value *V, bool PrintType,
1180 const Module *Context) {
1181 if (Context == 0) Context = getModuleFromVal(V);
1183 TypePrinting TypePrinter;
1184 std::vector<const Type*> NumberedTypes;
1185 AddModuleTypesToPrinter(TypePrinter, NumberedTypes, Context);
1187 TypePrinter.print(V->getType(), Out);
1191 WriteAsOperandInternal(Out, V, TypePrinter, 0);
1197 class AssemblyWriter {
1199 SlotTracker &Machine;
1200 const Module *TheModule;
1201 TypePrinting TypePrinter;
1202 AssemblyAnnotationWriter *AnnotationWriter;
1203 std::vector<const Type*> NumberedTypes;
1205 // Each MDNode is assigned unique MetadataIDNo.
1206 std::map<const MDNode *, unsigned> MDNodes;
1207 unsigned MetadataIDNo;
1209 inline AssemblyWriter(raw_ostream &o, SlotTracker &Mac, const Module *M,
1210 AssemblyAnnotationWriter *AAW)
1211 : Out(o), Machine(Mac), TheModule(M), AnnotationWriter(AAW), MetadataIDNo(0) {
1212 AddModuleTypesToPrinter(TypePrinter, NumberedTypes, M);
1215 void write(const Module *M) { printModule(M); }
1217 void write(const GlobalValue *G) {
1218 if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(G))
1220 else if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(G))
1222 else if (const Function *F = dyn_cast<Function>(G))
1225 llvm_unreachable("Unknown global");
1228 void write(const BasicBlock *BB) { printBasicBlock(BB); }
1229 void write(const Instruction *I) { printInstruction(*I); }
1231 void writeOperand(const Value *Op, bool PrintType);
1232 void writeParamOperand(const Value *Operand, Attributes Attrs);
1234 const Module* getModule() { return TheModule; }
1237 void printModule(const Module *M);
1238 void printTypeSymbolTable(const TypeSymbolTable &ST);
1239 void printGlobal(const GlobalVariable *GV);
1240 void printAlias(const GlobalAlias *GV);
1241 void printFunction(const Function *F);
1242 void printArgument(const Argument *FA, Attributes Attrs);
1243 void printBasicBlock(const BasicBlock *BB);
1244 void printInstruction(const Instruction &I);
1246 // printInfoComment - Print a little comment after the instruction indicating
1247 // which slot it occupies.
1248 void printInfoComment(const Value &V);
1250 } // end of anonymous namespace
1253 void AssemblyWriter::writeOperand(const Value *Operand, bool PrintType) {
1255 Out << "<null operand!>";
1258 TypePrinter.print(Operand->getType(), Out);
1261 WriteAsOperandInternal(Out, Operand, TypePrinter, &Machine);
1265 void AssemblyWriter::writeParamOperand(const Value *Operand,
1268 Out << "<null operand!>";
1271 TypePrinter.print(Operand->getType(), Out);
1272 // Print parameter attributes list
1273 if (Attrs != Attribute::None)
1274 Out << ' ' << Attribute::getAsString(Attrs);
1276 // Print the operand
1277 WriteAsOperandInternal(Out, Operand, TypePrinter, &Machine);
1281 void AssemblyWriter::printModule(const Module *M) {
1282 if (!M->getModuleIdentifier().empty() &&
1283 // Don't print the ID if it will start a new line (which would
1284 // require a comment char before it).
1285 M->getModuleIdentifier().find('\n') == std::string::npos)
1286 Out << "; ModuleID = '" << M->getModuleIdentifier() << "'\n";
1288 if (!M->getDataLayout().empty())
1289 Out << "target datalayout = \"" << M->getDataLayout() << "\"\n";
1290 if (!M->getTargetTriple().empty())
1291 Out << "target triple = \"" << M->getTargetTriple() << "\"\n";
1293 if (!M->getModuleInlineAsm().empty()) {
1294 // Split the string into lines, to make it easier to read the .ll file.
1295 std::string Asm = M->getModuleInlineAsm();
1297 size_t NewLine = Asm.find_first_of('\n', CurPos);
1298 while (NewLine != std::string::npos) {
1299 // We found a newline, print the portion of the asm string from the
1300 // last newline up to this newline.
1301 Out << "module asm \"";
1302 PrintEscapedString(std::string(Asm.begin()+CurPos, Asm.begin()+NewLine),
1306 NewLine = Asm.find_first_of('\n', CurPos);
1308 Out << "module asm \"";
1309 PrintEscapedString(std::string(Asm.begin()+CurPos, Asm.end()), Out);
1313 // Loop over the dependent libraries and emit them.
1314 Module::lib_iterator LI = M->lib_begin();
1315 Module::lib_iterator LE = M->lib_end();
1317 Out << "deplibs = [ ";
1319 Out << '"' << *LI << '"';
1327 // Loop over the symbol table, emitting all id'd types.
1328 printTypeSymbolTable(M->getTypeSymbolTable());
1330 for (Module::const_global_iterator I = M->global_begin(), E = M->global_end();
1334 // Output all aliases.
1335 if (!M->alias_empty()) Out << "\n";
1336 for (Module::const_alias_iterator I = M->alias_begin(), E = M->alias_end();
1340 // Output all of the functions.
1341 for (Module::const_iterator I = M->begin(), E = M->end(); I != E; ++I)
1344 WriteMDNodes(Out, TypePrinter, Machine);
1347 static void PrintLinkage(GlobalValue::LinkageTypes LT, raw_ostream &Out) {
1349 case GlobalValue::ExternalLinkage: break;
1350 case GlobalValue::PrivateLinkage: Out << "private "; break;
1351 case GlobalValue::LinkerPrivateLinkage: Out << "linker_private "; break;
1352 case GlobalValue::InternalLinkage: Out << "internal "; break;
1353 case GlobalValue::LinkOnceAnyLinkage: Out << "linkonce "; break;
1354 case GlobalValue::LinkOnceODRLinkage: Out << "linkonce_odr "; break;
1355 case GlobalValue::WeakAnyLinkage: Out << "weak "; break;
1356 case GlobalValue::WeakODRLinkage: Out << "weak_odr "; break;
1357 case GlobalValue::CommonLinkage: Out << "common "; break;
1358 case GlobalValue::AppendingLinkage: Out << "appending "; break;
1359 case GlobalValue::DLLImportLinkage: Out << "dllimport "; break;
1360 case GlobalValue::DLLExportLinkage: Out << "dllexport "; break;
1361 case GlobalValue::ExternalWeakLinkage: Out << "extern_weak "; break;
1362 case GlobalValue::AvailableExternallyLinkage:
1363 Out << "available_externally ";
1365 case GlobalValue::GhostLinkage:
1366 llvm_unreachable("GhostLinkage not allowed in AsmWriter!");
1371 static void PrintVisibility(GlobalValue::VisibilityTypes Vis,
1374 default: llvm_unreachable("Invalid visibility style!");
1375 case GlobalValue::DefaultVisibility: break;
1376 case GlobalValue::HiddenVisibility: Out << "hidden "; break;
1377 case GlobalValue::ProtectedVisibility: Out << "protected "; break;
1381 void AssemblyWriter::printGlobal(const GlobalVariable *GV) {
1382 if (GV->hasName()) {
1383 PrintLLVMName(Out, GV);
1387 if (!GV->hasInitializer() && GV->hasExternalLinkage())
1390 PrintLinkage(GV->getLinkage(), Out);
1391 PrintVisibility(GV->getVisibility(), Out);
1393 if (GV->isThreadLocal()) Out << "thread_local ";
1394 if (unsigned AddressSpace = GV->getType()->getAddressSpace())
1395 Out << "addrspace(" << AddressSpace << ") ";
1396 Out << (GV->isConstant() ? "constant " : "global ");
1397 TypePrinter.print(GV->getType()->getElementType(), Out);
1399 if (GV->hasInitializer()) {
1401 writeOperand(GV->getInitializer(), false);
1404 if (GV->hasSection())
1405 Out << ", section \"" << GV->getSection() << '"';
1406 if (GV->getAlignment())
1407 Out << ", align " << GV->getAlignment();
1409 printInfoComment(*GV);
1413 void AssemblyWriter::printAlias(const GlobalAlias *GA) {
1414 // Don't crash when dumping partially built GA
1416 Out << "<<nameless>> = ";
1418 PrintLLVMName(Out, GA);
1421 PrintVisibility(GA->getVisibility(), Out);
1425 PrintLinkage(GA->getLinkage(), Out);
1427 const Constant *Aliasee = GA->getAliasee();
1429 if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(Aliasee)) {
1430 TypePrinter.print(GV->getType(), Out);
1432 PrintLLVMName(Out, GV);
1433 } else if (const Function *F = dyn_cast<Function>(Aliasee)) {
1434 TypePrinter.print(F->getFunctionType(), Out);
1437 WriteAsOperandInternal(Out, F, TypePrinter, &Machine);
1438 } else if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(Aliasee)) {
1439 TypePrinter.print(GA->getType(), Out);
1441 PrintLLVMName(Out, GA);
1443 const ConstantExpr *CE = cast<ConstantExpr>(Aliasee);
1444 // The only valid GEP is an all zero GEP.
1445 assert((CE->getOpcode() == Instruction::BitCast ||
1446 CE->getOpcode() == Instruction::GetElementPtr) &&
1447 "Unsupported aliasee");
1448 writeOperand(CE, false);
1451 printInfoComment(*GA);
1455 void AssemblyWriter::printTypeSymbolTable(const TypeSymbolTable &ST) {
1456 // Emit all numbered types.
1457 for (unsigned i = 0, e = NumberedTypes.size(); i != e; ++i) {
1460 // Make sure we print out at least one level of the type structure, so
1461 // that we do not get %2 = type %2
1462 TypePrinter.printAtLeastOneLevel(NumberedTypes[i], Out);
1463 Out << "\t\t; type %" << i << '\n';
1466 // Print the named types.
1467 for (TypeSymbolTable::const_iterator TI = ST.begin(), TE = ST.end();
1470 PrintLLVMName(Out, TI->first, LocalPrefix);
1473 // Make sure we print out at least one level of the type structure, so
1474 // that we do not get %FILE = type %FILE
1475 TypePrinter.printAtLeastOneLevel(TI->second, Out);
1480 /// printFunction - Print all aspects of a function.
1482 void AssemblyWriter::printFunction(const Function *F) {
1483 // Print out the return type and name.
1486 if (AnnotationWriter) AnnotationWriter->emitFunctionAnnot(F, Out);
1488 if (F->isDeclaration())
1493 PrintLinkage(F->getLinkage(), Out);
1494 PrintVisibility(F->getVisibility(), Out);
1496 // Print the calling convention.
1497 switch (F->getCallingConv()) {
1498 case CallingConv::C: break; // default
1499 case CallingConv::Fast: Out << "fastcc "; break;
1500 case CallingConv::Cold: Out << "coldcc "; break;
1501 case CallingConv::X86_StdCall: Out << "x86_stdcallcc "; break;
1502 case CallingConv::X86_FastCall: Out << "x86_fastcallcc "; break;
1503 case CallingConv::ARM_APCS: Out << "arm_apcscc "; break;
1504 case CallingConv::ARM_AAPCS: Out << "arm_aapcscc "; break;
1505 case CallingConv::ARM_AAPCS_VFP:Out << "arm_aapcs_vfpcc "; break;
1506 default: Out << "cc" << F->getCallingConv() << " "; break;
1509 const FunctionType *FT = F->getFunctionType();
1510 const AttrListPtr &Attrs = F->getAttributes();
1511 Attributes RetAttrs = Attrs.getRetAttributes();
1512 if (RetAttrs != Attribute::None)
1513 Out << Attribute::getAsString(Attrs.getRetAttributes()) << ' ';
1514 TypePrinter.print(F->getReturnType(), Out);
1516 WriteAsOperandInternal(Out, F, TypePrinter, &Machine);
1518 Machine.incorporateFunction(F);
1520 // Loop over the arguments, printing them...
1523 if (!F->isDeclaration()) {
1524 // If this isn't a declaration, print the argument names as well.
1525 for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
1527 // Insert commas as we go... the first arg doesn't get a comma
1528 if (I != F->arg_begin()) Out << ", ";
1529 printArgument(I, Attrs.getParamAttributes(Idx));
1533 // Otherwise, print the types from the function type.
1534 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
1535 // Insert commas as we go... the first arg doesn't get a comma
1539 TypePrinter.print(FT->getParamType(i), Out);
1541 Attributes ArgAttrs = Attrs.getParamAttributes(i+1);
1542 if (ArgAttrs != Attribute::None)
1543 Out << ' ' << Attribute::getAsString(ArgAttrs);
1547 // Finish printing arguments...
1548 if (FT->isVarArg()) {
1549 if (FT->getNumParams()) Out << ", ";
1550 Out << "..."; // Output varargs portion of signature!
1553 Attributes FnAttrs = Attrs.getFnAttributes();
1554 if (FnAttrs != Attribute::None)
1555 Out << ' ' << Attribute::getAsString(Attrs.getFnAttributes());
1556 if (F->hasSection())
1557 Out << " section \"" << F->getSection() << '"';
1558 if (F->getAlignment())
1559 Out << " align " << F->getAlignment();
1561 Out << " gc \"" << F->getGC() << '"';
1562 if (F->isDeclaration()) {
1567 // Output all of its basic blocks... for the function
1568 for (Function::const_iterator I = F->begin(), E = F->end(); I != E; ++I)
1574 Machine.purgeFunction();
1577 /// printArgument - This member is called for every argument that is passed into
1578 /// the function. Simply print it out
1580 void AssemblyWriter::printArgument(const Argument *Arg,
1583 TypePrinter.print(Arg->getType(), Out);
1585 // Output parameter attributes list
1586 if (Attrs != Attribute::None)
1587 Out << ' ' << Attribute::getAsString(Attrs);
1589 // Output name, if available...
1590 if (Arg->hasName()) {
1592 PrintLLVMName(Out, Arg);
1596 /// printBasicBlock - This member is called for each basic block in a method.
1598 void AssemblyWriter::printBasicBlock(const BasicBlock *BB) {
1599 if (BB->hasName()) { // Print out the label if it exists...
1601 PrintLLVMName(Out, BB->getName(), LabelPrefix);
1603 } else if (!BB->use_empty()) { // Don't print block # of no uses...
1604 Out << "\n; <label>:";
1605 int Slot = Machine.getLocalSlot(BB);
1612 if (BB->getParent() == 0)
1613 Out << "\t\t; Error: Block without parent!";
1614 else if (BB != &BB->getParent()->getEntryBlock()) { // Not the entry block?
1615 // Output predecessors for the block...
1617 pred_const_iterator PI = pred_begin(BB), PE = pred_end(BB);
1620 Out << " No predecessors!";
1623 writeOperand(*PI, false);
1624 for (++PI; PI != PE; ++PI) {
1626 writeOperand(*PI, false);
1633 if (AnnotationWriter) AnnotationWriter->emitBasicBlockStartAnnot(BB, Out);
1635 // Output all of the instructions in the basic block...
1636 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I != E; ++I) {
1637 printInstruction(*I);
1641 if (AnnotationWriter) AnnotationWriter->emitBasicBlockEndAnnot(BB, Out);
1645 /// printInfoComment - Print a little comment after the instruction indicating
1646 /// which slot it occupies.
1648 void AssemblyWriter::printInfoComment(const Value &V) {
1649 if (V.getType() != Type::VoidTy) {
1651 TypePrinter.print(V.getType(), Out);
1654 if (!V.hasName() && !isa<Instruction>(V)) {
1656 if (const GlobalValue *GV = dyn_cast<GlobalValue>(&V))
1657 SlotNum = Machine.getGlobalSlot(GV);
1659 SlotNum = Machine.getLocalSlot(&V);
1663 Out << ':' << SlotNum; // Print out the def slot taken.
1665 Out << " [#uses=" << V.getNumUses() << ']'; // Output # uses
1669 // This member is called for each Instruction in a function..
1670 void AssemblyWriter::printInstruction(const Instruction &I) {
1671 if (AnnotationWriter) AnnotationWriter->emitInstructionAnnot(&I, Out);
1675 // Print out name if it exists...
1677 PrintLLVMName(Out, &I);
1679 } else if (I.getType() != Type::VoidTy) {
1680 // Print out the def slot taken.
1681 int SlotNum = Machine.getLocalSlot(&I);
1683 Out << "<badref> = ";
1685 Out << '%' << SlotNum << " = ";
1688 // If this is a volatile load or store, print out the volatile marker.
1689 if ((isa<LoadInst>(I) && cast<LoadInst>(I).isVolatile()) ||
1690 (isa<StoreInst>(I) && cast<StoreInst>(I).isVolatile())) {
1692 } else if (isa<CallInst>(I) && cast<CallInst>(I).isTailCall()) {
1693 // If this is a call, check if it's a tail call.
1697 // Print out the opcode...
1698 Out << I.getOpcodeName();
1700 // Print out optimization information.
1701 WriteOptimizationInfo(Out, &I);
1703 // Print out the compare instruction predicates
1704 if (const CmpInst *CI = dyn_cast<CmpInst>(&I))
1705 Out << ' ' << getPredicateText(CI->getPredicate());
1707 // Print out the type of the operands...
1708 const Value *Operand = I.getNumOperands() ? I.getOperand(0) : 0;
1710 // Special case conditional branches to swizzle the condition out to the front
1711 if (isa<BranchInst>(I) && cast<BranchInst>(I).isConditional()) {
1712 BranchInst &BI(cast<BranchInst>(I));
1714 writeOperand(BI.getCondition(), true);
1716 writeOperand(BI.getSuccessor(0), true);
1718 writeOperand(BI.getSuccessor(1), true);
1720 } else if (isa<SwitchInst>(I)) {
1721 // Special case switch statement to get formatting nice and correct...
1723 writeOperand(Operand , true);
1725 writeOperand(I.getOperand(1), true);
1728 for (unsigned op = 2, Eop = I.getNumOperands(); op < Eop; op += 2) {
1730 writeOperand(I.getOperand(op ), true);
1732 writeOperand(I.getOperand(op+1), true);
1735 } else if (isa<PHINode>(I)) {
1737 TypePrinter.print(I.getType(), Out);
1740 for (unsigned op = 0, Eop = I.getNumOperands(); op < Eop; op += 2) {
1741 if (op) Out << ", ";
1743 writeOperand(I.getOperand(op ), false); Out << ", ";
1744 writeOperand(I.getOperand(op+1), false); Out << " ]";
1746 } else if (const ExtractValueInst *EVI = dyn_cast<ExtractValueInst>(&I)) {
1748 writeOperand(I.getOperand(0), true);
1749 for (const unsigned *i = EVI->idx_begin(), *e = EVI->idx_end(); i != e; ++i)
1751 } else if (const InsertValueInst *IVI = dyn_cast<InsertValueInst>(&I)) {
1753 writeOperand(I.getOperand(0), true); Out << ", ";
1754 writeOperand(I.getOperand(1), true);
1755 for (const unsigned *i = IVI->idx_begin(), *e = IVI->idx_end(); i != e; ++i)
1757 } else if (isa<ReturnInst>(I) && !Operand) {
1759 } else if (const CallInst *CI = dyn_cast<CallInst>(&I)) {
1760 // Print the calling convention being used.
1761 switch (CI->getCallingConv()) {
1762 case CallingConv::C: break; // default
1763 case CallingConv::Fast: Out << " fastcc"; break;
1764 case CallingConv::Cold: Out << " coldcc"; break;
1765 case CallingConv::X86_StdCall: Out << " x86_stdcallcc"; break;
1766 case CallingConv::X86_FastCall: Out << " x86_fastcallcc"; break;
1767 case CallingConv::ARM_APCS: Out << " arm_apcscc "; break;
1768 case CallingConv::ARM_AAPCS: Out << " arm_aapcscc "; break;
1769 case CallingConv::ARM_AAPCS_VFP:Out << " arm_aapcs_vfpcc "; break;
1770 default: Out << " cc" << CI->getCallingConv(); break;
1773 const PointerType *PTy = cast<PointerType>(Operand->getType());
1774 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
1775 const Type *RetTy = FTy->getReturnType();
1776 const AttrListPtr &PAL = CI->getAttributes();
1778 if (PAL.getRetAttributes() != Attribute::None)
1779 Out << ' ' << Attribute::getAsString(PAL.getRetAttributes());
1781 // If possible, print out the short form of the call instruction. We can
1782 // only do this if the first argument is a pointer to a nonvararg function,
1783 // and if the return type is not a pointer to a function.
1786 if (!FTy->isVarArg() &&
1787 (!isa<PointerType>(RetTy) ||
1788 !isa<FunctionType>(cast<PointerType>(RetTy)->getElementType()))) {
1789 TypePrinter.print(RetTy, Out);
1791 writeOperand(Operand, false);
1793 writeOperand(Operand, true);
1796 for (unsigned op = 1, Eop = I.getNumOperands(); op < Eop; ++op) {
1799 writeParamOperand(I.getOperand(op), PAL.getParamAttributes(op));
1802 if (PAL.getFnAttributes() != Attribute::None)
1803 Out << ' ' << Attribute::getAsString(PAL.getFnAttributes());
1804 } else if (const InvokeInst *II = dyn_cast<InvokeInst>(&I)) {
1805 const PointerType *PTy = cast<PointerType>(Operand->getType());
1806 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
1807 const Type *RetTy = FTy->getReturnType();
1808 const AttrListPtr &PAL = II->getAttributes();
1810 // Print the calling convention being used.
1811 switch (II->getCallingConv()) {
1812 case CallingConv::C: break; // default
1813 case CallingConv::Fast: Out << " fastcc"; break;
1814 case CallingConv::Cold: Out << " coldcc"; break;
1815 case CallingConv::X86_StdCall: Out << " x86_stdcallcc"; break;
1816 case CallingConv::X86_FastCall: Out << " x86_fastcallcc"; break;
1817 case CallingConv::ARM_APCS: Out << " arm_apcscc "; break;
1818 case CallingConv::ARM_AAPCS: Out << " arm_aapcscc "; break;
1819 case CallingConv::ARM_AAPCS_VFP:Out << " arm_aapcs_vfpcc "; break;
1820 default: Out << " cc" << II->getCallingConv(); break;
1823 if (PAL.getRetAttributes() != Attribute::None)
1824 Out << ' ' << Attribute::getAsString(PAL.getRetAttributes());
1826 // If possible, print out the short form of the invoke instruction. We can
1827 // only do this if the first argument is a pointer to a nonvararg function,
1828 // and if the return type is not a pointer to a function.
1831 if (!FTy->isVarArg() &&
1832 (!isa<PointerType>(RetTy) ||
1833 !isa<FunctionType>(cast<PointerType>(RetTy)->getElementType()))) {
1834 TypePrinter.print(RetTy, Out);
1836 writeOperand(Operand, false);
1838 writeOperand(Operand, true);
1841 for (unsigned op = 3, Eop = I.getNumOperands(); op < Eop; ++op) {
1844 writeParamOperand(I.getOperand(op), PAL.getParamAttributes(op-2));
1848 if (PAL.getFnAttributes() != Attribute::None)
1849 Out << ' ' << Attribute::getAsString(PAL.getFnAttributes());
1851 Out << "\n\t\t\tto ";
1852 writeOperand(II->getNormalDest(), true);
1854 writeOperand(II->getUnwindDest(), true);
1856 } else if (const AllocationInst *AI = dyn_cast<AllocationInst>(&I)) {
1858 TypePrinter.print(AI->getType()->getElementType(), Out);
1859 if (AI->isArrayAllocation()) {
1861 writeOperand(AI->getArraySize(), true);
1863 if (AI->getAlignment()) {
1864 Out << ", align " << AI->getAlignment();
1866 } else if (isa<CastInst>(I)) {
1869 writeOperand(Operand, true); // Work with broken code
1872 TypePrinter.print(I.getType(), Out);
1873 } else if (isa<VAArgInst>(I)) {
1876 writeOperand(Operand, true); // Work with broken code
1879 TypePrinter.print(I.getType(), Out);
1880 } else if (Operand) { // Print the normal way.
1882 // PrintAllTypes - Instructions who have operands of all the same type
1883 // omit the type from all but the first operand. If the instruction has
1884 // different type operands (for example br), then they are all printed.
1885 bool PrintAllTypes = false;
1886 const Type *TheType = Operand->getType();
1888 // Select, Store and ShuffleVector always print all types.
1889 if (isa<SelectInst>(I) || isa<StoreInst>(I) || isa<ShuffleVectorInst>(I)
1890 || isa<ReturnInst>(I)) {
1891 PrintAllTypes = true;
1893 for (unsigned i = 1, E = I.getNumOperands(); i != E; ++i) {
1894 Operand = I.getOperand(i);
1895 // note that Operand shouldn't be null, but the test helps make dump()
1896 // more tolerant of malformed IR
1897 if (Operand && Operand->getType() != TheType) {
1898 PrintAllTypes = true; // We have differing types! Print them all!
1904 if (!PrintAllTypes) {
1906 TypePrinter.print(TheType, Out);
1910 for (unsigned i = 0, E = I.getNumOperands(); i != E; ++i) {
1912 writeOperand(I.getOperand(i), PrintAllTypes);
1916 // Print post operand alignment for load/store
1917 if (isa<LoadInst>(I) && cast<LoadInst>(I).getAlignment()) {
1918 Out << ", align " << cast<LoadInst>(I).getAlignment();
1919 } else if (isa<StoreInst>(I) && cast<StoreInst>(I).getAlignment()) {
1920 Out << ", align " << cast<StoreInst>(I).getAlignment();
1923 printInfoComment(I);
1927 //===----------------------------------------------------------------------===//
1928 // External Interface declarations
1929 //===----------------------------------------------------------------------===//
1931 void Module::print(std::ostream &o, AssemblyAnnotationWriter *AAW) const {
1932 raw_os_ostream OS(o);
1935 void Module::print(raw_ostream &OS, AssemblyAnnotationWriter *AAW) const {
1936 SlotTracker SlotTable(this);
1937 AssemblyWriter W(OS, SlotTable, this, AAW);
1941 void Type::print(std::ostream &o) const {
1942 raw_os_ostream OS(o);
1946 void Type::print(raw_ostream &OS) const {
1948 OS << "<null Type>";
1951 TypePrinting().print(this, OS);
1954 void Value::print(raw_ostream &OS, AssemblyAnnotationWriter *AAW) const {
1956 OS << "printing a <null> value\n";
1959 if (const Instruction *I = dyn_cast<Instruction>(this)) {
1960 const Function *F = I->getParent() ? I->getParent()->getParent() : 0;
1961 SlotTracker SlotTable(F);
1962 AssemblyWriter W(OS, SlotTable, F ? F->getParent() : 0, AAW);
1964 } else if (const BasicBlock *BB = dyn_cast<BasicBlock>(this)) {
1965 SlotTracker SlotTable(BB->getParent());
1966 AssemblyWriter W(OS, SlotTable,
1967 BB->getParent() ? BB->getParent()->getParent() : 0, AAW);
1969 } else if (const GlobalValue *GV = dyn_cast<GlobalValue>(this)) {
1970 SlotTracker SlotTable(GV->getParent());
1971 AssemblyWriter W(OS, SlotTable, GV->getParent(), AAW);
1973 } else if (const MDString *MDS = dyn_cast<MDString>(this)) {
1974 TypePrinting TypePrinter;
1975 TypePrinter.print(MDS->getType(), OS);
1978 PrintEscapedString(MDS->getString(), OS);
1980 } else if (const MDNode *N = dyn_cast<MDNode>(this)) {
1981 SlotTracker SlotTable(N);
1982 TypePrinting TypePrinter;
1983 SlotTable.initialize();
1984 WriteMDNodes(OS, TypePrinter, SlotTable);
1985 } else if (const Constant *C = dyn_cast<Constant>(this)) {
1986 TypePrinting TypePrinter;
1987 TypePrinter.print(C->getType(), OS);
1989 WriteConstantInt(OS, C, TypePrinter, 0);
1990 } else if (const Argument *A = dyn_cast<Argument>(this)) {
1991 WriteAsOperand(OS, this, true,
1992 A->getParent() ? A->getParent()->getParent() : 0);
1993 } else if (isa<InlineAsm>(this)) {
1994 WriteAsOperand(OS, this, true, 0);
1996 llvm_unreachable("Unknown value to print out!");
2000 void Value::print(std::ostream &O, AssemblyAnnotationWriter *AAW) const {
2001 raw_os_ostream OS(O);
2005 // Value::dump - allow easy printing of Values from the debugger.
2006 void Value::dump() const { print(errs()); errs() << '\n'; }
2008 // Type::dump - allow easy printing of Types from the debugger.
2009 // This one uses type names from the given context module
2010 void Type::dump(const Module *Context) const {
2011 WriteTypeSymbolic(errs(), this, Context);
2015 // Type::dump - allow easy printing of Types from the debugger.
2016 void Type::dump() const { dump(0); }
2018 // Module::dump() - Allow printing of Modules from the debugger.
2019 void Module::dump() const { print(errs(), 0); }