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 std::string calcTypeName(const Type *Ty,
228 std::vector<const Type *> &TypeStack,
229 std::map<const Type *, std::string> &TypeNames){
230 if (Ty->isPrimitiveType() && !isa<OpaqueType>(Ty))
231 return Ty->getDescription(); // Base case
233 // Check to see if the type is named.
234 std::map<const Type *, std::string>::iterator I = TypeNames.find(Ty);
235 if (I != TypeNames.end()) return I->second;
237 if (isa<OpaqueType>(Ty))
240 // Check to see if the Type is already on the stack...
241 unsigned Slot = 0, CurSize = TypeStack.size();
242 while (Slot < CurSize && TypeStack[Slot] != Ty) ++Slot; // Scan for type
244 // This is another base case for the recursion. In this case, we know
245 // that we have looped back to a type that we have previously visited.
246 // Generate the appropriate upreference to handle this.
248 return "\\" + utostr(CurSize-Slot); // Here's the upreference
250 TypeStack.push_back(Ty); // Recursive case: Add us to the stack..
253 switch (Ty->getPrimitiveID()) {
254 case Type::FunctionTyID: {
255 const FunctionType *FTy = cast<FunctionType>(Ty);
256 Result = calcTypeName(FTy->getReturnType(), TypeStack, TypeNames) + " (";
257 for (FunctionType::param_iterator I = FTy->param_begin(),
258 E = FTy->param_end(); I != E; ++I) {
259 if (I != FTy->param_begin())
261 Result += calcTypeName(*I, TypeStack, TypeNames);
263 if (FTy->isVarArg()) {
264 if (FTy->getNumParams()) Result += ", ";
270 case Type::StructTyID: {
271 const StructType *STy = cast<StructType>(Ty);
273 for (StructType::element_iterator I = STy->element_begin(),
274 E = STy->element_end(); I != E; ++I) {
275 if (I != STy->element_begin())
277 Result += calcTypeName(*I, TypeStack, TypeNames);
282 case Type::PointerTyID:
283 Result = calcTypeName(cast<PointerType>(Ty)->getElementType(),
284 TypeStack, TypeNames) + "*";
286 case Type::ArrayTyID: {
287 const ArrayType *ATy = cast<ArrayType>(Ty);
288 Result = "[" + utostr(ATy->getNumElements()) + " x ";
289 Result += calcTypeName(ATy->getElementType(), TypeStack, TypeNames) + "]";
292 case Type::OpaqueTyID:
296 Result = "<unrecognized-type>";
299 TypeStack.pop_back(); // Remove self from stack...
304 /// printTypeInt - The internal guts of printing out a type that has a
305 /// potentially named portion.
307 static std::ostream &printTypeInt(std::ostream &Out, const Type *Ty,
308 std::map<const Type *, std::string> &TypeNames) {
309 // Primitive types always print out their description, regardless of whether
310 // they have been named or not.
312 if (Ty->isPrimitiveType() && !isa<OpaqueType>(Ty))
313 return Out << Ty->getDescription();
315 // Check to see if the type is named.
316 std::map<const Type *, std::string>::iterator I = TypeNames.find(Ty);
317 if (I != TypeNames.end()) return Out << I->second;
319 // Otherwise we have a type that has not been named but is a derived type.
320 // Carefully recurse the type hierarchy to print out any contained symbolic
323 std::vector<const Type *> TypeStack;
324 std::string TypeName = calcTypeName(Ty, TypeStack, TypeNames);
325 TypeNames.insert(std::make_pair(Ty, TypeName));//Cache type name for later use
326 return Out << TypeName;
330 /// WriteTypeSymbolic - This attempts to write the specified type as a symbolic
331 /// type, iff there is an entry in the modules symbol table for the specified
332 /// type or one of it's component types. This is slower than a simple x << Type
334 std::ostream &llvm::WriteTypeSymbolic(std::ostream &Out, const Type *Ty,
338 // If they want us to print out a type, attempt to make it symbolic if there
339 // is a symbol table in the module...
341 std::map<const Type *, std::string> TypeNames;
342 fillTypeNameTable(M, TypeNames);
344 return printTypeInt(Out, Ty, TypeNames);
346 return Out << Ty->getDescription();
350 static void WriteConstantInt(std::ostream &Out, const Constant *CV,
352 std::map<const Type *, std::string> &TypeTable,
353 SlotMachine *Machine) {
354 if (const ConstantBool *CB = dyn_cast<ConstantBool>(CV)) {
355 Out << (CB == ConstantBool::True ? "true" : "false");
356 } else if (const ConstantSInt *CI = dyn_cast<ConstantSInt>(CV)) {
357 Out << CI->getValue();
358 } else if (const ConstantUInt *CI = dyn_cast<ConstantUInt>(CV)) {
359 Out << CI->getValue();
360 } else if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CV)) {
361 // We would like to output the FP constant value in exponential notation,
362 // but we cannot do this if doing so will lose precision. Check here to
363 // make sure that we only output it in exponential format if we can parse
364 // the value back and get the same value.
366 std::string StrVal = ftostr(CFP->getValue());
368 // Check to make sure that the stringized number is not some string like
369 // "Inf" or NaN, that atof will accept, but the lexer will not. Check that
370 // the string matches the "[-+]?[0-9]" regex.
372 if ((StrVal[0] >= '0' && StrVal[0] <= '9') ||
373 ((StrVal[0] == '-' || StrVal[0] == '+') &&
374 (StrVal[1] >= '0' && StrVal[1] <= '9')))
375 // Reparse stringized version!
376 if (atof(StrVal.c_str()) == CFP->getValue()) {
377 Out << StrVal; return;
380 // Otherwise we could not reparse it to exactly the same value, so we must
381 // output the string in hexadecimal format!
383 // Behave nicely in the face of C TBAA rules... see:
384 // http://www.nullstone.com/htmls/category/aliastyp.htm
386 double Val = CFP->getValue();
387 char *Ptr = (char*)&Val;
388 assert(sizeof(double) == sizeof(uint64_t) && sizeof(double) == 8 &&
389 "assuming that double is 64 bits!");
390 Out << "0x" << utohexstr(*(uint64_t*)Ptr);
392 } else if (isa<ConstantAggregateZero>(CV)) {
393 Out << "zeroinitializer";
394 } else if (const ConstantArray *CA = dyn_cast<ConstantArray>(CV)) {
395 // As a special case, print the array as a string if it is an array of
396 // ubytes or an array of sbytes with positive values.
398 const Type *ETy = CA->getType()->getElementType();
399 bool isString = (ETy == Type::SByteTy || ETy == Type::UByteTy);
401 if (ETy == Type::SByteTy)
402 for (unsigned i = 0; i < CA->getNumOperands(); ++i)
403 if (cast<ConstantSInt>(CA->getOperand(i))->getValue() < 0) {
410 for (unsigned i = 0; i < CA->getNumOperands(); ++i) {
411 unsigned char C = cast<ConstantInt>(CA->getOperand(i))->getRawValue();
413 if (isprint(C) && C != '"' && C != '\\') {
417 << (char) ((C/16 < 10) ? ( C/16 +'0') : ( C/16 -10+'A'))
418 << (char)(((C&15) < 10) ? ((C&15)+'0') : ((C&15)-10+'A'));
423 } else { // Cannot output in string format...
425 if (CA->getNumOperands()) {
427 printTypeInt(Out, ETy, TypeTable);
428 WriteAsOperandInternal(Out, CA->getOperand(0),
429 PrintName, TypeTable, Machine);
430 for (unsigned i = 1, e = CA->getNumOperands(); i != e; ++i) {
432 printTypeInt(Out, ETy, TypeTable);
433 WriteAsOperandInternal(Out, CA->getOperand(i), PrintName,
439 } else if (const ConstantStruct *CS = dyn_cast<ConstantStruct>(CV)) {
441 if (CS->getNumOperands()) {
443 printTypeInt(Out, CS->getOperand(0)->getType(), TypeTable);
445 WriteAsOperandInternal(Out, CS->getOperand(0),
446 PrintName, TypeTable, Machine);
448 for (unsigned i = 1; i < CS->getNumOperands(); i++) {
450 printTypeInt(Out, CS->getOperand(i)->getType(), TypeTable);
452 WriteAsOperandInternal(Out, CS->getOperand(i),
453 PrintName, TypeTable, Machine);
458 } else if (isa<ConstantPointerNull>(CV)) {
461 } else if (const ConstantPointerRef *PR = dyn_cast<ConstantPointerRef>(CV)) {
462 WriteAsOperandInternal(Out, PR->getValue(), true, TypeTable, Machine);
464 } else if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV)) {
465 Out << CE->getOpcodeName() << " (";
467 for (User::const_op_iterator OI=CE->op_begin(); OI != CE->op_end(); ++OI) {
468 printTypeInt(Out, (*OI)->getType(), TypeTable);
469 WriteAsOperandInternal(Out, *OI, PrintName, TypeTable, Machine);
470 if (OI+1 != CE->op_end())
474 if (CE->getOpcode() == Instruction::Cast) {
476 printTypeInt(Out, CE->getType(), TypeTable);
481 Out << "<placeholder or erroneous Constant>";
486 /// WriteAsOperand - Write the name of the specified value out to the specified
487 /// ostream. This can be useful when you just want to print int %reg126, not
488 /// the whole instruction that generated it.
490 static void WriteAsOperandInternal(std::ostream &Out, const Value *V,
492 std::map<const Type*, std::string> &TypeTable,
493 SlotMachine *Machine) {
495 if (PrintName && V->hasName()) {
496 Out << getLLVMName(V->getName());
498 if (const Constant *CV = dyn_cast<Constant>(V)) {
499 WriteConstantInt(Out, CV, PrintName, TypeTable, Machine);
503 Slot = Machine->getSlot(V);
505 if (const Type *Ty = dyn_cast<Type>(V)) {
506 Out << Ty->getDescription();
510 Machine = createSlotMachine(V);
511 if (Machine == 0) { Out << "BAD VALUE TYPE!"; return; }
513 Slot = Machine->getSlot(V);
522 /// WriteAsOperand - Write the name of the specified value out to the specified
523 /// ostream. This can be useful when you just want to print int %reg126, not
524 /// the whole instruction that generated it.
526 std::ostream &llvm::WriteAsOperand(std::ostream &Out, const Value *V,
527 bool PrintType, bool PrintName,
528 const Module *Context) {
529 std::map<const Type *, std::string> TypeNames;
530 if (Context == 0) Context = getModuleFromVal(V);
533 fillTypeNameTable(Context, TypeNames);
536 printTypeInt(Out, V->getType(), TypeNames);
538 if (const Type *Ty = dyn_cast<Type> (V))
539 printTypeInt(Out, Ty, TypeNames);
541 WriteAsOperandInternal(Out, V, PrintName, TypeNames, 0);
547 class AssemblyWriter {
549 SlotMachine &Machine;
550 const Module *TheModule;
551 std::map<const Type *, std::string> TypeNames;
552 AssemblyAnnotationWriter *AnnotationWriter;
554 inline AssemblyWriter(std::ostream &o, SlotMachine &Mac, const Module *M,
555 AssemblyAnnotationWriter *AAW)
556 : Out(&o), Machine(Mac), TheModule(M), AnnotationWriter(AAW) {
558 // If the module has a symbol table, take all global types and stuff their
559 // names into the TypeNames map.
561 fillTypeNameTable(M, TypeNames);
564 inline void write(const Module *M) { printModule(M); }
565 inline void write(const GlobalVariable *G) { printGlobal(G); }
566 inline void write(const Function *F) { printFunction(F); }
567 inline void write(const BasicBlock *BB) { printBasicBlock(BB); }
568 inline void write(const Instruction *I) { printInstruction(*I); }
569 inline void write(const Constant *CPV) { printConstant(CPV); }
570 inline void write(const Type *Ty) { printType(Ty); }
572 void writeOperand(const Value *Op, bool PrintType, bool PrintName = true);
574 const Module* getModule() { return TheModule; }
575 void setStream(std::ostream &os) { Out = &os; }
578 void printModule(const Module *M);
579 void printSymbolTable(const SymbolTable &ST);
580 void printConstant(const Constant *CPV);
581 void printGlobal(const GlobalVariable *GV);
582 void printFunction(const Function *F);
583 void printArgument(const Argument *FA);
584 void printBasicBlock(const BasicBlock *BB);
585 void printInstruction(const Instruction &I);
587 // printType - Go to extreme measures to attempt to print out a short,
588 // symbolic version of a type name.
590 std::ostream &printType(const Type *Ty) {
591 return printTypeInt(*Out, Ty, TypeNames);
594 // printTypeAtLeastOneLevel - Print out one level of the possibly complex type
595 // without considering any symbolic types that we may have equal to it.
597 std::ostream &printTypeAtLeastOneLevel(const Type *Ty);
599 // printInfoComment - Print a little comment after the instruction indicating
600 // which slot it occupies.
601 void printInfoComment(const Value &V);
603 } // end of anonymous namespace
605 /// printTypeAtLeastOneLevel - Print out one level of the possibly complex type
606 /// without considering any symbolic types that we may have equal to it.
608 std::ostream &AssemblyWriter::printTypeAtLeastOneLevel(const Type *Ty) {
609 if (const FunctionType *FTy = dyn_cast<FunctionType>(Ty)) {
610 printType(FTy->getReturnType()) << " (";
611 for (FunctionType::param_iterator I = FTy->param_begin(),
612 E = FTy->param_end(); I != E; ++I) {
613 if (I != FTy->param_begin())
617 if (FTy->isVarArg()) {
618 if (FTy->getNumParams()) *Out << ", ";
622 } else if (const StructType *STy = dyn_cast<StructType>(Ty)) {
624 for (StructType::element_iterator I = STy->element_begin(),
625 E = STy->element_end(); I != E; ++I) {
626 if (I != STy->element_begin())
631 } else if (const PointerType *PTy = dyn_cast<PointerType>(Ty)) {
632 printType(PTy->getElementType()) << "*";
633 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
634 *Out << "[" << ATy->getNumElements() << " x ";
635 printType(ATy->getElementType()) << "]";
636 } else if (const OpaqueType *OTy = dyn_cast<OpaqueType>(Ty)) {
639 if (!Ty->isPrimitiveType())
640 *Out << "<unknown derived type>";
647 void AssemblyWriter::writeOperand(const Value *Operand, bool PrintType,
649 if (PrintType) { *Out << " "; printType(Operand->getType()); }
650 WriteAsOperandInternal(*Out, Operand, PrintName, TypeNames, &Machine);
654 void AssemblyWriter::printModule(const Module *M) {
655 switch (M->getEndianness()) {
656 case Module::LittleEndian: *Out << "target endian = little\n"; break;
657 case Module::BigEndian: *Out << "target endian = big\n"; break;
658 case Module::AnyEndianness: break;
660 switch (M->getPointerSize()) {
661 case Module::Pointer32: *Out << "target pointersize = 32\n"; break;
662 case Module::Pointer64: *Out << "target pointersize = 64\n"; break;
663 case Module::AnyPointerSize: break;
666 // Loop over the symbol table, emitting all named constants...
667 printSymbolTable(M->getSymbolTable());
669 for (Module::const_giterator I = M->gbegin(), E = M->gend(); I != E; ++I)
672 *Out << "\nimplementation ; Functions:\n";
674 // Output all of the functions...
675 for (Module::const_iterator I = M->begin(), E = M->end(); I != E; ++I)
679 void AssemblyWriter::printGlobal(const GlobalVariable *GV) {
680 if (GV->hasName()) *Out << getLLVMName(GV->getName()) << " = ";
682 if (!GV->hasInitializer())
685 switch (GV->getLinkage()) {
686 case GlobalValue::InternalLinkage: *Out << "internal "; break;
687 case GlobalValue::LinkOnceLinkage: *Out << "linkonce "; break;
688 case GlobalValue::WeakLinkage: *Out << "weak "; break;
689 case GlobalValue::AppendingLinkage: *Out << "appending "; break;
690 case GlobalValue::ExternalLinkage: break;
693 *Out << (GV->isConstant() ? "constant " : "global ");
694 printType(GV->getType()->getElementType());
696 if (GV->hasInitializer())
697 writeOperand(GV->getInitializer(), false, false);
699 printInfoComment(*GV);
704 // printSymbolTable - Run through symbol table looking for constants
705 // and types. Emit their declarations.
706 void AssemblyWriter::printSymbolTable(const SymbolTable &ST) {
709 for (SymbolTable::type_const_iterator TI = ST.type_begin();
710 TI != ST.type_end(); ++TI ) {
711 *Out << "\t" << getLLVMName(TI->first) << " = type ";
713 // Make sure we print out at least one level of the type structure, so
714 // that we do not get %FILE = type %FILE
716 printTypeAtLeastOneLevel(TI->second) << "\n";
719 // Print the constants, in type plane order.
720 for (SymbolTable::plane_const_iterator PI = ST.plane_begin();
721 PI != ST.plane_end(); ++PI ) {
722 SymbolTable::value_const_iterator VI = ST.value_begin(PI->first);
723 SymbolTable::value_const_iterator VE = ST.value_end(PI->first);
725 for (; VI != VE; ++VI) {
726 const Value *V = VI->second;
727 if (const Constant *CPV = dyn_cast<Constant>(V)) {
735 /// printConstant - Print out a constant pool entry...
737 void AssemblyWriter::printConstant(const Constant *CPV) {
738 // Don't print out unnamed constants, they will be inlined
739 if (!CPV->hasName()) return;
742 *Out << "\t" << getLLVMName(CPV->getName()) << " =";
744 // Write the value out now...
745 writeOperand(CPV, true, false);
747 printInfoComment(*CPV);
751 /// printFunction - Print all aspects of a function.
753 void AssemblyWriter::printFunction(const Function *F) {
754 // Print out the return type and name...
757 if (AnnotationWriter) AnnotationWriter->emitFunctionAnnot(F, *Out);
762 switch (F->getLinkage()) {
763 case GlobalValue::InternalLinkage: *Out << "internal "; break;
764 case GlobalValue::LinkOnceLinkage: *Out << "linkonce "; break;
765 case GlobalValue::WeakLinkage: *Out << "weak "; break;
766 case GlobalValue::AppendingLinkage: *Out << "appending "; break;
767 case GlobalValue::ExternalLinkage: break;
770 printType(F->getReturnType()) << " ";
771 if (!F->getName().empty())
772 *Out << getLLVMName(F->getName());
776 Machine.incorporateFunction(F);
778 // Loop over the arguments, printing them...
779 const FunctionType *FT = F->getFunctionType();
781 for(Function::const_aiterator I = F->abegin(), E = F->aend(); I != E; ++I)
784 // Finish printing arguments...
785 if (FT->isVarArg()) {
786 if (FT->getNumParams()) *Out << ", ";
787 *Out << "..."; // Output varargs portion of signature!
791 if (F->isExternal()) {
796 // Output all of its basic blocks... for the function
797 for (Function::const_iterator I = F->begin(), E = F->end(); I != E; ++I)
803 Machine.purgeFunction();
806 /// printArgument - This member is called for every argument that is passed into
807 /// the function. Simply print it out
809 void AssemblyWriter::printArgument(const Argument *Arg) {
810 // Insert commas as we go... the first arg doesn't get a comma
811 if (Arg != &Arg->getParent()->afront()) *Out << ", ";
814 printType(Arg->getType());
816 // Output name, if available...
818 *Out << " " << getLLVMName(Arg->getName());
821 /// printBasicBlock - This member is called for each basic block in a method.
823 void AssemblyWriter::printBasicBlock(const BasicBlock *BB) {
824 if (BB->hasName()) { // Print out the label if it exists...
825 *Out << "\n" << BB->getName() << ":";
826 } else if (!BB->use_empty()) { // Don't print block # of no uses...
827 *Out << "\n; <label>:" << Machine.getSlot(BB);
830 if (BB->getParent() == 0)
831 *Out << "\t\t; Error: Block without parent!";
833 if (BB != &BB->getParent()->front()) { // Not the entry block?
834 // Output predecessors for the block...
836 pred_const_iterator PI = pred_begin(BB), PE = pred_end(BB);
839 *Out << " No predecessors!";
842 writeOperand(*PI, false, true);
843 for (++PI; PI != PE; ++PI) {
845 writeOperand(*PI, false, true);
853 if (AnnotationWriter) AnnotationWriter->emitBasicBlockStartAnnot(BB, *Out);
855 // Output all of the instructions in the basic block...
856 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I != E; ++I)
857 printInstruction(*I);
859 if (AnnotationWriter) AnnotationWriter->emitBasicBlockEndAnnot(BB, *Out);
863 /// printInfoComment - Print a little comment after the instruction indicating
864 /// which slot it occupies.
866 void AssemblyWriter::printInfoComment(const Value &V) {
867 if (V.getType() != Type::VoidTy) {
869 printType(V.getType()) << ">";
872 *Out << ":" << Machine.getSlot(&V); // Print out the def slot taken.
874 *Out << " [#uses=" << V.use_size() << "]"; // Output # uses
878 /// printInstruction - This member is called for each Instruction in a method.
880 void AssemblyWriter::printInstruction(const Instruction &I) {
881 if (AnnotationWriter) AnnotationWriter->emitInstructionAnnot(&I, *Out);
885 // Print out name if it exists...
887 *Out << getLLVMName(I.getName()) << " = ";
889 // If this is a volatile load or store, print out the volatile marker
890 if ((isa<LoadInst>(I) && cast<LoadInst>(I).isVolatile()) ||
891 (isa<StoreInst>(I) && cast<StoreInst>(I).isVolatile()))
894 // Print out the opcode...
895 *Out << I.getOpcodeName();
897 // Print out the type of the operands...
898 const Value *Operand = I.getNumOperands() ? I.getOperand(0) : 0;
900 // Special case conditional branches to swizzle the condition out to the front
901 if (isa<BranchInst>(I) && I.getNumOperands() > 1) {
902 writeOperand(I.getOperand(2), true);
904 writeOperand(Operand, true);
906 writeOperand(I.getOperand(1), true);
908 } else if (isa<SwitchInst>(I)) {
909 // Special case switch statement to get formatting nice and correct...
910 writeOperand(Operand , true); *Out << ",";
911 writeOperand(I.getOperand(1), true); *Out << " [";
913 for (unsigned op = 2, Eop = I.getNumOperands(); op < Eop; op += 2) {
915 writeOperand(I.getOperand(op ), true); *Out << ",";
916 writeOperand(I.getOperand(op+1), true);
919 } else if (isa<PHINode>(I)) {
921 printType(I.getType());
924 for (unsigned op = 0, Eop = I.getNumOperands(); op < Eop; op += 2) {
925 if (op) *Out << ", ";
927 writeOperand(I.getOperand(op ), false); *Out << ",";
928 writeOperand(I.getOperand(op+1), false); *Out << " ]";
930 } else if (isa<ReturnInst>(I) && !Operand) {
932 } else if (isa<CallInst>(I)) {
933 const PointerType *PTy = cast<PointerType>(Operand->getType());
934 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
935 const Type *RetTy = FTy->getReturnType();
937 // If possible, print out the short form of the call instruction. We can
938 // only do this if the first argument is a pointer to a nonvararg function,
939 // and if the return type is not a pointer to a function.
941 if (!FTy->isVarArg() &&
942 (!isa<PointerType>(RetTy) ||
943 !isa<FunctionType>(cast<PointerType>(RetTy)->getElementType()))) {
944 *Out << " "; printType(RetTy);
945 writeOperand(Operand, false);
947 writeOperand(Operand, true);
950 if (I.getNumOperands() > 1) writeOperand(I.getOperand(1), true);
951 for (unsigned op = 2, Eop = I.getNumOperands(); op < Eop; ++op) {
953 writeOperand(I.getOperand(op), true);
957 } else if (const InvokeInst *II = dyn_cast<InvokeInst>(&I)) {
958 const PointerType *PTy = cast<PointerType>(Operand->getType());
959 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
960 const Type *RetTy = FTy->getReturnType();
962 // If possible, print out the short form of the invoke instruction. We can
963 // only do this if the first argument is a pointer to a nonvararg function,
964 // and if the return type is not a pointer to a function.
966 if (!FTy->isVarArg() &&
967 (!isa<PointerType>(RetTy) ||
968 !isa<FunctionType>(cast<PointerType>(RetTy)->getElementType()))) {
969 *Out << " "; printType(RetTy);
970 writeOperand(Operand, false);
972 writeOperand(Operand, true);
976 if (I.getNumOperands() > 3) writeOperand(I.getOperand(3), true);
977 for (unsigned op = 4, Eop = I.getNumOperands(); op < Eop; ++op) {
979 writeOperand(I.getOperand(op), true);
982 *Out << " )\n\t\t\tto";
983 writeOperand(II->getNormalDest(), true);
985 writeOperand(II->getUnwindDest(), true);
987 } else if (const AllocationInst *AI = dyn_cast<AllocationInst>(&I)) {
989 printType(AI->getType()->getElementType());
990 if (AI->isArrayAllocation()) {
992 writeOperand(AI->getArraySize(), true);
994 } else if (isa<CastInst>(I)) {
995 if (Operand) writeOperand(Operand, true); // Work with broken code
997 printType(I.getType());
998 } else if (isa<VAArgInst>(I)) {
999 if (Operand) writeOperand(Operand, true); // Work with broken code
1001 printType(I.getType());
1002 } else if (const VANextInst *VAN = dyn_cast<VANextInst>(&I)) {
1003 if (Operand) writeOperand(Operand, true); // Work with broken code
1005 printType(VAN->getArgType());
1006 } else if (Operand) { // Print the normal way...
1008 // PrintAllTypes - Instructions who have operands of all the same type
1009 // omit the type from all but the first operand. If the instruction has
1010 // different type operands (for example br), then they are all printed.
1011 bool PrintAllTypes = false;
1012 const Type *TheType = Operand->getType();
1014 // Shift Left & Right print both types even for Ubyte LHS, and select prints
1015 // types even if all operands are bools.
1016 if (isa<ShiftInst>(I) || isa<SelectInst>(I)) {
1017 PrintAllTypes = true;
1019 for (unsigned i = 1, E = I.getNumOperands(); i != E; ++i) {
1020 Operand = I.getOperand(i);
1021 if (Operand->getType() != TheType) {
1022 PrintAllTypes = true; // We have differing types! Print them all!
1028 if (!PrintAllTypes) {
1033 for (unsigned i = 0, E = I.getNumOperands(); i != E; ++i) {
1035 writeOperand(I.getOperand(i), PrintAllTypes);
1039 printInfoComment(I);
1044 //===----------------------------------------------------------------------===//
1045 // External Interface declarations
1046 //===----------------------------------------------------------------------===//
1048 void Module::print(std::ostream &o, AssemblyAnnotationWriter *AAW) const {
1049 SlotMachine SlotTable(this);
1050 AssemblyWriter W(o, SlotTable, this, AAW);
1054 void GlobalVariable::print(std::ostream &o) const {
1055 SlotMachine SlotTable(getParent());
1056 AssemblyWriter W(o, SlotTable, getParent(), 0);
1060 void Function::print(std::ostream &o, AssemblyAnnotationWriter *AAW) const {
1061 SlotMachine SlotTable(getParent());
1062 AssemblyWriter W(o, SlotTable, getParent(), AAW);
1067 void BasicBlock::print(std::ostream &o, AssemblyAnnotationWriter *AAW) const {
1068 SlotMachine SlotTable(getParent());
1069 AssemblyWriter W(o, SlotTable,
1070 getParent() ? getParent()->getParent() : 0, AAW);
1074 void Instruction::print(std::ostream &o, AssemblyAnnotationWriter *AAW) const {
1075 const Function *F = getParent() ? getParent()->getParent() : 0;
1076 SlotMachine SlotTable(F);
1077 AssemblyWriter W(o, SlotTable, F ? F->getParent() : 0, AAW);
1082 void Constant::print(std::ostream &o) const {
1083 if (this == 0) { o << "<null> constant value\n"; return; }
1085 // Handle CPR's special, because they have context information...
1086 if (const ConstantPointerRef *CPR = dyn_cast<ConstantPointerRef>(this)) {
1087 CPR->getValue()->print(o); // Print as a global value, with context info.
1091 o << " " << getType()->getDescription() << " ";
1093 std::map<const Type *, std::string> TypeTable;
1094 WriteConstantInt(o, this, false, TypeTable, 0);
1097 void Type::print(std::ostream &o) const {
1101 o << getDescription();
1104 void Argument::print(std::ostream &o) const {
1105 o << getType() << " " << getName();
1108 // Value::dump - allow easy printing of Values from the debugger.
1109 // Located here because so much of the needed functionality is here.
1110 void Value::dump() const { print(std::cerr); }
1112 // Type::dump - allow easy printing of Values from the debugger.
1113 // Located here because so much of the needed functionality is here.
1114 void Type::dump() const { print(std::cerr); }
1116 //===----------------------------------------------------------------------===//
1117 // CachedWriter Class Implementation
1118 //===----------------------------------------------------------------------===//
1120 void CachedWriter::setModule(const Module *M) {
1121 delete SC; delete AW;
1123 SC = new SlotMachine(M );
1124 AW = new AssemblyWriter(*Out, *SC, M, 0);
1130 CachedWriter::~CachedWriter() {
1135 CachedWriter &CachedWriter::operator<<(const Value *V) {
1136 assert(AW && SC && "CachedWriter does not have a current module!");
1137 switch (V->getValueType()) {
1138 case Value::ConstantVal:
1139 case Value::ArgumentVal: AW->writeOperand(V, true, true); break;
1140 case Value::TypeVal: AW->write(cast<Type>(V)); break;
1141 case Value::InstructionVal: AW->write(cast<Instruction>(V)); break;
1142 case Value::BasicBlockVal: AW->write(cast<BasicBlock>(V)); break;
1143 case Value::FunctionVal: AW->write(cast<Function>(V)); break;
1144 case Value::GlobalVariableVal: AW->write(cast<GlobalVariable>(V)); break;
1145 default: *Out << "<unknown value type: " << V->getValueType() << ">"; break;
1150 CachedWriter& CachedWriter::operator<<(const Type *X) {
1151 if (SymbolicTypes) {
1152 const Module *M = AW->getModule();
1153 if (M) WriteTypeSymbolic(*Out, X, M);
1156 return *this << (const Value*)X;
1159 void CachedWriter::setStream(std::ostream &os) {
1161 if (AW) AW->setStream(os);
1164 //===----------------------------------------------------------------------===//
1165 //===-- SlotMachine Implementation
1166 //===----------------------------------------------------------------------===//
1169 #define SC_DEBUG(X) std::cerr << X
1174 // Module level constructor. Causes the contents of the Module (sans functions)
1175 // to be added to the slot table.
1176 SlotMachine::SlotMachine(const Module *M)
1177 : TheModule(M) ///< Saved for lazy initialization.
1184 // Function level constructor. Causes the contents of the Module and the one
1185 // function provided to be added to the slot table.
1186 SlotMachine::SlotMachine(const Function *F )
1187 : TheModule( F ? F->getParent() : 0 ) ///< Saved for lazy initialization
1188 , TheFunction(F) ///< Saved for lazy initialization
1194 inline void SlotMachine::initialize(void) {
1197 TheModule = 0; ///< Prevent re-processing next time we're called.
1199 if ( TheFunction ) {
1204 // Iterate through all the global variables, functions, and global
1205 // variable initializers and create slots for them.
1206 void SlotMachine::processModule() {
1207 SC_DEBUG("begin processModule!\n");
1209 // Add all of the global variables to the value table...
1210 for (Module::const_giterator I = TheModule->gbegin(), E = TheModule->gend();
1214 // Add all the functions to the table
1215 for (Module::const_iterator I = TheModule->begin(), E = TheModule->end();
1219 SC_DEBUG("end processModule!\n");
1223 // Process the arguments, basic blocks, and instructions of a function.
1224 void SlotMachine::processFunction() {
1225 SC_DEBUG("begin processFunction!\n");
1227 // Add all the function arguments
1228 for(Function::const_aiterator AI = TheFunction->abegin(),
1229 AE = TheFunction->aend(); AI != AE; ++AI)
1232 SC_DEBUG("Inserting Instructions:\n");
1234 // Add all of the basic blocks and instructions
1235 for (Function::const_iterator BB = TheFunction->begin(),
1236 E = TheFunction->end(); BB != E; ++BB) {
1238 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I!=E; ++I) {
1243 SC_DEBUG("end processFunction!\n");
1246 // Clean up after incorporating a function. This is the only way
1247 // to get out of the function incorporation state that affects the
1248 // getSlot/createSlot lock. Function incorporation state is indicated
1249 // by TheFunction != 0.
1250 void SlotMachine::purgeFunction() {
1251 SC_DEBUG("begin purgeFunction!\n");
1252 fMap.clear(); // Simply discard the function level map
1254 SC_DEBUG("end purgeFunction!\n");
1257 /// Get the slot number for a value. This function will assert if you
1258 /// ask for a Value that hasn't previously been inserted with createSlot.
1259 /// Types are forbidden because Type does not inherit from Value (any more).
1260 unsigned SlotMachine::getSlot(const Value *V) {
1261 assert( V && "Can't get slot for null Value" );
1262 assert( !isa<Type>(V) && "Can't get slot for a type" );
1263 assert(!isa<Constant>(V) || isa<GlobalValue>(V) &&
1264 "Can't insert a non-GlobalValue Constant into SlotMachine");
1266 // Check for uninitialized state and do lazy initialization
1269 // Do not number CPR's at all. They are an abomination
1270 if ( const ConstantPointerRef* CPR = dyn_cast<ConstantPointerRef>(V) )
1271 V = CPR->getValue() ;
1273 // Get the type of the value
1274 const Type* VTy = V->getType();
1276 // Find the type plane in the module map
1277 TypedPlanes::const_iterator MI = mMap.find(VTy);
1279 if ( TheFunction ) {
1280 // Lookup the type in the function map too
1281 TypedPlanes::const_iterator FI = fMap.find(VTy);
1282 // If there is a corresponding type plane in the function map
1283 if ( FI != fMap.end() ) {
1284 // Lookup the Value in the function map
1285 ValueMap::const_iterator FVI = FI->second.map.find(V);
1286 // If the value doesn't exist in the function map
1287 if ( FVI == FI->second.map.end() ) {
1288 // Look up the value in the module map
1289 ValueMap::const_iterator MVI = MI->second.map.find(V);
1290 // If we didn't find it, it wasn't inserted
1291 assert( MVI != MI->second.map.end() && "Value not found");
1292 // We found it only at the module level
1295 // else the value exists in the function map
1297 // Return the slot number as the module's contribution to
1298 // the type plane plus the index in the function's contribution
1299 // to the type plane.
1300 return MI->second.next_slot + FVI->second;
1303 // else there is not a corresponding type plane in the function map
1305 assert( MI != mMap.end() && "No such type plane!" );
1306 // Look up the value in the module's map
1307 ValueMap::const_iterator MVI = MI->second.map.find(V);
1308 // If we didn't find it, it wasn't inserted.
1309 assert( MVI != MI->second.map.end() && "Value not found");
1310 // We found it only in the module level and function level
1311 // didn't even have a type plane.
1316 // N.B. Can only get here if !TheFunction
1318 // Make sure the type plane exists
1319 assert( MI != mMap.end() && "No such type plane!" );
1320 // Lookup the value in the module's map
1321 ValueMap::const_iterator MVI = MI->second.map.find(V);
1322 // Make sure we found it.
1323 assert( MVI != MI->second.map.end() && "Value not found" );
1329 // Create a new slot, or return the existing slot if it is already
1330 // inserted. Note that the logic here parallels getSlot but instead
1331 // of asserting when the Value* isn't found, it inserts the value.
1332 unsigned SlotMachine::createSlot(const Value *V) {
1333 assert( V && "Can't insert a null Value to SlotMachine");
1334 assert( !isa<Type>(V) && "Can't insert a Type into SlotMachine");
1335 assert(!isa<Constant>(V) || isa<GlobalValue>(V) &&
1336 "Can't insert a non-GlobalValue Constant into SlotMachine");
1338 const Type* VTy = V->getType();
1340 // Just ignore void typed things
1341 if (VTy == Type::VoidTy) return 0; // FIXME: Wrong return value!
1343 // Look up the type plane for the Value's type from the module map
1344 TypedPlanes::const_iterator MI = mMap.find(VTy);
1346 if ( TheFunction ) {
1347 // Get the type plane for the Value's type from the function map
1348 TypedPlanes::const_iterator FI = fMap.find(VTy);
1349 // If there is a corresponding type plane in the function map
1350 if ( FI != fMap.end() ) {
1351 // Lookup the Value in the function map
1352 ValueMap::const_iterator FVI = FI->second.map.find(V);
1353 // If the value doesn't exist in the function map
1354 if ( FVI == FI->second.map.end() ) {
1355 // If there is no corresponding type plane in the module map
1356 if ( MI == mMap.end() )
1357 return insertValue(V);
1358 // Look up the value in the module map
1359 ValueMap::const_iterator MVI = MI->second.map.find(V);
1360 // If we didn't find it, it wasn't inserted
1361 if ( MVI == MI->second.map.end() )
1362 return insertValue(V);
1364 // We found it only at the module level
1367 // else the value exists in the function map
1369 if ( MI == mMap.end() )
1372 // Return the slot number as the module's contribution to
1373 // the type plane plus the index in the function's contribution
1374 // to the type plane.
1375 return MI->second.next_slot + FVI->second;
1378 // else there is not a corresponding type plane in the function map
1380 // If the type plane doesn't exists at the module level
1381 if ( MI == mMap.end() ) {
1382 return insertValue(V);
1383 // else type plane exists at the module level, examine it
1385 // Look up the value in the module's map
1386 ValueMap::const_iterator MVI = MI->second.map.find(V);
1387 // If we didn't find it there either
1388 if ( MVI == MI->second.map.end() )
1389 // Return the slot number as the module's contribution to
1390 // the type plane plus the index of the function map insertion.
1391 return MI->second.next_slot + insertValue(V);
1398 // N.B. Can only get here if !TheFunction
1400 // If the module map's type plane is not for the Value's type
1401 if ( MI != mMap.end() ) {
1402 // Lookup the value in the module's map
1403 ValueMap::const_iterator MVI = MI->second.map.find(V);
1404 if ( MVI != MI->second.map.end() )
1408 return insertValue(V);
1412 // Low level insert function. Minimal checking is done. This
1413 // function is just for the convenience of createSlot (above).
1414 unsigned SlotMachine::insertValue(const Value *V ) {
1415 assert(V && "Can't insert a null Value into SlotMachine!");
1416 assert(!isa<Type>(V) && "Can't insert a Type into SlotMachine!");
1417 assert(!isa<Constant>(V) || isa<GlobalValue>(V) &&
1418 "Can't insert a non-GlobalValue Constant into SlotMachine");
1420 // If this value does not contribute to a plane (is void)
1421 // or if the value already has a name then ignore it.
1422 if (V->getType() == Type::VoidTy || V->hasName() ) {
1423 SC_DEBUG("ignored value " << *V << "\n");
1424 return 0; // FIXME: Wrong return value
1427 const Type *VTy = V->getType();
1428 unsigned DestSlot = 0;
1430 if ( TheFunction ) {
1431 TypedPlanes::iterator I = fMap.find( VTy );
1432 if ( I == fMap.end() )
1433 I = fMap.insert(std::make_pair(VTy,Plane())).first;
1434 DestSlot = I->second.map[V] = I->second.next_slot++;
1436 TypedPlanes::iterator I = mMap.find( VTy );
1437 if ( I == mMap.end() )
1438 I = mMap.insert(std::make_pair(VTy,Plane())).first;
1439 DestSlot = I->second.map[V] = I->second.next_slot++;
1442 SC_DEBUG(" Inserting value [" << VTy << "] = " << V << " slot=" <<
1444 // G = Global, C = Constant, T = Type, F = Function, o = other
1445 SC_DEBUG((isa<GlobalVariable>(V) ? "G" : (isa<Constant>(V) ? "C" :
1446 (isa<Function>(V) ? "F" : "o"))));