1 //===-- AsmWriter.cpp - Printing LLVM as an assembly file -----------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This library implements the functionality defined in llvm/Assembly/Writer.h
12 // Note that these routines must be extremely tolerant of various errors in the
13 // LLVM code, because it can be used for debugging transformations.
15 //===----------------------------------------------------------------------===//
17 #include "llvm/Assembly/Writer.h"
18 #include "llvm/Assembly/PrintModulePass.h"
19 #include "llvm/Assembly/AsmAnnotationWriter.h"
20 #include "llvm/CallingConv.h"
21 #include "llvm/Constants.h"
22 #include "llvm/DerivedTypes.h"
23 #include "llvm/InlineAsm.h"
24 #include "llvm/Instruction.h"
25 #include "llvm/Instructions.h"
26 #include "llvm/Module.h"
27 #include "llvm/ValueSymbolTable.h"
28 #include "llvm/TypeSymbolTable.h"
29 #include "llvm/ADT/StringExtras.h"
30 #include "llvm/ADT/STLExtras.h"
31 #include "llvm/Support/CFG.h"
32 #include "llvm/Support/MathExtras.h"
33 #include "llvm/Support/Streams.h"
40 // Make virtual table appear in this compilation unit.
41 AssemblyAnnotationWriter::~AssemblyAnnotationWriter() {}
43 /// This class provides computation of slot numbers for LLVM Assembly writing.
44 /// @brief LLVM Assembly Writing Slot Computation.
51 /// @brief A mapping of Values to slot numbers
52 typedef std::map<const Value*,unsigned> ValueMap;
55 /// @name Constructors
58 /// @brief Construct from a module
59 explicit SlotMachine(const Module *M);
61 /// @brief Construct from a function, starting out in incorp state.
62 explicit SlotMachine(const Function *F);
68 /// Return the slot number of the specified value in it's type
69 /// plane. If something is not in the SlotMachine, return -1.
70 int getLocalSlot(const Value *V);
71 int getGlobalSlot(const GlobalValue *V);
77 /// If you'd like to deal with a function instead of just a module, use
78 /// this method to get its data into the SlotMachine.
79 void incorporateFunction(const Function *F) {
81 FunctionProcessed = false;
84 /// After calling incorporateFunction, use this method to remove the
85 /// most recently incorporated function from the SlotMachine. This
86 /// will reset the state of the machine back to just the module contents.
90 /// @name Implementation Details
93 /// This function does the actual initialization.
94 inline void initialize();
96 /// CreateModuleSlot - Insert the specified GlobalValue* into the slot table.
97 void CreateModuleSlot(const GlobalValue *V);
99 /// CreateFunctionSlot - Insert the specified Value* into the slot table.
100 void CreateFunctionSlot(const Value *V);
102 /// Add all of the module level global variables (and their initializers)
103 /// and function declarations, but not the contents of those functions.
104 void processModule();
106 /// Add all of the functions arguments, basic blocks, and instructions
107 void processFunction();
109 SlotMachine(const SlotMachine &); // DO NOT IMPLEMENT
110 void operator=(const SlotMachine &); // DO NOT IMPLEMENT
117 /// @brief The module for which we are holding slot numbers
118 const Module* TheModule;
120 /// @brief The function for which we are holding slot numbers
121 const Function* TheFunction;
122 bool FunctionProcessed;
124 /// @brief The TypePlanes map for the module level data
128 /// @brief The TypePlanes map for the function level data
136 } // end namespace llvm
138 char PrintModulePass::ID = 0;
139 static RegisterPass<PrintModulePass>
140 X("printm", "Print module to stderr");
141 char PrintFunctionPass::ID = 0;
142 static RegisterPass<PrintFunctionPass>
143 Y("print","Print function to stderr");
145 static void WriteAsOperandInternal(std::ostream &Out, const Value *V,
146 std::map<const Type *, std::string> &TypeTable,
147 SlotMachine *Machine);
149 static const Module *getModuleFromVal(const Value *V) {
150 if (const Argument *MA = dyn_cast<Argument>(V))
151 return MA->getParent() ? MA->getParent()->getParent() : 0;
152 else if (const BasicBlock *BB = dyn_cast<BasicBlock>(V))
153 return BB->getParent() ? BB->getParent()->getParent() : 0;
154 else if (const Instruction *I = dyn_cast<Instruction>(V)) {
155 const Function *M = I->getParent() ? I->getParent()->getParent() : 0;
156 return M ? M->getParent() : 0;
157 } else if (const GlobalValue *GV = dyn_cast<GlobalValue>(V))
158 return GV->getParent();
162 static SlotMachine *createSlotMachine(const Value *V) {
163 if (const Argument *FA = dyn_cast<Argument>(V)) {
164 return new SlotMachine(FA->getParent());
165 } else if (const Instruction *I = dyn_cast<Instruction>(V)) {
166 return new SlotMachine(I->getParent()->getParent());
167 } else if (const BasicBlock *BB = dyn_cast<BasicBlock>(V)) {
168 return new SlotMachine(BB->getParent());
169 } else if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(V)){
170 return new SlotMachine(GV->getParent());
171 } else if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(V)){
172 return new SlotMachine(GA->getParent());
173 } else if (const Function *Func = dyn_cast<Function>(V)) {
174 return new SlotMachine(Func);
179 /// NameNeedsQuotes - Return true if the specified llvm name should be wrapped
181 static std::string QuoteNameIfNeeded(const std::string &Name) {
183 bool needsQuotes = Name[0] >= '0' && Name[0] <= '9';
184 // Scan the name to see if it needs quotes and to replace funky chars with
185 // their octal equivalent.
186 for (unsigned i = 0, e = Name.size(); i != e; ++i) {
188 assert(C != '"' && "Illegal character in LLVM value name!");
189 if (isalnum(C) || C == '-' || C == '.' || C == '_')
191 else if (C == '\\') {
194 } else if (isprint(C)) {
200 char hex1 = (C >> 4) & 0x0F;
202 result += hex1 + '0';
204 result += hex1 - 10 + 'A';
205 char hex2 = C & 0x0F;
207 result += hex2 + '0';
209 result += hex2 - 10 + 'A';
213 result.insert(0,"\"");
225 /// getLLVMName - Turn the specified string into an 'LLVM name', which is either
226 /// prefixed with % (if the string only contains simple characters) or is
227 /// surrounded with ""'s (if it has special chars in it).
228 static std::string getLLVMName(const std::string &Name, PrefixType Prefix) {
229 assert(!Name.empty() && "Cannot get empty name!");
231 default: assert(0 && "Bad prefix!");
232 case GlobalPrefix: return '@' + QuoteNameIfNeeded(Name);
233 case LabelPrefix: return QuoteNameIfNeeded(Name);
234 case LocalPrefix: return '%' + QuoteNameIfNeeded(Name);
239 /// fillTypeNameTable - If the module has a symbol table, take all global types
240 /// and stuff their names into the TypeNames map.
242 static void fillTypeNameTable(const Module *M,
243 std::map<const Type *, std::string> &TypeNames) {
245 const TypeSymbolTable &ST = M->getTypeSymbolTable();
246 TypeSymbolTable::const_iterator TI = ST.begin();
247 for (; TI != ST.end(); ++TI) {
248 // As a heuristic, don't insert pointer to primitive types, because
249 // they are used too often to have a single useful name.
251 const Type *Ty = cast<Type>(TI->second);
252 if (!isa<PointerType>(Ty) ||
253 !cast<PointerType>(Ty)->getElementType()->isPrimitiveType() ||
254 !cast<PointerType>(Ty)->getElementType()->isInteger() ||
255 isa<OpaqueType>(cast<PointerType>(Ty)->getElementType()))
256 TypeNames.insert(std::make_pair(Ty, getLLVMName(TI->first, LocalPrefix)));
262 static void calcTypeName(const Type *Ty,
263 std::vector<const Type *> &TypeStack,
264 std::map<const Type *, std::string> &TypeNames,
265 std::string & Result){
266 if (Ty->isInteger() || (Ty->isPrimitiveType() && !isa<OpaqueType>(Ty))) {
267 Result += Ty->getDescription(); // Base case
271 // Check to see if the type is named.
272 std::map<const Type *, std::string>::iterator I = TypeNames.find(Ty);
273 if (I != TypeNames.end()) {
278 if (isa<OpaqueType>(Ty)) {
283 // Check to see if the Type is already on the stack...
284 unsigned Slot = 0, CurSize = TypeStack.size();
285 while (Slot < CurSize && TypeStack[Slot] != Ty) ++Slot; // Scan for type
287 // This is another base case for the recursion. In this case, we know
288 // that we have looped back to a type that we have previously visited.
289 // Generate the appropriate upreference to handle this.
290 if (Slot < CurSize) {
291 Result += "\\" + utostr(CurSize-Slot); // Here's the upreference
295 TypeStack.push_back(Ty); // Recursive case: Add us to the stack..
297 switch (Ty->getTypeID()) {
298 case Type::IntegerTyID: {
299 unsigned BitWidth = cast<IntegerType>(Ty)->getBitWidth();
300 Result += "i" + utostr(BitWidth);
303 case Type::FunctionTyID: {
304 const FunctionType *FTy = cast<FunctionType>(Ty);
305 calcTypeName(FTy->getReturnType(), TypeStack, TypeNames, Result);
307 for (FunctionType::param_iterator I = FTy->param_begin(),
308 E = FTy->param_end(); I != E; ++I) {
309 if (I != FTy->param_begin())
311 calcTypeName(*I, TypeStack, TypeNames, Result);
313 if (FTy->isVarArg()) {
314 if (FTy->getNumParams()) Result += ", ";
320 case Type::StructTyID: {
321 const StructType *STy = cast<StructType>(Ty);
325 for (StructType::element_iterator I = STy->element_begin(),
326 E = STy->element_end(); I != E; ++I) {
327 if (I != STy->element_begin())
329 calcTypeName(*I, TypeStack, TypeNames, Result);
336 case Type::PointerTyID: {
337 const PointerType *PTy = cast<PointerType>(Ty);
338 calcTypeName(PTy->getElementType(),
339 TypeStack, TypeNames, Result);
340 if (unsigned AddressSpace = PTy->getAddressSpace())
341 Result += " addrspace(" + utostr(AddressSpace) + ")";
345 case Type::ArrayTyID: {
346 const ArrayType *ATy = cast<ArrayType>(Ty);
347 Result += "[" + utostr(ATy->getNumElements()) + " x ";
348 calcTypeName(ATy->getElementType(), TypeStack, TypeNames, Result);
352 case Type::VectorTyID: {
353 const VectorType *PTy = cast<VectorType>(Ty);
354 Result += "<" + utostr(PTy->getNumElements()) + " x ";
355 calcTypeName(PTy->getElementType(), TypeStack, TypeNames, Result);
359 case Type::OpaqueTyID:
363 Result += "<unrecognized-type>";
367 TypeStack.pop_back(); // Remove self from stack...
371 /// printTypeInt - The internal guts of printing out a type that has a
372 /// potentially named portion.
374 static std::ostream &printTypeInt(std::ostream &Out, const Type *Ty,
375 std::map<const Type *, std::string> &TypeNames) {
376 // Primitive types always print out their description, regardless of whether
377 // they have been named or not.
379 if (Ty->isInteger() || (Ty->isPrimitiveType() && !isa<OpaqueType>(Ty)))
380 return Out << Ty->getDescription();
382 // Check to see if the type is named.
383 std::map<const Type *, std::string>::iterator I = TypeNames.find(Ty);
384 if (I != TypeNames.end()) return Out << I->second;
386 // Otherwise we have a type that has not been named but is a derived type.
387 // Carefully recurse the type hierarchy to print out any contained symbolic
390 std::vector<const Type *> TypeStack;
391 std::string TypeName;
392 calcTypeName(Ty, TypeStack, TypeNames, TypeName);
393 TypeNames.insert(std::make_pair(Ty, TypeName));//Cache type name for later use
394 return (Out << TypeName);
398 /// WriteTypeSymbolic - This attempts to write the specified type as a symbolic
399 /// type, iff there is an entry in the modules symbol table for the specified
400 /// type or one of it's component types. This is slower than a simple x << Type
402 std::ostream &llvm::WriteTypeSymbolic(std::ostream &Out, const Type *Ty,
406 // If they want us to print out a type, but there is no context, we can't
407 // print it symbolically.
409 return Out << Ty->getDescription();
411 std::map<const Type *, std::string> TypeNames;
412 fillTypeNameTable(M, TypeNames);
413 return printTypeInt(Out, Ty, TypeNames);
416 // PrintEscapedString - Print each character of the specified string, escaping
417 // it if it is not printable or if it is an escape char.
418 static void PrintEscapedString(const std::string &Str, std::ostream &Out) {
419 for (unsigned i = 0, e = Str.size(); i != e; ++i) {
420 unsigned char C = Str[i];
421 if (isprint(C) && C != '"' && C != '\\') {
425 << (char) ((C/16 < 10) ? ( C/16 +'0') : ( C/16 -10+'A'))
426 << (char)(((C&15) < 10) ? ((C&15)+'0') : ((C&15)-10+'A'));
431 static const char *getPredicateText(unsigned predicate) {
432 const char * pred = "unknown";
434 case FCmpInst::FCMP_FALSE: pred = "false"; break;
435 case FCmpInst::FCMP_OEQ: pred = "oeq"; break;
436 case FCmpInst::FCMP_OGT: pred = "ogt"; break;
437 case FCmpInst::FCMP_OGE: pred = "oge"; break;
438 case FCmpInst::FCMP_OLT: pred = "olt"; break;
439 case FCmpInst::FCMP_OLE: pred = "ole"; break;
440 case FCmpInst::FCMP_ONE: pred = "one"; break;
441 case FCmpInst::FCMP_ORD: pred = "ord"; break;
442 case FCmpInst::FCMP_UNO: pred = "uno"; break;
443 case FCmpInst::FCMP_UEQ: pred = "ueq"; break;
444 case FCmpInst::FCMP_UGT: pred = "ugt"; break;
445 case FCmpInst::FCMP_UGE: pred = "uge"; break;
446 case FCmpInst::FCMP_ULT: pred = "ult"; break;
447 case FCmpInst::FCMP_ULE: pred = "ule"; break;
448 case FCmpInst::FCMP_UNE: pred = "une"; break;
449 case FCmpInst::FCMP_TRUE: pred = "true"; break;
450 case ICmpInst::ICMP_EQ: pred = "eq"; break;
451 case ICmpInst::ICMP_NE: pred = "ne"; break;
452 case ICmpInst::ICMP_SGT: pred = "sgt"; break;
453 case ICmpInst::ICMP_SGE: pred = "sge"; break;
454 case ICmpInst::ICMP_SLT: pred = "slt"; break;
455 case ICmpInst::ICMP_SLE: pred = "sle"; break;
456 case ICmpInst::ICMP_UGT: pred = "ugt"; break;
457 case ICmpInst::ICMP_UGE: pred = "uge"; break;
458 case ICmpInst::ICMP_ULT: pred = "ult"; break;
459 case ICmpInst::ICMP_ULE: pred = "ule"; break;
464 /// @brief Internal constant writer.
465 static void WriteConstantInt(std::ostream &Out, const Constant *CV,
466 std::map<const Type *, std::string> &TypeTable,
467 SlotMachine *Machine) {
468 const int IndentSize = 4;
469 static std::string Indent = "\n";
470 if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV)) {
471 if (CI->getType() == Type::Int1Ty)
472 Out << (CI->getZExtValue() ? "true" : "false");
474 Out << CI->getValue().toStringSigned(10);
475 } else if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CV)) {
476 if (&CFP->getValueAPF().getSemantics() == &APFloat::IEEEdouble ||
477 &CFP->getValueAPF().getSemantics() == &APFloat::IEEEsingle) {
478 // We would like to output the FP constant value in exponential notation,
479 // but we cannot do this if doing so will lose precision. Check here to
480 // make sure that we only output it in exponential format if we can parse
481 // the value back and get the same value.
483 bool isDouble = &CFP->getValueAPF().getSemantics()==&APFloat::IEEEdouble;
484 double Val = (isDouble) ? CFP->getValueAPF().convertToDouble() :
485 CFP->getValueAPF().convertToFloat();
486 std::string StrVal = ftostr(CFP->getValueAPF());
488 // Check to make sure that the stringized number is not some string like
489 // "Inf" or NaN, that atof will accept, but the lexer will not. Check
490 // that the string matches the "[-+]?[0-9]" regex.
492 if ((StrVal[0] >= '0' && StrVal[0] <= '9') ||
493 ((StrVal[0] == '-' || StrVal[0] == '+') &&
494 (StrVal[1] >= '0' && StrVal[1] <= '9'))) {
495 // Reparse stringized version!
496 if (atof(StrVal.c_str()) == Val) {
501 // Otherwise we could not reparse it to exactly the same value, so we must
502 // output the string in hexadecimal format!
503 assert(sizeof(double) == sizeof(uint64_t) &&
504 "assuming that double is 64 bits!");
505 Out << "0x" << utohexstr(DoubleToBits(Val));
507 // Some form of long double. These appear as a magic letter identifying
508 // the type, then a fixed number of hex digits.
510 if (&CFP->getValueAPF().getSemantics() == &APFloat::x87DoubleExtended)
512 else if (&CFP->getValueAPF().getSemantics() == &APFloat::IEEEquad)
514 else if (&CFP->getValueAPF().getSemantics() == &APFloat::PPCDoubleDouble)
517 assert(0 && "Unsupported floating point type");
518 // api needed to prevent premature destruction
519 APInt api = CFP->getValueAPF().convertToAPInt();
520 const uint64_t* p = api.getRawData();
523 int width = api.getBitWidth();
524 for (int j=0; j<width; j+=4, shiftcount-=4) {
525 unsigned int nibble = (word>>shiftcount) & 15;
527 Out << (unsigned char)(nibble + '0');
529 Out << (unsigned char)(nibble - 10 + 'A');
530 if (shiftcount == 0 && j+4 < width) {
534 shiftcount = width-j-4;
538 } else if (isa<ConstantAggregateZero>(CV)) {
539 Out << "zeroinitializer";
540 } else if (const ConstantArray *CA = dyn_cast<ConstantArray>(CV)) {
541 // As a special case, print the array as a string if it is an array of
542 // i8 with ConstantInt values.
544 const Type *ETy = CA->getType()->getElementType();
545 if (CA->isString()) {
547 PrintEscapedString(CA->getAsString(), Out);
550 } else { // Cannot output in string format...
552 if (CA->getNumOperands()) {
554 printTypeInt(Out, ETy, TypeTable);
555 WriteAsOperandInternal(Out, CA->getOperand(0),
557 for (unsigned i = 1, e = CA->getNumOperands(); i != e; ++i) {
559 printTypeInt(Out, ETy, TypeTable);
560 WriteAsOperandInternal(Out, CA->getOperand(i), TypeTable, Machine);
565 } else if (const ConstantStruct *CS = dyn_cast<ConstantStruct>(CV)) {
566 if (CS->getType()->isPacked())
569 unsigned N = CS->getNumOperands();
572 Indent += std::string(IndentSize, ' ');
577 printTypeInt(Out, CS->getOperand(0)->getType(), TypeTable);
579 WriteAsOperandInternal(Out, CS->getOperand(0), TypeTable, Machine);
581 for (unsigned i = 1; i < N; i++) {
583 if (N > 2) Out << Indent;
584 printTypeInt(Out, CS->getOperand(i)->getType(), TypeTable);
586 WriteAsOperandInternal(Out, CS->getOperand(i), TypeTable, Machine);
588 if (N > 2) Indent.resize(Indent.size() - IndentSize);
592 if (CS->getType()->isPacked())
594 } else if (const ConstantVector *CP = dyn_cast<ConstantVector>(CV)) {
595 const Type *ETy = CP->getType()->getElementType();
596 assert(CP->getNumOperands() > 0 &&
597 "Number of operands for a PackedConst must be > 0");
600 printTypeInt(Out, ETy, TypeTable);
601 WriteAsOperandInternal(Out, CP->getOperand(0), TypeTable, Machine);
602 for (unsigned i = 1, e = CP->getNumOperands(); i != e; ++i) {
604 printTypeInt(Out, ETy, TypeTable);
605 WriteAsOperandInternal(Out, CP->getOperand(i), TypeTable, Machine);
608 } else if (isa<ConstantPointerNull>(CV)) {
611 } else if (isa<UndefValue>(CV)) {
614 } else if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV)) {
615 Out << CE->getOpcodeName();
617 Out << " " << getPredicateText(CE->getPredicate());
620 for (User::const_op_iterator OI=CE->op_begin(); OI != CE->op_end(); ++OI) {
621 printTypeInt(Out, (*OI)->getType(), TypeTable);
622 WriteAsOperandInternal(Out, *OI, TypeTable, Machine);
623 if (OI+1 != CE->op_end())
629 printTypeInt(Out, CE->getType(), TypeTable);
635 Out << "<placeholder or erroneous Constant>";
640 /// WriteAsOperand - Write the name of the specified value out to the specified
641 /// ostream. This can be useful when you just want to print int %reg126, not
642 /// the whole instruction that generated it.
644 static void WriteAsOperandInternal(std::ostream &Out, const Value *V,
645 std::map<const Type*, std::string> &TypeTable,
646 SlotMachine *Machine) {
649 Out << getLLVMName(V->getName(),
650 isa<GlobalValue>(V) ? GlobalPrefix : LocalPrefix);
652 const Constant *CV = dyn_cast<Constant>(V);
653 if (CV && !isa<GlobalValue>(CV)) {
654 WriteConstantInt(Out, CV, TypeTable, Machine);
655 } else if (const InlineAsm *IA = dyn_cast<InlineAsm>(V)) {
657 if (IA->hasSideEffects())
658 Out << "sideeffect ";
660 PrintEscapedString(IA->getAsmString(), Out);
662 PrintEscapedString(IA->getConstraintString(), Out);
668 if (const GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
669 Slot = Machine->getGlobalSlot(GV);
672 Slot = Machine->getLocalSlot(V);
675 Machine = createSlotMachine(V);
677 if (const GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
678 Slot = Machine->getGlobalSlot(GV);
681 Slot = Machine->getLocalSlot(V);
689 Out << Prefix << Slot;
696 /// WriteAsOperand - Write the name of the specified value out to the specified
697 /// ostream. This can be useful when you just want to print int %reg126, not
698 /// the whole instruction that generated it.
700 std::ostream &llvm::WriteAsOperand(std::ostream &Out, const Value *V,
701 bool PrintType, const Module *Context) {
702 std::map<const Type *, std::string> TypeNames;
703 if (Context == 0) Context = getModuleFromVal(V);
706 fillTypeNameTable(Context, TypeNames);
709 printTypeInt(Out, V->getType(), TypeNames);
711 WriteAsOperandInternal(Out, V, TypeNames, 0);
718 class AssemblyWriter {
720 SlotMachine &Machine;
721 const Module *TheModule;
722 std::map<const Type *, std::string> TypeNames;
723 AssemblyAnnotationWriter *AnnotationWriter;
725 inline AssemblyWriter(std::ostream &o, SlotMachine &Mac, const Module *M,
726 AssemblyAnnotationWriter *AAW)
727 : Out(o), Machine(Mac), TheModule(M), AnnotationWriter(AAW) {
729 // If the module has a symbol table, take all global types and stuff their
730 // names into the TypeNames map.
732 fillTypeNameTable(M, TypeNames);
735 inline void write(const Module *M) { printModule(M); }
736 inline void write(const GlobalVariable *G) { printGlobal(G); }
737 inline void write(const GlobalAlias *G) { printAlias(G); }
738 inline void write(const Function *F) { printFunction(F); }
739 inline void write(const BasicBlock *BB) { printBasicBlock(BB); }
740 inline void write(const Instruction *I) { printInstruction(*I); }
741 inline void write(const Type *Ty) { printType(Ty); }
743 void writeOperand(const Value *Op, bool PrintType);
744 void writeParamOperand(const Value *Operand, ParameterAttributes Attrs);
746 const Module* getModule() { return TheModule; }
749 void printModule(const Module *M);
750 void printTypeSymbolTable(const TypeSymbolTable &ST);
751 void printGlobal(const GlobalVariable *GV);
752 void printAlias(const GlobalAlias *GV);
753 void printFunction(const Function *F);
754 void printArgument(const Argument *FA, ParameterAttributes Attrs);
755 void printBasicBlock(const BasicBlock *BB);
756 void printInstruction(const Instruction &I);
758 // printType - Go to extreme measures to attempt to print out a short,
759 // symbolic version of a type name.
761 std::ostream &printType(const Type *Ty) {
762 return printTypeInt(Out, Ty, TypeNames);
765 // printTypeAtLeastOneLevel - Print out one level of the possibly complex type
766 // without considering any symbolic types that we may have equal to it.
768 std::ostream &printTypeAtLeastOneLevel(const Type *Ty);
770 // printInfoComment - Print a little comment after the instruction indicating
771 // which slot it occupies.
772 void printInfoComment(const Value &V);
774 } // end of llvm namespace
776 /// printTypeAtLeastOneLevel - Print out one level of the possibly complex type
777 /// without considering any symbolic types that we may have equal to it.
779 std::ostream &AssemblyWriter::printTypeAtLeastOneLevel(const Type *Ty) {
780 if (const IntegerType *ITy = dyn_cast<IntegerType>(Ty))
781 Out << "i" << utostr(ITy->getBitWidth());
782 else if (const FunctionType *FTy = dyn_cast<FunctionType>(Ty)) {
783 printType(FTy->getReturnType());
785 for (FunctionType::param_iterator I = FTy->param_begin(),
786 E = FTy->param_end(); I != E; ++I) {
787 if (I != FTy->param_begin())
791 if (FTy->isVarArg()) {
792 if (FTy->getNumParams()) Out << ", ";
796 } else if (const StructType *STy = dyn_cast<StructType>(Ty)) {
800 for (StructType::element_iterator I = STy->element_begin(),
801 E = STy->element_end(); I != E; ++I) {
802 if (I != STy->element_begin())
809 } else if (const PointerType *PTy = dyn_cast<PointerType>(Ty)) {
810 printType(PTy->getElementType());
811 if (unsigned AddressSpace = PTy->getAddressSpace())
812 Out << " addrspace(" << AddressSpace << ")";
814 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
815 Out << '[' << ATy->getNumElements() << " x ";
816 printType(ATy->getElementType()) << ']';
817 } else if (const VectorType *PTy = dyn_cast<VectorType>(Ty)) {
818 Out << '<' << PTy->getNumElements() << " x ";
819 printType(PTy->getElementType()) << '>';
821 else if (isa<OpaqueType>(Ty)) {
824 if (!Ty->isPrimitiveType())
825 Out << "<unknown derived type>";
832 void AssemblyWriter::writeOperand(const Value *Operand, bool PrintType) {
834 Out << "<null operand!>";
836 if (PrintType) { Out << ' '; printType(Operand->getType()); }
837 WriteAsOperandInternal(Out, Operand, TypeNames, &Machine);
841 void AssemblyWriter::writeParamOperand(const Value *Operand,
842 ParameterAttributes Attrs) {
844 Out << "<null operand!>";
848 printType(Operand->getType());
849 // Print parameter attributes list
850 if (Attrs != ParamAttr::None)
851 Out << ' ' << ParamAttr::getAsString(Attrs);
853 WriteAsOperandInternal(Out, Operand, TypeNames, &Machine);
857 void AssemblyWriter::printModule(const Module *M) {
858 if (!M->getModuleIdentifier().empty() &&
859 // Don't print the ID if it will start a new line (which would
860 // require a comment char before it).
861 M->getModuleIdentifier().find('\n') == std::string::npos)
862 Out << "; ModuleID = '" << M->getModuleIdentifier() << "'\n";
864 if (!M->getDataLayout().empty())
865 Out << "target datalayout = \"" << M->getDataLayout() << "\"\n";
866 if (!M->getTargetTriple().empty())
867 Out << "target triple = \"" << M->getTargetTriple() << "\"\n";
869 if (!M->getModuleInlineAsm().empty()) {
870 // Split the string into lines, to make it easier to read the .ll file.
871 std::string Asm = M->getModuleInlineAsm();
873 size_t NewLine = Asm.find_first_of('\n', CurPos);
874 while (NewLine != std::string::npos) {
875 // We found a newline, print the portion of the asm string from the
876 // last newline up to this newline.
877 Out << "module asm \"";
878 PrintEscapedString(std::string(Asm.begin()+CurPos, Asm.begin()+NewLine),
882 NewLine = Asm.find_first_of('\n', CurPos);
884 Out << "module asm \"";
885 PrintEscapedString(std::string(Asm.begin()+CurPos, Asm.end()), Out);
889 // Loop over the dependent libraries and emit them.
890 Module::lib_iterator LI = M->lib_begin();
891 Module::lib_iterator LE = M->lib_end();
893 Out << "deplibs = [ ";
895 Out << '"' << *LI << '"';
903 // Loop over the symbol table, emitting all named constants.
904 printTypeSymbolTable(M->getTypeSymbolTable());
906 for (Module::const_global_iterator I = M->global_begin(), E = M->global_end();
910 // Output all aliases.
911 if (!M->alias_empty()) Out << "\n";
912 for (Module::const_alias_iterator I = M->alias_begin(), E = M->alias_end();
916 // Output all of the functions.
917 for (Module::const_iterator I = M->begin(), E = M->end(); I != E; ++I)
921 void AssemblyWriter::printGlobal(const GlobalVariable *GV) {
922 if (GV->hasName()) Out << getLLVMName(GV->getName(), GlobalPrefix) << " = ";
924 if (!GV->hasInitializer()) {
925 switch (GV->getLinkage()) {
926 case GlobalValue::DLLImportLinkage: Out << "dllimport "; break;
927 case GlobalValue::ExternalWeakLinkage: Out << "extern_weak "; break;
928 default: Out << "external "; break;
931 switch (GV->getLinkage()) {
932 case GlobalValue::InternalLinkage: Out << "internal "; break;
933 case GlobalValue::CommonLinkage: Out << "common "; break;
934 case GlobalValue::LinkOnceLinkage: Out << "linkonce "; break;
935 case GlobalValue::WeakLinkage: Out << "weak "; break;
936 case GlobalValue::AppendingLinkage: Out << "appending "; break;
937 case GlobalValue::DLLImportLinkage: Out << "dllimport "; break;
938 case GlobalValue::DLLExportLinkage: Out << "dllexport "; break;
939 case GlobalValue::ExternalWeakLinkage: Out << "extern_weak "; break;
940 case GlobalValue::ExternalLinkage: break;
941 case GlobalValue::GhostLinkage:
942 cerr << "GhostLinkage not allowed in AsmWriter!\n";
945 switch (GV->getVisibility()) {
946 default: assert(0 && "Invalid visibility style!");
947 case GlobalValue::DefaultVisibility: break;
948 case GlobalValue::HiddenVisibility: Out << "hidden "; break;
949 case GlobalValue::ProtectedVisibility: Out << "protected "; break;
953 if (GV->isThreadLocal()) Out << "thread_local ";
954 Out << (GV->isConstant() ? "constant " : "global ");
955 printType(GV->getType()->getElementType());
957 if (GV->hasInitializer()) {
958 Constant* C = cast<Constant>(GV->getInitializer());
959 assert(C && "GlobalVar initializer isn't constant?");
960 writeOperand(GV->getInitializer(), false);
963 if (unsigned AddressSpace = GV->getType()->getAddressSpace())
964 Out << " addrspace(" << AddressSpace << ") ";
966 if (GV->hasSection())
967 Out << ", section \"" << GV->getSection() << '"';
968 if (GV->getAlignment())
969 Out << ", align " << GV->getAlignment();
971 printInfoComment(*GV);
975 void AssemblyWriter::printAlias(const GlobalAlias *GA) {
976 Out << getLLVMName(GA->getName(), GlobalPrefix) << " = ";
977 switch (GA->getVisibility()) {
978 default: assert(0 && "Invalid visibility style!");
979 case GlobalValue::DefaultVisibility: break;
980 case GlobalValue::HiddenVisibility: Out << "hidden "; break;
981 case GlobalValue::ProtectedVisibility: Out << "protected "; break;
986 switch (GA->getLinkage()) {
987 case GlobalValue::WeakLinkage: Out << "weak "; break;
988 case GlobalValue::InternalLinkage: Out << "internal "; break;
989 case GlobalValue::ExternalLinkage: break;
991 assert(0 && "Invalid alias linkage");
994 const Constant *Aliasee = GA->getAliasee();
996 if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(Aliasee)) {
997 printType(GV->getType());
998 Out << " " << getLLVMName(GV->getName(), GlobalPrefix);
999 } else if (const Function *F = dyn_cast<Function>(Aliasee)) {
1000 printType(F->getFunctionType());
1003 if (!F->getName().empty())
1004 Out << getLLVMName(F->getName(), GlobalPrefix);
1007 } else if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(Aliasee)) {
1008 printType(GA->getType());
1009 Out << " " << getLLVMName(GA->getName(), GlobalPrefix);
1011 const ConstantExpr *CE = 0;
1012 if ((CE = dyn_cast<ConstantExpr>(Aliasee)) &&
1013 (CE->getOpcode() == Instruction::BitCast)) {
1014 writeOperand(CE, false);
1016 assert(0 && "Unsupported aliasee");
1019 printInfoComment(*GA);
1023 void AssemblyWriter::printTypeSymbolTable(const TypeSymbolTable &ST) {
1025 for (TypeSymbolTable::const_iterator TI = ST.begin(), TE = ST.end();
1027 Out << "\t" << getLLVMName(TI->first, LocalPrefix) << " = type ";
1029 // Make sure we print out at least one level of the type structure, so
1030 // that we do not get %FILE = type %FILE
1032 printTypeAtLeastOneLevel(TI->second) << "\n";
1036 /// printFunction - Print all aspects of a function.
1038 void AssemblyWriter::printFunction(const Function *F) {
1039 // Print out the return type and name...
1042 if (AnnotationWriter) AnnotationWriter->emitFunctionAnnot(F, Out);
1044 if (F->isDeclaration())
1049 switch (F->getLinkage()) {
1050 case GlobalValue::InternalLinkage: Out << "internal "; break;
1051 case GlobalValue::LinkOnceLinkage: Out << "linkonce "; break;
1052 case GlobalValue::WeakLinkage: Out << "weak "; break;
1053 case GlobalValue::CommonLinkage: Out << "common "; break;
1054 case GlobalValue::AppendingLinkage: Out << "appending "; break;
1055 case GlobalValue::DLLImportLinkage: Out << "dllimport "; break;
1056 case GlobalValue::DLLExportLinkage: Out << "dllexport "; break;
1057 case GlobalValue::ExternalWeakLinkage: Out << "extern_weak "; break;
1058 case GlobalValue::ExternalLinkage: break;
1059 case GlobalValue::GhostLinkage:
1060 cerr << "GhostLinkage not allowed in AsmWriter!\n";
1063 switch (F->getVisibility()) {
1064 default: assert(0 && "Invalid visibility style!");
1065 case GlobalValue::DefaultVisibility: break;
1066 case GlobalValue::HiddenVisibility: Out << "hidden "; break;
1067 case GlobalValue::ProtectedVisibility: Out << "protected "; break;
1070 // Print the calling convention.
1071 switch (F->getCallingConv()) {
1072 case CallingConv::C: break; // default
1073 case CallingConv::Fast: Out << "fastcc "; break;
1074 case CallingConv::Cold: Out << "coldcc "; break;
1075 case CallingConv::X86_StdCall: Out << "x86_stdcallcc "; break;
1076 case CallingConv::X86_FastCall: Out << "x86_fastcallcc "; break;
1077 default: Out << "cc" << F->getCallingConv() << " "; break;
1080 const FunctionType *FT = F->getFunctionType();
1081 const PAListPtr &Attrs = F->getParamAttrs();
1082 printType(F->getReturnType()) << ' ';
1083 if (!F->getName().empty())
1084 Out << getLLVMName(F->getName(), GlobalPrefix);
1088 Machine.incorporateFunction(F);
1090 // Loop over the arguments, printing them...
1093 if (!F->isDeclaration()) {
1094 // If this isn't a declaration, print the argument names as well.
1095 for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
1097 // Insert commas as we go... the first arg doesn't get a comma
1098 if (I != F->arg_begin()) Out << ", ";
1099 printArgument(I, Attrs.getParamAttrs(Idx));
1103 // Otherwise, print the types from the function type.
1104 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
1105 // Insert commas as we go... the first arg doesn't get a comma
1109 printType(FT->getParamType(i));
1111 ParameterAttributes ArgAttrs = Attrs.getParamAttrs(i+1);
1112 if (ArgAttrs != ParamAttr::None)
1113 Out << ' ' << ParamAttr::getAsString(ArgAttrs);
1117 // Finish printing arguments...
1118 if (FT->isVarArg()) {
1119 if (FT->getNumParams()) Out << ", ";
1120 Out << "..."; // Output varargs portion of signature!
1123 ParameterAttributes RetAttrs = Attrs.getParamAttrs(0);
1124 if (RetAttrs != ParamAttr::None)
1125 Out << ' ' << ParamAttr::getAsString(Attrs.getParamAttrs(0));
1126 if (F->hasSection())
1127 Out << " section \"" << F->getSection() << '"';
1128 if (F->getAlignment())
1129 Out << " align " << F->getAlignment();
1130 if (F->hasCollector())
1131 Out << " gc \"" << F->getCollector() << '"';
1133 if (F->isDeclaration()) {
1138 // Output all of its basic blocks... for the function
1139 for (Function::const_iterator I = F->begin(), E = F->end(); I != E; ++I)
1145 Machine.purgeFunction();
1148 /// printArgument - This member is called for every argument that is passed into
1149 /// the function. Simply print it out
1151 void AssemblyWriter::printArgument(const Argument *Arg,
1152 ParameterAttributes Attrs) {
1154 printType(Arg->getType());
1156 // Output parameter attributes list
1157 if (Attrs != ParamAttr::None)
1158 Out << ' ' << ParamAttr::getAsString(Attrs);
1160 // Output name, if available...
1162 Out << ' ' << getLLVMName(Arg->getName(), LocalPrefix);
1165 /// printBasicBlock - This member is called for each basic block in a method.
1167 void AssemblyWriter::printBasicBlock(const BasicBlock *BB) {
1168 if (BB->hasName()) { // Print out the label if it exists...
1169 Out << "\n" << getLLVMName(BB->getName(), LabelPrefix) << ':';
1170 } else if (!BB->use_empty()) { // Don't print block # of no uses...
1171 Out << "\n; <label>:";
1172 int Slot = Machine.getLocalSlot(BB);
1179 if (BB->getParent() == 0)
1180 Out << "\t\t; Error: Block without parent!";
1181 else if (BB != &BB->getParent()->getEntryBlock()) { // Not the entry block?
1182 // Output predecessors for the block...
1184 pred_const_iterator PI = pred_begin(BB), PE = pred_end(BB);
1187 Out << " No predecessors!";
1190 writeOperand(*PI, false);
1191 for (++PI; PI != PE; ++PI) {
1193 writeOperand(*PI, false);
1200 if (AnnotationWriter) AnnotationWriter->emitBasicBlockStartAnnot(BB, Out);
1202 // Output all of the instructions in the basic block...
1203 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I != E; ++I)
1204 printInstruction(*I);
1206 if (AnnotationWriter) AnnotationWriter->emitBasicBlockEndAnnot(BB, Out);
1210 /// printInfoComment - Print a little comment after the instruction indicating
1211 /// which slot it occupies.
1213 void AssemblyWriter::printInfoComment(const Value &V) {
1214 if (V.getType() != Type::VoidTy) {
1216 printType(V.getType()) << '>';
1220 if (const GlobalValue *GV = dyn_cast<GlobalValue>(&V))
1221 SlotNum = Machine.getGlobalSlot(GV);
1223 SlotNum = Machine.getLocalSlot(&V);
1227 Out << ':' << SlotNum; // Print out the def slot taken.
1229 Out << " [#uses=" << V.getNumUses() << ']'; // Output # uses
1233 // This member is called for each Instruction in a function..
1234 void AssemblyWriter::printInstruction(const Instruction &I) {
1235 if (AnnotationWriter) AnnotationWriter->emitInstructionAnnot(&I, Out);
1239 // Print out name if it exists...
1241 Out << getLLVMName(I.getName(), LocalPrefix) << " = ";
1243 // If this is a volatile load or store, print out the volatile marker.
1244 if ((isa<LoadInst>(I) && cast<LoadInst>(I).isVolatile()) ||
1245 (isa<StoreInst>(I) && cast<StoreInst>(I).isVolatile())) {
1247 } else if (isa<CallInst>(I) && cast<CallInst>(I).isTailCall()) {
1248 // If this is a call, check if it's a tail call.
1252 // Print out the opcode...
1253 Out << I.getOpcodeName();
1255 // Print out the compare instruction predicates
1256 if (const CmpInst *CI = dyn_cast<CmpInst>(&I))
1257 Out << " " << getPredicateText(CI->getPredicate());
1259 // Print out the type of the operands...
1260 const Value *Operand = I.getNumOperands() ? I.getOperand(0) : 0;
1262 // Special case conditional branches to swizzle the condition out to the front
1263 if (isa<BranchInst>(I) && I.getNumOperands() > 1) {
1264 writeOperand(I.getOperand(2), true);
1266 writeOperand(Operand, true);
1268 writeOperand(I.getOperand(1), true);
1270 } else if (isa<SwitchInst>(I)) {
1271 // Special case switch statement to get formatting nice and correct...
1272 writeOperand(Operand , true); Out << ',';
1273 writeOperand(I.getOperand(1), true); Out << " [";
1275 for (unsigned op = 2, Eop = I.getNumOperands(); op < Eop; op += 2) {
1277 writeOperand(I.getOperand(op ), true); Out << ',';
1278 writeOperand(I.getOperand(op+1), true);
1281 } else if (isa<PHINode>(I)) {
1283 printType(I.getType());
1286 for (unsigned op = 0, Eop = I.getNumOperands(); op < Eop; op += 2) {
1287 if (op) Out << ", ";
1289 writeOperand(I.getOperand(op ), false); Out << ',';
1290 writeOperand(I.getOperand(op+1), false); Out << " ]";
1292 } else if (const GetResultInst *GRI = dyn_cast<GetResultInst>(&I)) {
1293 writeOperand(I.getOperand(0), true);
1294 Out << ", " << GRI->getIndex();
1295 } else if (isa<ReturnInst>(I) && !Operand) {
1297 } else if (const CallInst *CI = dyn_cast<CallInst>(&I)) {
1298 // Print the calling convention being used.
1299 switch (CI->getCallingConv()) {
1300 case CallingConv::C: break; // default
1301 case CallingConv::Fast: Out << " fastcc"; break;
1302 case CallingConv::Cold: Out << " coldcc"; break;
1303 case CallingConv::X86_StdCall: Out << " x86_stdcallcc"; break;
1304 case CallingConv::X86_FastCall: Out << " x86_fastcallcc"; break;
1305 default: Out << " cc" << CI->getCallingConv(); break;
1308 const PointerType *PTy = cast<PointerType>(Operand->getType());
1309 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
1310 const Type *RetTy = FTy->getReturnType();
1311 const PAListPtr &PAL = CI->getParamAttrs();
1313 // If possible, print out the short form of the call instruction. We can
1314 // only do this if the first argument is a pointer to a nonvararg function,
1315 // and if the return type is not a pointer to a function.
1317 if (!FTy->isVarArg() &&
1318 (!isa<PointerType>(RetTy) ||
1319 !isa<FunctionType>(cast<PointerType>(RetTy)->getElementType()))) {
1320 Out << ' '; printType(RetTy);
1321 writeOperand(Operand, false);
1323 writeOperand(Operand, true);
1326 for (unsigned op = 1, Eop = I.getNumOperands(); op < Eop; ++op) {
1329 writeParamOperand(I.getOperand(op), PAL.getParamAttrs(op));
1332 if (PAL.getParamAttrs(0) != ParamAttr::None)
1333 Out << ' ' << ParamAttr::getAsString(PAL.getParamAttrs(0));
1334 } else if (const InvokeInst *II = dyn_cast<InvokeInst>(&I)) {
1335 const PointerType *PTy = cast<PointerType>(Operand->getType());
1336 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
1337 const Type *RetTy = FTy->getReturnType();
1338 const PAListPtr &PAL = II->getParamAttrs();
1340 // Print the calling convention being used.
1341 switch (II->getCallingConv()) {
1342 case CallingConv::C: break; // default
1343 case CallingConv::Fast: Out << " fastcc"; break;
1344 case CallingConv::Cold: Out << " coldcc"; break;
1345 case CallingConv::X86_StdCall: Out << "x86_stdcallcc "; break;
1346 case CallingConv::X86_FastCall: Out << "x86_fastcallcc "; break;
1347 default: Out << " cc" << II->getCallingConv(); break;
1350 // If possible, print out the short form of the invoke instruction. We can
1351 // only do this if the first argument is a pointer to a nonvararg function,
1352 // and if the return type is not a pointer to a function.
1354 if (!FTy->isVarArg() &&
1355 (!isa<PointerType>(RetTy) ||
1356 !isa<FunctionType>(cast<PointerType>(RetTy)->getElementType()))) {
1357 Out << ' '; printType(RetTy);
1358 writeOperand(Operand, false);
1360 writeOperand(Operand, true);
1364 for (unsigned op = 3, Eop = I.getNumOperands(); op < Eop; ++op) {
1367 writeParamOperand(I.getOperand(op), PAL.getParamAttrs(op-2));
1371 if (PAL.getParamAttrs(0) != ParamAttr::None)
1372 Out << " " << ParamAttr::getAsString(PAL.getParamAttrs(0));
1373 Out << "\n\t\t\tto";
1374 writeOperand(II->getNormalDest(), true);
1376 writeOperand(II->getUnwindDest(), true);
1378 } else if (const AllocationInst *AI = dyn_cast<AllocationInst>(&I)) {
1380 printType(AI->getType()->getElementType());
1381 if (AI->isArrayAllocation()) {
1383 writeOperand(AI->getArraySize(), true);
1385 if (AI->getAlignment()) {
1386 Out << ", align " << AI->getAlignment();
1388 } else if (isa<CastInst>(I)) {
1389 if (Operand) writeOperand(Operand, true); // Work with broken code
1391 printType(I.getType());
1392 } else if (isa<VAArgInst>(I)) {
1393 if (Operand) writeOperand(Operand, true); // Work with broken code
1395 printType(I.getType());
1396 } else if (Operand) { // Print the normal way...
1398 // PrintAllTypes - Instructions who have operands of all the same type
1399 // omit the type from all but the first operand. If the instruction has
1400 // different type operands (for example br), then they are all printed.
1401 bool PrintAllTypes = false;
1402 const Type *TheType = Operand->getType();
1404 // Select, Store and ShuffleVector always print all types.
1405 if (isa<SelectInst>(I) || isa<StoreInst>(I) || isa<ShuffleVectorInst>(I)
1406 || isa<ReturnInst>(I)) {
1407 PrintAllTypes = true;
1409 for (unsigned i = 1, E = I.getNumOperands(); i != E; ++i) {
1410 Operand = I.getOperand(i);
1411 if (Operand->getType() != TheType) {
1412 PrintAllTypes = true; // We have differing types! Print them all!
1418 if (!PrintAllTypes) {
1423 for (unsigned i = 0, E = I.getNumOperands(); i != E; ++i) {
1425 writeOperand(I.getOperand(i), PrintAllTypes);
1429 // Print post operand alignment for load/store
1430 if (isa<LoadInst>(I) && cast<LoadInst>(I).getAlignment()) {
1431 Out << ", align " << cast<LoadInst>(I).getAlignment();
1432 } else if (isa<StoreInst>(I) && cast<StoreInst>(I).getAlignment()) {
1433 Out << ", align " << cast<StoreInst>(I).getAlignment();
1436 printInfoComment(I);
1441 //===----------------------------------------------------------------------===//
1442 // External Interface declarations
1443 //===----------------------------------------------------------------------===//
1445 void Module::print(std::ostream &o, AssemblyAnnotationWriter *AAW) const {
1446 SlotMachine SlotTable(this);
1447 AssemblyWriter W(o, SlotTable, this, AAW);
1451 void GlobalVariable::print(std::ostream &o) const {
1452 SlotMachine SlotTable(getParent());
1453 AssemblyWriter W(o, SlotTable, getParent(), 0);
1457 void GlobalAlias::print(std::ostream &o) const {
1458 SlotMachine SlotTable(getParent());
1459 AssemblyWriter W(o, SlotTable, getParent(), 0);
1463 void Function::print(std::ostream &o, AssemblyAnnotationWriter *AAW) const {
1464 SlotMachine SlotTable(getParent());
1465 AssemblyWriter W(o, SlotTable, getParent(), AAW);
1470 void InlineAsm::print(std::ostream &o, AssemblyAnnotationWriter *AAW) const {
1471 WriteAsOperand(o, this, true, 0);
1474 void BasicBlock::print(std::ostream &o, AssemblyAnnotationWriter *AAW) const {
1475 SlotMachine SlotTable(getParent());
1476 AssemblyWriter W(o, SlotTable,
1477 getParent() ? getParent()->getParent() : 0, AAW);
1481 void Instruction::print(std::ostream &o, AssemblyAnnotationWriter *AAW) const {
1482 const Function *F = getParent() ? getParent()->getParent() : 0;
1483 SlotMachine SlotTable(F);
1484 AssemblyWriter W(o, SlotTable, F ? F->getParent() : 0, AAW);
1489 void Constant::print(std::ostream &o) const {
1490 if (this == 0) { o << "<null> constant value\n"; return; }
1492 o << ' ' << getType()->getDescription() << ' ';
1494 std::map<const Type *, std::string> TypeTable;
1495 WriteConstantInt(o, this, TypeTable, 0);
1498 void Type::print(std::ostream &o) const {
1502 o << getDescription();
1505 void Argument::print(std::ostream &o) const {
1506 WriteAsOperand(o, this, true, getParent() ? getParent()->getParent() : 0);
1509 // Value::dump - allow easy printing of Values from the debugger.
1510 // Located here because so much of the needed functionality is here.
1511 void Value::dump() const { print(*cerr.stream()); cerr << '\n'; }
1513 // Type::dump - allow easy printing of Values from the debugger.
1514 // Located here because so much of the needed functionality is here.
1515 void Type::dump() const { print(*cerr.stream()); cerr << '\n'; }
1517 //===----------------------------------------------------------------------===//
1518 // SlotMachine Implementation
1519 //===----------------------------------------------------------------------===//
1522 #define SC_DEBUG(X) cerr << X
1527 // Module level constructor. Causes the contents of the Module (sans functions)
1528 // to be added to the slot table.
1529 SlotMachine::SlotMachine(const Module *M)
1530 : TheModule(M) ///< Saved for lazy initialization.
1532 , FunctionProcessed(false)
1533 , mMap(), mNext(0), fMap(), fNext(0)
1537 // Function level constructor. Causes the contents of the Module and the one
1538 // function provided to be added to the slot table.
1539 SlotMachine::SlotMachine(const Function *F)
1540 : TheModule(F ? F->getParent() : 0) ///< Saved for lazy initialization
1541 , TheFunction(F) ///< Saved for lazy initialization
1542 , FunctionProcessed(false)
1543 , mMap(), mNext(0), fMap(), fNext(0)
1547 inline void SlotMachine::initialize() {
1550 TheModule = 0; ///< Prevent re-processing next time we're called.
1552 if (TheFunction && !FunctionProcessed)
1556 // Iterate through all the global variables, functions, and global
1557 // variable initializers and create slots for them.
1558 void SlotMachine::processModule() {
1559 SC_DEBUG("begin processModule!\n");
1561 // Add all of the unnamed global variables to the value table.
1562 for (Module::const_global_iterator I = TheModule->global_begin(),
1563 E = TheModule->global_end(); I != E; ++I)
1565 CreateModuleSlot(I);
1567 // Add all the unnamed functions to the table.
1568 for (Module::const_iterator I = TheModule->begin(), E = TheModule->end();
1571 CreateModuleSlot(I);
1573 SC_DEBUG("end processModule!\n");
1577 // Process the arguments, basic blocks, and instructions of a function.
1578 void SlotMachine::processFunction() {
1579 SC_DEBUG("begin processFunction!\n");
1582 // Add all the function arguments with no names.
1583 for(Function::const_arg_iterator AI = TheFunction->arg_begin(),
1584 AE = TheFunction->arg_end(); AI != AE; ++AI)
1586 CreateFunctionSlot(AI);
1588 SC_DEBUG("Inserting Instructions:\n");
1590 // Add all of the basic blocks and instructions with no names.
1591 for (Function::const_iterator BB = TheFunction->begin(),
1592 E = TheFunction->end(); BB != E; ++BB) {
1594 CreateFunctionSlot(BB);
1595 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I != E; ++I)
1596 if (I->getType() != Type::VoidTy && !I->hasName())
1597 CreateFunctionSlot(I);
1600 FunctionProcessed = true;
1602 SC_DEBUG("end processFunction!\n");
1605 /// Clean up after incorporating a function. This is the only way to get out of
1606 /// the function incorporation state that affects get*Slot/Create*Slot. Function
1607 /// incorporation state is indicated by TheFunction != 0.
1608 void SlotMachine::purgeFunction() {
1609 SC_DEBUG("begin purgeFunction!\n");
1610 fMap.clear(); // Simply discard the function level map
1612 FunctionProcessed = false;
1613 SC_DEBUG("end purgeFunction!\n");
1616 /// getGlobalSlot - Get the slot number of a global value.
1617 int SlotMachine::getGlobalSlot(const GlobalValue *V) {
1618 // Check for uninitialized state and do lazy initialization.
1621 // Find the type plane in the module map
1622 ValueMap::const_iterator MI = mMap.find(V);
1623 if (MI == mMap.end()) return -1;
1629 /// getLocalSlot - Get the slot number for a value that is local to a function.
1630 int SlotMachine::getLocalSlot(const Value *V) {
1631 assert(!isa<Constant>(V) && "Can't get a constant or global slot with this!");
1633 // Check for uninitialized state and do lazy initialization.
1636 ValueMap::const_iterator FI = fMap.find(V);
1637 if (FI == fMap.end()) return -1;
1643 /// CreateModuleSlot - Insert the specified GlobalValue* into the slot table.
1644 void SlotMachine::CreateModuleSlot(const GlobalValue *V) {
1645 assert(V && "Can't insert a null Value into SlotMachine!");
1646 assert(V->getType() != Type::VoidTy && "Doesn't need a slot!");
1647 assert(!V->hasName() && "Doesn't need a slot!");
1649 unsigned DestSlot = mNext++;
1652 SC_DEBUG(" Inserting value [" << V->getType() << "] = " << V << " slot=" <<
1654 // G = Global, F = Function, A = Alias, o = other
1655 SC_DEBUG((isa<GlobalVariable>(V) ? 'G' :
1656 (isa<Function> ? 'F' :
1657 (isa<GlobalAlias> ? 'A' : 'o'))) << "]\n");
1661 /// CreateSlot - Create a new slot for the specified value if it has no name.
1662 void SlotMachine::CreateFunctionSlot(const Value *V) {
1663 const Type *VTy = V->getType();
1664 assert(VTy != Type::VoidTy && !V->hasName() && "Doesn't need a slot!");
1666 unsigned DestSlot = fNext++;
1669 // G = Global, F = Function, o = other
1670 SC_DEBUG(" Inserting value [" << VTy << "] = " << V << " slot=" <<
1671 DestSlot << " [o]\n");