1 //===-- AsmWriter.cpp - Printing LLVM as an assembly file -----------------===//
3 // The LLVM Compiler Infrastructure
5 // This file was developed by the LLVM research group and is distributed under
6 // the University of Illinois Open Source 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/CachedWriter.h"
18 #include "llvm/Assembly/Writer.h"
19 #include "llvm/Assembly/PrintModulePass.h"
20 #include "llvm/Assembly/AsmAnnotationWriter.h"
21 #include "llvm/Constants.h"
22 #include "llvm/DerivedTypes.h"
23 #include "llvm/Instruction.h"
24 #include "llvm/iMemory.h"
25 #include "llvm/iTerminators.h"
26 #include "llvm/iPHINode.h"
27 #include "llvm/iOther.h"
28 #include "llvm/Module.h"
29 #include "llvm/SymbolTable.h"
30 #include "llvm/Assembly/Writer.h"
31 #include "llvm/Support/CFG.h"
32 #include "Support/StringExtras.h"
33 #include "Support/STLExtras.h"
39 /// This class provides computation of slot numbers for LLVM Assembly writing.
40 /// @brief LLVM Assembly Writing Slot Computation.
47 /// @brief A mapping of Values to slot numbers
48 typedef std::map<const Value*, unsigned> ValueMap;
50 /// @brief A plane with next slot number and ValueMap
52 unsigned next_slot; ///< The next slot number to use
53 ValueMap map; ///< The map of Value* -> unsigned
54 Plane() { next_slot = 0; } ///< Make sure we start at 0
57 /// @brief The map of planes by Type
58 typedef std::map<const Type*, Plane> TypedPlanes;
61 /// @name Constructors
64 /// @brief Construct from a module
65 SlotMachine(const Module *M );
67 /// @brief Construct from a function, starting out in incorp state.
68 SlotMachine(const Function *F );
74 /// Return the slot number of the specified value in it's type
75 /// plane. Its an error to ask for something not in the SlotMachine.
76 /// Its an error to ask for a Type*
77 int getSlot(const Value *V);
79 /// Determine if a Value has a slot or not
80 bool hasSlot(const Value* V);
86 /// If you'd like to deal with a function instead of just a module, use
87 /// this method to get its data into the SlotMachine.
88 void incorporateFunction(const Function *F) { TheFunction = F; }
90 /// After calling incorporateFunction, use this method to remove the
91 /// most recently incorporated function from the SlotMachine. This
92 /// will reset the state of the machine back to just the module contents.
96 /// @name Implementation Details
99 /// This function does the actual initialization.
100 inline void initialize();
102 /// Values can be crammed into here at will. If they haven't
103 /// been inserted already, they get inserted, otherwise they are ignored.
104 /// Either way, the slot number for the Value* is returned.
105 unsigned createSlot(const Value *V);
107 /// Insert a value into the value table. Return the slot number
108 /// that it now occupies. BadThings(TM) will happen if you insert a
109 /// Value that's already been inserted.
110 unsigned insertValue( const Value *V );
112 /// Add all of the module level global variables (and their initializers)
113 /// and function declarations, but not the contents of those functions.
114 void processModule();
116 /// Add all of the functions arguments, basic blocks, and instructions
117 void processFunction();
119 SlotMachine(const SlotMachine &); // DO NOT IMPLEMENT
120 void operator=(const SlotMachine &); // DO NOT IMPLEMENT
127 /// @brief The module for which we are holding slot numbers
128 const Module* TheModule;
130 /// @brief The function for which we are holding slot numbers
131 const Function* TheFunction;
133 /// @brief The TypePlanes map for the module level data
136 /// @brief The TypePlanes map for the function level data
145 static RegisterPass<PrintModulePass>
146 X("printm", "Print module to stderr",PassInfo::Analysis|PassInfo::Optimization);
147 static RegisterPass<PrintFunctionPass>
148 Y("print","Print function to stderr",PassInfo::Analysis|PassInfo::Optimization);
150 static void WriteAsOperandInternal(std::ostream &Out, const Value *V,
152 std::map<const Type *, std::string> &TypeTable,
153 SlotMachine *Machine);
155 static const Module *getModuleFromVal(const Value *V) {
156 if (const Argument *MA = dyn_cast<Argument>(V))
157 return MA->getParent() ? MA->getParent()->getParent() : 0;
158 else if (const BasicBlock *BB = dyn_cast<BasicBlock>(V))
159 return BB->getParent() ? BB->getParent()->getParent() : 0;
160 else if (const Instruction *I = dyn_cast<Instruction>(V)) {
161 const Function *M = I->getParent() ? I->getParent()->getParent() : 0;
162 return M ? M->getParent() : 0;
163 } else if (const GlobalValue *GV = dyn_cast<GlobalValue>(V))
164 return GV->getParent();
168 static SlotMachine *createSlotMachine(const Value *V) {
169 assert(!isa<Type>(V) && "Can't create an SC for a type!");
170 if (const Argument *FA = dyn_cast<Argument>(V)) {
171 return new SlotMachine(FA->getParent());
172 } else if (const Instruction *I = dyn_cast<Instruction>(V)) {
173 return new SlotMachine(I->getParent()->getParent());
174 } else if (const BasicBlock *BB = dyn_cast<BasicBlock>(V)) {
175 return new SlotMachine(BB->getParent());
176 } else if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(V)){
177 return new SlotMachine(GV->getParent());
178 } else if (const Function *Func = dyn_cast<Function>(V)) {
179 return new SlotMachine(Func);
184 // getLLVMName - Turn the specified string into an 'LLVM name', which is either
185 // prefixed with % (if the string only contains simple characters) or is
186 // surrounded with ""'s (if it has special chars in it).
187 static std::string getLLVMName(const std::string &Name) {
188 assert(!Name.empty() && "Cannot get empty name!");
190 // First character cannot start with a number...
191 if (Name[0] >= '0' && Name[0] <= '9')
192 return "\"" + Name + "\"";
194 // Scan to see if we have any characters that are not on the "white list"
195 for (unsigned i = 0, e = Name.size(); i != e; ++i) {
197 assert(C != '"' && "Illegal character in LLVM value name!");
198 if ((C < 'a' || C > 'z') && (C < 'A' || C > 'Z') && (C < '0' || C > '9') &&
199 C != '-' && C != '.' && C != '_')
200 return "\"" + Name + "\"";
203 // If we get here, then the identifier is legal to use as a "VarID".
208 /// fillTypeNameTable - If the module has a symbol table, take all global types
209 /// and stuff their names into the TypeNames map.
211 static void fillTypeNameTable(const Module *M,
212 std::map<const Type *, std::string> &TypeNames) {
214 const SymbolTable &ST = M->getSymbolTable();
215 SymbolTable::type_const_iterator TI = ST.type_begin();
216 for (; TI != ST.type_end(); ++TI ) {
217 // As a heuristic, don't insert pointer to primitive types, because
218 // they are used too often to have a single useful name.
220 const Type *Ty = cast<Type>(TI->second);
221 if (!isa<PointerType>(Ty) ||
222 !cast<PointerType>(Ty)->getElementType()->isPrimitiveType() ||
223 isa<OpaqueType>(cast<PointerType>(Ty)->getElementType()))
224 TypeNames.insert(std::make_pair(Ty, getLLVMName(TI->first)));
230 static void calcTypeName(const Type *Ty,
231 std::vector<const Type *> &TypeStack,
232 std::map<const Type *, std::string> &TypeNames,
233 std::string & Result){
234 if (Ty->isPrimitiveType() && !isa<OpaqueType>(Ty)) {
235 Result += Ty->getDescription(); // Base case
239 // Check to see if the type is named.
240 std::map<const Type *, std::string>::iterator I = TypeNames.find(Ty);
241 if (I != TypeNames.end()) {
246 if (isa<OpaqueType>(Ty)) {
251 // Check to see if the Type is already on the stack...
252 unsigned Slot = 0, CurSize = TypeStack.size();
253 while (Slot < CurSize && TypeStack[Slot] != Ty) ++Slot; // Scan for type
255 // This is another base case for the recursion. In this case, we know
256 // that we have looped back to a type that we have previously visited.
257 // Generate the appropriate upreference to handle this.
258 if (Slot < CurSize) {
259 Result += "\\" + utostr(CurSize-Slot); // Here's the upreference
263 TypeStack.push_back(Ty); // Recursive case: Add us to the stack..
265 switch (Ty->getPrimitiveID()) {
266 case Type::FunctionTyID: {
267 const FunctionType *FTy = cast<FunctionType>(Ty);
268 calcTypeName(FTy->getReturnType(), TypeStack, TypeNames, Result);
270 for (FunctionType::param_iterator I = FTy->param_begin(),
271 E = FTy->param_end(); I != E; ++I) {
272 if (I != FTy->param_begin())
274 calcTypeName(*I, TypeStack, TypeNames, Result);
276 if (FTy->isVarArg()) {
277 if (FTy->getNumParams()) Result += ", ";
283 case Type::StructTyID: {
284 const StructType *STy = cast<StructType>(Ty);
286 for (StructType::element_iterator I = STy->element_begin(),
287 E = STy->element_end(); I != E; ++I) {
288 if (I != STy->element_begin())
290 calcTypeName(*I, TypeStack, TypeNames, Result);
295 case Type::PointerTyID:
296 calcTypeName(cast<PointerType>(Ty)->getElementType(),
297 TypeStack, TypeNames, Result);
300 case Type::ArrayTyID: {
301 const ArrayType *ATy = cast<ArrayType>(Ty);
302 Result += "[" + utostr(ATy->getNumElements()) + " x ";
303 calcTypeName(ATy->getElementType(), TypeStack, TypeNames, Result);
307 case Type::OpaqueTyID:
311 Result += "<unrecognized-type>";
314 TypeStack.pop_back(); // Remove self from stack...
319 /// printTypeInt - The internal guts of printing out a type that has a
320 /// potentially named portion.
322 static std::ostream &printTypeInt(std::ostream &Out, const Type *Ty,
323 std::map<const Type *, std::string> &TypeNames) {
324 // Primitive types always print out their description, regardless of whether
325 // they have been named or not.
327 if (Ty->isPrimitiveType() && !isa<OpaqueType>(Ty))
328 return Out << Ty->getDescription();
330 // Check to see if the type is named.
331 std::map<const Type *, std::string>::iterator I = TypeNames.find(Ty);
332 if (I != TypeNames.end()) return Out << I->second;
334 // Otherwise we have a type that has not been named but is a derived type.
335 // Carefully recurse the type hierarchy to print out any contained symbolic
338 std::vector<const Type *> TypeStack;
339 std::string TypeName;
340 calcTypeName(Ty, TypeStack, TypeNames, TypeName);
341 TypeNames.insert(std::make_pair(Ty, TypeName));//Cache type name for later use
342 return (Out << TypeName);
346 /// WriteTypeSymbolic - This attempts to write the specified type as a symbolic
347 /// type, iff there is an entry in the modules symbol table for the specified
348 /// type or one of it's component types. This is slower than a simple x << Type
350 std::ostream &llvm::WriteTypeSymbolic(std::ostream &Out, const Type *Ty,
354 // If they want us to print out a type, attempt to make it symbolic if there
355 // is a symbol table in the module...
357 std::map<const Type *, std::string> TypeNames;
358 fillTypeNameTable(M, TypeNames);
360 return printTypeInt(Out, Ty, TypeNames);
362 return Out << Ty->getDescription();
366 static void WriteConstantInt(std::ostream &Out, const Constant *CV,
368 std::map<const Type *, std::string> &TypeTable,
369 SlotMachine *Machine) {
370 if (const ConstantBool *CB = dyn_cast<ConstantBool>(CV)) {
371 Out << (CB == ConstantBool::True ? "true" : "false");
372 } else if (const ConstantSInt *CI = dyn_cast<ConstantSInt>(CV)) {
373 Out << CI->getValue();
374 } else if (const ConstantUInt *CI = dyn_cast<ConstantUInt>(CV)) {
375 Out << CI->getValue();
376 } else if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CV)) {
377 // We would like to output the FP constant value in exponential notation,
378 // but we cannot do this if doing so will lose precision. Check here to
379 // make sure that we only output it in exponential format if we can parse
380 // the value back and get the same value.
382 std::string StrVal = ftostr(CFP->getValue());
384 // Check to make sure that the stringized number is not some string like
385 // "Inf" or NaN, that atof will accept, but the lexer will not. Check that
386 // the string matches the "[-+]?[0-9]" regex.
388 if ((StrVal[0] >= '0' && StrVal[0] <= '9') ||
389 ((StrVal[0] == '-' || StrVal[0] == '+') &&
390 (StrVal[1] >= '0' && StrVal[1] <= '9')))
391 // Reparse stringized version!
392 if (atof(StrVal.c_str()) == CFP->getValue()) {
393 Out << StrVal; return;
396 // Otherwise we could not reparse it to exactly the same value, so we must
397 // output the string in hexadecimal format!
399 // Behave nicely in the face of C TBAA rules... see:
400 // http://www.nullstone.com/htmls/category/aliastyp.htm
402 double Val = CFP->getValue();
403 char *Ptr = (char*)&Val;
404 assert(sizeof(double) == sizeof(uint64_t) && sizeof(double) == 8 &&
405 "assuming that double is 64 bits!");
406 Out << "0x" << utohexstr(*(uint64_t*)Ptr);
408 } else if (isa<ConstantAggregateZero>(CV)) {
409 Out << "zeroinitializer";
410 } else if (const ConstantArray *CA = dyn_cast<ConstantArray>(CV)) {
411 // As a special case, print the array as a string if it is an array of
412 // ubytes or an array of sbytes with positive values.
414 const Type *ETy = CA->getType()->getElementType();
415 bool isString = (ETy == Type::SByteTy || ETy == Type::UByteTy);
417 if (ETy == Type::SByteTy)
418 for (unsigned i = 0; i < CA->getNumOperands(); ++i)
419 if (cast<ConstantSInt>(CA->getOperand(i))->getValue() < 0) {
426 for (unsigned i = 0; i < CA->getNumOperands(); ++i) {
428 (unsigned char)cast<ConstantInt>(CA->getOperand(i))->getRawValue();
430 if (isprint(C) && C != '"' && C != '\\') {
434 << (char) ((C/16 < 10) ? ( C/16 +'0') : ( C/16 -10+'A'))
435 << (char)(((C&15) < 10) ? ((C&15)+'0') : ((C&15)-10+'A'));
440 } else { // Cannot output in string format...
442 if (CA->getNumOperands()) {
444 printTypeInt(Out, ETy, TypeTable);
445 WriteAsOperandInternal(Out, CA->getOperand(0),
446 PrintName, TypeTable, Machine);
447 for (unsigned i = 1, e = CA->getNumOperands(); i != e; ++i) {
449 printTypeInt(Out, ETy, TypeTable);
450 WriteAsOperandInternal(Out, CA->getOperand(i), PrintName,
456 } else if (const ConstantStruct *CS = dyn_cast<ConstantStruct>(CV)) {
458 if (CS->getNumOperands()) {
460 printTypeInt(Out, CS->getOperand(0)->getType(), TypeTable);
462 WriteAsOperandInternal(Out, CS->getOperand(0),
463 PrintName, TypeTable, Machine);
465 for (unsigned i = 1; i < CS->getNumOperands(); i++) {
467 printTypeInt(Out, CS->getOperand(i)->getType(), TypeTable);
469 WriteAsOperandInternal(Out, CS->getOperand(i),
470 PrintName, TypeTable, Machine);
475 } else if (isa<ConstantPointerNull>(CV)) {
478 } else if (const ConstantPointerRef *PR = dyn_cast<ConstantPointerRef>(CV)) {
479 WriteAsOperandInternal(Out, PR->getValue(), true, TypeTable, Machine);
481 } else if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV)) {
482 Out << CE->getOpcodeName() << " (";
484 for (User::const_op_iterator OI=CE->op_begin(); OI != CE->op_end(); ++OI) {
485 printTypeInt(Out, (*OI)->getType(), TypeTable);
486 WriteAsOperandInternal(Out, *OI, PrintName, TypeTable, Machine);
487 if (OI+1 != CE->op_end())
491 if (CE->getOpcode() == Instruction::Cast) {
493 printTypeInt(Out, CE->getType(), TypeTable);
498 Out << "<placeholder or erroneous Constant>";
503 /// WriteAsOperand - Write the name of the specified value out to the specified
504 /// ostream. This can be useful when you just want to print int %reg126, not
505 /// the whole instruction that generated it.
507 static void WriteAsOperandInternal(std::ostream &Out, const Value *V,
509 std::map<const Type*, std::string> &TypeTable,
510 SlotMachine *Machine) {
512 if (PrintName && V->hasName()) {
513 Out << getLLVMName(V->getName());
515 if (const Constant *CV = dyn_cast<Constant>(V)) {
516 WriteConstantInt(Out, CV, PrintName, TypeTable, Machine);
520 Slot = Machine->getSlot(V);
522 if (const Type *Ty = dyn_cast<Type>(V)) {
523 Out << Ty->getDescription();
527 Machine = createSlotMachine(V);
529 Slot = Machine->getSlot(V);
543 /// WriteAsOperand - Write the name of the specified value out to the specified
544 /// ostream. This can be useful when you just want to print int %reg126, not
545 /// the whole instruction that generated it.
547 std::ostream &llvm::WriteAsOperand(std::ostream &Out, const Value *V,
548 bool PrintType, bool PrintName,
549 const Module *Context) {
550 std::map<const Type *, std::string> TypeNames;
551 if (Context == 0) Context = getModuleFromVal(V);
554 fillTypeNameTable(Context, TypeNames);
557 printTypeInt(Out, V->getType(), TypeNames);
559 if (const Type *Ty = dyn_cast<Type> (V))
560 printTypeInt(Out, Ty, TypeNames);
562 WriteAsOperandInternal(Out, V, PrintName, TypeNames, 0);
568 class AssemblyWriter {
570 SlotMachine &Machine;
571 const Module *TheModule;
572 std::map<const Type *, std::string> TypeNames;
573 AssemblyAnnotationWriter *AnnotationWriter;
575 inline AssemblyWriter(std::ostream &o, SlotMachine &Mac, const Module *M,
576 AssemblyAnnotationWriter *AAW)
577 : Out(&o), Machine(Mac), TheModule(M), AnnotationWriter(AAW) {
579 // If the module has a symbol table, take all global types and stuff their
580 // names into the TypeNames map.
582 fillTypeNameTable(M, TypeNames);
585 inline void write(const Module *M) { printModule(M); }
586 inline void write(const GlobalVariable *G) { printGlobal(G); }
587 inline void write(const Function *F) { printFunction(F); }
588 inline void write(const BasicBlock *BB) { printBasicBlock(BB); }
589 inline void write(const Instruction *I) { printInstruction(*I); }
590 inline void write(const Constant *CPV) { printConstant(CPV); }
591 inline void write(const Type *Ty) { printType(Ty); }
593 void writeOperand(const Value *Op, bool PrintType, bool PrintName = true);
595 const Module* getModule() { return TheModule; }
596 void setStream(std::ostream &os) { Out = &os; }
599 void printModule(const Module *M);
600 void printSymbolTable(const SymbolTable &ST);
601 void printConstant(const Constant *CPV);
602 void printGlobal(const GlobalVariable *GV);
603 void printFunction(const Function *F);
604 void printArgument(const Argument *FA);
605 void printBasicBlock(const BasicBlock *BB);
606 void printInstruction(const Instruction &I);
608 // printType - Go to extreme measures to attempt to print out a short,
609 // symbolic version of a type name.
611 std::ostream &printType(const Type *Ty) {
612 return printTypeInt(*Out, Ty, TypeNames);
615 // printTypeAtLeastOneLevel - Print out one level of the possibly complex type
616 // without considering any symbolic types that we may have equal to it.
618 std::ostream &printTypeAtLeastOneLevel(const Type *Ty);
620 // printInfoComment - Print a little comment after the instruction indicating
621 // which slot it occupies.
622 void printInfoComment(const Value &V);
624 } // end of llvm namespace
626 /// printTypeAtLeastOneLevel - Print out one level of the possibly complex type
627 /// without considering any symbolic types that we may have equal to it.
629 std::ostream &AssemblyWriter::printTypeAtLeastOneLevel(const Type *Ty) {
630 if (const FunctionType *FTy = dyn_cast<FunctionType>(Ty)) {
631 printType(FTy->getReturnType()) << " (";
632 for (FunctionType::param_iterator I = FTy->param_begin(),
633 E = FTy->param_end(); I != E; ++I) {
634 if (I != FTy->param_begin())
638 if (FTy->isVarArg()) {
639 if (FTy->getNumParams()) *Out << ", ";
643 } else if (const StructType *STy = dyn_cast<StructType>(Ty)) {
645 for (StructType::element_iterator I = STy->element_begin(),
646 E = STy->element_end(); I != E; ++I) {
647 if (I != STy->element_begin())
652 } else if (const PointerType *PTy = dyn_cast<PointerType>(Ty)) {
653 printType(PTy->getElementType()) << '*';
654 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
655 *Out << '[' << ATy->getNumElements() << " x ";
656 printType(ATy->getElementType()) << ']';
657 } else if (const OpaqueType *OTy = dyn_cast<OpaqueType>(Ty)) {
660 if (!Ty->isPrimitiveType())
661 *Out << "<unknown derived type>";
668 void AssemblyWriter::writeOperand(const Value *Operand, bool PrintType,
670 if (PrintType) { *Out << ' '; printType(Operand->getType()); }
671 WriteAsOperandInternal(*Out, Operand, PrintName, TypeNames, &Machine);
675 void AssemblyWriter::printModule(const Module *M) {
676 switch (M->getEndianness()) {
677 case Module::LittleEndian: *Out << "target endian = little\n"; break;
678 case Module::BigEndian: *Out << "target endian = big\n"; break;
679 case Module::AnyEndianness: break;
681 switch (M->getPointerSize()) {
682 case Module::Pointer32: *Out << "target pointersize = 32\n"; break;
683 case Module::Pointer64: *Out << "target pointersize = 64\n"; break;
684 case Module::AnyPointerSize: break;
687 // Loop over the symbol table, emitting all named constants...
688 printSymbolTable(M->getSymbolTable());
690 for (Module::const_giterator I = M->gbegin(), E = M->gend(); I != E; ++I)
693 *Out << "\nimplementation ; Functions:\n";
695 // Output all of the functions...
696 for (Module::const_iterator I = M->begin(), E = M->end(); I != E; ++I)
700 void AssemblyWriter::printGlobal(const GlobalVariable *GV) {
701 if (GV->hasName()) *Out << getLLVMName(GV->getName()) << " = ";
703 if (!GV->hasInitializer())
706 switch (GV->getLinkage()) {
707 case GlobalValue::InternalLinkage: *Out << "internal "; break;
708 case GlobalValue::LinkOnceLinkage: *Out << "linkonce "; break;
709 case GlobalValue::WeakLinkage: *Out << "weak "; break;
710 case GlobalValue::AppendingLinkage: *Out << "appending "; break;
711 case GlobalValue::ExternalLinkage: break;
714 *Out << (GV->isConstant() ? "constant " : "global ");
715 printType(GV->getType()->getElementType());
717 if (GV->hasInitializer())
718 writeOperand(GV->getInitializer(), false, false);
720 printInfoComment(*GV);
725 // printSymbolTable - Run through symbol table looking for constants
726 // and types. Emit their declarations.
727 void AssemblyWriter::printSymbolTable(const SymbolTable &ST) {
730 for (SymbolTable::type_const_iterator TI = ST.type_begin();
731 TI != ST.type_end(); ++TI ) {
732 *Out << "\t" << getLLVMName(TI->first) << " = type ";
734 // Make sure we print out at least one level of the type structure, so
735 // that we do not get %FILE = type %FILE
737 printTypeAtLeastOneLevel(TI->second) << "\n";
740 // Print the constants, in type plane order.
741 for (SymbolTable::plane_const_iterator PI = ST.plane_begin();
742 PI != ST.plane_end(); ++PI ) {
743 SymbolTable::value_const_iterator VI = ST.value_begin(PI->first);
744 SymbolTable::value_const_iterator VE = ST.value_end(PI->first);
746 for (; VI != VE; ++VI) {
747 const Value *V = VI->second;
748 if (const Constant *CPV = dyn_cast<Constant>(V)) {
756 /// printConstant - Print out a constant pool entry...
758 void AssemblyWriter::printConstant(const Constant *CPV) {
759 // Don't print out unnamed constants, they will be inlined
760 if (!CPV->hasName()) return;
763 *Out << "\t" << getLLVMName(CPV->getName()) << " =";
765 // Write the value out now...
766 writeOperand(CPV, true, false);
768 printInfoComment(*CPV);
772 /// printFunction - Print all aspects of a function.
774 void AssemblyWriter::printFunction(const Function *F) {
775 // Print out the return type and name...
778 if (AnnotationWriter) AnnotationWriter->emitFunctionAnnot(F, *Out);
783 switch (F->getLinkage()) {
784 case GlobalValue::InternalLinkage: *Out << "internal "; break;
785 case GlobalValue::LinkOnceLinkage: *Out << "linkonce "; break;
786 case GlobalValue::WeakLinkage: *Out << "weak "; break;
787 case GlobalValue::AppendingLinkage: *Out << "appending "; break;
788 case GlobalValue::ExternalLinkage: break;
791 printType(F->getReturnType()) << ' ';
792 if (!F->getName().empty())
793 *Out << getLLVMName(F->getName());
797 Machine.incorporateFunction(F);
799 // Loop over the arguments, printing them...
800 const FunctionType *FT = F->getFunctionType();
802 for(Function::const_aiterator I = F->abegin(), E = F->aend(); I != E; ++I)
805 // Finish printing arguments...
806 if (FT->isVarArg()) {
807 if (FT->getNumParams()) *Out << ", ";
808 *Out << "..."; // Output varargs portion of signature!
812 if (F->isExternal()) {
817 // Output all of its basic blocks... for the function
818 for (Function::const_iterator I = F->begin(), E = F->end(); I != E; ++I)
824 Machine.purgeFunction();
827 /// printArgument - This member is called for every argument that is passed into
828 /// the function. Simply print it out
830 void AssemblyWriter::printArgument(const Argument *Arg) {
831 // Insert commas as we go... the first arg doesn't get a comma
832 if (Arg != &Arg->getParent()->afront()) *Out << ", ";
835 printType(Arg->getType());
837 // Output name, if available...
839 *Out << ' ' << getLLVMName(Arg->getName());
842 /// printBasicBlock - This member is called for each basic block in a method.
844 void AssemblyWriter::printBasicBlock(const BasicBlock *BB) {
845 if (BB->hasName()) { // Print out the label if it exists...
846 *Out << "\n" << BB->getName() << ':';
847 } else if (!BB->use_empty()) { // Don't print block # of no uses...
848 *Out << "\n; <label>:";
849 int Slot = Machine.getSlot(BB);
856 if (BB->getParent() == 0)
857 *Out << "\t\t; Error: Block without parent!";
859 if (BB != &BB->getParent()->front()) { // Not the entry block?
860 // Output predecessors for the block...
862 pred_const_iterator PI = pred_begin(BB), PE = pred_end(BB);
865 *Out << " No predecessors!";
868 writeOperand(*PI, false, true);
869 for (++PI; PI != PE; ++PI) {
871 writeOperand(*PI, false, true);
879 if (AnnotationWriter) AnnotationWriter->emitBasicBlockStartAnnot(BB, *Out);
881 // Output all of the instructions in the basic block...
882 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I != E; ++I)
883 printInstruction(*I);
885 if (AnnotationWriter) AnnotationWriter->emitBasicBlockEndAnnot(BB, *Out);
889 /// printInfoComment - Print a little comment after the instruction indicating
890 /// which slot it occupies.
892 void AssemblyWriter::printInfoComment(const Value &V) {
893 if (V.getType() != Type::VoidTy) {
895 printType(V.getType()) << '>';
898 int SlotNum = Machine.getSlot(&V);
902 *Out << ':' << SlotNum; // Print out the def slot taken.
904 *Out << " [#uses=" << V.use_size() << ']'; // Output # uses
908 /// printInstruction - This member is called for each Instruction in a function..
910 void AssemblyWriter::printInstruction(const Instruction &I) {
911 if (AnnotationWriter) AnnotationWriter->emitInstructionAnnot(&I, *Out);
915 // Print out name if it exists...
917 *Out << getLLVMName(I.getName()) << " = ";
919 // If this is a volatile load or store, print out the volatile marker
920 if ((isa<LoadInst>(I) && cast<LoadInst>(I).isVolatile()) ||
921 (isa<StoreInst>(I) && cast<StoreInst>(I).isVolatile()))
924 // Print out the opcode...
925 *Out << I.getOpcodeName();
927 // Print out the type of the operands...
928 const Value *Operand = I.getNumOperands() ? I.getOperand(0) : 0;
930 // Special case conditional branches to swizzle the condition out to the front
931 if (isa<BranchInst>(I) && I.getNumOperands() > 1) {
932 writeOperand(I.getOperand(2), true);
934 writeOperand(Operand, true);
936 writeOperand(I.getOperand(1), true);
938 } else if (isa<SwitchInst>(I)) {
939 // Special case switch statement to get formatting nice and correct...
940 writeOperand(Operand , true); *Out << ',';
941 writeOperand(I.getOperand(1), true); *Out << " [";
943 for (unsigned op = 2, Eop = I.getNumOperands(); op < Eop; op += 2) {
945 writeOperand(I.getOperand(op ), true); *Out << ',';
946 writeOperand(I.getOperand(op+1), true);
949 } else if (isa<PHINode>(I)) {
951 printType(I.getType());
954 for (unsigned op = 0, Eop = I.getNumOperands(); op < Eop; op += 2) {
955 if (op) *Out << ", ";
957 writeOperand(I.getOperand(op ), false); *Out << ',';
958 writeOperand(I.getOperand(op+1), false); *Out << " ]";
960 } else if (isa<ReturnInst>(I) && !Operand) {
962 } else if (isa<CallInst>(I)) {
963 const PointerType *PTy = cast<PointerType>(Operand->getType());
964 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
965 const Type *RetTy = FTy->getReturnType();
967 // If possible, print out the short form of the call instruction. We can
968 // only do this if the first argument is a pointer to a nonvararg function,
969 // and if the return type is not a pointer to a function.
971 if (!FTy->isVarArg() &&
972 (!isa<PointerType>(RetTy) ||
973 !isa<FunctionType>(cast<PointerType>(RetTy)->getElementType()))) {
974 *Out << ' '; printType(RetTy);
975 writeOperand(Operand, false);
977 writeOperand(Operand, true);
980 if (I.getNumOperands() > 1) writeOperand(I.getOperand(1), true);
981 for (unsigned op = 2, Eop = I.getNumOperands(); op < Eop; ++op) {
983 writeOperand(I.getOperand(op), true);
987 } else if (const InvokeInst *II = dyn_cast<InvokeInst>(&I)) {
988 const PointerType *PTy = cast<PointerType>(Operand->getType());
989 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
990 const Type *RetTy = FTy->getReturnType();
992 // If possible, print out the short form of the invoke instruction. We can
993 // only do this if the first argument is a pointer to a nonvararg function,
994 // and if the return type is not a pointer to a function.
996 if (!FTy->isVarArg() &&
997 (!isa<PointerType>(RetTy) ||
998 !isa<FunctionType>(cast<PointerType>(RetTy)->getElementType()))) {
999 *Out << ' '; printType(RetTy);
1000 writeOperand(Operand, false);
1002 writeOperand(Operand, true);
1006 if (I.getNumOperands() > 3) writeOperand(I.getOperand(3), true);
1007 for (unsigned op = 4, Eop = I.getNumOperands(); op < Eop; ++op) {
1009 writeOperand(I.getOperand(op), true);
1012 *Out << " )\n\t\t\tto";
1013 writeOperand(II->getNormalDest(), true);
1015 writeOperand(II->getUnwindDest(), true);
1017 } else if (const AllocationInst *AI = dyn_cast<AllocationInst>(&I)) {
1019 printType(AI->getType()->getElementType());
1020 if (AI->isArrayAllocation()) {
1022 writeOperand(AI->getArraySize(), true);
1024 } else if (isa<CastInst>(I)) {
1025 if (Operand) writeOperand(Operand, true); // Work with broken code
1027 printType(I.getType());
1028 } else if (isa<VAArgInst>(I)) {
1029 if (Operand) writeOperand(Operand, true); // Work with broken code
1031 printType(I.getType());
1032 } else if (const VANextInst *VAN = dyn_cast<VANextInst>(&I)) {
1033 if (Operand) writeOperand(Operand, true); // Work with broken code
1035 printType(VAN->getArgType());
1036 } else if (Operand) { // Print the normal way...
1038 // PrintAllTypes - Instructions who have operands of all the same type
1039 // omit the type from all but the first operand. If the instruction has
1040 // different type operands (for example br), then they are all printed.
1041 bool PrintAllTypes = false;
1042 const Type *TheType = Operand->getType();
1044 // Shift Left & Right print both types even for Ubyte LHS, and select prints
1045 // types even if all operands are bools.
1046 if (isa<ShiftInst>(I) || isa<SelectInst>(I)) {
1047 PrintAllTypes = true;
1049 for (unsigned i = 1, E = I.getNumOperands(); i != E; ++i) {
1050 Operand = I.getOperand(i);
1051 if (Operand->getType() != TheType) {
1052 PrintAllTypes = true; // We have differing types! Print them all!
1058 if (!PrintAllTypes) {
1063 for (unsigned i = 0, E = I.getNumOperands(); i != E; ++i) {
1065 writeOperand(I.getOperand(i), PrintAllTypes);
1069 printInfoComment(I);
1074 //===----------------------------------------------------------------------===//
1075 // External Interface declarations
1076 //===----------------------------------------------------------------------===//
1078 void Module::print(std::ostream &o, AssemblyAnnotationWriter *AAW) const {
1079 SlotMachine SlotTable(this);
1080 AssemblyWriter W(o, SlotTable, this, AAW);
1084 void GlobalVariable::print(std::ostream &o) const {
1085 SlotMachine SlotTable(getParent());
1086 AssemblyWriter W(o, SlotTable, getParent(), 0);
1090 void Function::print(std::ostream &o, AssemblyAnnotationWriter *AAW) const {
1091 SlotMachine SlotTable(getParent());
1092 AssemblyWriter W(o, SlotTable, getParent(), AAW);
1097 void BasicBlock::print(std::ostream &o, AssemblyAnnotationWriter *AAW) const {
1098 SlotMachine SlotTable(getParent());
1099 AssemblyWriter W(o, SlotTable,
1100 getParent() ? getParent()->getParent() : 0, AAW);
1104 void Instruction::print(std::ostream &o, AssemblyAnnotationWriter *AAW) const {
1105 const Function *F = getParent() ? getParent()->getParent() : 0;
1106 SlotMachine SlotTable(F);
1107 AssemblyWriter W(o, SlotTable, F ? F->getParent() : 0, AAW);
1112 void Constant::print(std::ostream &o) const {
1113 if (this == 0) { o << "<null> constant value\n"; return; }
1115 // Handle CPR's special, because they have context information...
1116 if (const ConstantPointerRef *CPR = dyn_cast<ConstantPointerRef>(this)) {
1117 CPR->getValue()->print(o); // Print as a global value, with context info.
1121 o << ' ' << getType()->getDescription() << ' ';
1123 std::map<const Type *, std::string> TypeTable;
1124 WriteConstantInt(o, this, false, TypeTable, 0);
1127 void Type::print(std::ostream &o) const {
1131 o << getDescription();
1134 void Argument::print(std::ostream &o) const {
1135 o << getType() << ' ' << getName();
1138 // Value::dump - allow easy printing of Values from the debugger.
1139 // Located here because so much of the needed functionality is here.
1140 void Value::dump() const { print(std::cerr); }
1142 // Type::dump - allow easy printing of Values from the debugger.
1143 // Located here because so much of the needed functionality is here.
1144 void Type::dump() const { print(std::cerr); }
1146 //===----------------------------------------------------------------------===//
1147 // CachedWriter Class Implementation
1148 //===----------------------------------------------------------------------===//
1150 void CachedWriter::setModule(const Module *M) {
1151 delete SC; delete AW;
1153 SC = new SlotMachine(M );
1154 AW = new AssemblyWriter(Out, *SC, M, 0);
1160 CachedWriter::~CachedWriter() {
1165 CachedWriter &CachedWriter::operator<<(const Value *V) {
1166 assert(AW && SC && "CachedWriter does not have a current module!");
1167 switch (V->getValueType()) {
1168 case Value::ConstantVal:
1169 case Value::ArgumentVal: AW->writeOperand(V, true, true); break;
1170 case Value::TypeVal: AW->write(cast<Type>(V)); break;
1171 case Value::InstructionVal: AW->write(cast<Instruction>(V)); break;
1172 case Value::BasicBlockVal: AW->write(cast<BasicBlock>(V)); break;
1173 case Value::FunctionVal: AW->write(cast<Function>(V)); break;
1174 case Value::GlobalVariableVal: AW->write(cast<GlobalVariable>(V)); break;
1175 default: Out << "<unknown value type: " << V->getValueType() << '>'; break;
1180 CachedWriter& CachedWriter::operator<<(const Type *X) {
1181 if (SymbolicTypes) {
1182 const Module *M = AW->getModule();
1183 if (M) WriteTypeSymbolic(Out, X, M);
1186 return *this << (const Value*)X;
1189 //===----------------------------------------------------------------------===//
1190 //===-- SlotMachine Implementation
1191 //===----------------------------------------------------------------------===//
1194 #define SC_DEBUG(X) std::cerr << X
1199 // Module level constructor. Causes the contents of the Module (sans functions)
1200 // to be added to the slot table.
1201 SlotMachine::SlotMachine(const Module *M)
1202 : TheModule(M) ///< Saved for lazy initialization.
1209 // Function level constructor. Causes the contents of the Module and the one
1210 // function provided to be added to the slot table.
1211 SlotMachine::SlotMachine(const Function *F )
1212 : TheModule( F ? F->getParent() : 0 ) ///< Saved for lazy initialization
1213 , TheFunction(F) ///< Saved for lazy initialization
1219 inline void SlotMachine::initialize(void) {
1222 TheModule = 0; ///< Prevent re-processing next time we're called.
1224 if ( TheFunction ) {
1229 // Iterate through all the global variables, functions, and global
1230 // variable initializers and create slots for them.
1231 void SlotMachine::processModule() {
1232 SC_DEBUG("begin processModule!\n");
1234 // Add all of the global variables to the value table...
1235 for (Module::const_giterator I = TheModule->gbegin(), E = TheModule->gend();
1239 // Add all the functions to the table
1240 for (Module::const_iterator I = TheModule->begin(), E = TheModule->end();
1244 SC_DEBUG("end processModule!\n");
1248 // Process the arguments, basic blocks, and instructions of a function.
1249 void SlotMachine::processFunction() {
1250 SC_DEBUG("begin processFunction!\n");
1252 // Add all the function arguments
1253 for(Function::const_aiterator AI = TheFunction->abegin(),
1254 AE = TheFunction->aend(); AI != AE; ++AI)
1257 SC_DEBUG("Inserting Instructions:\n");
1259 // Add all of the basic blocks and instructions
1260 for (Function::const_iterator BB = TheFunction->begin(),
1261 E = TheFunction->end(); BB != E; ++BB) {
1263 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I!=E; ++I) {
1268 SC_DEBUG("end processFunction!\n");
1271 // Clean up after incorporating a function. This is the only way
1272 // to get out of the function incorporation state that affects the
1273 // getSlot/createSlot lock. Function incorporation state is indicated
1274 // by TheFunction != 0.
1275 void SlotMachine::purgeFunction() {
1276 SC_DEBUG("begin purgeFunction!\n");
1277 fMap.clear(); // Simply discard the function level map
1279 SC_DEBUG("end purgeFunction!\n");
1282 /// Get the slot number for a value. This function will assert if you
1283 /// ask for a Value that hasn't previously been inserted with createSlot.
1284 /// Types are forbidden because Type does not inherit from Value (any more).
1285 int SlotMachine::getSlot(const Value *V) {
1286 assert( V && "Can't get slot for null Value" );
1287 assert( !isa<Type>(V) && "Can't get slot for a type" );
1288 assert(!isa<Constant>(V) || isa<GlobalValue>(V) &&
1289 "Can't insert a non-GlobalValue Constant into SlotMachine");
1291 // Check for uninitialized state and do lazy initialization
1294 // Do not number CPR's at all. They are an abomination
1295 if ( const ConstantPointerRef* CPR = dyn_cast<ConstantPointerRef>(V) )
1296 V = CPR->getValue() ;
1298 // Get the type of the value
1299 const Type* VTy = V->getType();
1301 // Find the type plane in the module map
1302 TypedPlanes::const_iterator MI = mMap.find(VTy);
1304 if ( TheFunction ) {
1305 // Lookup the type in the function map too
1306 TypedPlanes::const_iterator FI = fMap.find(VTy);
1307 // If there is a corresponding type plane in the function map
1308 if ( FI != fMap.end() ) {
1309 // Lookup the Value in the function map
1310 ValueMap::const_iterator FVI = FI->second.map.find(V);
1311 // If the value doesn't exist in the function map
1312 if ( FVI == FI->second.map.end() ) {
1313 // Look up the value in the module map
1314 ValueMap::const_iterator MVI = MI->second.map.find(V);
1315 // If we didn't find it, it wasn't inserted
1316 if (MVI == MI->second.map.end()) return -1;
1317 assert( MVI != MI->second.map.end() && "Value not found");
1318 // We found it only at the module level
1321 // else the value exists in the function map
1323 // Return the slot number as the module's contribution to
1324 // the type plane plus the index in the function's contribution
1325 // to the type plane.
1326 return MI->second.next_slot + FVI->second;
1331 // N.B. Can get here only if either !TheFunction or the function doesn't
1332 // have a corresponding type plane for the Value
1334 // Make sure the type plane exists
1335 if (MI == mMap.end()) return -1;
1336 // Lookup the value in the module's map
1337 ValueMap::const_iterator MVI = MI->second.map.find(V);
1338 // Make sure we found it.
1339 if (MVI == MI->second.map.end()) return -1;
1344 // Create a new slot, or return the existing slot if it is already
1345 // inserted. Note that the logic here parallels getSlot but instead
1346 // of asserting when the Value* isn't found, it inserts the value.
1347 unsigned SlotMachine::createSlot(const Value *V) {
1348 assert( V && "Can't insert a null Value to SlotMachine");
1349 assert( !isa<Type>(V) && "Can't insert a Type into SlotMachine");
1350 assert(!isa<Constant>(V) || isa<GlobalValue>(V) &&
1351 "Can't insert a non-GlobalValue Constant into SlotMachine");
1353 const Type* VTy = V->getType();
1355 // Just ignore void typed things
1356 if (VTy == Type::VoidTy) return 0; // FIXME: Wrong return value!
1358 // Look up the type plane for the Value's type from the module map
1359 TypedPlanes::const_iterator MI = mMap.find(VTy);
1361 if ( TheFunction ) {
1362 // Get the type plane for the Value's type from the function map
1363 TypedPlanes::const_iterator FI = fMap.find(VTy);
1364 // If there is a corresponding type plane in the function map
1365 if ( FI != fMap.end() ) {
1366 // Lookup the Value in the function map
1367 ValueMap::const_iterator FVI = FI->second.map.find(V);
1368 // If the value doesn't exist in the function map
1369 if ( FVI == FI->second.map.end() ) {
1370 // If there is no corresponding type plane in the module map
1371 if ( MI == mMap.end() )
1372 return insertValue(V);
1373 // Look up the value in the module map
1374 ValueMap::const_iterator MVI = MI->second.map.find(V);
1375 // If we didn't find it, it wasn't inserted
1376 if ( MVI == MI->second.map.end() )
1377 return insertValue(V);
1379 // We found it only at the module level
1382 // else the value exists in the function map
1384 if ( MI == mMap.end() )
1387 // Return the slot number as the module's contribution to
1388 // the type plane plus the index in the function's contribution
1389 // to the type plane.
1390 return MI->second.next_slot + FVI->second;
1393 // else there is not a corresponding type plane in the function map
1395 // If the type plane doesn't exists at the module level
1396 if ( MI == mMap.end() ) {
1397 return insertValue(V);
1398 // else type plane exists at the module level, examine it
1400 // Look up the value in the module's map
1401 ValueMap::const_iterator MVI = MI->second.map.find(V);
1402 // If we didn't find it there either
1403 if ( MVI == MI->second.map.end() )
1404 // Return the slot number as the module's contribution to
1405 // the type plane plus the index of the function map insertion.
1406 return MI->second.next_slot + insertValue(V);
1413 // N.B. Can only get here if !TheFunction
1415 // If the module map's type plane is not for the Value's type
1416 if ( MI != mMap.end() ) {
1417 // Lookup the value in the module's map
1418 ValueMap::const_iterator MVI = MI->second.map.find(V);
1419 if ( MVI != MI->second.map.end() )
1423 return insertValue(V);
1427 // Low level insert function. Minimal checking is done. This
1428 // function is just for the convenience of createSlot (above).
1429 unsigned SlotMachine::insertValue(const Value *V ) {
1430 assert(V && "Can't insert a null Value into SlotMachine!");
1431 assert(!isa<Type>(V) && "Can't insert a Type into SlotMachine!");
1432 assert(!isa<Constant>(V) || isa<GlobalValue>(V) &&
1433 "Can't insert a non-GlobalValue Constant into SlotMachine");
1435 // If this value does not contribute to a plane (is void)
1436 // or if the value already has a name then ignore it.
1437 if (V->getType() == Type::VoidTy || V->hasName() ) {
1438 SC_DEBUG("ignored value " << *V << "\n");
1439 return 0; // FIXME: Wrong return value
1442 const Type *VTy = V->getType();
1443 unsigned DestSlot = 0;
1445 if ( TheFunction ) {
1446 TypedPlanes::iterator I = fMap.find( VTy );
1447 if ( I == fMap.end() )
1448 I = fMap.insert(std::make_pair(VTy,Plane())).first;
1449 DestSlot = I->second.map[V] = I->second.next_slot++;
1451 TypedPlanes::iterator I = mMap.find( VTy );
1452 if ( I == mMap.end() )
1453 I = mMap.insert(std::make_pair(VTy,Plane())).first;
1454 DestSlot = I->second.map[V] = I->second.next_slot++;
1457 SC_DEBUG(" Inserting value [" << VTy << "] = " << V << " slot=" <<
1459 // G = Global, C = Constant, T = Type, F = Function, o = other
1460 SC_DEBUG((isa<GlobalVariable>(V) ? 'G' : (isa<Constant>(V) ? 'C' :
1461 (isa<Function>(V) ? 'F' : 'o'))));