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/CachedWriter.h"
18 #include "llvm/Assembly/Writer.h"
19 #include "llvm/Assembly/PrintModulePass.h"
20 #include "llvm/Assembly/AsmAnnotationWriter.h"
21 #include "llvm/CallingConv.h"
22 #include "llvm/Constants.h"
23 #include "llvm/DerivedTypes.h"
24 #include "llvm/InlineAsm.h"
25 #include "llvm/Instruction.h"
26 #include "llvm/Instructions.h"
27 #include "llvm/Module.h"
28 #include "llvm/SymbolTable.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;
52 typedef std::map<const Type*, unsigned> TypeMap;
54 /// @brief A plane with next slot number and ValueMap
56 unsigned next_slot; ///< The next slot number to use
57 ValueMap map; ///< The map of Value* -> unsigned
58 ValuePlane() { next_slot = 0; } ///< Make sure we start at 0
64 TypePlane() { next_slot = 0; }
65 void clear() { map.clear(); next_slot = 0; }
68 /// @brief The map of planes by Type
69 typedef std::map<const Type*, ValuePlane> TypedPlanes;
72 /// @name Constructors
75 /// @brief Construct from a module
76 SlotMachine(const Module *M );
78 /// @brief Construct from a function, starting out in incorp state.
79 SlotMachine(const Function *F );
85 /// Return the slot number of the specified value in it's type
86 /// plane. Its an error to ask for something not in the SlotMachine.
87 /// Its an error to ask for a Type*
88 int getSlot(const Value *V);
89 int getSlot(const Type*Ty);
91 /// Determine if a Value has a slot or not
92 bool hasSlot(const Value* V);
93 bool hasSlot(const Type* Ty);
99 /// If you'd like to deal with a function instead of just a module, use
100 /// this method to get its data into the SlotMachine.
101 void incorporateFunction(const Function *F) {
103 FunctionProcessed = false;
106 /// After calling incorporateFunction, use this method to remove the
107 /// most recently incorporated function from the SlotMachine. This
108 /// will reset the state of the machine back to just the module contents.
109 void purgeFunction();
112 /// @name Implementation Details
115 /// This function does the actual initialization.
116 inline void initialize();
118 /// Values can be crammed into here at will. If they haven't
119 /// been inserted already, they get inserted, otherwise they are ignored.
120 /// Either way, the slot number for the Value* is returned.
121 unsigned createSlot(const Value *V);
122 unsigned createSlot(const Type* Ty);
124 /// Insert a value into the value table. Return the slot number
125 /// that it now occupies. BadThings(TM) will happen if you insert a
126 /// Value that's already been inserted.
127 unsigned insertValue( const Value *V );
128 unsigned insertValue( const Type* Ty);
130 /// Add all of the module level global variables (and their initializers)
131 /// and function declarations, but not the contents of those functions.
132 void processModule();
134 /// Add all of the functions arguments, basic blocks, and instructions
135 void processFunction();
137 SlotMachine(const SlotMachine &); // DO NOT IMPLEMENT
138 void operator=(const SlotMachine &); // DO NOT IMPLEMENT
145 /// @brief The module for which we are holding slot numbers
146 const Module* TheModule;
148 /// @brief The function for which we are holding slot numbers
149 const Function* TheFunction;
150 bool FunctionProcessed;
152 /// @brief The TypePlanes map for the module level data
156 /// @brief The TypePlanes map for the function level data
164 } // end namespace llvm
166 static RegisterPass<PrintModulePass>
167 X("printm", "Print module to stderr");
168 static RegisterPass<PrintFunctionPass>
169 Y("print","Print function to stderr");
171 static void WriteAsOperandInternal(std::ostream &Out, const Value *V,
173 std::map<const Type *, std::string> &TypeTable,
174 SlotMachine *Machine);
176 static void WriteAsOperandInternal(std::ostream &Out, const Type *T,
178 std::map<const Type *, std::string> &TypeTable,
179 SlotMachine *Machine);
181 static const Module *getModuleFromVal(const Value *V) {
182 if (const Argument *MA = dyn_cast<Argument>(V))
183 return MA->getParent() ? MA->getParent()->getParent() : 0;
184 else if (const BasicBlock *BB = dyn_cast<BasicBlock>(V))
185 return BB->getParent() ? BB->getParent()->getParent() : 0;
186 else if (const Instruction *I = dyn_cast<Instruction>(V)) {
187 const Function *M = I->getParent() ? I->getParent()->getParent() : 0;
188 return M ? M->getParent() : 0;
189 } else if (const GlobalValue *GV = dyn_cast<GlobalValue>(V))
190 return GV->getParent();
194 static SlotMachine *createSlotMachine(const Value *V) {
195 if (const Argument *FA = dyn_cast<Argument>(V)) {
196 return new SlotMachine(FA->getParent());
197 } else if (const Instruction *I = dyn_cast<Instruction>(V)) {
198 return new SlotMachine(I->getParent()->getParent());
199 } else if (const BasicBlock *BB = dyn_cast<BasicBlock>(V)) {
200 return new SlotMachine(BB->getParent());
201 } else if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(V)){
202 return new SlotMachine(GV->getParent());
203 } else if (const Function *Func = dyn_cast<Function>(V)) {
204 return new SlotMachine(Func);
209 // getLLVMName - Turn the specified string into an 'LLVM name', which is either
210 // prefixed with % (if the string only contains simple characters) or is
211 // surrounded with ""'s (if it has special chars in it).
212 static std::string getLLVMName(const std::string &Name,
213 bool prefixName = true) {
214 assert(!Name.empty() && "Cannot get empty name!");
216 // First character cannot start with a number...
217 if (Name[0] >= '0' && Name[0] <= '9')
218 return "\"" + Name + "\"";
220 // Scan to see if we have any characters that are not on the "white list"
221 for (unsigned i = 0, e = Name.size(); i != e; ++i) {
223 assert(C != '"' && "Illegal character in LLVM value name!");
224 if ((C < 'a' || C > 'z') && (C < 'A' || C > 'Z') && (C < '0' || C > '9') &&
225 C != '-' && C != '.' && C != '_')
226 return "\"" + Name + "\"";
229 // If we get here, then the identifier is legal to use as a "VarID".
237 /// fillTypeNameTable - If the module has a symbol table, take all global types
238 /// and stuff their names into the TypeNames map.
240 static void fillTypeNameTable(const Module *M,
241 std::map<const Type *, std::string> &TypeNames) {
243 const SymbolTable &ST = M->getSymbolTable();
244 SymbolTable::type_const_iterator TI = ST.type_begin();
245 for (; TI != ST.type_end(); ++TI ) {
246 // As a heuristic, don't insert pointer to primitive types, because
247 // they are used too often to have a single useful name.
249 const Type *Ty = cast<Type>(TI->second);
250 if (!isa<PointerType>(Ty) ||
251 !cast<PointerType>(Ty)->getElementType()->isPrimitiveType() ||
252 isa<OpaqueType>(cast<PointerType>(Ty)->getElementType()))
253 TypeNames.insert(std::make_pair(Ty, getLLVMName(TI->first)));
259 static void calcTypeName(const Type *Ty,
260 std::vector<const Type *> &TypeStack,
261 std::map<const Type *, std::string> &TypeNames,
262 std::string & Result){
263 if (Ty->isPrimitiveType() && !isa<OpaqueType>(Ty)) {
264 Result += Ty->getDescription(); // Base case
268 // Check to see if the type is named.
269 std::map<const Type *, std::string>::iterator I = TypeNames.find(Ty);
270 if (I != TypeNames.end()) {
275 if (isa<OpaqueType>(Ty)) {
280 // Check to see if the Type is already on the stack...
281 unsigned Slot = 0, CurSize = TypeStack.size();
282 while (Slot < CurSize && TypeStack[Slot] != Ty) ++Slot; // Scan for type
284 // This is another base case for the recursion. In this case, we know
285 // that we have looped back to a type that we have previously visited.
286 // Generate the appropriate upreference to handle this.
287 if (Slot < CurSize) {
288 Result += "\\" + utostr(CurSize-Slot); // Here's the upreference
292 TypeStack.push_back(Ty); // Recursive case: Add us to the stack..
294 switch (Ty->getTypeID()) {
295 case Type::FunctionTyID: {
296 const FunctionType *FTy = cast<FunctionType>(Ty);
297 calcTypeName(FTy->getReturnType(), TypeStack, TypeNames, Result);
299 for (FunctionType::param_iterator I = FTy->param_begin(),
300 E = FTy->param_end(); I != E; ++I) {
301 if (I != FTy->param_begin())
303 calcTypeName(*I, TypeStack, TypeNames, Result);
305 if (FTy->isVarArg()) {
306 if (FTy->getNumParams()) Result += ", ";
312 case Type::StructTyID: {
313 const StructType *STy = cast<StructType>(Ty);
315 for (StructType::element_iterator I = STy->element_begin(),
316 E = STy->element_end(); I != E; ++I) {
317 if (I != STy->element_begin())
319 calcTypeName(*I, TypeStack, TypeNames, Result);
324 case Type::PointerTyID:
325 calcTypeName(cast<PointerType>(Ty)->getElementType(),
326 TypeStack, TypeNames, Result);
329 case Type::ArrayTyID: {
330 const ArrayType *ATy = cast<ArrayType>(Ty);
331 Result += "[" + utostr(ATy->getNumElements()) + " x ";
332 calcTypeName(ATy->getElementType(), TypeStack, TypeNames, Result);
336 case Type::PackedTyID: {
337 const PackedType *PTy = cast<PackedType>(Ty);
338 Result += "<" + utostr(PTy->getNumElements()) + " x ";
339 calcTypeName(PTy->getElementType(), TypeStack, TypeNames, Result);
343 case Type::OpaqueTyID:
347 Result += "<unrecognized-type>";
350 TypeStack.pop_back(); // Remove self from stack...
355 /// printTypeInt - The internal guts of printing out a type that has a
356 /// potentially named portion.
358 static std::ostream &printTypeInt(std::ostream &Out, const Type *Ty,
359 std::map<const Type *, std::string> &TypeNames) {
360 // Primitive types always print out their description, regardless of whether
361 // they have been named or not.
363 if (Ty->isPrimitiveType() && !isa<OpaqueType>(Ty))
364 return Out << Ty->getDescription();
366 // Check to see if the type is named.
367 std::map<const Type *, std::string>::iterator I = TypeNames.find(Ty);
368 if (I != TypeNames.end()) return Out << I->second;
370 // Otherwise we have a type that has not been named but is a derived type.
371 // Carefully recurse the type hierarchy to print out any contained symbolic
374 std::vector<const Type *> TypeStack;
375 std::string TypeName;
376 calcTypeName(Ty, TypeStack, TypeNames, TypeName);
377 TypeNames.insert(std::make_pair(Ty, TypeName));//Cache type name for later use
378 return (Out << TypeName);
382 /// WriteTypeSymbolic - This attempts to write the specified type as a symbolic
383 /// type, iff there is an entry in the modules symbol table for the specified
384 /// type or one of it's component types. This is slower than a simple x << Type
386 std::ostream &llvm::WriteTypeSymbolic(std::ostream &Out, const Type *Ty,
390 // If they want us to print out a type, attempt to make it symbolic if there
391 // is a symbol table in the module...
393 std::map<const Type *, std::string> TypeNames;
394 fillTypeNameTable(M, TypeNames);
396 return printTypeInt(Out, Ty, TypeNames);
398 return Out << Ty->getDescription();
402 // PrintEscapedString - Print each character of the specified string, escaping
403 // it if it is not printable or if it is an escape char.
404 static void PrintEscapedString(const std::string &Str, std::ostream &Out) {
405 for (unsigned i = 0, e = Str.size(); i != e; ++i) {
406 unsigned char C = Str[i];
407 if (isprint(C) && C != '"' && C != '\\') {
411 << (char) ((C/16 < 10) ? ( C/16 +'0') : ( C/16 -10+'A'))
412 << (char)(((C&15) < 10) ? ((C&15)+'0') : ((C&15)-10+'A'));
417 /// @brief Internal constant writer.
418 static void WriteConstantInt(std::ostream &Out, const Constant *CV,
420 std::map<const Type *, std::string> &TypeTable,
421 SlotMachine *Machine) {
422 const int IndentSize = 4;
423 static std::string Indent = "\n";
424 if (const ConstantBool *CB = dyn_cast<ConstantBool>(CV)) {
425 Out << (CB->getValue() ? "true" : "false");
426 } else if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV)) {
427 if (CI->getType()->isSigned())
428 Out << CI->getSExtValue();
430 Out << CI->getZExtValue();
431 } else if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CV)) {
432 // We would like to output the FP constant value in exponential notation,
433 // but we cannot do this if doing so will lose precision. Check here to
434 // make sure that we only output it in exponential format if we can parse
435 // the value back and get the same value.
437 std::string StrVal = ftostr(CFP->getValue());
439 // Check to make sure that the stringized number is not some string like
440 // "Inf" or NaN, that atof will accept, but the lexer will not. Check that
441 // the string matches the "[-+]?[0-9]" regex.
443 if ((StrVal[0] >= '0' && StrVal[0] <= '9') ||
444 ((StrVal[0] == '-' || StrVal[0] == '+') &&
445 (StrVal[1] >= '0' && StrVal[1] <= '9')))
446 // Reparse stringized version!
447 if (atof(StrVal.c_str()) == CFP->getValue()) {
452 // Otherwise we could not reparse it to exactly the same value, so we must
453 // output the string in hexadecimal format!
454 assert(sizeof(double) == sizeof(uint64_t) &&
455 "assuming that double is 64 bits!");
456 Out << "0x" << utohexstr(DoubleToBits(CFP->getValue()));
458 } else if (isa<ConstantAggregateZero>(CV)) {
459 Out << "zeroinitializer";
460 } else if (const ConstantArray *CA = dyn_cast<ConstantArray>(CV)) {
461 // As a special case, print the array as a string if it is an array of
462 // ubytes or an array of sbytes with positive values.
464 const Type *ETy = CA->getType()->getElementType();
465 if (CA->isString()) {
467 PrintEscapedString(CA->getAsString(), Out);
470 } else { // Cannot output in string format...
472 if (CA->getNumOperands()) {
474 printTypeInt(Out, ETy, TypeTable);
475 WriteAsOperandInternal(Out, CA->getOperand(0),
476 PrintName, TypeTable, Machine);
477 for (unsigned i = 1, e = CA->getNumOperands(); i != e; ++i) {
479 printTypeInt(Out, ETy, TypeTable);
480 WriteAsOperandInternal(Out, CA->getOperand(i), PrintName,
486 } else if (const ConstantStruct *CS = dyn_cast<ConstantStruct>(CV)) {
488 unsigned N = CS->getNumOperands();
491 Indent += std::string(IndentSize, ' ');
496 printTypeInt(Out, CS->getOperand(0)->getType(), TypeTable);
498 WriteAsOperandInternal(Out, CS->getOperand(0),
499 PrintName, TypeTable, Machine);
501 for (unsigned i = 1; i < N; i++) {
503 if (N > 2) Out << Indent;
504 printTypeInt(Out, CS->getOperand(i)->getType(), TypeTable);
506 WriteAsOperandInternal(Out, CS->getOperand(i),
507 PrintName, TypeTable, Machine);
509 if (N > 2) Indent.resize(Indent.size() - IndentSize);
513 } else if (const ConstantPacked *CP = dyn_cast<ConstantPacked>(CV)) {
514 const Type *ETy = CP->getType()->getElementType();
515 assert(CP->getNumOperands() > 0 &&
516 "Number of operands for a PackedConst must be > 0");
519 printTypeInt(Out, ETy, TypeTable);
520 WriteAsOperandInternal(Out, CP->getOperand(0),
521 PrintName, TypeTable, Machine);
522 for (unsigned i = 1, e = CP->getNumOperands(); i != e; ++i) {
524 printTypeInt(Out, ETy, TypeTable);
525 WriteAsOperandInternal(Out, CP->getOperand(i), PrintName,
529 } else if (isa<ConstantPointerNull>(CV)) {
532 } else if (isa<UndefValue>(CV)) {
535 } else if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV)) {
536 Out << CE->getOpcodeName() << " (";
538 for (User::const_op_iterator OI=CE->op_begin(); OI != CE->op_end(); ++OI) {
539 printTypeInt(Out, (*OI)->getType(), TypeTable);
540 WriteAsOperandInternal(Out, *OI, PrintName, TypeTable, Machine);
541 if (OI+1 != CE->op_end())
547 printTypeInt(Out, CE->getType(), TypeTable);
553 Out << "<placeholder or erroneous Constant>";
558 /// WriteAsOperand - Write the name of the specified value out to the specified
559 /// ostream. This can be useful when you just want to print int %reg126, not
560 /// the whole instruction that generated it.
562 static void WriteAsOperandInternal(std::ostream &Out, const Value *V,
564 std::map<const Type*, std::string> &TypeTable,
565 SlotMachine *Machine) {
567 if ((PrintName || isa<GlobalValue>(V)) && V->hasName())
568 Out << getLLVMName(V->getName());
570 const Constant *CV = dyn_cast<Constant>(V);
571 if (CV && !isa<GlobalValue>(CV)) {
572 WriteConstantInt(Out, CV, PrintName, TypeTable, Machine);
573 } else if (const InlineAsm *IA = dyn_cast<InlineAsm>(V)) {
575 if (IA->hasSideEffects())
576 Out << "sideeffect ";
578 PrintEscapedString(IA->getAsmString(), Out);
580 PrintEscapedString(IA->getConstraintString(), Out);
585 Slot = Machine->getSlot(V);
587 Machine = createSlotMachine(V);
589 Slot = Machine->getSlot(V);
602 /// WriteAsOperand - Write the name of the specified value out to the specified
603 /// ostream. This can be useful when you just want to print int %reg126, not
604 /// the whole instruction that generated it.
606 std::ostream &llvm::WriteAsOperand(std::ostream &Out, const Value *V,
607 bool PrintType, bool PrintName,
608 const Module *Context) {
609 std::map<const Type *, std::string> TypeNames;
610 if (Context == 0) Context = getModuleFromVal(V);
613 fillTypeNameTable(Context, TypeNames);
616 printTypeInt(Out, V->getType(), TypeNames);
618 WriteAsOperandInternal(Out, V, PrintName, TypeNames, 0);
622 /// WriteAsOperandInternal - Write the name of the specified value out to
623 /// the specified ostream. This can be useful when you just want to print
624 /// int %reg126, not the whole instruction that generated it.
626 static void WriteAsOperandInternal(std::ostream &Out, const Type *T,
628 std::map<const Type*, std::string> &TypeTable,
629 SlotMachine *Machine) {
633 Slot = Machine->getSlot(T);
639 Out << T->getDescription();
643 /// WriteAsOperand - Write the name of the specified value out to the specified
644 /// ostream. This can be useful when you just want to print int %reg126, not
645 /// the whole instruction that generated it.
647 std::ostream &llvm::WriteAsOperand(std::ostream &Out, const Type *Ty,
648 bool PrintType, bool PrintName,
649 const Module *Context) {
650 std::map<const Type *, std::string> TypeNames;
651 assert(Context != 0 && "Can't write types as operand without module context");
653 fillTypeNameTable(Context, TypeNames);
656 // printTypeInt(Out, V->getType(), TypeNames);
658 printTypeInt(Out, Ty, TypeNames);
660 WriteAsOperandInternal(Out, Ty, PrintName, TypeNames, 0);
666 class AssemblyWriter {
668 SlotMachine &Machine;
669 const Module *TheModule;
670 std::map<const Type *, std::string> TypeNames;
671 AssemblyAnnotationWriter *AnnotationWriter;
673 inline AssemblyWriter(std::ostream &o, SlotMachine &Mac, const Module *M,
674 AssemblyAnnotationWriter *AAW)
675 : Out(o), Machine(Mac), TheModule(M), AnnotationWriter(AAW) {
677 // If the module has a symbol table, take all global types and stuff their
678 // names into the TypeNames map.
680 fillTypeNameTable(M, TypeNames);
683 inline void write(const Module *M) { printModule(M); }
684 inline void write(const GlobalVariable *G) { printGlobal(G); }
685 inline void write(const Function *F) { printFunction(F); }
686 inline void write(const BasicBlock *BB) { printBasicBlock(BB); }
687 inline void write(const Instruction *I) { printInstruction(*I); }
688 inline void write(const Constant *CPV) { printConstant(CPV); }
689 inline void write(const Type *Ty) { printType(Ty); }
691 void writeOperand(const Value *Op, bool PrintType, bool PrintName = true);
693 const Module* getModule() { return TheModule; }
696 void printModule(const Module *M);
697 void printSymbolTable(const SymbolTable &ST);
698 void printConstant(const Constant *CPV);
699 void printGlobal(const GlobalVariable *GV);
700 void printFunction(const Function *F);
701 void printArgument(const Argument *FA);
702 void printBasicBlock(const BasicBlock *BB);
703 void printInstruction(const Instruction &I);
705 // printType - Go to extreme measures to attempt to print out a short,
706 // symbolic version of a type name.
708 std::ostream &printType(const Type *Ty) {
709 return printTypeInt(Out, Ty, TypeNames);
712 // printTypeAtLeastOneLevel - Print out one level of the possibly complex type
713 // without considering any symbolic types that we may have equal to it.
715 std::ostream &printTypeAtLeastOneLevel(const Type *Ty);
717 // printInfoComment - Print a little comment after the instruction indicating
718 // which slot it occupies.
719 void printInfoComment(const Value &V);
721 } // end of llvm namespace
723 /// printTypeAtLeastOneLevel - Print out one level of the possibly complex type
724 /// without considering any symbolic types that we may have equal to it.
726 std::ostream &AssemblyWriter::printTypeAtLeastOneLevel(const Type *Ty) {
727 if (const FunctionType *FTy = dyn_cast<FunctionType>(Ty)) {
728 printType(FTy->getReturnType()) << " (";
729 for (FunctionType::param_iterator I = FTy->param_begin(),
730 E = FTy->param_end(); I != E; ++I) {
731 if (I != FTy->param_begin())
735 if (FTy->isVarArg()) {
736 if (FTy->getNumParams()) Out << ", ";
740 } else if (const StructType *STy = dyn_cast<StructType>(Ty)) {
742 for (StructType::element_iterator I = STy->element_begin(),
743 E = STy->element_end(); I != E; ++I) {
744 if (I != STy->element_begin())
749 } else if (const PointerType *PTy = dyn_cast<PointerType>(Ty)) {
750 printType(PTy->getElementType()) << '*';
751 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
752 Out << '[' << ATy->getNumElements() << " x ";
753 printType(ATy->getElementType()) << ']';
754 } else if (const PackedType *PTy = dyn_cast<PackedType>(Ty)) {
755 Out << '<' << PTy->getNumElements() << " x ";
756 printType(PTy->getElementType()) << '>';
758 else if (isa<OpaqueType>(Ty)) {
761 if (!Ty->isPrimitiveType())
762 Out << "<unknown derived type>";
769 void AssemblyWriter::writeOperand(const Value *Operand, bool PrintType,
772 if (PrintType) { Out << ' '; printType(Operand->getType()); }
773 WriteAsOperandInternal(Out, Operand, PrintName, TypeNames, &Machine);
775 Out << "<null operand!>";
780 void AssemblyWriter::printModule(const Module *M) {
781 if (!M->getModuleIdentifier().empty() &&
782 // Don't print the ID if it will start a new line (which would
783 // require a comment char before it).
784 M->getModuleIdentifier().find('\n') == std::string::npos)
785 Out << "; ModuleID = '" << M->getModuleIdentifier() << "'\n";
787 if (!M->getDataLayout().empty())
788 Out << "target datalayout = \"" << M->getDataLayout() << "\"\n";
790 switch (M->getEndianness()) {
791 case Module::LittleEndian: Out << "target endian = little\n"; break;
792 case Module::BigEndian: Out << "target endian = big\n"; break;
793 case Module::AnyEndianness: break;
795 switch (M->getPointerSize()) {
796 case Module::Pointer32: Out << "target pointersize = 32\n"; break;
797 case Module::Pointer64: Out << "target pointersize = 64\n"; break;
798 case Module::AnyPointerSize: break;
800 if (!M->getTargetTriple().empty())
801 Out << "target triple = \"" << M->getTargetTriple() << "\"\n";
803 if (!M->getModuleInlineAsm().empty()) {
804 // Split the string into lines, to make it easier to read the .ll file.
805 std::string Asm = M->getModuleInlineAsm();
807 size_t NewLine = Asm.find_first_of('\n', CurPos);
808 while (NewLine != std::string::npos) {
809 // We found a newline, print the portion of the asm string from the
810 // last newline up to this newline.
811 Out << "module asm \"";
812 PrintEscapedString(std::string(Asm.begin()+CurPos, Asm.begin()+NewLine),
816 NewLine = Asm.find_first_of('\n', CurPos);
818 Out << "module asm \"";
819 PrintEscapedString(std::string(Asm.begin()+CurPos, Asm.end()), Out);
823 // Loop over the dependent libraries and emit them.
824 Module::lib_iterator LI = M->lib_begin();
825 Module::lib_iterator LE = M->lib_end();
827 Out << "deplibs = [ ";
829 Out << '"' << *LI << '"';
837 // Loop over the symbol table, emitting all named constants.
838 printSymbolTable(M->getSymbolTable());
840 for (Module::const_global_iterator I = M->global_begin(), E = M->global_end(); I != E; ++I)
843 Out << "\nimplementation ; Functions:\n";
845 // Output all of the functions.
846 for (Module::const_iterator I = M->begin(), E = M->end(); I != E; ++I)
850 void AssemblyWriter::printGlobal(const GlobalVariable *GV) {
851 if (GV->hasName()) Out << getLLVMName(GV->getName()) << " = ";
853 if (!GV->hasInitializer())
854 switch (GV->getLinkage()) {
855 case GlobalValue::DLLImportLinkage: Out << "dllimport "; break;
856 case GlobalValue::ExternalWeakLinkage: Out << "extern_weak "; break;
857 default: Out << "external "; break;
860 switch (GV->getLinkage()) {
861 case GlobalValue::InternalLinkage: Out << "internal "; break;
862 case GlobalValue::LinkOnceLinkage: Out << "linkonce "; break;
863 case GlobalValue::WeakLinkage: Out << "weak "; break;
864 case GlobalValue::AppendingLinkage: Out << "appending "; break;
865 case GlobalValue::DLLImportLinkage: Out << "dllimport "; break;
866 case GlobalValue::DLLExportLinkage: Out << "dllexport "; break;
867 case GlobalValue::ExternalWeakLinkage: Out << "extern_weak "; break;
868 case GlobalValue::ExternalLinkage: break;
869 case GlobalValue::GhostLinkage:
870 llvm_cerr << "GhostLinkage not allowed in AsmWriter!\n";
874 Out << (GV->isConstant() ? "constant " : "global ");
875 printType(GV->getType()->getElementType());
877 if (GV->hasInitializer()) {
878 Constant* C = cast<Constant>(GV->getInitializer());
879 assert(C && "GlobalVar initializer isn't constant?");
880 writeOperand(GV->getInitializer(), false, isa<GlobalValue>(C));
883 if (GV->hasSection())
884 Out << ", section \"" << GV->getSection() << '"';
885 if (GV->getAlignment())
886 Out << ", align " << GV->getAlignment();
888 printInfoComment(*GV);
893 // printSymbolTable - Run through symbol table looking for constants
894 // and types. Emit their declarations.
895 void AssemblyWriter::printSymbolTable(const SymbolTable &ST) {
898 for (SymbolTable::type_const_iterator TI = ST.type_begin();
899 TI != ST.type_end(); ++TI ) {
900 Out << "\t" << getLLVMName(TI->first) << " = type ";
902 // Make sure we print out at least one level of the type structure, so
903 // that we do not get %FILE = type %FILE
905 printTypeAtLeastOneLevel(TI->second) << "\n";
908 // Print the constants, in type plane order.
909 for (SymbolTable::plane_const_iterator PI = ST.plane_begin();
910 PI != ST.plane_end(); ++PI ) {
911 SymbolTable::value_const_iterator VI = ST.value_begin(PI->first);
912 SymbolTable::value_const_iterator VE = ST.value_end(PI->first);
914 for (; VI != VE; ++VI) {
915 const Value* V = VI->second;
916 const Constant *CPV = dyn_cast<Constant>(V) ;
917 if (CPV && !isa<GlobalValue>(V)) {
925 /// printConstant - Print out a constant pool entry...
927 void AssemblyWriter::printConstant(const Constant *CPV) {
928 // Don't print out unnamed constants, they will be inlined
929 if (!CPV->hasName()) return;
932 Out << "\t" << getLLVMName(CPV->getName()) << " =";
934 // Write the value out now...
935 writeOperand(CPV, true, false);
937 printInfoComment(*CPV);
941 /// printFunction - Print all aspects of a function.
943 void AssemblyWriter::printFunction(const Function *F) {
944 // Print out the return type and name...
947 // Ensure that no local symbols conflict with global symbols.
948 const_cast<Function*>(F)->renameLocalSymbols();
950 if (AnnotationWriter) AnnotationWriter->emitFunctionAnnot(F, Out);
953 switch (F->getLinkage()) {
954 case GlobalValue::DLLImportLinkage: Out << "declare dllimport "; break;
955 case GlobalValue::ExternalWeakLinkage: Out << "declare extern_weak "; break;
956 default: Out << "declare ";
959 switch (F->getLinkage()) {
960 case GlobalValue::InternalLinkage: Out << "internal "; break;
961 case GlobalValue::LinkOnceLinkage: Out << "linkonce "; break;
962 case GlobalValue::WeakLinkage: Out << "weak "; break;
963 case GlobalValue::AppendingLinkage: Out << "appending "; break;
964 case GlobalValue::DLLImportLinkage: Out << "dllimport "; break;
965 case GlobalValue::DLLExportLinkage: Out << "dllexport "; break;
966 case GlobalValue::ExternalWeakLinkage: Out << "extern_weak "; break;
967 case GlobalValue::ExternalLinkage: break;
968 case GlobalValue::GhostLinkage:
969 llvm_cerr << "GhostLinkage not allowed in AsmWriter!\n";
973 // Print the calling convention.
974 switch (F->getCallingConv()) {
975 case CallingConv::C: break; // default
976 case CallingConv::CSRet: Out << "csretcc "; break;
977 case CallingConv::Fast: Out << "fastcc "; break;
978 case CallingConv::Cold: Out << "coldcc "; break;
979 case CallingConv::X86_StdCall: Out << "x86_stdcallcc "; break;
980 case CallingConv::X86_FastCall: Out << "x86_fastcallcc "; break;
981 default: Out << "cc" << F->getCallingConv() << " "; break;
984 printType(F->getReturnType()) << ' ';
985 if (!F->getName().empty())
986 Out << getLLVMName(F->getName());
990 Machine.incorporateFunction(F);
992 // Loop over the arguments, printing them...
993 const FunctionType *FT = F->getFunctionType();
995 for(Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end(); I != E; ++I)
998 // Finish printing arguments...
999 if (FT->isVarArg()) {
1000 if (FT->getNumParams()) Out << ", ";
1001 Out << "..."; // Output varargs portion of signature!
1005 if (F->hasSection())
1006 Out << " section \"" << F->getSection() << '"';
1007 if (F->getAlignment())
1008 Out << " align " << F->getAlignment();
1010 if (F->isExternal()) {
1015 // Output all of its basic blocks... for the function
1016 for (Function::const_iterator I = F->begin(), E = F->end(); I != E; ++I)
1022 Machine.purgeFunction();
1025 /// printArgument - This member is called for every argument that is passed into
1026 /// the function. Simply print it out
1028 void AssemblyWriter::printArgument(const Argument *Arg) {
1029 // Insert commas as we go... the first arg doesn't get a comma
1030 if (Arg != Arg->getParent()->arg_begin()) Out << ", ";
1033 printType(Arg->getType());
1035 // Output name, if available...
1037 Out << ' ' << getLLVMName(Arg->getName());
1040 /// printBasicBlock - This member is called for each basic block in a method.
1042 void AssemblyWriter::printBasicBlock(const BasicBlock *BB) {
1043 if (BB->hasName()) { // Print out the label if it exists...
1044 Out << "\n" << getLLVMName(BB->getName(), false) << ':';
1045 } else if (!BB->use_empty()) { // Don't print block # of no uses...
1046 Out << "\n; <label>:";
1047 int Slot = Machine.getSlot(BB);
1054 if (BB->getParent() == 0)
1055 Out << "\t\t; Error: Block without parent!";
1057 if (BB != &BB->getParent()->front()) { // Not the entry block?
1058 // Output predecessors for the block...
1060 pred_const_iterator PI = pred_begin(BB), PE = pred_end(BB);
1063 Out << " No predecessors!";
1066 writeOperand(*PI, false, true);
1067 for (++PI; PI != PE; ++PI) {
1069 writeOperand(*PI, false, true);
1077 if (AnnotationWriter) AnnotationWriter->emitBasicBlockStartAnnot(BB, Out);
1079 // Output all of the instructions in the basic block...
1080 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I != E; ++I)
1081 printInstruction(*I);
1083 if (AnnotationWriter) AnnotationWriter->emitBasicBlockEndAnnot(BB, Out);
1087 /// printInfoComment - Print a little comment after the instruction indicating
1088 /// which slot it occupies.
1090 void AssemblyWriter::printInfoComment(const Value &V) {
1091 if (V.getType() != Type::VoidTy) {
1093 printType(V.getType()) << '>';
1096 int SlotNum = Machine.getSlot(&V);
1100 Out << ':' << SlotNum; // Print out the def slot taken.
1102 Out << " [#uses=" << V.getNumUses() << ']'; // Output # uses
1106 // This member is called for each Instruction in a function..
1107 void AssemblyWriter::printInstruction(const Instruction &I) {
1108 if (AnnotationWriter) AnnotationWriter->emitInstructionAnnot(&I, Out);
1112 // Print out name if it exists...
1114 Out << getLLVMName(I.getName()) << " = ";
1116 // If this is a volatile load or store, print out the volatile marker.
1117 if ((isa<LoadInst>(I) && cast<LoadInst>(I).isVolatile()) ||
1118 (isa<StoreInst>(I) && cast<StoreInst>(I).isVolatile())) {
1120 } else if (isa<CallInst>(I) && cast<CallInst>(I).isTailCall()) {
1121 // If this is a call, check if it's a tail call.
1125 // Print out the opcode...
1126 Out << I.getOpcodeName();
1128 // Print out the compare instruction predicates
1129 if (const FCmpInst *FCI = dyn_cast<FCmpInst>(&I)) {
1130 const char *pred = 0;
1131 switch (FCI->getPredicate()) {
1132 case FCmpInst::FCMP_FALSE: pred = "false";
1133 case FCmpInst::FCMP_OEQ: pred = "oeq";
1134 case FCmpInst::FCMP_OGT: pred = "ogt";
1135 case FCmpInst::FCMP_OGE: pred = "oge";
1136 case FCmpInst::FCMP_OLT: pred = "olt";
1137 case FCmpInst::FCMP_OLE: pred = "ole";
1138 case FCmpInst::FCMP_ONE: pred = "one";
1139 case FCmpInst::FCMP_ORD: pred = "ord";
1140 case FCmpInst::FCMP_UNO: pred = "uno";
1141 case FCmpInst::FCMP_UEQ: pred = "ueq";
1142 case FCmpInst::FCMP_UGT: pred = "ugt";
1143 case FCmpInst::FCMP_UGE: pred = "uge";
1144 case FCmpInst::FCMP_ULT: pred = "ult";
1145 case FCmpInst::FCMP_ULE: pred = "ule";
1146 case FCmpInst::FCMP_UNE: pred = "une";
1147 case FCmpInst::FCMP_TRUE: pred = "true";
1150 } else if (const ICmpInst *ICI = dyn_cast<ICmpInst>(&I)) {
1151 const char *pred = 0;
1152 switch (ICI->getPredicate()) {
1153 case ICmpInst::ICMP_EQ: pred = "eq";
1154 case ICmpInst::ICMP_NE: pred = "ne";
1155 case ICmpInst::ICMP_SGT: pred = "sgt";
1156 case ICmpInst::ICMP_SGE: pred = "sge";
1157 case ICmpInst::ICMP_SLT: pred = "slt";
1158 case ICmpInst::ICMP_SLE: pred = "sle";
1159 case ICmpInst::ICMP_UGT: pred = "ugt";
1160 case ICmpInst::ICMP_UGE: pred = "uge";
1161 case ICmpInst::ICMP_ULT: pred = "ult";
1162 case ICmpInst::ICMP_ULE: pred = "ule";
1167 // Print out the type of the operands...
1168 const Value *Operand = I.getNumOperands() ? I.getOperand(0) : 0;
1170 // Special case conditional branches to swizzle the condition out to the front
1171 if (isa<BranchInst>(I) && I.getNumOperands() > 1) {
1172 writeOperand(I.getOperand(2), true);
1174 writeOperand(Operand, true);
1176 writeOperand(I.getOperand(1), true);
1178 } else if (isa<SwitchInst>(I)) {
1179 // Special case switch statement to get formatting nice and correct...
1180 writeOperand(Operand , true); Out << ',';
1181 writeOperand(I.getOperand(1), true); Out << " [";
1183 for (unsigned op = 2, Eop = I.getNumOperands(); op < Eop; op += 2) {
1185 writeOperand(I.getOperand(op ), true); Out << ',';
1186 writeOperand(I.getOperand(op+1), true);
1189 } else if (isa<PHINode>(I)) {
1191 printType(I.getType());
1194 for (unsigned op = 0, Eop = I.getNumOperands(); op < Eop; op += 2) {
1195 if (op) Out << ", ";
1197 writeOperand(I.getOperand(op ), false); Out << ',';
1198 writeOperand(I.getOperand(op+1), false); Out << " ]";
1200 } else if (isa<ReturnInst>(I) && !Operand) {
1202 } else if (const CallInst *CI = dyn_cast<CallInst>(&I)) {
1203 // Print the calling convention being used.
1204 switch (CI->getCallingConv()) {
1205 case CallingConv::C: break; // default
1206 case CallingConv::CSRet: Out << " csretcc"; break;
1207 case CallingConv::Fast: Out << " fastcc"; break;
1208 case CallingConv::Cold: Out << " coldcc"; break;
1209 case CallingConv::X86_StdCall: Out << "x86_stdcallcc "; break;
1210 case CallingConv::X86_FastCall: Out << "x86_fastcallcc "; break;
1211 default: Out << " cc" << CI->getCallingConv(); break;
1214 const PointerType *PTy = cast<PointerType>(Operand->getType());
1215 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
1216 const Type *RetTy = FTy->getReturnType();
1218 // If possible, print out the short form of the call instruction. We can
1219 // only do this if the first argument is a pointer to a nonvararg function,
1220 // and if the return type is not a pointer to a function.
1222 if (!FTy->isVarArg() &&
1223 (!isa<PointerType>(RetTy) ||
1224 !isa<FunctionType>(cast<PointerType>(RetTy)->getElementType()))) {
1225 Out << ' '; printType(RetTy);
1226 writeOperand(Operand, false);
1228 writeOperand(Operand, true);
1231 if (CI->getNumOperands() > 1) writeOperand(CI->getOperand(1), true);
1232 for (unsigned op = 2, Eop = I.getNumOperands(); op < Eop; ++op) {
1234 writeOperand(I.getOperand(op), true);
1238 } else if (const InvokeInst *II = dyn_cast<InvokeInst>(&I)) {
1239 const PointerType *PTy = cast<PointerType>(Operand->getType());
1240 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
1241 const Type *RetTy = FTy->getReturnType();
1243 // Print the calling convention being used.
1244 switch (II->getCallingConv()) {
1245 case CallingConv::C: break; // default
1246 case CallingConv::CSRet: Out << " csretcc"; break;
1247 case CallingConv::Fast: Out << " fastcc"; break;
1248 case CallingConv::Cold: Out << " coldcc"; break;
1249 case CallingConv::X86_StdCall: Out << "x86_stdcallcc "; break;
1250 case CallingConv::X86_FastCall: Out << "x86_fastcallcc "; break;
1251 default: Out << " cc" << II->getCallingConv(); break;
1254 // If possible, print out the short form of the invoke instruction. We can
1255 // only do this if the first argument is a pointer to a nonvararg function,
1256 // and if the return type is not a pointer to a function.
1258 if (!FTy->isVarArg() &&
1259 (!isa<PointerType>(RetTy) ||
1260 !isa<FunctionType>(cast<PointerType>(RetTy)->getElementType()))) {
1261 Out << ' '; printType(RetTy);
1262 writeOperand(Operand, false);
1264 writeOperand(Operand, true);
1268 if (I.getNumOperands() > 3) writeOperand(I.getOperand(3), true);
1269 for (unsigned op = 4, Eop = I.getNumOperands(); op < Eop; ++op) {
1271 writeOperand(I.getOperand(op), true);
1274 Out << " )\n\t\t\tto";
1275 writeOperand(II->getNormalDest(), true);
1277 writeOperand(II->getUnwindDest(), true);
1279 } else if (const AllocationInst *AI = dyn_cast<AllocationInst>(&I)) {
1281 printType(AI->getType()->getElementType());
1282 if (AI->isArrayAllocation()) {
1284 writeOperand(AI->getArraySize(), true);
1286 if (AI->getAlignment()) {
1287 Out << ", align " << AI->getAlignment();
1289 } else if (isa<CastInst>(I)) {
1290 if (Operand) writeOperand(Operand, true); // Work with broken code
1292 printType(I.getType());
1293 } else if (isa<VAArgInst>(I)) {
1294 if (Operand) writeOperand(Operand, true); // Work with broken code
1296 printType(I.getType());
1297 } else if (Operand) { // Print the normal way...
1299 // PrintAllTypes - Instructions who have operands of all the same type
1300 // omit the type from all but the first operand. If the instruction has
1301 // different type operands (for example br), then they are all printed.
1302 bool PrintAllTypes = false;
1303 const Type *TheType = Operand->getType();
1305 // Shift Left & Right print both types even for Ubyte LHS, and select prints
1306 // types even if all operands are bools.
1307 if (isa<ShiftInst>(I) || isa<SelectInst>(I) || isa<StoreInst>(I) ||
1308 isa<ShuffleVectorInst>(I)) {
1309 PrintAllTypes = true;
1311 for (unsigned i = 1, E = I.getNumOperands(); i != E; ++i) {
1312 Operand = I.getOperand(i);
1313 if (Operand->getType() != TheType) {
1314 PrintAllTypes = true; // We have differing types! Print them all!
1320 if (!PrintAllTypes) {
1325 for (unsigned i = 0, E = I.getNumOperands(); i != E; ++i) {
1327 writeOperand(I.getOperand(i), PrintAllTypes);
1331 printInfoComment(I);
1336 //===----------------------------------------------------------------------===//
1337 // External Interface declarations
1338 //===----------------------------------------------------------------------===//
1340 void Module::print(std::ostream &o, AssemblyAnnotationWriter *AAW) const {
1341 SlotMachine SlotTable(this);
1342 AssemblyWriter W(o, SlotTable, this, AAW);
1346 void GlobalVariable::print(std::ostream &o) const {
1347 SlotMachine SlotTable(getParent());
1348 AssemblyWriter W(o, SlotTable, getParent(), 0);
1352 void Function::print(std::ostream &o, AssemblyAnnotationWriter *AAW) const {
1353 SlotMachine SlotTable(getParent());
1354 AssemblyWriter W(o, SlotTable, getParent(), AAW);
1359 void InlineAsm::print(std::ostream &o, AssemblyAnnotationWriter *AAW) const {
1360 WriteAsOperand(o, this, true, true, 0);
1363 void BasicBlock::print(std::ostream &o, AssemblyAnnotationWriter *AAW) const {
1364 SlotMachine SlotTable(getParent());
1365 AssemblyWriter W(o, SlotTable,
1366 getParent() ? getParent()->getParent() : 0, AAW);
1370 void Instruction::print(std::ostream &o, AssemblyAnnotationWriter *AAW) const {
1371 const Function *F = getParent() ? getParent()->getParent() : 0;
1372 SlotMachine SlotTable(F);
1373 AssemblyWriter W(o, SlotTable, F ? F->getParent() : 0, AAW);
1378 void Constant::print(std::ostream &o) const {
1379 if (this == 0) { o << "<null> constant value\n"; return; }
1381 o << ' ' << getType()->getDescription() << ' ';
1383 std::map<const Type *, std::string> TypeTable;
1384 WriteConstantInt(o, this, false, TypeTable, 0);
1387 void Type::print(std::ostream &o) const {
1391 o << getDescription();
1394 void Argument::print(std::ostream &o) const {
1395 WriteAsOperand(o, this, true, true,
1396 getParent() ? getParent()->getParent() : 0);
1399 // Value::dump - allow easy printing of Values from the debugger.
1400 // Located here because so much of the needed functionality is here.
1401 void Value::dump() const { print(std::cerr); llvm_cerr << '\n'; }
1403 // Type::dump - allow easy printing of Values from the debugger.
1404 // Located here because so much of the needed functionality is here.
1405 void Type::dump() const { print(std::cerr); llvm_cerr << '\n'; }
1407 //===----------------------------------------------------------------------===//
1408 // CachedWriter Class Implementation
1409 //===----------------------------------------------------------------------===//
1411 void CachedWriter::setModule(const Module *M) {
1412 delete SC; delete AW;
1414 SC = new SlotMachine(M );
1415 AW = new AssemblyWriter(Out, *SC, M, 0);
1421 CachedWriter::~CachedWriter() {
1426 CachedWriter &CachedWriter::operator<<(const Value &V) {
1427 assert(AW && SC && "CachedWriter does not have a current module!");
1428 if (const Instruction *I = dyn_cast<Instruction>(&V))
1430 else if (const BasicBlock *BB = dyn_cast<BasicBlock>(&V))
1432 else if (const Function *F = dyn_cast<Function>(&V))
1434 else if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(&V))
1437 AW->writeOperand(&V, true, true);
1441 CachedWriter& CachedWriter::operator<<(const Type &Ty) {
1442 if (SymbolicTypes) {
1443 const Module *M = AW->getModule();
1444 if (M) WriteTypeSymbolic(Out, &Ty, M);
1451 //===----------------------------------------------------------------------===//
1452 //===-- SlotMachine Implementation
1453 //===----------------------------------------------------------------------===//
1456 #define SC_DEBUG(X) llvm_cerr << X
1461 // Module level constructor. Causes the contents of the Module (sans functions)
1462 // to be added to the slot table.
1463 SlotMachine::SlotMachine(const Module *M)
1464 : TheModule(M) ///< Saved for lazy initialization.
1466 , FunctionProcessed(false)
1474 // Function level constructor. Causes the contents of the Module and the one
1475 // function provided to be added to the slot table.
1476 SlotMachine::SlotMachine(const Function *F )
1477 : TheModule( F ? F->getParent() : 0 ) ///< Saved for lazy initialization
1478 , TheFunction(F) ///< Saved for lazy initialization
1479 , FunctionProcessed(false)
1487 inline void SlotMachine::initialize(void) {
1490 TheModule = 0; ///< Prevent re-processing next time we're called.
1492 if ( TheFunction && ! FunctionProcessed) {
1497 // Iterate through all the global variables, functions, and global
1498 // variable initializers and create slots for them.
1499 void SlotMachine::processModule() {
1500 SC_DEBUG("begin processModule!\n");
1502 // Add all of the global variables to the value table...
1503 for (Module::const_global_iterator I = TheModule->global_begin(), E = TheModule->global_end();
1507 // Add all the functions to the table
1508 for (Module::const_iterator I = TheModule->begin(), E = TheModule->end();
1512 SC_DEBUG("end processModule!\n");
1516 // Process the arguments, basic blocks, and instructions of a function.
1517 void SlotMachine::processFunction() {
1518 SC_DEBUG("begin processFunction!\n");
1520 // Add all the function arguments
1521 for(Function::const_arg_iterator AI = TheFunction->arg_begin(),
1522 AE = TheFunction->arg_end(); AI != AE; ++AI)
1525 SC_DEBUG("Inserting Instructions:\n");
1527 // Add all of the basic blocks and instructions
1528 for (Function::const_iterator BB = TheFunction->begin(),
1529 E = TheFunction->end(); BB != E; ++BB) {
1531 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I!=E; ++I) {
1536 FunctionProcessed = true;
1538 SC_DEBUG("end processFunction!\n");
1541 // Clean up after incorporating a function. This is the only way
1542 // to get out of the function incorporation state that affects the
1543 // getSlot/createSlot lock. Function incorporation state is indicated
1544 // by TheFunction != 0.
1545 void SlotMachine::purgeFunction() {
1546 SC_DEBUG("begin purgeFunction!\n");
1547 fMap.clear(); // Simply discard the function level map
1550 FunctionProcessed = false;
1551 SC_DEBUG("end purgeFunction!\n");
1554 /// Get the slot number for a value. This function will assert if you
1555 /// ask for a Value that hasn't previously been inserted with createSlot.
1556 /// Types are forbidden because Type does not inherit from Value (any more).
1557 int SlotMachine::getSlot(const Value *V) {
1558 assert( V && "Can't get slot for null Value" );
1559 assert(!isa<Constant>(V) || isa<GlobalValue>(V) &&
1560 "Can't insert a non-GlobalValue Constant into SlotMachine");
1562 // Check for uninitialized state and do lazy initialization
1565 // Get the type of the value
1566 const Type* VTy = V->getType();
1568 // Find the type plane in the module map
1569 TypedPlanes::const_iterator MI = mMap.find(VTy);
1571 if ( TheFunction ) {
1572 // Lookup the type in the function map too
1573 TypedPlanes::const_iterator FI = fMap.find(VTy);
1574 // If there is a corresponding type plane in the function map
1575 if ( FI != fMap.end() ) {
1576 // Lookup the Value in the function map
1577 ValueMap::const_iterator FVI = FI->second.map.find(V);
1578 // If the value doesn't exist in the function map
1579 if ( FVI == FI->second.map.end() ) {
1580 // Look up the value in the module map.
1581 if (MI == mMap.end()) return -1;
1582 ValueMap::const_iterator MVI = MI->second.map.find(V);
1583 // If we didn't find it, it wasn't inserted
1584 if (MVI == MI->second.map.end()) return -1;
1585 assert( MVI != MI->second.map.end() && "Value not found");
1586 // We found it only at the module level
1589 // else the value exists in the function map
1591 // Return the slot number as the module's contribution to
1592 // the type plane plus the index in the function's contribution
1593 // to the type plane.
1594 if (MI != mMap.end())
1595 return MI->second.next_slot + FVI->second;
1602 // N.B. Can get here only if either !TheFunction or the function doesn't
1603 // have a corresponding type plane for the Value
1605 // Make sure the type plane exists
1606 if (MI == mMap.end()) return -1;
1607 // Lookup the value in the module's map
1608 ValueMap::const_iterator MVI = MI->second.map.find(V);
1609 // Make sure we found it.
1610 if (MVI == MI->second.map.end()) return -1;
1615 /// Get the slot number for a value. This function will assert if you
1616 /// ask for a Value that hasn't previously been inserted with createSlot.
1617 /// Types are forbidden because Type does not inherit from Value (any more).
1618 int SlotMachine::getSlot(const Type *Ty) {
1619 assert( Ty && "Can't get slot for null Type" );
1621 // Check for uninitialized state and do lazy initialization
1624 if ( TheFunction ) {
1625 // Lookup the Type in the function map
1626 TypeMap::const_iterator FTI = fTypes.map.find(Ty);
1627 // If the Type doesn't exist in the function map
1628 if ( FTI == fTypes.map.end() ) {
1629 TypeMap::const_iterator MTI = mTypes.map.find(Ty);
1630 // If we didn't find it, it wasn't inserted
1631 if (MTI == mTypes.map.end())
1633 // We found it only at the module level
1636 // else the value exists in the function map
1638 // Return the slot number as the module's contribution to
1639 // the type plane plus the index in the function's contribution
1640 // to the type plane.
1641 return mTypes.next_slot + FTI->second;
1645 // N.B. Can get here only if either !TheFunction
1647 // Lookup the value in the module's map
1648 TypeMap::const_iterator MTI = mTypes.map.find(Ty);
1649 // Make sure we found it.
1650 if (MTI == mTypes.map.end()) return -1;
1655 // Create a new slot, or return the existing slot if it is already
1656 // inserted. Note that the logic here parallels getSlot but instead
1657 // of asserting when the Value* isn't found, it inserts the value.
1658 unsigned SlotMachine::createSlot(const Value *V) {
1659 assert( V && "Can't insert a null Value to SlotMachine");
1660 assert(!isa<Constant>(V) || isa<GlobalValue>(V) &&
1661 "Can't insert a non-GlobalValue Constant into SlotMachine");
1663 const Type* VTy = V->getType();
1665 // Just ignore void typed things
1666 if (VTy == Type::VoidTy) return 0; // FIXME: Wrong return value!
1668 // Look up the type plane for the Value's type from the module map
1669 TypedPlanes::const_iterator MI = mMap.find(VTy);
1671 if ( TheFunction ) {
1672 // Get the type plane for the Value's type from the function map
1673 TypedPlanes::const_iterator FI = fMap.find(VTy);
1674 // If there is a corresponding type plane in the function map
1675 if ( FI != fMap.end() ) {
1676 // Lookup the Value in the function map
1677 ValueMap::const_iterator FVI = FI->second.map.find(V);
1678 // If the value doesn't exist in the function map
1679 if ( FVI == FI->second.map.end() ) {
1680 // If there is no corresponding type plane in the module map
1681 if ( MI == mMap.end() )
1682 return insertValue(V);
1683 // Look up the value in the module map
1684 ValueMap::const_iterator MVI = MI->second.map.find(V);
1685 // If we didn't find it, it wasn't inserted
1686 if ( MVI == MI->second.map.end() )
1687 return insertValue(V);
1689 // We found it only at the module level
1692 // else the value exists in the function map
1694 if ( MI == mMap.end() )
1697 // Return the slot number as the module's contribution to
1698 // the type plane plus the index in the function's contribution
1699 // to the type plane.
1700 return MI->second.next_slot + FVI->second;
1703 // else there is not a corresponding type plane in the function map
1705 // If the type plane doesn't exists at the module level
1706 if ( MI == mMap.end() ) {
1707 return insertValue(V);
1708 // else type plane exists at the module level, examine it
1710 // Look up the value in the module's map
1711 ValueMap::const_iterator MVI = MI->second.map.find(V);
1712 // If we didn't find it there either
1713 if ( MVI == MI->second.map.end() )
1714 // Return the slot number as the module's contribution to
1715 // the type plane plus the index of the function map insertion.
1716 return MI->second.next_slot + insertValue(V);
1723 // N.B. Can only get here if !TheFunction
1725 // If the module map's type plane is not for the Value's type
1726 if ( MI != mMap.end() ) {
1727 // Lookup the value in the module's map
1728 ValueMap::const_iterator MVI = MI->second.map.find(V);
1729 if ( MVI != MI->second.map.end() )
1733 return insertValue(V);
1736 // Create a new slot, or return the existing slot if it is already
1737 // inserted. Note that the logic here parallels getSlot but instead
1738 // of asserting when the Value* isn't found, it inserts the value.
1739 unsigned SlotMachine::createSlot(const Type *Ty) {
1740 assert( Ty && "Can't insert a null Type to SlotMachine");
1742 if ( TheFunction ) {
1743 // Lookup the Type in the function map
1744 TypeMap::const_iterator FTI = fTypes.map.find(Ty);
1745 // If the type doesn't exist in the function map
1746 if ( FTI == fTypes.map.end() ) {
1747 // Look up the type in the module map
1748 TypeMap::const_iterator MTI = mTypes.map.find(Ty);
1749 // If we didn't find it, it wasn't inserted
1750 if ( MTI == mTypes.map.end() )
1751 return insertValue(Ty);
1753 // We found it only at the module level
1756 // else the value exists in the function map
1758 // Return the slot number as the module's contribution to
1759 // the type plane plus the index in the function's contribution
1760 // to the type plane.
1761 return mTypes.next_slot + FTI->second;
1765 // N.B. Can only get here if !TheFunction
1767 // Lookup the type in the module's map
1768 TypeMap::const_iterator MTI = mTypes.map.find(Ty);
1769 if ( MTI != mTypes.map.end() )
1772 return insertValue(Ty);
1775 // Low level insert function. Minimal checking is done. This
1776 // function is just for the convenience of createSlot (above).
1777 unsigned SlotMachine::insertValue(const Value *V ) {
1778 assert(V && "Can't insert a null Value into SlotMachine!");
1779 assert(!isa<Constant>(V) || isa<GlobalValue>(V) &&
1780 "Can't insert a non-GlobalValue Constant into SlotMachine");
1782 // If this value does not contribute to a plane (is void)
1783 // or if the value already has a name then ignore it.
1784 if (V->getType() == Type::VoidTy || V->hasName() ) {
1785 SC_DEBUG("ignored value " << *V << "\n");
1786 return 0; // FIXME: Wrong return value
1789 const Type *VTy = V->getType();
1790 unsigned DestSlot = 0;
1792 if ( TheFunction ) {
1793 TypedPlanes::iterator I = fMap.find( VTy );
1794 if ( I == fMap.end() )
1795 I = fMap.insert(std::make_pair(VTy,ValuePlane())).first;
1796 DestSlot = I->second.map[V] = I->second.next_slot++;
1798 TypedPlanes::iterator I = mMap.find( VTy );
1799 if ( I == mMap.end() )
1800 I = mMap.insert(std::make_pair(VTy,ValuePlane())).first;
1801 DestSlot = I->second.map[V] = I->second.next_slot++;
1804 SC_DEBUG(" Inserting value [" << VTy << "] = " << V << " slot=" <<
1806 // G = Global, C = Constant, T = Type, F = Function, o = other
1807 SC_DEBUG((isa<GlobalVariable>(V) ? 'G' : (isa<Function>(V) ? 'F' :
1808 (isa<Constant>(V) ? 'C' : 'o'))));
1813 // Low level insert function. Minimal checking is done. This
1814 // function is just for the convenience of createSlot (above).
1815 unsigned SlotMachine::insertValue(const Type *Ty ) {
1816 assert(Ty && "Can't insert a null Type into SlotMachine!");
1818 unsigned DestSlot = 0;
1820 if ( TheFunction ) {
1821 DestSlot = fTypes.map[Ty] = fTypes.next_slot++;
1823 DestSlot = fTypes.map[Ty] = fTypes.next_slot++;
1825 SC_DEBUG(" Inserting type [" << DestSlot << "] = " << Ty << "\n");