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 static RegisterPass<PrintModulePass>
139 X("printm", "Print module to stderr");
140 static RegisterPass<PrintFunctionPass>
141 Y("print","Print function to stderr");
143 static void WriteAsOperandInternal(std::ostream &Out, const Value *V,
144 std::map<const Type *, std::string> &TypeTable,
145 SlotMachine *Machine);
147 static const Module *getModuleFromVal(const Value *V) {
148 if (const Argument *MA = dyn_cast<Argument>(V))
149 return MA->getParent() ? MA->getParent()->getParent() : 0;
150 else if (const BasicBlock *BB = dyn_cast<BasicBlock>(V))
151 return BB->getParent() ? BB->getParent()->getParent() : 0;
152 else if (const Instruction *I = dyn_cast<Instruction>(V)) {
153 const Function *M = I->getParent() ? I->getParent()->getParent() : 0;
154 return M ? M->getParent() : 0;
155 } else if (const GlobalValue *GV = dyn_cast<GlobalValue>(V))
156 return GV->getParent();
160 static SlotMachine *createSlotMachine(const Value *V) {
161 if (const Argument *FA = dyn_cast<Argument>(V)) {
162 return new SlotMachine(FA->getParent());
163 } else if (const Instruction *I = dyn_cast<Instruction>(V)) {
164 return new SlotMachine(I->getParent()->getParent());
165 } else if (const BasicBlock *BB = dyn_cast<BasicBlock>(V)) {
166 return new SlotMachine(BB->getParent());
167 } else if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(V)){
168 return new SlotMachine(GV->getParent());
169 } else if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(V)){
170 return new SlotMachine(GA->getParent());
171 } else if (const Function *Func = dyn_cast<Function>(V)) {
172 return new SlotMachine(Func);
177 /// NameNeedsQuotes - Return true if the specified llvm name should be wrapped
179 static bool NameNeedsQuotes(const std::string &Name) {
180 if (Name[0] >= '0' && Name[0] <= '9') return true;
181 // Scan to see if we have any characters that are not on the "white list"
182 for (unsigned i = 0, e = Name.size(); i != e; ++i) {
184 assert(C != '"' && "Illegal character in LLVM value name!");
185 if ((C < 'a' || C > 'z') && (C < 'A' || C > 'Z') && (C < '0' || C > '9') &&
186 C != '-' && C != '.' && C != '_')
198 /// getLLVMName - Turn the specified string into an 'LLVM name', which is either
199 /// prefixed with % (if the string only contains simple characters) or is
200 /// surrounded with ""'s (if it has special chars in it).
201 static std::string getLLVMName(const std::string &Name, PrefixType Prefix) {
202 assert(!Name.empty() && "Cannot get empty name!");
204 // First character cannot start with a number...
205 if (NameNeedsQuotes(Name)) {
206 if (Prefix == GlobalPrefix)
207 return "@\"" + Name + "\"";
208 return "\"" + Name + "\"";
211 // If we get here, then the identifier is legal to use as a "VarID".
213 default: assert(0 && "Bad prefix!");
214 case GlobalPrefix: return '@' + Name;
215 case LabelPrefix: return Name;
216 case LocalPrefix: return '%' + Name;
221 /// fillTypeNameTable - If the module has a symbol table, take all global types
222 /// and stuff their names into the TypeNames map.
224 static void fillTypeNameTable(const Module *M,
225 std::map<const Type *, std::string> &TypeNames) {
227 const TypeSymbolTable &ST = M->getTypeSymbolTable();
228 TypeSymbolTable::const_iterator TI = ST.begin();
229 for (; TI != ST.end(); ++TI) {
230 // As a heuristic, don't insert pointer to primitive types, because
231 // they are used too often to have a single useful name.
233 const Type *Ty = cast<Type>(TI->second);
234 if (!isa<PointerType>(Ty) ||
235 !cast<PointerType>(Ty)->getElementType()->isPrimitiveType() ||
236 !cast<PointerType>(Ty)->getElementType()->isInteger() ||
237 isa<OpaqueType>(cast<PointerType>(Ty)->getElementType()))
238 TypeNames.insert(std::make_pair(Ty, getLLVMName(TI->first, LocalPrefix)));
244 static void calcTypeName(const Type *Ty,
245 std::vector<const Type *> &TypeStack,
246 std::map<const Type *, std::string> &TypeNames,
247 std::string & Result){
248 if (Ty->isInteger() || (Ty->isPrimitiveType() && !isa<OpaqueType>(Ty))) {
249 Result += Ty->getDescription(); // Base case
253 // Check to see if the type is named.
254 std::map<const Type *, std::string>::iterator I = TypeNames.find(Ty);
255 if (I != TypeNames.end()) {
260 if (isa<OpaqueType>(Ty)) {
265 // Check to see if the Type is already on the stack...
266 unsigned Slot = 0, CurSize = TypeStack.size();
267 while (Slot < CurSize && TypeStack[Slot] != Ty) ++Slot; // Scan for type
269 // This is another base case for the recursion. In this case, we know
270 // that we have looped back to a type that we have previously visited.
271 // Generate the appropriate upreference to handle this.
272 if (Slot < CurSize) {
273 Result += "\\" + utostr(CurSize-Slot); // Here's the upreference
277 TypeStack.push_back(Ty); // Recursive case: Add us to the stack..
279 switch (Ty->getTypeID()) {
280 case Type::IntegerTyID: {
281 unsigned BitWidth = cast<IntegerType>(Ty)->getBitWidth();
282 Result += "i" + utostr(BitWidth);
285 case Type::FunctionTyID: {
286 const FunctionType *FTy = cast<FunctionType>(Ty);
287 calcTypeName(FTy->getReturnType(), TypeStack, TypeNames, Result);
290 const ParamAttrsList *Attrs = FTy->getParamAttrs();
291 for (FunctionType::param_iterator I = FTy->param_begin(),
292 E = FTy->param_end(); I != E; ++I) {
293 if (I != FTy->param_begin())
295 calcTypeName(*I, TypeStack, TypeNames, Result);
296 if (Attrs && Attrs->getParamAttrs(Idx) != ParamAttr::None) {
298 Result += Attrs->getParamAttrsTextByIndex(Idx);
302 if (FTy->isVarArg()) {
303 if (FTy->getNumParams()) Result += ", ";
307 if (Attrs && Attrs->getParamAttrs(0) != ParamAttr::None) {
309 Result += Attrs->getParamAttrsTextByIndex(0);
313 case Type::StructTyID: {
314 const StructType *STy = cast<StructType>(Ty);
318 for (StructType::element_iterator I = STy->element_begin(),
319 E = STy->element_end(); I != E; ++I) {
320 if (I != STy->element_begin())
322 calcTypeName(*I, TypeStack, TypeNames, Result);
329 case Type::PointerTyID:
330 calcTypeName(cast<PointerType>(Ty)->getElementType(),
331 TypeStack, TypeNames, Result);
334 case Type::ArrayTyID: {
335 const ArrayType *ATy = cast<ArrayType>(Ty);
336 Result += "[" + utostr(ATy->getNumElements()) + " x ";
337 calcTypeName(ATy->getElementType(), TypeStack, TypeNames, Result);
341 case Type::VectorTyID: {
342 const VectorType *PTy = cast<VectorType>(Ty);
343 Result += "<" + utostr(PTy->getNumElements()) + " x ";
344 calcTypeName(PTy->getElementType(), TypeStack, TypeNames, Result);
348 case Type::OpaqueTyID:
352 Result += "<unrecognized-type>";
356 TypeStack.pop_back(); // Remove self from stack...
360 /// printTypeInt - The internal guts of printing out a type that has a
361 /// potentially named portion.
363 static std::ostream &printTypeInt(std::ostream &Out, const Type *Ty,
364 std::map<const Type *, std::string> &TypeNames) {
365 // Primitive types always print out their description, regardless of whether
366 // they have been named or not.
368 if (Ty->isInteger() || (Ty->isPrimitiveType() && !isa<OpaqueType>(Ty)))
369 return Out << Ty->getDescription();
371 // Check to see if the type is named.
372 std::map<const Type *, std::string>::iterator I = TypeNames.find(Ty);
373 if (I != TypeNames.end()) return Out << I->second;
375 // Otherwise we have a type that has not been named but is a derived type.
376 // Carefully recurse the type hierarchy to print out any contained symbolic
379 std::vector<const Type *> TypeStack;
380 std::string TypeName;
381 calcTypeName(Ty, TypeStack, TypeNames, TypeName);
382 TypeNames.insert(std::make_pair(Ty, TypeName));//Cache type name for later use
383 return (Out << TypeName);
387 /// WriteTypeSymbolic - This attempts to write the specified type as a symbolic
388 /// type, iff there is an entry in the modules symbol table for the specified
389 /// type or one of it's component types. This is slower than a simple x << Type
391 std::ostream &llvm::WriteTypeSymbolic(std::ostream &Out, const Type *Ty,
395 // If they want us to print out a type, but there is no context, we can't
396 // print it symbolically.
398 return Out << Ty->getDescription();
400 std::map<const Type *, std::string> TypeNames;
401 fillTypeNameTable(M, TypeNames);
402 return printTypeInt(Out, Ty, TypeNames);
405 // PrintEscapedString - Print each character of the specified string, escaping
406 // it if it is not printable or if it is an escape char.
407 static void PrintEscapedString(const std::string &Str, std::ostream &Out) {
408 for (unsigned i = 0, e = Str.size(); i != e; ++i) {
409 unsigned char C = Str[i];
410 if (isprint(C) && C != '"' && C != '\\') {
414 << (char) ((C/16 < 10) ? ( C/16 +'0') : ( C/16 -10+'A'))
415 << (char)(((C&15) < 10) ? ((C&15)+'0') : ((C&15)-10+'A'));
420 static const char *getPredicateText(unsigned predicate) {
421 const char * pred = "unknown";
423 case FCmpInst::FCMP_FALSE: pred = "false"; break;
424 case FCmpInst::FCMP_OEQ: pred = "oeq"; break;
425 case FCmpInst::FCMP_OGT: pred = "ogt"; break;
426 case FCmpInst::FCMP_OGE: pred = "oge"; break;
427 case FCmpInst::FCMP_OLT: pred = "olt"; break;
428 case FCmpInst::FCMP_OLE: pred = "ole"; break;
429 case FCmpInst::FCMP_ONE: pred = "one"; break;
430 case FCmpInst::FCMP_ORD: pred = "ord"; break;
431 case FCmpInst::FCMP_UNO: pred = "uno"; break;
432 case FCmpInst::FCMP_UEQ: pred = "ueq"; break;
433 case FCmpInst::FCMP_UGT: pred = "ugt"; break;
434 case FCmpInst::FCMP_UGE: pred = "uge"; break;
435 case FCmpInst::FCMP_ULT: pred = "ult"; break;
436 case FCmpInst::FCMP_ULE: pred = "ule"; break;
437 case FCmpInst::FCMP_UNE: pred = "une"; break;
438 case FCmpInst::FCMP_TRUE: pred = "true"; break;
439 case ICmpInst::ICMP_EQ: pred = "eq"; break;
440 case ICmpInst::ICMP_NE: pred = "ne"; break;
441 case ICmpInst::ICMP_SGT: pred = "sgt"; break;
442 case ICmpInst::ICMP_SGE: pred = "sge"; break;
443 case ICmpInst::ICMP_SLT: pred = "slt"; break;
444 case ICmpInst::ICMP_SLE: pred = "sle"; break;
445 case ICmpInst::ICMP_UGT: pred = "ugt"; break;
446 case ICmpInst::ICMP_UGE: pred = "uge"; break;
447 case ICmpInst::ICMP_ULT: pred = "ult"; break;
448 case ICmpInst::ICMP_ULE: pred = "ule"; break;
453 /// @brief Internal constant writer.
454 static void WriteConstantInt(std::ostream &Out, const Constant *CV,
455 std::map<const Type *, std::string> &TypeTable,
456 SlotMachine *Machine) {
457 const int IndentSize = 4;
458 static std::string Indent = "\n";
459 if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV)) {
460 if (CI->getType() == Type::Int1Ty)
461 Out << (CI->getZExtValue() ? "true" : "false");
463 Out << CI->getValue().toStringSigned(10);
464 } else if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CV)) {
465 // We would like to output the FP constant value in exponential notation,
466 // but we cannot do this if doing so will lose precision. Check here to
467 // make sure that we only output it in exponential format if we can parse
468 // the value back and get the same value.
470 std::string StrVal = ftostr(CFP->getValue());
472 // Check to make sure that the stringized number is not some string like
473 // "Inf" or NaN, that atof will accept, but the lexer will not. Check that
474 // the string matches the "[-+]?[0-9]" regex.
476 if ((StrVal[0] >= '0' && StrVal[0] <= '9') ||
477 ((StrVal[0] == '-' || StrVal[0] == '+') &&
478 (StrVal[1] >= '0' && StrVal[1] <= '9')))
479 // Reparse stringized version!
480 if (atof(StrVal.c_str()) == CFP->getValue()) {
485 // Otherwise we could not reparse it to exactly the same value, so we must
486 // output the string in hexadecimal format!
487 assert(sizeof(double) == sizeof(uint64_t) &&
488 "assuming that double is 64 bits!");
489 Out << "0x" << utohexstr(DoubleToBits(CFP->getValue()));
491 } else if (isa<ConstantAggregateZero>(CV)) {
492 Out << "zeroinitializer";
493 } else if (const ConstantArray *CA = dyn_cast<ConstantArray>(CV)) {
494 // As a special case, print the array as a string if it is an array of
495 // ubytes or an array of sbytes with positive values.
497 const Type *ETy = CA->getType()->getElementType();
498 if (CA->isString()) {
500 PrintEscapedString(CA->getAsString(), Out);
503 } else { // Cannot output in string format...
505 if (CA->getNumOperands()) {
507 printTypeInt(Out, ETy, TypeTable);
508 WriteAsOperandInternal(Out, CA->getOperand(0),
510 for (unsigned i = 1, e = CA->getNumOperands(); i != e; ++i) {
512 printTypeInt(Out, ETy, TypeTable);
513 WriteAsOperandInternal(Out, CA->getOperand(i), TypeTable, Machine);
518 } else if (const ConstantStruct *CS = dyn_cast<ConstantStruct>(CV)) {
519 if (CS->getType()->isPacked())
522 unsigned N = CS->getNumOperands();
525 Indent += std::string(IndentSize, ' ');
530 printTypeInt(Out, CS->getOperand(0)->getType(), TypeTable);
532 WriteAsOperandInternal(Out, CS->getOperand(0), TypeTable, Machine);
534 for (unsigned i = 1; i < N; i++) {
536 if (N > 2) Out << Indent;
537 printTypeInt(Out, CS->getOperand(i)->getType(), TypeTable);
539 WriteAsOperandInternal(Out, CS->getOperand(i), TypeTable, Machine);
541 if (N > 2) Indent.resize(Indent.size() - IndentSize);
545 if (CS->getType()->isPacked())
547 } else if (const ConstantVector *CP = dyn_cast<ConstantVector>(CV)) {
548 const Type *ETy = CP->getType()->getElementType();
549 assert(CP->getNumOperands() > 0 &&
550 "Number of operands for a PackedConst must be > 0");
553 printTypeInt(Out, ETy, TypeTable);
554 WriteAsOperandInternal(Out, CP->getOperand(0), TypeTable, Machine);
555 for (unsigned i = 1, e = CP->getNumOperands(); i != e; ++i) {
557 printTypeInt(Out, ETy, TypeTable);
558 WriteAsOperandInternal(Out, CP->getOperand(i), TypeTable, Machine);
561 } else if (isa<ConstantPointerNull>(CV)) {
564 } else if (isa<UndefValue>(CV)) {
567 } else if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV)) {
568 Out << CE->getOpcodeName();
570 Out << " " << getPredicateText(CE->getPredicate());
573 for (User::const_op_iterator OI=CE->op_begin(); OI != CE->op_end(); ++OI) {
574 printTypeInt(Out, (*OI)->getType(), TypeTable);
575 WriteAsOperandInternal(Out, *OI, TypeTable, Machine);
576 if (OI+1 != CE->op_end())
582 printTypeInt(Out, CE->getType(), TypeTable);
588 Out << "<placeholder or erroneous Constant>";
593 /// WriteAsOperand - Write the name of the specified value out to the specified
594 /// ostream. This can be useful when you just want to print int %reg126, not
595 /// the whole instruction that generated it.
597 static void WriteAsOperandInternal(std::ostream &Out, const Value *V,
598 std::map<const Type*, std::string> &TypeTable,
599 SlotMachine *Machine) {
602 Out << getLLVMName(V->getName(),
603 isa<GlobalValue>(V) ? GlobalPrefix : LocalPrefix);
605 const Constant *CV = dyn_cast<Constant>(V);
606 if (CV && !isa<GlobalValue>(CV)) {
607 WriteConstantInt(Out, CV, TypeTable, Machine);
608 } else if (const InlineAsm *IA = dyn_cast<InlineAsm>(V)) {
610 if (IA->hasSideEffects())
611 Out << "sideeffect ";
613 PrintEscapedString(IA->getAsmString(), Out);
615 PrintEscapedString(IA->getConstraintString(), Out);
621 if (const GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
622 Slot = Machine->getGlobalSlot(GV);
625 Slot = Machine->getLocalSlot(V);
628 Machine = createSlotMachine(V);
630 if (const GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
631 Slot = Machine->getGlobalSlot(GV);
634 Slot = Machine->getLocalSlot(V);
642 Out << Prefix << Slot;
649 /// WriteAsOperand - Write the name of the specified value out to the specified
650 /// ostream. This can be useful when you just want to print int %reg126, not
651 /// the whole instruction that generated it.
653 std::ostream &llvm::WriteAsOperand(std::ostream &Out, const Value *V,
654 bool PrintType, const Module *Context) {
655 std::map<const Type *, std::string> TypeNames;
656 if (Context == 0) Context = getModuleFromVal(V);
659 fillTypeNameTable(Context, TypeNames);
662 printTypeInt(Out, V->getType(), TypeNames);
664 WriteAsOperandInternal(Out, V, TypeNames, 0);
671 class AssemblyWriter {
673 SlotMachine &Machine;
674 const Module *TheModule;
675 std::map<const Type *, std::string> TypeNames;
676 AssemblyAnnotationWriter *AnnotationWriter;
678 inline AssemblyWriter(std::ostream &o, SlotMachine &Mac, const Module *M,
679 AssemblyAnnotationWriter *AAW)
680 : Out(o), Machine(Mac), TheModule(M), AnnotationWriter(AAW) {
682 // If the module has a symbol table, take all global types and stuff their
683 // names into the TypeNames map.
685 fillTypeNameTable(M, TypeNames);
688 inline void write(const Module *M) { printModule(M); }
689 inline void write(const GlobalVariable *G) { printGlobal(G); }
690 inline void write(const GlobalAlias *G) { printAlias(G); }
691 inline void write(const Function *F) { printFunction(F); }
692 inline void write(const BasicBlock *BB) { printBasicBlock(BB); }
693 inline void write(const Instruction *I) { printInstruction(*I); }
694 inline void write(const Type *Ty) { printType(Ty); }
696 void writeOperand(const Value *Op, bool PrintType);
698 const Module* getModule() { return TheModule; }
701 void printModule(const Module *M);
702 void printTypeSymbolTable(const TypeSymbolTable &ST);
703 void printGlobal(const GlobalVariable *GV);
704 void printAlias(const GlobalAlias *GV);
705 void printFunction(const Function *F);
706 void printArgument(const Argument *FA, uint16_t ParamAttrs);
707 void printBasicBlock(const BasicBlock *BB);
708 void printInstruction(const Instruction &I);
710 // printType - Go to extreme measures to attempt to print out a short,
711 // symbolic version of a type name.
713 std::ostream &printType(const Type *Ty) {
714 return printTypeInt(Out, Ty, TypeNames);
717 // printTypeAtLeastOneLevel - Print out one level of the possibly complex type
718 // without considering any symbolic types that we may have equal to it.
720 std::ostream &printTypeAtLeastOneLevel(const Type *Ty);
722 // printInfoComment - Print a little comment after the instruction indicating
723 // which slot it occupies.
724 void printInfoComment(const Value &V);
726 } // end of llvm namespace
728 /// printTypeAtLeastOneLevel - Print out one level of the possibly complex type
729 /// without considering any symbolic types that we may have equal to it.
731 std::ostream &AssemblyWriter::printTypeAtLeastOneLevel(const Type *Ty) {
732 if (const IntegerType *ITy = dyn_cast<IntegerType>(Ty))
733 Out << "i" << utostr(ITy->getBitWidth());
734 else if (const FunctionType *FTy = dyn_cast<FunctionType>(Ty)) {
735 printType(FTy->getReturnType());
738 const ParamAttrsList *Attrs = FTy->getParamAttrs();
739 for (FunctionType::param_iterator I = FTy->param_begin(),
740 E = FTy->param_end(); I != E; ++I) {
741 if (I != FTy->param_begin())
744 if (Attrs && Attrs->getParamAttrs(Idx) != ParamAttr::None) {
745 Out << " " << Attrs->getParamAttrsTextByIndex(Idx);
749 if (FTy->isVarArg()) {
750 if (FTy->getNumParams()) Out << ", ";
754 if (Attrs && Attrs->getParamAttrs(0) != ParamAttr::None)
755 Out << ' ' << Attrs->getParamAttrsTextByIndex(0);
756 } else if (const StructType *STy = dyn_cast<StructType>(Ty)) {
760 for (StructType::element_iterator I = STy->element_begin(),
761 E = STy->element_end(); I != E; ++I) {
762 if (I != STy->element_begin())
769 } else if (const PointerType *PTy = dyn_cast<PointerType>(Ty)) {
770 printType(PTy->getElementType()) << '*';
771 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
772 Out << '[' << ATy->getNumElements() << " x ";
773 printType(ATy->getElementType()) << ']';
774 } else if (const VectorType *PTy = dyn_cast<VectorType>(Ty)) {
775 Out << '<' << PTy->getNumElements() << " x ";
776 printType(PTy->getElementType()) << '>';
778 else if (isa<OpaqueType>(Ty)) {
781 if (!Ty->isPrimitiveType())
782 Out << "<unknown derived type>";
789 void AssemblyWriter::writeOperand(const Value *Operand, bool PrintType) {
791 Out << "<null operand!>";
793 if (PrintType) { Out << ' '; printType(Operand->getType()); }
794 WriteAsOperandInternal(Out, Operand, TypeNames, &Machine);
799 void AssemblyWriter::printModule(const Module *M) {
800 if (!M->getModuleIdentifier().empty() &&
801 // Don't print the ID if it will start a new line (which would
802 // require a comment char before it).
803 M->getModuleIdentifier().find('\n') == std::string::npos)
804 Out << "; ModuleID = '" << M->getModuleIdentifier() << "'\n";
806 if (!M->getDataLayout().empty())
807 Out << "target datalayout = \"" << M->getDataLayout() << "\"\n";
808 if (!M->getTargetTriple().empty())
809 Out << "target triple = \"" << M->getTargetTriple() << "\"\n";
811 if (!M->getModuleInlineAsm().empty()) {
812 // Split the string into lines, to make it easier to read the .ll file.
813 std::string Asm = M->getModuleInlineAsm();
815 size_t NewLine = Asm.find_first_of('\n', CurPos);
816 while (NewLine != std::string::npos) {
817 // We found a newline, print the portion of the asm string from the
818 // last newline up to this newline.
819 Out << "module asm \"";
820 PrintEscapedString(std::string(Asm.begin()+CurPos, Asm.begin()+NewLine),
824 NewLine = Asm.find_first_of('\n', CurPos);
826 Out << "module asm \"";
827 PrintEscapedString(std::string(Asm.begin()+CurPos, Asm.end()), Out);
831 // Loop over the dependent libraries and emit them.
832 Module::lib_iterator LI = M->lib_begin();
833 Module::lib_iterator LE = M->lib_end();
835 Out << "deplibs = [ ";
837 Out << '"' << *LI << '"';
845 // Loop over the symbol table, emitting all named constants.
846 printTypeSymbolTable(M->getTypeSymbolTable());
848 for (Module::const_global_iterator I = M->global_begin(), E = M->global_end();
852 // Output all aliases.
853 if (!M->alias_empty()) Out << "\n";
854 for (Module::const_alias_iterator I = M->alias_begin(), E = M->alias_end();
858 // Output all of the functions.
859 for (Module::const_iterator I = M->begin(), E = M->end(); I != E; ++I)
863 void AssemblyWriter::printGlobal(const GlobalVariable *GV) {
864 if (GV->hasName()) Out << getLLVMName(GV->getName(), GlobalPrefix) << " = ";
866 if (!GV->hasInitializer())
867 switch (GV->getLinkage()) {
868 case GlobalValue::DLLImportLinkage: Out << "dllimport "; break;
869 case GlobalValue::ExternalWeakLinkage: Out << "extern_weak "; break;
870 default: Out << "external "; break;
872 switch (GV->getLinkage()) {
873 case GlobalValue::InternalLinkage: Out << "internal "; break;
874 case GlobalValue::LinkOnceLinkage: Out << "linkonce "; break;
875 case GlobalValue::WeakLinkage: Out << "weak "; break;
876 case GlobalValue::AppendingLinkage: Out << "appending "; break;
877 case GlobalValue::DLLImportLinkage: Out << "dllimport "; break;
878 case GlobalValue::DLLExportLinkage: Out << "dllexport "; break;
879 case GlobalValue::ExternalWeakLinkage: Out << "extern_weak "; break;
880 case GlobalValue::ExternalLinkage: break;
881 case GlobalValue::GhostLinkage:
882 cerr << "GhostLinkage not allowed in AsmWriter!\n";
885 switch (GV->getVisibility()) {
886 default: assert(0 && "Invalid visibility style!");
887 case GlobalValue::DefaultVisibility: break;
888 case GlobalValue::HiddenVisibility: Out << "hidden "; break;
889 case GlobalValue::ProtectedVisibility: Out << "protected "; break;
893 if (GV->isThreadLocal()) Out << "thread_local ";
894 Out << (GV->isConstant() ? "constant " : "global ");
895 printType(GV->getType()->getElementType());
897 if (GV->hasInitializer()) {
898 Constant* C = cast<Constant>(GV->getInitializer());
899 assert(C && "GlobalVar initializer isn't constant?");
900 writeOperand(GV->getInitializer(), false);
903 if (GV->hasSection())
904 Out << ", section \"" << GV->getSection() << '"';
905 if (GV->getAlignment())
906 Out << ", align " << GV->getAlignment();
908 printInfoComment(*GV);
912 void AssemblyWriter::printAlias(const GlobalAlias *GA) {
913 Out << getLLVMName(GA->getName(), GlobalPrefix) << " = ";
914 switch (GA->getVisibility()) {
915 default: assert(0 && "Invalid visibility style!");
916 case GlobalValue::DefaultVisibility: break;
917 case GlobalValue::HiddenVisibility: Out << "hidden "; break;
918 case GlobalValue::ProtectedVisibility: Out << "protected "; break;
923 switch (GA->getLinkage()) {
924 case GlobalValue::WeakLinkage: Out << "weak "; break;
925 case GlobalValue::InternalLinkage: Out << "internal "; break;
926 case GlobalValue::ExternalLinkage: break;
928 assert(0 && "Invalid alias linkage");
931 const Constant *Aliasee = GA->getAliasee();
933 if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(Aliasee)) {
934 printType(GV->getType());
935 Out << " " << getLLVMName(GV->getName(), GlobalPrefix);
936 } else if (const Function *F = dyn_cast<Function>(Aliasee)) {
937 printType(F->getFunctionType());
940 if (!F->getName().empty())
941 Out << getLLVMName(F->getName(), GlobalPrefix);
945 const ConstantExpr *CE = 0;
946 if ((CE = dyn_cast<ConstantExpr>(Aliasee)) &&
947 (CE->getOpcode() == Instruction::BitCast)) {
948 writeOperand(CE, false);
950 assert(0 && "Unsupported aliasee");
953 printInfoComment(*GA);
957 void AssemblyWriter::printTypeSymbolTable(const TypeSymbolTable &ST) {
959 for (TypeSymbolTable::const_iterator TI = ST.begin(), TE = ST.end();
961 Out << "\t" << getLLVMName(TI->first, LocalPrefix) << " = type ";
963 // Make sure we print out at least one level of the type structure, so
964 // that we do not get %FILE = type %FILE
966 printTypeAtLeastOneLevel(TI->second) << "\n";
970 /// printFunction - Print all aspects of a function.
972 void AssemblyWriter::printFunction(const Function *F) {
973 // Print out the return type and name...
976 if (AnnotationWriter) AnnotationWriter->emitFunctionAnnot(F, Out);
978 if (F->isDeclaration())
979 switch (F->getLinkage()) {
980 case GlobalValue::DLLImportLinkage: Out << "declare dllimport "; break;
981 case GlobalValue::ExternalWeakLinkage: Out << "declare extern_weak "; break;
982 default: Out << "declare ";
986 switch (F->getLinkage()) {
987 case GlobalValue::InternalLinkage: Out << "internal "; break;
988 case GlobalValue::LinkOnceLinkage: Out << "linkonce "; break;
989 case GlobalValue::WeakLinkage: Out << "weak "; break;
990 case GlobalValue::AppendingLinkage: Out << "appending "; break;
991 case GlobalValue::DLLImportLinkage: Out << "dllimport "; break;
992 case GlobalValue::DLLExportLinkage: Out << "dllexport "; break;
993 case GlobalValue::ExternalWeakLinkage: Out << "extern_weak "; break;
994 case GlobalValue::ExternalLinkage: break;
995 case GlobalValue::GhostLinkage:
996 cerr << "GhostLinkage not allowed in AsmWriter!\n";
999 switch (F->getVisibility()) {
1000 default: assert(0 && "Invalid visibility style!");
1001 case GlobalValue::DefaultVisibility: break;
1002 case GlobalValue::HiddenVisibility: Out << "hidden "; break;
1003 case GlobalValue::ProtectedVisibility: Out << "protected "; break;
1007 // Print the calling convention.
1008 switch (F->getCallingConv()) {
1009 case CallingConv::C: break; // default
1010 case CallingConv::Fast: Out << "fastcc "; break;
1011 case CallingConv::Cold: Out << "coldcc "; break;
1012 case CallingConv::X86_StdCall: Out << "x86_stdcallcc "; break;
1013 case CallingConv::X86_FastCall: Out << "x86_fastcallcc "; break;
1014 default: Out << "cc" << F->getCallingConv() << " "; break;
1017 const FunctionType *FT = F->getFunctionType();
1018 const ParamAttrsList *Attrs = FT->getParamAttrs();
1019 printType(F->getReturnType()) << ' ';
1020 if (!F->getName().empty())
1021 Out << getLLVMName(F->getName(), GlobalPrefix);
1025 Machine.incorporateFunction(F);
1027 // Loop over the arguments, printing them...
1030 if (!F->isDeclaration()) {
1031 // If this isn't a declaration, print the argument names as well.
1032 for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
1034 // Insert commas as we go... the first arg doesn't get a comma
1035 if (I != F->arg_begin()) Out << ", ";
1036 printArgument(I, (Attrs ? Attrs->getParamAttrs(Idx)
1037 : uint16_t(ParamAttr::None)));
1041 // Otherwise, print the types from the function type.
1042 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
1043 // Insert commas as we go... the first arg doesn't get a comma
1047 printType(FT->getParamType(i));
1049 unsigned ArgAttrs = ParamAttr::None;
1050 if (Attrs) ArgAttrs = Attrs->getParamAttrs(i+1);
1051 if (ArgAttrs != ParamAttr::None)
1052 Out << ' ' << ParamAttrsList::getParamAttrsText(ArgAttrs);
1056 // Finish printing arguments...
1057 if (FT->isVarArg()) {
1058 if (FT->getNumParams()) Out << ", ";
1059 Out << "..."; // Output varargs portion of signature!
1062 if (Attrs && Attrs->getParamAttrs(0) != ParamAttr::None)
1063 Out << ' ' << Attrs->getParamAttrsTextByIndex(0);
1064 if (F->hasSection())
1065 Out << " section \"" << F->getSection() << '"';
1066 if (F->getAlignment())
1067 Out << " align " << F->getAlignment();
1069 if (F->isDeclaration()) {
1074 // Output all of its basic blocks... for the function
1075 for (Function::const_iterator I = F->begin(), E = F->end(); I != E; ++I)
1081 Machine.purgeFunction();
1084 /// printArgument - This member is called for every argument that is passed into
1085 /// the function. Simply print it out
1087 void AssemblyWriter::printArgument(const Argument *Arg, uint16_t Attrs) {
1089 printType(Arg->getType());
1091 if (Attrs != ParamAttr::None)
1092 Out << ' ' << ParamAttrsList::getParamAttrsText(Attrs);
1094 // Output name, if available...
1096 Out << ' ' << getLLVMName(Arg->getName(), LocalPrefix);
1099 /// printBasicBlock - This member is called for each basic block in a method.
1101 void AssemblyWriter::printBasicBlock(const BasicBlock *BB) {
1102 if (BB->hasName()) { // Print out the label if it exists...
1103 Out << "\n" << getLLVMName(BB->getName(), LabelPrefix) << ':';
1104 } else if (!BB->use_empty()) { // Don't print block # of no uses...
1105 Out << "\n; <label>:";
1106 int Slot = Machine.getLocalSlot(BB);
1113 if (BB->getParent() == 0)
1114 Out << "\t\t; Error: Block without parent!";
1116 if (BB != &BB->getParent()->getEntryBlock()) { // Not the entry block?
1117 // Output predecessors for the block...
1119 pred_const_iterator PI = pred_begin(BB), PE = pred_end(BB);
1122 Out << " No predecessors!";
1125 writeOperand(*PI, false);
1126 for (++PI; PI != PE; ++PI) {
1128 writeOperand(*PI, false);
1136 if (AnnotationWriter) AnnotationWriter->emitBasicBlockStartAnnot(BB, Out);
1138 // Output all of the instructions in the basic block...
1139 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I != E; ++I)
1140 printInstruction(*I);
1142 if (AnnotationWriter) AnnotationWriter->emitBasicBlockEndAnnot(BB, Out);
1146 /// printInfoComment - Print a little comment after the instruction indicating
1147 /// which slot it occupies.
1149 void AssemblyWriter::printInfoComment(const Value &V) {
1150 if (V.getType() != Type::VoidTy) {
1152 printType(V.getType()) << '>';
1156 if (const GlobalValue *GV = dyn_cast<GlobalValue>(&V))
1157 SlotNum = Machine.getGlobalSlot(GV);
1159 SlotNum = Machine.getLocalSlot(&V);
1163 Out << ':' << SlotNum; // Print out the def slot taken.
1165 Out << " [#uses=" << V.getNumUses() << ']'; // Output # uses
1169 // This member is called for each Instruction in a function..
1170 void AssemblyWriter::printInstruction(const Instruction &I) {
1171 if (AnnotationWriter) AnnotationWriter->emitInstructionAnnot(&I, Out);
1175 // Print out name if it exists...
1177 Out << getLLVMName(I.getName(), LocalPrefix) << " = ";
1179 // If this is a volatile load or store, print out the volatile marker.
1180 if ((isa<LoadInst>(I) && cast<LoadInst>(I).isVolatile()) ||
1181 (isa<StoreInst>(I) && cast<StoreInst>(I).isVolatile())) {
1183 } else if (isa<CallInst>(I) && cast<CallInst>(I).isTailCall()) {
1184 // If this is a call, check if it's a tail call.
1188 // Print out the opcode...
1189 Out << I.getOpcodeName();
1191 // Print out the compare instruction predicates
1192 if (const FCmpInst *FCI = dyn_cast<FCmpInst>(&I)) {
1193 Out << " " << getPredicateText(FCI->getPredicate());
1194 } else if (const ICmpInst *ICI = dyn_cast<ICmpInst>(&I)) {
1195 Out << " " << getPredicateText(ICI->getPredicate());
1198 // Print out the type of the operands...
1199 const Value *Operand = I.getNumOperands() ? I.getOperand(0) : 0;
1201 // Special case conditional branches to swizzle the condition out to the front
1202 if (isa<BranchInst>(I) && I.getNumOperands() > 1) {
1203 writeOperand(I.getOperand(2), true);
1205 writeOperand(Operand, true);
1207 writeOperand(I.getOperand(1), true);
1209 } else if (isa<SwitchInst>(I)) {
1210 // Special case switch statement to get formatting nice and correct...
1211 writeOperand(Operand , true); Out << ',';
1212 writeOperand(I.getOperand(1), true); Out << " [";
1214 for (unsigned op = 2, Eop = I.getNumOperands(); op < Eop; op += 2) {
1216 writeOperand(I.getOperand(op ), true); Out << ',';
1217 writeOperand(I.getOperand(op+1), true);
1220 } else if (isa<PHINode>(I)) {
1222 printType(I.getType());
1225 for (unsigned op = 0, Eop = I.getNumOperands(); op < Eop; op += 2) {
1226 if (op) Out << ", ";
1228 writeOperand(I.getOperand(op ), false); Out << ',';
1229 writeOperand(I.getOperand(op+1), false); Out << " ]";
1231 } else if (isa<ReturnInst>(I) && !Operand) {
1233 } else if (const CallInst *CI = dyn_cast<CallInst>(&I)) {
1234 // Print the calling convention being used.
1235 switch (CI->getCallingConv()) {
1236 case CallingConv::C: break; // default
1237 case CallingConv::Fast: Out << " fastcc"; break;
1238 case CallingConv::Cold: Out << " coldcc"; break;
1239 case CallingConv::X86_StdCall: Out << "x86_stdcallcc "; break;
1240 case CallingConv::X86_FastCall: Out << "x86_fastcallcc "; break;
1241 default: Out << " cc" << CI->getCallingConv(); break;
1244 const PointerType *PTy = cast<PointerType>(Operand->getType());
1245 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
1246 const Type *RetTy = FTy->getReturnType();
1247 const ParamAttrsList *PAL = FTy->getParamAttrs();
1249 // If possible, print out the short form of the call instruction. We can
1250 // only do this if the first argument is a pointer to a nonvararg function,
1251 // and if the return type is not a pointer to a function.
1253 if (!FTy->isVarArg() &&
1254 (!isa<PointerType>(RetTy) ||
1255 !isa<FunctionType>(cast<PointerType>(RetTy)->getElementType()))) {
1256 Out << ' '; printType(RetTy);
1257 writeOperand(Operand, false);
1259 writeOperand(Operand, true);
1262 for (unsigned op = 1, Eop = I.getNumOperands(); op < Eop; ++op) {
1265 writeOperand(I.getOperand(op), true);
1266 if (PAL && PAL->getParamAttrs(op) != ParamAttr::None)
1267 Out << " " << PAL->getParamAttrsTextByIndex(op);
1270 if (PAL && PAL->getParamAttrs(0) != ParamAttr::None)
1271 Out << ' ' << PAL->getParamAttrsTextByIndex(0);
1272 } else if (const InvokeInst *II = dyn_cast<InvokeInst>(&I)) {
1273 const PointerType *PTy = cast<PointerType>(Operand->getType());
1274 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
1275 const Type *RetTy = FTy->getReturnType();
1276 const ParamAttrsList *PAL = FTy->getParamAttrs();
1278 // Print the calling convention being used.
1279 switch (II->getCallingConv()) {
1280 case CallingConv::C: break; // default
1281 case CallingConv::Fast: Out << " fastcc"; break;
1282 case CallingConv::Cold: Out << " coldcc"; break;
1283 case CallingConv::X86_StdCall: Out << "x86_stdcallcc "; break;
1284 case CallingConv::X86_FastCall: Out << "x86_fastcallcc "; break;
1285 default: Out << " cc" << II->getCallingConv(); break;
1288 // If possible, print out the short form of the invoke instruction. We can
1289 // only do this if the first argument is a pointer to a nonvararg function,
1290 // and if the return type is not a pointer to a function.
1292 if (!FTy->isVarArg() &&
1293 (!isa<PointerType>(RetTy) ||
1294 !isa<FunctionType>(cast<PointerType>(RetTy)->getElementType()))) {
1295 Out << ' '; printType(RetTy);
1296 writeOperand(Operand, false);
1298 writeOperand(Operand, true);
1302 for (unsigned op = 3, Eop = I.getNumOperands(); op < Eop; ++op) {
1305 writeOperand(I.getOperand(op), true);
1306 if (PAL && PAL->getParamAttrs(op-2) != ParamAttr::None)
1307 Out << " " << PAL->getParamAttrsTextByIndex(op-2);
1311 if (PAL && PAL->getParamAttrs(0) != ParamAttr::None)
1312 Out << " " << PAL->getParamAttrsTextByIndex(0);
1313 Out << "\n\t\t\tto";
1314 writeOperand(II->getNormalDest(), true);
1316 writeOperand(II->getUnwindDest(), true);
1318 } else if (const AllocationInst *AI = dyn_cast<AllocationInst>(&I)) {
1320 printType(AI->getType()->getElementType());
1321 if (AI->isArrayAllocation()) {
1323 writeOperand(AI->getArraySize(), true);
1325 if (AI->getAlignment()) {
1326 Out << ", align " << AI->getAlignment();
1328 } else if (isa<CastInst>(I)) {
1329 if (Operand) writeOperand(Operand, true); // Work with broken code
1331 printType(I.getType());
1332 } else if (isa<VAArgInst>(I)) {
1333 if (Operand) writeOperand(Operand, true); // Work with broken code
1335 printType(I.getType());
1336 } else if (Operand) { // Print the normal way...
1338 // PrintAllTypes - Instructions who have operands of all the same type
1339 // omit the type from all but the first operand. If the instruction has
1340 // different type operands (for example br), then they are all printed.
1341 bool PrintAllTypes = false;
1342 const Type *TheType = Operand->getType();
1344 // Select, Store and ShuffleVector always print all types.
1345 if (isa<SelectInst>(I) || isa<StoreInst>(I) || isa<ShuffleVectorInst>(I)) {
1346 PrintAllTypes = true;
1348 for (unsigned i = 1, E = I.getNumOperands(); i != E; ++i) {
1349 Operand = I.getOperand(i);
1350 if (Operand->getType() != TheType) {
1351 PrintAllTypes = true; // We have differing types! Print them all!
1357 if (!PrintAllTypes) {
1362 for (unsigned i = 0, E = I.getNumOperands(); i != E; ++i) {
1364 writeOperand(I.getOperand(i), PrintAllTypes);
1368 // Print post operand alignment for load/store
1369 if (isa<LoadInst>(I) && cast<LoadInst>(I).getAlignment()) {
1370 Out << ", align " << cast<LoadInst>(I).getAlignment();
1371 } else if (isa<StoreInst>(I) && cast<StoreInst>(I).getAlignment()) {
1372 Out << ", align " << cast<StoreInst>(I).getAlignment();
1375 printInfoComment(I);
1380 //===----------------------------------------------------------------------===//
1381 // External Interface declarations
1382 //===----------------------------------------------------------------------===//
1384 void Module::print(std::ostream &o, AssemblyAnnotationWriter *AAW) const {
1385 SlotMachine SlotTable(this);
1386 AssemblyWriter W(o, SlotTable, this, AAW);
1390 void GlobalVariable::print(std::ostream &o) const {
1391 SlotMachine SlotTable(getParent());
1392 AssemblyWriter W(o, SlotTable, getParent(), 0);
1396 void GlobalAlias::print(std::ostream &o) const {
1397 SlotMachine SlotTable(getParent());
1398 AssemblyWriter W(o, SlotTable, getParent(), 0);
1402 void Function::print(std::ostream &o, AssemblyAnnotationWriter *AAW) const {
1403 SlotMachine SlotTable(getParent());
1404 AssemblyWriter W(o, SlotTable, getParent(), AAW);
1409 void InlineAsm::print(std::ostream &o, AssemblyAnnotationWriter *AAW) const {
1410 WriteAsOperand(o, this, true, 0);
1413 void BasicBlock::print(std::ostream &o, AssemblyAnnotationWriter *AAW) const {
1414 SlotMachine SlotTable(getParent());
1415 AssemblyWriter W(o, SlotTable,
1416 getParent() ? getParent()->getParent() : 0, AAW);
1420 void Instruction::print(std::ostream &o, AssemblyAnnotationWriter *AAW) const {
1421 const Function *F = getParent() ? getParent()->getParent() : 0;
1422 SlotMachine SlotTable(F);
1423 AssemblyWriter W(o, SlotTable, F ? F->getParent() : 0, AAW);
1428 void Constant::print(std::ostream &o) const {
1429 if (this == 0) { o << "<null> constant value\n"; return; }
1431 o << ' ' << getType()->getDescription() << ' ';
1433 std::map<const Type *, std::string> TypeTable;
1434 WriteConstantInt(o, this, TypeTable, 0);
1437 void Type::print(std::ostream &o) const {
1441 o << getDescription();
1444 void Argument::print(std::ostream &o) const {
1445 WriteAsOperand(o, this, true, getParent() ? getParent()->getParent() : 0);
1448 // Value::dump - allow easy printing of Values from the debugger.
1449 // Located here because so much of the needed functionality is here.
1450 void Value::dump() const { print(*cerr.stream()); cerr << '\n'; }
1452 // Type::dump - allow easy printing of Values from the debugger.
1453 // Located here because so much of the needed functionality is here.
1454 void Type::dump() const { print(*cerr.stream()); cerr << '\n'; }
1457 ParamAttrsList::dump() const {
1459 for (unsigned i = 0; i < attrs.size(); ++i) {
1460 uint16_t index = getParamIndex(i);
1461 uint16_t attrs = getParamAttrs(index);
1462 cerr << "{" << index << "," << attrs << "} ";
1467 //===----------------------------------------------------------------------===//
1468 // SlotMachine Implementation
1469 //===----------------------------------------------------------------------===//
1472 #define SC_DEBUG(X) cerr << X
1477 // Module level constructor. Causes the contents of the Module (sans functions)
1478 // to be added to the slot table.
1479 SlotMachine::SlotMachine(const Module *M)
1480 : TheModule(M) ///< Saved for lazy initialization.
1482 , FunctionProcessed(false)
1483 , mMap(), mNext(0), fMap(), fNext(0)
1487 // Function level constructor. Causes the contents of the Module and the one
1488 // function provided to be added to the slot table.
1489 SlotMachine::SlotMachine(const Function *F)
1490 : TheModule(F ? F->getParent() : 0) ///< Saved for lazy initialization
1491 , TheFunction(F) ///< Saved for lazy initialization
1492 , FunctionProcessed(false)
1493 , mMap(), mNext(0), fMap(), fNext(0)
1497 inline void SlotMachine::initialize() {
1500 TheModule = 0; ///< Prevent re-processing next time we're called.
1502 if (TheFunction && !FunctionProcessed)
1506 // Iterate through all the global variables, functions, and global
1507 // variable initializers and create slots for them.
1508 void SlotMachine::processModule() {
1509 SC_DEBUG("begin processModule!\n");
1511 // Add all of the unnamed global variables to the value table.
1512 for (Module::const_global_iterator I = TheModule->global_begin(),
1513 E = TheModule->global_end(); I != E; ++I)
1515 CreateModuleSlot(I);
1517 // Add all the unnamed functions to the table.
1518 for (Module::const_iterator I = TheModule->begin(), E = TheModule->end();
1521 CreateModuleSlot(I);
1523 SC_DEBUG("end processModule!\n");
1527 // Process the arguments, basic blocks, and instructions of a function.
1528 void SlotMachine::processFunction() {
1529 SC_DEBUG("begin processFunction!\n");
1532 // Add all the function arguments with no names.
1533 for(Function::const_arg_iterator AI = TheFunction->arg_begin(),
1534 AE = TheFunction->arg_end(); AI != AE; ++AI)
1536 CreateFunctionSlot(AI);
1538 SC_DEBUG("Inserting Instructions:\n");
1540 // Add all of the basic blocks and instructions with no names.
1541 for (Function::const_iterator BB = TheFunction->begin(),
1542 E = TheFunction->end(); BB != E; ++BB) {
1544 CreateFunctionSlot(BB);
1545 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I != E; ++I)
1546 if (I->getType() != Type::VoidTy && !I->hasName())
1547 CreateFunctionSlot(I);
1550 FunctionProcessed = true;
1552 SC_DEBUG("end processFunction!\n");
1555 /// Clean up after incorporating a function. This is the only way to get out of
1556 /// the function incorporation state that affects get*Slot/Create*Slot. Function
1557 /// incorporation state is indicated by TheFunction != 0.
1558 void SlotMachine::purgeFunction() {
1559 SC_DEBUG("begin purgeFunction!\n");
1560 fMap.clear(); // Simply discard the function level map
1562 FunctionProcessed = false;
1563 SC_DEBUG("end purgeFunction!\n");
1566 /// getGlobalSlot - Get the slot number of a global value.
1567 int SlotMachine::getGlobalSlot(const GlobalValue *V) {
1568 // Check for uninitialized state and do lazy initialization.
1571 // Find the type plane in the module map
1572 ValueMap::const_iterator MI = mMap.find(V);
1573 if (MI == mMap.end()) return -1;
1579 /// getLocalSlot - Get the slot number for a value that is local to a function.
1580 int SlotMachine::getLocalSlot(const Value *V) {
1581 assert(!isa<Constant>(V) && "Can't get a constant or global slot with this!");
1583 // Check for uninitialized state and do lazy initialization.
1586 ValueMap::const_iterator FI = fMap.find(V);
1587 if (FI == fMap.end()) return -1;
1593 /// CreateModuleSlot - Insert the specified GlobalValue* into the slot table.
1594 void SlotMachine::CreateModuleSlot(const GlobalValue *V) {
1595 assert(V && "Can't insert a null Value into SlotMachine!");
1596 assert(V->getType() != Type::VoidTy && "Doesn't need a slot!");
1597 assert(!V->hasName() && "Doesn't need a slot!");
1599 unsigned DestSlot = mNext++;
1602 SC_DEBUG(" Inserting value [" << V->getType() << "] = " << V << " slot=" <<
1604 // G = Global, F = Function, A = Alias, o = other
1605 SC_DEBUG((isa<GlobalVariable>(V) ? 'G' :
1606 (isa<Function> ? 'F' :
1607 (isa<GlobalAlias> ? 'A' : 'o'))) << "]\n");
1611 /// CreateSlot - Create a new slot for the specified value if it has no name.
1612 void SlotMachine::CreateFunctionSlot(const Value *V) {
1613 const Type *VTy = V->getType();
1614 assert(VTy != Type::VoidTy && !V->hasName() && "Doesn't need a slot!");
1616 unsigned DestSlot = fNext++;
1619 // G = Global, F = Function, o = other
1620 SC_DEBUG(" Inserting value [" << VTy << "] = " << V << " slot=" <<
1621 DestSlot << " [o]\n");