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/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/ParameterAttributes.h"
24 #include "llvm/InlineAsm.h"
25 #include "llvm/Instruction.h"
26 #include "llvm/Instructions.h"
27 #include "llvm/Module.h"
28 #include "llvm/ValueSymbolTable.h"
29 #include "llvm/TypeSymbolTable.h"
30 #include "llvm/ADT/StringExtras.h"
31 #include "llvm/ADT/STLExtras.h"
32 #include "llvm/Support/CFG.h"
33 #include "llvm/Support/MathExtras.h"
34 #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 SlotMachine(const Module *M);
61 /// @brief Construct from a function, starting out in incorp state.
62 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 bool NameNeedsQuotes(const std::string &Name) {
182 if (Name[0] >= '0' && Name[0] <= '9') return true;
183 // Scan to see if we have any characters that are not on the "white list"
184 for (unsigned i = 0, e = Name.size(); i != e; ++i) {
186 assert(C != '"' && "Illegal character in LLVM value name!");
187 if ((C < 'a' || C > 'z') && (C < 'A' || C > 'Z') && (C < '0' || C > '9') &&
188 C != '-' && C != '.' && C != '_')
200 /// getLLVMName - Turn the specified string into an 'LLVM name', which is either
201 /// prefixed with % (if the string only contains simple characters) or is
202 /// surrounded with ""'s (if it has special chars in it).
203 static std::string getLLVMName(const std::string &Name, PrefixType Prefix) {
204 assert(!Name.empty() && "Cannot get empty name!");
206 // First character cannot start with a number...
207 if (NameNeedsQuotes(Name)) {
208 if (Prefix == GlobalPrefix)
209 return "@\"" + Name + "\"";
210 return "\"" + Name + "\"";
213 // If we get here, then the identifier is legal to use as a "VarID".
215 default: assert(0 && "Bad prefix!");
216 case GlobalPrefix: return '@' + Name;
217 case LabelPrefix: return Name;
218 case LocalPrefix: return '%' + Name;
223 /// fillTypeNameTable - If the module has a symbol table, take all global types
224 /// and stuff their names into the TypeNames map.
226 static void fillTypeNameTable(const Module *M,
227 std::map<const Type *, std::string> &TypeNames) {
229 const TypeSymbolTable &ST = M->getTypeSymbolTable();
230 TypeSymbolTable::const_iterator TI = ST.begin();
231 for (; TI != ST.end(); ++TI) {
232 // As a heuristic, don't insert pointer to primitive types, because
233 // they are used too often to have a single useful name.
235 const Type *Ty = cast<Type>(TI->second);
236 if (!isa<PointerType>(Ty) ||
237 !cast<PointerType>(Ty)->getElementType()->isPrimitiveType() ||
238 !cast<PointerType>(Ty)->getElementType()->isInteger() ||
239 isa<OpaqueType>(cast<PointerType>(Ty)->getElementType()))
240 TypeNames.insert(std::make_pair(Ty, getLLVMName(TI->first, LocalPrefix)));
246 static void calcTypeName(const Type *Ty,
247 std::vector<const Type *> &TypeStack,
248 std::map<const Type *, std::string> &TypeNames,
249 std::string & Result){
250 if (Ty->isInteger() || (Ty->isPrimitiveType() && !isa<OpaqueType>(Ty))) {
251 Result += Ty->getDescription(); // Base case
255 // Check to see if the type is named.
256 std::map<const Type *, std::string>::iterator I = TypeNames.find(Ty);
257 if (I != TypeNames.end()) {
262 if (isa<OpaqueType>(Ty)) {
267 // Check to see if the Type is already on the stack...
268 unsigned Slot = 0, CurSize = TypeStack.size();
269 while (Slot < CurSize && TypeStack[Slot] != Ty) ++Slot; // Scan for type
271 // This is another base case for the recursion. In this case, we know
272 // that we have looped back to a type that we have previously visited.
273 // Generate the appropriate upreference to handle this.
274 if (Slot < CurSize) {
275 Result += "\\" + utostr(CurSize-Slot); // Here's the upreference
279 TypeStack.push_back(Ty); // Recursive case: Add us to the stack..
281 switch (Ty->getTypeID()) {
282 case Type::IntegerTyID: {
283 unsigned BitWidth = cast<IntegerType>(Ty)->getBitWidth();
284 Result += "i" + utostr(BitWidth);
287 case Type::FunctionTyID: {
288 const FunctionType *FTy = cast<FunctionType>(Ty);
289 calcTypeName(FTy->getReturnType(), TypeStack, TypeNames, Result);
292 const ParamAttrsList *Attrs = FTy->getParamAttrs();
293 for (FunctionType::param_iterator I = FTy->param_begin(),
294 E = FTy->param_end(); I != E; ++I) {
295 if (I != FTy->param_begin())
297 calcTypeName(*I, TypeStack, TypeNames, Result);
298 if (Attrs && Attrs->getParamAttrs(Idx) != ParamAttr::None) {
300 Result += Attrs->getParamAttrsTextByIndex(Idx);
304 if (FTy->isVarArg()) {
305 if (FTy->getNumParams()) Result += ", ";
309 if (Attrs && Attrs->getParamAttrs(0) != ParamAttr::None) {
311 Result += Attrs->getParamAttrsTextByIndex(0);
315 case Type::StructTyID: {
316 const StructType *STy = cast<StructType>(Ty);
320 for (StructType::element_iterator I = STy->element_begin(),
321 E = STy->element_end(); I != E; ++I) {
322 if (I != STy->element_begin())
324 calcTypeName(*I, TypeStack, TypeNames, Result);
331 case Type::PointerTyID:
332 calcTypeName(cast<PointerType>(Ty)->getElementType(),
333 TypeStack, TypeNames, Result);
336 case Type::ArrayTyID: {
337 const ArrayType *ATy = cast<ArrayType>(Ty);
338 Result += "[" + utostr(ATy->getNumElements()) + " x ";
339 calcTypeName(ATy->getElementType(), TypeStack, TypeNames, Result);
343 case Type::VectorTyID: {
344 const VectorType *PTy = cast<VectorType>(Ty);
345 Result += "<" + utostr(PTy->getNumElements()) + " x ";
346 calcTypeName(PTy->getElementType(), TypeStack, TypeNames, Result);
350 case Type::OpaqueTyID:
354 Result += "<unrecognized-type>";
358 TypeStack.pop_back(); // Remove self from stack...
362 /// printTypeInt - The internal guts of printing out a type that has a
363 /// potentially named portion.
365 static std::ostream &printTypeInt(std::ostream &Out, const Type *Ty,
366 std::map<const Type *, std::string> &TypeNames) {
367 // Primitive types always print out their description, regardless of whether
368 // they have been named or not.
370 if (Ty->isInteger() || (Ty->isPrimitiveType() && !isa<OpaqueType>(Ty)))
371 return Out << Ty->getDescription();
373 // Check to see if the type is named.
374 std::map<const Type *, std::string>::iterator I = TypeNames.find(Ty);
375 if (I != TypeNames.end()) return Out << I->second;
377 // Otherwise we have a type that has not been named but is a derived type.
378 // Carefully recurse the type hierarchy to print out any contained symbolic
381 std::vector<const Type *> TypeStack;
382 std::string TypeName;
383 calcTypeName(Ty, TypeStack, TypeNames, TypeName);
384 TypeNames.insert(std::make_pair(Ty, TypeName));//Cache type name for later use
385 return (Out << TypeName);
389 /// WriteTypeSymbolic - This attempts to write the specified type as a symbolic
390 /// type, iff there is an entry in the modules symbol table for the specified
391 /// type or one of it's component types. This is slower than a simple x << Type
393 std::ostream &llvm::WriteTypeSymbolic(std::ostream &Out, const Type *Ty,
397 // If they want us to print out a type, but there is no context, we can't
398 // print it symbolically.
400 return Out << Ty->getDescription();
402 std::map<const Type *, std::string> TypeNames;
403 fillTypeNameTable(M, TypeNames);
404 return printTypeInt(Out, Ty, TypeNames);
407 // PrintEscapedString - Print each character of the specified string, escaping
408 // it if it is not printable or if it is an escape char.
409 static void PrintEscapedString(const std::string &Str, std::ostream &Out) {
410 for (unsigned i = 0, e = Str.size(); i != e; ++i) {
411 unsigned char C = Str[i];
412 if (isprint(C) && C != '"' && C != '\\') {
416 << (char) ((C/16 < 10) ? ( C/16 +'0') : ( C/16 -10+'A'))
417 << (char)(((C&15) < 10) ? ((C&15)+'0') : ((C&15)-10+'A'));
422 static const char *getPredicateText(unsigned predicate) {
423 const char * pred = "unknown";
425 case FCmpInst::FCMP_FALSE: pred = "false"; break;
426 case FCmpInst::FCMP_OEQ: pred = "oeq"; break;
427 case FCmpInst::FCMP_OGT: pred = "ogt"; break;
428 case FCmpInst::FCMP_OGE: pred = "oge"; break;
429 case FCmpInst::FCMP_OLT: pred = "olt"; break;
430 case FCmpInst::FCMP_OLE: pred = "ole"; break;
431 case FCmpInst::FCMP_ONE: pred = "one"; break;
432 case FCmpInst::FCMP_ORD: pred = "ord"; break;
433 case FCmpInst::FCMP_UNO: pred = "uno"; break;
434 case FCmpInst::FCMP_UEQ: pred = "ueq"; break;
435 case FCmpInst::FCMP_UGT: pred = "ugt"; break;
436 case FCmpInst::FCMP_UGE: pred = "uge"; break;
437 case FCmpInst::FCMP_ULT: pred = "ult"; break;
438 case FCmpInst::FCMP_ULE: pred = "ule"; break;
439 case FCmpInst::FCMP_UNE: pred = "une"; break;
440 case FCmpInst::FCMP_TRUE: pred = "true"; break;
441 case ICmpInst::ICMP_EQ: pred = "eq"; break;
442 case ICmpInst::ICMP_NE: pred = "ne"; break;
443 case ICmpInst::ICMP_SGT: pred = "sgt"; break;
444 case ICmpInst::ICMP_SGE: pred = "sge"; break;
445 case ICmpInst::ICMP_SLT: pred = "slt"; break;
446 case ICmpInst::ICMP_SLE: pred = "sle"; break;
447 case ICmpInst::ICMP_UGT: pred = "ugt"; break;
448 case ICmpInst::ICMP_UGE: pred = "uge"; break;
449 case ICmpInst::ICMP_ULT: pred = "ult"; break;
450 case ICmpInst::ICMP_ULE: pred = "ule"; break;
455 /// @brief Internal constant writer.
456 static void WriteConstantInt(std::ostream &Out, const Constant *CV,
457 std::map<const Type *, std::string> &TypeTable,
458 SlotMachine *Machine) {
459 const int IndentSize = 4;
460 static std::string Indent = "\n";
461 if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV)) {
462 if (CI->getType() == Type::Int1Ty)
463 Out << (CI->getZExtValue() ? "true" : "false");
465 Out << CI->getValue().toStringSigned(10);
466 } else if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CV)) {
467 // We would like to output the FP constant value in exponential notation,
468 // but we cannot do this if doing so will lose precision. Check here to
469 // make sure that we only output it in exponential format if we can parse
470 // the value back and get the same value.
472 std::string StrVal = ftostr(CFP->getValue());
474 // Check to make sure that the stringized number is not some string like
475 // "Inf" or NaN, that atof will accept, but the lexer will not. Check that
476 // the string matches the "[-+]?[0-9]" regex.
478 if ((StrVal[0] >= '0' && StrVal[0] <= '9') ||
479 ((StrVal[0] == '-' || StrVal[0] == '+') &&
480 (StrVal[1] >= '0' && StrVal[1] <= '9')))
481 // Reparse stringized version!
482 if (atof(StrVal.c_str()) == CFP->getValue()) {
487 // Otherwise we could not reparse it to exactly the same value, so we must
488 // output the string in hexadecimal format!
489 assert(sizeof(double) == sizeof(uint64_t) &&
490 "assuming that double is 64 bits!");
491 Out << "0x" << utohexstr(DoubleToBits(CFP->getValue()));
493 } else if (isa<ConstantAggregateZero>(CV)) {
494 Out << "zeroinitializer";
495 } else if (const ConstantArray *CA = dyn_cast<ConstantArray>(CV)) {
496 // As a special case, print the array as a string if it is an array of
497 // ubytes or an array of sbytes with positive values.
499 const Type *ETy = CA->getType()->getElementType();
500 if (CA->isString()) {
502 PrintEscapedString(CA->getAsString(), Out);
505 } else { // Cannot output in string format...
507 if (CA->getNumOperands()) {
509 printTypeInt(Out, ETy, TypeTable);
510 WriteAsOperandInternal(Out, CA->getOperand(0),
512 for (unsigned i = 1, e = CA->getNumOperands(); i != e; ++i) {
514 printTypeInt(Out, ETy, TypeTable);
515 WriteAsOperandInternal(Out, CA->getOperand(i), TypeTable, Machine);
520 } else if (const ConstantStruct *CS = dyn_cast<ConstantStruct>(CV)) {
521 if (CS->getType()->isPacked())
524 unsigned N = CS->getNumOperands();
527 Indent += std::string(IndentSize, ' ');
532 printTypeInt(Out, CS->getOperand(0)->getType(), TypeTable);
534 WriteAsOperandInternal(Out, CS->getOperand(0), TypeTable, Machine);
536 for (unsigned i = 1; i < N; i++) {
538 if (N > 2) Out << Indent;
539 printTypeInt(Out, CS->getOperand(i)->getType(), TypeTable);
541 WriteAsOperandInternal(Out, CS->getOperand(i), TypeTable, Machine);
543 if (N > 2) Indent.resize(Indent.size() - IndentSize);
547 if (CS->getType()->isPacked())
549 } else if (const ConstantVector *CP = dyn_cast<ConstantVector>(CV)) {
550 const Type *ETy = CP->getType()->getElementType();
551 assert(CP->getNumOperands() > 0 &&
552 "Number of operands for a PackedConst must be > 0");
555 printTypeInt(Out, ETy, TypeTable);
556 WriteAsOperandInternal(Out, CP->getOperand(0), TypeTable, Machine);
557 for (unsigned i = 1, e = CP->getNumOperands(); i != e; ++i) {
559 printTypeInt(Out, ETy, TypeTable);
560 WriteAsOperandInternal(Out, CP->getOperand(i), TypeTable, Machine);
563 } else if (isa<ConstantPointerNull>(CV)) {
566 } else if (isa<UndefValue>(CV)) {
569 } else if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV)) {
570 Out << CE->getOpcodeName();
572 Out << " " << getPredicateText(CE->getPredicate());
575 for (User::const_op_iterator OI=CE->op_begin(); OI != CE->op_end(); ++OI) {
576 printTypeInt(Out, (*OI)->getType(), TypeTable);
577 WriteAsOperandInternal(Out, *OI, TypeTable, Machine);
578 if (OI+1 != CE->op_end())
584 printTypeInt(Out, CE->getType(), TypeTable);
590 Out << "<placeholder or erroneous Constant>";
595 /// WriteAsOperand - Write the name of the specified value out to the specified
596 /// ostream. This can be useful when you just want to print int %reg126, not
597 /// the whole instruction that generated it.
599 static void WriteAsOperandInternal(std::ostream &Out, const Value *V,
600 std::map<const Type*, std::string> &TypeTable,
601 SlotMachine *Machine) {
604 Out << getLLVMName(V->getName(),
605 isa<GlobalValue>(V) ? GlobalPrefix : LocalPrefix);
607 const Constant *CV = dyn_cast<Constant>(V);
608 if (CV && !isa<GlobalValue>(CV)) {
609 WriteConstantInt(Out, CV, TypeTable, Machine);
610 } else if (const InlineAsm *IA = dyn_cast<InlineAsm>(V)) {
612 if (IA->hasSideEffects())
613 Out << "sideeffect ";
615 PrintEscapedString(IA->getAsmString(), Out);
617 PrintEscapedString(IA->getConstraintString(), Out);
623 if (const GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
624 Slot = Machine->getGlobalSlot(GV);
627 Slot = Machine->getLocalSlot(V);
630 Machine = createSlotMachine(V);
632 if (const GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
633 Slot = Machine->getGlobalSlot(GV);
636 Slot = Machine->getLocalSlot(V);
644 Out << Prefix << Slot;
651 /// WriteAsOperand - Write the name of the specified value out to the specified
652 /// ostream. This can be useful when you just want to print int %reg126, not
653 /// the whole instruction that generated it.
655 std::ostream &llvm::WriteAsOperand(std::ostream &Out, const Value *V,
656 bool PrintType, const Module *Context) {
657 std::map<const Type *, std::string> TypeNames;
658 if (Context == 0) Context = getModuleFromVal(V);
661 fillTypeNameTable(Context, TypeNames);
664 printTypeInt(Out, V->getType(), TypeNames);
666 WriteAsOperandInternal(Out, V, TypeNames, 0);
673 class AssemblyWriter {
675 SlotMachine &Machine;
676 const Module *TheModule;
677 std::map<const Type *, std::string> TypeNames;
678 AssemblyAnnotationWriter *AnnotationWriter;
680 inline AssemblyWriter(std::ostream &o, SlotMachine &Mac, const Module *M,
681 AssemblyAnnotationWriter *AAW)
682 : Out(o), Machine(Mac), TheModule(M), AnnotationWriter(AAW) {
684 // If the module has a symbol table, take all global types and stuff their
685 // names into the TypeNames map.
687 fillTypeNameTable(M, TypeNames);
690 inline void write(const Module *M) { printModule(M); }
691 inline void write(const GlobalVariable *G) { printGlobal(G); }
692 inline void write(const GlobalAlias *G) { printAlias(G); }
693 inline void write(const Function *F) { printFunction(F); }
694 inline void write(const BasicBlock *BB) { printBasicBlock(BB); }
695 inline void write(const Instruction *I) { printInstruction(*I); }
696 inline void write(const Type *Ty) { printType(Ty); }
698 void writeOperand(const Value *Op, bool PrintType);
700 const Module* getModule() { return TheModule; }
703 void printModule(const Module *M);
704 void printTypeSymbolTable(const TypeSymbolTable &ST);
705 void printGlobal(const GlobalVariable *GV);
706 void printAlias(const GlobalAlias *GV);
707 void printFunction(const Function *F);
708 void printArgument(const Argument *FA, uint16_t ParamAttrs);
709 void printBasicBlock(const BasicBlock *BB);
710 void printInstruction(const Instruction &I);
712 // printType - Go to extreme measures to attempt to print out a short,
713 // symbolic version of a type name.
715 std::ostream &printType(const Type *Ty) {
716 return printTypeInt(Out, Ty, TypeNames);
719 // printTypeAtLeastOneLevel - Print out one level of the possibly complex type
720 // without considering any symbolic types that we may have equal to it.
722 std::ostream &printTypeAtLeastOneLevel(const Type *Ty);
724 // printInfoComment - Print a little comment after the instruction indicating
725 // which slot it occupies.
726 void printInfoComment(const Value &V);
728 } // end of llvm namespace
730 /// printTypeAtLeastOneLevel - Print out one level of the possibly complex type
731 /// without considering any symbolic types that we may have equal to it.
733 std::ostream &AssemblyWriter::printTypeAtLeastOneLevel(const Type *Ty) {
734 if (const IntegerType *ITy = dyn_cast<IntegerType>(Ty))
735 Out << "i" << utostr(ITy->getBitWidth());
736 else if (const FunctionType *FTy = dyn_cast<FunctionType>(Ty)) {
737 printType(FTy->getReturnType());
740 const ParamAttrsList *Attrs = FTy->getParamAttrs();
741 for (FunctionType::param_iterator I = FTy->param_begin(),
742 E = FTy->param_end(); I != E; ++I) {
743 if (I != FTy->param_begin())
746 if (Attrs && Attrs->getParamAttrs(Idx) != ParamAttr::None) {
747 Out << " " << Attrs->getParamAttrsTextByIndex(Idx);
751 if (FTy->isVarArg()) {
752 if (FTy->getNumParams()) Out << ", ";
756 if (Attrs && Attrs->getParamAttrs(0) != ParamAttr::None)
757 Out << ' ' << Attrs->getParamAttrsTextByIndex(0);
758 } else if (const StructType *STy = dyn_cast<StructType>(Ty)) {
762 for (StructType::element_iterator I = STy->element_begin(),
763 E = STy->element_end(); I != E; ++I) {
764 if (I != STy->element_begin())
771 } else if (const PointerType *PTy = dyn_cast<PointerType>(Ty)) {
772 printType(PTy->getElementType()) << '*';
773 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
774 Out << '[' << ATy->getNumElements() << " x ";
775 printType(ATy->getElementType()) << ']';
776 } else if (const VectorType *PTy = dyn_cast<VectorType>(Ty)) {
777 Out << '<' << PTy->getNumElements() << " x ";
778 printType(PTy->getElementType()) << '>';
780 else if (isa<OpaqueType>(Ty)) {
783 if (!Ty->isPrimitiveType())
784 Out << "<unknown derived type>";
791 void AssemblyWriter::writeOperand(const Value *Operand, bool PrintType) {
793 Out << "<null operand!>";
795 if (PrintType) { Out << ' '; printType(Operand->getType()); }
796 WriteAsOperandInternal(Out, Operand, TypeNames, &Machine);
801 void AssemblyWriter::printModule(const Module *M) {
802 if (!M->getModuleIdentifier().empty() &&
803 // Don't print the ID if it will start a new line (which would
804 // require a comment char before it).
805 M->getModuleIdentifier().find('\n') == std::string::npos)
806 Out << "; ModuleID = '" << M->getModuleIdentifier() << "'\n";
808 if (!M->getDataLayout().empty())
809 Out << "target datalayout = \"" << M->getDataLayout() << "\"\n";
810 if (!M->getTargetTriple().empty())
811 Out << "target triple = \"" << M->getTargetTriple() << "\"\n";
813 if (!M->getModuleInlineAsm().empty()) {
814 // Split the string into lines, to make it easier to read the .ll file.
815 std::string Asm = M->getModuleInlineAsm();
817 size_t NewLine = Asm.find_first_of('\n', CurPos);
818 while (NewLine != std::string::npos) {
819 // We found a newline, print the portion of the asm string from the
820 // last newline up to this newline.
821 Out << "module asm \"";
822 PrintEscapedString(std::string(Asm.begin()+CurPos, Asm.begin()+NewLine),
826 NewLine = Asm.find_first_of('\n', CurPos);
828 Out << "module asm \"";
829 PrintEscapedString(std::string(Asm.begin()+CurPos, Asm.end()), Out);
833 // Loop over the dependent libraries and emit them.
834 Module::lib_iterator LI = M->lib_begin();
835 Module::lib_iterator LE = M->lib_end();
837 Out << "deplibs = [ ";
839 Out << '"' << *LI << '"';
847 // Loop over the symbol table, emitting all named constants.
848 printTypeSymbolTable(M->getTypeSymbolTable());
850 for (Module::const_global_iterator I = M->global_begin(), E = M->global_end();
854 // Output all aliases.
855 if (!M->alias_empty()) Out << "\n";
856 for (Module::const_alias_iterator I = M->alias_begin(), E = M->alias_end();
860 // Output all of the functions.
861 for (Module::const_iterator I = M->begin(), E = M->end(); I != E; ++I)
865 void AssemblyWriter::printGlobal(const GlobalVariable *GV) {
866 if (GV->hasName()) Out << getLLVMName(GV->getName(), GlobalPrefix) << " = ";
868 if (!GV->hasInitializer())
869 switch (GV->getLinkage()) {
870 case GlobalValue::DLLImportLinkage: Out << "dllimport "; break;
871 case GlobalValue::ExternalWeakLinkage: Out << "extern_weak "; break;
872 default: Out << "external "; break;
874 switch (GV->getLinkage()) {
875 case GlobalValue::InternalLinkage: Out << "internal "; break;
876 case GlobalValue::LinkOnceLinkage: Out << "linkonce "; break;
877 case GlobalValue::WeakLinkage: Out << "weak "; break;
878 case GlobalValue::AppendingLinkage: Out << "appending "; break;
879 case GlobalValue::DLLImportLinkage: Out << "dllimport "; break;
880 case GlobalValue::DLLExportLinkage: Out << "dllexport "; break;
881 case GlobalValue::ExternalWeakLinkage: Out << "extern_weak "; break;
882 case GlobalValue::ExternalLinkage: break;
883 case GlobalValue::GhostLinkage:
884 cerr << "GhostLinkage not allowed in AsmWriter!\n";
887 switch (GV->getVisibility()) {
888 default: assert(0 && "Invalid visibility style!");
889 case GlobalValue::DefaultVisibility: break;
890 case GlobalValue::HiddenVisibility: Out << "hidden "; break;
891 case GlobalValue::ProtectedVisibility: Out << "protected "; break;
895 if (GV->isThreadLocal()) Out << "thread_local ";
896 Out << (GV->isConstant() ? "constant " : "global ");
897 printType(GV->getType()->getElementType());
899 if (GV->hasInitializer()) {
900 Constant* C = cast<Constant>(GV->getInitializer());
901 assert(C && "GlobalVar initializer isn't constant?");
902 writeOperand(GV->getInitializer(), false);
905 if (GV->hasSection())
906 Out << ", section \"" << GV->getSection() << '"';
907 if (GV->getAlignment())
908 Out << ", align " << GV->getAlignment();
910 printInfoComment(*GV);
914 void AssemblyWriter::printAlias(const GlobalAlias *GA) {
915 Out << getLLVMName(GA->getName(), GlobalPrefix) << " = ";
916 switch (GA->getVisibility()) {
917 default: assert(0 && "Invalid visibility style!");
918 case GlobalValue::DefaultVisibility: break;
919 case GlobalValue::HiddenVisibility: Out << "hidden "; break;
920 case GlobalValue::ProtectedVisibility: Out << "protected "; break;
925 switch (GA->getLinkage()) {
926 case GlobalValue::WeakLinkage: Out << "weak "; break;
927 case GlobalValue::InternalLinkage: Out << "internal "; break;
928 case GlobalValue::ExternalLinkage: break;
930 assert(0 && "Invalid alias linkage");
933 const Constant *Aliasee = GA->getAliasee();
935 if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(Aliasee)) {
936 printType(GV->getType());
937 Out << " " << getLLVMName(GV->getName(), GlobalPrefix);
938 } else if (const Function *F = dyn_cast<Function>(Aliasee)) {
939 printType(F->getFunctionType());
942 if (!F->getName().empty())
943 Out << getLLVMName(F->getName(), GlobalPrefix);
947 const ConstantExpr *CE = 0;
948 if ((CE = dyn_cast<ConstantExpr>(Aliasee)) &&
949 (CE->getOpcode() == Instruction::BitCast)) {
950 writeOperand(CE, false);
952 assert(0 && "Unsupported aliasee");
955 printInfoComment(*GA);
959 void AssemblyWriter::printTypeSymbolTable(const TypeSymbolTable &ST) {
961 for (TypeSymbolTable::const_iterator TI = ST.begin(), TE = ST.end();
963 Out << "\t" << getLLVMName(TI->first, LocalPrefix) << " = type ";
965 // Make sure we print out at least one level of the type structure, so
966 // that we do not get %FILE = type %FILE
968 printTypeAtLeastOneLevel(TI->second) << "\n";
972 /// printFunction - Print all aspects of a function.
974 void AssemblyWriter::printFunction(const Function *F) {
975 // Print out the return type and name...
978 if (AnnotationWriter) AnnotationWriter->emitFunctionAnnot(F, Out);
980 if (F->isDeclaration())
981 switch (F->getLinkage()) {
982 case GlobalValue::DLLImportLinkage: Out << "declare dllimport "; break;
983 case GlobalValue::ExternalWeakLinkage: Out << "declare extern_weak "; break;
984 default: Out << "declare ";
988 switch (F->getLinkage()) {
989 case GlobalValue::InternalLinkage: Out << "internal "; break;
990 case GlobalValue::LinkOnceLinkage: Out << "linkonce "; break;
991 case GlobalValue::WeakLinkage: Out << "weak "; break;
992 case GlobalValue::AppendingLinkage: Out << "appending "; break;
993 case GlobalValue::DLLImportLinkage: Out << "dllimport "; break;
994 case GlobalValue::DLLExportLinkage: Out << "dllexport "; break;
995 case GlobalValue::ExternalWeakLinkage: Out << "extern_weak "; break;
996 case GlobalValue::ExternalLinkage: break;
997 case GlobalValue::GhostLinkage:
998 cerr << "GhostLinkage not allowed in AsmWriter!\n";
1001 switch (F->getVisibility()) {
1002 default: assert(0 && "Invalid visibility style!");
1003 case GlobalValue::DefaultVisibility: break;
1004 case GlobalValue::HiddenVisibility: Out << "hidden "; break;
1005 case GlobalValue::ProtectedVisibility: Out << "protected "; break;
1009 // Print the calling convention.
1010 switch (F->getCallingConv()) {
1011 case CallingConv::C: break; // default
1012 case CallingConv::Fast: Out << "fastcc "; break;
1013 case CallingConv::Cold: Out << "coldcc "; break;
1014 case CallingConv::X86_StdCall: Out << "x86_stdcallcc "; break;
1015 case CallingConv::X86_FastCall: Out << "x86_fastcallcc "; break;
1016 default: Out << "cc" << F->getCallingConv() << " "; break;
1019 const FunctionType *FT = F->getFunctionType();
1020 const ParamAttrsList *Attrs = FT->getParamAttrs();
1021 printType(F->getReturnType()) << ' ';
1022 if (!F->getName().empty())
1023 Out << getLLVMName(F->getName(), GlobalPrefix);
1027 Machine.incorporateFunction(F);
1029 // Loop over the arguments, printing them...
1032 if (!F->isDeclaration()) {
1033 // If this isn't a declaration, print the argument names as well.
1034 for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
1036 // Insert commas as we go... the first arg doesn't get a comma
1037 if (I != F->arg_begin()) Out << ", ";
1038 printArgument(I, (Attrs ? Attrs->getParamAttrs(Idx)
1039 : uint16_t(ParamAttr::None)));
1043 // Otherwise, print the types from the function type.
1044 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
1045 // Insert commas as we go... the first arg doesn't get a comma
1049 printType(FT->getParamType(i));
1051 unsigned ArgAttrs = ParamAttr::None;
1052 if (Attrs) ArgAttrs = Attrs->getParamAttrs(i+1);
1053 if (ArgAttrs != ParamAttr::None)
1054 Out << ' ' << ParamAttrsList::getParamAttrsText(ArgAttrs);
1058 // Finish printing arguments...
1059 if (FT->isVarArg()) {
1060 if (FT->getNumParams()) Out << ", ";
1061 Out << "..."; // Output varargs portion of signature!
1064 if (Attrs && Attrs->getParamAttrs(0) != ParamAttr::None)
1065 Out << ' ' << Attrs->getParamAttrsTextByIndex(0);
1066 if (F->hasSection())
1067 Out << " section \"" << F->getSection() << '"';
1068 if (F->getAlignment())
1069 Out << " align " << F->getAlignment();
1071 if (F->isDeclaration()) {
1076 // Output all of its basic blocks... for the function
1077 for (Function::const_iterator I = F->begin(), E = F->end(); I != E; ++I)
1083 Machine.purgeFunction();
1086 /// printArgument - This member is called for every argument that is passed into
1087 /// the function. Simply print it out
1089 void AssemblyWriter::printArgument(const Argument *Arg, uint16_t Attrs) {
1091 printType(Arg->getType());
1093 if (Attrs != ParamAttr::None)
1094 Out << ' ' << ParamAttrsList::getParamAttrsText(Attrs);
1096 // Output name, if available...
1098 Out << ' ' << getLLVMName(Arg->getName(), LocalPrefix);
1101 /// printBasicBlock - This member is called for each basic block in a method.
1103 void AssemblyWriter::printBasicBlock(const BasicBlock *BB) {
1104 if (BB->hasName()) { // Print out the label if it exists...
1105 Out << "\n" << getLLVMName(BB->getName(), LabelPrefix) << ':';
1106 } else if (!BB->use_empty()) { // Don't print block # of no uses...
1107 Out << "\n; <label>:";
1108 int Slot = Machine.getLocalSlot(BB);
1115 if (BB->getParent() == 0)
1116 Out << "\t\t; Error: Block without parent!";
1118 if (BB != &BB->getParent()->getEntryBlock()) { // Not the entry block?
1119 // Output predecessors for the block...
1121 pred_const_iterator PI = pred_begin(BB), PE = pred_end(BB);
1124 Out << " No predecessors!";
1127 writeOperand(*PI, false);
1128 for (++PI; PI != PE; ++PI) {
1130 writeOperand(*PI, false);
1138 if (AnnotationWriter) AnnotationWriter->emitBasicBlockStartAnnot(BB, Out);
1140 // Output all of the instructions in the basic block...
1141 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I != E; ++I)
1142 printInstruction(*I);
1144 if (AnnotationWriter) AnnotationWriter->emitBasicBlockEndAnnot(BB, Out);
1148 /// printInfoComment - Print a little comment after the instruction indicating
1149 /// which slot it occupies.
1151 void AssemblyWriter::printInfoComment(const Value &V) {
1152 if (V.getType() != Type::VoidTy) {
1154 printType(V.getType()) << '>';
1158 if (const GlobalValue *GV = dyn_cast<GlobalValue>(&V))
1159 SlotNum = Machine.getGlobalSlot(GV);
1161 SlotNum = Machine.getLocalSlot(&V);
1165 Out << ':' << SlotNum; // Print out the def slot taken.
1167 Out << " [#uses=" << V.getNumUses() << ']'; // Output # uses
1171 // This member is called for each Instruction in a function..
1172 void AssemblyWriter::printInstruction(const Instruction &I) {
1173 if (AnnotationWriter) AnnotationWriter->emitInstructionAnnot(&I, Out);
1177 // Print out name if it exists...
1179 Out << getLLVMName(I.getName(), LocalPrefix) << " = ";
1181 // If this is a volatile load or store, print out the volatile marker.
1182 if ((isa<LoadInst>(I) && cast<LoadInst>(I).isVolatile()) ||
1183 (isa<StoreInst>(I) && cast<StoreInst>(I).isVolatile())) {
1185 } else if (isa<CallInst>(I) && cast<CallInst>(I).isTailCall()) {
1186 // If this is a call, check if it's a tail call.
1190 // Print out the opcode...
1191 Out << I.getOpcodeName();
1193 // Print out the compare instruction predicates
1194 if (const FCmpInst *FCI = dyn_cast<FCmpInst>(&I)) {
1195 Out << " " << getPredicateText(FCI->getPredicate());
1196 } else if (const ICmpInst *ICI = dyn_cast<ICmpInst>(&I)) {
1197 Out << " " << getPredicateText(ICI->getPredicate());
1200 // Print out the type of the operands...
1201 const Value *Operand = I.getNumOperands() ? I.getOperand(0) : 0;
1203 // Special case conditional branches to swizzle the condition out to the front
1204 if (isa<BranchInst>(I) && I.getNumOperands() > 1) {
1205 writeOperand(I.getOperand(2), true);
1207 writeOperand(Operand, true);
1209 writeOperand(I.getOperand(1), true);
1211 } else if (isa<SwitchInst>(I)) {
1212 // Special case switch statement to get formatting nice and correct...
1213 writeOperand(Operand , true); Out << ',';
1214 writeOperand(I.getOperand(1), true); Out << " [";
1216 for (unsigned op = 2, Eop = I.getNumOperands(); op < Eop; op += 2) {
1218 writeOperand(I.getOperand(op ), true); Out << ',';
1219 writeOperand(I.getOperand(op+1), true);
1222 } else if (isa<PHINode>(I)) {
1224 printType(I.getType());
1227 for (unsigned op = 0, Eop = I.getNumOperands(); op < Eop; op += 2) {
1228 if (op) Out << ", ";
1230 writeOperand(I.getOperand(op ), false); Out << ',';
1231 writeOperand(I.getOperand(op+1), false); Out << " ]";
1233 } else if (isa<ReturnInst>(I) && !Operand) {
1235 } else if (const CallInst *CI = dyn_cast<CallInst>(&I)) {
1236 // Print the calling convention being used.
1237 switch (CI->getCallingConv()) {
1238 case CallingConv::C: break; // default
1239 case CallingConv::Fast: Out << " fastcc"; break;
1240 case CallingConv::Cold: Out << " coldcc"; break;
1241 case CallingConv::X86_StdCall: Out << "x86_stdcallcc "; break;
1242 case CallingConv::X86_FastCall: Out << "x86_fastcallcc "; break;
1243 default: Out << " cc" << CI->getCallingConv(); break;
1246 const PointerType *PTy = cast<PointerType>(Operand->getType());
1247 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
1248 const Type *RetTy = FTy->getReturnType();
1249 const ParamAttrsList *PAL = FTy->getParamAttrs();
1251 // If possible, print out the short form of the call instruction. We can
1252 // only do this if the first argument is a pointer to a nonvararg function,
1253 // and if the return type is not a pointer to a function.
1255 if (!FTy->isVarArg() &&
1256 (!isa<PointerType>(RetTy) ||
1257 !isa<FunctionType>(cast<PointerType>(RetTy)->getElementType()))) {
1258 Out << ' '; printType(RetTy);
1259 writeOperand(Operand, false);
1261 writeOperand(Operand, true);
1264 for (unsigned op = 1, Eop = I.getNumOperands(); op < Eop; ++op) {
1267 writeOperand(I.getOperand(op), true);
1268 if (PAL && PAL->getParamAttrs(op) != ParamAttr::None)
1269 Out << " " << PAL->getParamAttrsTextByIndex(op);
1272 if (PAL && PAL->getParamAttrs(0) != ParamAttr::None)
1273 Out << ' ' << PAL->getParamAttrsTextByIndex(0);
1274 } else if (const InvokeInst *II = dyn_cast<InvokeInst>(&I)) {
1275 const PointerType *PTy = cast<PointerType>(Operand->getType());
1276 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
1277 const Type *RetTy = FTy->getReturnType();
1278 const ParamAttrsList *PAL = FTy->getParamAttrs();
1280 // Print the calling convention being used.
1281 switch (II->getCallingConv()) {
1282 case CallingConv::C: break; // default
1283 case CallingConv::Fast: Out << " fastcc"; break;
1284 case CallingConv::Cold: Out << " coldcc"; break;
1285 case CallingConv::X86_StdCall: Out << "x86_stdcallcc "; break;
1286 case CallingConv::X86_FastCall: Out << "x86_fastcallcc "; break;
1287 default: Out << " cc" << II->getCallingConv(); break;
1290 // If possible, print out the short form of the invoke instruction. We can
1291 // only do this if the first argument is a pointer to a nonvararg function,
1292 // and if the return type is not a pointer to a function.
1294 if (!FTy->isVarArg() &&
1295 (!isa<PointerType>(RetTy) ||
1296 !isa<FunctionType>(cast<PointerType>(RetTy)->getElementType()))) {
1297 Out << ' '; printType(RetTy);
1298 writeOperand(Operand, false);
1300 writeOperand(Operand, true);
1304 for (unsigned op = 3, Eop = I.getNumOperands(); op < Eop; ++op) {
1307 writeOperand(I.getOperand(op), true);
1308 if (PAL && PAL->getParamAttrs(op-2) != ParamAttr::None)
1309 Out << " " << PAL->getParamAttrsTextByIndex(op-2);
1313 if (PAL && PAL->getParamAttrs(0) != ParamAttr::None)
1314 Out << " " << PAL->getParamAttrsTextByIndex(0);
1315 Out << "\n\t\t\tto";
1316 writeOperand(II->getNormalDest(), true);
1318 writeOperand(II->getUnwindDest(), true);
1320 } else if (const AllocationInst *AI = dyn_cast<AllocationInst>(&I)) {
1322 printType(AI->getType()->getElementType());
1323 if (AI->isArrayAllocation()) {
1325 writeOperand(AI->getArraySize(), true);
1327 if (AI->getAlignment()) {
1328 Out << ", align " << AI->getAlignment();
1330 } else if (isa<CastInst>(I)) {
1331 if (Operand) writeOperand(Operand, true); // Work with broken code
1333 printType(I.getType());
1334 } else if (isa<VAArgInst>(I)) {
1335 if (Operand) writeOperand(Operand, true); // Work with broken code
1337 printType(I.getType());
1338 } else if (Operand) { // Print the normal way...
1340 // PrintAllTypes - Instructions who have operands of all the same type
1341 // omit the type from all but the first operand. If the instruction has
1342 // different type operands (for example br), then they are all printed.
1343 bool PrintAllTypes = false;
1344 const Type *TheType = Operand->getType();
1346 // Select, Store and ShuffleVector always print all types.
1347 if (isa<SelectInst>(I) || isa<StoreInst>(I) || isa<ShuffleVectorInst>(I)) {
1348 PrintAllTypes = true;
1350 for (unsigned i = 1, E = I.getNumOperands(); i != E; ++i) {
1351 Operand = I.getOperand(i);
1352 if (Operand->getType() != TheType) {
1353 PrintAllTypes = true; // We have differing types! Print them all!
1359 if (!PrintAllTypes) {
1364 for (unsigned i = 0, E = I.getNumOperands(); i != E; ++i) {
1366 writeOperand(I.getOperand(i), PrintAllTypes);
1370 // Print post operand alignment for load/store
1371 if (isa<LoadInst>(I) && cast<LoadInst>(I).getAlignment()) {
1372 Out << ", align " << cast<LoadInst>(I).getAlignment();
1373 } else if (isa<StoreInst>(I) && cast<StoreInst>(I).getAlignment()) {
1374 Out << ", align " << cast<StoreInst>(I).getAlignment();
1377 printInfoComment(I);
1382 //===----------------------------------------------------------------------===//
1383 // External Interface declarations
1384 //===----------------------------------------------------------------------===//
1386 void Module::print(std::ostream &o, AssemblyAnnotationWriter *AAW) const {
1387 SlotMachine SlotTable(this);
1388 AssemblyWriter W(o, SlotTable, this, AAW);
1392 void GlobalVariable::print(std::ostream &o) const {
1393 SlotMachine SlotTable(getParent());
1394 AssemblyWriter W(o, SlotTable, getParent(), 0);
1398 void GlobalAlias::print(std::ostream &o) const {
1399 SlotMachine SlotTable(getParent());
1400 AssemblyWriter W(o, SlotTable, getParent(), 0);
1404 void Function::print(std::ostream &o, AssemblyAnnotationWriter *AAW) const {
1405 SlotMachine SlotTable(getParent());
1406 AssemblyWriter W(o, SlotTable, getParent(), AAW);
1411 void InlineAsm::print(std::ostream &o, AssemblyAnnotationWriter *AAW) const {
1412 WriteAsOperand(o, this, true, 0);
1415 void BasicBlock::print(std::ostream &o, AssemblyAnnotationWriter *AAW) const {
1416 SlotMachine SlotTable(getParent());
1417 AssemblyWriter W(o, SlotTable,
1418 getParent() ? getParent()->getParent() : 0, AAW);
1422 void Instruction::print(std::ostream &o, AssemblyAnnotationWriter *AAW) const {
1423 const Function *F = getParent() ? getParent()->getParent() : 0;
1424 SlotMachine SlotTable(F);
1425 AssemblyWriter W(o, SlotTable, F ? F->getParent() : 0, AAW);
1430 void Constant::print(std::ostream &o) const {
1431 if (this == 0) { o << "<null> constant value\n"; return; }
1433 o << ' ' << getType()->getDescription() << ' ';
1435 std::map<const Type *, std::string> TypeTable;
1436 WriteConstantInt(o, this, TypeTable, 0);
1439 void Type::print(std::ostream &o) const {
1443 o << getDescription();
1446 void Argument::print(std::ostream &o) const {
1447 WriteAsOperand(o, this, true, getParent() ? getParent()->getParent() : 0);
1450 // Value::dump - allow easy printing of Values from the debugger.
1451 // Located here because so much of the needed functionality is here.
1452 void Value::dump() const { print(*cerr.stream()); cerr << '\n'; }
1454 // Type::dump - allow easy printing of Values from the debugger.
1455 // Located here because so much of the needed functionality is here.
1456 void Type::dump() const { print(*cerr.stream()); cerr << '\n'; }
1459 ParamAttrsList::dump() const {
1461 for (unsigned i = 0; i < attrs.size(); ++i) {
1462 uint16_t index = getParamIndex(i);
1463 uint16_t attrs = getParamAttrs(index);
1464 cerr << "{" << index << "," << attrs << "} ";
1469 //===----------------------------------------------------------------------===//
1470 // SlotMachine Implementation
1471 //===----------------------------------------------------------------------===//
1474 #define SC_DEBUG(X) cerr << X
1479 // Module level constructor. Causes the contents of the Module (sans functions)
1480 // to be added to the slot table.
1481 SlotMachine::SlotMachine(const Module *M)
1482 : TheModule(M) ///< Saved for lazy initialization.
1484 , FunctionProcessed(false)
1485 , mMap(), mNext(0), fMap(), fNext(0)
1489 // Function level constructor. Causes the contents of the Module and the one
1490 // function provided to be added to the slot table.
1491 SlotMachine::SlotMachine(const Function *F)
1492 : TheModule(F ? F->getParent() : 0) ///< Saved for lazy initialization
1493 , TheFunction(F) ///< Saved for lazy initialization
1494 , FunctionProcessed(false)
1495 , mMap(), mNext(0), fMap(), fNext(0)
1499 inline void SlotMachine::initialize() {
1502 TheModule = 0; ///< Prevent re-processing next time we're called.
1504 if (TheFunction && !FunctionProcessed)
1508 // Iterate through all the global variables, functions, and global
1509 // variable initializers and create slots for them.
1510 void SlotMachine::processModule() {
1511 SC_DEBUG("begin processModule!\n");
1513 // Add all of the unnamed global variables to the value table.
1514 for (Module::const_global_iterator I = TheModule->global_begin(),
1515 E = TheModule->global_end(); I != E; ++I)
1517 CreateModuleSlot(I);
1519 // Add all the unnamed functions to the table.
1520 for (Module::const_iterator I = TheModule->begin(), E = TheModule->end();
1523 CreateModuleSlot(I);
1525 SC_DEBUG("end processModule!\n");
1529 // Process the arguments, basic blocks, and instructions of a function.
1530 void SlotMachine::processFunction() {
1531 SC_DEBUG("begin processFunction!\n");
1534 // Add all the function arguments with no names.
1535 for(Function::const_arg_iterator AI = TheFunction->arg_begin(),
1536 AE = TheFunction->arg_end(); AI != AE; ++AI)
1538 CreateFunctionSlot(AI);
1540 SC_DEBUG("Inserting Instructions:\n");
1542 // Add all of the basic blocks and instructions with no names.
1543 for (Function::const_iterator BB = TheFunction->begin(),
1544 E = TheFunction->end(); BB != E; ++BB) {
1546 CreateFunctionSlot(BB);
1547 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I != E; ++I)
1548 if (I->getType() != Type::VoidTy && !I->hasName())
1549 CreateFunctionSlot(I);
1552 FunctionProcessed = true;
1554 SC_DEBUG("end processFunction!\n");
1557 /// Clean up after incorporating a function. This is the only way to get out of
1558 /// the function incorporation state that affects get*Slot/Create*Slot. Function
1559 /// incorporation state is indicated by TheFunction != 0.
1560 void SlotMachine::purgeFunction() {
1561 SC_DEBUG("begin purgeFunction!\n");
1562 fMap.clear(); // Simply discard the function level map
1564 FunctionProcessed = false;
1565 SC_DEBUG("end purgeFunction!\n");
1568 /// getGlobalSlot - Get the slot number of a global value.
1569 int SlotMachine::getGlobalSlot(const GlobalValue *V) {
1570 // Check for uninitialized state and do lazy initialization.
1573 // Find the type plane in the module map
1574 ValueMap::const_iterator MI = mMap.find(V);
1575 if (MI == mMap.end()) return -1;
1581 /// getLocalSlot - Get the slot number for a value that is local to a function.
1582 int SlotMachine::getLocalSlot(const Value *V) {
1583 assert(!isa<Constant>(V) && "Can't get a constant or global slot with this!");
1585 // Check for uninitialized state and do lazy initialization.
1588 ValueMap::const_iterator FI = fMap.find(V);
1589 if (FI == fMap.end()) return -1;
1595 /// CreateModuleSlot - Insert the specified GlobalValue* into the slot table.
1596 void SlotMachine::CreateModuleSlot(const GlobalValue *V) {
1597 assert(V && "Can't insert a null Value into SlotMachine!");
1598 assert(V->getType() != Type::VoidTy && "Doesn't need a slot!");
1599 assert(!V->hasName() && "Doesn't need a slot!");
1601 unsigned DestSlot = mNext++;
1604 SC_DEBUG(" Inserting value [" << V->getType() << "] = " << V << " slot=" <<
1606 // G = Global, F = Function, A = Alias, o = other
1607 SC_DEBUG((isa<GlobalVariable>(V) ? 'G' :
1608 (isa<Function> ? 'F' :
1609 (isa<GlobalAlias> ? 'A' : 'o'))) << "]\n");
1613 /// CreateSlot - Create a new slot for the specified value if it has no name.
1614 void SlotMachine::CreateFunctionSlot(const Value *V) {
1615 const Type *VTy = V->getType();
1616 assert(VTy != Type::VoidTy && !V->hasName() && "Doesn't need a slot!");
1618 unsigned DestSlot = fNext++;
1621 // G = Global, F = Function, o = other
1622 SC_DEBUG(" Inserting value [" << VTy << "] = " << V << " slot=" <<
1623 DestSlot << " [o]\n");