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 unsigned getSlot(const Value *V) ;
83 /// If you'd like to deal with a function instead of just a module, use
84 /// this method to get its data into the SlotMachine.
85 void incorporateFunction(const Function *F) { TheFunction = F; }
87 /// After calling incorporateFunction, use this method to remove the
88 /// most recently incorporated function from the SlotMachine. This
89 /// will reset the state of the machine back to just the module contents.
93 /// @name Implementation Details
96 /// This function does the actual initialization.
97 inline void initialize();
99 /// Values can be crammed into here at will. If they haven't
100 /// been inserted already, they get inserted, otherwise they are ignored.
101 /// Either way, the slot number for the Value* is returned.
102 unsigned createSlot(const Value *V);
104 /// Insert a value into the value table. Return the slot number
105 /// that it now occupies. BadThings(TM) will happen if you insert a
106 /// Value that's already been inserted.
107 unsigned insertValue( const Value *V );
109 /// Add all of the module level global variables (and their initializers)
110 /// and function declarations, but not the contents of those functions.
111 void processModule();
113 /// Add all of the functions arguments, basic blocks, and instructions
114 void processFunction();
116 SlotMachine(const SlotMachine &); // DO NOT IMPLEMENT
117 void operator=(const SlotMachine &); // DO NOT IMPLEMENT
124 /// @brief The module for which we are holding slot numbers
125 const Module* TheModule;
127 /// @brief The function for which we are holding slot numbers
128 const Function* TheFunction;
130 /// @brief The TypePlanes map for the module level data
133 /// @brief The TypePlanes map for the function level data
142 static RegisterPass<PrintModulePass>
143 X("printm", "Print module to stderr",PassInfo::Analysis|PassInfo::Optimization);
144 static RegisterPass<PrintFunctionPass>
145 Y("print","Print function to stderr",PassInfo::Analysis|PassInfo::Optimization);
147 static void WriteAsOperandInternal(std::ostream &Out, const Value *V,
149 std::map<const Type *, std::string> &TypeTable,
150 SlotMachine *Machine);
152 static const Module *getModuleFromVal(const Value *V) {
153 if (const Argument *MA = dyn_cast<Argument>(V))
154 return MA->getParent() ? MA->getParent()->getParent() : 0;
155 else if (const BasicBlock *BB = dyn_cast<BasicBlock>(V))
156 return BB->getParent() ? BB->getParent()->getParent() : 0;
157 else if (const Instruction *I = dyn_cast<Instruction>(V)) {
158 const Function *M = I->getParent() ? I->getParent()->getParent() : 0;
159 return M ? M->getParent() : 0;
160 } else if (const GlobalValue *GV = dyn_cast<GlobalValue>(V))
161 return GV->getParent();
165 static SlotMachine *createSlotMachine(const Value *V) {
166 assert(!isa<Type>(V) && "Can't create an SC for a type!");
167 if (const Argument *FA = dyn_cast<Argument>(V)) {
168 return new SlotMachine(FA->getParent());
169 } else if (const Instruction *I = dyn_cast<Instruction>(V)) {
170 return new SlotMachine(I->getParent()->getParent());
171 } else if (const BasicBlock *BB = dyn_cast<BasicBlock>(V)) {
172 return new SlotMachine(BB->getParent());
173 } else if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(V)){
174 return new SlotMachine(GV->getParent());
175 } else if (const Function *Func = dyn_cast<Function>(V)) {
176 return new SlotMachine(Func);
181 // getLLVMName - Turn the specified string into an 'LLVM name', which is either
182 // prefixed with % (if the string only contains simple characters) or is
183 // surrounded with ""'s (if it has special chars in it).
184 static std::string getLLVMName(const std::string &Name) {
185 assert(!Name.empty() && "Cannot get empty name!");
187 // First character cannot start with a number...
188 if (Name[0] >= '0' && Name[0] <= '9')
189 return "\"" + Name + "\"";
191 // Scan to see if we have any characters that are not on the "white list"
192 for (unsigned i = 0, e = Name.size(); i != e; ++i) {
194 assert(C != '"' && "Illegal character in LLVM value name!");
195 if ((C < 'a' || C > 'z') && (C < 'A' || C > 'Z') && (C < '0' || C > '9') &&
196 C != '-' && C != '.' && C != '_')
197 return "\"" + Name + "\"";
200 // If we get here, then the identifier is legal to use as a "VarID".
205 /// fillTypeNameTable - If the module has a symbol table, take all global types
206 /// and stuff their names into the TypeNames map.
208 static void fillTypeNameTable(const Module *M,
209 std::map<const Type *, std::string> &TypeNames) {
211 const SymbolTable &ST = M->getSymbolTable();
212 SymbolTable::type_const_iterator TI = ST.type_begin();
213 for (; TI != ST.type_end(); ++TI ) {
214 // As a heuristic, don't insert pointer to primitive types, because
215 // they are used too often to have a single useful name.
217 const Type *Ty = cast<Type>(TI->second);
218 if (!isa<PointerType>(Ty) ||
219 !cast<PointerType>(Ty)->getElementType()->isPrimitiveType() ||
220 isa<OpaqueType>(cast<PointerType>(Ty)->getElementType()))
221 TypeNames.insert(std::make_pair(Ty, getLLVMName(TI->first)));
227 static void calcTypeName(const Type *Ty,
228 std::vector<const Type *> &TypeStack,
229 std::map<const Type *, std::string> &TypeNames,
230 std::string & Result){
231 if (Ty->isPrimitiveType() && !isa<OpaqueType>(Ty)) {
232 Result += Ty->getDescription(); // Base case
236 // Check to see if the type is named.
237 std::map<const Type *, std::string>::iterator I = TypeNames.find(Ty);
238 if (I != TypeNames.end()) {
243 if (isa<OpaqueType>(Ty)) {
248 // Check to see if the Type is already on the stack...
249 unsigned Slot = 0, CurSize = TypeStack.size();
250 while (Slot < CurSize && TypeStack[Slot] != Ty) ++Slot; // Scan for type
252 // This is another base case for the recursion. In this case, we know
253 // that we have looped back to a type that we have previously visited.
254 // Generate the appropriate upreference to handle this.
255 if (Slot < CurSize) {
256 Result += "\\" + utostr(CurSize-Slot); // Here's the upreference
260 TypeStack.push_back(Ty); // Recursive case: Add us to the stack..
262 switch (Ty->getPrimitiveID()) {
263 case Type::FunctionTyID: {
264 const FunctionType *FTy = cast<FunctionType>(Ty);
265 calcTypeName(FTy->getReturnType(), TypeStack, TypeNames, Result);
267 for (FunctionType::param_iterator I = FTy->param_begin(),
268 E = FTy->param_end(); I != E; ++I) {
269 if (I != FTy->param_begin())
271 calcTypeName(*I, TypeStack, TypeNames, Result);
273 if (FTy->isVarArg()) {
274 if (FTy->getNumParams()) Result += ", ";
280 case Type::StructTyID: {
281 const StructType *STy = cast<StructType>(Ty);
283 for (StructType::element_iterator I = STy->element_begin(),
284 E = STy->element_end(); I != E; ++I) {
285 if (I != STy->element_begin())
287 calcTypeName(*I, TypeStack, TypeNames, Result);
292 case Type::PointerTyID:
293 calcTypeName(cast<PointerType>(Ty)->getElementType(),
294 TypeStack, TypeNames, Result);
297 case Type::ArrayTyID: {
298 const ArrayType *ATy = cast<ArrayType>(Ty);
299 Result += "[" + utostr(ATy->getNumElements()) + " x ";
300 calcTypeName(ATy->getElementType(), TypeStack, TypeNames, Result);
304 case Type::OpaqueTyID:
308 Result += "<unrecognized-type>";
311 TypeStack.pop_back(); // Remove self from stack...
316 /// printTypeInt - The internal guts of printing out a type that has a
317 /// potentially named portion.
319 static std::ostream &printTypeInt(std::ostream &Out, const Type *Ty,
320 std::map<const Type *, std::string> &TypeNames) {
321 // Primitive types always print out their description, regardless of whether
322 // they have been named or not.
324 if (Ty->isPrimitiveType() && !isa<OpaqueType>(Ty))
325 return Out << Ty->getDescription();
327 // Check to see if the type is named.
328 std::map<const Type *, std::string>::iterator I = TypeNames.find(Ty);
329 if (I != TypeNames.end()) return Out << I->second;
331 // Otherwise we have a type that has not been named but is a derived type.
332 // Carefully recurse the type hierarchy to print out any contained symbolic
335 std::vector<const Type *> TypeStack;
336 std::string TypeName;
337 calcTypeName(Ty, TypeStack, TypeNames, TypeName);
338 TypeNames.insert(std::make_pair(Ty, TypeName));//Cache type name for later use
339 return (Out << TypeName);
343 /// WriteTypeSymbolic - This attempts to write the specified type as a symbolic
344 /// type, iff there is an entry in the modules symbol table for the specified
345 /// type or one of it's component types. This is slower than a simple x << Type
347 std::ostream &llvm::WriteTypeSymbolic(std::ostream &Out, const Type *Ty,
351 // If they want us to print out a type, attempt to make it symbolic if there
352 // is a symbol table in the module...
354 std::map<const Type *, std::string> TypeNames;
355 fillTypeNameTable(M, TypeNames);
357 return printTypeInt(Out, Ty, TypeNames);
359 return Out << Ty->getDescription();
363 static void WriteConstantInt(std::ostream &Out, const Constant *CV,
365 std::map<const Type *, std::string> &TypeTable,
366 SlotMachine *Machine) {
367 if (const ConstantBool *CB = dyn_cast<ConstantBool>(CV)) {
368 Out << (CB == ConstantBool::True ? "true" : "false");
369 } else if (const ConstantSInt *CI = dyn_cast<ConstantSInt>(CV)) {
370 Out << CI->getValue();
371 } else if (const ConstantUInt *CI = dyn_cast<ConstantUInt>(CV)) {
372 Out << CI->getValue();
373 } else if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CV)) {
374 // We would like to output the FP constant value in exponential notation,
375 // but we cannot do this if doing so will lose precision. Check here to
376 // make sure that we only output it in exponential format if we can parse
377 // the value back and get the same value.
379 std::string StrVal = ftostr(CFP->getValue());
381 // Check to make sure that the stringized number is not some string like
382 // "Inf" or NaN, that atof will accept, but the lexer will not. Check that
383 // the string matches the "[-+]?[0-9]" regex.
385 if ((StrVal[0] >= '0' && StrVal[0] <= '9') ||
386 ((StrVal[0] == '-' || StrVal[0] == '+') &&
387 (StrVal[1] >= '0' && StrVal[1] <= '9')))
388 // Reparse stringized version!
389 if (atof(StrVal.c_str()) == CFP->getValue()) {
390 Out << StrVal; return;
393 // Otherwise we could not reparse it to exactly the same value, so we must
394 // output the string in hexadecimal format!
396 // Behave nicely in the face of C TBAA rules... see:
397 // http://www.nullstone.com/htmls/category/aliastyp.htm
399 double Val = CFP->getValue();
400 char *Ptr = (char*)&Val;
401 assert(sizeof(double) == sizeof(uint64_t) && sizeof(double) == 8 &&
402 "assuming that double is 64 bits!");
403 Out << "0x" << utohexstr(*(uint64_t*)Ptr);
405 } else if (isa<ConstantAggregateZero>(CV)) {
406 Out << "zeroinitializer";
407 } else if (const ConstantArray *CA = dyn_cast<ConstantArray>(CV)) {
408 // As a special case, print the array as a string if it is an array of
409 // ubytes or an array of sbytes with positive values.
411 const Type *ETy = CA->getType()->getElementType();
412 bool isString = (ETy == Type::SByteTy || ETy == Type::UByteTy);
414 if (ETy == Type::SByteTy)
415 for (unsigned i = 0; i < CA->getNumOperands(); ++i)
416 if (cast<ConstantSInt>(CA->getOperand(i))->getValue() < 0) {
423 for (unsigned i = 0; i < CA->getNumOperands(); ++i) {
424 unsigned char C = cast<ConstantInt>(CA->getOperand(i))->getRawValue();
426 if (isprint(C) && C != '"' && C != '\\') {
430 << (char) ((C/16 < 10) ? ( C/16 +'0') : ( C/16 -10+'A'))
431 << (char)(((C&15) < 10) ? ((C&15)+'0') : ((C&15)-10+'A'));
436 } else { // Cannot output in string format...
438 if (CA->getNumOperands()) {
440 printTypeInt(Out, ETy, TypeTable);
441 WriteAsOperandInternal(Out, CA->getOperand(0),
442 PrintName, TypeTable, Machine);
443 for (unsigned i = 1, e = CA->getNumOperands(); i != e; ++i) {
445 printTypeInt(Out, ETy, TypeTable);
446 WriteAsOperandInternal(Out, CA->getOperand(i), PrintName,
452 } else if (const ConstantStruct *CS = dyn_cast<ConstantStruct>(CV)) {
454 if (CS->getNumOperands()) {
456 printTypeInt(Out, CS->getOperand(0)->getType(), TypeTable);
458 WriteAsOperandInternal(Out, CS->getOperand(0),
459 PrintName, TypeTable, Machine);
461 for (unsigned i = 1; i < CS->getNumOperands(); i++) {
463 printTypeInt(Out, CS->getOperand(i)->getType(), TypeTable);
465 WriteAsOperandInternal(Out, CS->getOperand(i),
466 PrintName, TypeTable, Machine);
471 } else if (isa<ConstantPointerNull>(CV)) {
474 } else if (const ConstantPointerRef *PR = dyn_cast<ConstantPointerRef>(CV)) {
475 WriteAsOperandInternal(Out, PR->getValue(), true, TypeTable, Machine);
477 } else if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV)) {
478 Out << CE->getOpcodeName() << " (";
480 for (User::const_op_iterator OI=CE->op_begin(); OI != CE->op_end(); ++OI) {
481 printTypeInt(Out, (*OI)->getType(), TypeTable);
482 WriteAsOperandInternal(Out, *OI, PrintName, TypeTable, Machine);
483 if (OI+1 != CE->op_end())
487 if (CE->getOpcode() == Instruction::Cast) {
489 printTypeInt(Out, CE->getType(), TypeTable);
494 Out << "<placeholder or erroneous Constant>";
499 /// WriteAsOperand - Write the name of the specified value out to the specified
500 /// ostream. This can be useful when you just want to print int %reg126, not
501 /// the whole instruction that generated it.
503 static void WriteAsOperandInternal(std::ostream &Out, const Value *V,
505 std::map<const Type*, std::string> &TypeTable,
506 SlotMachine *Machine) {
508 if (PrintName && V->hasName()) {
509 Out << getLLVMName(V->getName());
511 if (const Constant *CV = dyn_cast<Constant>(V)) {
512 WriteConstantInt(Out, CV, PrintName, TypeTable, Machine);
516 Slot = Machine->getSlot(V);
518 if (const Type *Ty = dyn_cast<Type>(V)) {
519 Out << Ty->getDescription();
523 Machine = createSlotMachine(V);
524 if (Machine == 0) { Out << "BAD VALUE TYPE!"; return; }
526 Slot = Machine->getSlot(V);
535 /// WriteAsOperand - Write the name of the specified value out to the specified
536 /// ostream. This can be useful when you just want to print int %reg126, not
537 /// the whole instruction that generated it.
539 std::ostream &llvm::WriteAsOperand(std::ostream &Out, const Value *V,
540 bool PrintType, bool PrintName,
541 const Module *Context) {
542 std::map<const Type *, std::string> TypeNames;
543 if (Context == 0) Context = getModuleFromVal(V);
546 fillTypeNameTable(Context, TypeNames);
549 printTypeInt(Out, V->getType(), TypeNames);
551 if (const Type *Ty = dyn_cast<Type> (V))
552 printTypeInt(Out, Ty, TypeNames);
554 WriteAsOperandInternal(Out, V, PrintName, TypeNames, 0);
560 class AssemblyWriter {
562 SlotMachine &Machine;
563 const Module *TheModule;
564 std::map<const Type *, std::string> TypeNames;
565 AssemblyAnnotationWriter *AnnotationWriter;
567 inline AssemblyWriter(std::ostream &o, SlotMachine &Mac, const Module *M,
568 AssemblyAnnotationWriter *AAW)
569 : Out(&o), Machine(Mac), TheModule(M), AnnotationWriter(AAW) {
571 // If the module has a symbol table, take all global types and stuff their
572 // names into the TypeNames map.
574 fillTypeNameTable(M, TypeNames);
577 inline void write(const Module *M) { printModule(M); }
578 inline void write(const GlobalVariable *G) { printGlobal(G); }
579 inline void write(const Function *F) { printFunction(F); }
580 inline void write(const BasicBlock *BB) { printBasicBlock(BB); }
581 inline void write(const Instruction *I) { printInstruction(*I); }
582 inline void write(const Constant *CPV) { printConstant(CPV); }
583 inline void write(const Type *Ty) { printType(Ty); }
585 void writeOperand(const Value *Op, bool PrintType, bool PrintName = true);
587 const Module* getModule() { return TheModule; }
588 void setStream(std::ostream &os) { Out = &os; }
591 void printModule(const Module *M);
592 void printSymbolTable(const SymbolTable &ST);
593 void printConstant(const Constant *CPV);
594 void printGlobal(const GlobalVariable *GV);
595 void printFunction(const Function *F);
596 void printArgument(const Argument *FA);
597 void printBasicBlock(const BasicBlock *BB);
598 void printInstruction(const Instruction &I);
600 // printType - Go to extreme measures to attempt to print out a short,
601 // symbolic version of a type name.
603 std::ostream &printType(const Type *Ty) {
604 return printTypeInt(*Out, Ty, TypeNames);
607 // printTypeAtLeastOneLevel - Print out one level of the possibly complex type
608 // without considering any symbolic types that we may have equal to it.
610 std::ostream &printTypeAtLeastOneLevel(const Type *Ty);
612 // printInfoComment - Print a little comment after the instruction indicating
613 // which slot it occupies.
614 void printInfoComment(const Value &V);
616 } // end of llvm namespace
618 /// printTypeAtLeastOneLevel - Print out one level of the possibly complex type
619 /// without considering any symbolic types that we may have equal to it.
621 std::ostream &AssemblyWriter::printTypeAtLeastOneLevel(const Type *Ty) {
622 if (const FunctionType *FTy = dyn_cast<FunctionType>(Ty)) {
623 printType(FTy->getReturnType()) << " (";
624 for (FunctionType::param_iterator I = FTy->param_begin(),
625 E = FTy->param_end(); I != E; ++I) {
626 if (I != FTy->param_begin())
630 if (FTy->isVarArg()) {
631 if (FTy->getNumParams()) *Out << ", ";
635 } else if (const StructType *STy = dyn_cast<StructType>(Ty)) {
637 for (StructType::element_iterator I = STy->element_begin(),
638 E = STy->element_end(); I != E; ++I) {
639 if (I != STy->element_begin())
644 } else if (const PointerType *PTy = dyn_cast<PointerType>(Ty)) {
645 printType(PTy->getElementType()) << '*';
646 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
647 *Out << '[' << ATy->getNumElements() << " x ";
648 printType(ATy->getElementType()) << ']';
649 } else if (const OpaqueType *OTy = dyn_cast<OpaqueType>(Ty)) {
652 if (!Ty->isPrimitiveType())
653 *Out << "<unknown derived type>";
660 void AssemblyWriter::writeOperand(const Value *Operand, bool PrintType,
662 if (PrintType) { *Out << ' '; printType(Operand->getType()); }
663 WriteAsOperandInternal(*Out, Operand, PrintName, TypeNames, &Machine);
667 void AssemblyWriter::printModule(const Module *M) {
668 switch (M->getEndianness()) {
669 case Module::LittleEndian: *Out << "target endian = little\n"; break;
670 case Module::BigEndian: *Out << "target endian = big\n"; break;
671 case Module::AnyEndianness: break;
673 switch (M->getPointerSize()) {
674 case Module::Pointer32: *Out << "target pointersize = 32\n"; break;
675 case Module::Pointer64: *Out << "target pointersize = 64\n"; break;
676 case Module::AnyPointerSize: break;
679 // Loop over the symbol table, emitting all named constants...
680 printSymbolTable(M->getSymbolTable());
682 for (Module::const_giterator I = M->gbegin(), E = M->gend(); I != E; ++I)
685 *Out << "\nimplementation ; Functions:\n";
687 // Output all of the functions...
688 for (Module::const_iterator I = M->begin(), E = M->end(); I != E; ++I)
692 void AssemblyWriter::printGlobal(const GlobalVariable *GV) {
693 if (GV->hasName()) *Out << getLLVMName(GV->getName()) << " = ";
695 if (!GV->hasInitializer())
698 switch (GV->getLinkage()) {
699 case GlobalValue::InternalLinkage: *Out << "internal "; break;
700 case GlobalValue::LinkOnceLinkage: *Out << "linkonce "; break;
701 case GlobalValue::WeakLinkage: *Out << "weak "; break;
702 case GlobalValue::AppendingLinkage: *Out << "appending "; break;
703 case GlobalValue::ExternalLinkage: break;
706 *Out << (GV->isConstant() ? "constant " : "global ");
707 printType(GV->getType()->getElementType());
709 if (GV->hasInitializer())
710 writeOperand(GV->getInitializer(), false, false);
712 printInfoComment(*GV);
717 // printSymbolTable - Run through symbol table looking for constants
718 // and types. Emit their declarations.
719 void AssemblyWriter::printSymbolTable(const SymbolTable &ST) {
722 for (SymbolTable::type_const_iterator TI = ST.type_begin();
723 TI != ST.type_end(); ++TI ) {
724 *Out << "\t" << getLLVMName(TI->first) << " = type ";
726 // Make sure we print out at least one level of the type structure, so
727 // that we do not get %FILE = type %FILE
729 printTypeAtLeastOneLevel(TI->second) << "\n";
732 // Print the constants, in type plane order.
733 for (SymbolTable::plane_const_iterator PI = ST.plane_begin();
734 PI != ST.plane_end(); ++PI ) {
735 SymbolTable::value_const_iterator VI = ST.value_begin(PI->first);
736 SymbolTable::value_const_iterator VE = ST.value_end(PI->first);
738 for (; VI != VE; ++VI) {
739 const Value *V = VI->second;
740 if (const Constant *CPV = dyn_cast<Constant>(V)) {
748 /// printConstant - Print out a constant pool entry...
750 void AssemblyWriter::printConstant(const Constant *CPV) {
751 // Don't print out unnamed constants, they will be inlined
752 if (!CPV->hasName()) return;
755 *Out << "\t" << getLLVMName(CPV->getName()) << " =";
757 // Write the value out now...
758 writeOperand(CPV, true, false);
760 printInfoComment(*CPV);
764 /// printFunction - Print all aspects of a function.
766 void AssemblyWriter::printFunction(const Function *F) {
767 // Print out the return type and name...
770 if (AnnotationWriter) AnnotationWriter->emitFunctionAnnot(F, *Out);
775 switch (F->getLinkage()) {
776 case GlobalValue::InternalLinkage: *Out << "internal "; break;
777 case GlobalValue::LinkOnceLinkage: *Out << "linkonce "; break;
778 case GlobalValue::WeakLinkage: *Out << "weak "; break;
779 case GlobalValue::AppendingLinkage: *Out << "appending "; break;
780 case GlobalValue::ExternalLinkage: break;
783 printType(F->getReturnType()) << ' ';
784 if (!F->getName().empty())
785 *Out << getLLVMName(F->getName());
789 Machine.incorporateFunction(F);
791 // Loop over the arguments, printing them...
792 const FunctionType *FT = F->getFunctionType();
794 for(Function::const_aiterator I = F->abegin(), E = F->aend(); I != E; ++I)
797 // Finish printing arguments...
798 if (FT->isVarArg()) {
799 if (FT->getNumParams()) *Out << ", ";
800 *Out << "..."; // Output varargs portion of signature!
804 if (F->isExternal()) {
809 // Output all of its basic blocks... for the function
810 for (Function::const_iterator I = F->begin(), E = F->end(); I != E; ++I)
816 Machine.purgeFunction();
819 /// printArgument - This member is called for every argument that is passed into
820 /// the function. Simply print it out
822 void AssemblyWriter::printArgument(const Argument *Arg) {
823 // Insert commas as we go... the first arg doesn't get a comma
824 if (Arg != &Arg->getParent()->afront()) *Out << ", ";
827 printType(Arg->getType());
829 // Output name, if available...
831 *Out << ' ' << getLLVMName(Arg->getName());
834 /// printBasicBlock - This member is called for each basic block in a method.
836 void AssemblyWriter::printBasicBlock(const BasicBlock *BB) {
837 if (BB->hasName()) { // Print out the label if it exists...
838 *Out << "\n" << BB->getName() << ':';
839 } else if (!BB->use_empty()) { // Don't print block # of no uses...
840 *Out << "\n; <label>:" << Machine.getSlot(BB);
843 if (BB->getParent() == 0)
844 *Out << "\t\t; Error: Block without parent!";
846 if (BB != &BB->getParent()->front()) { // Not the entry block?
847 // Output predecessors for the block...
849 pred_const_iterator PI = pred_begin(BB), PE = pred_end(BB);
852 *Out << " No predecessors!";
855 writeOperand(*PI, false, true);
856 for (++PI; PI != PE; ++PI) {
858 writeOperand(*PI, false, true);
866 if (AnnotationWriter) AnnotationWriter->emitBasicBlockStartAnnot(BB, *Out);
868 // Output all of the instructions in the basic block...
869 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I != E; ++I)
870 printInstruction(*I);
872 if (AnnotationWriter) AnnotationWriter->emitBasicBlockEndAnnot(BB, *Out);
876 /// printInfoComment - Print a little comment after the instruction indicating
877 /// which slot it occupies.
879 void AssemblyWriter::printInfoComment(const Value &V) {
880 if (V.getType() != Type::VoidTy) {
882 printType(V.getType()) << '>';
885 *Out << ':' << Machine.getSlot(&V); // Print out the def slot taken.
887 *Out << " [#uses=" << V.use_size() << ']'; // Output # uses
891 /// printInstruction - This member is called for each Instruction in a method.
893 void AssemblyWriter::printInstruction(const Instruction &I) {
894 if (AnnotationWriter) AnnotationWriter->emitInstructionAnnot(&I, *Out);
898 // Print out name if it exists...
900 *Out << getLLVMName(I.getName()) << " = ";
902 // If this is a volatile load or store, print out the volatile marker
903 if ((isa<LoadInst>(I) && cast<LoadInst>(I).isVolatile()) ||
904 (isa<StoreInst>(I) && cast<StoreInst>(I).isVolatile()))
907 // Print out the opcode...
908 *Out << I.getOpcodeName();
910 // Print out the type of the operands...
911 const Value *Operand = I.getNumOperands() ? I.getOperand(0) : 0;
913 // Special case conditional branches to swizzle the condition out to the front
914 if (isa<BranchInst>(I) && I.getNumOperands() > 1) {
915 writeOperand(I.getOperand(2), true);
917 writeOperand(Operand, true);
919 writeOperand(I.getOperand(1), true);
921 } else if (isa<SwitchInst>(I)) {
922 // Special case switch statement to get formatting nice and correct...
923 writeOperand(Operand , true); *Out << ',';
924 writeOperand(I.getOperand(1), true); *Out << " [";
926 for (unsigned op = 2, Eop = I.getNumOperands(); op < Eop; op += 2) {
928 writeOperand(I.getOperand(op ), true); *Out << ',';
929 writeOperand(I.getOperand(op+1), true);
932 } else if (isa<PHINode>(I)) {
934 printType(I.getType());
937 for (unsigned op = 0, Eop = I.getNumOperands(); op < Eop; op += 2) {
938 if (op) *Out << ", ";
940 writeOperand(I.getOperand(op ), false); *Out << ',';
941 writeOperand(I.getOperand(op+1), false); *Out << " ]";
943 } else if (isa<ReturnInst>(I) && !Operand) {
945 } else if (isa<CallInst>(I)) {
946 const PointerType *PTy = cast<PointerType>(Operand->getType());
947 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
948 const Type *RetTy = FTy->getReturnType();
950 // If possible, print out the short form of the call instruction. We can
951 // only do this if the first argument is a pointer to a nonvararg function,
952 // and if the return type is not a pointer to a function.
954 if (!FTy->isVarArg() &&
955 (!isa<PointerType>(RetTy) ||
956 !isa<FunctionType>(cast<PointerType>(RetTy)->getElementType()))) {
957 *Out << ' '; printType(RetTy);
958 writeOperand(Operand, false);
960 writeOperand(Operand, true);
963 if (I.getNumOperands() > 1) writeOperand(I.getOperand(1), true);
964 for (unsigned op = 2, Eop = I.getNumOperands(); op < Eop; ++op) {
966 writeOperand(I.getOperand(op), true);
970 } else if (const InvokeInst *II = dyn_cast<InvokeInst>(&I)) {
971 const PointerType *PTy = cast<PointerType>(Operand->getType());
972 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
973 const Type *RetTy = FTy->getReturnType();
975 // If possible, print out the short form of the invoke instruction. We can
976 // only do this if the first argument is a pointer to a nonvararg function,
977 // and if the return type is not a pointer to a function.
979 if (!FTy->isVarArg() &&
980 (!isa<PointerType>(RetTy) ||
981 !isa<FunctionType>(cast<PointerType>(RetTy)->getElementType()))) {
982 *Out << ' '; printType(RetTy);
983 writeOperand(Operand, false);
985 writeOperand(Operand, true);
989 if (I.getNumOperands() > 3) writeOperand(I.getOperand(3), true);
990 for (unsigned op = 4, Eop = I.getNumOperands(); op < Eop; ++op) {
992 writeOperand(I.getOperand(op), true);
995 *Out << " )\n\t\t\tto";
996 writeOperand(II->getNormalDest(), true);
998 writeOperand(II->getUnwindDest(), true);
1000 } else if (const AllocationInst *AI = dyn_cast<AllocationInst>(&I)) {
1002 printType(AI->getType()->getElementType());
1003 if (AI->isArrayAllocation()) {
1005 writeOperand(AI->getArraySize(), true);
1007 } else if (isa<CastInst>(I)) {
1008 if (Operand) writeOperand(Operand, true); // Work with broken code
1010 printType(I.getType());
1011 } else if (isa<VAArgInst>(I)) {
1012 if (Operand) writeOperand(Operand, true); // Work with broken code
1014 printType(I.getType());
1015 } else if (const VANextInst *VAN = dyn_cast<VANextInst>(&I)) {
1016 if (Operand) writeOperand(Operand, true); // Work with broken code
1018 printType(VAN->getArgType());
1019 } else if (Operand) { // Print the normal way...
1021 // PrintAllTypes - Instructions who have operands of all the same type
1022 // omit the type from all but the first operand. If the instruction has
1023 // different type operands (for example br), then they are all printed.
1024 bool PrintAllTypes = false;
1025 const Type *TheType = Operand->getType();
1027 // Shift Left & Right print both types even for Ubyte LHS, and select prints
1028 // types even if all operands are bools.
1029 if (isa<ShiftInst>(I) || isa<SelectInst>(I)) {
1030 PrintAllTypes = true;
1032 for (unsigned i = 1, E = I.getNumOperands(); i != E; ++i) {
1033 Operand = I.getOperand(i);
1034 if (Operand->getType() != TheType) {
1035 PrintAllTypes = true; // We have differing types! Print them all!
1041 if (!PrintAllTypes) {
1046 for (unsigned i = 0, E = I.getNumOperands(); i != E; ++i) {
1048 writeOperand(I.getOperand(i), PrintAllTypes);
1052 printInfoComment(I);
1057 //===----------------------------------------------------------------------===//
1058 // External Interface declarations
1059 //===----------------------------------------------------------------------===//
1061 void Module::print(std::ostream &o, AssemblyAnnotationWriter *AAW) const {
1062 SlotMachine SlotTable(this);
1063 AssemblyWriter W(o, SlotTable, this, AAW);
1067 void GlobalVariable::print(std::ostream &o) const {
1068 SlotMachine SlotTable(getParent());
1069 AssemblyWriter W(o, SlotTable, getParent(), 0);
1073 void Function::print(std::ostream &o, AssemblyAnnotationWriter *AAW) const {
1074 SlotMachine SlotTable(getParent());
1075 AssemblyWriter W(o, SlotTable, getParent(), AAW);
1080 void BasicBlock::print(std::ostream &o, AssemblyAnnotationWriter *AAW) const {
1081 SlotMachine SlotTable(getParent());
1082 AssemblyWriter W(o, SlotTable,
1083 getParent() ? getParent()->getParent() : 0, AAW);
1087 void Instruction::print(std::ostream &o, AssemblyAnnotationWriter *AAW) const {
1088 const Function *F = getParent() ? getParent()->getParent() : 0;
1089 SlotMachine SlotTable(F);
1090 AssemblyWriter W(o, SlotTable, F ? F->getParent() : 0, AAW);
1095 void Constant::print(std::ostream &o) const {
1096 if (this == 0) { o << "<null> constant value\n"; return; }
1098 // Handle CPR's special, because they have context information...
1099 if (const ConstantPointerRef *CPR = dyn_cast<ConstantPointerRef>(this)) {
1100 CPR->getValue()->print(o); // Print as a global value, with context info.
1104 o << ' ' << getType()->getDescription() << ' ';
1106 std::map<const Type *, std::string> TypeTable;
1107 WriteConstantInt(o, this, false, TypeTable, 0);
1110 void Type::print(std::ostream &o) const {
1114 o << getDescription();
1117 void Argument::print(std::ostream &o) const {
1118 o << getType() << ' ' << getName();
1121 // Value::dump - allow easy printing of Values from the debugger.
1122 // Located here because so much of the needed functionality is here.
1123 void Value::dump() const { print(std::cerr); }
1125 // Type::dump - allow easy printing of Values from the debugger.
1126 // Located here because so much of the needed functionality is here.
1127 void Type::dump() const { print(std::cerr); }
1129 //===----------------------------------------------------------------------===//
1130 // CachedWriter Class Implementation
1131 //===----------------------------------------------------------------------===//
1133 void CachedWriter::setModule(const Module *M) {
1134 delete SC; delete AW;
1136 SC = new SlotMachine(M );
1137 AW = new AssemblyWriter(Out, *SC, M, 0);
1143 CachedWriter::~CachedWriter() {
1148 CachedWriter &CachedWriter::operator<<(const Value *V) {
1149 assert(AW && SC && "CachedWriter does not have a current module!");
1150 switch (V->getValueType()) {
1151 case Value::ConstantVal:
1152 case Value::ArgumentVal: AW->writeOperand(V, true, true); break;
1153 case Value::TypeVal: AW->write(cast<Type>(V)); break;
1154 case Value::InstructionVal: AW->write(cast<Instruction>(V)); break;
1155 case Value::BasicBlockVal: AW->write(cast<BasicBlock>(V)); break;
1156 case Value::FunctionVal: AW->write(cast<Function>(V)); break;
1157 case Value::GlobalVariableVal: AW->write(cast<GlobalVariable>(V)); break;
1158 default: Out << "<unknown value type: " << V->getValueType() << '>'; break;
1163 CachedWriter& CachedWriter::operator<<(const Type *X) {
1164 if (SymbolicTypes) {
1165 const Module *M = AW->getModule();
1166 if (M) WriteTypeSymbolic(Out, X, M);
1169 return *this << (const Value*)X;
1172 //===----------------------------------------------------------------------===//
1173 //===-- SlotMachine Implementation
1174 //===----------------------------------------------------------------------===//
1177 #define SC_DEBUG(X) std::cerr << X
1182 // Module level constructor. Causes the contents of the Module (sans functions)
1183 // to be added to the slot table.
1184 SlotMachine::SlotMachine(const Module *M)
1185 : TheModule(M) ///< Saved for lazy initialization.
1192 // Function level constructor. Causes the contents of the Module and the one
1193 // function provided to be added to the slot table.
1194 SlotMachine::SlotMachine(const Function *F )
1195 : TheModule( F ? F->getParent() : 0 ) ///< Saved for lazy initialization
1196 , TheFunction(F) ///< Saved for lazy initialization
1202 inline void SlotMachine::initialize(void) {
1205 TheModule = 0; ///< Prevent re-processing next time we're called.
1207 if ( TheFunction ) {
1212 // Iterate through all the global variables, functions, and global
1213 // variable initializers and create slots for them.
1214 void SlotMachine::processModule() {
1215 SC_DEBUG("begin processModule!\n");
1217 // Add all of the global variables to the value table...
1218 for (Module::const_giterator I = TheModule->gbegin(), E = TheModule->gend();
1222 // Add all the functions to the table
1223 for (Module::const_iterator I = TheModule->begin(), E = TheModule->end();
1227 SC_DEBUG("end processModule!\n");
1231 // Process the arguments, basic blocks, and instructions of a function.
1232 void SlotMachine::processFunction() {
1233 SC_DEBUG("begin processFunction!\n");
1235 // Add all the function arguments
1236 for(Function::const_aiterator AI = TheFunction->abegin(),
1237 AE = TheFunction->aend(); AI != AE; ++AI)
1240 SC_DEBUG("Inserting Instructions:\n");
1242 // Add all of the basic blocks and instructions
1243 for (Function::const_iterator BB = TheFunction->begin(),
1244 E = TheFunction->end(); BB != E; ++BB) {
1246 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I!=E; ++I) {
1251 SC_DEBUG("end processFunction!\n");
1254 // Clean up after incorporating a function. This is the only way
1255 // to get out of the function incorporation state that affects the
1256 // getSlot/createSlot lock. Function incorporation state is indicated
1257 // by TheFunction != 0.
1258 void SlotMachine::purgeFunction() {
1259 SC_DEBUG("begin purgeFunction!\n");
1260 fMap.clear(); // Simply discard the function level map
1262 SC_DEBUG("end purgeFunction!\n");
1265 /// Get the slot number for a value. This function will assert if you
1266 /// ask for a Value that hasn't previously been inserted with createSlot.
1267 /// Types are forbidden because Type does not inherit from Value (any more).
1268 unsigned SlotMachine::getSlot(const Value *V) {
1269 assert( V && "Can't get slot for null Value" );
1270 assert( !isa<Type>(V) && "Can't get slot for a type" );
1271 assert(!isa<Constant>(V) || isa<GlobalValue>(V) &&
1272 "Can't insert a non-GlobalValue Constant into SlotMachine");
1274 // Check for uninitialized state and do lazy initialization
1277 // Do not number CPR's at all. They are an abomination
1278 if ( const ConstantPointerRef* CPR = dyn_cast<ConstantPointerRef>(V) )
1279 V = CPR->getValue() ;
1281 // Get the type of the value
1282 const Type* VTy = V->getType();
1284 // Find the type plane in the module map
1285 TypedPlanes::const_iterator MI = mMap.find(VTy);
1287 if ( TheFunction ) {
1288 // Lookup the type in the function map too
1289 TypedPlanes::const_iterator FI = fMap.find(VTy);
1290 // If there is a corresponding type plane in the function map
1291 if ( FI != fMap.end() ) {
1292 // Lookup the Value in the function map
1293 ValueMap::const_iterator FVI = FI->second.map.find(V);
1294 // If the value doesn't exist in the function map
1295 if ( FVI == FI->second.map.end() ) {
1296 // Look up the value in the module map
1297 ValueMap::const_iterator MVI = MI->second.map.find(V);
1298 // If we didn't find it, it wasn't inserted
1299 assert( MVI != MI->second.map.end() && "Value not found");
1300 // We found it only at the module level
1303 // else the value exists in the function map
1305 // Return the slot number as the module's contribution to
1306 // the type plane plus the index in the function's contribution
1307 // to the type plane.
1308 return MI->second.next_slot + FVI->second;
1311 // else there is not a corresponding type plane in the function map
1313 assert( MI != mMap.end() && "No such type plane!" );
1314 // Look up the value in the module's map
1315 ValueMap::const_iterator MVI = MI->second.map.find(V);
1316 // If we didn't find it, it wasn't inserted.
1317 assert( MVI != MI->second.map.end() && "Value not found");
1318 // We found it only in the module level and function level
1319 // didn't even have a type plane.
1324 // N.B. Can only get here if !TheFunction
1326 // Make sure the type plane exists
1327 assert( MI != mMap.end() && "No such type plane!" );
1328 // Lookup the value in the module's map
1329 ValueMap::const_iterator MVI = MI->second.map.find(V);
1330 // Make sure we found it.
1331 assert( MVI != MI->second.map.end() && "Value not found" );
1337 // Create a new slot, or return the existing slot if it is already
1338 // inserted. Note that the logic here parallels getSlot but instead
1339 // of asserting when the Value* isn't found, it inserts the value.
1340 unsigned SlotMachine::createSlot(const Value *V) {
1341 assert( V && "Can't insert a null Value to SlotMachine");
1342 assert( !isa<Type>(V) && "Can't insert a Type into SlotMachine");
1343 assert(!isa<Constant>(V) || isa<GlobalValue>(V) &&
1344 "Can't insert a non-GlobalValue Constant into SlotMachine");
1346 const Type* VTy = V->getType();
1348 // Just ignore void typed things
1349 if (VTy == Type::VoidTy) return 0; // FIXME: Wrong return value!
1351 // Look up the type plane for the Value's type from the module map
1352 TypedPlanes::const_iterator MI = mMap.find(VTy);
1354 if ( TheFunction ) {
1355 // Get the type plane for the Value's type from the function map
1356 TypedPlanes::const_iterator FI = fMap.find(VTy);
1357 // If there is a corresponding type plane in the function map
1358 if ( FI != fMap.end() ) {
1359 // Lookup the Value in the function map
1360 ValueMap::const_iterator FVI = FI->second.map.find(V);
1361 // If the value doesn't exist in the function map
1362 if ( FVI == FI->second.map.end() ) {
1363 // If there is no corresponding type plane in the module map
1364 if ( MI == mMap.end() )
1365 return insertValue(V);
1366 // Look up the value in the module map
1367 ValueMap::const_iterator MVI = MI->second.map.find(V);
1368 // If we didn't find it, it wasn't inserted
1369 if ( MVI == MI->second.map.end() )
1370 return insertValue(V);
1372 // We found it only at the module level
1375 // else the value exists in the function map
1377 if ( MI == mMap.end() )
1380 // Return the slot number as the module's contribution to
1381 // the type plane plus the index in the function's contribution
1382 // to the type plane.
1383 return MI->second.next_slot + FVI->second;
1386 // else there is not a corresponding type plane in the function map
1388 // If the type plane doesn't exists at the module level
1389 if ( MI == mMap.end() ) {
1390 return insertValue(V);
1391 // else type plane exists at the module level, examine it
1393 // Look up the value in the module's map
1394 ValueMap::const_iterator MVI = MI->second.map.find(V);
1395 // If we didn't find it there either
1396 if ( MVI == MI->second.map.end() )
1397 // Return the slot number as the module's contribution to
1398 // the type plane plus the index of the function map insertion.
1399 return MI->second.next_slot + insertValue(V);
1406 // N.B. Can only get here if !TheFunction
1408 // If the module map's type plane is not for the Value's type
1409 if ( MI != mMap.end() ) {
1410 // Lookup the value in the module's map
1411 ValueMap::const_iterator MVI = MI->second.map.find(V);
1412 if ( MVI != MI->second.map.end() )
1416 return insertValue(V);
1420 // Low level insert function. Minimal checking is done. This
1421 // function is just for the convenience of createSlot (above).
1422 unsigned SlotMachine::insertValue(const Value *V ) {
1423 assert(V && "Can't insert a null Value into SlotMachine!");
1424 assert(!isa<Type>(V) && "Can't insert a Type into SlotMachine!");
1425 assert(!isa<Constant>(V) || isa<GlobalValue>(V) &&
1426 "Can't insert a non-GlobalValue Constant into SlotMachine");
1428 // If this value does not contribute to a plane (is void)
1429 // or if the value already has a name then ignore it.
1430 if (V->getType() == Type::VoidTy || V->hasName() ) {
1431 SC_DEBUG("ignored value " << *V << "\n");
1432 return 0; // FIXME: Wrong return value
1435 const Type *VTy = V->getType();
1436 unsigned DestSlot = 0;
1438 if ( TheFunction ) {
1439 TypedPlanes::iterator I = fMap.find( VTy );
1440 if ( I == fMap.end() )
1441 I = fMap.insert(std::make_pair(VTy,Plane())).first;
1442 DestSlot = I->second.map[V] = I->second.next_slot++;
1444 TypedPlanes::iterator I = mMap.find( VTy );
1445 if ( I == mMap.end() )
1446 I = mMap.insert(std::make_pair(VTy,Plane())).first;
1447 DestSlot = I->second.map[V] = I->second.next_slot++;
1450 SC_DEBUG(" Inserting value [" << VTy << "] = " << V << " slot=" <<
1452 // G = Global, C = Constant, T = Type, F = Function, o = other
1453 SC_DEBUG((isa<GlobalVariable>(V) ? 'G' : (isa<Constant>(V) ? 'C' :
1454 (isa<Function>(V) ? 'F' : 'o'))));