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) {
425 (unsigned char)cast<ConstantInt>(CA->getOperand(i))->getRawValue();
427 if (isprint(C) && C != '"' && C != '\\') {
431 << (char) ((C/16 < 10) ? ( C/16 +'0') : ( C/16 -10+'A'))
432 << (char)(((C&15) < 10) ? ((C&15)+'0') : ((C&15)-10+'A'));
437 } else { // Cannot output in string format...
439 if (CA->getNumOperands()) {
441 printTypeInt(Out, ETy, TypeTable);
442 WriteAsOperandInternal(Out, CA->getOperand(0),
443 PrintName, TypeTable, Machine);
444 for (unsigned i = 1, e = CA->getNumOperands(); i != e; ++i) {
446 printTypeInt(Out, ETy, TypeTable);
447 WriteAsOperandInternal(Out, CA->getOperand(i), PrintName,
453 } else if (const ConstantStruct *CS = dyn_cast<ConstantStruct>(CV)) {
455 if (CS->getNumOperands()) {
457 printTypeInt(Out, CS->getOperand(0)->getType(), TypeTable);
459 WriteAsOperandInternal(Out, CS->getOperand(0),
460 PrintName, TypeTable, Machine);
462 for (unsigned i = 1; i < CS->getNumOperands(); i++) {
464 printTypeInt(Out, CS->getOperand(i)->getType(), TypeTable);
466 WriteAsOperandInternal(Out, CS->getOperand(i),
467 PrintName, TypeTable, Machine);
472 } else if (isa<ConstantPointerNull>(CV)) {
475 } else if (const ConstantPointerRef *PR = dyn_cast<ConstantPointerRef>(CV)) {
476 WriteAsOperandInternal(Out, PR->getValue(), true, TypeTable, Machine);
478 } else if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV)) {
479 Out << CE->getOpcodeName() << " (";
481 for (User::const_op_iterator OI=CE->op_begin(); OI != CE->op_end(); ++OI) {
482 printTypeInt(Out, (*OI)->getType(), TypeTable);
483 WriteAsOperandInternal(Out, *OI, PrintName, TypeTable, Machine);
484 if (OI+1 != CE->op_end())
488 if (CE->getOpcode() == Instruction::Cast) {
490 printTypeInt(Out, CE->getType(), TypeTable);
495 Out << "<placeholder or erroneous Constant>";
500 /// WriteAsOperand - Write the name of the specified value out to the specified
501 /// ostream. This can be useful when you just want to print int %reg126, not
502 /// the whole instruction that generated it.
504 static void WriteAsOperandInternal(std::ostream &Out, const Value *V,
506 std::map<const Type*, std::string> &TypeTable,
507 SlotMachine *Machine) {
509 if (PrintName && V->hasName()) {
510 Out << getLLVMName(V->getName());
512 if (const Constant *CV = dyn_cast<Constant>(V)) {
513 WriteConstantInt(Out, CV, PrintName, TypeTable, Machine);
517 Slot = Machine->getSlot(V);
519 if (const Type *Ty = dyn_cast<Type>(V)) {
520 Out << Ty->getDescription();
524 Machine = createSlotMachine(V);
525 if (Machine == 0) { Out << "BAD VALUE TYPE!"; return; }
527 Slot = Machine->getSlot(V);
536 /// WriteAsOperand - Write the name of the specified value out to the specified
537 /// ostream. This can be useful when you just want to print int %reg126, not
538 /// the whole instruction that generated it.
540 std::ostream &llvm::WriteAsOperand(std::ostream &Out, const Value *V,
541 bool PrintType, bool PrintName,
542 const Module *Context) {
543 std::map<const Type *, std::string> TypeNames;
544 if (Context == 0) Context = getModuleFromVal(V);
547 fillTypeNameTable(Context, TypeNames);
550 printTypeInt(Out, V->getType(), TypeNames);
552 if (const Type *Ty = dyn_cast<Type> (V))
553 printTypeInt(Out, Ty, TypeNames);
555 WriteAsOperandInternal(Out, V, PrintName, TypeNames, 0);
561 class AssemblyWriter {
563 SlotMachine &Machine;
564 const Module *TheModule;
565 std::map<const Type *, std::string> TypeNames;
566 AssemblyAnnotationWriter *AnnotationWriter;
568 inline AssemblyWriter(std::ostream &o, SlotMachine &Mac, const Module *M,
569 AssemblyAnnotationWriter *AAW)
570 : Out(&o), Machine(Mac), TheModule(M), AnnotationWriter(AAW) {
572 // If the module has a symbol table, take all global types and stuff their
573 // names into the TypeNames map.
575 fillTypeNameTable(M, TypeNames);
578 inline void write(const Module *M) { printModule(M); }
579 inline void write(const GlobalVariable *G) { printGlobal(G); }
580 inline void write(const Function *F) { printFunction(F); }
581 inline void write(const BasicBlock *BB) { printBasicBlock(BB); }
582 inline void write(const Instruction *I) { printInstruction(*I); }
583 inline void write(const Constant *CPV) { printConstant(CPV); }
584 inline void write(const Type *Ty) { printType(Ty); }
586 void writeOperand(const Value *Op, bool PrintType, bool PrintName = true);
588 const Module* getModule() { return TheModule; }
589 void setStream(std::ostream &os) { Out = &os; }
592 void printModule(const Module *M);
593 void printSymbolTable(const SymbolTable &ST);
594 void printConstant(const Constant *CPV);
595 void printGlobal(const GlobalVariable *GV);
596 void printFunction(const Function *F);
597 void printArgument(const Argument *FA);
598 void printBasicBlock(const BasicBlock *BB);
599 void printInstruction(const Instruction &I);
601 // printType - Go to extreme measures to attempt to print out a short,
602 // symbolic version of a type name.
604 std::ostream &printType(const Type *Ty) {
605 return printTypeInt(*Out, Ty, TypeNames);
608 // printTypeAtLeastOneLevel - Print out one level of the possibly complex type
609 // without considering any symbolic types that we may have equal to it.
611 std::ostream &printTypeAtLeastOneLevel(const Type *Ty);
613 // printInfoComment - Print a little comment after the instruction indicating
614 // which slot it occupies.
615 void printInfoComment(const Value &V);
617 } // end of llvm namespace
619 /// printTypeAtLeastOneLevel - Print out one level of the possibly complex type
620 /// without considering any symbolic types that we may have equal to it.
622 std::ostream &AssemblyWriter::printTypeAtLeastOneLevel(const Type *Ty) {
623 if (const FunctionType *FTy = dyn_cast<FunctionType>(Ty)) {
624 printType(FTy->getReturnType()) << " (";
625 for (FunctionType::param_iterator I = FTy->param_begin(),
626 E = FTy->param_end(); I != E; ++I) {
627 if (I != FTy->param_begin())
631 if (FTy->isVarArg()) {
632 if (FTy->getNumParams()) *Out << ", ";
636 } else if (const StructType *STy = dyn_cast<StructType>(Ty)) {
638 for (StructType::element_iterator I = STy->element_begin(),
639 E = STy->element_end(); I != E; ++I) {
640 if (I != STy->element_begin())
645 } else if (const PointerType *PTy = dyn_cast<PointerType>(Ty)) {
646 printType(PTy->getElementType()) << '*';
647 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
648 *Out << '[' << ATy->getNumElements() << " x ";
649 printType(ATy->getElementType()) << ']';
650 } else if (const OpaqueType *OTy = dyn_cast<OpaqueType>(Ty)) {
653 if (!Ty->isPrimitiveType())
654 *Out << "<unknown derived type>";
661 void AssemblyWriter::writeOperand(const Value *Operand, bool PrintType,
663 if (PrintType) { *Out << ' '; printType(Operand->getType()); }
664 WriteAsOperandInternal(*Out, Operand, PrintName, TypeNames, &Machine);
668 void AssemblyWriter::printModule(const Module *M) {
669 switch (M->getEndianness()) {
670 case Module::LittleEndian: *Out << "target endian = little\n"; break;
671 case Module::BigEndian: *Out << "target endian = big\n"; break;
672 case Module::AnyEndianness: break;
674 switch (M->getPointerSize()) {
675 case Module::Pointer32: *Out << "target pointersize = 32\n"; break;
676 case Module::Pointer64: *Out << "target pointersize = 64\n"; break;
677 case Module::AnyPointerSize: break;
680 // Loop over the symbol table, emitting all named constants...
681 printSymbolTable(M->getSymbolTable());
683 for (Module::const_giterator I = M->gbegin(), E = M->gend(); I != E; ++I)
686 *Out << "\nimplementation ; Functions:\n";
688 // Output all of the functions...
689 for (Module::const_iterator I = M->begin(), E = M->end(); I != E; ++I)
693 void AssemblyWriter::printGlobal(const GlobalVariable *GV) {
694 if (GV->hasName()) *Out << getLLVMName(GV->getName()) << " = ";
696 if (!GV->hasInitializer())
699 switch (GV->getLinkage()) {
700 case GlobalValue::InternalLinkage: *Out << "internal "; break;
701 case GlobalValue::LinkOnceLinkage: *Out << "linkonce "; break;
702 case GlobalValue::WeakLinkage: *Out << "weak "; break;
703 case GlobalValue::AppendingLinkage: *Out << "appending "; break;
704 case GlobalValue::ExternalLinkage: break;
707 *Out << (GV->isConstant() ? "constant " : "global ");
708 printType(GV->getType()->getElementType());
710 if (GV->hasInitializer())
711 writeOperand(GV->getInitializer(), false, false);
713 printInfoComment(*GV);
718 // printSymbolTable - Run through symbol table looking for constants
719 // and types. Emit their declarations.
720 void AssemblyWriter::printSymbolTable(const SymbolTable &ST) {
723 for (SymbolTable::type_const_iterator TI = ST.type_begin();
724 TI != ST.type_end(); ++TI ) {
725 *Out << "\t" << getLLVMName(TI->first) << " = type ";
727 // Make sure we print out at least one level of the type structure, so
728 // that we do not get %FILE = type %FILE
730 printTypeAtLeastOneLevel(TI->second) << "\n";
733 // Print the constants, in type plane order.
734 for (SymbolTable::plane_const_iterator PI = ST.plane_begin();
735 PI != ST.plane_end(); ++PI ) {
736 SymbolTable::value_const_iterator VI = ST.value_begin(PI->first);
737 SymbolTable::value_const_iterator VE = ST.value_end(PI->first);
739 for (; VI != VE; ++VI) {
740 const Value *V = VI->second;
741 if (const Constant *CPV = dyn_cast<Constant>(V)) {
749 /// printConstant - Print out a constant pool entry...
751 void AssemblyWriter::printConstant(const Constant *CPV) {
752 // Don't print out unnamed constants, they will be inlined
753 if (!CPV->hasName()) return;
756 *Out << "\t" << getLLVMName(CPV->getName()) << " =";
758 // Write the value out now...
759 writeOperand(CPV, true, false);
761 printInfoComment(*CPV);
765 /// printFunction - Print all aspects of a function.
767 void AssemblyWriter::printFunction(const Function *F) {
768 // Print out the return type and name...
771 if (AnnotationWriter) AnnotationWriter->emitFunctionAnnot(F, *Out);
776 switch (F->getLinkage()) {
777 case GlobalValue::InternalLinkage: *Out << "internal "; break;
778 case GlobalValue::LinkOnceLinkage: *Out << "linkonce "; break;
779 case GlobalValue::WeakLinkage: *Out << "weak "; break;
780 case GlobalValue::AppendingLinkage: *Out << "appending "; break;
781 case GlobalValue::ExternalLinkage: break;
784 printType(F->getReturnType()) << ' ';
785 if (!F->getName().empty())
786 *Out << getLLVMName(F->getName());
790 Machine.incorporateFunction(F);
792 // Loop over the arguments, printing them...
793 const FunctionType *FT = F->getFunctionType();
795 for(Function::const_aiterator I = F->abegin(), E = F->aend(); I != E; ++I)
798 // Finish printing arguments...
799 if (FT->isVarArg()) {
800 if (FT->getNumParams()) *Out << ", ";
801 *Out << "..."; // Output varargs portion of signature!
805 if (F->isExternal()) {
810 // Output all of its basic blocks... for the function
811 for (Function::const_iterator I = F->begin(), E = F->end(); I != E; ++I)
817 Machine.purgeFunction();
820 /// printArgument - This member is called for every argument that is passed into
821 /// the function. Simply print it out
823 void AssemblyWriter::printArgument(const Argument *Arg) {
824 // Insert commas as we go... the first arg doesn't get a comma
825 if (Arg != &Arg->getParent()->afront()) *Out << ", ";
828 printType(Arg->getType());
830 // Output name, if available...
832 *Out << ' ' << getLLVMName(Arg->getName());
835 /// printBasicBlock - This member is called for each basic block in a method.
837 void AssemblyWriter::printBasicBlock(const BasicBlock *BB) {
838 if (BB->hasName()) { // Print out the label if it exists...
839 *Out << "\n" << BB->getName() << ':';
840 } else if (!BB->use_empty()) { // Don't print block # of no uses...
841 *Out << "\n; <label>:" << Machine.getSlot(BB);
844 if (BB->getParent() == 0)
845 *Out << "\t\t; Error: Block without parent!";
847 if (BB != &BB->getParent()->front()) { // Not the entry block?
848 // Output predecessors for the block...
850 pred_const_iterator PI = pred_begin(BB), PE = pred_end(BB);
853 *Out << " No predecessors!";
856 writeOperand(*PI, false, true);
857 for (++PI; PI != PE; ++PI) {
859 writeOperand(*PI, false, true);
867 if (AnnotationWriter) AnnotationWriter->emitBasicBlockStartAnnot(BB, *Out);
869 // Output all of the instructions in the basic block...
870 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I != E; ++I)
871 printInstruction(*I);
873 if (AnnotationWriter) AnnotationWriter->emitBasicBlockEndAnnot(BB, *Out);
877 /// printInfoComment - Print a little comment after the instruction indicating
878 /// which slot it occupies.
880 void AssemblyWriter::printInfoComment(const Value &V) {
881 if (V.getType() != Type::VoidTy) {
883 printType(V.getType()) << '>';
886 *Out << ':' << Machine.getSlot(&V); // Print out the def slot taken.
888 *Out << " [#uses=" << V.use_size() << ']'; // Output # uses
892 /// printInstruction - This member is called for each Instruction in a method.
894 void AssemblyWriter::printInstruction(const Instruction &I) {
895 if (AnnotationWriter) AnnotationWriter->emitInstructionAnnot(&I, *Out);
899 // Print out name if it exists...
901 *Out << getLLVMName(I.getName()) << " = ";
903 // If this is a volatile load or store, print out the volatile marker
904 if ((isa<LoadInst>(I) && cast<LoadInst>(I).isVolatile()) ||
905 (isa<StoreInst>(I) && cast<StoreInst>(I).isVolatile()))
908 // Print out the opcode...
909 *Out << I.getOpcodeName();
911 // Print out the type of the operands...
912 const Value *Operand = I.getNumOperands() ? I.getOperand(0) : 0;
914 // Special case conditional branches to swizzle the condition out to the front
915 if (isa<BranchInst>(I) && I.getNumOperands() > 1) {
916 writeOperand(I.getOperand(2), true);
918 writeOperand(Operand, true);
920 writeOperand(I.getOperand(1), true);
922 } else if (isa<SwitchInst>(I)) {
923 // Special case switch statement to get formatting nice and correct...
924 writeOperand(Operand , true); *Out << ',';
925 writeOperand(I.getOperand(1), true); *Out << " [";
927 for (unsigned op = 2, Eop = I.getNumOperands(); op < Eop; op += 2) {
929 writeOperand(I.getOperand(op ), true); *Out << ',';
930 writeOperand(I.getOperand(op+1), true);
933 } else if (isa<PHINode>(I)) {
935 printType(I.getType());
938 for (unsigned op = 0, Eop = I.getNumOperands(); op < Eop; op += 2) {
939 if (op) *Out << ", ";
941 writeOperand(I.getOperand(op ), false); *Out << ',';
942 writeOperand(I.getOperand(op+1), false); *Out << " ]";
944 } else if (isa<ReturnInst>(I) && !Operand) {
946 } else if (isa<CallInst>(I)) {
947 const PointerType *PTy = cast<PointerType>(Operand->getType());
948 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
949 const Type *RetTy = FTy->getReturnType();
951 // If possible, print out the short form of the call instruction. We can
952 // only do this if the first argument is a pointer to a nonvararg function,
953 // and if the return type is not a pointer to a function.
955 if (!FTy->isVarArg() &&
956 (!isa<PointerType>(RetTy) ||
957 !isa<FunctionType>(cast<PointerType>(RetTy)->getElementType()))) {
958 *Out << ' '; printType(RetTy);
959 writeOperand(Operand, false);
961 writeOperand(Operand, true);
964 if (I.getNumOperands() > 1) writeOperand(I.getOperand(1), true);
965 for (unsigned op = 2, Eop = I.getNumOperands(); op < Eop; ++op) {
967 writeOperand(I.getOperand(op), true);
971 } else if (const InvokeInst *II = dyn_cast<InvokeInst>(&I)) {
972 const PointerType *PTy = cast<PointerType>(Operand->getType());
973 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
974 const Type *RetTy = FTy->getReturnType();
976 // If possible, print out the short form of the invoke instruction. We can
977 // only do this if the first argument is a pointer to a nonvararg function,
978 // and if the return type is not a pointer to a function.
980 if (!FTy->isVarArg() &&
981 (!isa<PointerType>(RetTy) ||
982 !isa<FunctionType>(cast<PointerType>(RetTy)->getElementType()))) {
983 *Out << ' '; printType(RetTy);
984 writeOperand(Operand, false);
986 writeOperand(Operand, true);
990 if (I.getNumOperands() > 3) writeOperand(I.getOperand(3), true);
991 for (unsigned op = 4, Eop = I.getNumOperands(); op < Eop; ++op) {
993 writeOperand(I.getOperand(op), true);
996 *Out << " )\n\t\t\tto";
997 writeOperand(II->getNormalDest(), true);
999 writeOperand(II->getUnwindDest(), true);
1001 } else if (const AllocationInst *AI = dyn_cast<AllocationInst>(&I)) {
1003 printType(AI->getType()->getElementType());
1004 if (AI->isArrayAllocation()) {
1006 writeOperand(AI->getArraySize(), true);
1008 } else if (isa<CastInst>(I)) {
1009 if (Operand) writeOperand(Operand, true); // Work with broken code
1011 printType(I.getType());
1012 } else if (isa<VAArgInst>(I)) {
1013 if (Operand) writeOperand(Operand, true); // Work with broken code
1015 printType(I.getType());
1016 } else if (const VANextInst *VAN = dyn_cast<VANextInst>(&I)) {
1017 if (Operand) writeOperand(Operand, true); // Work with broken code
1019 printType(VAN->getArgType());
1020 } else if (Operand) { // Print the normal way...
1022 // PrintAllTypes - Instructions who have operands of all the same type
1023 // omit the type from all but the first operand. If the instruction has
1024 // different type operands (for example br), then they are all printed.
1025 bool PrintAllTypes = false;
1026 const Type *TheType = Operand->getType();
1028 // Shift Left & Right print both types even for Ubyte LHS, and select prints
1029 // types even if all operands are bools.
1030 if (isa<ShiftInst>(I) || isa<SelectInst>(I)) {
1031 PrintAllTypes = true;
1033 for (unsigned i = 1, E = I.getNumOperands(); i != E; ++i) {
1034 Operand = I.getOperand(i);
1035 if (Operand->getType() != TheType) {
1036 PrintAllTypes = true; // We have differing types! Print them all!
1042 if (!PrintAllTypes) {
1047 for (unsigned i = 0, E = I.getNumOperands(); i != E; ++i) {
1049 writeOperand(I.getOperand(i), PrintAllTypes);
1053 printInfoComment(I);
1058 //===----------------------------------------------------------------------===//
1059 // External Interface declarations
1060 //===----------------------------------------------------------------------===//
1062 void Module::print(std::ostream &o, AssemblyAnnotationWriter *AAW) const {
1063 SlotMachine SlotTable(this);
1064 AssemblyWriter W(o, SlotTable, this, AAW);
1068 void GlobalVariable::print(std::ostream &o) const {
1069 SlotMachine SlotTable(getParent());
1070 AssemblyWriter W(o, SlotTable, getParent(), 0);
1074 void Function::print(std::ostream &o, AssemblyAnnotationWriter *AAW) const {
1075 SlotMachine SlotTable(getParent());
1076 AssemblyWriter W(o, SlotTable, getParent(), AAW);
1081 void BasicBlock::print(std::ostream &o, AssemblyAnnotationWriter *AAW) const {
1082 SlotMachine SlotTable(getParent());
1083 AssemblyWriter W(o, SlotTable,
1084 getParent() ? getParent()->getParent() : 0, AAW);
1088 void Instruction::print(std::ostream &o, AssemblyAnnotationWriter *AAW) const {
1089 const Function *F = getParent() ? getParent()->getParent() : 0;
1090 SlotMachine SlotTable(F);
1091 AssemblyWriter W(o, SlotTable, F ? F->getParent() : 0, AAW);
1096 void Constant::print(std::ostream &o) const {
1097 if (this == 0) { o << "<null> constant value\n"; return; }
1099 // Handle CPR's special, because they have context information...
1100 if (const ConstantPointerRef *CPR = dyn_cast<ConstantPointerRef>(this)) {
1101 CPR->getValue()->print(o); // Print as a global value, with context info.
1105 o << ' ' << getType()->getDescription() << ' ';
1107 std::map<const Type *, std::string> TypeTable;
1108 WriteConstantInt(o, this, false, TypeTable, 0);
1111 void Type::print(std::ostream &o) const {
1115 o << getDescription();
1118 void Argument::print(std::ostream &o) const {
1119 o << getType() << ' ' << getName();
1122 // Value::dump - allow easy printing of Values from the debugger.
1123 // Located here because so much of the needed functionality is here.
1124 void Value::dump() const { print(std::cerr); }
1126 // Type::dump - allow easy printing of Values from the debugger.
1127 // Located here because so much of the needed functionality is here.
1128 void Type::dump() const { print(std::cerr); }
1130 //===----------------------------------------------------------------------===//
1131 // CachedWriter Class Implementation
1132 //===----------------------------------------------------------------------===//
1134 void CachedWriter::setModule(const Module *M) {
1135 delete SC; delete AW;
1137 SC = new SlotMachine(M );
1138 AW = new AssemblyWriter(Out, *SC, M, 0);
1144 CachedWriter::~CachedWriter() {
1149 CachedWriter &CachedWriter::operator<<(const Value *V) {
1150 assert(AW && SC && "CachedWriter does not have a current module!");
1151 switch (V->getValueType()) {
1152 case Value::ConstantVal:
1153 case Value::ArgumentVal: AW->writeOperand(V, true, true); break;
1154 case Value::TypeVal: AW->write(cast<Type>(V)); break;
1155 case Value::InstructionVal: AW->write(cast<Instruction>(V)); break;
1156 case Value::BasicBlockVal: AW->write(cast<BasicBlock>(V)); break;
1157 case Value::FunctionVal: AW->write(cast<Function>(V)); break;
1158 case Value::GlobalVariableVal: AW->write(cast<GlobalVariable>(V)); break;
1159 default: Out << "<unknown value type: " << V->getValueType() << '>'; break;
1164 CachedWriter& CachedWriter::operator<<(const Type *X) {
1165 if (SymbolicTypes) {
1166 const Module *M = AW->getModule();
1167 if (M) WriteTypeSymbolic(Out, X, M);
1170 return *this << (const Value*)X;
1173 //===----------------------------------------------------------------------===//
1174 //===-- SlotMachine Implementation
1175 //===----------------------------------------------------------------------===//
1178 #define SC_DEBUG(X) std::cerr << X
1183 // Module level constructor. Causes the contents of the Module (sans functions)
1184 // to be added to the slot table.
1185 SlotMachine::SlotMachine(const Module *M)
1186 : TheModule(M) ///< Saved for lazy initialization.
1193 // Function level constructor. Causes the contents of the Module and the one
1194 // function provided to be added to the slot table.
1195 SlotMachine::SlotMachine(const Function *F )
1196 : TheModule( F ? F->getParent() : 0 ) ///< Saved for lazy initialization
1197 , TheFunction(F) ///< Saved for lazy initialization
1203 inline void SlotMachine::initialize(void) {
1206 TheModule = 0; ///< Prevent re-processing next time we're called.
1208 if ( TheFunction ) {
1213 // Iterate through all the global variables, functions, and global
1214 // variable initializers and create slots for them.
1215 void SlotMachine::processModule() {
1216 SC_DEBUG("begin processModule!\n");
1218 // Add all of the global variables to the value table...
1219 for (Module::const_giterator I = TheModule->gbegin(), E = TheModule->gend();
1223 // Add all the functions to the table
1224 for (Module::const_iterator I = TheModule->begin(), E = TheModule->end();
1228 SC_DEBUG("end processModule!\n");
1232 // Process the arguments, basic blocks, and instructions of a function.
1233 void SlotMachine::processFunction() {
1234 SC_DEBUG("begin processFunction!\n");
1236 // Add all the function arguments
1237 for(Function::const_aiterator AI = TheFunction->abegin(),
1238 AE = TheFunction->aend(); AI != AE; ++AI)
1241 SC_DEBUG("Inserting Instructions:\n");
1243 // Add all of the basic blocks and instructions
1244 for (Function::const_iterator BB = TheFunction->begin(),
1245 E = TheFunction->end(); BB != E; ++BB) {
1247 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I!=E; ++I) {
1252 SC_DEBUG("end processFunction!\n");
1255 // Clean up after incorporating a function. This is the only way
1256 // to get out of the function incorporation state that affects the
1257 // getSlot/createSlot lock. Function incorporation state is indicated
1258 // by TheFunction != 0.
1259 void SlotMachine::purgeFunction() {
1260 SC_DEBUG("begin purgeFunction!\n");
1261 fMap.clear(); // Simply discard the function level map
1263 SC_DEBUG("end purgeFunction!\n");
1266 /// Get the slot number for a value. This function will assert if you
1267 /// ask for a Value that hasn't previously been inserted with createSlot.
1268 /// Types are forbidden because Type does not inherit from Value (any more).
1269 unsigned SlotMachine::getSlot(const Value *V) {
1270 assert( V && "Can't get slot for null Value" );
1271 assert( !isa<Type>(V) && "Can't get slot for a type" );
1272 assert(!isa<Constant>(V) || isa<GlobalValue>(V) &&
1273 "Can't insert a non-GlobalValue Constant into SlotMachine");
1275 // Check for uninitialized state and do lazy initialization
1278 // Do not number CPR's at all. They are an abomination
1279 if ( const ConstantPointerRef* CPR = dyn_cast<ConstantPointerRef>(V) )
1280 V = CPR->getValue() ;
1282 // Get the type of the value
1283 const Type* VTy = V->getType();
1285 // Find the type plane in the module map
1286 TypedPlanes::const_iterator MI = mMap.find(VTy);
1288 if ( TheFunction ) {
1289 // Lookup the type in the function map too
1290 TypedPlanes::const_iterator FI = fMap.find(VTy);
1291 // If there is a corresponding type plane in the function map
1292 if ( FI != fMap.end() ) {
1293 // Lookup the Value in the function map
1294 ValueMap::const_iterator FVI = FI->second.map.find(V);
1295 // If the value doesn't exist in the function map
1296 if ( FVI == FI->second.map.end() ) {
1297 // Look up the value in the module map
1298 ValueMap::const_iterator MVI = MI->second.map.find(V);
1299 // If we didn't find it, it wasn't inserted
1300 assert( MVI != MI->second.map.end() && "Value not found");
1301 // We found it only at the module level
1304 // else the value exists in the function map
1306 // Return the slot number as the module's contribution to
1307 // the type plane plus the index in the function's contribution
1308 // to the type plane.
1309 return MI->second.next_slot + FVI->second;
1312 // else there is not a corresponding type plane in the function map
1314 assert( MI != mMap.end() && "No such type plane!" );
1315 // Look up the value in the module's map
1316 ValueMap::const_iterator MVI = MI->second.map.find(V);
1317 // If we didn't find it, it wasn't inserted.
1318 assert( MVI != MI->second.map.end() && "Value not found");
1319 // We found it only in the module level and function level
1320 // didn't even have a type plane.
1325 // N.B. Can only get here if !TheFunction
1327 // Make sure the type plane exists
1328 assert( MI != mMap.end() && "No such type plane!" );
1329 // Lookup the value in the module's map
1330 ValueMap::const_iterator MVI = MI->second.map.find(V);
1331 // Make sure we found it.
1332 assert( MVI != MI->second.map.end() && "Value not found" );
1338 // Create a new slot, or return the existing slot if it is already
1339 // inserted. Note that the logic here parallels getSlot but instead
1340 // of asserting when the Value* isn't found, it inserts the value.
1341 unsigned SlotMachine::createSlot(const Value *V) {
1342 assert( V && "Can't insert a null Value to SlotMachine");
1343 assert( !isa<Type>(V) && "Can't insert a Type into SlotMachine");
1344 assert(!isa<Constant>(V) || isa<GlobalValue>(V) &&
1345 "Can't insert a non-GlobalValue Constant into SlotMachine");
1347 const Type* VTy = V->getType();
1349 // Just ignore void typed things
1350 if (VTy == Type::VoidTy) return 0; // FIXME: Wrong return value!
1352 // Look up the type plane for the Value's type from the module map
1353 TypedPlanes::const_iterator MI = mMap.find(VTy);
1355 if ( TheFunction ) {
1356 // Get the type plane for the Value's type from the function map
1357 TypedPlanes::const_iterator FI = fMap.find(VTy);
1358 // If there is a corresponding type plane in the function map
1359 if ( FI != fMap.end() ) {
1360 // Lookup the Value in the function map
1361 ValueMap::const_iterator FVI = FI->second.map.find(V);
1362 // If the value doesn't exist in the function map
1363 if ( FVI == FI->second.map.end() ) {
1364 // If there is no corresponding type plane in the module map
1365 if ( MI == mMap.end() )
1366 return insertValue(V);
1367 // Look up the value in the module map
1368 ValueMap::const_iterator MVI = MI->second.map.find(V);
1369 // If we didn't find it, it wasn't inserted
1370 if ( MVI == MI->second.map.end() )
1371 return insertValue(V);
1373 // We found it only at the module level
1376 // else the value exists in the function map
1378 if ( MI == mMap.end() )
1381 // Return the slot number as the module's contribution to
1382 // the type plane plus the index in the function's contribution
1383 // to the type plane.
1384 return MI->second.next_slot + FVI->second;
1387 // else there is not a corresponding type plane in the function map
1389 // If the type plane doesn't exists at the module level
1390 if ( MI == mMap.end() ) {
1391 return insertValue(V);
1392 // else type plane exists at the module level, examine it
1394 // Look up the value in the module's map
1395 ValueMap::const_iterator MVI = MI->second.map.find(V);
1396 // If we didn't find it there either
1397 if ( MVI == MI->second.map.end() )
1398 // Return the slot number as the module's contribution to
1399 // the type plane plus the index of the function map insertion.
1400 return MI->second.next_slot + insertValue(V);
1407 // N.B. Can only get here if !TheFunction
1409 // If the module map's type plane is not for the Value's type
1410 if ( MI != mMap.end() ) {
1411 // Lookup the value in the module's map
1412 ValueMap::const_iterator MVI = MI->second.map.find(V);
1413 if ( MVI != MI->second.map.end() )
1417 return insertValue(V);
1421 // Low level insert function. Minimal checking is done. This
1422 // function is just for the convenience of createSlot (above).
1423 unsigned SlotMachine::insertValue(const Value *V ) {
1424 assert(V && "Can't insert a null Value into SlotMachine!");
1425 assert(!isa<Type>(V) && "Can't insert a Type into SlotMachine!");
1426 assert(!isa<Constant>(V) || isa<GlobalValue>(V) &&
1427 "Can't insert a non-GlobalValue Constant into SlotMachine");
1429 // If this value does not contribute to a plane (is void)
1430 // or if the value already has a name then ignore it.
1431 if (V->getType() == Type::VoidTy || V->hasName() ) {
1432 SC_DEBUG("ignored value " << *V << "\n");
1433 return 0; // FIXME: Wrong return value
1436 const Type *VTy = V->getType();
1437 unsigned DestSlot = 0;
1439 if ( TheFunction ) {
1440 TypedPlanes::iterator I = fMap.find( VTy );
1441 if ( I == fMap.end() )
1442 I = fMap.insert(std::make_pair(VTy,Plane())).first;
1443 DestSlot = I->second.map[V] = I->second.next_slot++;
1445 TypedPlanes::iterator I = mMap.find( VTy );
1446 if ( I == mMap.end() )
1447 I = mMap.insert(std::make_pair(VTy,Plane())).first;
1448 DestSlot = I->second.map[V] = I->second.next_slot++;
1451 SC_DEBUG(" Inserting value [" << VTy << "] = " << V << " slot=" <<
1453 // G = Global, C = Constant, T = Type, F = Function, o = other
1454 SC_DEBUG((isa<GlobalVariable>(V) ? 'G' : (isa<Constant>(V) ? 'C' :
1455 (isa<Function>(V) ? 'F' : 'o'))));