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. 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 TypeSymbolTable &ST = M->getTypeSymbolTable();
221 TypeSymbolTable::const_iterator TI = ST.begin();
222 for (; TI != ST.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);
277 for (FunctionType::param_iterator I = FTy->param_begin(),
278 E = FTy->param_end(); I != E; ++I) {
279 if (I != FTy->param_begin())
281 calcTypeName(*I, TypeStack, TypeNames, Result);
282 if (FTy->getParamAttrs(Idx)) {
284 Result += FunctionType::getParamAttrsText(FTy->getParamAttrs(Idx));
288 if (FTy->isVarArg()) {
289 if (FTy->getNumParams()) Result += ", ";
293 if (FTy->getParamAttrs(0)) {
295 Result += FunctionType::getParamAttrsText(FTy->getParamAttrs(0));
299 case Type::StructTyID: {
300 const StructType *STy = cast<StructType>(Ty);
304 for (StructType::element_iterator I = STy->element_begin(),
305 E = STy->element_end(); I != E; ++I) {
306 if (I != STy->element_begin())
308 calcTypeName(*I, TypeStack, TypeNames, Result);
315 case Type::PointerTyID:
316 calcTypeName(cast<PointerType>(Ty)->getElementType(),
317 TypeStack, TypeNames, Result);
320 case Type::ArrayTyID: {
321 const ArrayType *ATy = cast<ArrayType>(Ty);
322 Result += "[" + utostr(ATy->getNumElements()) + " x ";
323 calcTypeName(ATy->getElementType(), TypeStack, TypeNames, Result);
327 case Type::PackedTyID: {
328 const PackedType *PTy = cast<PackedType>(Ty);
329 Result += "<" + utostr(PTy->getNumElements()) + " x ";
330 calcTypeName(PTy->getElementType(), TypeStack, TypeNames, Result);
334 case Type::OpaqueTyID:
338 Result += "<unrecognized-type>";
342 TypeStack.pop_back(); // Remove self from stack...
346 /// printTypeInt - The internal guts of printing out a type that has a
347 /// potentially named portion.
349 static std::ostream &printTypeInt(std::ostream &Out, const Type *Ty,
350 std::map<const Type *, std::string> &TypeNames) {
351 // Primitive types always print out their description, regardless of whether
352 // they have been named or not.
354 if (Ty->isPrimitiveType() && !isa<OpaqueType>(Ty))
355 return Out << Ty->getDescription();
357 // Check to see if the type is named.
358 std::map<const Type *, std::string>::iterator I = TypeNames.find(Ty);
359 if (I != TypeNames.end()) return Out << I->second;
361 // Otherwise we have a type that has not been named but is a derived type.
362 // Carefully recurse the type hierarchy to print out any contained symbolic
365 std::vector<const Type *> TypeStack;
366 std::string TypeName;
367 calcTypeName(Ty, TypeStack, TypeNames, TypeName);
368 TypeNames.insert(std::make_pair(Ty, TypeName));//Cache type name for later use
369 return (Out << TypeName);
373 /// WriteTypeSymbolic - This attempts to write the specified type as a symbolic
374 /// type, iff there is an entry in the modules symbol table for the specified
375 /// type or one of it's component types. This is slower than a simple x << Type
377 std::ostream &llvm::WriteTypeSymbolic(std::ostream &Out, const Type *Ty,
381 // If they want us to print out a type, but there is no context, we can't
382 // print it symbolically.
384 return Out << Ty->getDescription();
386 std::map<const Type *, std::string> TypeNames;
387 fillTypeNameTable(M, TypeNames);
388 return printTypeInt(Out, Ty, TypeNames);
391 // PrintEscapedString - Print each character of the specified string, escaping
392 // it if it is not printable or if it is an escape char.
393 static void PrintEscapedString(const std::string &Str, std::ostream &Out) {
394 for (unsigned i = 0, e = Str.size(); i != e; ++i) {
395 unsigned char C = Str[i];
396 if (isprint(C) && C != '"' && C != '\\') {
400 << (char) ((C/16 < 10) ? ( C/16 +'0') : ( C/16 -10+'A'))
401 << (char)(((C&15) < 10) ? ((C&15)+'0') : ((C&15)-10+'A'));
406 static const char *getPredicateText(unsigned predicate) {
407 const char * pred = "unknown";
409 case FCmpInst::FCMP_FALSE: pred = "false"; break;
410 case FCmpInst::FCMP_OEQ: pred = "oeq"; break;
411 case FCmpInst::FCMP_OGT: pred = "ogt"; break;
412 case FCmpInst::FCMP_OGE: pred = "oge"; break;
413 case FCmpInst::FCMP_OLT: pred = "olt"; break;
414 case FCmpInst::FCMP_OLE: pred = "ole"; break;
415 case FCmpInst::FCMP_ONE: pred = "one"; break;
416 case FCmpInst::FCMP_ORD: pred = "ord"; break;
417 case FCmpInst::FCMP_UNO: pred = "uno"; break;
418 case FCmpInst::FCMP_UEQ: pred = "ueq"; break;
419 case FCmpInst::FCMP_UGT: pred = "ugt"; break;
420 case FCmpInst::FCMP_UGE: pred = "uge"; break;
421 case FCmpInst::FCMP_ULT: pred = "ult"; break;
422 case FCmpInst::FCMP_ULE: pred = "ule"; break;
423 case FCmpInst::FCMP_UNE: pred = "une"; break;
424 case FCmpInst::FCMP_TRUE: pred = "true"; break;
425 case ICmpInst::ICMP_EQ: pred = "eq"; break;
426 case ICmpInst::ICMP_NE: pred = "ne"; break;
427 case ICmpInst::ICMP_SGT: pred = "sgt"; break;
428 case ICmpInst::ICMP_SGE: pred = "sge"; break;
429 case ICmpInst::ICMP_SLT: pred = "slt"; break;
430 case ICmpInst::ICMP_SLE: pred = "sle"; break;
431 case ICmpInst::ICMP_UGT: pred = "ugt"; break;
432 case ICmpInst::ICMP_UGE: pred = "uge"; break;
433 case ICmpInst::ICMP_ULT: pred = "ult"; break;
434 case ICmpInst::ICMP_ULE: pred = "ule"; break;
439 /// @brief Internal constant writer.
440 static void WriteConstantInt(std::ostream &Out, const Constant *CV,
441 std::map<const Type *, std::string> &TypeTable,
442 SlotMachine *Machine) {
443 const int IndentSize = 4;
444 static std::string Indent = "\n";
445 if (const ConstantBool *CB = dyn_cast<ConstantBool>(CV)) {
446 Out << (CB->getValue() ? "true" : "false");
447 } else if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV)) {
448 Out << CI->getSExtValue();
449 } else if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CV)) {
450 // We would like to output the FP constant value in exponential notation,
451 // but we cannot do this if doing so will lose precision. Check here to
452 // make sure that we only output it in exponential format if we can parse
453 // the value back and get the same value.
455 std::string StrVal = ftostr(CFP->getValue());
457 // Check to make sure that the stringized number is not some string like
458 // "Inf" or NaN, that atof will accept, but the lexer will not. Check that
459 // the string matches the "[-+]?[0-9]" regex.
461 if ((StrVal[0] >= '0' && StrVal[0] <= '9') ||
462 ((StrVal[0] == '-' || StrVal[0] == '+') &&
463 (StrVal[1] >= '0' && StrVal[1] <= '9')))
464 // Reparse stringized version!
465 if (atof(StrVal.c_str()) == CFP->getValue()) {
470 // Otherwise we could not reparse it to exactly the same value, so we must
471 // output the string in hexadecimal format!
472 assert(sizeof(double) == sizeof(uint64_t) &&
473 "assuming that double is 64 bits!");
474 Out << "0x" << utohexstr(DoubleToBits(CFP->getValue()));
476 } else if (isa<ConstantAggregateZero>(CV)) {
477 Out << "zeroinitializer";
478 } else if (const ConstantArray *CA = dyn_cast<ConstantArray>(CV)) {
479 // As a special case, print the array as a string if it is an array of
480 // ubytes or an array of sbytes with positive values.
482 const Type *ETy = CA->getType()->getElementType();
483 if (CA->isString()) {
485 PrintEscapedString(CA->getAsString(), Out);
488 } else { // Cannot output in string format...
490 if (CA->getNumOperands()) {
492 printTypeInt(Out, ETy, TypeTable);
493 WriteAsOperandInternal(Out, CA->getOperand(0),
495 for (unsigned i = 1, e = CA->getNumOperands(); i != e; ++i) {
497 printTypeInt(Out, ETy, TypeTable);
498 WriteAsOperandInternal(Out, CA->getOperand(i), TypeTable, Machine);
503 } else if (const ConstantStruct *CS = dyn_cast<ConstantStruct>(CV)) {
505 unsigned N = CS->getNumOperands();
508 Indent += std::string(IndentSize, ' ');
513 printTypeInt(Out, CS->getOperand(0)->getType(), TypeTable);
515 WriteAsOperandInternal(Out, CS->getOperand(0), TypeTable, Machine);
517 for (unsigned i = 1; i < N; i++) {
519 if (N > 2) Out << Indent;
520 printTypeInt(Out, CS->getOperand(i)->getType(), TypeTable);
522 WriteAsOperandInternal(Out, CS->getOperand(i), TypeTable, Machine);
524 if (N > 2) Indent.resize(Indent.size() - IndentSize);
528 } else if (const ConstantPacked *CP = dyn_cast<ConstantPacked>(CV)) {
529 const Type *ETy = CP->getType()->getElementType();
530 assert(CP->getNumOperands() > 0 &&
531 "Number of operands for a PackedConst must be > 0");
534 printTypeInt(Out, ETy, TypeTable);
535 WriteAsOperandInternal(Out, CP->getOperand(0), TypeTable, Machine);
536 for (unsigned i = 1, e = CP->getNumOperands(); i != e; ++i) {
538 printTypeInt(Out, ETy, TypeTable);
539 WriteAsOperandInternal(Out, CP->getOperand(i), TypeTable, Machine);
542 } else if (isa<ConstantPointerNull>(CV)) {
545 } else if (isa<UndefValue>(CV)) {
548 } else if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV)) {
549 Out << CE->getOpcodeName();
551 Out << " " << getPredicateText(CE->getPredicate());
554 for (User::const_op_iterator OI=CE->op_begin(); OI != CE->op_end(); ++OI) {
555 printTypeInt(Out, (*OI)->getType(), TypeTable);
556 WriteAsOperandInternal(Out, *OI, TypeTable, Machine);
557 if (OI+1 != CE->op_end())
563 printTypeInt(Out, CE->getType(), TypeTable);
569 Out << "<placeholder or erroneous Constant>";
574 /// WriteAsOperand - Write the name of the specified value out to the specified
575 /// ostream. This can be useful when you just want to print int %reg126, not
576 /// the whole instruction that generated it.
578 static void WriteAsOperandInternal(std::ostream &Out, const Value *V,
579 std::map<const Type*, std::string> &TypeTable,
580 SlotMachine *Machine) {
583 Out << getLLVMName(V->getName());
585 const Constant *CV = dyn_cast<Constant>(V);
586 if (CV && !isa<GlobalValue>(CV)) {
587 WriteConstantInt(Out, CV, TypeTable, Machine);
588 } else if (const InlineAsm *IA = dyn_cast<InlineAsm>(V)) {
590 if (IA->hasSideEffects())
591 Out << "sideeffect ";
593 PrintEscapedString(IA->getAsmString(), Out);
595 PrintEscapedString(IA->getConstraintString(), Out);
600 Slot = Machine->getSlot(V);
602 Machine = createSlotMachine(V);
604 Slot = Machine->getSlot(V);
617 /// WriteAsOperand - Write the name of the specified value out to the specified
618 /// ostream. This can be useful when you just want to print int %reg126, not
619 /// the whole instruction that generated it.
621 std::ostream &llvm::WriteAsOperand(std::ostream &Out, const Value *V,
622 bool PrintType, const Module *Context) {
623 std::map<const Type *, std::string> TypeNames;
624 if (Context == 0) Context = getModuleFromVal(V);
627 fillTypeNameTable(Context, TypeNames);
630 printTypeInt(Out, V->getType(), TypeNames);
632 WriteAsOperandInternal(Out, V, TypeNames, 0);
639 class AssemblyWriter {
641 SlotMachine &Machine;
642 const Module *TheModule;
643 std::map<const Type *, std::string> TypeNames;
644 AssemblyAnnotationWriter *AnnotationWriter;
646 inline AssemblyWriter(std::ostream &o, SlotMachine &Mac, const Module *M,
647 AssemblyAnnotationWriter *AAW)
648 : Out(o), Machine(Mac), TheModule(M), AnnotationWriter(AAW) {
650 // If the module has a symbol table, take all global types and stuff their
651 // names into the TypeNames map.
653 fillTypeNameTable(M, TypeNames);
656 inline void write(const Module *M) { printModule(M); }
657 inline void write(const GlobalVariable *G) { printGlobal(G); }
658 inline void write(const Function *F) { printFunction(F); }
659 inline void write(const BasicBlock *BB) { printBasicBlock(BB); }
660 inline void write(const Instruction *I) { printInstruction(*I); }
661 inline void write(const Constant *CPV) { printConstant(CPV); }
662 inline void write(const Type *Ty) { printType(Ty); }
664 void writeOperand(const Value *Op, bool PrintType);
666 const Module* getModule() { return TheModule; }
669 void printModule(const Module *M);
670 void printTypeSymbolTable(const TypeSymbolTable &ST);
671 void printValueSymbolTable(const SymbolTable &ST);
672 void printConstant(const Constant *CPV);
673 void printGlobal(const GlobalVariable *GV);
674 void printFunction(const Function *F);
675 void printArgument(const Argument *FA, FunctionType::ParameterAttributes A);
676 void printBasicBlock(const BasicBlock *BB);
677 void printInstruction(const Instruction &I);
679 // printType - Go to extreme measures to attempt to print out a short,
680 // symbolic version of a type name.
682 std::ostream &printType(const Type *Ty) {
683 return printTypeInt(Out, Ty, TypeNames);
686 // printTypeAtLeastOneLevel - Print out one level of the possibly complex type
687 // without considering any symbolic types that we may have equal to it.
689 std::ostream &printTypeAtLeastOneLevel(const Type *Ty);
691 // printInfoComment - Print a little comment after the instruction indicating
692 // which slot it occupies.
693 void printInfoComment(const Value &V);
695 } // end of llvm namespace
697 /// printTypeAtLeastOneLevel - Print out one level of the possibly complex type
698 /// without considering any symbolic types that we may have equal to it.
700 std::ostream &AssemblyWriter::printTypeAtLeastOneLevel(const Type *Ty) {
701 if (const FunctionType *FTy = dyn_cast<FunctionType>(Ty)) {
702 printType(FTy->getReturnType());
705 for (FunctionType::param_iterator I = FTy->param_begin(),
706 E = FTy->param_end(); I != E; ++I) {
707 if (I != FTy->param_begin())
710 if (FTy->getParamAttrs(Idx)) {
711 Out << " " << FunctionType::getParamAttrsText(FTy->getParamAttrs(Idx));
715 if (FTy->isVarArg()) {
716 if (FTy->getNumParams()) Out << ", ";
720 if (FTy->getParamAttrs(0))
721 Out << ' ' << FunctionType::getParamAttrsText(FTy->getParamAttrs(0));
722 } else if (const StructType *STy = dyn_cast<StructType>(Ty)) {
726 for (StructType::element_iterator I = STy->element_begin(),
727 E = STy->element_end(); I != E; ++I) {
728 if (I != STy->element_begin())
735 } else if (const PointerType *PTy = dyn_cast<PointerType>(Ty)) {
736 printType(PTy->getElementType()) << '*';
737 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
738 Out << '[' << ATy->getNumElements() << " x ";
739 printType(ATy->getElementType()) << ']';
740 } else if (const PackedType *PTy = dyn_cast<PackedType>(Ty)) {
741 Out << '<' << PTy->getNumElements() << " x ";
742 printType(PTy->getElementType()) << '>';
744 else if (isa<OpaqueType>(Ty)) {
747 if (!Ty->isPrimitiveType())
748 Out << "<unknown derived type>";
755 void AssemblyWriter::writeOperand(const Value *Operand, bool PrintType) {
757 Out << "<null operand!>";
759 if (PrintType) { Out << ' '; printType(Operand->getType()); }
760 WriteAsOperandInternal(Out, Operand, TypeNames, &Machine);
765 void AssemblyWriter::printModule(const Module *M) {
766 if (!M->getModuleIdentifier().empty() &&
767 // Don't print the ID if it will start a new line (which would
768 // require a comment char before it).
769 M->getModuleIdentifier().find('\n') == std::string::npos)
770 Out << "; ModuleID = '" << M->getModuleIdentifier() << "'\n";
772 if (!M->getDataLayout().empty())
773 Out << "target datalayout = \"" << M->getDataLayout() << "\"\n";
775 switch (M->getEndianness()) {
776 case Module::LittleEndian: Out << "target endian = little\n"; break;
777 case Module::BigEndian: Out << "target endian = big\n"; break;
778 case Module::AnyEndianness: break;
780 switch (M->getPointerSize()) {
781 case Module::Pointer32: Out << "target pointersize = 32\n"; break;
782 case Module::Pointer64: Out << "target pointersize = 64\n"; break;
783 case Module::AnyPointerSize: break;
785 if (!M->getTargetTriple().empty())
786 Out << "target triple = \"" << M->getTargetTriple() << "\"\n";
788 if (!M->getModuleInlineAsm().empty()) {
789 // Split the string into lines, to make it easier to read the .ll file.
790 std::string Asm = M->getModuleInlineAsm();
792 size_t NewLine = Asm.find_first_of('\n', CurPos);
793 while (NewLine != std::string::npos) {
794 // We found a newline, print the portion of the asm string from the
795 // last newline up to this newline.
796 Out << "module asm \"";
797 PrintEscapedString(std::string(Asm.begin()+CurPos, Asm.begin()+NewLine),
801 NewLine = Asm.find_first_of('\n', CurPos);
803 Out << "module asm \"";
804 PrintEscapedString(std::string(Asm.begin()+CurPos, Asm.end()), Out);
808 // Loop over the dependent libraries and emit them.
809 Module::lib_iterator LI = M->lib_begin();
810 Module::lib_iterator LE = M->lib_end();
812 Out << "deplibs = [ ";
814 Out << '"' << *LI << '"';
822 // Loop over the symbol table, emitting all named constants.
823 printTypeSymbolTable(M->getTypeSymbolTable());
824 printValueSymbolTable(M->getValueSymbolTable());
826 for (Module::const_global_iterator I = M->global_begin(), E = M->global_end();
830 Out << "\nimplementation ; Functions:\n";
832 // Output all of the functions.
833 for (Module::const_iterator I = M->begin(), E = M->end(); I != E; ++I)
837 void AssemblyWriter::printGlobal(const GlobalVariable *GV) {
838 if (GV->hasName()) Out << getLLVMName(GV->getName()) << " = ";
840 if (!GV->hasInitializer())
841 switch (GV->getLinkage()) {
842 case GlobalValue::DLLImportLinkage: Out << "dllimport "; break;
843 case GlobalValue::ExternalWeakLinkage: Out << "extern_weak "; break;
844 default: Out << "external "; break;
847 switch (GV->getLinkage()) {
848 case GlobalValue::InternalLinkage: Out << "internal "; break;
849 case GlobalValue::LinkOnceLinkage: Out << "linkonce "; break;
850 case GlobalValue::WeakLinkage: Out << "weak "; break;
851 case GlobalValue::AppendingLinkage: Out << "appending "; break;
852 case GlobalValue::DLLImportLinkage: Out << "dllimport "; break;
853 case GlobalValue::DLLExportLinkage: Out << "dllexport "; break;
854 case GlobalValue::ExternalWeakLinkage: Out << "extern_weak "; break;
855 case GlobalValue::ExternalLinkage: break;
856 case GlobalValue::GhostLinkage:
857 cerr << "GhostLinkage not allowed in AsmWriter!\n";
861 Out << (GV->isConstant() ? "constant " : "global ");
862 printType(GV->getType()->getElementType());
864 if (GV->hasInitializer()) {
865 Constant* C = cast<Constant>(GV->getInitializer());
866 assert(C && "GlobalVar initializer isn't constant?");
867 writeOperand(GV->getInitializer(), false);
870 if (GV->hasSection())
871 Out << ", section \"" << GV->getSection() << '"';
872 if (GV->getAlignment())
873 Out << ", align " << GV->getAlignment();
875 printInfoComment(*GV);
879 void AssemblyWriter::printTypeSymbolTable(const TypeSymbolTable &ST) {
881 for (TypeSymbolTable::const_iterator TI = ST.begin(), TE = ST.end();
883 Out << "\t" << getLLVMName(TI->first) << " = type ";
885 // Make sure we print out at least one level of the type structure, so
886 // that we do not get %FILE = type %FILE
888 printTypeAtLeastOneLevel(TI->second) << "\n";
892 // printSymbolTable - Run through symbol table looking for constants
893 // and types. Emit their declarations.
894 void AssemblyWriter::printValueSymbolTable(const SymbolTable &ST) {
896 // Print the constants, in type plane order.
897 for (SymbolTable::plane_const_iterator PI = ST.plane_begin();
898 PI != ST.plane_end(); ++PI) {
899 SymbolTable::value_const_iterator VI = ST.value_begin(PI->first);
900 SymbolTable::value_const_iterator VE = ST.value_end(PI->first);
902 for (; VI != VE; ++VI) {
903 const Value* V = VI->second;
904 const Constant *CPV = dyn_cast<Constant>(V) ;
905 if (CPV && !isa<GlobalValue>(V)) {
913 /// printConstant - Print out a constant pool entry...
915 void AssemblyWriter::printConstant(const Constant *CPV) {
916 // Don't print out unnamed constants, they will be inlined
917 if (!CPV->hasName()) return;
920 Out << "\t" << getLLVMName(CPV->getName()) << " =";
922 // Write the value out now.
923 writeOperand(CPV, true);
925 printInfoComment(*CPV);
929 /// printFunction - Print all aspects of a function.
931 void AssemblyWriter::printFunction(const Function *F) {
932 // Print out the return type and name...
935 // Ensure that no local symbols conflict with global symbols.
936 const_cast<Function*>(F)->renameLocalSymbols();
938 if (AnnotationWriter) AnnotationWriter->emitFunctionAnnot(F, Out);
941 switch (F->getLinkage()) {
942 case GlobalValue::DLLImportLinkage: Out << "declare dllimport "; break;
943 case GlobalValue::ExternalWeakLinkage: Out << "declare extern_weak "; break;
944 default: Out << "declare ";
948 switch (F->getLinkage()) {
949 case GlobalValue::InternalLinkage: Out << "internal "; break;
950 case GlobalValue::LinkOnceLinkage: Out << "linkonce "; break;
951 case GlobalValue::WeakLinkage: Out << "weak "; break;
952 case GlobalValue::AppendingLinkage: Out << "appending "; break;
953 case GlobalValue::DLLImportLinkage: Out << "dllimport "; break;
954 case GlobalValue::DLLExportLinkage: Out << "dllexport "; break;
955 case GlobalValue::ExternalWeakLinkage: Out << "extern_weak "; break;
956 case GlobalValue::ExternalLinkage: break;
957 case GlobalValue::GhostLinkage:
958 cerr << "GhostLinkage not allowed in AsmWriter!\n";
963 // Print the calling convention.
964 switch (F->getCallingConv()) {
965 case CallingConv::C: break; // default
966 case CallingConv::CSRet: Out << "csretcc "; break;
967 case CallingConv::Fast: Out << "fastcc "; break;
968 case CallingConv::Cold: Out << "coldcc "; break;
969 case CallingConv::X86_StdCall: Out << "x86_stdcallcc "; break;
970 case CallingConv::X86_FastCall: Out << "x86_fastcallcc "; break;
971 default: Out << "cc" << F->getCallingConv() << " "; break;
974 const FunctionType *FT = F->getFunctionType();
975 printType(F->getReturnType()) << ' ';
976 if (!F->getName().empty())
977 Out << getLLVMName(F->getName());
981 Machine.incorporateFunction(F);
983 // Loop over the arguments, printing them...
986 for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
988 // Insert commas as we go... the first arg doesn't get a comma
989 if (I != F->arg_begin()) Out << ", ";
990 printArgument(I, FT->getParamAttrs(Idx));
994 // Finish printing arguments...
995 if (FT->isVarArg()) {
996 if (FT->getNumParams()) Out << ", ";
997 Out << "..."; // Output varargs portion of signature!
1000 if (FT->getParamAttrs(0))
1001 Out << ' ' << FunctionType::getParamAttrsText(FT->getParamAttrs(0));
1002 if (F->hasSection())
1003 Out << " section \"" << F->getSection() << '"';
1004 if (F->getAlignment())
1005 Out << " align " << F->getAlignment();
1007 if (F->isExternal()) {
1012 // Output all of its basic blocks... for the function
1013 for (Function::const_iterator I = F->begin(), E = F->end(); I != E; ++I)
1019 Machine.purgeFunction();
1022 /// printArgument - This member is called for every argument that is passed into
1023 /// the function. Simply print it out
1025 void AssemblyWriter::printArgument(const Argument *Arg,
1026 FunctionType::ParameterAttributes attrs) {
1028 printType(Arg->getType());
1030 if (attrs != FunctionType::NoAttributeSet)
1031 Out << ' ' << FunctionType::getParamAttrsText(attrs);
1033 // Output name, if available...
1035 Out << ' ' << getLLVMName(Arg->getName());
1038 /// printBasicBlock - This member is called for each basic block in a method.
1040 void AssemblyWriter::printBasicBlock(const BasicBlock *BB) {
1041 if (BB->hasName()) { // Print out the label if it exists...
1042 Out << "\n" << getLLVMName(BB->getName(), false) << ':';
1043 } else if (!BB->use_empty()) { // Don't print block # of no uses...
1044 Out << "\n; <label>:";
1045 int Slot = Machine.getSlot(BB);
1052 if (BB->getParent() == 0)
1053 Out << "\t\t; Error: Block without parent!";
1055 if (BB != &BB->getParent()->front()) { // Not the entry block?
1056 // Output predecessors for the block...
1058 pred_const_iterator PI = pred_begin(BB), PE = pred_end(BB);
1061 Out << " No predecessors!";
1064 writeOperand(*PI, false);
1065 for (++PI; PI != PE; ++PI) {
1067 writeOperand(*PI, false);
1075 if (AnnotationWriter) AnnotationWriter->emitBasicBlockStartAnnot(BB, Out);
1077 // Output all of the instructions in the basic block...
1078 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I != E; ++I)
1079 printInstruction(*I);
1081 if (AnnotationWriter) AnnotationWriter->emitBasicBlockEndAnnot(BB, Out);
1085 /// printInfoComment - Print a little comment after the instruction indicating
1086 /// which slot it occupies.
1088 void AssemblyWriter::printInfoComment(const Value &V) {
1089 if (V.getType() != Type::VoidTy) {
1091 printType(V.getType()) << '>';
1094 int SlotNum = Machine.getSlot(&V);
1098 Out << ':' << SlotNum; // Print out the def slot taken.
1100 Out << " [#uses=" << V.getNumUses() << ']'; // Output # uses
1104 // This member is called for each Instruction in a function..
1105 void AssemblyWriter::printInstruction(const Instruction &I) {
1106 if (AnnotationWriter) AnnotationWriter->emitInstructionAnnot(&I, Out);
1110 // Print out name if it exists...
1112 Out << getLLVMName(I.getName()) << " = ";
1114 // If this is a volatile load or store, print out the volatile marker.
1115 if ((isa<LoadInst>(I) && cast<LoadInst>(I).isVolatile()) ||
1116 (isa<StoreInst>(I) && cast<StoreInst>(I).isVolatile())) {
1118 } else if (isa<CallInst>(I) && cast<CallInst>(I).isTailCall()) {
1119 // If this is a call, check if it's a tail call.
1123 // Print out the opcode...
1124 Out << I.getOpcodeName();
1126 // Print out the compare instruction predicates
1127 if (const FCmpInst *FCI = dyn_cast<FCmpInst>(&I)) {
1128 Out << " " << getPredicateText(FCI->getPredicate());
1129 } else if (const ICmpInst *ICI = dyn_cast<ICmpInst>(&I)) {
1130 Out << " " << getPredicateText(ICI->getPredicate());
1133 // Print out the type of the operands...
1134 const Value *Operand = I.getNumOperands() ? I.getOperand(0) : 0;
1136 // Special case conditional branches to swizzle the condition out to the front
1137 if (isa<BranchInst>(I) && I.getNumOperands() > 1) {
1138 writeOperand(I.getOperand(2), true);
1140 writeOperand(Operand, true);
1142 writeOperand(I.getOperand(1), true);
1144 } else if (isa<SwitchInst>(I)) {
1145 // Special case switch statement to get formatting nice and correct...
1146 writeOperand(Operand , true); Out << ',';
1147 writeOperand(I.getOperand(1), true); Out << " [";
1149 for (unsigned op = 2, Eop = I.getNumOperands(); op < Eop; op += 2) {
1151 writeOperand(I.getOperand(op ), true); Out << ',';
1152 writeOperand(I.getOperand(op+1), true);
1155 } else if (isa<PHINode>(I)) {
1157 printType(I.getType());
1160 for (unsigned op = 0, Eop = I.getNumOperands(); op < Eop; op += 2) {
1161 if (op) Out << ", ";
1163 writeOperand(I.getOperand(op ), false); Out << ',';
1164 writeOperand(I.getOperand(op+1), false); Out << " ]";
1166 } else if (isa<ReturnInst>(I) && !Operand) {
1168 } else if (const CallInst *CI = dyn_cast<CallInst>(&I)) {
1169 // Print the calling convention being used.
1170 switch (CI->getCallingConv()) {
1171 case CallingConv::C: break; // default
1172 case CallingConv::CSRet: Out << " csretcc"; break;
1173 case CallingConv::Fast: Out << " fastcc"; break;
1174 case CallingConv::Cold: Out << " coldcc"; break;
1175 case CallingConv::X86_StdCall: Out << "x86_stdcallcc "; break;
1176 case CallingConv::X86_FastCall: Out << "x86_fastcallcc "; break;
1177 default: Out << " cc" << CI->getCallingConv(); break;
1180 const PointerType *PTy = cast<PointerType>(Operand->getType());
1181 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
1182 const Type *RetTy = FTy->getReturnType();
1184 // If possible, print out the short form of the call instruction. We can
1185 // only do this if the first argument is a pointer to a nonvararg function,
1186 // and if the return type is not a pointer to a function.
1188 if (!FTy->isVarArg() &&
1189 (!isa<PointerType>(RetTy) ||
1190 !isa<FunctionType>(cast<PointerType>(RetTy)->getElementType()))) {
1191 Out << ' '; printType(RetTy);
1192 writeOperand(Operand, false);
1194 writeOperand(Operand, true);
1197 for (unsigned op = 1, Eop = I.getNumOperands(); op < Eop; ++op) {
1200 writeOperand(I.getOperand(op), true);
1201 if (FTy->getParamAttrs(op) != FunctionType::NoAttributeSet)
1202 Out << " " << FTy->getParamAttrsText(FTy->getParamAttrs(op));
1205 if (FTy->getParamAttrs(0) != FunctionType::NoAttributeSet)
1206 Out << ' ' << FTy->getParamAttrsText(FTy->getParamAttrs(0));
1207 } else if (const InvokeInst *II = dyn_cast<InvokeInst>(&I)) {
1208 const PointerType *PTy = cast<PointerType>(Operand->getType());
1209 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
1210 const Type *RetTy = FTy->getReturnType();
1212 // Print the calling convention being used.
1213 switch (II->getCallingConv()) {
1214 case CallingConv::C: break; // default
1215 case CallingConv::CSRet: Out << " csretcc"; break;
1216 case CallingConv::Fast: Out << " fastcc"; break;
1217 case CallingConv::Cold: Out << " coldcc"; break;
1218 case CallingConv::X86_StdCall: Out << "x86_stdcallcc "; break;
1219 case CallingConv::X86_FastCall: Out << "x86_fastcallcc "; break;
1220 default: Out << " cc" << II->getCallingConv(); break;
1223 // If possible, print out the short form of the invoke instruction. We can
1224 // only do this if the first argument is a pointer to a nonvararg function,
1225 // and if the return type is not a pointer to a function.
1227 if (!FTy->isVarArg() &&
1228 (!isa<PointerType>(RetTy) ||
1229 !isa<FunctionType>(cast<PointerType>(RetTy)->getElementType()))) {
1230 Out << ' '; printType(RetTy);
1231 writeOperand(Operand, false);
1233 writeOperand(Operand, true);
1237 for (unsigned op = 3, Eop = I.getNumOperands(); op < Eop; ++op) {
1240 writeOperand(I.getOperand(op), true);
1241 if (FTy->getParamAttrs(op-2) != FunctionType::NoAttributeSet)
1242 Out << " " << FTy->getParamAttrsText(FTy->getParamAttrs(op-2));
1246 if (FTy->getParamAttrs(0) != FunctionType::NoAttributeSet)
1247 Out << " " << FTy->getParamAttrsText(FTy->getParamAttrs(0));
1248 Out << "\n\t\t\tto";
1249 writeOperand(II->getNormalDest(), true);
1251 writeOperand(II->getUnwindDest(), true);
1253 } else if (const AllocationInst *AI = dyn_cast<AllocationInst>(&I)) {
1255 printType(AI->getType()->getElementType());
1256 if (AI->isArrayAllocation()) {
1258 writeOperand(AI->getArraySize(), true);
1260 if (AI->getAlignment()) {
1261 Out << ", align " << AI->getAlignment();
1263 } else if (isa<CastInst>(I)) {
1264 if (Operand) writeOperand(Operand, true); // Work with broken code
1266 printType(I.getType());
1267 } else if (isa<VAArgInst>(I)) {
1268 if (Operand) writeOperand(Operand, true); // Work with broken code
1270 printType(I.getType());
1271 } else if (Operand) { // Print the normal way...
1273 // PrintAllTypes - Instructions who have operands of all the same type
1274 // omit the type from all but the first operand. If the instruction has
1275 // different type operands (for example br), then they are all printed.
1276 bool PrintAllTypes = false;
1277 const Type *TheType = Operand->getType();
1279 // Shift Left & Right print both types even for Ubyte LHS, and select prints
1280 // types even if all operands are bools.
1281 if (isa<ShiftInst>(I) || isa<SelectInst>(I) || isa<StoreInst>(I) ||
1282 isa<ShuffleVectorInst>(I)) {
1283 PrintAllTypes = true;
1285 for (unsigned i = 1, E = I.getNumOperands(); i != E; ++i) {
1286 Operand = I.getOperand(i);
1287 if (Operand->getType() != TheType) {
1288 PrintAllTypes = true; // We have differing types! Print them all!
1294 if (!PrintAllTypes) {
1299 for (unsigned i = 0, E = I.getNumOperands(); i != E; ++i) {
1301 writeOperand(I.getOperand(i), PrintAllTypes);
1305 printInfoComment(I);
1310 //===----------------------------------------------------------------------===//
1311 // External Interface declarations
1312 //===----------------------------------------------------------------------===//
1314 void Module::print(std::ostream &o, AssemblyAnnotationWriter *AAW) const {
1315 SlotMachine SlotTable(this);
1316 AssemblyWriter W(o, SlotTable, this, AAW);
1320 void GlobalVariable::print(std::ostream &o) const {
1321 SlotMachine SlotTable(getParent());
1322 AssemblyWriter W(o, SlotTable, getParent(), 0);
1326 void Function::print(std::ostream &o, AssemblyAnnotationWriter *AAW) const {
1327 SlotMachine SlotTable(getParent());
1328 AssemblyWriter W(o, SlotTable, getParent(), AAW);
1333 void InlineAsm::print(std::ostream &o, AssemblyAnnotationWriter *AAW) const {
1334 WriteAsOperand(o, this, true, 0);
1337 void BasicBlock::print(std::ostream &o, AssemblyAnnotationWriter *AAW) const {
1338 SlotMachine SlotTable(getParent());
1339 AssemblyWriter W(o, SlotTable,
1340 getParent() ? getParent()->getParent() : 0, AAW);
1344 void Instruction::print(std::ostream &o, AssemblyAnnotationWriter *AAW) const {
1345 const Function *F = getParent() ? getParent()->getParent() : 0;
1346 SlotMachine SlotTable(F);
1347 AssemblyWriter W(o, SlotTable, F ? F->getParent() : 0, AAW);
1352 void Constant::print(std::ostream &o) const {
1353 if (this == 0) { o << "<null> constant value\n"; return; }
1355 o << ' ' << getType()->getDescription() << ' ';
1357 std::map<const Type *, std::string> TypeTable;
1358 WriteConstantInt(o, this, TypeTable, 0);
1361 void Type::print(std::ostream &o) const {
1365 o << getDescription();
1368 void Argument::print(std::ostream &o) const {
1369 WriteAsOperand(o, this, true, getParent() ? getParent()->getParent() : 0);
1372 // Value::dump - allow easy printing of Values from the debugger.
1373 // Located here because so much of the needed functionality is here.
1374 void Value::dump() const { print(*cerr.stream()); cerr << '\n'; }
1376 // Type::dump - allow easy printing of Values from the debugger.
1377 // Located here because so much of the needed functionality is here.
1378 void Type::dump() const { print(*cerr.stream()); cerr << '\n'; }
1380 //===----------------------------------------------------------------------===//
1381 // SlotMachine Implementation
1382 //===----------------------------------------------------------------------===//
1385 #define SC_DEBUG(X) cerr << X
1390 // Module level constructor. Causes the contents of the Module (sans functions)
1391 // to be added to the slot table.
1392 SlotMachine::SlotMachine(const Module *M)
1393 : TheModule(M) ///< Saved for lazy initialization.
1395 , FunctionProcessed(false)
1399 // Function level constructor. Causes the contents of the Module and the one
1400 // function provided to be added to the slot table.
1401 SlotMachine::SlotMachine(const Function *F)
1402 : TheModule(F ? F->getParent() : 0) ///< Saved for lazy initialization
1403 , TheFunction(F) ///< Saved for lazy initialization
1404 , FunctionProcessed(false)
1408 inline void SlotMachine::initialize(void) {
1411 TheModule = 0; ///< Prevent re-processing next time we're called.
1413 if (TheFunction && !FunctionProcessed)
1417 // Iterate through all the global variables, functions, and global
1418 // variable initializers and create slots for them.
1419 void SlotMachine::processModule() {
1420 SC_DEBUG("begin processModule!\n");
1422 // Add all of the unnamed global variables to the value table.
1423 for (Module::const_global_iterator I = TheModule->global_begin(),
1424 E = TheModule->global_end(); I != E; ++I)
1428 // Add all the unnamed functions to the table.
1429 for (Module::const_iterator I = TheModule->begin(), E = TheModule->end();
1434 SC_DEBUG("end processModule!\n");
1438 // Process the arguments, basic blocks, and instructions of a function.
1439 void SlotMachine::processFunction() {
1440 SC_DEBUG("begin processFunction!\n");
1442 // Add all the function arguments with no names.
1443 for(Function::const_arg_iterator AI = TheFunction->arg_begin(),
1444 AE = TheFunction->arg_end(); AI != AE; ++AI)
1446 getOrCreateSlot(AI);
1448 SC_DEBUG("Inserting Instructions:\n");
1450 // Add all of the basic blocks and instructions with no names.
1451 for (Function::const_iterator BB = TheFunction->begin(),
1452 E = TheFunction->end(); BB != E; ++BB) {
1454 getOrCreateSlot(BB);
1455 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I != E; ++I)
1456 if (I->getType() != Type::VoidTy && !I->hasName())
1460 FunctionProcessed = true;
1462 SC_DEBUG("end processFunction!\n");
1465 /// Clean up after incorporating a function. This is the only way to get out of
1466 /// the function incorporation state that affects the
1467 /// getSlot/getOrCreateSlot lock. Function incorporation state is indicated
1468 /// by TheFunction != 0.
1469 void SlotMachine::purgeFunction() {
1470 SC_DEBUG("begin purgeFunction!\n");
1471 fMap.clear(); // Simply discard the function level map
1473 FunctionProcessed = false;
1474 SC_DEBUG("end purgeFunction!\n");
1477 /// Get the slot number for a value. This function will assert if you
1478 /// ask for a Value that hasn't previously been inserted with getOrCreateSlot.
1479 /// Types are forbidden because Type does not inherit from Value (any more).
1480 int SlotMachine::getSlot(const Value *V) {
1481 assert(V && "Can't get slot for null Value");
1482 assert(!isa<Constant>(V) || isa<GlobalValue>(V) &&
1483 "Can't insert a non-GlobalValue Constant into SlotMachine");
1485 // Check for uninitialized state and do lazy initialization
1488 // Get the type of the value
1489 const Type* VTy = V->getType();
1491 // Find the type plane in the module map
1492 TypedPlanes::const_iterator MI = mMap.find(VTy);
1495 // Lookup the type in the function map too
1496 TypedPlanes::const_iterator FI = fMap.find(VTy);
1497 // If there is a corresponding type plane in the function map
1498 if (FI != fMap.end()) {
1499 // Lookup the Value in the function map
1500 ValueMap::const_iterator FVI = FI->second.map.find(V);
1501 // If the value doesn't exist in the function map
1502 if (FVI == FI->second.map.end()) {
1503 // Look up the value in the module map.
1504 if (MI == mMap.end()) return -1;
1505 ValueMap::const_iterator MVI = MI->second.map.find(V);
1506 // If we didn't find it, it wasn't inserted
1507 if (MVI == MI->second.map.end()) return -1;
1508 assert(MVI != MI->second.map.end() && "Value not found");
1509 // We found it only at the module level
1512 // else the value exists in the function map
1514 // Return the slot number as the module's contribution to
1515 // the type plane plus the index in the function's contribution
1516 // to the type plane.
1517 if (MI != mMap.end())
1518 return MI->second.next_slot + FVI->second;
1525 // N.B. Can get here only if either !TheFunction or the function doesn't
1526 // have a corresponding type plane for the Value
1528 // Make sure the type plane exists
1529 if (MI == mMap.end()) return -1;
1530 // Lookup the value in the module's map
1531 ValueMap::const_iterator MVI = MI->second.map.find(V);
1532 // Make sure we found it.
1533 if (MVI == MI->second.map.end()) return -1;
1539 // Create a new slot, or return the existing slot if it is already
1540 // inserted. Note that the logic here parallels getSlot but instead
1541 // of asserting when the Value* isn't found, it inserts the value.
1542 unsigned SlotMachine::getOrCreateSlot(const Value *V) {
1543 const Type* VTy = V->getType();
1544 assert(VTy != Type::VoidTy && !V->hasName() && "Doesn't need a slot!");
1545 assert(!isa<Constant>(V) || isa<GlobalValue>(V) &&
1546 "Can't insert a non-GlobalValue Constant into SlotMachine");
1548 // Look up the type plane for the Value's type from the module map
1549 TypedPlanes::const_iterator MI = mMap.find(VTy);
1552 // Get the type plane for the Value's type from the function map
1553 TypedPlanes::const_iterator FI = fMap.find(VTy);
1554 // If there is a corresponding type plane in the function map
1555 if (FI != fMap.end()) {
1556 // Lookup the Value in the function map
1557 ValueMap::const_iterator FVI = FI->second.map.find(V);
1558 // If the value doesn't exist in the function map
1559 if (FVI == FI->second.map.end()) {
1560 // If there is no corresponding type plane in the module map
1561 if (MI == mMap.end())
1562 return insertValue(V);
1563 // Look up the value in the module map
1564 ValueMap::const_iterator MVI = MI->second.map.find(V);
1565 // If we didn't find it, it wasn't inserted
1566 if (MVI == MI->second.map.end())
1567 return insertValue(V);
1569 // We found it only at the module level
1572 // else the value exists in the function map
1574 if (MI == mMap.end())
1577 // Return the slot number as the module's contribution to
1578 // the type plane plus the index in the function's contribution
1579 // to the type plane.
1580 return MI->second.next_slot + FVI->second;
1583 // else there is not a corresponding type plane in the function map
1585 // If the type plane doesn't exists at the module level
1586 if (MI == mMap.end()) {
1587 return insertValue(V);
1588 // else type plane exists at the module level, examine it
1590 // Look up the value in the module's map
1591 ValueMap::const_iterator MVI = MI->second.map.find(V);
1592 // If we didn't find it there either
1593 if (MVI == MI->second.map.end())
1594 // Return the slot number as the module's contribution to
1595 // the type plane plus the index of the function map insertion.
1596 return MI->second.next_slot + insertValue(V);
1603 // N.B. Can only get here if TheFunction == 0
1605 // If the module map's type plane is not for the Value's type
1606 if (MI != mMap.end()) {
1607 // Lookup the value in the module's map
1608 ValueMap::const_iterator MVI = MI->second.map.find(V);
1609 if (MVI != MI->second.map.end())
1613 return insertValue(V);
1617 // Low level insert function. Minimal checking is done. This
1618 // function is just for the convenience of getOrCreateSlot (above).
1619 unsigned SlotMachine::insertValue(const Value *V) {
1620 assert(V && "Can't insert a null Value into SlotMachine!");
1621 assert(!isa<Constant>(V) || isa<GlobalValue>(V) &&
1622 "Can't insert a non-GlobalValue Constant into SlotMachine");
1623 assert(V->getType() != Type::VoidTy && !V->hasName());
1625 const Type *VTy = V->getType();
1626 unsigned DestSlot = 0;
1629 TypedPlanes::iterator I = fMap.find(VTy);
1630 if (I == fMap.end())
1631 I = fMap.insert(std::make_pair(VTy,ValuePlane())).first;
1632 DestSlot = I->second.map[V] = I->second.next_slot++;
1634 TypedPlanes::iterator I = mMap.find(VTy);
1635 if (I == mMap.end())
1636 I = mMap.insert(std::make_pair(VTy,ValuePlane())).first;
1637 DestSlot = I->second.map[V] = I->second.next_slot++;
1640 SC_DEBUG(" Inserting value [" << VTy << "] = " << V << " slot=" <<
1642 // G = Global, F = Function, o = other
1643 SC_DEBUG((isa<GlobalVariable>(V) ? 'G' : (isa<Function>(V) ? 'F' : 'o')));