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/InlineAsm.h"
24 #include "llvm/Instruction.h"
25 #include "llvm/Instructions.h"
26 #include "llvm/Module.h"
27 #include "llvm/SymbolTable.h"
28 #include "llvm/TypeSymbolTable.h"
29 #include "llvm/ADT/StringExtras.h"
30 #include "llvm/ADT/STLExtras.h"
31 #include "llvm/Support/CFG.h"
32 #include "llvm/Support/MathExtras.h"
33 #include "llvm/Support/Streams.h"
39 // Make virtual table appear in this compilation unit.
40 AssemblyAnnotationWriter::~AssemblyAnnotationWriter() {}
42 /// This class provides computation of slot numbers for LLVM Assembly writing.
43 /// @brief LLVM Assembly Writing Slot Computation.
50 /// @brief A mapping of Values to slot numbers
51 typedef std::map<const Value*, unsigned> ValueMap;
53 /// @brief A plane with next slot number and ValueMap
55 unsigned next_slot; ///< The next slot number to use
56 ValueMap map; ///< The map of Value* -> unsigned
57 ValuePlane() { next_slot = 0; } ///< Make sure we start at 0
60 /// @brief The map of planes by Type
61 typedef std::map<const Type*, ValuePlane> TypedPlanes;
64 /// @name Constructors
67 /// @brief Construct from a module
68 SlotMachine(const Module *M);
70 /// @brief Construct from a function, starting out in incorp state.
71 SlotMachine(const Function *F);
77 /// Return the slot number of the specified value in it's type
78 /// plane. If something is not in the SlotMachine, return -1.
79 int getLocalSlot(const Value *V);
80 int getGlobalSlot(const GlobalValue *V);
86 /// If you'd like to deal with a function instead of just a module, use
87 /// this method to get its data into the SlotMachine.
88 void incorporateFunction(const Function *F) {
90 FunctionProcessed = false;
93 /// After calling incorporateFunction, use this method to remove the
94 /// most recently incorporated function from the SlotMachine. This
95 /// will reset the state of the machine back to just the module contents.
99 /// @name Implementation Details
102 /// This function does the actual initialization.
103 inline void initialize();
105 /// CreateModuleSlot - Insert the specified GlobalValue* into the slot table.
106 void CreateModuleSlot(const GlobalValue *V);
108 /// CreateFunctionSlot - Insert the specified Value* into the slot table.
109 void CreateFunctionSlot(const Value *V);
111 /// Add all of the module level global variables (and their initializers)
112 /// and function declarations, but not the contents of those functions.
113 void processModule();
115 /// Add all of the functions arguments, basic blocks, and instructions
116 void processFunction();
118 SlotMachine(const SlotMachine &); // DO NOT IMPLEMENT
119 void operator=(const SlotMachine &); // DO NOT IMPLEMENT
126 /// @brief The module for which we are holding slot numbers
127 const Module* TheModule;
129 /// @brief The function for which we are holding slot numbers
130 const Function* TheFunction;
131 bool FunctionProcessed;
133 /// @brief The TypePlanes map for the module level data
136 /// @brief The TypePlanes map for the function level data
143 } // end namespace llvm
145 static RegisterPass<PrintModulePass>
146 X("printm", "Print module to stderr");
147 static RegisterPass<PrintFunctionPass>
148 Y("print","Print function to stderr");
150 static void WriteAsOperandInternal(std::ostream &Out, const Value *V,
151 std::map<const Type *, std::string> &TypeTable,
152 SlotMachine *Machine);
154 static const Module *getModuleFromVal(const Value *V) {
155 if (const Argument *MA = dyn_cast<Argument>(V))
156 return MA->getParent() ? MA->getParent()->getParent() : 0;
157 else if (const BasicBlock *BB = dyn_cast<BasicBlock>(V))
158 return BB->getParent() ? BB->getParent()->getParent() : 0;
159 else if (const Instruction *I = dyn_cast<Instruction>(V)) {
160 const Function *M = I->getParent() ? I->getParent()->getParent() : 0;
161 return M ? M->getParent() : 0;
162 } else if (const GlobalValue *GV = dyn_cast<GlobalValue>(V))
163 return GV->getParent();
167 static SlotMachine *createSlotMachine(const Value *V) {
168 if (const Argument *FA = dyn_cast<Argument>(V)) {
169 return new SlotMachine(FA->getParent());
170 } else if (const Instruction *I = dyn_cast<Instruction>(V)) {
171 return new SlotMachine(I->getParent()->getParent());
172 } else if (const BasicBlock *BB = dyn_cast<BasicBlock>(V)) {
173 return new SlotMachine(BB->getParent());
174 } else if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(V)){
175 return new SlotMachine(GV->getParent());
176 } else if (const Function *Func = dyn_cast<Function>(V)) {
177 return new SlotMachine(Func);
182 // getLLVMName - Turn the specified string into an 'LLVM name', which is either
183 // prefixed with % (if the string only contains simple characters) or is
184 // surrounded with ""'s (if it has special chars in it).
185 static std::string getLLVMName(const std::string &Name,
186 bool prefixName = true) {
187 assert(!Name.empty() && "Cannot get empty name!");
189 // First character cannot start with a number...
190 if (Name[0] >= '0' && Name[0] <= '9')
191 return "\"" + Name + "\"";
193 // Scan to see if we have any characters that are not on the "white list"
194 for (unsigned i = 0, e = Name.size(); i != e; ++i) {
196 assert(C != '"' && "Illegal character in LLVM value name!");
197 if ((C < 'a' || C > 'z') && (C < 'A' || C > 'Z') && (C < '0' || C > '9') &&
198 C != '-' && C != '.' && C != '_')
199 return "\"" + Name + "\"";
202 // If we get here, then the identifier is legal to use as a "VarID".
210 /// fillTypeNameTable - If the module has a symbol table, take all global types
211 /// and stuff their names into the TypeNames map.
213 static void fillTypeNameTable(const Module *M,
214 std::map<const Type *, std::string> &TypeNames) {
216 const TypeSymbolTable &ST = M->getTypeSymbolTable();
217 TypeSymbolTable::const_iterator TI = ST.begin();
218 for (; TI != ST.end(); ++TI) {
219 // As a heuristic, don't insert pointer to primitive types, because
220 // they are used too often to have a single useful name.
222 const Type *Ty = cast<Type>(TI->second);
223 if (!isa<PointerType>(Ty) ||
224 !cast<PointerType>(Ty)->getElementType()->isPrimitiveType() ||
225 !cast<PointerType>(Ty)->getElementType()->isInteger() ||
226 isa<OpaqueType>(cast<PointerType>(Ty)->getElementType()))
227 TypeNames.insert(std::make_pair(Ty, getLLVMName(TI->first)));
233 static void calcTypeName(const Type *Ty,
234 std::vector<const Type *> &TypeStack,
235 std::map<const Type *, std::string> &TypeNames,
236 std::string & Result){
237 if (Ty->isInteger() || (Ty->isPrimitiveType() && !isa<OpaqueType>(Ty))) {
238 Result += Ty->getDescription(); // Base case
242 // Check to see if the type is named.
243 std::map<const Type *, std::string>::iterator I = TypeNames.find(Ty);
244 if (I != TypeNames.end()) {
249 if (isa<OpaqueType>(Ty)) {
254 // Check to see if the Type is already on the stack...
255 unsigned Slot = 0, CurSize = TypeStack.size();
256 while (Slot < CurSize && TypeStack[Slot] != Ty) ++Slot; // Scan for type
258 // This is another base case for the recursion. In this case, we know
259 // that we have looped back to a type that we have previously visited.
260 // Generate the appropriate upreference to handle this.
261 if (Slot < CurSize) {
262 Result += "\\" + utostr(CurSize-Slot); // Here's the upreference
266 TypeStack.push_back(Ty); // Recursive case: Add us to the stack..
268 switch (Ty->getTypeID()) {
269 case Type::IntegerTyID: {
270 unsigned BitWidth = cast<IntegerType>(Ty)->getBitWidth();
271 Result += "i" + utostr(BitWidth);
274 case Type::FunctionTyID: {
275 const FunctionType *FTy = cast<FunctionType>(Ty);
276 calcTypeName(FTy->getReturnType(), TypeStack, TypeNames, Result);
279 for (FunctionType::param_iterator I = FTy->param_begin(),
280 E = FTy->param_end(); I != E; ++I) {
281 if (I != FTy->param_begin())
283 calcTypeName(*I, TypeStack, TypeNames, Result);
284 if (FTy->getParamAttrs(Idx)) {
286 Result += FunctionType::getParamAttrsText(FTy->getParamAttrs(Idx));
290 if (FTy->isVarArg()) {
291 if (FTy->getNumParams()) Result += ", ";
295 if (FTy->getParamAttrs(0)) {
297 Result += FunctionType::getParamAttrsText(FTy->getParamAttrs(0));
301 case Type::StructTyID: {
302 const StructType *STy = cast<StructType>(Ty);
306 for (StructType::element_iterator I = STy->element_begin(),
307 E = STy->element_end(); I != E; ++I) {
308 if (I != STy->element_begin())
310 calcTypeName(*I, TypeStack, TypeNames, Result);
317 case Type::PointerTyID:
318 calcTypeName(cast<PointerType>(Ty)->getElementType(),
319 TypeStack, TypeNames, Result);
322 case Type::ArrayTyID: {
323 const ArrayType *ATy = cast<ArrayType>(Ty);
324 Result += "[" + utostr(ATy->getNumElements()) + " x ";
325 calcTypeName(ATy->getElementType(), TypeStack, TypeNames, Result);
329 case Type::PackedTyID: {
330 const PackedType *PTy = cast<PackedType>(Ty);
331 Result += "<" + utostr(PTy->getNumElements()) + " x ";
332 calcTypeName(PTy->getElementType(), TypeStack, TypeNames, Result);
336 case Type::OpaqueTyID:
340 Result += "<unrecognized-type>";
344 TypeStack.pop_back(); // Remove self from stack...
348 /// printTypeInt - The internal guts of printing out a type that has a
349 /// potentially named portion.
351 static std::ostream &printTypeInt(std::ostream &Out, const Type *Ty,
352 std::map<const Type *, std::string> &TypeNames) {
353 // Primitive types always print out their description, regardless of whether
354 // they have been named or not.
356 if (Ty->isInteger() || (Ty->isPrimitiveType() && !isa<OpaqueType>(Ty)))
357 return Out << Ty->getDescription();
359 // Check to see if the type is named.
360 std::map<const Type *, std::string>::iterator I = TypeNames.find(Ty);
361 if (I != TypeNames.end()) return Out << I->second;
363 // Otherwise we have a type that has not been named but is a derived type.
364 // Carefully recurse the type hierarchy to print out any contained symbolic
367 std::vector<const Type *> TypeStack;
368 std::string TypeName;
369 calcTypeName(Ty, TypeStack, TypeNames, TypeName);
370 TypeNames.insert(std::make_pair(Ty, TypeName));//Cache type name for later use
371 return (Out << TypeName);
375 /// WriteTypeSymbolic - This attempts to write the specified type as a symbolic
376 /// type, iff there is an entry in the modules symbol table for the specified
377 /// type or one of it's component types. This is slower than a simple x << Type
379 std::ostream &llvm::WriteTypeSymbolic(std::ostream &Out, const Type *Ty,
383 // If they want us to print out a type, but there is no context, we can't
384 // print it symbolically.
386 return Out << Ty->getDescription();
388 std::map<const Type *, std::string> TypeNames;
389 fillTypeNameTable(M, TypeNames);
390 return printTypeInt(Out, Ty, TypeNames);
393 // PrintEscapedString - Print each character of the specified string, escaping
394 // it if it is not printable or if it is an escape char.
395 static void PrintEscapedString(const std::string &Str, std::ostream &Out) {
396 for (unsigned i = 0, e = Str.size(); i != e; ++i) {
397 unsigned char C = Str[i];
398 if (isprint(C) && C != '"' && C != '\\') {
402 << (char) ((C/16 < 10) ? ( C/16 +'0') : ( C/16 -10+'A'))
403 << (char)(((C&15) < 10) ? ((C&15)+'0') : ((C&15)-10+'A'));
408 static const char *getPredicateText(unsigned predicate) {
409 const char * pred = "unknown";
411 case FCmpInst::FCMP_FALSE: pred = "false"; break;
412 case FCmpInst::FCMP_OEQ: pred = "oeq"; break;
413 case FCmpInst::FCMP_OGT: pred = "ogt"; break;
414 case FCmpInst::FCMP_OGE: pred = "oge"; break;
415 case FCmpInst::FCMP_OLT: pred = "olt"; break;
416 case FCmpInst::FCMP_OLE: pred = "ole"; break;
417 case FCmpInst::FCMP_ONE: pred = "one"; break;
418 case FCmpInst::FCMP_ORD: pred = "ord"; break;
419 case FCmpInst::FCMP_UNO: pred = "uno"; break;
420 case FCmpInst::FCMP_UEQ: pred = "ueq"; break;
421 case FCmpInst::FCMP_UGT: pred = "ugt"; break;
422 case FCmpInst::FCMP_UGE: pred = "uge"; break;
423 case FCmpInst::FCMP_ULT: pred = "ult"; break;
424 case FCmpInst::FCMP_ULE: pred = "ule"; break;
425 case FCmpInst::FCMP_UNE: pred = "une"; break;
426 case FCmpInst::FCMP_TRUE: pred = "true"; break;
427 case ICmpInst::ICMP_EQ: pred = "eq"; break;
428 case ICmpInst::ICMP_NE: pred = "ne"; break;
429 case ICmpInst::ICMP_SGT: pred = "sgt"; break;
430 case ICmpInst::ICMP_SGE: pred = "sge"; break;
431 case ICmpInst::ICMP_SLT: pred = "slt"; break;
432 case ICmpInst::ICMP_SLE: pred = "sle"; break;
433 case ICmpInst::ICMP_UGT: pred = "ugt"; break;
434 case ICmpInst::ICMP_UGE: pred = "uge"; break;
435 case ICmpInst::ICMP_ULT: pred = "ult"; break;
436 case ICmpInst::ICMP_ULE: pred = "ule"; break;
441 /// @brief Internal constant writer.
442 static void WriteConstantInt(std::ostream &Out, const Constant *CV,
443 std::map<const Type *, std::string> &TypeTable,
444 SlotMachine *Machine) {
445 const int IndentSize = 4;
446 static std::string Indent = "\n";
447 if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV)) {
448 if (CI->getType() == Type::Int1Ty)
449 Out << (CI->getZExtValue() ? "true" : "false");
451 Out << CI->getSExtValue();
452 } else if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CV)) {
453 // We would like to output the FP constant value in exponential notation,
454 // but we cannot do this if doing so will lose precision. Check here to
455 // make sure that we only output it in exponential format if we can parse
456 // the value back and get the same value.
458 std::string StrVal = ftostr(CFP->getValue());
460 // Check to make sure that the stringized number is not some string like
461 // "Inf" or NaN, that atof will accept, but the lexer will not. Check that
462 // the string matches the "[-+]?[0-9]" regex.
464 if ((StrVal[0] >= '0' && StrVal[0] <= '9') ||
465 ((StrVal[0] == '-' || StrVal[0] == '+') &&
466 (StrVal[1] >= '0' && StrVal[1] <= '9')))
467 // Reparse stringized version!
468 if (atof(StrVal.c_str()) == CFP->getValue()) {
473 // Otherwise we could not reparse it to exactly the same value, so we must
474 // output the string in hexadecimal format!
475 assert(sizeof(double) == sizeof(uint64_t) &&
476 "assuming that double is 64 bits!");
477 Out << "0x" << utohexstr(DoubleToBits(CFP->getValue()));
479 } else if (isa<ConstantAggregateZero>(CV)) {
480 Out << "zeroinitializer";
481 } else if (const ConstantArray *CA = dyn_cast<ConstantArray>(CV)) {
482 // As a special case, print the array as a string if it is an array of
483 // ubytes or an array of sbytes with positive values.
485 const Type *ETy = CA->getType()->getElementType();
486 if (CA->isString()) {
488 PrintEscapedString(CA->getAsString(), Out);
491 } else { // Cannot output in string format...
493 if (CA->getNumOperands()) {
495 printTypeInt(Out, ETy, TypeTable);
496 WriteAsOperandInternal(Out, CA->getOperand(0),
498 for (unsigned i = 1, e = CA->getNumOperands(); i != e; ++i) {
500 printTypeInt(Out, ETy, TypeTable);
501 WriteAsOperandInternal(Out, CA->getOperand(i), TypeTable, Machine);
506 } else if (const ConstantStruct *CS = dyn_cast<ConstantStruct>(CV)) {
507 if (CS->getType()->isPacked())
510 unsigned N = CS->getNumOperands();
513 Indent += std::string(IndentSize, ' ');
518 printTypeInt(Out, CS->getOperand(0)->getType(), TypeTable);
520 WriteAsOperandInternal(Out, CS->getOperand(0), TypeTable, Machine);
522 for (unsigned i = 1; i < N; i++) {
524 if (N > 2) Out << Indent;
525 printTypeInt(Out, CS->getOperand(i)->getType(), TypeTable);
527 WriteAsOperandInternal(Out, CS->getOperand(i), TypeTable, Machine);
529 if (N > 2) Indent.resize(Indent.size() - IndentSize);
533 if (CS->getType()->isPacked())
535 } else if (const ConstantPacked *CP = dyn_cast<ConstantPacked>(CV)) {
536 const Type *ETy = CP->getType()->getElementType();
537 assert(CP->getNumOperands() > 0 &&
538 "Number of operands for a PackedConst must be > 0");
541 printTypeInt(Out, ETy, TypeTable);
542 WriteAsOperandInternal(Out, CP->getOperand(0), TypeTable, Machine);
543 for (unsigned i = 1, e = CP->getNumOperands(); i != e; ++i) {
545 printTypeInt(Out, ETy, TypeTable);
546 WriteAsOperandInternal(Out, CP->getOperand(i), TypeTable, Machine);
549 } else if (isa<ConstantPointerNull>(CV)) {
552 } else if (isa<UndefValue>(CV)) {
555 } else if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV)) {
556 Out << CE->getOpcodeName();
558 Out << " " << getPredicateText(CE->getPredicate());
561 for (User::const_op_iterator OI=CE->op_begin(); OI != CE->op_end(); ++OI) {
562 printTypeInt(Out, (*OI)->getType(), TypeTable);
563 WriteAsOperandInternal(Out, *OI, TypeTable, Machine);
564 if (OI+1 != CE->op_end())
570 printTypeInt(Out, CE->getType(), TypeTable);
576 Out << "<placeholder or erroneous Constant>";
581 /// WriteAsOperand - Write the name of the specified value out to the specified
582 /// ostream. This can be useful when you just want to print int %reg126, not
583 /// the whole instruction that generated it.
585 static void WriteAsOperandInternal(std::ostream &Out, const Value *V,
586 std::map<const Type*, std::string> &TypeTable,
587 SlotMachine *Machine) {
590 Out << getLLVMName(V->getName());
592 const Constant *CV = dyn_cast<Constant>(V);
593 if (CV && !isa<GlobalValue>(CV)) {
594 WriteConstantInt(Out, CV, TypeTable, Machine);
595 } else if (const InlineAsm *IA = dyn_cast<InlineAsm>(V)) {
597 if (IA->hasSideEffects())
598 Out << "sideeffect ";
600 PrintEscapedString(IA->getAsmString(), Out);
602 PrintEscapedString(IA->getConstraintString(), Out);
607 if (const GlobalValue *GV = dyn_cast<GlobalValue>(V))
608 Slot = Machine->getGlobalSlot(GV);
610 Slot = Machine->getLocalSlot(V);
612 Machine = createSlotMachine(V);
614 if (const GlobalValue *GV = dyn_cast<GlobalValue>(V))
615 Slot = Machine->getGlobalSlot(GV);
617 Slot = Machine->getLocalSlot(V);
631 /// WriteAsOperand - Write the name of the specified value out to the specified
632 /// ostream. This can be useful when you just want to print int %reg126, not
633 /// the whole instruction that generated it.
635 std::ostream &llvm::WriteAsOperand(std::ostream &Out, const Value *V,
636 bool PrintType, const Module *Context) {
637 std::map<const Type *, std::string> TypeNames;
638 if (Context == 0) Context = getModuleFromVal(V);
641 fillTypeNameTable(Context, TypeNames);
644 printTypeInt(Out, V->getType(), TypeNames);
646 WriteAsOperandInternal(Out, V, TypeNames, 0);
653 class AssemblyWriter {
655 SlotMachine &Machine;
656 const Module *TheModule;
657 std::map<const Type *, std::string> TypeNames;
658 AssemblyAnnotationWriter *AnnotationWriter;
660 inline AssemblyWriter(std::ostream &o, SlotMachine &Mac, const Module *M,
661 AssemblyAnnotationWriter *AAW)
662 : Out(o), Machine(Mac), TheModule(M), AnnotationWriter(AAW) {
664 // If the module has a symbol table, take all global types and stuff their
665 // names into the TypeNames map.
667 fillTypeNameTable(M, TypeNames);
670 inline void write(const Module *M) { printModule(M); }
671 inline void write(const GlobalVariable *G) { printGlobal(G); }
672 inline void write(const Function *F) { printFunction(F); }
673 inline void write(const BasicBlock *BB) { printBasicBlock(BB); }
674 inline void write(const Instruction *I) { printInstruction(*I); }
675 inline void write(const Constant *CPV) { printConstant(CPV); }
676 inline void write(const Type *Ty) { printType(Ty); }
678 void writeOperand(const Value *Op, bool PrintType);
680 const Module* getModule() { return TheModule; }
683 void printModule(const Module *M);
684 void printTypeSymbolTable(const TypeSymbolTable &ST);
685 void printValueSymbolTable(const SymbolTable &ST);
686 void printConstant(const Constant *CPV);
687 void printGlobal(const GlobalVariable *GV);
688 void printFunction(const Function *F);
689 void printArgument(const Argument *FA, FunctionType::ParameterAttributes A);
690 void printBasicBlock(const BasicBlock *BB);
691 void printInstruction(const Instruction &I);
693 // printType - Go to extreme measures to attempt to print out a short,
694 // symbolic version of a type name.
696 std::ostream &printType(const Type *Ty) {
697 return printTypeInt(Out, Ty, TypeNames);
700 // printTypeAtLeastOneLevel - Print out one level of the possibly complex type
701 // without considering any symbolic types that we may have equal to it.
703 std::ostream &printTypeAtLeastOneLevel(const Type *Ty);
705 // printInfoComment - Print a little comment after the instruction indicating
706 // which slot it occupies.
707 void printInfoComment(const Value &V);
709 } // end of llvm namespace
711 /// printTypeAtLeastOneLevel - Print out one level of the possibly complex type
712 /// without considering any symbolic types that we may have equal to it.
714 std::ostream &AssemblyWriter::printTypeAtLeastOneLevel(const Type *Ty) {
715 if (const IntegerType *ITy = dyn_cast<IntegerType>(Ty))
716 Out << "i" << utostr(ITy->getBitWidth());
717 else if (const FunctionType *FTy = dyn_cast<FunctionType>(Ty)) {
718 printType(FTy->getReturnType());
721 for (FunctionType::param_iterator I = FTy->param_begin(),
722 E = FTy->param_end(); I != E; ++I) {
723 if (I != FTy->param_begin())
726 if (FTy->getParamAttrs(Idx)) {
727 Out << " " << FunctionType::getParamAttrsText(FTy->getParamAttrs(Idx));
731 if (FTy->isVarArg()) {
732 if (FTy->getNumParams()) Out << ", ";
736 if (FTy->getParamAttrs(0))
737 Out << ' ' << FunctionType::getParamAttrsText(FTy->getParamAttrs(0));
738 } else if (const StructType *STy = dyn_cast<StructType>(Ty)) {
742 for (StructType::element_iterator I = STy->element_begin(),
743 E = STy->element_end(); I != E; ++I) {
744 if (I != STy->element_begin())
751 } else if (const PointerType *PTy = dyn_cast<PointerType>(Ty)) {
752 printType(PTy->getElementType()) << '*';
753 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
754 Out << '[' << ATy->getNumElements() << " x ";
755 printType(ATy->getElementType()) << ']';
756 } else if (const PackedType *PTy = dyn_cast<PackedType>(Ty)) {
757 Out << '<' << PTy->getNumElements() << " x ";
758 printType(PTy->getElementType()) << '>';
760 else if (isa<OpaqueType>(Ty)) {
763 if (!Ty->isPrimitiveType())
764 Out << "<unknown derived type>";
771 void AssemblyWriter::writeOperand(const Value *Operand, bool PrintType) {
773 Out << "<null operand!>";
775 if (PrintType) { Out << ' '; printType(Operand->getType()); }
776 WriteAsOperandInternal(Out, Operand, TypeNames, &Machine);
781 void AssemblyWriter::printModule(const Module *M) {
782 if (!M->getModuleIdentifier().empty() &&
783 // Don't print the ID if it will start a new line (which would
784 // require a comment char before it).
785 M->getModuleIdentifier().find('\n') == std::string::npos)
786 Out << "; ModuleID = '" << M->getModuleIdentifier() << "'\n";
788 if (!M->getDataLayout().empty())
789 Out << "target datalayout = \"" << M->getDataLayout() << "\"\n";
791 switch (M->getEndianness()) {
792 case Module::LittleEndian: Out << "target endian = little\n"; break;
793 case Module::BigEndian: Out << "target endian = big\n"; break;
794 case Module::AnyEndianness: break;
796 switch (M->getPointerSize()) {
797 case Module::Pointer32: Out << "target pointersize = 32\n"; break;
798 case Module::Pointer64: Out << "target pointersize = 64\n"; break;
799 case Module::AnyPointerSize: break;
801 if (!M->getTargetTriple().empty())
802 Out << "target triple = \"" << M->getTargetTriple() << "\"\n";
804 if (!M->getModuleInlineAsm().empty()) {
805 // Split the string into lines, to make it easier to read the .ll file.
806 std::string Asm = M->getModuleInlineAsm();
808 size_t NewLine = Asm.find_first_of('\n', CurPos);
809 while (NewLine != std::string::npos) {
810 // We found a newline, print the portion of the asm string from the
811 // last newline up to this newline.
812 Out << "module asm \"";
813 PrintEscapedString(std::string(Asm.begin()+CurPos, Asm.begin()+NewLine),
817 NewLine = Asm.find_first_of('\n', CurPos);
819 Out << "module asm \"";
820 PrintEscapedString(std::string(Asm.begin()+CurPos, Asm.end()), Out);
824 // Loop over the dependent libraries and emit them.
825 Module::lib_iterator LI = M->lib_begin();
826 Module::lib_iterator LE = M->lib_end();
828 Out << "deplibs = [ ";
830 Out << '"' << *LI << '"';
838 // Loop over the symbol table, emitting all named constants.
839 printTypeSymbolTable(M->getTypeSymbolTable());
840 printValueSymbolTable(M->getValueSymbolTable());
842 for (Module::const_global_iterator I = M->global_begin(), E = M->global_end();
846 Out << "\nimplementation ; Functions:\n";
848 // Output all of the functions.
849 for (Module::const_iterator I = M->begin(), E = M->end(); I != E; ++I)
853 void AssemblyWriter::printGlobal(const GlobalVariable *GV) {
854 if (GV->hasName()) Out << getLLVMName(GV->getName()) << " = ";
856 if (!GV->hasInitializer())
857 switch (GV->getLinkage()) {
858 case GlobalValue::DLLImportLinkage: Out << "dllimport "; break;
859 case GlobalValue::ExternalWeakLinkage: Out << "extern_weak "; break;
860 default: Out << "external "; break;
862 switch (GV->getLinkage()) {
863 case GlobalValue::InternalLinkage: Out << "internal "; break;
864 case GlobalValue::LinkOnceLinkage: Out << "linkonce "; break;
865 case GlobalValue::WeakLinkage: Out << "weak "; break;
866 case GlobalValue::AppendingLinkage: Out << "appending "; break;
867 case GlobalValue::DLLImportLinkage: Out << "dllimport "; break;
868 case GlobalValue::DLLExportLinkage: Out << "dllexport "; break;
869 case GlobalValue::ExternalWeakLinkage: Out << "extern_weak "; break;
870 case GlobalValue::ExternalLinkage: break;
871 case GlobalValue::GhostLinkage:
872 cerr << "GhostLinkage not allowed in AsmWriter!\n";
875 switch (GV->getVisibility()) {
876 default: assert(0 && "Invalid visibility style!");
877 case GlobalValue::DefaultVisibility: break;
878 case GlobalValue::HiddenVisibility: Out << "hidden "; break;
882 Out << (GV->isConstant() ? "constant " : "global ");
883 printType(GV->getType()->getElementType());
885 if (GV->hasInitializer()) {
886 Constant* C = cast<Constant>(GV->getInitializer());
887 assert(C && "GlobalVar initializer isn't constant?");
888 writeOperand(GV->getInitializer(), false);
891 if (GV->hasSection())
892 Out << ", section \"" << GV->getSection() << '"';
893 if (GV->getAlignment())
894 Out << ", align " << GV->getAlignment();
896 printInfoComment(*GV);
900 void AssemblyWriter::printTypeSymbolTable(const TypeSymbolTable &ST) {
902 for (TypeSymbolTable::const_iterator TI = ST.begin(), TE = ST.end();
904 Out << "\t" << getLLVMName(TI->first) << " = type ";
906 // Make sure we print out at least one level of the type structure, so
907 // that we do not get %FILE = type %FILE
909 printTypeAtLeastOneLevel(TI->second) << "\n";
913 // printSymbolTable - Run through symbol table looking for constants
914 // and types. Emit their declarations.
915 void AssemblyWriter::printValueSymbolTable(const SymbolTable &ST) {
917 // Print the constants, in type plane order.
918 for (SymbolTable::plane_const_iterator PI = ST.plane_begin();
919 PI != ST.plane_end(); ++PI) {
920 SymbolTable::value_const_iterator VI = ST.value_begin(PI->first);
921 SymbolTable::value_const_iterator VE = ST.value_end(PI->first);
923 for (; VI != VE; ++VI) {
924 const Value* V = VI->second;
925 const Constant *CPV = dyn_cast<Constant>(V) ;
926 if (CPV && !isa<GlobalValue>(V)) {
934 /// printConstant - Print out a constant pool entry...
936 void AssemblyWriter::printConstant(const Constant *CPV) {
937 // Don't print out unnamed constants, they will be inlined
938 if (!CPV->hasName()) return;
941 Out << "\t" << getLLVMName(CPV->getName()) << " =";
943 // Write the value out now.
944 writeOperand(CPV, true);
946 printInfoComment(*CPV);
950 /// printFunction - Print all aspects of a function.
952 void AssemblyWriter::printFunction(const Function *F) {
953 // Print out the return type and name...
956 // Ensure that no local symbols conflict with global symbols.
957 const_cast<Function*>(F)->renameLocalSymbols();
959 if (AnnotationWriter) AnnotationWriter->emitFunctionAnnot(F, Out);
962 switch (F->getLinkage()) {
963 case GlobalValue::DLLImportLinkage: Out << "declare dllimport "; break;
964 case GlobalValue::ExternalWeakLinkage: Out << "declare extern_weak "; break;
965 default: Out << "declare ";
969 switch (F->getLinkage()) {
970 case GlobalValue::InternalLinkage: Out << "internal "; break;
971 case GlobalValue::LinkOnceLinkage: Out << "linkonce "; break;
972 case GlobalValue::WeakLinkage: Out << "weak "; break;
973 case GlobalValue::AppendingLinkage: Out << "appending "; break;
974 case GlobalValue::DLLImportLinkage: Out << "dllimport "; break;
975 case GlobalValue::DLLExportLinkage: Out << "dllexport "; break;
976 case GlobalValue::ExternalWeakLinkage: Out << "extern_weak "; break;
977 case GlobalValue::ExternalLinkage: break;
978 case GlobalValue::GhostLinkage:
979 cerr << "GhostLinkage not allowed in AsmWriter!\n";
982 switch (F->getVisibility()) {
983 default: assert(0 && "Invalid visibility style!");
984 case GlobalValue::DefaultVisibility: break;
985 case GlobalValue::HiddenVisibility: Out << "hidden "; break;
989 // Print the calling convention.
990 switch (F->getCallingConv()) {
991 case CallingConv::C: break; // default
992 case CallingConv::CSRet: Out << "csretcc "; break;
993 case CallingConv::Fast: Out << "fastcc "; break;
994 case CallingConv::Cold: Out << "coldcc "; break;
995 case CallingConv::X86_StdCall: Out << "x86_stdcallcc "; break;
996 case CallingConv::X86_FastCall: Out << "x86_fastcallcc "; break;
997 default: Out << "cc" << F->getCallingConv() << " "; break;
1000 const FunctionType *FT = F->getFunctionType();
1001 printType(F->getReturnType()) << ' ';
1002 if (!F->getName().empty())
1003 Out << getLLVMName(F->getName());
1007 Machine.incorporateFunction(F);
1009 // Loop over the arguments, printing them...
1012 for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
1014 // Insert commas as we go... the first arg doesn't get a comma
1015 if (I != F->arg_begin()) Out << ", ";
1016 printArgument(I, FT->getParamAttrs(Idx));
1020 // Finish printing arguments...
1021 if (FT->isVarArg()) {
1022 if (FT->getNumParams()) Out << ", ";
1023 Out << "..."; // Output varargs portion of signature!
1026 if (FT->getParamAttrs(0))
1027 Out << ' ' << FunctionType::getParamAttrsText(FT->getParamAttrs(0));
1028 if (F->hasSection())
1029 Out << " section \"" << F->getSection() << '"';
1030 if (F->getAlignment())
1031 Out << " align " << F->getAlignment();
1033 if (F->isExternal()) {
1038 // Output all of its basic blocks... for the function
1039 for (Function::const_iterator I = F->begin(), E = F->end(); I != E; ++I)
1045 Machine.purgeFunction();
1048 /// printArgument - This member is called for every argument that is passed into
1049 /// the function. Simply print it out
1051 void AssemblyWriter::printArgument(const Argument *Arg,
1052 FunctionType::ParameterAttributes attrs) {
1054 printType(Arg->getType());
1056 if (attrs != FunctionType::NoAttributeSet)
1057 Out << ' ' << FunctionType::getParamAttrsText(attrs);
1059 // Output name, if available...
1061 Out << ' ' << getLLVMName(Arg->getName());
1064 /// printBasicBlock - This member is called for each basic block in a method.
1066 void AssemblyWriter::printBasicBlock(const BasicBlock *BB) {
1067 if (BB->hasName()) { // Print out the label if it exists...
1068 Out << "\n" << getLLVMName(BB->getName(), false) << ':';
1069 } else if (!BB->use_empty()) { // Don't print block # of no uses...
1070 Out << "\n; <label>:";
1071 int Slot = Machine.getLocalSlot(BB);
1078 if (BB->getParent() == 0)
1079 Out << "\t\t; Error: Block without parent!";
1081 if (BB != &BB->getParent()->front()) { // Not the entry block?
1082 // Output predecessors for the block...
1084 pred_const_iterator PI = pred_begin(BB), PE = pred_end(BB);
1087 Out << " No predecessors!";
1090 writeOperand(*PI, false);
1091 for (++PI; PI != PE; ++PI) {
1093 writeOperand(*PI, false);
1101 if (AnnotationWriter) AnnotationWriter->emitBasicBlockStartAnnot(BB, Out);
1103 // Output all of the instructions in the basic block...
1104 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I != E; ++I)
1105 printInstruction(*I);
1107 if (AnnotationWriter) AnnotationWriter->emitBasicBlockEndAnnot(BB, Out);
1111 /// printInfoComment - Print a little comment after the instruction indicating
1112 /// which slot it occupies.
1114 void AssemblyWriter::printInfoComment(const Value &V) {
1115 if (V.getType() != Type::VoidTy) {
1117 printType(V.getType()) << '>';
1121 if (const GlobalValue *GV = dyn_cast<GlobalValue>(&V))
1122 SlotNum = Machine.getGlobalSlot(GV);
1124 SlotNum = Machine.getLocalSlot(&V);
1128 Out << ':' << SlotNum; // Print out the def slot taken.
1130 Out << " [#uses=" << V.getNumUses() << ']'; // Output # uses
1134 // This member is called for each Instruction in a function..
1135 void AssemblyWriter::printInstruction(const Instruction &I) {
1136 if (AnnotationWriter) AnnotationWriter->emitInstructionAnnot(&I, Out);
1140 // Print out name if it exists...
1142 Out << getLLVMName(I.getName()) << " = ";
1144 // If this is a volatile load or store, print out the volatile marker.
1145 if ((isa<LoadInst>(I) && cast<LoadInst>(I).isVolatile()) ||
1146 (isa<StoreInst>(I) && cast<StoreInst>(I).isVolatile())) {
1148 } else if (isa<CallInst>(I) && cast<CallInst>(I).isTailCall()) {
1149 // If this is a call, check if it's a tail call.
1153 // Print out the opcode...
1154 Out << I.getOpcodeName();
1156 // Print out the compare instruction predicates
1157 if (const FCmpInst *FCI = dyn_cast<FCmpInst>(&I)) {
1158 Out << " " << getPredicateText(FCI->getPredicate());
1159 } else if (const ICmpInst *ICI = dyn_cast<ICmpInst>(&I)) {
1160 Out << " " << getPredicateText(ICI->getPredicate());
1163 // Print out the type of the operands...
1164 const Value *Operand = I.getNumOperands() ? I.getOperand(0) : 0;
1166 // Special case conditional branches to swizzle the condition out to the front
1167 if (isa<BranchInst>(I) && I.getNumOperands() > 1) {
1168 writeOperand(I.getOperand(2), true);
1170 writeOperand(Operand, true);
1172 writeOperand(I.getOperand(1), true);
1174 } else if (isa<SwitchInst>(I)) {
1175 // Special case switch statement to get formatting nice and correct...
1176 writeOperand(Operand , true); Out << ',';
1177 writeOperand(I.getOperand(1), true); Out << " [";
1179 for (unsigned op = 2, Eop = I.getNumOperands(); op < Eop; op += 2) {
1181 writeOperand(I.getOperand(op ), true); Out << ',';
1182 writeOperand(I.getOperand(op+1), true);
1185 } else if (isa<PHINode>(I)) {
1187 printType(I.getType());
1190 for (unsigned op = 0, Eop = I.getNumOperands(); op < Eop; op += 2) {
1191 if (op) Out << ", ";
1193 writeOperand(I.getOperand(op ), false); Out << ',';
1194 writeOperand(I.getOperand(op+1), false); Out << " ]";
1196 } else if (isa<ReturnInst>(I) && !Operand) {
1198 } else if (const CallInst *CI = dyn_cast<CallInst>(&I)) {
1199 // Print the calling convention being used.
1200 switch (CI->getCallingConv()) {
1201 case CallingConv::C: break; // default
1202 case CallingConv::CSRet: Out << " csretcc"; break;
1203 case CallingConv::Fast: Out << " fastcc"; break;
1204 case CallingConv::Cold: Out << " coldcc"; break;
1205 case CallingConv::X86_StdCall: Out << "x86_stdcallcc "; break;
1206 case CallingConv::X86_FastCall: Out << "x86_fastcallcc "; break;
1207 default: Out << " cc" << CI->getCallingConv(); break;
1210 const PointerType *PTy = cast<PointerType>(Operand->getType());
1211 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
1212 const Type *RetTy = FTy->getReturnType();
1214 // If possible, print out the short form of the call instruction. We can
1215 // only do this if the first argument is a pointer to a nonvararg function,
1216 // and if the return type is not a pointer to a function.
1218 if (!FTy->isVarArg() &&
1219 (!isa<PointerType>(RetTy) ||
1220 !isa<FunctionType>(cast<PointerType>(RetTy)->getElementType()))) {
1221 Out << ' '; printType(RetTy);
1222 writeOperand(Operand, false);
1224 writeOperand(Operand, true);
1227 for (unsigned op = 1, Eop = I.getNumOperands(); op < Eop; ++op) {
1230 writeOperand(I.getOperand(op), true);
1231 if (FTy->getParamAttrs(op) != FunctionType::NoAttributeSet)
1232 Out << " " << FTy->getParamAttrsText(FTy->getParamAttrs(op));
1235 if (FTy->getParamAttrs(0) != FunctionType::NoAttributeSet)
1236 Out << ' ' << FTy->getParamAttrsText(FTy->getParamAttrs(0));
1237 } else if (const InvokeInst *II = dyn_cast<InvokeInst>(&I)) {
1238 const PointerType *PTy = cast<PointerType>(Operand->getType());
1239 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
1240 const Type *RetTy = FTy->getReturnType();
1242 // Print the calling convention being used.
1243 switch (II->getCallingConv()) {
1244 case CallingConv::C: break; // default
1245 case CallingConv::CSRet: Out << " csretcc"; break;
1246 case CallingConv::Fast: Out << " fastcc"; break;
1247 case CallingConv::Cold: Out << " coldcc"; break;
1248 case CallingConv::X86_StdCall: Out << "x86_stdcallcc "; break;
1249 case CallingConv::X86_FastCall: Out << "x86_fastcallcc "; break;
1250 default: Out << " cc" << II->getCallingConv(); break;
1253 // If possible, print out the short form of the invoke instruction. We can
1254 // only do this if the first argument is a pointer to a nonvararg function,
1255 // and if the return type is not a pointer to a function.
1257 if (!FTy->isVarArg() &&
1258 (!isa<PointerType>(RetTy) ||
1259 !isa<FunctionType>(cast<PointerType>(RetTy)->getElementType()))) {
1260 Out << ' '; printType(RetTy);
1261 writeOperand(Operand, false);
1263 writeOperand(Operand, true);
1267 for (unsigned op = 3, Eop = I.getNumOperands(); op < Eop; ++op) {
1270 writeOperand(I.getOperand(op), true);
1271 if (FTy->getParamAttrs(op-2) != FunctionType::NoAttributeSet)
1272 Out << " " << FTy->getParamAttrsText(FTy->getParamAttrs(op-2));
1276 if (FTy->getParamAttrs(0) != FunctionType::NoAttributeSet)
1277 Out << " " << FTy->getParamAttrsText(FTy->getParamAttrs(0));
1278 Out << "\n\t\t\tto";
1279 writeOperand(II->getNormalDest(), true);
1281 writeOperand(II->getUnwindDest(), true);
1283 } else if (const AllocationInst *AI = dyn_cast<AllocationInst>(&I)) {
1285 printType(AI->getType()->getElementType());
1286 if (AI->isArrayAllocation()) {
1288 writeOperand(AI->getArraySize(), true);
1290 if (AI->getAlignment()) {
1291 Out << ", align " << AI->getAlignment();
1293 } else if (isa<CastInst>(I)) {
1294 if (Operand) writeOperand(Operand, true); // Work with broken code
1296 printType(I.getType());
1297 } else if (isa<VAArgInst>(I)) {
1298 if (Operand) writeOperand(Operand, true); // Work with broken code
1300 printType(I.getType());
1301 } else if (Operand) { // Print the normal way...
1303 // PrintAllTypes - Instructions who have operands of all the same type
1304 // omit the type from all but the first operand. If the instruction has
1305 // different type operands (for example br), then they are all printed.
1306 bool PrintAllTypes = false;
1307 const Type *TheType = Operand->getType();
1309 // Shift Left & Right print both types even for Ubyte LHS, and select prints
1310 // types even if all operands are bools.
1311 if (isa<ShiftInst>(I) || isa<SelectInst>(I) || isa<StoreInst>(I) ||
1312 isa<ShuffleVectorInst>(I)) {
1313 PrintAllTypes = true;
1315 for (unsigned i = 1, E = I.getNumOperands(); i != E; ++i) {
1316 Operand = I.getOperand(i);
1317 if (Operand->getType() != TheType) {
1318 PrintAllTypes = true; // We have differing types! Print them all!
1324 if (!PrintAllTypes) {
1329 for (unsigned i = 0, E = I.getNumOperands(); i != E; ++i) {
1331 writeOperand(I.getOperand(i), PrintAllTypes);
1335 printInfoComment(I);
1340 //===----------------------------------------------------------------------===//
1341 // External Interface declarations
1342 //===----------------------------------------------------------------------===//
1344 void Module::print(std::ostream &o, AssemblyAnnotationWriter *AAW) const {
1345 SlotMachine SlotTable(this);
1346 AssemblyWriter W(o, SlotTable, this, AAW);
1350 void GlobalVariable::print(std::ostream &o) const {
1351 SlotMachine SlotTable(getParent());
1352 AssemblyWriter W(o, SlotTable, getParent(), 0);
1356 void Function::print(std::ostream &o, AssemblyAnnotationWriter *AAW) const {
1357 SlotMachine SlotTable(getParent());
1358 AssemblyWriter W(o, SlotTable, getParent(), AAW);
1363 void InlineAsm::print(std::ostream &o, AssemblyAnnotationWriter *AAW) const {
1364 WriteAsOperand(o, this, true, 0);
1367 void BasicBlock::print(std::ostream &o, AssemblyAnnotationWriter *AAW) const {
1368 SlotMachine SlotTable(getParent());
1369 AssemblyWriter W(o, SlotTable,
1370 getParent() ? getParent()->getParent() : 0, AAW);
1374 void Instruction::print(std::ostream &o, AssemblyAnnotationWriter *AAW) const {
1375 const Function *F = getParent() ? getParent()->getParent() : 0;
1376 SlotMachine SlotTable(F);
1377 AssemblyWriter W(o, SlotTable, F ? F->getParent() : 0, AAW);
1382 void Constant::print(std::ostream &o) const {
1383 if (this == 0) { o << "<null> constant value\n"; return; }
1385 o << ' ' << getType()->getDescription() << ' ';
1387 std::map<const Type *, std::string> TypeTable;
1388 WriteConstantInt(o, this, TypeTable, 0);
1391 void Type::print(std::ostream &o) const {
1395 o << getDescription();
1398 void Argument::print(std::ostream &o) const {
1399 WriteAsOperand(o, this, true, getParent() ? getParent()->getParent() : 0);
1402 // Value::dump - allow easy printing of Values from the debugger.
1403 // Located here because so much of the needed functionality is here.
1404 void Value::dump() const { print(*cerr.stream()); cerr << '\n'; }
1406 // Type::dump - allow easy printing of Values from the debugger.
1407 // Located here because so much of the needed functionality is here.
1408 void Type::dump() const { print(*cerr.stream()); cerr << '\n'; }
1410 //===----------------------------------------------------------------------===//
1411 // SlotMachine Implementation
1412 //===----------------------------------------------------------------------===//
1415 #define SC_DEBUG(X) cerr << X
1420 // Module level constructor. Causes the contents of the Module (sans functions)
1421 // to be added to the slot table.
1422 SlotMachine::SlotMachine(const Module *M)
1423 : TheModule(M) ///< Saved for lazy initialization.
1425 , FunctionProcessed(false)
1429 // Function level constructor. Causes the contents of the Module and the one
1430 // function provided to be added to the slot table.
1431 SlotMachine::SlotMachine(const Function *F)
1432 : TheModule(F ? F->getParent() : 0) ///< Saved for lazy initialization
1433 , TheFunction(F) ///< Saved for lazy initialization
1434 , FunctionProcessed(false)
1438 inline void SlotMachine::initialize() {
1441 TheModule = 0; ///< Prevent re-processing next time we're called.
1443 if (TheFunction && !FunctionProcessed)
1447 // Iterate through all the global variables, functions, and global
1448 // variable initializers and create slots for them.
1449 void SlotMachine::processModule() {
1450 SC_DEBUG("begin processModule!\n");
1452 // Add all of the unnamed global variables to the value table.
1453 for (Module::const_global_iterator I = TheModule->global_begin(),
1454 E = TheModule->global_end(); I != E; ++I)
1456 CreateModuleSlot(I);
1458 // Add all the unnamed functions to the table.
1459 for (Module::const_iterator I = TheModule->begin(), E = TheModule->end();
1462 CreateModuleSlot(I);
1464 SC_DEBUG("end processModule!\n");
1468 // Process the arguments, basic blocks, and instructions of a function.
1469 void SlotMachine::processFunction() {
1470 SC_DEBUG("begin processFunction!\n");
1472 // Add all the function arguments with no names.
1473 for(Function::const_arg_iterator AI = TheFunction->arg_begin(),
1474 AE = TheFunction->arg_end(); AI != AE; ++AI)
1476 CreateFunctionSlot(AI);
1478 SC_DEBUG("Inserting Instructions:\n");
1480 // Add all of the basic blocks and instructions with no names.
1481 for (Function::const_iterator BB = TheFunction->begin(),
1482 E = TheFunction->end(); BB != E; ++BB) {
1484 CreateFunctionSlot(BB);
1485 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I != E; ++I)
1486 if (I->getType() != Type::VoidTy && !I->hasName())
1487 CreateFunctionSlot(I);
1490 FunctionProcessed = true;
1492 SC_DEBUG("end processFunction!\n");
1495 /// Clean up after incorporating a function. This is the only way to get out of
1496 /// the function incorporation state that affects get*Slot/Create*Slot. Function
1497 /// incorporation state is indicated by TheFunction != 0.
1498 void SlotMachine::purgeFunction() {
1499 SC_DEBUG("begin purgeFunction!\n");
1500 fMap.clear(); // Simply discard the function level map
1502 FunctionProcessed = false;
1503 SC_DEBUG("end purgeFunction!\n");
1506 /// getGlobalSlot - Get the slot number of a global value.
1507 int SlotMachine::getGlobalSlot(const GlobalValue *V) {
1508 // Check for uninitialized state and do lazy initialization.
1511 // Find the type plane in the module map
1512 TypedPlanes::const_iterator MI = mMap.find(V->getType());
1513 if (MI == mMap.end()) return -1;
1515 // Lookup the value in the module plane's map.
1516 ValueMap::const_iterator MVI = MI->second.map.find(V);
1517 return MVI != MI->second.map.end() ? int(MVI->second) : -1;
1521 /// getLocalSlot - Get the slot number for a value that is local to a function.
1522 int SlotMachine::getLocalSlot(const Value *V) {
1523 assert(!isa<Constant>(V) && "Can't get a constant or global slot with this!");
1525 // Check for uninitialized state and do lazy initialization.
1528 // Get the type of the value
1529 const Type *VTy = V->getType();
1531 TypedPlanes::const_iterator FI = fMap.find(VTy);
1532 if (FI == fMap.end()) return -1;
1534 // Lookup the Value in the function and module maps.
1535 ValueMap::const_iterator FVI = FI->second.map.find(V);
1536 TypedPlanes::const_iterator MI = mMap.find(VTy);
1538 // If the value doesn't exist in the function map, it is a <badref>
1539 if (FVI == FI->second.map.end()) return -1;
1541 // Return the slot number as the module's contribution to
1542 // the type plane plus the index in the function's contribution
1543 // to the type plane.
1544 if (MI != mMap.end())
1545 return MI->second.next_slot + FVI->second;
1551 /// CreateModuleSlot - Insert the specified GlobalValue* into the slot table.
1552 void SlotMachine::CreateModuleSlot(const GlobalValue *V) {
1553 assert(V && "Can't insert a null Value into SlotMachine!");
1555 unsigned DestSlot = 0;
1556 const Type *VTy = V->getType();
1558 ValuePlane &PlaneMap = mMap[VTy];
1559 DestSlot = PlaneMap.map[V] = PlaneMap.next_slot++;
1561 SC_DEBUG(" Inserting value [" << VTy << "] = " << V << " slot=" <<
1563 // G = Global, F = Function, o = other
1564 SC_DEBUG((isa<GlobalVariable>(V) ? 'G' : 'F') << "]\n");
1568 /// CreateSlot - Create a new slot for the specified value if it has no name.
1569 void SlotMachine::CreateFunctionSlot(const Value *V) {
1570 const Type *VTy = V->getType();
1571 assert(VTy != Type::VoidTy && !V->hasName() && "Doesn't need a slot!");
1573 unsigned DestSlot = 0;
1575 ValuePlane &PlaneMap = fMap[VTy];
1576 DestSlot = PlaneMap.map[V] = PlaneMap.next_slot++;
1578 // G = Global, F = Function, o = other
1579 SC_DEBUG(" Inserting value [" << VTy << "] = " << V << " slot=" <<
1580 DestSlot << " [o]\n");