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/ADT/StringExtras.h"
29 #include "llvm/ADT/STLExtras.h"
30 #include "llvm/Support/CFG.h"
31 #include "llvm/Support/MathExtras.h"
32 #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. Its an error to ask for something not in the SlotMachine.
79 /// Its an error to ask for a Type*
80 int getSlot(const Value *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 /// Values can be crammed into here at will. If they haven't
106 /// been inserted already, they get inserted, otherwise they are ignored.
107 /// Either way, the slot number for the Value* is returned.
108 unsigned getOrCreateSlot(const Value *V);
110 /// Insert a value into the value table. Return the slot number
111 /// that it now occupies. BadThings(TM) will happen if you insert a
112 /// Value that's already been inserted.
113 unsigned insertValue(const Value *V);
115 /// Add all of the module level global variables (and their initializers)
116 /// and function declarations, but not the contents of those functions.
117 void processModule();
119 /// Add all of the functions arguments, basic blocks, and instructions
120 void processFunction();
122 SlotMachine(const SlotMachine &); // DO NOT IMPLEMENT
123 void operator=(const SlotMachine &); // DO NOT IMPLEMENT
130 /// @brief The module for which we are holding slot numbers
131 const Module* TheModule;
133 /// @brief The function for which we are holding slot numbers
134 const Function* TheFunction;
135 bool FunctionProcessed;
137 /// @brief The TypePlanes map for the module level data
140 /// @brief The TypePlanes map for the function level data
147 } // end namespace llvm
149 static RegisterPass<PrintModulePass>
150 X("printm", "Print module to stderr");
151 static RegisterPass<PrintFunctionPass>
152 Y("print","Print function to stderr");
154 static void WriteAsOperandInternal(std::ostream &Out, const Value *V,
155 std::map<const Type *, std::string> &TypeTable,
156 SlotMachine *Machine);
158 static const Module *getModuleFromVal(const Value *V) {
159 if (const Argument *MA = dyn_cast<Argument>(V))
160 return MA->getParent() ? MA->getParent()->getParent() : 0;
161 else if (const BasicBlock *BB = dyn_cast<BasicBlock>(V))
162 return BB->getParent() ? BB->getParent()->getParent() : 0;
163 else if (const Instruction *I = dyn_cast<Instruction>(V)) {
164 const Function *M = I->getParent() ? I->getParent()->getParent() : 0;
165 return M ? M->getParent() : 0;
166 } else if (const GlobalValue *GV = dyn_cast<GlobalValue>(V))
167 return GV->getParent();
171 static SlotMachine *createSlotMachine(const Value *V) {
172 if (const Argument *FA = dyn_cast<Argument>(V)) {
173 return new SlotMachine(FA->getParent());
174 } else if (const Instruction *I = dyn_cast<Instruction>(V)) {
175 return new SlotMachine(I->getParent()->getParent());
176 } else if (const BasicBlock *BB = dyn_cast<BasicBlock>(V)) {
177 return new SlotMachine(BB->getParent());
178 } else if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(V)){
179 return new SlotMachine(GV->getParent());
180 } else if (const Function *Func = dyn_cast<Function>(V)) {
181 return new SlotMachine(Func);
186 // getLLVMName - Turn the specified string into an 'LLVM name', which is either
187 // prefixed with % (if the string only contains simple characters) or is
188 // surrounded with ""'s (if it has special chars in it).
189 static std::string getLLVMName(const std::string &Name,
190 bool prefixName = true) {
191 assert(!Name.empty() && "Cannot get empty name!");
193 // First character cannot start with a number...
194 if (Name[0] >= '0' && Name[0] <= '9')
195 return "\"" + Name + "\"";
197 // Scan to see if we have any characters that are not on the "white list"
198 for (unsigned i = 0, e = Name.size(); i != e; ++i) {
200 assert(C != '"' && "Illegal character in LLVM value name!");
201 if ((C < 'a' || C > 'z') && (C < 'A' || C > 'Z') && (C < '0' || C > '9') &&
202 C != '-' && C != '.' && C != '_')
203 return "\"" + Name + "\"";
206 // If we get here, then the identifier is legal to use as a "VarID".
214 /// fillTypeNameTable - If the module has a symbol table, take all global types
215 /// and stuff their names into the TypeNames map.
217 static void fillTypeNameTable(const Module *M,
218 std::map<const Type *, std::string> &TypeNames) {
220 const SymbolTable &ST = M->getSymbolTable();
221 SymbolTable::type_const_iterator TI = ST.type_begin();
222 for (; TI != ST.type_end(); ++TI) {
223 // As a heuristic, don't insert pointer to primitive types, because
224 // they are used too often to have a single useful name.
226 const Type *Ty = cast<Type>(TI->second);
227 if (!isa<PointerType>(Ty) ||
228 !cast<PointerType>(Ty)->getElementType()->isPrimitiveType() ||
229 isa<OpaqueType>(cast<PointerType>(Ty)->getElementType()))
230 TypeNames.insert(std::make_pair(Ty, getLLVMName(TI->first)));
236 static void calcTypeName(const Type *Ty,
237 std::vector<const Type *> &TypeStack,
238 std::map<const Type *, std::string> &TypeNames,
239 std::string & Result){
240 if (Ty->isPrimitiveType() && !isa<OpaqueType>(Ty)) {
241 Result += Ty->getDescription(); // Base case
245 // Check to see if the type is named.
246 std::map<const Type *, std::string>::iterator I = TypeNames.find(Ty);
247 if (I != TypeNames.end()) {
252 if (isa<OpaqueType>(Ty)) {
257 // Check to see if the Type is already on the stack...
258 unsigned Slot = 0, CurSize = TypeStack.size();
259 while (Slot < CurSize && TypeStack[Slot] != Ty) ++Slot; // Scan for type
261 // This is another base case for the recursion. In this case, we know
262 // that we have looped back to a type that we have previously visited.
263 // Generate the appropriate upreference to handle this.
264 if (Slot < CurSize) {
265 Result += "\\" + utostr(CurSize-Slot); // Here's the upreference
269 TypeStack.push_back(Ty); // Recursive case: Add us to the stack..
271 switch (Ty->getTypeID()) {
272 case Type::FunctionTyID: {
273 const FunctionType *FTy = cast<FunctionType>(Ty);
274 calcTypeName(FTy->getReturnType(), TypeStack, TypeNames, Result);
276 for (FunctionType::param_iterator I = FTy->param_begin(),
277 E = FTy->param_end(); I != E; ++I) {
278 if (I != FTy->param_begin())
280 calcTypeName(*I, TypeStack, TypeNames, Result);
282 if (FTy->isVarArg()) {
283 if (FTy->getNumParams()) Result += ", ";
289 case Type::StructTyID: {
290 const StructType *STy = cast<StructType>(Ty);
292 for (StructType::element_iterator I = STy->element_begin(),
293 E = STy->element_end(); I != E; ++I) {
294 if (I != STy->element_begin())
296 calcTypeName(*I, TypeStack, TypeNames, Result);
301 case Type::PointerTyID:
302 calcTypeName(cast<PointerType>(Ty)->getElementType(),
303 TypeStack, TypeNames, Result);
306 case Type::ArrayTyID: {
307 const ArrayType *ATy = cast<ArrayType>(Ty);
308 Result += "[" + utostr(ATy->getNumElements()) + " x ";
309 calcTypeName(ATy->getElementType(), TypeStack, TypeNames, Result);
313 case Type::PackedTyID: {
314 const PackedType *PTy = cast<PackedType>(Ty);
315 Result += "<" + utostr(PTy->getNumElements()) + " x ";
316 calcTypeName(PTy->getElementType(), TypeStack, TypeNames, Result);
320 case Type::OpaqueTyID:
324 Result += "<unrecognized-type>";
328 TypeStack.pop_back(); // Remove self from stack...
332 /// printTypeInt - The internal guts of printing out a type that has a
333 /// potentially named portion.
335 static std::ostream &printTypeInt(std::ostream &Out, const Type *Ty,
336 std::map<const Type *, std::string> &TypeNames) {
337 // Primitive types always print out their description, regardless of whether
338 // they have been named or not.
340 if (Ty->isPrimitiveType() && !isa<OpaqueType>(Ty))
341 return Out << Ty->getDescription();
343 // Check to see if the type is named.
344 std::map<const Type *, std::string>::iterator I = TypeNames.find(Ty);
345 if (I != TypeNames.end()) return Out << I->second;
347 // Otherwise we have a type that has not been named but is a derived type.
348 // Carefully recurse the type hierarchy to print out any contained symbolic
351 std::vector<const Type *> TypeStack;
352 std::string TypeName;
353 calcTypeName(Ty, TypeStack, TypeNames, TypeName);
354 TypeNames.insert(std::make_pair(Ty, TypeName));//Cache type name for later use
355 return (Out << TypeName);
359 /// WriteTypeSymbolic - This attempts to write the specified type as a symbolic
360 /// type, iff there is an entry in the modules symbol table for the specified
361 /// type or one of it's component types. This is slower than a simple x << Type
363 std::ostream &llvm::WriteTypeSymbolic(std::ostream &Out, const Type *Ty,
367 // If they want us to print out a type, but there is no context, we can't
368 // print it symbolically.
370 return Out << Ty->getDescription();
372 std::map<const Type *, std::string> TypeNames;
373 fillTypeNameTable(M, TypeNames);
374 return printTypeInt(Out, Ty, TypeNames);
377 // PrintEscapedString - Print each character of the specified string, escaping
378 // it if it is not printable or if it is an escape char.
379 static void PrintEscapedString(const std::string &Str, std::ostream &Out) {
380 for (unsigned i = 0, e = Str.size(); i != e; ++i) {
381 unsigned char C = Str[i];
382 if (isprint(C) && C != '"' && C != '\\') {
386 << (char) ((C/16 < 10) ? ( C/16 +'0') : ( C/16 -10+'A'))
387 << (char)(((C&15) < 10) ? ((C&15)+'0') : ((C&15)-10+'A'));
392 static const char *getPredicateText(unsigned predicate) {
393 const char * pred = "unknown";
395 case FCmpInst::FCMP_FALSE: pred = "false"; break;
396 case FCmpInst::FCMP_OEQ: pred = "oeq"; break;
397 case FCmpInst::FCMP_OGT: pred = "ogt"; break;
398 case FCmpInst::FCMP_OGE: pred = "oge"; break;
399 case FCmpInst::FCMP_OLT: pred = "olt"; break;
400 case FCmpInst::FCMP_OLE: pred = "ole"; break;
401 case FCmpInst::FCMP_ONE: pred = "one"; break;
402 case FCmpInst::FCMP_ORD: pred = "ord"; break;
403 case FCmpInst::FCMP_UNO: pred = "uno"; break;
404 case FCmpInst::FCMP_UEQ: pred = "ueq"; break;
405 case FCmpInst::FCMP_UGT: pred = "ugt"; break;
406 case FCmpInst::FCMP_UGE: pred = "uge"; break;
407 case FCmpInst::FCMP_ULT: pred = "ult"; break;
408 case FCmpInst::FCMP_ULE: pred = "ule"; break;
409 case FCmpInst::FCMP_UNE: pred = "une"; break;
410 case FCmpInst::FCMP_TRUE: pred = "true"; break;
411 case ICmpInst::ICMP_EQ: pred = "eq"; break;
412 case ICmpInst::ICMP_NE: pred = "ne"; break;
413 case ICmpInst::ICMP_SGT: pred = "sgt"; break;
414 case ICmpInst::ICMP_SGE: pred = "sge"; break;
415 case ICmpInst::ICMP_SLT: pred = "slt"; break;
416 case ICmpInst::ICMP_SLE: pred = "sle"; break;
417 case ICmpInst::ICMP_UGT: pred = "ugt"; break;
418 case ICmpInst::ICMP_UGE: pred = "uge"; break;
419 case ICmpInst::ICMP_ULT: pred = "ult"; break;
420 case ICmpInst::ICMP_ULE: pred = "ule"; break;
425 /// @brief Internal constant writer.
426 static void WriteConstantInt(std::ostream &Out, const Constant *CV,
427 std::map<const Type *, std::string> &TypeTable,
428 SlotMachine *Machine) {
429 const int IndentSize = 4;
430 static std::string Indent = "\n";
431 if (const ConstantBool *CB = dyn_cast<ConstantBool>(CV)) {
432 Out << (CB->getValue() ? "true" : "false");
433 } else if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV)) {
434 if (CI->getType()->isSigned())
435 Out << CI->getSExtValue();
437 Out << CI->getZExtValue();
438 } else if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CV)) {
439 // We would like to output the FP constant value in exponential notation,
440 // but we cannot do this if doing so will lose precision. Check here to
441 // make sure that we only output it in exponential format if we can parse
442 // the value back and get the same value.
444 std::string StrVal = ftostr(CFP->getValue());
446 // Check to make sure that the stringized number is not some string like
447 // "Inf" or NaN, that atof will accept, but the lexer will not. Check that
448 // the string matches the "[-+]?[0-9]" regex.
450 if ((StrVal[0] >= '0' && StrVal[0] <= '9') ||
451 ((StrVal[0] == '-' || StrVal[0] == '+') &&
452 (StrVal[1] >= '0' && StrVal[1] <= '9')))
453 // Reparse stringized version!
454 if (atof(StrVal.c_str()) == CFP->getValue()) {
459 // Otherwise we could not reparse it to exactly the same value, so we must
460 // output the string in hexadecimal format!
461 assert(sizeof(double) == sizeof(uint64_t) &&
462 "assuming that double is 64 bits!");
463 Out << "0x" << utohexstr(DoubleToBits(CFP->getValue()));
465 } else if (isa<ConstantAggregateZero>(CV)) {
466 Out << "zeroinitializer";
467 } else if (const ConstantArray *CA = dyn_cast<ConstantArray>(CV)) {
468 // As a special case, print the array as a string if it is an array of
469 // ubytes or an array of sbytes with positive values.
471 const Type *ETy = CA->getType()->getElementType();
472 if (CA->isString()) {
474 PrintEscapedString(CA->getAsString(), Out);
477 } else { // Cannot output in string format...
479 if (CA->getNumOperands()) {
481 printTypeInt(Out, ETy, TypeTable);
482 WriteAsOperandInternal(Out, CA->getOperand(0),
484 for (unsigned i = 1, e = CA->getNumOperands(); i != e; ++i) {
486 printTypeInt(Out, ETy, TypeTable);
487 WriteAsOperandInternal(Out, CA->getOperand(i), TypeTable, Machine);
492 } else if (const ConstantStruct *CS = dyn_cast<ConstantStruct>(CV)) {
494 unsigned N = CS->getNumOperands();
497 Indent += std::string(IndentSize, ' ');
502 printTypeInt(Out, CS->getOperand(0)->getType(), TypeTable);
504 WriteAsOperandInternal(Out, CS->getOperand(0), TypeTable, Machine);
506 for (unsigned i = 1; i < N; i++) {
508 if (N > 2) Out << Indent;
509 printTypeInt(Out, CS->getOperand(i)->getType(), TypeTable);
511 WriteAsOperandInternal(Out, CS->getOperand(i), TypeTable, Machine);
513 if (N > 2) Indent.resize(Indent.size() - IndentSize);
517 } else if (const ConstantPacked *CP = dyn_cast<ConstantPacked>(CV)) {
518 const Type *ETy = CP->getType()->getElementType();
519 assert(CP->getNumOperands() > 0 &&
520 "Number of operands for a PackedConst must be > 0");
523 printTypeInt(Out, ETy, TypeTable);
524 WriteAsOperandInternal(Out, CP->getOperand(0), TypeTable, Machine);
525 for (unsigned i = 1, e = CP->getNumOperands(); i != e; ++i) {
527 printTypeInt(Out, ETy, TypeTable);
528 WriteAsOperandInternal(Out, CP->getOperand(i), TypeTable, Machine);
531 } else if (isa<ConstantPointerNull>(CV)) {
534 } else if (isa<UndefValue>(CV)) {
537 } else if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV)) {
538 Out << CE->getOpcodeName();
540 Out << " " << getPredicateText(CE->getPredicate());
543 for (User::const_op_iterator OI=CE->op_begin(); OI != CE->op_end(); ++OI) {
544 printTypeInt(Out, (*OI)->getType(), TypeTable);
545 WriteAsOperandInternal(Out, *OI, TypeTable, Machine);
546 if (OI+1 != CE->op_end())
552 printTypeInt(Out, CE->getType(), TypeTable);
558 Out << "<placeholder or erroneous Constant>";
563 /// WriteAsOperand - Write the name of the specified value out to the specified
564 /// ostream. This can be useful when you just want to print int %reg126, not
565 /// the whole instruction that generated it.
567 static void WriteAsOperandInternal(std::ostream &Out, const Value *V,
568 std::map<const Type*, std::string> &TypeTable,
569 SlotMachine *Machine) {
572 Out << getLLVMName(V->getName());
574 const Constant *CV = dyn_cast<Constant>(V);
575 if (CV && !isa<GlobalValue>(CV)) {
576 WriteConstantInt(Out, CV, TypeTable, Machine);
577 } else if (const InlineAsm *IA = dyn_cast<InlineAsm>(V)) {
579 if (IA->hasSideEffects())
580 Out << "sideeffect ";
582 PrintEscapedString(IA->getAsmString(), Out);
584 PrintEscapedString(IA->getConstraintString(), Out);
589 Slot = Machine->getSlot(V);
591 Machine = createSlotMachine(V);
593 Slot = Machine->getSlot(V);
606 /// WriteAsOperand - Write the name of the specified value out to the specified
607 /// ostream. This can be useful when you just want to print int %reg126, not
608 /// the whole instruction that generated it.
610 std::ostream &llvm::WriteAsOperand(std::ostream &Out, const Value *V,
611 bool PrintType, const Module *Context) {
612 std::map<const Type *, std::string> TypeNames;
613 if (Context == 0) Context = getModuleFromVal(V);
616 fillTypeNameTable(Context, TypeNames);
619 printTypeInt(Out, V->getType(), TypeNames);
621 WriteAsOperandInternal(Out, V, TypeNames, 0);
628 class AssemblyWriter {
630 SlotMachine &Machine;
631 const Module *TheModule;
632 std::map<const Type *, std::string> TypeNames;
633 AssemblyAnnotationWriter *AnnotationWriter;
635 inline AssemblyWriter(std::ostream &o, SlotMachine &Mac, const Module *M,
636 AssemblyAnnotationWriter *AAW)
637 : Out(o), Machine(Mac), TheModule(M), AnnotationWriter(AAW) {
639 // If the module has a symbol table, take all global types and stuff their
640 // names into the TypeNames map.
642 fillTypeNameTable(M, TypeNames);
645 inline void write(const Module *M) { printModule(M); }
646 inline void write(const GlobalVariable *G) { printGlobal(G); }
647 inline void write(const Function *F) { printFunction(F); }
648 inline void write(const BasicBlock *BB) { printBasicBlock(BB); }
649 inline void write(const Instruction *I) { printInstruction(*I); }
650 inline void write(const Constant *CPV) { printConstant(CPV); }
651 inline void write(const Type *Ty) { printType(Ty); }
653 void writeOperand(const Value *Op, bool PrintType);
655 const Module* getModule() { return TheModule; }
658 void printModule(const Module *M);
659 void printSymbolTable(const SymbolTable &ST);
660 void printConstant(const Constant *CPV);
661 void printGlobal(const GlobalVariable *GV);
662 void printFunction(const Function *F);
663 void printArgument(const Argument *FA);
664 void printBasicBlock(const BasicBlock *BB);
665 void printInstruction(const Instruction &I);
667 // printType - Go to extreme measures to attempt to print out a short,
668 // symbolic version of a type name.
670 std::ostream &printType(const Type *Ty) {
671 return printTypeInt(Out, Ty, TypeNames);
674 // printTypeAtLeastOneLevel - Print out one level of the possibly complex type
675 // without considering any symbolic types that we may have equal to it.
677 std::ostream &printTypeAtLeastOneLevel(const Type *Ty);
679 // printInfoComment - Print a little comment after the instruction indicating
680 // which slot it occupies.
681 void printInfoComment(const Value &V);
683 } // end of llvm namespace
685 /// printTypeAtLeastOneLevel - Print out one level of the possibly complex type
686 /// without considering any symbolic types that we may have equal to it.
688 std::ostream &AssemblyWriter::printTypeAtLeastOneLevel(const Type *Ty) {
689 if (const FunctionType *FTy = dyn_cast<FunctionType>(Ty)) {
690 printType(FTy->getReturnType()) << " (";
691 for (FunctionType::param_iterator I = FTy->param_begin(),
692 E = FTy->param_end(); I != E; ++I) {
693 if (I != FTy->param_begin())
697 if (FTy->isVarArg()) {
698 if (FTy->getNumParams()) Out << ", ";
702 } else if (const StructType *STy = dyn_cast<StructType>(Ty)) {
704 for (StructType::element_iterator I = STy->element_begin(),
705 E = STy->element_end(); I != E; ++I) {
706 if (I != STy->element_begin())
711 } else if (const PointerType *PTy = dyn_cast<PointerType>(Ty)) {
712 printType(PTy->getElementType()) << '*';
713 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
714 Out << '[' << ATy->getNumElements() << " x ";
715 printType(ATy->getElementType()) << ']';
716 } else if (const PackedType *PTy = dyn_cast<PackedType>(Ty)) {
717 Out << '<' << PTy->getNumElements() << " x ";
718 printType(PTy->getElementType()) << '>';
720 else if (isa<OpaqueType>(Ty)) {
723 if (!Ty->isPrimitiveType())
724 Out << "<unknown derived type>";
731 void AssemblyWriter::writeOperand(const Value *Operand, bool PrintType) {
733 Out << "<null operand!>";
735 if (PrintType) { Out << ' '; printType(Operand->getType()); }
736 WriteAsOperandInternal(Out, Operand, TypeNames, &Machine);
741 void AssemblyWriter::printModule(const Module *M) {
742 if (!M->getModuleIdentifier().empty() &&
743 // Don't print the ID if it will start a new line (which would
744 // require a comment char before it).
745 M->getModuleIdentifier().find('\n') == std::string::npos)
746 Out << "; ModuleID = '" << M->getModuleIdentifier() << "'\n";
748 if (!M->getDataLayout().empty())
749 Out << "target datalayout = \"" << M->getDataLayout() << "\"\n";
751 switch (M->getEndianness()) {
752 case Module::LittleEndian: Out << "target endian = little\n"; break;
753 case Module::BigEndian: Out << "target endian = big\n"; break;
754 case Module::AnyEndianness: break;
756 switch (M->getPointerSize()) {
757 case Module::Pointer32: Out << "target pointersize = 32\n"; break;
758 case Module::Pointer64: Out << "target pointersize = 64\n"; break;
759 case Module::AnyPointerSize: break;
761 if (!M->getTargetTriple().empty())
762 Out << "target triple = \"" << M->getTargetTriple() << "\"\n";
764 if (!M->getModuleInlineAsm().empty()) {
765 // Split the string into lines, to make it easier to read the .ll file.
766 std::string Asm = M->getModuleInlineAsm();
768 size_t NewLine = Asm.find_first_of('\n', CurPos);
769 while (NewLine != std::string::npos) {
770 // We found a newline, print the portion of the asm string from the
771 // last newline up to this newline.
772 Out << "module asm \"";
773 PrintEscapedString(std::string(Asm.begin()+CurPos, Asm.begin()+NewLine),
777 NewLine = Asm.find_first_of('\n', CurPos);
779 Out << "module asm \"";
780 PrintEscapedString(std::string(Asm.begin()+CurPos, Asm.end()), Out);
784 // Loop over the dependent libraries and emit them.
785 Module::lib_iterator LI = M->lib_begin();
786 Module::lib_iterator LE = M->lib_end();
788 Out << "deplibs = [ ";
790 Out << '"' << *LI << '"';
798 // Loop over the symbol table, emitting all named constants.
799 printSymbolTable(M->getSymbolTable());
801 for (Module::const_global_iterator I = M->global_begin(), E = M->global_end();
805 Out << "\nimplementation ; Functions:\n";
807 // Output all of the functions.
808 for (Module::const_iterator I = M->begin(), E = M->end(); I != E; ++I)
812 void AssemblyWriter::printGlobal(const GlobalVariable *GV) {
813 if (GV->hasName()) Out << getLLVMName(GV->getName()) << " = ";
815 if (!GV->hasInitializer())
816 switch (GV->getLinkage()) {
817 case GlobalValue::DLLImportLinkage: Out << "dllimport "; break;
818 case GlobalValue::ExternalWeakLinkage: Out << "extern_weak "; break;
819 default: Out << "external "; break;
822 switch (GV->getLinkage()) {
823 case GlobalValue::InternalLinkage: Out << "internal "; break;
824 case GlobalValue::LinkOnceLinkage: Out << "linkonce "; break;
825 case GlobalValue::WeakLinkage: Out << "weak "; break;
826 case GlobalValue::AppendingLinkage: Out << "appending "; break;
827 case GlobalValue::DLLImportLinkage: Out << "dllimport "; break;
828 case GlobalValue::DLLExportLinkage: Out << "dllexport "; break;
829 case GlobalValue::ExternalWeakLinkage: Out << "extern_weak "; break;
830 case GlobalValue::ExternalLinkage: break;
831 case GlobalValue::GhostLinkage:
832 cerr << "GhostLinkage not allowed in AsmWriter!\n";
836 Out << (GV->isConstant() ? "constant " : "global ");
837 printType(GV->getType()->getElementType());
839 if (GV->hasInitializer()) {
840 Constant* C = cast<Constant>(GV->getInitializer());
841 assert(C && "GlobalVar initializer isn't constant?");
842 writeOperand(GV->getInitializer(), false);
845 if (GV->hasSection())
846 Out << ", section \"" << GV->getSection() << '"';
847 if (GV->getAlignment())
848 Out << ", align " << GV->getAlignment();
850 printInfoComment(*GV);
855 // printSymbolTable - Run through symbol table looking for constants
856 // and types. Emit their declarations.
857 void AssemblyWriter::printSymbolTable(const SymbolTable &ST) {
860 for (SymbolTable::type_const_iterator TI = ST.type_begin();
861 TI != ST.type_end(); ++TI) {
862 Out << "\t" << getLLVMName(TI->first) << " = type ";
864 // Make sure we print out at least one level of the type structure, so
865 // that we do not get %FILE = type %FILE
867 printTypeAtLeastOneLevel(TI->second) << "\n";
870 // Print the constants, in type plane order.
871 for (SymbolTable::plane_const_iterator PI = ST.plane_begin();
872 PI != ST.plane_end(); ++PI) {
873 SymbolTable::value_const_iterator VI = ST.value_begin(PI->first);
874 SymbolTable::value_const_iterator VE = ST.value_end(PI->first);
876 for (; VI != VE; ++VI) {
877 const Value* V = VI->second;
878 const Constant *CPV = dyn_cast<Constant>(V) ;
879 if (CPV && !isa<GlobalValue>(V)) {
887 /// printConstant - Print out a constant pool entry...
889 void AssemblyWriter::printConstant(const Constant *CPV) {
890 // Don't print out unnamed constants, they will be inlined
891 if (!CPV->hasName()) return;
894 Out << "\t" << getLLVMName(CPV->getName()) << " =";
896 // Write the value out now.
897 writeOperand(CPV, true);
899 printInfoComment(*CPV);
903 /// printFunction - Print all aspects of a function.
905 void AssemblyWriter::printFunction(const Function *F) {
906 // Print out the return type and name...
909 // Ensure that no local symbols conflict with global symbols.
910 const_cast<Function*>(F)->renameLocalSymbols();
912 if (AnnotationWriter) AnnotationWriter->emitFunctionAnnot(F, Out);
915 switch (F->getLinkage()) {
916 case GlobalValue::DLLImportLinkage: Out << "declare dllimport "; break;
917 case GlobalValue::ExternalWeakLinkage: Out << "declare extern_weak "; break;
918 default: Out << "declare ";
921 switch (F->getLinkage()) {
922 case GlobalValue::InternalLinkage: Out << "internal "; break;
923 case GlobalValue::LinkOnceLinkage: Out << "linkonce "; break;
924 case GlobalValue::WeakLinkage: Out << "weak "; break;
925 case GlobalValue::AppendingLinkage: Out << "appending "; break;
926 case GlobalValue::DLLImportLinkage: Out << "dllimport "; break;
927 case GlobalValue::DLLExportLinkage: Out << "dllexport "; break;
928 case GlobalValue::ExternalWeakLinkage: Out << "extern_weak "; break;
929 case GlobalValue::ExternalLinkage: break;
930 case GlobalValue::GhostLinkage:
931 cerr << "GhostLinkage not allowed in AsmWriter!\n";
935 // Print the calling convention.
936 switch (F->getCallingConv()) {
937 case CallingConv::C: break; // default
938 case CallingConv::CSRet: Out << "csretcc "; break;
939 case CallingConv::Fast: Out << "fastcc "; break;
940 case CallingConv::Cold: Out << "coldcc "; break;
941 case CallingConv::X86_StdCall: Out << "x86_stdcallcc "; break;
942 case CallingConv::X86_FastCall: Out << "x86_fastcallcc "; break;
943 default: Out << "cc" << F->getCallingConv() << " "; break;
946 printType(F->getReturnType()) << ' ';
947 if (!F->getName().empty())
948 Out << getLLVMName(F->getName());
952 Machine.incorporateFunction(F);
954 // Loop over the arguments, printing them...
955 const FunctionType *FT = F->getFunctionType();
957 for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
961 // Finish printing arguments...
962 if (FT->isVarArg()) {
963 if (FT->getNumParams()) Out << ", ";
964 Out << "..."; // Output varargs portion of signature!
969 Out << " section \"" << F->getSection() << '"';
970 if (F->getAlignment())
971 Out << " align " << F->getAlignment();
973 if (F->isExternal()) {
978 // Output all of its basic blocks... for the function
979 for (Function::const_iterator I = F->begin(), E = F->end(); I != E; ++I)
985 Machine.purgeFunction();
988 /// printArgument - This member is called for every argument that is passed into
989 /// the function. Simply print it out
991 void AssemblyWriter::printArgument(const Argument *Arg) {
992 // Insert commas as we go... the first arg doesn't get a comma
993 if (Arg != Arg->getParent()->arg_begin()) Out << ", ";
996 printType(Arg->getType());
998 // Output name, if available...
1000 Out << ' ' << getLLVMName(Arg->getName());
1003 /// printBasicBlock - This member is called for each basic block in a method.
1005 void AssemblyWriter::printBasicBlock(const BasicBlock *BB) {
1006 if (BB->hasName()) { // Print out the label if it exists...
1007 Out << "\n" << getLLVMName(BB->getName(), false) << ':';
1008 } else if (!BB->use_empty()) { // Don't print block # of no uses...
1009 Out << "\n; <label>:";
1010 int Slot = Machine.getSlot(BB);
1017 if (BB->getParent() == 0)
1018 Out << "\t\t; Error: Block without parent!";
1020 if (BB != &BB->getParent()->front()) { // Not the entry block?
1021 // Output predecessors for the block...
1023 pred_const_iterator PI = pred_begin(BB), PE = pred_end(BB);
1026 Out << " No predecessors!";
1029 writeOperand(*PI, false);
1030 for (++PI; PI != PE; ++PI) {
1032 writeOperand(*PI, false);
1040 if (AnnotationWriter) AnnotationWriter->emitBasicBlockStartAnnot(BB, Out);
1042 // Output all of the instructions in the basic block...
1043 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I != E; ++I)
1044 printInstruction(*I);
1046 if (AnnotationWriter) AnnotationWriter->emitBasicBlockEndAnnot(BB, Out);
1050 /// printInfoComment - Print a little comment after the instruction indicating
1051 /// which slot it occupies.
1053 void AssemblyWriter::printInfoComment(const Value &V) {
1054 if (V.getType() != Type::VoidTy) {
1056 printType(V.getType()) << '>';
1059 int SlotNum = Machine.getSlot(&V);
1063 Out << ':' << SlotNum; // Print out the def slot taken.
1065 Out << " [#uses=" << V.getNumUses() << ']'; // Output # uses
1069 // This member is called for each Instruction in a function..
1070 void AssemblyWriter::printInstruction(const Instruction &I) {
1071 if (AnnotationWriter) AnnotationWriter->emitInstructionAnnot(&I, Out);
1075 // Print out name if it exists...
1077 Out << getLLVMName(I.getName()) << " = ";
1079 // If this is a volatile load or store, print out the volatile marker.
1080 if ((isa<LoadInst>(I) && cast<LoadInst>(I).isVolatile()) ||
1081 (isa<StoreInst>(I) && cast<StoreInst>(I).isVolatile())) {
1083 } else if (isa<CallInst>(I) && cast<CallInst>(I).isTailCall()) {
1084 // If this is a call, check if it's a tail call.
1088 // Print out the opcode...
1089 Out << I.getOpcodeName();
1091 // Print out the compare instruction predicates
1092 if (const FCmpInst *FCI = dyn_cast<FCmpInst>(&I)) {
1093 Out << " " << getPredicateText(FCI->getPredicate());
1094 } else if (const ICmpInst *ICI = dyn_cast<ICmpInst>(&I)) {
1095 Out << " " << getPredicateText(ICI->getPredicate());
1098 // Print out the type of the operands...
1099 const Value *Operand = I.getNumOperands() ? I.getOperand(0) : 0;
1101 // Special case conditional branches to swizzle the condition out to the front
1102 if (isa<BranchInst>(I) && I.getNumOperands() > 1) {
1103 writeOperand(I.getOperand(2), true);
1105 writeOperand(Operand, true);
1107 writeOperand(I.getOperand(1), true);
1109 } else if (isa<SwitchInst>(I)) {
1110 // Special case switch statement to get formatting nice and correct...
1111 writeOperand(Operand , true); Out << ',';
1112 writeOperand(I.getOperand(1), true); Out << " [";
1114 for (unsigned op = 2, Eop = I.getNumOperands(); op < Eop; op += 2) {
1116 writeOperand(I.getOperand(op ), true); Out << ',';
1117 writeOperand(I.getOperand(op+1), true);
1120 } else if (isa<PHINode>(I)) {
1122 printType(I.getType());
1125 for (unsigned op = 0, Eop = I.getNumOperands(); op < Eop; op += 2) {
1126 if (op) Out << ", ";
1128 writeOperand(I.getOperand(op ), false); Out << ',';
1129 writeOperand(I.getOperand(op+1), false); Out << " ]";
1131 } else if (isa<ReturnInst>(I) && !Operand) {
1133 } else if (const CallInst *CI = dyn_cast<CallInst>(&I)) {
1134 // Print the calling convention being used.
1135 switch (CI->getCallingConv()) {
1136 case CallingConv::C: break; // default
1137 case CallingConv::CSRet: Out << " csretcc"; break;
1138 case CallingConv::Fast: Out << " fastcc"; break;
1139 case CallingConv::Cold: Out << " coldcc"; break;
1140 case CallingConv::X86_StdCall: Out << "x86_stdcallcc "; break;
1141 case CallingConv::X86_FastCall: Out << "x86_fastcallcc "; break;
1142 default: Out << " cc" << CI->getCallingConv(); break;
1145 const PointerType *PTy = cast<PointerType>(Operand->getType());
1146 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
1147 const Type *RetTy = FTy->getReturnType();
1149 // If possible, print out the short form of the call instruction. We can
1150 // only do this if the first argument is a pointer to a nonvararg function,
1151 // and if the return type is not a pointer to a function.
1153 if (!FTy->isVarArg() &&
1154 (!isa<PointerType>(RetTy) ||
1155 !isa<FunctionType>(cast<PointerType>(RetTy)->getElementType()))) {
1156 Out << ' '; printType(RetTy);
1157 writeOperand(Operand, false);
1159 writeOperand(Operand, true);
1162 if (CI->getNumOperands() > 1) writeOperand(CI->getOperand(1), true);
1163 for (unsigned op = 2, Eop = I.getNumOperands(); op < Eop; ++op) {
1165 writeOperand(I.getOperand(op), true);
1169 } else if (const InvokeInst *II = dyn_cast<InvokeInst>(&I)) {
1170 const PointerType *PTy = cast<PointerType>(Operand->getType());
1171 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
1172 const Type *RetTy = FTy->getReturnType();
1174 // Print the calling convention being used.
1175 switch (II->getCallingConv()) {
1176 case CallingConv::C: break; // default
1177 case CallingConv::CSRet: Out << " csretcc"; break;
1178 case CallingConv::Fast: Out << " fastcc"; break;
1179 case CallingConv::Cold: Out << " coldcc"; break;
1180 case CallingConv::X86_StdCall: Out << "x86_stdcallcc "; break;
1181 case CallingConv::X86_FastCall: Out << "x86_fastcallcc "; break;
1182 default: Out << " cc" << II->getCallingConv(); break;
1185 // If possible, print out the short form of the invoke instruction. We can
1186 // only do this if the first argument is a pointer to a nonvararg function,
1187 // and if the return type is not a pointer to a function.
1189 if (!FTy->isVarArg() &&
1190 (!isa<PointerType>(RetTy) ||
1191 !isa<FunctionType>(cast<PointerType>(RetTy)->getElementType()))) {
1192 Out << ' '; printType(RetTy);
1193 writeOperand(Operand, false);
1195 writeOperand(Operand, true);
1199 if (I.getNumOperands() > 3) writeOperand(I.getOperand(3), true);
1200 for (unsigned op = 4, Eop = I.getNumOperands(); op < Eop; ++op) {
1202 writeOperand(I.getOperand(op), true);
1205 Out << " )\n\t\t\tto";
1206 writeOperand(II->getNormalDest(), true);
1208 writeOperand(II->getUnwindDest(), true);
1210 } else if (const AllocationInst *AI = dyn_cast<AllocationInst>(&I)) {
1212 printType(AI->getType()->getElementType());
1213 if (AI->isArrayAllocation()) {
1215 writeOperand(AI->getArraySize(), true);
1217 if (AI->getAlignment()) {
1218 Out << ", align " << AI->getAlignment();
1220 } else if (isa<CastInst>(I)) {
1221 if (Operand) writeOperand(Operand, true); // Work with broken code
1223 printType(I.getType());
1224 } else if (isa<VAArgInst>(I)) {
1225 if (Operand) writeOperand(Operand, true); // Work with broken code
1227 printType(I.getType());
1228 } else if (Operand) { // Print the normal way...
1230 // PrintAllTypes - Instructions who have operands of all the same type
1231 // omit the type from all but the first operand. If the instruction has
1232 // different type operands (for example br), then they are all printed.
1233 bool PrintAllTypes = false;
1234 const Type *TheType = Operand->getType();
1236 // Shift Left & Right print both types even for Ubyte LHS, and select prints
1237 // types even if all operands are bools.
1238 if (isa<ShiftInst>(I) || isa<SelectInst>(I) || isa<StoreInst>(I) ||
1239 isa<ShuffleVectorInst>(I)) {
1240 PrintAllTypes = true;
1242 for (unsigned i = 1, E = I.getNumOperands(); i != E; ++i) {
1243 Operand = I.getOperand(i);
1244 if (Operand->getType() != TheType) {
1245 PrintAllTypes = true; // We have differing types! Print them all!
1251 if (!PrintAllTypes) {
1256 for (unsigned i = 0, E = I.getNumOperands(); i != E; ++i) {
1258 writeOperand(I.getOperand(i), PrintAllTypes);
1262 printInfoComment(I);
1267 //===----------------------------------------------------------------------===//
1268 // External Interface declarations
1269 //===----------------------------------------------------------------------===//
1271 void Module::print(std::ostream &o, AssemblyAnnotationWriter *AAW) const {
1272 SlotMachine SlotTable(this);
1273 AssemblyWriter W(o, SlotTable, this, AAW);
1277 void GlobalVariable::print(std::ostream &o) const {
1278 SlotMachine SlotTable(getParent());
1279 AssemblyWriter W(o, SlotTable, getParent(), 0);
1283 void Function::print(std::ostream &o, AssemblyAnnotationWriter *AAW) const {
1284 SlotMachine SlotTable(getParent());
1285 AssemblyWriter W(o, SlotTable, getParent(), AAW);
1290 void InlineAsm::print(std::ostream &o, AssemblyAnnotationWriter *AAW) const {
1291 WriteAsOperand(o, this, true, 0);
1294 void BasicBlock::print(std::ostream &o, AssemblyAnnotationWriter *AAW) const {
1295 SlotMachine SlotTable(getParent());
1296 AssemblyWriter W(o, SlotTable,
1297 getParent() ? getParent()->getParent() : 0, AAW);
1301 void Instruction::print(std::ostream &o, AssemblyAnnotationWriter *AAW) const {
1302 const Function *F = getParent() ? getParent()->getParent() : 0;
1303 SlotMachine SlotTable(F);
1304 AssemblyWriter W(o, SlotTable, F ? F->getParent() : 0, AAW);
1309 void Constant::print(std::ostream &o) const {
1310 if (this == 0) { o << "<null> constant value\n"; return; }
1312 o << ' ' << getType()->getDescription() << ' ';
1314 std::map<const Type *, std::string> TypeTable;
1315 WriteConstantInt(o, this, TypeTable, 0);
1318 void Type::print(std::ostream &o) const {
1322 o << getDescription();
1325 void Argument::print(std::ostream &o) const {
1326 WriteAsOperand(o, this, true, getParent() ? getParent()->getParent() : 0);
1329 // Value::dump - allow easy printing of Values from the debugger.
1330 // Located here because so much of the needed functionality is here.
1331 void Value::dump() const { print(std::cerr); cerr << '\n'; }
1333 // Type::dump - allow easy printing of Values from the debugger.
1334 // Located here because so much of the needed functionality is here.
1335 void Type::dump() const { print(std::cerr); cerr << '\n'; }
1337 //===----------------------------------------------------------------------===//
1338 // SlotMachine Implementation
1339 //===----------------------------------------------------------------------===//
1342 #define SC_DEBUG(X) cerr << X
1347 // Module level constructor. Causes the contents of the Module (sans functions)
1348 // to be added to the slot table.
1349 SlotMachine::SlotMachine(const Module *M)
1350 : TheModule(M) ///< Saved for lazy initialization.
1352 , FunctionProcessed(false)
1356 // Function level constructor. Causes the contents of the Module and the one
1357 // function provided to be added to the slot table.
1358 SlotMachine::SlotMachine(const Function *F)
1359 : TheModule(F ? F->getParent() : 0) ///< Saved for lazy initialization
1360 , TheFunction(F) ///< Saved for lazy initialization
1361 , FunctionProcessed(false)
1365 inline void SlotMachine::initialize(void) {
1368 TheModule = 0; ///< Prevent re-processing next time we're called.
1370 if (TheFunction && !FunctionProcessed)
1374 // Iterate through all the global variables, functions, and global
1375 // variable initializers and create slots for them.
1376 void SlotMachine::processModule() {
1377 SC_DEBUG("begin processModule!\n");
1379 // Add all of the unnamed global variables to the value table.
1380 for (Module::const_global_iterator I = TheModule->global_begin(),
1381 E = TheModule->global_end(); I != E; ++I)
1385 // Add all the unnamed functions to the table.
1386 for (Module::const_iterator I = TheModule->begin(), E = TheModule->end();
1391 SC_DEBUG("end processModule!\n");
1395 // Process the arguments, basic blocks, and instructions of a function.
1396 void SlotMachine::processFunction() {
1397 SC_DEBUG("begin processFunction!\n");
1399 // Add all the function arguments with no names.
1400 for(Function::const_arg_iterator AI = TheFunction->arg_begin(),
1401 AE = TheFunction->arg_end(); AI != AE; ++AI)
1403 getOrCreateSlot(AI);
1405 SC_DEBUG("Inserting Instructions:\n");
1407 // Add all of the basic blocks and instructions with no names.
1408 for (Function::const_iterator BB = TheFunction->begin(),
1409 E = TheFunction->end(); BB != E; ++BB) {
1411 getOrCreateSlot(BB);
1412 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I != E; ++I)
1413 if (I->getType() != Type::VoidTy && !I->hasName())
1417 FunctionProcessed = true;
1419 SC_DEBUG("end processFunction!\n");
1422 /// Clean up after incorporating a function. This is the only way to get out of
1423 /// the function incorporation state that affects the
1424 /// getSlot/getOrCreateSlot lock. Function incorporation state is indicated
1425 /// by TheFunction != 0.
1426 void SlotMachine::purgeFunction() {
1427 SC_DEBUG("begin purgeFunction!\n");
1428 fMap.clear(); // Simply discard the function level map
1430 FunctionProcessed = false;
1431 SC_DEBUG("end purgeFunction!\n");
1434 /// Get the slot number for a value. This function will assert if you
1435 /// ask for a Value that hasn't previously been inserted with getOrCreateSlot.
1436 /// Types are forbidden because Type does not inherit from Value (any more).
1437 int SlotMachine::getSlot(const Value *V) {
1438 assert(V && "Can't get slot for null Value");
1439 assert(!isa<Constant>(V) || isa<GlobalValue>(V) &&
1440 "Can't insert a non-GlobalValue Constant into SlotMachine");
1442 // Check for uninitialized state and do lazy initialization
1445 // Get the type of the value
1446 const Type* VTy = V->getType();
1448 // Find the type plane in the module map
1449 TypedPlanes::const_iterator MI = mMap.find(VTy);
1452 // Lookup the type in the function map too
1453 TypedPlanes::const_iterator FI = fMap.find(VTy);
1454 // If there is a corresponding type plane in the function map
1455 if (FI != fMap.end()) {
1456 // Lookup the Value in the function map
1457 ValueMap::const_iterator FVI = FI->second.map.find(V);
1458 // If the value doesn't exist in the function map
1459 if (FVI == FI->second.map.end()) {
1460 // Look up the value in the module map.
1461 if (MI == mMap.end()) return -1;
1462 ValueMap::const_iterator MVI = MI->second.map.find(V);
1463 // If we didn't find it, it wasn't inserted
1464 if (MVI == MI->second.map.end()) return -1;
1465 assert(MVI != MI->second.map.end() && "Value not found");
1466 // We found it only at the module level
1469 // else the value exists in the function map
1471 // Return the slot number as the module's contribution to
1472 // the type plane plus the index in the function's contribution
1473 // to the type plane.
1474 if (MI != mMap.end())
1475 return MI->second.next_slot + FVI->second;
1482 // N.B. Can get here only if either !TheFunction or the function doesn't
1483 // have a corresponding type plane for the Value
1485 // Make sure the type plane exists
1486 if (MI == mMap.end()) return -1;
1487 // Lookup the value in the module's map
1488 ValueMap::const_iterator MVI = MI->second.map.find(V);
1489 // Make sure we found it.
1490 if (MVI == MI->second.map.end()) return -1;
1496 // Create a new slot, or return the existing slot if it is already
1497 // inserted. Note that the logic here parallels getSlot but instead
1498 // of asserting when the Value* isn't found, it inserts the value.
1499 unsigned SlotMachine::getOrCreateSlot(const Value *V) {
1500 const Type* VTy = V->getType();
1501 assert(VTy != Type::VoidTy && !V->hasName() && "Doesn't need a slot!");
1502 assert(!isa<Constant>(V) || isa<GlobalValue>(V) &&
1503 "Can't insert a non-GlobalValue Constant into SlotMachine");
1505 // Look up the type plane for the Value's type from the module map
1506 TypedPlanes::const_iterator MI = mMap.find(VTy);
1509 // Get the type plane for the Value's type from the function map
1510 TypedPlanes::const_iterator FI = fMap.find(VTy);
1511 // If there is a corresponding type plane in the function map
1512 if (FI != fMap.end()) {
1513 // Lookup the Value in the function map
1514 ValueMap::const_iterator FVI = FI->second.map.find(V);
1515 // If the value doesn't exist in the function map
1516 if (FVI == FI->second.map.end()) {
1517 // If there is no corresponding type plane in the module map
1518 if (MI == mMap.end())
1519 return insertValue(V);
1520 // Look up the value in the module map
1521 ValueMap::const_iterator MVI = MI->second.map.find(V);
1522 // If we didn't find it, it wasn't inserted
1523 if (MVI == MI->second.map.end())
1524 return insertValue(V);
1526 // We found it only at the module level
1529 // else the value exists in the function map
1531 if (MI == mMap.end())
1534 // Return the slot number as the module's contribution to
1535 // the type plane plus the index in the function's contribution
1536 // to the type plane.
1537 return MI->second.next_slot + FVI->second;
1540 // else there is not a corresponding type plane in the function map
1542 // If the type plane doesn't exists at the module level
1543 if (MI == mMap.end()) {
1544 return insertValue(V);
1545 // else type plane exists at the module level, examine it
1547 // Look up the value in the module's map
1548 ValueMap::const_iterator MVI = MI->second.map.find(V);
1549 // If we didn't find it there either
1550 if (MVI == MI->second.map.end())
1551 // Return the slot number as the module's contribution to
1552 // the type plane plus the index of the function map insertion.
1553 return MI->second.next_slot + insertValue(V);
1560 // N.B. Can only get here if TheFunction == 0
1562 // If the module map's type plane is not for the Value's type
1563 if (MI != mMap.end()) {
1564 // Lookup the value in the module's map
1565 ValueMap::const_iterator MVI = MI->second.map.find(V);
1566 if (MVI != MI->second.map.end())
1570 return insertValue(V);
1574 // Low level insert function. Minimal checking is done. This
1575 // function is just for the convenience of getOrCreateSlot (above).
1576 unsigned SlotMachine::insertValue(const Value *V) {
1577 assert(V && "Can't insert a null Value into SlotMachine!");
1578 assert(!isa<Constant>(V) || isa<GlobalValue>(V) &&
1579 "Can't insert a non-GlobalValue Constant into SlotMachine");
1580 assert(V->getType() != Type::VoidTy && !V->hasName());
1582 const Type *VTy = V->getType();
1583 unsigned DestSlot = 0;
1586 TypedPlanes::iterator I = fMap.find(VTy);
1587 if (I == fMap.end())
1588 I = fMap.insert(std::make_pair(VTy,ValuePlane())).first;
1589 DestSlot = I->second.map[V] = I->second.next_slot++;
1591 TypedPlanes::iterator I = mMap.find(VTy);
1592 if (I == mMap.end())
1593 I = mMap.insert(std::make_pair(VTy,ValuePlane())).first;
1594 DestSlot = I->second.map[V] = I->second.next_slot++;
1597 SC_DEBUG(" Inserting value [" << VTy << "] = " << V << " slot=" <<
1599 // G = Global, F = Function, o = other
1600 SC_DEBUG((isa<GlobalVariable>(V) ? 'G' : (isa<Function>(V) ? 'F' : 'o')));