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/Metadata.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/Dwarf.h"
36 #include "llvm/Support/ErrorHandling.h"
37 #include "llvm/Support/MathExtras.h"
38 #include "llvm/Support/FormattedStream.h"
44 // Make virtual table appear in this compilation unit.
45 AssemblyAnnotationWriter::~AssemblyAnnotationWriter() {}
47 //===----------------------------------------------------------------------===//
49 //===----------------------------------------------------------------------===//
51 static const Module *getModuleFromVal(const Value *V) {
52 if (const Argument *MA = dyn_cast<Argument>(V))
53 return MA->getParent() ? MA->getParent()->getParent() : 0;
55 if (const BasicBlock *BB = dyn_cast<BasicBlock>(V))
56 return BB->getParent() ? BB->getParent()->getParent() : 0;
58 if (const Instruction *I = dyn_cast<Instruction>(V)) {
59 const Function *M = I->getParent() ? I->getParent()->getParent() : 0;
60 return M ? M->getParent() : 0;
63 if (const GlobalValue *GV = dyn_cast<GlobalValue>(V))
64 return GV->getParent();
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(const StringRef &Name,
72 for (unsigned i = 0, e = Name.size(); i != e; ++i) {
73 unsigned char C = Name[i];
74 if (isprint(C) && C != '\\' && C != '"')
77 Out << '\\' << hexdigit(C >> 4) << hexdigit(C & 0x0F);
88 /// PrintLLVMName - Turn the specified name into an 'LLVM name', which is either
89 /// prefixed with % (if the string only contains simple characters) or is
90 /// surrounded with ""'s (if it has special chars in it). Print it out.
91 static void PrintLLVMName(raw_ostream &OS, const StringRef &Name,
93 assert(Name.data() && "Cannot get empty name!");
95 default: llvm_unreachable("Bad prefix!");
97 case GlobalPrefix: OS << '@'; break;
98 case LabelPrefix: break;
99 case LocalPrefix: OS << '%'; break;
102 // Scan the name to see if it needs quotes first.
103 bool NeedsQuotes = isdigit(Name[0]);
105 for (unsigned i = 0, e = Name.size(); i != e; ++i) {
107 if (!isalnum(C) && C != '-' && C != '.' && C != '_') {
114 // If we didn't need any quotes, just write out the name in one blast.
120 // Okay, we need quotes. Output the quotes and escape any scary characters as
123 PrintEscapedString(Name, OS);
127 /// PrintLLVMName - Turn the specified name into an 'LLVM name', which is either
128 /// prefixed with % (if the string only contains simple characters) or is
129 /// surrounded with ""'s (if it has special chars in it). Print it out.
130 static void PrintLLVMName(raw_ostream &OS, const Value *V) {
131 PrintLLVMName(OS, V->getName(),
132 isa<GlobalValue>(V) ? GlobalPrefix : LocalPrefix);
135 //===----------------------------------------------------------------------===//
136 // TypePrinting Class: Type printing machinery
137 //===----------------------------------------------------------------------===//
139 static DenseMap<const Type *, std::string> &getTypeNamesMap(void *M) {
140 return *static_cast<DenseMap<const Type *, std::string>*>(M);
143 void TypePrinting::clear() {
144 getTypeNamesMap(TypeNames).clear();
147 bool TypePrinting::hasTypeName(const Type *Ty) const {
148 return getTypeNamesMap(TypeNames).count(Ty);
151 void TypePrinting::addTypeName(const Type *Ty, const std::string &N) {
152 getTypeNamesMap(TypeNames).insert(std::make_pair(Ty, N));
156 TypePrinting::TypePrinting() {
157 TypeNames = new DenseMap<const Type *, std::string>();
160 TypePrinting::~TypePrinting() {
161 delete &getTypeNamesMap(TypeNames);
164 /// CalcTypeName - Write the specified type to the specified raw_ostream, making
165 /// use of type names or up references to shorten the type name where possible.
166 void TypePrinting::CalcTypeName(const Type *Ty,
167 SmallVectorImpl<const Type *> &TypeStack,
168 raw_ostream &OS, bool IgnoreTopLevelName) {
169 // Check to see if the type is named.
170 if (!IgnoreTopLevelName) {
171 DenseMap<const Type *, std::string> &TM = getTypeNamesMap(TypeNames);
172 DenseMap<const Type *, std::string>::iterator I = TM.find(Ty);
179 // Check to see if the Type is already on the stack...
180 unsigned Slot = 0, CurSize = TypeStack.size();
181 while (Slot < CurSize && TypeStack[Slot] != Ty) ++Slot; // Scan for type
183 // This is another base case for the recursion. In this case, we know
184 // that we have looped back to a type that we have previously visited.
185 // Generate the appropriate upreference to handle this.
186 if (Slot < CurSize) {
187 OS << '\\' << unsigned(CurSize-Slot); // Here's the upreference
191 TypeStack.push_back(Ty); // Recursive case: Add us to the stack..
193 switch (Ty->getTypeID()) {
194 case Type::VoidTyID: OS << "void"; break;
195 case Type::FloatTyID: OS << "float"; break;
196 case Type::DoubleTyID: OS << "double"; break;
197 case Type::X86_FP80TyID: OS << "x86_fp80"; break;
198 case Type::FP128TyID: OS << "fp128"; break;
199 case Type::PPC_FP128TyID: OS << "ppc_fp128"; break;
200 case Type::LabelTyID: OS << "label"; break;
201 case Type::MetadataTyID: OS << "metadata"; break;
202 case Type::IntegerTyID:
203 OS << 'i' << cast<IntegerType>(Ty)->getBitWidth();
206 case Type::FunctionTyID: {
207 const FunctionType *FTy = cast<FunctionType>(Ty);
208 CalcTypeName(FTy->getReturnType(), TypeStack, OS);
210 for (FunctionType::param_iterator I = FTy->param_begin(),
211 E = FTy->param_end(); I != E; ++I) {
212 if (I != FTy->param_begin())
214 CalcTypeName(*I, TypeStack, OS);
216 if (FTy->isVarArg()) {
217 if (FTy->getNumParams()) OS << ", ";
223 case Type::StructTyID: {
224 const StructType *STy = cast<StructType>(Ty);
228 for (StructType::element_iterator I = STy->element_begin(),
229 E = STy->element_end(); I != E; ++I) {
230 CalcTypeName(*I, TypeStack, OS);
231 if (next(I) != STy->element_end())
240 case Type::PointerTyID: {
241 const PointerType *PTy = cast<PointerType>(Ty);
242 CalcTypeName(PTy->getElementType(), TypeStack, OS);
243 if (unsigned AddressSpace = PTy->getAddressSpace())
244 OS << " addrspace(" << AddressSpace << ')';
248 case Type::ArrayTyID: {
249 const ArrayType *ATy = cast<ArrayType>(Ty);
250 OS << '[' << ATy->getNumElements() << " x ";
251 CalcTypeName(ATy->getElementType(), TypeStack, OS);
255 case Type::VectorTyID: {
256 const VectorType *PTy = cast<VectorType>(Ty);
257 OS << "<" << PTy->getNumElements() << " x ";
258 CalcTypeName(PTy->getElementType(), TypeStack, OS);
262 case Type::OpaqueTyID:
266 OS << "<unrecognized-type>";
270 TypeStack.pop_back(); // Remove self from stack.
273 /// printTypeInt - The internal guts of printing out a type that has a
274 /// potentially named portion.
276 void TypePrinting::print(const Type *Ty, raw_ostream &OS,
277 bool IgnoreTopLevelName) {
278 // Check to see if the type is named.
279 DenseMap<const Type*, std::string> &TM = getTypeNamesMap(TypeNames);
280 if (!IgnoreTopLevelName) {
281 DenseMap<const Type*, std::string>::iterator I = TM.find(Ty);
288 // Otherwise we have a type that has not been named but is a derived type.
289 // Carefully recurse the type hierarchy to print out any contained symbolic
291 SmallVector<const Type *, 16> TypeStack;
292 std::string TypeName;
294 raw_string_ostream TypeOS(TypeName);
295 CalcTypeName(Ty, TypeStack, TypeOS, IgnoreTopLevelName);
298 // Cache type name for later use.
299 if (!IgnoreTopLevelName)
300 TM.insert(std::make_pair(Ty, TypeOS.str()));
305 // To avoid walking constant expressions multiple times and other IR
306 // objects, we keep several helper maps.
307 DenseSet<const Value*> VisitedConstants;
308 DenseSet<const Type*> VisitedTypes;
311 std::vector<const Type*> &NumberedTypes;
313 TypeFinder(TypePrinting &tp, std::vector<const Type*> &numberedTypes)
314 : TP(tp), NumberedTypes(numberedTypes) {}
316 void Run(const Module &M) {
317 // Get types from the type symbol table. This gets opaque types referened
318 // only through derived named types.
319 const TypeSymbolTable &ST = M.getTypeSymbolTable();
320 for (TypeSymbolTable::const_iterator TI = ST.begin(), E = ST.end();
322 IncorporateType(TI->second);
324 // Get types from global variables.
325 for (Module::const_global_iterator I = M.global_begin(),
326 E = M.global_end(); I != E; ++I) {
327 IncorporateType(I->getType());
328 if (I->hasInitializer())
329 IncorporateValue(I->getInitializer());
332 // Get types from aliases.
333 for (Module::const_alias_iterator I = M.alias_begin(),
334 E = M.alias_end(); I != E; ++I) {
335 IncorporateType(I->getType());
336 IncorporateValue(I->getAliasee());
339 // Get types from functions.
340 for (Module::const_iterator FI = M.begin(), E = M.end(); FI != E; ++FI) {
341 IncorporateType(FI->getType());
343 for (Function::const_iterator BB = FI->begin(), E = FI->end();
345 for (BasicBlock::const_iterator II = BB->begin(),
346 E = BB->end(); II != E; ++II) {
347 const Instruction &I = *II;
348 // Incorporate the type of the instruction and all its operands.
349 IncorporateType(I.getType());
350 for (User::const_op_iterator OI = I.op_begin(), OE = I.op_end();
352 IncorporateValue(*OI);
358 void IncorporateType(const Type *Ty) {
359 // Check to see if we're already visited this type.
360 if (!VisitedTypes.insert(Ty).second)
363 // If this is a structure or opaque type, add a name for the type.
364 if (((isa<StructType>(Ty) && cast<StructType>(Ty)->getNumElements())
365 || isa<OpaqueType>(Ty)) && !TP.hasTypeName(Ty)) {
366 TP.addTypeName(Ty, "%"+utostr(unsigned(NumberedTypes.size())));
367 NumberedTypes.push_back(Ty);
370 // Recursively walk all contained types.
371 for (Type::subtype_iterator I = Ty->subtype_begin(),
372 E = Ty->subtype_end(); I != E; ++I)
376 /// IncorporateValue - This method is used to walk operand lists finding
377 /// types hiding in constant expressions and other operands that won't be
378 /// walked in other ways. GlobalValues, basic blocks, instructions, and
379 /// inst operands are all explicitly enumerated.
380 void IncorporateValue(const Value *V) {
381 if (V == 0 || !isa<Constant>(V) || isa<GlobalValue>(V)) return;
384 if (!VisitedConstants.insert(V).second)
388 IncorporateType(V->getType());
390 // Look in operands for types.
391 const Constant *C = cast<Constant>(V);
392 for (Constant::const_op_iterator I = C->op_begin(),
393 E = C->op_end(); I != E;++I)
394 IncorporateValue(*I);
397 } // end anonymous namespace
400 /// AddModuleTypesToPrinter - Add all of the symbolic type names for types in
401 /// the specified module to the TypePrinter and all numbered types to it and the
402 /// NumberedTypes table.
403 static void AddModuleTypesToPrinter(TypePrinting &TP,
404 std::vector<const Type*> &NumberedTypes,
408 // If the module has a symbol table, take all global types and stuff their
409 // names into the TypeNames map.
410 const TypeSymbolTable &ST = M->getTypeSymbolTable();
411 for (TypeSymbolTable::const_iterator TI = ST.begin(), E = ST.end();
413 const Type *Ty = cast<Type>(TI->second);
415 // As a heuristic, don't insert pointer to primitive types, because
416 // they are used too often to have a single useful name.
417 if (const PointerType *PTy = dyn_cast<PointerType>(Ty)) {
418 const Type *PETy = PTy->getElementType();
419 if ((PETy->isPrimitiveType() || PETy->isInteger()) &&
420 !isa<OpaqueType>(PETy))
424 // Likewise don't insert primitives either.
425 if (Ty->isInteger() || Ty->isPrimitiveType())
428 // Get the name as a string and insert it into TypeNames.
430 raw_string_ostream NameROS(NameStr);
431 formatted_raw_ostream NameOS(NameROS);
432 PrintLLVMName(NameOS, TI->first, LocalPrefix);
434 TP.addTypeName(Ty, NameStr);
437 // Walk the entire module to find references to unnamed structure and opaque
438 // types. This is required for correctness by opaque types (because multiple
439 // uses of an unnamed opaque type needs to be referred to by the same ID) and
440 // it shrinks complex recursive structure types substantially in some cases.
441 TypeFinder(TP, NumberedTypes).Run(*M);
445 /// WriteTypeSymbolic - This attempts to write the specified type as a symbolic
446 /// type, iff there is an entry in the modules symbol table for the specified
447 /// type or one of it's component types.
449 void llvm::WriteTypeSymbolic(raw_ostream &OS, const Type *Ty, const Module *M) {
450 TypePrinting Printer;
451 std::vector<const Type*> NumberedTypes;
452 AddModuleTypesToPrinter(Printer, NumberedTypes, M);
453 Printer.print(Ty, OS);
456 //===----------------------------------------------------------------------===//
457 // SlotTracker Class: Enumerate slot numbers for unnamed values
458 //===----------------------------------------------------------------------===//
462 /// This class provides computation of slot numbers for LLVM Assembly writing.
466 /// ValueMap - A mapping of Values to slot numbers.
467 typedef DenseMap<const Value*, unsigned> ValueMap;
470 /// TheModule - The module for which we are holding slot numbers.
471 const Module* TheModule;
473 /// TheFunction - The function for which we are holding slot numbers.
474 const Function* TheFunction;
475 bool FunctionProcessed;
477 /// TheMDNode - The MDNode for which we are holding slot numbers.
478 const MDNode *TheMDNode;
480 /// TheNamedMDNode - The MDNode for which we are holding slot numbers.
481 const NamedMDNode *TheNamedMDNode;
483 /// mMap - The TypePlanes map for the module level data.
487 /// fMap - The TypePlanes map for the function level data.
491 /// mdnMap - Map for MDNodes.
495 /// Construct from a module
496 explicit SlotTracker(const Module *M);
497 /// Construct from a function, starting out in incorp state.
498 explicit SlotTracker(const Function *F);
499 /// Construct from a mdnode.
500 explicit SlotTracker(const MDNode *N);
501 /// Construct from a named mdnode.
502 explicit SlotTracker(const NamedMDNode *N);
504 /// Return the slot number of the specified value in it's type
505 /// plane. If something is not in the SlotTracker, return -1.
506 int getLocalSlot(const Value *V);
507 int getGlobalSlot(const GlobalValue *V);
508 int getMetadataSlot(const MDNode *N);
510 /// If you'd like to deal with a function instead of just a module, use
511 /// this method to get its data into the SlotTracker.
512 void incorporateFunction(const Function *F) {
514 FunctionProcessed = false;
517 /// After calling incorporateFunction, use this method to remove the
518 /// most recently incorporated function from the SlotTracker. This
519 /// will reset the state of the machine back to just the module contents.
520 void purgeFunction();
522 /// MDNode map iterators.
523 ValueMap::iterator mdnBegin() { return mdnMap.begin(); }
524 ValueMap::iterator mdnEnd() { return mdnMap.end(); }
525 unsigned mdnSize() const { return mdnMap.size(); }
526 bool mdnEmpty() const { return mdnMap.empty(); }
528 /// This function does the actual initialization.
529 inline void initialize();
531 // Implementation Details
533 /// CreateModuleSlot - Insert the specified GlobalValue* into the slot table.
534 void CreateModuleSlot(const GlobalValue *V);
536 /// CreateMetadataSlot - Insert the specified MDNode* into the slot table.
537 void CreateMetadataSlot(const MDNode *N);
539 /// CreateFunctionSlot - Insert the specified Value* into the slot table.
540 void CreateFunctionSlot(const Value *V);
542 /// Add all of the module level global variables (and their initializers)
543 /// and function declarations, but not the contents of those functions.
544 void processModule();
546 /// Add all of the functions arguments, basic blocks, and instructions.
547 void processFunction();
549 /// Add all MDNode operands.
550 void processMDNode();
552 /// Add all MDNode operands.
553 void processNamedMDNode();
555 SlotTracker(const SlotTracker &); // DO NOT IMPLEMENT
556 void operator=(const SlotTracker &); // DO NOT IMPLEMENT
559 } // end anonymous namespace
562 static SlotTracker *createSlotTracker(const Value *V) {
563 if (const Argument *FA = dyn_cast<Argument>(V))
564 return new SlotTracker(FA->getParent());
566 if (const Instruction *I = dyn_cast<Instruction>(V))
567 return new SlotTracker(I->getParent()->getParent());
569 if (const BasicBlock *BB = dyn_cast<BasicBlock>(V))
570 return new SlotTracker(BB->getParent());
572 if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(V))
573 return new SlotTracker(GV->getParent());
575 if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(V))
576 return new SlotTracker(GA->getParent());
578 if (const Function *Func = dyn_cast<Function>(V))
579 return new SlotTracker(Func);
585 #define ST_DEBUG(X) errs() << X
590 // Module level constructor. Causes the contents of the Module (sans functions)
591 // to be added to the slot table.
592 SlotTracker::SlotTracker(const Module *M)
593 : TheModule(M), TheFunction(0), FunctionProcessed(false), TheMDNode(0),
594 TheNamedMDNode(0), mNext(0), fNext(0), mdnNext(0) {
597 // Function level constructor. Causes the contents of the Module and the one
598 // function provided to be added to the slot table.
599 SlotTracker::SlotTracker(const Function *F)
600 : TheModule(F ? F->getParent() : 0), TheFunction(F), FunctionProcessed(false),
601 TheMDNode(0), TheNamedMDNode(0), mNext(0), fNext(0), mdnNext(0) {
604 // Constructor to handle single MDNode.
605 SlotTracker::SlotTracker(const MDNode *C)
606 : TheModule(0), TheFunction(0), FunctionProcessed(false), TheMDNode(C),
607 TheNamedMDNode(0), mNext(0), fNext(0), mdnNext(0) {
610 // Constructor to handle single NamedMDNode.
611 SlotTracker::SlotTracker(const NamedMDNode *N)
612 : TheModule(0), TheFunction(0), FunctionProcessed(false), TheMDNode(0),
613 TheNamedMDNode(N), mNext(0), fNext(0), mdnNext(0) {
616 inline void SlotTracker::initialize() {
619 TheModule = 0; ///< Prevent re-processing next time we're called.
622 if (TheFunction && !FunctionProcessed)
629 processNamedMDNode();
632 // Iterate through all the global variables, functions, and global
633 // variable initializers and create slots for them.
634 void SlotTracker::processModule() {
635 ST_DEBUG("begin processModule!\n");
637 // Add all of the unnamed global variables to the value table.
638 for (Module::const_global_iterator I = TheModule->global_begin(),
639 E = TheModule->global_end(); I != E; ++I) {
642 if (I->hasInitializer()) {
643 if (MDNode *N = dyn_cast<MDNode>(I->getInitializer()))
644 CreateMetadataSlot(N);
648 // Add metadata used by named metadata.
649 for (Module::const_named_metadata_iterator
650 I = TheModule->named_metadata_begin(),
651 E = TheModule->named_metadata_end(); I != E; ++I) {
652 const NamedMDNode *NMD = I;
653 for (unsigned i = 0, e = NMD->getNumElements(); i != e; ++i) {
654 MDNode *MD = dyn_cast_or_null<MDNode>(NMD->getElement(i));
656 CreateMetadataSlot(MD);
660 // Add all the unnamed functions to the table.
661 for (Module::const_iterator I = TheModule->begin(), E = TheModule->end();
666 ST_DEBUG("end processModule!\n");
669 // Process the arguments, basic blocks, and instructions of a function.
670 void SlotTracker::processFunction() {
671 ST_DEBUG("begin processFunction!\n");
674 // Add all the function arguments with no names.
675 for(Function::const_arg_iterator AI = TheFunction->arg_begin(),
676 AE = TheFunction->arg_end(); AI != AE; ++AI)
678 CreateFunctionSlot(AI);
680 ST_DEBUG("Inserting Instructions:\n");
682 MetadataContext &TheMetadata = TheFunction->getContext().getMetadata();
684 // Add all of the basic blocks and instructions with no names.
685 for (Function::const_iterator BB = TheFunction->begin(),
686 E = TheFunction->end(); BB != E; ++BB) {
688 CreateFunctionSlot(BB);
689 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I != E;
691 if (I->getType() != Type::getVoidTy(TheFunction->getContext()) &&
693 CreateFunctionSlot(I);
694 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
695 if (MDNode *N = dyn_cast_or_null<MDNode>(I->getOperand(i)))
696 CreateMetadataSlot(N);
698 // Process metadata attached with this instruction.
699 const MetadataContext::MDMapTy *MDs = TheMetadata.getMDs(I);
701 for (MetadataContext::MDMapTy::const_iterator MI = MDs->begin(),
702 ME = MDs->end(); MI != ME; ++MI)
703 if (MDNode *MDN = dyn_cast_or_null<MDNode>(MI->second))
704 CreateMetadataSlot(MDN);
708 FunctionProcessed = true;
710 ST_DEBUG("end processFunction!\n");
713 /// processMDNode - Process TheMDNode.
714 void SlotTracker::processMDNode() {
715 ST_DEBUG("begin processMDNode!\n");
717 CreateMetadataSlot(TheMDNode);
719 ST_DEBUG("end processMDNode!\n");
722 /// processNamedMDNode - Process TheNamedMDNode.
723 void SlotTracker::processNamedMDNode() {
724 ST_DEBUG("begin processNamedMDNode!\n");
726 for (unsigned i = 0, e = TheNamedMDNode->getNumElements(); i != e; ++i) {
727 MDNode *MD = dyn_cast_or_null<MDNode>(TheNamedMDNode->getElement(i));
729 CreateMetadataSlot(MD);
732 ST_DEBUG("end processNamedMDNode!\n");
735 /// Clean up after incorporating a function. This is the only way to get out of
736 /// the function incorporation state that affects get*Slot/Create*Slot. Function
737 /// incorporation state is indicated by TheFunction != 0.
738 void SlotTracker::purgeFunction() {
739 ST_DEBUG("begin purgeFunction!\n");
740 fMap.clear(); // Simply discard the function level map
742 FunctionProcessed = false;
743 ST_DEBUG("end purgeFunction!\n");
746 /// getGlobalSlot - Get the slot number of a global value.
747 int SlotTracker::getGlobalSlot(const GlobalValue *V) {
748 // Check for uninitialized state and do lazy initialization.
751 // Find the type plane in the module map
752 ValueMap::iterator MI = mMap.find(V);
753 return MI == mMap.end() ? -1 : (int)MI->second;
756 /// getGlobalSlot - Get the slot number of a MDNode.
757 int SlotTracker::getMetadataSlot(const MDNode *N) {
758 // Check for uninitialized state and do lazy initialization.
761 // Find the type plane in the module map
762 ValueMap::iterator MI = mdnMap.find(N);
763 return MI == mdnMap.end() ? -1 : (int)MI->second;
767 /// getLocalSlot - Get the slot number for a value that is local to a function.
768 int SlotTracker::getLocalSlot(const Value *V) {
769 assert(!isa<Constant>(V) && "Can't get a constant or global slot with this!");
771 // Check for uninitialized state and do lazy initialization.
774 ValueMap::iterator FI = fMap.find(V);
775 return FI == fMap.end() ? -1 : (int)FI->second;
779 /// CreateModuleSlot - Insert the specified GlobalValue* into the slot table.
780 void SlotTracker::CreateModuleSlot(const GlobalValue *V) {
781 assert(V && "Can't insert a null Value into SlotTracker!");
782 assert(V->getType() != Type::getVoidTy(V->getContext()) &&
783 "Doesn't need a slot!");
784 assert(!V->hasName() && "Doesn't need a slot!");
786 unsigned DestSlot = mNext++;
789 ST_DEBUG(" Inserting value [" << V->getType() << "] = " << V << " slot=" <<
791 // G = Global, F = Function, A = Alias, o = other
792 ST_DEBUG((isa<GlobalVariable>(V) ? 'G' :
793 (isa<Function>(V) ? 'F' :
794 (isa<GlobalAlias>(V) ? 'A' : 'o'))) << "]\n");
797 /// CreateSlot - Create a new slot for the specified value if it has no name.
798 void SlotTracker::CreateFunctionSlot(const Value *V) {
799 assert(V->getType() != Type::getVoidTy(TheFunction->getContext()) &&
800 !V->hasName() && "Doesn't need a slot!");
802 unsigned DestSlot = fNext++;
805 // G = Global, F = Function, o = other
806 ST_DEBUG(" Inserting value [" << V->getType() << "] = " << V << " slot=" <<
807 DestSlot << " [o]\n");
810 /// CreateModuleSlot - Insert the specified MDNode* into the slot table.
811 void SlotTracker::CreateMetadataSlot(const MDNode *N) {
812 assert(N && "Can't insert a null Value into SlotTracker!");
814 ValueMap::iterator I = mdnMap.find(N);
815 if (I != mdnMap.end())
818 unsigned DestSlot = mdnNext++;
819 mdnMap[N] = DestSlot;
821 for (MDNode::const_elem_iterator MDI = N->elem_begin(),
822 MDE = N->elem_end(); MDI != MDE; ++MDI) {
823 const Value *TV = *MDI;
825 if (const MDNode *N2 = dyn_cast<MDNode>(TV))
826 CreateMetadataSlot(N2);
830 //===----------------------------------------------------------------------===//
831 // AsmWriter Implementation
832 //===----------------------------------------------------------------------===//
834 static void WriteAsOperandInternal(raw_ostream &Out, const Value *V,
835 TypePrinting *TypePrinter,
836 SlotTracker *Machine);
840 static const char *getPredicateText(unsigned predicate) {
841 const char * pred = "unknown";
843 case FCmpInst::FCMP_FALSE: pred = "false"; break;
844 case FCmpInst::FCMP_OEQ: pred = "oeq"; break;
845 case FCmpInst::FCMP_OGT: pred = "ogt"; break;
846 case FCmpInst::FCMP_OGE: pred = "oge"; break;
847 case FCmpInst::FCMP_OLT: pred = "olt"; break;
848 case FCmpInst::FCMP_OLE: pred = "ole"; break;
849 case FCmpInst::FCMP_ONE: pred = "one"; break;
850 case FCmpInst::FCMP_ORD: pred = "ord"; break;
851 case FCmpInst::FCMP_UNO: pred = "uno"; break;
852 case FCmpInst::FCMP_UEQ: pred = "ueq"; break;
853 case FCmpInst::FCMP_UGT: pred = "ugt"; break;
854 case FCmpInst::FCMP_UGE: pred = "uge"; break;
855 case FCmpInst::FCMP_ULT: pred = "ult"; break;
856 case FCmpInst::FCMP_ULE: pred = "ule"; break;
857 case FCmpInst::FCMP_UNE: pred = "une"; break;
858 case FCmpInst::FCMP_TRUE: pred = "true"; break;
859 case ICmpInst::ICMP_EQ: pred = "eq"; break;
860 case ICmpInst::ICMP_NE: pred = "ne"; break;
861 case ICmpInst::ICMP_SGT: pred = "sgt"; break;
862 case ICmpInst::ICMP_SGE: pred = "sge"; break;
863 case ICmpInst::ICMP_SLT: pred = "slt"; break;
864 case ICmpInst::ICMP_SLE: pred = "sle"; break;
865 case ICmpInst::ICMP_UGT: pred = "ugt"; break;
866 case ICmpInst::ICMP_UGE: pred = "uge"; break;
867 case ICmpInst::ICMP_ULT: pred = "ult"; break;
868 case ICmpInst::ICMP_ULE: pred = "ule"; break;
873 static void WriteMDNodeComment(const MDNode *Node,
874 formatted_raw_ostream &Out) {
875 if (Node->getNumElements() < 1)
877 ConstantInt *CI = dyn_cast_or_null<ConstantInt>(Node->getElement(0));
879 unsigned Val = CI->getZExtValue();
880 unsigned Tag = Val & ~LLVMDebugVersionMask;
881 if (Val >= LLVMDebugVersion) {
882 if (Tag == dwarf::DW_TAG_auto_variable)
883 Out << "; [ DW_TAG_auto_variable ]";
884 else if (Tag == dwarf::DW_TAG_arg_variable)
885 Out << "; [ DW_TAG_arg_variable ]";
886 else if (Tag == dwarf::DW_TAG_return_variable)
887 Out << "; [ DW_TAG_return_variable ]";
888 else if (Tag == dwarf::DW_TAG_vector_type)
889 Out << "; [ DW_TAG_vector_type ]";
890 else if (Tag == dwarf::DW_TAG_user_base)
891 Out << "; [ DW_TAG_user_base ]";
893 Out << "; [" << dwarf::TagString(Tag) << " ]";
897 static void WriteMDNodes(formatted_raw_ostream &Out, TypePrinting &TypePrinter,
898 SlotTracker &Machine) {
899 SmallVector<const MDNode *, 16> Nodes;
900 Nodes.resize(Machine.mdnSize());
901 for (SlotTracker::ValueMap::iterator I =
902 Machine.mdnBegin(), E = Machine.mdnEnd(); I != E; ++I)
903 Nodes[I->second] = cast<MDNode>(I->first);
905 for (unsigned i = 0, e = Nodes.size(); i != e; ++i) {
906 Out << '!' << i << " = metadata ";
907 const MDNode *Node = Nodes[i];
909 for (MDNode::const_elem_iterator NI = Node->elem_begin(),
910 NE = Node->elem_end(); NI != NE;) {
911 const Value *V = *NI;
914 else if (const MDNode *N = dyn_cast<MDNode>(V)) {
916 Out << '!' << Machine.getMetadataSlot(N);
919 TypePrinter.print((*NI)->getType(), Out);
921 WriteAsOperandInternal(Out, *NI, &TypePrinter, &Machine);
928 WriteMDNodeComment(Node, Out);
933 static void WriteOptimizationInfo(raw_ostream &Out, const User *U) {
934 if (const OverflowingBinaryOperator *OBO =
935 dyn_cast<OverflowingBinaryOperator>(U)) {
936 if (OBO->hasNoUnsignedWrap())
938 if (OBO->hasNoSignedWrap())
940 } else if (const SDivOperator *Div = dyn_cast<SDivOperator>(U)) {
943 } else if (const GEPOperator *GEP = dyn_cast<GEPOperator>(U)) {
944 if (GEP->isInBounds())
949 static void WriteConstantInt(raw_ostream &Out, const Constant *CV,
950 TypePrinting &TypePrinter, SlotTracker *Machine) {
951 if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV)) {
952 if (CI->getType() == Type::getInt1Ty(CV->getContext())) {
953 Out << (CI->getZExtValue() ? "true" : "false");
956 Out << CI->getValue();
960 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CV)) {
961 if (&CFP->getValueAPF().getSemantics() == &APFloat::IEEEdouble ||
962 &CFP->getValueAPF().getSemantics() == &APFloat::IEEEsingle) {
963 // We would like to output the FP constant value in exponential notation,
964 // but we cannot do this if doing so will lose precision. Check here to
965 // make sure that we only output it in exponential format if we can parse
966 // the value back and get the same value.
969 bool isDouble = &CFP->getValueAPF().getSemantics()==&APFloat::IEEEdouble;
970 double Val = isDouble ? CFP->getValueAPF().convertToDouble() :
971 CFP->getValueAPF().convertToFloat();
972 std::string StrVal = ftostr(CFP->getValueAPF());
974 // Check to make sure that the stringized number is not some string like
975 // "Inf" or NaN, that atof will accept, but the lexer will not. Check
976 // that the string matches the "[-+]?[0-9]" regex.
978 if ((StrVal[0] >= '0' && StrVal[0] <= '9') ||
979 ((StrVal[0] == '-' || StrVal[0] == '+') &&
980 (StrVal[1] >= '0' && StrVal[1] <= '9'))) {
981 // Reparse stringized version!
982 if (atof(StrVal.c_str()) == Val) {
987 // Otherwise we could not reparse it to exactly the same value, so we must
988 // output the string in hexadecimal format! Note that loading and storing
989 // floating point types changes the bits of NaNs on some hosts, notably
990 // x86, so we must not use these types.
991 assert(sizeof(double) == sizeof(uint64_t) &&
992 "assuming that double is 64 bits!");
994 APFloat apf = CFP->getValueAPF();
995 // Floats are represented in ASCII IR as double, convert.
997 apf.convert(APFloat::IEEEdouble, APFloat::rmNearestTiesToEven,
1000 utohex_buffer(uint64_t(apf.bitcastToAPInt().getZExtValue()),
1005 // Some form of long double. These appear as a magic letter identifying
1006 // the type, then a fixed number of hex digits.
1008 if (&CFP->getValueAPF().getSemantics() == &APFloat::x87DoubleExtended) {
1010 // api needed to prevent premature destruction
1011 APInt api = CFP->getValueAPF().bitcastToAPInt();
1012 const uint64_t* p = api.getRawData();
1013 uint64_t word = p[1];
1015 int width = api.getBitWidth();
1016 for (int j=0; j<width; j+=4, shiftcount-=4) {
1017 unsigned int nibble = (word>>shiftcount) & 15;
1019 Out << (unsigned char)(nibble + '0');
1021 Out << (unsigned char)(nibble - 10 + 'A');
1022 if (shiftcount == 0 && j+4 < width) {
1026 shiftcount = width-j-4;
1030 } else if (&CFP->getValueAPF().getSemantics() == &APFloat::IEEEquad)
1032 else if (&CFP->getValueAPF().getSemantics() == &APFloat::PPCDoubleDouble)
1035 llvm_unreachable("Unsupported floating point type");
1036 // api needed to prevent premature destruction
1037 APInt api = CFP->getValueAPF().bitcastToAPInt();
1038 const uint64_t* p = api.getRawData();
1041 int width = api.getBitWidth();
1042 for (int j=0; j<width; j+=4, shiftcount-=4) {
1043 unsigned int nibble = (word>>shiftcount) & 15;
1045 Out << (unsigned char)(nibble + '0');
1047 Out << (unsigned char)(nibble - 10 + 'A');
1048 if (shiftcount == 0 && j+4 < width) {
1052 shiftcount = width-j-4;
1058 if (isa<ConstantAggregateZero>(CV)) {
1059 Out << "zeroinitializer";
1063 if (const ConstantArray *CA = dyn_cast<ConstantArray>(CV)) {
1064 // As a special case, print the array as a string if it is an array of
1065 // i8 with ConstantInt values.
1067 const Type *ETy = CA->getType()->getElementType();
1068 if (CA->isString()) {
1070 PrintEscapedString(CA->getAsString(), Out);
1072 } else { // Cannot output in string format...
1074 if (CA->getNumOperands()) {
1075 TypePrinter.print(ETy, Out);
1077 WriteAsOperandInternal(Out, CA->getOperand(0),
1078 &TypePrinter, Machine);
1079 for (unsigned i = 1, e = CA->getNumOperands(); i != e; ++i) {
1081 TypePrinter.print(ETy, Out);
1083 WriteAsOperandInternal(Out, CA->getOperand(i), &TypePrinter, Machine);
1091 if (const ConstantStruct *CS = dyn_cast<ConstantStruct>(CV)) {
1092 if (CS->getType()->isPacked())
1095 unsigned N = CS->getNumOperands();
1098 TypePrinter.print(CS->getOperand(0)->getType(), Out);
1101 WriteAsOperandInternal(Out, CS->getOperand(0), &TypePrinter, Machine);
1103 for (unsigned i = 1; i < N; i++) {
1105 TypePrinter.print(CS->getOperand(i)->getType(), Out);
1108 WriteAsOperandInternal(Out, CS->getOperand(i), &TypePrinter, Machine);
1114 if (CS->getType()->isPacked())
1119 if (const ConstantVector *CP = dyn_cast<ConstantVector>(CV)) {
1120 const Type *ETy = CP->getType()->getElementType();
1121 assert(CP->getNumOperands() > 0 &&
1122 "Number of operands for a PackedConst must be > 0");
1124 TypePrinter.print(ETy, Out);
1126 WriteAsOperandInternal(Out, CP->getOperand(0), &TypePrinter, Machine);
1127 for (unsigned i = 1, e = CP->getNumOperands(); i != e; ++i) {
1129 TypePrinter.print(ETy, Out);
1131 WriteAsOperandInternal(Out, CP->getOperand(i), &TypePrinter, Machine);
1137 if (isa<ConstantPointerNull>(CV)) {
1142 if (isa<UndefValue>(CV)) {
1147 if (const MDNode *Node = dyn_cast<MDNode>(CV)) {
1148 Out << "!" << Machine->getMetadataSlot(Node);
1152 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV)) {
1153 Out << CE->getOpcodeName();
1154 WriteOptimizationInfo(Out, CE);
1155 if (CE->isCompare())
1156 Out << ' ' << getPredicateText(CE->getPredicate());
1159 for (User::const_op_iterator OI=CE->op_begin(); OI != CE->op_end(); ++OI) {
1160 TypePrinter.print((*OI)->getType(), Out);
1162 WriteAsOperandInternal(Out, *OI, &TypePrinter, Machine);
1163 if (OI+1 != CE->op_end())
1167 if (CE->hasIndices()) {
1168 const SmallVector<unsigned, 4> &Indices = CE->getIndices();
1169 for (unsigned i = 0, e = Indices.size(); i != e; ++i)
1170 Out << ", " << Indices[i];
1175 TypePrinter.print(CE->getType(), Out);
1182 Out << "<placeholder or erroneous Constant>";
1186 /// WriteAsOperand - Write the name of the specified value out to the specified
1187 /// ostream. This can be useful when you just want to print int %reg126, not
1188 /// the whole instruction that generated it.
1190 static void WriteAsOperandInternal(raw_ostream &Out, const Value *V,
1191 TypePrinting *TypePrinter,
1192 SlotTracker *Machine) {
1194 PrintLLVMName(Out, V);
1198 const Constant *CV = dyn_cast<Constant>(V);
1199 if (CV && !isa<GlobalValue>(CV)) {
1200 assert(TypePrinter && "Constants require TypePrinting!");
1201 WriteConstantInt(Out, CV, *TypePrinter, Machine);
1205 if (const InlineAsm *IA = dyn_cast<InlineAsm>(V)) {
1207 if (IA->hasSideEffects())
1208 Out << "sideeffect ";
1210 PrintEscapedString(IA->getAsmString(), Out);
1212 PrintEscapedString(IA->getConstraintString(), Out);
1217 if (const MDNode *N = dyn_cast<MDNode>(V)) {
1218 Out << '!' << Machine->getMetadataSlot(N);
1222 if (const MDString *MDS = dyn_cast<MDString>(V)) {
1224 PrintEscapedString(MDS->getString(), Out);
1229 if (V->getValueID() == Value::PseudoSourceValueVal) {
1237 if (const GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
1238 Slot = Machine->getGlobalSlot(GV);
1241 Slot = Machine->getLocalSlot(V);
1244 Machine = createSlotTracker(V);
1246 if (const GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
1247 Slot = Machine->getGlobalSlot(GV);
1250 Slot = Machine->getLocalSlot(V);
1259 Out << Prefix << Slot;
1264 void llvm::WriteAsOperand(raw_ostream &Out, const Value *V,
1265 bool PrintType, const Module *Context) {
1267 // Fast path: Don't construct and populate a TypePrinting object if we
1268 // won't be needing any types printed.
1270 (!isa<Constant>(V) || V->hasName() || isa<GlobalValue>(V))) {
1271 WriteAsOperandInternal(Out, V, 0, 0);
1275 if (Context == 0) Context = getModuleFromVal(V);
1277 TypePrinting TypePrinter;
1278 std::vector<const Type*> NumberedTypes;
1279 AddModuleTypesToPrinter(TypePrinter, NumberedTypes, Context);
1281 TypePrinter.print(V->getType(), Out);
1285 WriteAsOperandInternal(Out, V, &TypePrinter, 0);
1290 class AssemblyWriter {
1291 formatted_raw_ostream &Out;
1292 SlotTracker &Machine;
1293 const Module *TheModule;
1294 TypePrinting TypePrinter;
1295 AssemblyAnnotationWriter *AnnotationWriter;
1296 std::vector<const Type*> NumberedTypes;
1297 DenseMap<unsigned, const char *> MDNames;
1300 inline AssemblyWriter(formatted_raw_ostream &o, SlotTracker &Mac,
1302 AssemblyAnnotationWriter *AAW)
1303 : Out(o), Machine(Mac), TheModule(M), AnnotationWriter(AAW) {
1304 AddModuleTypesToPrinter(TypePrinter, NumberedTypes, M);
1305 // FIXME: Provide MDPrinter
1306 MetadataContext &TheMetadata = M->getContext().getMetadata();
1307 const StringMap<unsigned> *Names = TheMetadata.getHandlerNames();
1308 for (StringMapConstIterator<unsigned> I = Names->begin(),
1309 E = Names->end(); I != E; ++I) {
1310 const StringMapEntry<unsigned> &Entry = *I;
1311 MDNames[I->second] = Entry.getKeyData();
1315 void write(const Module *M) { printModule(M); }
1317 void write(const GlobalValue *G) {
1318 if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(G))
1320 else if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(G))
1322 else if (const Function *F = dyn_cast<Function>(G))
1325 llvm_unreachable("Unknown global");
1328 void write(const BasicBlock *BB) { printBasicBlock(BB); }
1329 void write(const Instruction *I) { printInstruction(*I); }
1331 void writeOperand(const Value *Op, bool PrintType);
1332 void writeParamOperand(const Value *Operand, Attributes Attrs);
1335 void printModule(const Module *M);
1336 void printTypeSymbolTable(const TypeSymbolTable &ST);
1337 void printGlobal(const GlobalVariable *GV);
1338 void printAlias(const GlobalAlias *GV);
1339 void printFunction(const Function *F);
1340 void printArgument(const Argument *FA, Attributes Attrs);
1341 void printBasicBlock(const BasicBlock *BB);
1342 void printInstruction(const Instruction &I);
1344 // printInfoComment - Print a little comment after the instruction indicating
1345 // which slot it occupies.
1346 void printInfoComment(const Value &V);
1348 } // end of anonymous namespace
1351 void AssemblyWriter::writeOperand(const Value *Operand, bool PrintType) {
1353 Out << "<null operand!>";
1356 TypePrinter.print(Operand->getType(), Out);
1359 WriteAsOperandInternal(Out, Operand, &TypePrinter, &Machine);
1363 void AssemblyWriter::writeParamOperand(const Value *Operand,
1366 Out << "<null operand!>";
1369 TypePrinter.print(Operand->getType(), Out);
1370 // Print parameter attributes list
1371 if (Attrs != Attribute::None)
1372 Out << ' ' << Attribute::getAsString(Attrs);
1374 // Print the operand
1375 WriteAsOperandInternal(Out, Operand, &TypePrinter, &Machine);
1379 void AssemblyWriter::printModule(const Module *M) {
1380 if (!M->getModuleIdentifier().empty() &&
1381 // Don't print the ID if it will start a new line (which would
1382 // require a comment char before it).
1383 M->getModuleIdentifier().find('\n') == std::string::npos)
1384 Out << "; ModuleID = '" << M->getModuleIdentifier() << "'\n";
1386 if (!M->getDataLayout().empty())
1387 Out << "target datalayout = \"" << M->getDataLayout() << "\"\n";
1388 if (!M->getTargetTriple().empty())
1389 Out << "target triple = \"" << M->getTargetTriple() << "\"\n";
1391 if (!M->getModuleInlineAsm().empty()) {
1392 // Split the string into lines, to make it easier to read the .ll file.
1393 std::string Asm = M->getModuleInlineAsm();
1395 size_t NewLine = Asm.find_first_of('\n', CurPos);
1397 while (NewLine != std::string::npos) {
1398 // We found a newline, print the portion of the asm string from the
1399 // last newline up to this newline.
1400 Out << "module asm \"";
1401 PrintEscapedString(std::string(Asm.begin()+CurPos, Asm.begin()+NewLine),
1405 NewLine = Asm.find_first_of('\n', CurPos);
1407 Out << "module asm \"";
1408 PrintEscapedString(std::string(Asm.begin()+CurPos, Asm.end()), Out);
1412 // Loop over the dependent libraries and emit them.
1413 Module::lib_iterator LI = M->lib_begin();
1414 Module::lib_iterator LE = M->lib_end();
1417 Out << "deplibs = [ ";
1419 Out << '"' << *LI << '"';
1427 // Loop over the symbol table, emitting all id'd types.
1428 if (!M->getTypeSymbolTable().empty() || !NumberedTypes.empty()) Out << '\n';
1429 printTypeSymbolTable(M->getTypeSymbolTable());
1431 // Output all globals.
1432 if (!M->global_empty()) Out << '\n';
1433 for (Module::const_global_iterator I = M->global_begin(), E = M->global_end();
1437 // Output all aliases.
1438 if (!M->alias_empty()) Out << "\n";
1439 for (Module::const_alias_iterator I = M->alias_begin(), E = M->alias_end();
1443 // Output all of the functions.
1444 for (Module::const_iterator I = M->begin(), E = M->end(); I != E; ++I)
1447 // Output named metadata.
1448 if (!M->named_metadata_empty()) Out << '\n';
1449 for (Module::const_named_metadata_iterator I = M->named_metadata_begin(),
1450 E = M->named_metadata_end(); I != E; ++I) {
1451 const NamedMDNode *NMD = I;
1452 Out << "!" << NMD->getName() << " = !{";
1453 for (unsigned i = 0, e = NMD->getNumElements(); i != e; ++i) {
1455 MDNode *MD = dyn_cast_or_null<MDNode>(NMD->getElement(i));
1456 Out << '!' << Machine.getMetadataSlot(MD);
1462 if (!Machine.mdnEmpty()) Out << '\n';
1463 WriteMDNodes(Out, TypePrinter, Machine);
1466 static void PrintLinkage(GlobalValue::LinkageTypes LT,
1467 formatted_raw_ostream &Out) {
1469 case GlobalValue::ExternalLinkage: break;
1470 case GlobalValue::PrivateLinkage: Out << "private "; break;
1471 case GlobalValue::LinkerPrivateLinkage: Out << "linker_private "; break;
1472 case GlobalValue::InternalLinkage: Out << "internal "; break;
1473 case GlobalValue::LinkOnceAnyLinkage: Out << "linkonce "; break;
1474 case GlobalValue::LinkOnceODRLinkage: Out << "linkonce_odr "; break;
1475 case GlobalValue::WeakAnyLinkage: Out << "weak "; break;
1476 case GlobalValue::WeakODRLinkage: Out << "weak_odr "; break;
1477 case GlobalValue::CommonLinkage: Out << "common "; break;
1478 case GlobalValue::AppendingLinkage: Out << "appending "; break;
1479 case GlobalValue::DLLImportLinkage: Out << "dllimport "; break;
1480 case GlobalValue::DLLExportLinkage: Out << "dllexport "; break;
1481 case GlobalValue::ExternalWeakLinkage: Out << "extern_weak "; break;
1482 case GlobalValue::AvailableExternallyLinkage:
1483 Out << "available_externally ";
1485 case GlobalValue::GhostLinkage:
1486 llvm_unreachable("GhostLinkage not allowed in AsmWriter!");
1491 static void PrintVisibility(GlobalValue::VisibilityTypes Vis,
1492 formatted_raw_ostream &Out) {
1494 default: llvm_unreachable("Invalid visibility style!");
1495 case GlobalValue::DefaultVisibility: break;
1496 case GlobalValue::HiddenVisibility: Out << "hidden "; break;
1497 case GlobalValue::ProtectedVisibility: Out << "protected "; break;
1501 void AssemblyWriter::printGlobal(const GlobalVariable *GV) {
1502 WriteAsOperandInternal(Out, GV, &TypePrinter, &Machine);
1505 if (!GV->hasInitializer() && GV->hasExternalLinkage())
1508 PrintLinkage(GV->getLinkage(), Out);
1509 PrintVisibility(GV->getVisibility(), Out);
1511 if (GV->isThreadLocal()) Out << "thread_local ";
1512 if (unsigned AddressSpace = GV->getType()->getAddressSpace())
1513 Out << "addrspace(" << AddressSpace << ") ";
1514 Out << (GV->isConstant() ? "constant " : "global ");
1515 TypePrinter.print(GV->getType()->getElementType(), Out);
1517 if (GV->hasInitializer()) {
1519 writeOperand(GV->getInitializer(), false);
1522 if (GV->hasSection())
1523 Out << ", section \"" << GV->getSection() << '"';
1524 if (GV->getAlignment())
1525 Out << ", align " << GV->getAlignment();
1527 printInfoComment(*GV);
1531 void AssemblyWriter::printAlias(const GlobalAlias *GA) {
1532 // Don't crash when dumping partially built GA
1534 Out << "<<nameless>> = ";
1536 PrintLLVMName(Out, GA);
1539 PrintVisibility(GA->getVisibility(), Out);
1543 PrintLinkage(GA->getLinkage(), Out);
1545 const Constant *Aliasee = GA->getAliasee();
1547 if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(Aliasee)) {
1548 TypePrinter.print(GV->getType(), Out);
1550 PrintLLVMName(Out, GV);
1551 } else if (const Function *F = dyn_cast<Function>(Aliasee)) {
1552 TypePrinter.print(F->getFunctionType(), Out);
1555 WriteAsOperandInternal(Out, F, &TypePrinter, &Machine);
1556 } else if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(Aliasee)) {
1557 TypePrinter.print(GA->getType(), Out);
1559 PrintLLVMName(Out, GA);
1561 const ConstantExpr *CE = cast<ConstantExpr>(Aliasee);
1562 // The only valid GEP is an all zero GEP.
1563 assert((CE->getOpcode() == Instruction::BitCast ||
1564 CE->getOpcode() == Instruction::GetElementPtr) &&
1565 "Unsupported aliasee");
1566 writeOperand(CE, false);
1569 printInfoComment(*GA);
1573 void AssemblyWriter::printTypeSymbolTable(const TypeSymbolTable &ST) {
1574 // Emit all numbered types.
1575 for (unsigned i = 0, e = NumberedTypes.size(); i != e; ++i) {
1576 Out << '%' << i << " = type ";
1578 // Make sure we print out at least one level of the type structure, so
1579 // that we do not get %2 = type %2
1580 TypePrinter.printAtLeastOneLevel(NumberedTypes[i], Out);
1584 // Print the named types.
1585 for (TypeSymbolTable::const_iterator TI = ST.begin(), TE = ST.end();
1587 PrintLLVMName(Out, TI->first, LocalPrefix);
1590 // Make sure we print out at least one level of the type structure, so
1591 // that we do not get %FILE = type %FILE
1592 TypePrinter.printAtLeastOneLevel(TI->second, Out);
1597 /// printFunction - Print all aspects of a function.
1599 void AssemblyWriter::printFunction(const Function *F) {
1600 // Print out the return type and name.
1603 if (AnnotationWriter) AnnotationWriter->emitFunctionAnnot(F, Out);
1605 if (F->isDeclaration())
1610 PrintLinkage(F->getLinkage(), Out);
1611 PrintVisibility(F->getVisibility(), Out);
1613 // Print the calling convention.
1614 switch (F->getCallingConv()) {
1615 case CallingConv::C: break; // default
1616 case CallingConv::Fast: Out << "fastcc "; break;
1617 case CallingConv::Cold: Out << "coldcc "; break;
1618 case CallingConv::X86_StdCall: Out << "x86_stdcallcc "; break;
1619 case CallingConv::X86_FastCall: Out << "x86_fastcallcc "; break;
1620 case CallingConv::ARM_APCS: Out << "arm_apcscc "; break;
1621 case CallingConv::ARM_AAPCS: Out << "arm_aapcscc "; break;
1622 case CallingConv::ARM_AAPCS_VFP:Out << "arm_aapcs_vfpcc "; break;
1623 default: Out << "cc" << F->getCallingConv() << " "; break;
1626 const FunctionType *FT = F->getFunctionType();
1627 const AttrListPtr &Attrs = F->getAttributes();
1628 Attributes RetAttrs = Attrs.getRetAttributes();
1629 if (RetAttrs != Attribute::None)
1630 Out << Attribute::getAsString(Attrs.getRetAttributes()) << ' ';
1631 TypePrinter.print(F->getReturnType(), Out);
1633 WriteAsOperandInternal(Out, F, &TypePrinter, &Machine);
1635 Machine.incorporateFunction(F);
1637 // Loop over the arguments, printing them...
1640 if (!F->isDeclaration()) {
1641 // If this isn't a declaration, print the argument names as well.
1642 for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
1644 // Insert commas as we go... the first arg doesn't get a comma
1645 if (I != F->arg_begin()) Out << ", ";
1646 printArgument(I, Attrs.getParamAttributes(Idx));
1650 // Otherwise, print the types from the function type.
1651 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
1652 // Insert commas as we go... the first arg doesn't get a comma
1656 TypePrinter.print(FT->getParamType(i), Out);
1658 Attributes ArgAttrs = Attrs.getParamAttributes(i+1);
1659 if (ArgAttrs != Attribute::None)
1660 Out << ' ' << Attribute::getAsString(ArgAttrs);
1664 // Finish printing arguments...
1665 if (FT->isVarArg()) {
1666 if (FT->getNumParams()) Out << ", ";
1667 Out << "..."; // Output varargs portion of signature!
1670 Attributes FnAttrs = Attrs.getFnAttributes();
1671 if (FnAttrs != Attribute::None)
1672 Out << ' ' << Attribute::getAsString(Attrs.getFnAttributes());
1673 if (F->hasSection())
1674 Out << " section \"" << F->getSection() << '"';
1675 if (F->getAlignment())
1676 Out << " align " << F->getAlignment();
1678 Out << " gc \"" << F->getGC() << '"';
1679 if (F->isDeclaration()) {
1684 // Output all of its basic blocks... for the function
1685 for (Function::const_iterator I = F->begin(), E = F->end(); I != E; ++I)
1691 Machine.purgeFunction();
1694 /// printArgument - This member is called for every argument that is passed into
1695 /// the function. Simply print it out
1697 void AssemblyWriter::printArgument(const Argument *Arg,
1700 TypePrinter.print(Arg->getType(), Out);
1702 // Output parameter attributes list
1703 if (Attrs != Attribute::None)
1704 Out << ' ' << Attribute::getAsString(Attrs);
1706 // Output name, if available...
1707 if (Arg->hasName()) {
1709 PrintLLVMName(Out, Arg);
1713 /// printBasicBlock - This member is called for each basic block in a method.
1715 void AssemblyWriter::printBasicBlock(const BasicBlock *BB) {
1716 if (BB->hasName()) { // Print out the label if it exists...
1718 PrintLLVMName(Out, BB->getName(), LabelPrefix);
1720 } else if (!BB->use_empty()) { // Don't print block # of no uses...
1721 Out << "\n; <label>:";
1722 int Slot = Machine.getLocalSlot(BB);
1729 if (BB->getParent() == 0) {
1730 Out.PadToColumn(50);
1731 Out << "; Error: Block without parent!";
1732 } else if (BB != &BB->getParent()->getEntryBlock()) { // Not the entry block?
1733 // Output predecessors for the block...
1734 Out.PadToColumn(50);
1736 pred_const_iterator PI = pred_begin(BB), PE = pred_end(BB);
1739 Out << " No predecessors!";
1742 writeOperand(*PI, false);
1743 for (++PI; PI != PE; ++PI) {
1745 writeOperand(*PI, false);
1752 if (AnnotationWriter) AnnotationWriter->emitBasicBlockStartAnnot(BB, Out);
1754 // Output all of the instructions in the basic block...
1755 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I != E; ++I) {
1756 printInstruction(*I);
1760 if (AnnotationWriter) AnnotationWriter->emitBasicBlockEndAnnot(BB, Out);
1764 /// printInfoComment - Print a little comment after the instruction indicating
1765 /// which slot it occupies.
1767 void AssemblyWriter::printInfoComment(const Value &V) {
1768 if (V.getType() != Type::getVoidTy(V.getContext())) {
1769 Out.PadToColumn(50);
1771 TypePrinter.print(V.getType(), Out);
1772 Out << "> [#uses=" << V.getNumUses() << ']'; // Output # uses
1776 // This member is called for each Instruction in a function..
1777 void AssemblyWriter::printInstruction(const Instruction &I) {
1778 if (AnnotationWriter) AnnotationWriter->emitInstructionAnnot(&I, Out);
1780 // Print out indentation for an instruction.
1783 // Print out name if it exists...
1785 PrintLLVMName(Out, &I);
1787 } else if (I.getType() != Type::getVoidTy(I.getContext())) {
1788 // Print out the def slot taken.
1789 int SlotNum = Machine.getLocalSlot(&I);
1791 Out << "<badref> = ";
1793 Out << '%' << SlotNum << " = ";
1796 // If this is a volatile load or store, print out the volatile marker.
1797 if ((isa<LoadInst>(I) && cast<LoadInst>(I).isVolatile()) ||
1798 (isa<StoreInst>(I) && cast<StoreInst>(I).isVolatile())) {
1800 } else if (isa<CallInst>(I) && cast<CallInst>(I).isTailCall()) {
1801 // If this is a call, check if it's a tail call.
1805 // Print out the opcode...
1806 Out << I.getOpcodeName();
1808 // Print out optimization information.
1809 WriteOptimizationInfo(Out, &I);
1811 // Print out the compare instruction predicates
1812 if (const CmpInst *CI = dyn_cast<CmpInst>(&I))
1813 Out << ' ' << getPredicateText(CI->getPredicate());
1815 // Print out the type of the operands...
1816 const Value *Operand = I.getNumOperands() ? I.getOperand(0) : 0;
1818 // Special case conditional branches to swizzle the condition out to the front
1819 if (isa<BranchInst>(I) && cast<BranchInst>(I).isConditional()) {
1820 BranchInst &BI(cast<BranchInst>(I));
1822 writeOperand(BI.getCondition(), true);
1824 writeOperand(BI.getSuccessor(0), true);
1826 writeOperand(BI.getSuccessor(1), true);
1828 } else if (isa<SwitchInst>(I)) {
1829 // Special case switch statement to get formatting nice and correct...
1831 writeOperand(Operand , true);
1833 writeOperand(I.getOperand(1), true);
1836 for (unsigned op = 2, Eop = I.getNumOperands(); op < Eop; op += 2) {
1838 writeOperand(I.getOperand(op ), true);
1840 writeOperand(I.getOperand(op+1), true);
1843 } else if (isa<PHINode>(I)) {
1845 TypePrinter.print(I.getType(), Out);
1848 for (unsigned op = 0, Eop = I.getNumOperands(); op < Eop; op += 2) {
1849 if (op) Out << ", ";
1851 writeOperand(I.getOperand(op ), false); Out << ", ";
1852 writeOperand(I.getOperand(op+1), false); Out << " ]";
1854 } else if (const ExtractValueInst *EVI = dyn_cast<ExtractValueInst>(&I)) {
1856 writeOperand(I.getOperand(0), true);
1857 for (const unsigned *i = EVI->idx_begin(), *e = EVI->idx_end(); i != e; ++i)
1859 } else if (const InsertValueInst *IVI = dyn_cast<InsertValueInst>(&I)) {
1861 writeOperand(I.getOperand(0), true); Out << ", ";
1862 writeOperand(I.getOperand(1), true);
1863 for (const unsigned *i = IVI->idx_begin(), *e = IVI->idx_end(); i != e; ++i)
1865 } else if (isa<ReturnInst>(I) && !Operand) {
1867 } else if (const CallInst *CI = dyn_cast<CallInst>(&I)) {
1868 // Print the calling convention being used.
1869 switch (CI->getCallingConv()) {
1870 case CallingConv::C: break; // default
1871 case CallingConv::Fast: Out << " fastcc"; break;
1872 case CallingConv::Cold: Out << " coldcc"; break;
1873 case CallingConv::X86_StdCall: Out << " x86_stdcallcc"; break;
1874 case CallingConv::X86_FastCall: Out << " x86_fastcallcc"; break;
1875 case CallingConv::ARM_APCS: Out << " arm_apcscc "; break;
1876 case CallingConv::ARM_AAPCS: Out << " arm_aapcscc "; break;
1877 case CallingConv::ARM_AAPCS_VFP:Out << " arm_aapcs_vfpcc "; break;
1878 default: Out << " cc" << CI->getCallingConv(); break;
1881 const PointerType *PTy = cast<PointerType>(Operand->getType());
1882 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
1883 const Type *RetTy = FTy->getReturnType();
1884 const AttrListPtr &PAL = CI->getAttributes();
1886 if (PAL.getRetAttributes() != Attribute::None)
1887 Out << ' ' << Attribute::getAsString(PAL.getRetAttributes());
1889 // If possible, print out the short form of the call instruction. We can
1890 // only do this if the first argument is a pointer to a nonvararg function,
1891 // and if the return type is not a pointer to a function.
1894 if (!FTy->isVarArg() &&
1895 (!isa<PointerType>(RetTy) ||
1896 !isa<FunctionType>(cast<PointerType>(RetTy)->getElementType()))) {
1897 TypePrinter.print(RetTy, Out);
1899 writeOperand(Operand, false);
1901 writeOperand(Operand, true);
1904 for (unsigned op = 1, Eop = I.getNumOperands(); op < Eop; ++op) {
1907 writeParamOperand(I.getOperand(op), PAL.getParamAttributes(op));
1910 if (PAL.getFnAttributes() != Attribute::None)
1911 Out << ' ' << Attribute::getAsString(PAL.getFnAttributes());
1912 } else if (const InvokeInst *II = dyn_cast<InvokeInst>(&I)) {
1913 const PointerType *PTy = cast<PointerType>(Operand->getType());
1914 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
1915 const Type *RetTy = FTy->getReturnType();
1916 const AttrListPtr &PAL = II->getAttributes();
1918 // Print the calling convention being used.
1919 switch (II->getCallingConv()) {
1920 case CallingConv::C: break; // default
1921 case CallingConv::Fast: Out << " fastcc"; break;
1922 case CallingConv::Cold: Out << " coldcc"; break;
1923 case CallingConv::X86_StdCall: Out << " x86_stdcallcc"; break;
1924 case CallingConv::X86_FastCall: Out << " x86_fastcallcc"; break;
1925 case CallingConv::ARM_APCS: Out << " arm_apcscc "; break;
1926 case CallingConv::ARM_AAPCS: Out << " arm_aapcscc "; break;
1927 case CallingConv::ARM_AAPCS_VFP:Out << " arm_aapcs_vfpcc "; break;
1928 default: Out << " cc" << II->getCallingConv(); break;
1931 if (PAL.getRetAttributes() != Attribute::None)
1932 Out << ' ' << Attribute::getAsString(PAL.getRetAttributes());
1934 // If possible, print out the short form of the invoke instruction. We can
1935 // only do this if the first argument is a pointer to a nonvararg function,
1936 // and if the return type is not a pointer to a function.
1939 if (!FTy->isVarArg() &&
1940 (!isa<PointerType>(RetTy) ||
1941 !isa<FunctionType>(cast<PointerType>(RetTy)->getElementType()))) {
1942 TypePrinter.print(RetTy, Out);
1944 writeOperand(Operand, false);
1946 writeOperand(Operand, true);
1949 for (unsigned op = 3, Eop = I.getNumOperands(); op < Eop; ++op) {
1952 writeParamOperand(I.getOperand(op), PAL.getParamAttributes(op-2));
1956 if (PAL.getFnAttributes() != Attribute::None)
1957 Out << ' ' << Attribute::getAsString(PAL.getFnAttributes());
1960 writeOperand(II->getNormalDest(), true);
1962 writeOperand(II->getUnwindDest(), true);
1964 } else if (const AllocationInst *AI = dyn_cast<AllocationInst>(&I)) {
1966 TypePrinter.print(AI->getType()->getElementType(), Out);
1967 if (!AI->getArraySize() || AI->isArrayAllocation()) {
1969 writeOperand(AI->getArraySize(), true);
1971 if (AI->getAlignment()) {
1972 Out << ", align " << AI->getAlignment();
1974 } else if (isa<CastInst>(I)) {
1977 writeOperand(Operand, true); // Work with broken code
1980 TypePrinter.print(I.getType(), Out);
1981 } else if (isa<VAArgInst>(I)) {
1984 writeOperand(Operand, true); // Work with broken code
1987 TypePrinter.print(I.getType(), Out);
1988 } else if (Operand) { // Print the normal way.
1990 // PrintAllTypes - Instructions who have operands of all the same type
1991 // omit the type from all but the first operand. If the instruction has
1992 // different type operands (for example br), then they are all printed.
1993 bool PrintAllTypes = false;
1994 const Type *TheType = Operand->getType();
1996 // Select, Store and ShuffleVector always print all types.
1997 if (isa<SelectInst>(I) || isa<StoreInst>(I) || isa<ShuffleVectorInst>(I)
1998 || isa<ReturnInst>(I)) {
1999 PrintAllTypes = true;
2001 for (unsigned i = 1, E = I.getNumOperands(); i != E; ++i) {
2002 Operand = I.getOperand(i);
2003 // note that Operand shouldn't be null, but the test helps make dump()
2004 // more tolerant of malformed IR
2005 if (Operand && Operand->getType() != TheType) {
2006 PrintAllTypes = true; // We have differing types! Print them all!
2012 if (!PrintAllTypes) {
2014 TypePrinter.print(TheType, Out);
2018 for (unsigned i = 0, E = I.getNumOperands(); i != E; ++i) {
2020 writeOperand(I.getOperand(i), PrintAllTypes);
2024 // Print post operand alignment for load/store
2025 if (isa<LoadInst>(I) && cast<LoadInst>(I).getAlignment()) {
2026 Out << ", align " << cast<LoadInst>(I).getAlignment();
2027 } else if (isa<StoreInst>(I) && cast<StoreInst>(I).getAlignment()) {
2028 Out << ", align " << cast<StoreInst>(I).getAlignment();
2031 // Print Metadata info
2032 MetadataContext &TheMetadata = I.getContext().getMetadata();
2033 const MetadataContext::MDMapTy *MDMap = TheMetadata.getMDs(&I);
2035 for (MetadataContext::MDMapTy::const_iterator MI = MDMap->begin(),
2036 ME = MDMap->end(); MI != ME; ++MI)
2037 if (const MDNode *MD = dyn_cast_or_null<MDNode>(MI->second))
2038 Out << ", !" << MDNames[MI->first]
2039 << " !" << Machine.getMetadataSlot(MD);
2041 printInfoComment(I);
2045 //===----------------------------------------------------------------------===//
2046 // External Interface declarations
2047 //===----------------------------------------------------------------------===//
2049 void Module::print(raw_ostream &ROS, AssemblyAnnotationWriter *AAW) const {
2050 SlotTracker SlotTable(this);
2051 formatted_raw_ostream OS(ROS);
2052 AssemblyWriter W(OS, SlotTable, this, AAW);
2056 void Type::print(raw_ostream &OS) const {
2058 OS << "<null Type>";
2061 TypePrinting().print(this, OS);
2064 void Value::print(raw_ostream &ROS, AssemblyAnnotationWriter *AAW) const {
2066 ROS << "printing a <null> value\n";
2069 formatted_raw_ostream OS(ROS);
2070 if (const Instruction *I = dyn_cast<Instruction>(this)) {
2071 const Function *F = I->getParent() ? I->getParent()->getParent() : 0;
2072 SlotTracker SlotTable(F);
2073 AssemblyWriter W(OS, SlotTable, F ? F->getParent() : 0, AAW);
2075 } else if (const BasicBlock *BB = dyn_cast<BasicBlock>(this)) {
2076 SlotTracker SlotTable(BB->getParent());
2077 AssemblyWriter W(OS, SlotTable,
2078 BB->getParent() ? BB->getParent()->getParent() : 0, AAW);
2080 } else if (const GlobalValue *GV = dyn_cast<GlobalValue>(this)) {
2081 SlotTracker SlotTable(GV->getParent());
2082 AssemblyWriter W(OS, SlotTable, GV->getParent(), AAW);
2084 } else if (const MDString *MDS = dyn_cast<MDString>(this)) {
2085 TypePrinting TypePrinter;
2086 TypePrinter.print(MDS->getType(), OS);
2089 PrintEscapedString(MDS->getString(), OS);
2091 } else if (const MDNode *N = dyn_cast<MDNode>(this)) {
2092 SlotTracker SlotTable(N);
2093 TypePrinting TypePrinter;
2094 SlotTable.initialize();
2095 WriteMDNodes(OS, TypePrinter, SlotTable);
2096 } else if (const NamedMDNode *N = dyn_cast<NamedMDNode>(this)) {
2097 SlotTracker SlotTable(N);
2098 TypePrinting TypePrinter;
2099 SlotTable.initialize();
2100 OS << "!" << N->getName() << " = !{";
2101 for (unsigned i = 0, e = N->getNumElements(); i != e; ++i) {
2103 MDNode *MD = dyn_cast_or_null<MDNode>(N->getElement(i));
2105 OS << '!' << SlotTable.getMetadataSlot(MD);
2110 WriteMDNodes(OS, TypePrinter, SlotTable);
2111 } else if (const Constant *C = dyn_cast<Constant>(this)) {
2112 TypePrinting TypePrinter;
2113 TypePrinter.print(C->getType(), OS);
2115 WriteConstantInt(OS, C, TypePrinter, 0);
2116 } else if (const Argument *A = dyn_cast<Argument>(this)) {
2117 WriteAsOperand(OS, this, true,
2118 A->getParent() ? A->getParent()->getParent() : 0);
2119 } else if (isa<InlineAsm>(this)) {
2120 WriteAsOperand(OS, this, true, 0);
2122 // Otherwise we don't know what it is. Call the virtual function to
2123 // allow a subclass to print itself.
2128 // Value::printCustom - subclasses should override this to implement printing.
2129 void Value::printCustom(raw_ostream &OS) const {
2130 llvm_unreachable("Unknown value to print out!");
2133 // Value::dump - allow easy printing of Values from the debugger.
2134 void Value::dump() const { print(errs()); errs() << '\n'; }
2136 // Type::dump - allow easy printing of Types from the debugger.
2137 // This one uses type names from the given context module
2138 void Type::dump(const Module *Context) const {
2139 WriteTypeSymbolic(errs(), this, Context);
2143 // Type::dump - allow easy printing of Types from the debugger.
2144 void Type::dump() const { dump(0); }
2146 // Module::dump() - Allow printing of Modules from the debugger.
2147 void Module::dump() const { print(errs(), 0); }