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)) {
504 if (CS->getType()->isPacked())
507 unsigned N = CS->getNumOperands();
510 Indent += std::string(IndentSize, ' ');
515 printTypeInt(Out, CS->getOperand(0)->getType(), TypeTable);
517 WriteAsOperandInternal(Out, CS->getOperand(0), TypeTable, Machine);
519 for (unsigned i = 1; i < N; i++) {
521 if (N > 2) Out << Indent;
522 printTypeInt(Out, CS->getOperand(i)->getType(), TypeTable);
524 WriteAsOperandInternal(Out, CS->getOperand(i), TypeTable, Machine);
526 if (N > 2) Indent.resize(Indent.size() - IndentSize);
530 if (CS->getType()->isPacked())
532 } else if (const ConstantPacked *CP = dyn_cast<ConstantPacked>(CV)) {
533 const Type *ETy = CP->getType()->getElementType();
534 assert(CP->getNumOperands() > 0 &&
535 "Number of operands for a PackedConst must be > 0");
538 printTypeInt(Out, ETy, TypeTable);
539 WriteAsOperandInternal(Out, CP->getOperand(0), TypeTable, Machine);
540 for (unsigned i = 1, e = CP->getNumOperands(); i != e; ++i) {
542 printTypeInt(Out, ETy, TypeTable);
543 WriteAsOperandInternal(Out, CP->getOperand(i), TypeTable, Machine);
546 } else if (isa<ConstantPointerNull>(CV)) {
549 } else if (isa<UndefValue>(CV)) {
552 } else if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV)) {
553 Out << CE->getOpcodeName();
555 Out << " " << getPredicateText(CE->getPredicate());
558 for (User::const_op_iterator OI=CE->op_begin(); OI != CE->op_end(); ++OI) {
559 printTypeInt(Out, (*OI)->getType(), TypeTable);
560 WriteAsOperandInternal(Out, *OI, TypeTable, Machine);
561 if (OI+1 != CE->op_end())
567 printTypeInt(Out, CE->getType(), TypeTable);
573 Out << "<placeholder or erroneous Constant>";
578 /// WriteAsOperand - Write the name of the specified value out to the specified
579 /// ostream. This can be useful when you just want to print int %reg126, not
580 /// the whole instruction that generated it.
582 static void WriteAsOperandInternal(std::ostream &Out, const Value *V,
583 std::map<const Type*, std::string> &TypeTable,
584 SlotMachine *Machine) {
587 Out << getLLVMName(V->getName());
589 const Constant *CV = dyn_cast<Constant>(V);
590 if (CV && !isa<GlobalValue>(CV)) {
591 WriteConstantInt(Out, CV, TypeTable, Machine);
592 } else if (const InlineAsm *IA = dyn_cast<InlineAsm>(V)) {
594 if (IA->hasSideEffects())
595 Out << "sideeffect ";
597 PrintEscapedString(IA->getAsmString(), Out);
599 PrintEscapedString(IA->getConstraintString(), Out);
604 Slot = Machine->getSlot(V);
606 Machine = createSlotMachine(V);
608 Slot = Machine->getSlot(V);
621 /// WriteAsOperand - Write the name of the specified value out to the specified
622 /// ostream. This can be useful when you just want to print int %reg126, not
623 /// the whole instruction that generated it.
625 std::ostream &llvm::WriteAsOperand(std::ostream &Out, const Value *V,
626 bool PrintType, const Module *Context) {
627 std::map<const Type *, std::string> TypeNames;
628 if (Context == 0) Context = getModuleFromVal(V);
631 fillTypeNameTable(Context, TypeNames);
634 printTypeInt(Out, V->getType(), TypeNames);
636 WriteAsOperandInternal(Out, V, TypeNames, 0);
643 class AssemblyWriter {
645 SlotMachine &Machine;
646 const Module *TheModule;
647 std::map<const Type *, std::string> TypeNames;
648 AssemblyAnnotationWriter *AnnotationWriter;
650 inline AssemblyWriter(std::ostream &o, SlotMachine &Mac, const Module *M,
651 AssemblyAnnotationWriter *AAW)
652 : Out(o), Machine(Mac), TheModule(M), AnnotationWriter(AAW) {
654 // If the module has a symbol table, take all global types and stuff their
655 // names into the TypeNames map.
657 fillTypeNameTable(M, TypeNames);
660 inline void write(const Module *M) { printModule(M); }
661 inline void write(const GlobalVariable *G) { printGlobal(G); }
662 inline void write(const Function *F) { printFunction(F); }
663 inline void write(const BasicBlock *BB) { printBasicBlock(BB); }
664 inline void write(const Instruction *I) { printInstruction(*I); }
665 inline void write(const Constant *CPV) { printConstant(CPV); }
666 inline void write(const Type *Ty) { printType(Ty); }
668 void writeOperand(const Value *Op, bool PrintType);
670 const Module* getModule() { return TheModule; }
673 void printModule(const Module *M);
674 void printTypeSymbolTable(const TypeSymbolTable &ST);
675 void printValueSymbolTable(const SymbolTable &ST);
676 void printConstant(const Constant *CPV);
677 void printGlobal(const GlobalVariable *GV);
678 void printFunction(const Function *F);
679 void printArgument(const Argument *FA, FunctionType::ParameterAttributes A);
680 void printBasicBlock(const BasicBlock *BB);
681 void printInstruction(const Instruction &I);
683 // printType - Go to extreme measures to attempt to print out a short,
684 // symbolic version of a type name.
686 std::ostream &printType(const Type *Ty) {
687 return printTypeInt(Out, Ty, TypeNames);
690 // printTypeAtLeastOneLevel - Print out one level of the possibly complex type
691 // without considering any symbolic types that we may have equal to it.
693 std::ostream &printTypeAtLeastOneLevel(const Type *Ty);
695 // printInfoComment - Print a little comment after the instruction indicating
696 // which slot it occupies.
697 void printInfoComment(const Value &V);
699 } // end of llvm namespace
701 /// printTypeAtLeastOneLevel - Print out one level of the possibly complex type
702 /// without considering any symbolic types that we may have equal to it.
704 std::ostream &AssemblyWriter::printTypeAtLeastOneLevel(const Type *Ty) {
705 if (const FunctionType *FTy = dyn_cast<FunctionType>(Ty)) {
706 printType(FTy->getReturnType());
709 for (FunctionType::param_iterator I = FTy->param_begin(),
710 E = FTy->param_end(); I != E; ++I) {
711 if (I != FTy->param_begin())
714 if (FTy->getParamAttrs(Idx)) {
715 Out << " " << FunctionType::getParamAttrsText(FTy->getParamAttrs(Idx));
719 if (FTy->isVarArg()) {
720 if (FTy->getNumParams()) Out << ", ";
724 if (FTy->getParamAttrs(0))
725 Out << ' ' << FunctionType::getParamAttrsText(FTy->getParamAttrs(0));
726 } else if (const StructType *STy = dyn_cast<StructType>(Ty)) {
730 for (StructType::element_iterator I = STy->element_begin(),
731 E = STy->element_end(); I != E; ++I) {
732 if (I != STy->element_begin())
739 } else if (const PointerType *PTy = dyn_cast<PointerType>(Ty)) {
740 printType(PTy->getElementType()) << '*';
741 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
742 Out << '[' << ATy->getNumElements() << " x ";
743 printType(ATy->getElementType()) << ']';
744 } else if (const PackedType *PTy = dyn_cast<PackedType>(Ty)) {
745 Out << '<' << PTy->getNumElements() << " x ";
746 printType(PTy->getElementType()) << '>';
748 else if (isa<OpaqueType>(Ty)) {
751 if (!Ty->isPrimitiveType())
752 Out << "<unknown derived type>";
759 void AssemblyWriter::writeOperand(const Value *Operand, bool PrintType) {
761 Out << "<null operand!>";
763 if (PrintType) { Out << ' '; printType(Operand->getType()); }
764 WriteAsOperandInternal(Out, Operand, TypeNames, &Machine);
769 void AssemblyWriter::printModule(const Module *M) {
770 if (!M->getModuleIdentifier().empty() &&
771 // Don't print the ID if it will start a new line (which would
772 // require a comment char before it).
773 M->getModuleIdentifier().find('\n') == std::string::npos)
774 Out << "; ModuleID = '" << M->getModuleIdentifier() << "'\n";
776 if (!M->getDataLayout().empty())
777 Out << "target datalayout = \"" << M->getDataLayout() << "\"\n";
779 switch (M->getEndianness()) {
780 case Module::LittleEndian: Out << "target endian = little\n"; break;
781 case Module::BigEndian: Out << "target endian = big\n"; break;
782 case Module::AnyEndianness: break;
784 switch (M->getPointerSize()) {
785 case Module::Pointer32: Out << "target pointersize = 32\n"; break;
786 case Module::Pointer64: Out << "target pointersize = 64\n"; break;
787 case Module::AnyPointerSize: break;
789 if (!M->getTargetTriple().empty())
790 Out << "target triple = \"" << M->getTargetTriple() << "\"\n";
792 if (!M->getModuleInlineAsm().empty()) {
793 // Split the string into lines, to make it easier to read the .ll file.
794 std::string Asm = M->getModuleInlineAsm();
796 size_t NewLine = Asm.find_first_of('\n', CurPos);
797 while (NewLine != std::string::npos) {
798 // We found a newline, print the portion of the asm string from the
799 // last newline up to this newline.
800 Out << "module asm \"";
801 PrintEscapedString(std::string(Asm.begin()+CurPos, Asm.begin()+NewLine),
805 NewLine = Asm.find_first_of('\n', CurPos);
807 Out << "module asm \"";
808 PrintEscapedString(std::string(Asm.begin()+CurPos, Asm.end()), Out);
812 // Loop over the dependent libraries and emit them.
813 Module::lib_iterator LI = M->lib_begin();
814 Module::lib_iterator LE = M->lib_end();
816 Out << "deplibs = [ ";
818 Out << '"' << *LI << '"';
826 // Loop over the symbol table, emitting all named constants.
827 printTypeSymbolTable(M->getTypeSymbolTable());
828 printValueSymbolTable(M->getValueSymbolTable());
830 for (Module::const_global_iterator I = M->global_begin(), E = M->global_end();
834 Out << "\nimplementation ; Functions:\n";
836 // Output all of the functions.
837 for (Module::const_iterator I = M->begin(), E = M->end(); I != E; ++I)
841 void AssemblyWriter::printGlobal(const GlobalVariable *GV) {
842 if (GV->hasName()) Out << getLLVMName(GV->getName()) << " = ";
844 if (!GV->hasInitializer())
845 switch (GV->getLinkage()) {
846 case GlobalValue::DLLImportLinkage: Out << "dllimport "; break;
847 case GlobalValue::ExternalWeakLinkage: Out << "extern_weak "; break;
848 default: Out << "external "; break;
851 switch (GV->getLinkage()) {
852 case GlobalValue::InternalLinkage: Out << "internal "; break;
853 case GlobalValue::LinkOnceLinkage: Out << "linkonce "; break;
854 case GlobalValue::WeakLinkage: Out << "weak "; break;
855 case GlobalValue::AppendingLinkage: Out << "appending "; break;
856 case GlobalValue::DLLImportLinkage: Out << "dllimport "; break;
857 case GlobalValue::DLLExportLinkage: Out << "dllexport "; break;
858 case GlobalValue::ExternalWeakLinkage: Out << "extern_weak "; break;
859 case GlobalValue::ExternalLinkage: break;
860 case GlobalValue::GhostLinkage:
861 cerr << "GhostLinkage not allowed in AsmWriter!\n";
865 Out << (GV->isConstant() ? "constant " : "global ");
866 printType(GV->getType()->getElementType());
868 if (GV->hasInitializer()) {
869 Constant* C = cast<Constant>(GV->getInitializer());
870 assert(C && "GlobalVar initializer isn't constant?");
871 writeOperand(GV->getInitializer(), false);
874 if (GV->hasSection())
875 Out << ", section \"" << GV->getSection() << '"';
876 if (GV->getAlignment())
877 Out << ", align " << GV->getAlignment();
879 printInfoComment(*GV);
883 void AssemblyWriter::printTypeSymbolTable(const TypeSymbolTable &ST) {
885 for (TypeSymbolTable::const_iterator TI = ST.begin(), TE = ST.end();
887 Out << "\t" << getLLVMName(TI->first) << " = type ";
889 // Make sure we print out at least one level of the type structure, so
890 // that we do not get %FILE = type %FILE
892 printTypeAtLeastOneLevel(TI->second) << "\n";
896 // printSymbolTable - Run through symbol table looking for constants
897 // and types. Emit their declarations.
898 void AssemblyWriter::printValueSymbolTable(const SymbolTable &ST) {
900 // Print the constants, in type plane order.
901 for (SymbolTable::plane_const_iterator PI = ST.plane_begin();
902 PI != ST.plane_end(); ++PI) {
903 SymbolTable::value_const_iterator VI = ST.value_begin(PI->first);
904 SymbolTable::value_const_iterator VE = ST.value_end(PI->first);
906 for (; VI != VE; ++VI) {
907 const Value* V = VI->second;
908 const Constant *CPV = dyn_cast<Constant>(V) ;
909 if (CPV && !isa<GlobalValue>(V)) {
917 /// printConstant - Print out a constant pool entry...
919 void AssemblyWriter::printConstant(const Constant *CPV) {
920 // Don't print out unnamed constants, they will be inlined
921 if (!CPV->hasName()) return;
924 Out << "\t" << getLLVMName(CPV->getName()) << " =";
926 // Write the value out now.
927 writeOperand(CPV, true);
929 printInfoComment(*CPV);
933 /// printFunction - Print all aspects of a function.
935 void AssemblyWriter::printFunction(const Function *F) {
936 // Print out the return type and name...
939 // Ensure that no local symbols conflict with global symbols.
940 const_cast<Function*>(F)->renameLocalSymbols();
942 if (AnnotationWriter) AnnotationWriter->emitFunctionAnnot(F, Out);
945 switch (F->getLinkage()) {
946 case GlobalValue::DLLImportLinkage: Out << "declare dllimport "; break;
947 case GlobalValue::ExternalWeakLinkage: Out << "declare extern_weak "; break;
948 default: Out << "declare ";
952 switch (F->getLinkage()) {
953 case GlobalValue::InternalLinkage: Out << "internal "; break;
954 case GlobalValue::LinkOnceLinkage: Out << "linkonce "; break;
955 case GlobalValue::WeakLinkage: Out << "weak "; break;
956 case GlobalValue::AppendingLinkage: Out << "appending "; break;
957 case GlobalValue::DLLImportLinkage: Out << "dllimport "; break;
958 case GlobalValue::DLLExportLinkage: Out << "dllexport "; break;
959 case GlobalValue::ExternalWeakLinkage: Out << "extern_weak "; break;
960 case GlobalValue::ExternalLinkage: break;
961 case GlobalValue::GhostLinkage:
962 cerr << "GhostLinkage not allowed in AsmWriter!\n";
967 // Print the calling convention.
968 switch (F->getCallingConv()) {
969 case CallingConv::C: break; // default
970 case CallingConv::CSRet: Out << "csretcc "; break;
971 case CallingConv::Fast: Out << "fastcc "; break;
972 case CallingConv::Cold: Out << "coldcc "; break;
973 case CallingConv::X86_StdCall: Out << "x86_stdcallcc "; break;
974 case CallingConv::X86_FastCall: Out << "x86_fastcallcc "; break;
975 default: Out << "cc" << F->getCallingConv() << " "; break;
978 const FunctionType *FT = F->getFunctionType();
979 printType(F->getReturnType()) << ' ';
980 if (!F->getName().empty())
981 Out << getLLVMName(F->getName());
985 Machine.incorporateFunction(F);
987 // Loop over the arguments, printing them...
990 for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
992 // Insert commas as we go... the first arg doesn't get a comma
993 if (I != F->arg_begin()) Out << ", ";
994 printArgument(I, FT->getParamAttrs(Idx));
998 // Finish printing arguments...
999 if (FT->isVarArg()) {
1000 if (FT->getNumParams()) Out << ", ";
1001 Out << "..."; // Output varargs portion of signature!
1004 if (FT->getParamAttrs(0))
1005 Out << ' ' << FunctionType::getParamAttrsText(FT->getParamAttrs(0));
1006 if (F->hasSection())
1007 Out << " section \"" << F->getSection() << '"';
1008 if (F->getAlignment())
1009 Out << " align " << F->getAlignment();
1011 if (F->isExternal()) {
1016 // Output all of its basic blocks... for the function
1017 for (Function::const_iterator I = F->begin(), E = F->end(); I != E; ++I)
1023 Machine.purgeFunction();
1026 /// printArgument - This member is called for every argument that is passed into
1027 /// the function. Simply print it out
1029 void AssemblyWriter::printArgument(const Argument *Arg,
1030 FunctionType::ParameterAttributes attrs) {
1032 printType(Arg->getType());
1034 if (attrs != FunctionType::NoAttributeSet)
1035 Out << ' ' << FunctionType::getParamAttrsText(attrs);
1037 // Output name, if available...
1039 Out << ' ' << getLLVMName(Arg->getName());
1042 /// printBasicBlock - This member is called for each basic block in a method.
1044 void AssemblyWriter::printBasicBlock(const BasicBlock *BB) {
1045 if (BB->hasName()) { // Print out the label if it exists...
1046 Out << "\n" << getLLVMName(BB->getName(), false) << ':';
1047 } else if (!BB->use_empty()) { // Don't print block # of no uses...
1048 Out << "\n; <label>:";
1049 int Slot = Machine.getSlot(BB);
1056 if (BB->getParent() == 0)
1057 Out << "\t\t; Error: Block without parent!";
1059 if (BB != &BB->getParent()->front()) { // Not the entry block?
1060 // Output predecessors for the block...
1062 pred_const_iterator PI = pred_begin(BB), PE = pred_end(BB);
1065 Out << " No predecessors!";
1068 writeOperand(*PI, false);
1069 for (++PI; PI != PE; ++PI) {
1071 writeOperand(*PI, false);
1079 if (AnnotationWriter) AnnotationWriter->emitBasicBlockStartAnnot(BB, Out);
1081 // Output all of the instructions in the basic block...
1082 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I != E; ++I)
1083 printInstruction(*I);
1085 if (AnnotationWriter) AnnotationWriter->emitBasicBlockEndAnnot(BB, Out);
1089 /// printInfoComment - Print a little comment after the instruction indicating
1090 /// which slot it occupies.
1092 void AssemblyWriter::printInfoComment(const Value &V) {
1093 if (V.getType() != Type::VoidTy) {
1095 printType(V.getType()) << '>';
1098 int SlotNum = Machine.getSlot(&V);
1102 Out << ':' << SlotNum; // Print out the def slot taken.
1104 Out << " [#uses=" << V.getNumUses() << ']'; // Output # uses
1108 // This member is called for each Instruction in a function..
1109 void AssemblyWriter::printInstruction(const Instruction &I) {
1110 if (AnnotationWriter) AnnotationWriter->emitInstructionAnnot(&I, Out);
1114 // Print out name if it exists...
1116 Out << getLLVMName(I.getName()) << " = ";
1118 // If this is a volatile load or store, print out the volatile marker.
1119 if ((isa<LoadInst>(I) && cast<LoadInst>(I).isVolatile()) ||
1120 (isa<StoreInst>(I) && cast<StoreInst>(I).isVolatile())) {
1122 } else if (isa<CallInst>(I) && cast<CallInst>(I).isTailCall()) {
1123 // If this is a call, check if it's a tail call.
1127 // Print out the opcode...
1128 Out << I.getOpcodeName();
1130 // Print out the compare instruction predicates
1131 if (const FCmpInst *FCI = dyn_cast<FCmpInst>(&I)) {
1132 Out << " " << getPredicateText(FCI->getPredicate());
1133 } else if (const ICmpInst *ICI = dyn_cast<ICmpInst>(&I)) {
1134 Out << " " << getPredicateText(ICI->getPredicate());
1137 // Print out the type of the operands...
1138 const Value *Operand = I.getNumOperands() ? I.getOperand(0) : 0;
1140 // Special case conditional branches to swizzle the condition out to the front
1141 if (isa<BranchInst>(I) && I.getNumOperands() > 1) {
1142 writeOperand(I.getOperand(2), true);
1144 writeOperand(Operand, true);
1146 writeOperand(I.getOperand(1), true);
1148 } else if (isa<SwitchInst>(I)) {
1149 // Special case switch statement to get formatting nice and correct...
1150 writeOperand(Operand , true); Out << ',';
1151 writeOperand(I.getOperand(1), true); Out << " [";
1153 for (unsigned op = 2, Eop = I.getNumOperands(); op < Eop; op += 2) {
1155 writeOperand(I.getOperand(op ), true); Out << ',';
1156 writeOperand(I.getOperand(op+1), true);
1159 } else if (isa<PHINode>(I)) {
1161 printType(I.getType());
1164 for (unsigned op = 0, Eop = I.getNumOperands(); op < Eop; op += 2) {
1165 if (op) Out << ", ";
1167 writeOperand(I.getOperand(op ), false); Out << ',';
1168 writeOperand(I.getOperand(op+1), false); Out << " ]";
1170 } else if (isa<ReturnInst>(I) && !Operand) {
1172 } else if (const CallInst *CI = dyn_cast<CallInst>(&I)) {
1173 // Print the calling convention being used.
1174 switch (CI->getCallingConv()) {
1175 case CallingConv::C: break; // default
1176 case CallingConv::CSRet: Out << " csretcc"; break;
1177 case CallingConv::Fast: Out << " fastcc"; break;
1178 case CallingConv::Cold: Out << " coldcc"; break;
1179 case CallingConv::X86_StdCall: Out << "x86_stdcallcc "; break;
1180 case CallingConv::X86_FastCall: Out << "x86_fastcallcc "; break;
1181 default: Out << " cc" << CI->getCallingConv(); break;
1184 const PointerType *PTy = cast<PointerType>(Operand->getType());
1185 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
1186 const Type *RetTy = FTy->getReturnType();
1188 // If possible, print out the short form of the call instruction. We can
1189 // only do this if the first argument is a pointer to a nonvararg function,
1190 // and if the return type is not a pointer to a function.
1192 if (!FTy->isVarArg() &&
1193 (!isa<PointerType>(RetTy) ||
1194 !isa<FunctionType>(cast<PointerType>(RetTy)->getElementType()))) {
1195 Out << ' '; printType(RetTy);
1196 writeOperand(Operand, false);
1198 writeOperand(Operand, true);
1201 for (unsigned op = 1, Eop = I.getNumOperands(); op < Eop; ++op) {
1204 writeOperand(I.getOperand(op), true);
1205 if (FTy->getParamAttrs(op) != FunctionType::NoAttributeSet)
1206 Out << " " << FTy->getParamAttrsText(FTy->getParamAttrs(op));
1209 if (FTy->getParamAttrs(0) != FunctionType::NoAttributeSet)
1210 Out << ' ' << FTy->getParamAttrsText(FTy->getParamAttrs(0));
1211 } else if (const InvokeInst *II = dyn_cast<InvokeInst>(&I)) {
1212 const PointerType *PTy = cast<PointerType>(Operand->getType());
1213 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
1214 const Type *RetTy = FTy->getReturnType();
1216 // Print the calling convention being used.
1217 switch (II->getCallingConv()) {
1218 case CallingConv::C: break; // default
1219 case CallingConv::CSRet: Out << " csretcc"; break;
1220 case CallingConv::Fast: Out << " fastcc"; break;
1221 case CallingConv::Cold: Out << " coldcc"; break;
1222 case CallingConv::X86_StdCall: Out << "x86_stdcallcc "; break;
1223 case CallingConv::X86_FastCall: Out << "x86_fastcallcc "; break;
1224 default: Out << " cc" << II->getCallingConv(); break;
1227 // If possible, print out the short form of the invoke instruction. We can
1228 // only do this if the first argument is a pointer to a nonvararg function,
1229 // and if the return type is not a pointer to a function.
1231 if (!FTy->isVarArg() &&
1232 (!isa<PointerType>(RetTy) ||
1233 !isa<FunctionType>(cast<PointerType>(RetTy)->getElementType()))) {
1234 Out << ' '; printType(RetTy);
1235 writeOperand(Operand, false);
1237 writeOperand(Operand, true);
1241 for (unsigned op = 3, Eop = I.getNumOperands(); op < Eop; ++op) {
1244 writeOperand(I.getOperand(op), true);
1245 if (FTy->getParamAttrs(op-2) != FunctionType::NoAttributeSet)
1246 Out << " " << FTy->getParamAttrsText(FTy->getParamAttrs(op-2));
1250 if (FTy->getParamAttrs(0) != FunctionType::NoAttributeSet)
1251 Out << " " << FTy->getParamAttrsText(FTy->getParamAttrs(0));
1252 Out << "\n\t\t\tto";
1253 writeOperand(II->getNormalDest(), true);
1255 writeOperand(II->getUnwindDest(), true);
1257 } else if (const AllocationInst *AI = dyn_cast<AllocationInst>(&I)) {
1259 printType(AI->getType()->getElementType());
1260 if (AI->isArrayAllocation()) {
1262 writeOperand(AI->getArraySize(), true);
1264 if (AI->getAlignment()) {
1265 Out << ", align " << AI->getAlignment();
1267 } else if (isa<CastInst>(I)) {
1268 if (Operand) writeOperand(Operand, true); // Work with broken code
1270 printType(I.getType());
1271 } else if (isa<VAArgInst>(I)) {
1272 if (Operand) writeOperand(Operand, true); // Work with broken code
1274 printType(I.getType());
1275 } else if (Operand) { // Print the normal way...
1277 // PrintAllTypes - Instructions who have operands of all the same type
1278 // omit the type from all but the first operand. If the instruction has
1279 // different type operands (for example br), then they are all printed.
1280 bool PrintAllTypes = false;
1281 const Type *TheType = Operand->getType();
1283 // Shift Left & Right print both types even for Ubyte LHS, and select prints
1284 // types even if all operands are bools.
1285 if (isa<ShiftInst>(I) || isa<SelectInst>(I) || isa<StoreInst>(I) ||
1286 isa<ShuffleVectorInst>(I)) {
1287 PrintAllTypes = true;
1289 for (unsigned i = 1, E = I.getNumOperands(); i != E; ++i) {
1290 Operand = I.getOperand(i);
1291 if (Operand->getType() != TheType) {
1292 PrintAllTypes = true; // We have differing types! Print them all!
1298 if (!PrintAllTypes) {
1303 for (unsigned i = 0, E = I.getNumOperands(); i != E; ++i) {
1305 writeOperand(I.getOperand(i), PrintAllTypes);
1309 printInfoComment(I);
1314 //===----------------------------------------------------------------------===//
1315 // External Interface declarations
1316 //===----------------------------------------------------------------------===//
1318 void Module::print(std::ostream &o, AssemblyAnnotationWriter *AAW) const {
1319 SlotMachine SlotTable(this);
1320 AssemblyWriter W(o, SlotTable, this, AAW);
1324 void GlobalVariable::print(std::ostream &o) const {
1325 SlotMachine SlotTable(getParent());
1326 AssemblyWriter W(o, SlotTable, getParent(), 0);
1330 void Function::print(std::ostream &o, AssemblyAnnotationWriter *AAW) const {
1331 SlotMachine SlotTable(getParent());
1332 AssemblyWriter W(o, SlotTable, getParent(), AAW);
1337 void InlineAsm::print(std::ostream &o, AssemblyAnnotationWriter *AAW) const {
1338 WriteAsOperand(o, this, true, 0);
1341 void BasicBlock::print(std::ostream &o, AssemblyAnnotationWriter *AAW) const {
1342 SlotMachine SlotTable(getParent());
1343 AssemblyWriter W(o, SlotTable,
1344 getParent() ? getParent()->getParent() : 0, AAW);
1348 void Instruction::print(std::ostream &o, AssemblyAnnotationWriter *AAW) const {
1349 const Function *F = getParent() ? getParent()->getParent() : 0;
1350 SlotMachine SlotTable(F);
1351 AssemblyWriter W(o, SlotTable, F ? F->getParent() : 0, AAW);
1356 void Constant::print(std::ostream &o) const {
1357 if (this == 0) { o << "<null> constant value\n"; return; }
1359 o << ' ' << getType()->getDescription() << ' ';
1361 std::map<const Type *, std::string> TypeTable;
1362 WriteConstantInt(o, this, TypeTable, 0);
1365 void Type::print(std::ostream &o) const {
1369 o << getDescription();
1372 void Argument::print(std::ostream &o) const {
1373 WriteAsOperand(o, this, true, getParent() ? getParent()->getParent() : 0);
1376 // Value::dump - allow easy printing of Values from the debugger.
1377 // Located here because so much of the needed functionality is here.
1378 void Value::dump() const { print(*cerr.stream()); cerr << '\n'; }
1380 // Type::dump - allow easy printing of Values from the debugger.
1381 // Located here because so much of the needed functionality is here.
1382 void Type::dump() const { print(*cerr.stream()); cerr << '\n'; }
1384 //===----------------------------------------------------------------------===//
1385 // SlotMachine Implementation
1386 //===----------------------------------------------------------------------===//
1389 #define SC_DEBUG(X) cerr << X
1394 // Module level constructor. Causes the contents of the Module (sans functions)
1395 // to be added to the slot table.
1396 SlotMachine::SlotMachine(const Module *M)
1397 : TheModule(M) ///< Saved for lazy initialization.
1399 , FunctionProcessed(false)
1403 // Function level constructor. Causes the contents of the Module and the one
1404 // function provided to be added to the slot table.
1405 SlotMachine::SlotMachine(const Function *F)
1406 : TheModule(F ? F->getParent() : 0) ///< Saved for lazy initialization
1407 , TheFunction(F) ///< Saved for lazy initialization
1408 , FunctionProcessed(false)
1412 inline void SlotMachine::initialize(void) {
1415 TheModule = 0; ///< Prevent re-processing next time we're called.
1417 if (TheFunction && !FunctionProcessed)
1421 // Iterate through all the global variables, functions, and global
1422 // variable initializers and create slots for them.
1423 void SlotMachine::processModule() {
1424 SC_DEBUG("begin processModule!\n");
1426 // Add all of the unnamed global variables to the value table.
1427 for (Module::const_global_iterator I = TheModule->global_begin(),
1428 E = TheModule->global_end(); I != E; ++I)
1432 // Add all the unnamed functions to the table.
1433 for (Module::const_iterator I = TheModule->begin(), E = TheModule->end();
1438 SC_DEBUG("end processModule!\n");
1442 // Process the arguments, basic blocks, and instructions of a function.
1443 void SlotMachine::processFunction() {
1444 SC_DEBUG("begin processFunction!\n");
1446 // Add all the function arguments with no names.
1447 for(Function::const_arg_iterator AI = TheFunction->arg_begin(),
1448 AE = TheFunction->arg_end(); AI != AE; ++AI)
1450 getOrCreateSlot(AI);
1452 SC_DEBUG("Inserting Instructions:\n");
1454 // Add all of the basic blocks and instructions with no names.
1455 for (Function::const_iterator BB = TheFunction->begin(),
1456 E = TheFunction->end(); BB != E; ++BB) {
1458 getOrCreateSlot(BB);
1459 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I != E; ++I)
1460 if (I->getType() != Type::VoidTy && !I->hasName())
1464 FunctionProcessed = true;
1466 SC_DEBUG("end processFunction!\n");
1469 /// Clean up after incorporating a function. This is the only way to get out of
1470 /// the function incorporation state that affects the
1471 /// getSlot/getOrCreateSlot lock. Function incorporation state is indicated
1472 /// by TheFunction != 0.
1473 void SlotMachine::purgeFunction() {
1474 SC_DEBUG("begin purgeFunction!\n");
1475 fMap.clear(); // Simply discard the function level map
1477 FunctionProcessed = false;
1478 SC_DEBUG("end purgeFunction!\n");
1481 /// Get the slot number for a value. This function will assert if you
1482 /// ask for a Value that hasn't previously been inserted with getOrCreateSlot.
1483 /// Types are forbidden because Type does not inherit from Value (any more).
1484 int SlotMachine::getSlot(const Value *V) {
1485 assert(V && "Can't get slot for null Value");
1486 assert(!isa<Constant>(V) || isa<GlobalValue>(V) &&
1487 "Can't insert a non-GlobalValue Constant into SlotMachine");
1489 // Check for uninitialized state and do lazy initialization
1492 // Get the type of the value
1493 const Type* VTy = V->getType();
1495 // Find the type plane in the module map
1496 TypedPlanes::const_iterator MI = mMap.find(VTy);
1499 // Lookup the type in the function map too
1500 TypedPlanes::const_iterator FI = fMap.find(VTy);
1501 // If there is a corresponding type plane in the function map
1502 if (FI != fMap.end()) {
1503 // Lookup the Value in the function map
1504 ValueMap::const_iterator FVI = FI->second.map.find(V);
1505 // If the value doesn't exist in the function map
1506 if (FVI == FI->second.map.end()) {
1507 // Look up the value in the module map.
1508 if (MI == mMap.end()) return -1;
1509 ValueMap::const_iterator MVI = MI->second.map.find(V);
1510 // If we didn't find it, it wasn't inserted
1511 if (MVI == MI->second.map.end()) return -1;
1512 assert(MVI != MI->second.map.end() && "Value not found");
1513 // We found it only at the module level
1516 // else the value exists in the function map
1518 // Return the slot number as the module's contribution to
1519 // the type plane plus the index in the function's contribution
1520 // to the type plane.
1521 if (MI != mMap.end())
1522 return MI->second.next_slot + FVI->second;
1529 // N.B. Can get here only if either !TheFunction or the function doesn't
1530 // have a corresponding type plane for the Value
1532 // Make sure the type plane exists
1533 if (MI == mMap.end()) return -1;
1534 // Lookup the value in the module's map
1535 ValueMap::const_iterator MVI = MI->second.map.find(V);
1536 // Make sure we found it.
1537 if (MVI == MI->second.map.end()) return -1;
1543 // Create a new slot, or return the existing slot if it is already
1544 // inserted. Note that the logic here parallels getSlot but instead
1545 // of asserting when the Value* isn't found, it inserts the value.
1546 unsigned SlotMachine::getOrCreateSlot(const Value *V) {
1547 const Type* VTy = V->getType();
1548 assert(VTy != Type::VoidTy && !V->hasName() && "Doesn't need a slot!");
1549 assert(!isa<Constant>(V) || isa<GlobalValue>(V) &&
1550 "Can't insert a non-GlobalValue Constant into SlotMachine");
1552 // Look up the type plane for the Value's type from the module map
1553 TypedPlanes::const_iterator MI = mMap.find(VTy);
1556 // Get the type plane for the Value's type from the function map
1557 TypedPlanes::const_iterator FI = fMap.find(VTy);
1558 // If there is a corresponding type plane in the function map
1559 if (FI != fMap.end()) {
1560 // Lookup the Value in the function map
1561 ValueMap::const_iterator FVI = FI->second.map.find(V);
1562 // If the value doesn't exist in the function map
1563 if (FVI == FI->second.map.end()) {
1564 // If there is no corresponding type plane in the module map
1565 if (MI == mMap.end())
1566 return insertValue(V);
1567 // Look up the value in the module map
1568 ValueMap::const_iterator MVI = MI->second.map.find(V);
1569 // If we didn't find it, it wasn't inserted
1570 if (MVI == MI->second.map.end())
1571 return insertValue(V);
1573 // We found it only at the module level
1576 // else the value exists in the function map
1578 if (MI == mMap.end())
1581 // Return the slot number as the module's contribution to
1582 // the type plane plus the index in the function's contribution
1583 // to the type plane.
1584 return MI->second.next_slot + FVI->second;
1587 // else there is not a corresponding type plane in the function map
1589 // If the type plane doesn't exists at the module level
1590 if (MI == mMap.end()) {
1591 return insertValue(V);
1592 // else type plane exists at the module level, examine it
1594 // Look up the value in the module's map
1595 ValueMap::const_iterator MVI = MI->second.map.find(V);
1596 // If we didn't find it there either
1597 if (MVI == MI->second.map.end())
1598 // Return the slot number as the module's contribution to
1599 // the type plane plus the index of the function map insertion.
1600 return MI->second.next_slot + insertValue(V);
1607 // N.B. Can only get here if TheFunction == 0
1609 // If the module map's type plane is not for the Value's type
1610 if (MI != mMap.end()) {
1611 // Lookup the value in the module's map
1612 ValueMap::const_iterator MVI = MI->second.map.find(V);
1613 if (MVI != MI->second.map.end())
1617 return insertValue(V);
1621 // Low level insert function. Minimal checking is done. This
1622 // function is just for the convenience of getOrCreateSlot (above).
1623 unsigned SlotMachine::insertValue(const Value *V) {
1624 assert(V && "Can't insert a null Value into SlotMachine!");
1625 assert(!isa<Constant>(V) || isa<GlobalValue>(V) &&
1626 "Can't insert a non-GlobalValue Constant into SlotMachine");
1627 assert(V->getType() != Type::VoidTy && !V->hasName());
1629 const Type *VTy = V->getType();
1630 unsigned DestSlot = 0;
1633 TypedPlanes::iterator I = fMap.find(VTy);
1634 if (I == fMap.end())
1635 I = fMap.insert(std::make_pair(VTy,ValuePlane())).first;
1636 DestSlot = I->second.map[V] = I->second.next_slot++;
1638 TypedPlanes::iterator I = mMap.find(VTy);
1639 if (I == mMap.end())
1640 I = mMap.insert(std::make_pair(VTy,ValuePlane())).first;
1641 DestSlot = I->second.map[V] = I->second.next_slot++;
1644 SC_DEBUG(" Inserting value [" << VTy << "] = " << V << " slot=" <<
1646 // G = Global, F = Function, o = other
1647 SC_DEBUG((isa<GlobalVariable>(V) ? 'G' : (isa<Function>(V) ? 'F' : 'o')));