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/ParameterAttributes.h"
24 #include "llvm/InlineAsm.h"
25 #include "llvm/Instruction.h"
26 #include "llvm/Instructions.h"
27 #include "llvm/Module.h"
28 #include "llvm/ValueSymbolTable.h"
29 #include "llvm/TypeSymbolTable.h"
30 #include "llvm/ADT/StringExtras.h"
31 #include "llvm/ADT/STLExtras.h"
32 #include "llvm/Support/CFG.h"
33 #include "llvm/Support/MathExtras.h"
34 #include "llvm/Support/Streams.h"
40 // Make virtual table appear in this compilation unit.
41 AssemblyAnnotationWriter::~AssemblyAnnotationWriter() {}
43 /// This class provides computation of slot numbers for LLVM Assembly writing.
44 /// @brief LLVM Assembly Writing Slot Computation.
51 /// @brief A mapping of Values to slot numbers
52 typedef std::map<const Value*,unsigned> ValueMap;
55 /// @name Constructors
58 /// @brief Construct from a module
59 SlotMachine(const Module *M);
61 /// @brief Construct from a function, starting out in incorp state.
62 SlotMachine(const Function *F);
68 /// Return the slot number of the specified value in it's type
69 /// plane. If something is not in the SlotMachine, return -1.
70 int getLocalSlot(const Value *V);
71 int getGlobalSlot(const GlobalValue *V);
77 /// If you'd like to deal with a function instead of just a module, use
78 /// this method to get its data into the SlotMachine.
79 void incorporateFunction(const Function *F) {
81 FunctionProcessed = false;
84 /// After calling incorporateFunction, use this method to remove the
85 /// most recently incorporated function from the SlotMachine. This
86 /// will reset the state of the machine back to just the module contents.
90 /// @name Implementation Details
93 /// This function does the actual initialization.
94 inline void initialize();
96 /// CreateModuleSlot - Insert the specified GlobalValue* into the slot table.
97 void CreateModuleSlot(const GlobalValue *V);
99 /// CreateFunctionSlot - Insert the specified Value* into the slot table.
100 void CreateFunctionSlot(const Value *V);
102 /// Add all of the module level global variables (and their initializers)
103 /// and function declarations, but not the contents of those functions.
104 void processModule();
106 /// Add all of the functions arguments, basic blocks, and instructions
107 void processFunction();
109 SlotMachine(const SlotMachine &); // DO NOT IMPLEMENT
110 void operator=(const SlotMachine &); // DO NOT IMPLEMENT
117 /// @brief The module for which we are holding slot numbers
118 const Module* TheModule;
120 /// @brief The function for which we are holding slot numbers
121 const Function* TheFunction;
122 bool FunctionProcessed;
124 /// @brief The TypePlanes map for the module level data
128 /// @brief The TypePlanes map for the function level data
136 } // end namespace llvm
138 static RegisterPass<PrintModulePass>
139 X("printm", "Print module to stderr");
140 static RegisterPass<PrintFunctionPass>
141 Y("print","Print function to stderr");
143 static void WriteAsOperandInternal(std::ostream &Out, const Value *V,
144 std::map<const Type *, std::string> &TypeTable,
145 SlotMachine *Machine);
147 static const Module *getModuleFromVal(const Value *V) {
148 if (const Argument *MA = dyn_cast<Argument>(V))
149 return MA->getParent() ? MA->getParent()->getParent() : 0;
150 else if (const BasicBlock *BB = dyn_cast<BasicBlock>(V))
151 return BB->getParent() ? BB->getParent()->getParent() : 0;
152 else if (const Instruction *I = dyn_cast<Instruction>(V)) {
153 const Function *M = I->getParent() ? I->getParent()->getParent() : 0;
154 return M ? M->getParent() : 0;
155 } else if (const GlobalValue *GV = dyn_cast<GlobalValue>(V))
156 return GV->getParent();
160 static SlotMachine *createSlotMachine(const Value *V) {
161 if (const Argument *FA = dyn_cast<Argument>(V)) {
162 return new SlotMachine(FA->getParent());
163 } else if (const Instruction *I = dyn_cast<Instruction>(V)) {
164 return new SlotMachine(I->getParent()->getParent());
165 } else if (const BasicBlock *BB = dyn_cast<BasicBlock>(V)) {
166 return new SlotMachine(BB->getParent());
167 } else if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(V)){
168 return new SlotMachine(GV->getParent());
169 } else if (const Function *Func = dyn_cast<Function>(V)) {
170 return new SlotMachine(Func);
175 /// NameNeedsQuotes - Return true if the specified llvm name should be wrapped
177 static bool NameNeedsQuotes(const std::string &Name) {
178 if (Name[0] >= '0' && Name[0] <= '9') return true;
179 // Scan to see if we have any characters that are not on the "white list"
180 for (unsigned i = 0, e = Name.size(); i != e; ++i) {
182 assert(C != '"' && "Illegal character in LLVM value name!");
183 if ((C < 'a' || C > 'z') && (C < 'A' || C > 'Z') && (C < '0' || C > '9') &&
184 C != '-' && C != '.' && C != '_')
196 /// getLLVMName - Turn the specified string into an 'LLVM name', which is either
197 /// prefixed with % (if the string only contains simple characters) or is
198 /// surrounded with ""'s (if it has special chars in it).
199 static std::string getLLVMName(const std::string &Name, PrefixType Prefix) {
200 assert(!Name.empty() && "Cannot get empty name!");
202 // First character cannot start with a number...
203 if (NameNeedsQuotes(Name)) {
204 if (Prefix == GlobalPrefix)
205 return "@\"" + Name + "\"";
206 return "\"" + Name + "\"";
209 // If we get here, then the identifier is legal to use as a "VarID".
211 default: assert(0 && "Bad prefix!");
212 case GlobalPrefix: return '@' + Name;
213 case LabelPrefix: return Name;
214 case LocalPrefix: return '%' + Name;
219 /// fillTypeNameTable - If the module has a symbol table, take all global types
220 /// and stuff their names into the TypeNames map.
222 static void fillTypeNameTable(const Module *M,
223 std::map<const Type *, std::string> &TypeNames) {
225 const TypeSymbolTable &ST = M->getTypeSymbolTable();
226 TypeSymbolTable::const_iterator TI = ST.begin();
227 for (; TI != ST.end(); ++TI) {
228 // As a heuristic, don't insert pointer to primitive types, because
229 // they are used too often to have a single useful name.
231 const Type *Ty = cast<Type>(TI->second);
232 if (!isa<PointerType>(Ty) ||
233 !cast<PointerType>(Ty)->getElementType()->isPrimitiveType() ||
234 !cast<PointerType>(Ty)->getElementType()->isInteger() ||
235 isa<OpaqueType>(cast<PointerType>(Ty)->getElementType()))
236 TypeNames.insert(std::make_pair(Ty, getLLVMName(TI->first, LocalPrefix)));
242 static void calcTypeName(const Type *Ty,
243 std::vector<const Type *> &TypeStack,
244 std::map<const Type *, std::string> &TypeNames,
245 std::string & Result){
246 if (Ty->isInteger() || (Ty->isPrimitiveType() && !isa<OpaqueType>(Ty))) {
247 Result += Ty->getDescription(); // Base case
251 // Check to see if the type is named.
252 std::map<const Type *, std::string>::iterator I = TypeNames.find(Ty);
253 if (I != TypeNames.end()) {
258 if (isa<OpaqueType>(Ty)) {
263 // Check to see if the Type is already on the stack...
264 unsigned Slot = 0, CurSize = TypeStack.size();
265 while (Slot < CurSize && TypeStack[Slot] != Ty) ++Slot; // Scan for type
267 // This is another base case for the recursion. In this case, we know
268 // that we have looped back to a type that we have previously visited.
269 // Generate the appropriate upreference to handle this.
270 if (Slot < CurSize) {
271 Result += "\\" + utostr(CurSize-Slot); // Here's the upreference
275 TypeStack.push_back(Ty); // Recursive case: Add us to the stack..
277 switch (Ty->getTypeID()) {
278 case Type::IntegerTyID: {
279 unsigned BitWidth = cast<IntegerType>(Ty)->getBitWidth();
280 Result += "i" + utostr(BitWidth);
283 case Type::FunctionTyID: {
284 const FunctionType *FTy = cast<FunctionType>(Ty);
285 calcTypeName(FTy->getReturnType(), TypeStack, TypeNames, Result);
288 const ParamAttrsList *Attrs = FTy->getParamAttrs();
289 for (FunctionType::param_iterator I = FTy->param_begin(),
290 E = FTy->param_end(); I != E; ++I) {
291 if (I != FTy->param_begin())
293 calcTypeName(*I, TypeStack, TypeNames, Result);
294 if (Attrs && Attrs->getParamAttrs(Idx) != ParamAttr::None) {
296 Result += Attrs->getParamAttrsTextByIndex(Idx);
300 if (FTy->isVarArg()) {
301 if (FTy->getNumParams()) Result += ", ";
305 if (Attrs && Attrs->getParamAttrs(0) != ParamAttr::None) {
307 Result += Attrs->getParamAttrsTextByIndex(0);
311 case Type::StructTyID: {
312 const StructType *STy = cast<StructType>(Ty);
316 for (StructType::element_iterator I = STy->element_begin(),
317 E = STy->element_end(); I != E; ++I) {
318 if (I != STy->element_begin())
320 calcTypeName(*I, TypeStack, TypeNames, Result);
327 case Type::PointerTyID:
328 calcTypeName(cast<PointerType>(Ty)->getElementType(),
329 TypeStack, TypeNames, Result);
332 case Type::ArrayTyID: {
333 const ArrayType *ATy = cast<ArrayType>(Ty);
334 Result += "[" + utostr(ATy->getNumElements()) + " x ";
335 calcTypeName(ATy->getElementType(), TypeStack, TypeNames, Result);
339 case Type::VectorTyID: {
340 const VectorType *PTy = cast<VectorType>(Ty);
341 Result += "<" + utostr(PTy->getNumElements()) + " x ";
342 calcTypeName(PTy->getElementType(), TypeStack, TypeNames, Result);
346 case Type::OpaqueTyID:
350 Result += "<unrecognized-type>";
354 TypeStack.pop_back(); // Remove self from stack...
358 /// printTypeInt - The internal guts of printing out a type that has a
359 /// potentially named portion.
361 static std::ostream &printTypeInt(std::ostream &Out, const Type *Ty,
362 std::map<const Type *, std::string> &TypeNames) {
363 // Primitive types always print out their description, regardless of whether
364 // they have been named or not.
366 if (Ty->isInteger() || (Ty->isPrimitiveType() && !isa<OpaqueType>(Ty)))
367 return Out << Ty->getDescription();
369 // Check to see if the type is named.
370 std::map<const Type *, std::string>::iterator I = TypeNames.find(Ty);
371 if (I != TypeNames.end()) return Out << I->second;
373 // Otherwise we have a type that has not been named but is a derived type.
374 // Carefully recurse the type hierarchy to print out any contained symbolic
377 std::vector<const Type *> TypeStack;
378 std::string TypeName;
379 calcTypeName(Ty, TypeStack, TypeNames, TypeName);
380 TypeNames.insert(std::make_pair(Ty, TypeName));//Cache type name for later use
381 return (Out << TypeName);
385 /// WriteTypeSymbolic - This attempts to write the specified type as a symbolic
386 /// type, iff there is an entry in the modules symbol table for the specified
387 /// type or one of it's component types. This is slower than a simple x << Type
389 std::ostream &llvm::WriteTypeSymbolic(std::ostream &Out, const Type *Ty,
393 // If they want us to print out a type, but there is no context, we can't
394 // print it symbolically.
396 return Out << Ty->getDescription();
398 std::map<const Type *, std::string> TypeNames;
399 fillTypeNameTable(M, TypeNames);
400 return printTypeInt(Out, Ty, TypeNames);
403 // PrintEscapedString - Print each character of the specified string, escaping
404 // it if it is not printable or if it is an escape char.
405 static void PrintEscapedString(const std::string &Str, std::ostream &Out) {
406 for (unsigned i = 0, e = Str.size(); i != e; ++i) {
407 unsigned char C = Str[i];
408 if (isprint(C) && C != '"' && C != '\\') {
412 << (char) ((C/16 < 10) ? ( C/16 +'0') : ( C/16 -10+'A'))
413 << (char)(((C&15) < 10) ? ((C&15)+'0') : ((C&15)-10+'A'));
418 static const char *getPredicateText(unsigned predicate) {
419 const char * pred = "unknown";
421 case FCmpInst::FCMP_FALSE: pred = "false"; break;
422 case FCmpInst::FCMP_OEQ: pred = "oeq"; break;
423 case FCmpInst::FCMP_OGT: pred = "ogt"; break;
424 case FCmpInst::FCMP_OGE: pred = "oge"; break;
425 case FCmpInst::FCMP_OLT: pred = "olt"; break;
426 case FCmpInst::FCMP_OLE: pred = "ole"; break;
427 case FCmpInst::FCMP_ONE: pred = "one"; break;
428 case FCmpInst::FCMP_ORD: pred = "ord"; break;
429 case FCmpInst::FCMP_UNO: pred = "uno"; break;
430 case FCmpInst::FCMP_UEQ: pred = "ueq"; break;
431 case FCmpInst::FCMP_UGT: pred = "ugt"; break;
432 case FCmpInst::FCMP_UGE: pred = "uge"; break;
433 case FCmpInst::FCMP_ULT: pred = "ult"; break;
434 case FCmpInst::FCMP_ULE: pred = "ule"; break;
435 case FCmpInst::FCMP_UNE: pred = "une"; break;
436 case FCmpInst::FCMP_TRUE: pred = "true"; break;
437 case ICmpInst::ICMP_EQ: pred = "eq"; break;
438 case ICmpInst::ICMP_NE: pred = "ne"; break;
439 case ICmpInst::ICMP_SGT: pred = "sgt"; break;
440 case ICmpInst::ICMP_SGE: pred = "sge"; break;
441 case ICmpInst::ICMP_SLT: pred = "slt"; break;
442 case ICmpInst::ICMP_SLE: pred = "sle"; break;
443 case ICmpInst::ICMP_UGT: pred = "ugt"; break;
444 case ICmpInst::ICMP_UGE: pred = "uge"; break;
445 case ICmpInst::ICMP_ULT: pred = "ult"; break;
446 case ICmpInst::ICMP_ULE: pred = "ule"; break;
451 /// @brief Internal constant writer.
452 static void WriteConstantInt(std::ostream &Out, const Constant *CV,
453 std::map<const Type *, std::string> &TypeTable,
454 SlotMachine *Machine) {
455 const int IndentSize = 4;
456 static std::string Indent = "\n";
457 if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV)) {
458 if (CI->getType() == Type::Int1Ty)
459 Out << (CI->getZExtValue() ? "true" : "false");
461 Out << CI->getValue().toStringSigned(10);
462 } else if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CV)) {
463 // We would like to output the FP constant value in exponential notation,
464 // but we cannot do this if doing so will lose precision. Check here to
465 // make sure that we only output it in exponential format if we can parse
466 // the value back and get the same value.
468 std::string StrVal = ftostr(CFP->getValue());
470 // Check to make sure that the stringized number is not some string like
471 // "Inf" or NaN, that atof will accept, but the lexer will not. Check that
472 // the string matches the "[-+]?[0-9]" regex.
474 if ((StrVal[0] >= '0' && StrVal[0] <= '9') ||
475 ((StrVal[0] == '-' || StrVal[0] == '+') &&
476 (StrVal[1] >= '0' && StrVal[1] <= '9')))
477 // Reparse stringized version!
478 if (atof(StrVal.c_str()) == CFP->getValue()) {
483 // Otherwise we could not reparse it to exactly the same value, so we must
484 // output the string in hexadecimal format!
485 assert(sizeof(double) == sizeof(uint64_t) &&
486 "assuming that double is 64 bits!");
487 Out << "0x" << utohexstr(DoubleToBits(CFP->getValue()));
489 } else if (isa<ConstantAggregateZero>(CV)) {
490 Out << "zeroinitializer";
491 } else if (const ConstantArray *CA = dyn_cast<ConstantArray>(CV)) {
492 // As a special case, print the array as a string if it is an array of
493 // ubytes or an array of sbytes with positive values.
495 const Type *ETy = CA->getType()->getElementType();
496 if (CA->isString()) {
498 PrintEscapedString(CA->getAsString(), Out);
501 } else { // Cannot output in string format...
503 if (CA->getNumOperands()) {
505 printTypeInt(Out, ETy, TypeTable);
506 WriteAsOperandInternal(Out, CA->getOperand(0),
508 for (unsigned i = 1, e = CA->getNumOperands(); i != e; ++i) {
510 printTypeInt(Out, ETy, TypeTable);
511 WriteAsOperandInternal(Out, CA->getOperand(i), TypeTable, Machine);
516 } else if (const ConstantStruct *CS = dyn_cast<ConstantStruct>(CV)) {
517 if (CS->getType()->isPacked())
520 unsigned N = CS->getNumOperands();
523 Indent += std::string(IndentSize, ' ');
528 printTypeInt(Out, CS->getOperand(0)->getType(), TypeTable);
530 WriteAsOperandInternal(Out, CS->getOperand(0), TypeTable, Machine);
532 for (unsigned i = 1; i < N; i++) {
534 if (N > 2) Out << Indent;
535 printTypeInt(Out, CS->getOperand(i)->getType(), TypeTable);
537 WriteAsOperandInternal(Out, CS->getOperand(i), TypeTable, Machine);
539 if (N > 2) Indent.resize(Indent.size() - IndentSize);
543 if (CS->getType()->isPacked())
545 } else if (const ConstantVector *CP = dyn_cast<ConstantVector>(CV)) {
546 const Type *ETy = CP->getType()->getElementType();
547 assert(CP->getNumOperands() > 0 &&
548 "Number of operands for a PackedConst must be > 0");
551 printTypeInt(Out, ETy, TypeTable);
552 WriteAsOperandInternal(Out, CP->getOperand(0), TypeTable, Machine);
553 for (unsigned i = 1, e = CP->getNumOperands(); i != e; ++i) {
555 printTypeInt(Out, ETy, TypeTable);
556 WriteAsOperandInternal(Out, CP->getOperand(i), TypeTable, Machine);
559 } else if (isa<ConstantPointerNull>(CV)) {
562 } else if (isa<UndefValue>(CV)) {
565 } else if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV)) {
566 Out << CE->getOpcodeName();
568 Out << " " << getPredicateText(CE->getPredicate());
571 for (User::const_op_iterator OI=CE->op_begin(); OI != CE->op_end(); ++OI) {
572 printTypeInt(Out, (*OI)->getType(), TypeTable);
573 WriteAsOperandInternal(Out, *OI, TypeTable, Machine);
574 if (OI+1 != CE->op_end())
580 printTypeInt(Out, CE->getType(), TypeTable);
586 Out << "<placeholder or erroneous Constant>";
591 /// WriteAsOperand - Write the name of the specified value out to the specified
592 /// ostream. This can be useful when you just want to print int %reg126, not
593 /// the whole instruction that generated it.
595 static void WriteAsOperandInternal(std::ostream &Out, const Value *V,
596 std::map<const Type*, std::string> &TypeTable,
597 SlotMachine *Machine) {
600 Out << getLLVMName(V->getName(),
601 isa<GlobalValue>(V) ? GlobalPrefix : LocalPrefix);
603 const Constant *CV = dyn_cast<Constant>(V);
604 if (CV && !isa<GlobalValue>(CV)) {
605 WriteConstantInt(Out, CV, TypeTable, Machine);
606 } else if (const InlineAsm *IA = dyn_cast<InlineAsm>(V)) {
608 if (IA->hasSideEffects())
609 Out << "sideeffect ";
611 PrintEscapedString(IA->getAsmString(), Out);
613 PrintEscapedString(IA->getConstraintString(), Out);
619 if (const GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
620 Slot = Machine->getGlobalSlot(GV);
623 Slot = Machine->getLocalSlot(V);
626 Machine = createSlotMachine(V);
628 if (const GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
629 Slot = Machine->getGlobalSlot(GV);
632 Slot = Machine->getLocalSlot(V);
640 Out << Prefix << Slot;
647 /// WriteAsOperand - Write the name of the specified value out to the specified
648 /// ostream. This can be useful when you just want to print int %reg126, not
649 /// the whole instruction that generated it.
651 std::ostream &llvm::WriteAsOperand(std::ostream &Out, const Value *V,
652 bool PrintType, const Module *Context) {
653 std::map<const Type *, std::string> TypeNames;
654 if (Context == 0) Context = getModuleFromVal(V);
657 fillTypeNameTable(Context, TypeNames);
660 printTypeInt(Out, V->getType(), TypeNames);
662 WriteAsOperandInternal(Out, V, TypeNames, 0);
669 class AssemblyWriter {
671 SlotMachine &Machine;
672 const Module *TheModule;
673 std::map<const Type *, std::string> TypeNames;
674 AssemblyAnnotationWriter *AnnotationWriter;
676 inline AssemblyWriter(std::ostream &o, SlotMachine &Mac, const Module *M,
677 AssemblyAnnotationWriter *AAW)
678 : Out(o), Machine(Mac), TheModule(M), AnnotationWriter(AAW) {
680 // If the module has a symbol table, take all global types and stuff their
681 // names into the TypeNames map.
683 fillTypeNameTable(M, TypeNames);
686 inline void write(const Module *M) { printModule(M); }
687 inline void write(const GlobalVariable *G) { printGlobal(G); }
688 inline void write(const Function *F) { printFunction(F); }
689 inline void write(const BasicBlock *BB) { printBasicBlock(BB); }
690 inline void write(const Instruction *I) { printInstruction(*I); }
691 inline void write(const Type *Ty) { printType(Ty); }
693 void writeOperand(const Value *Op, bool PrintType);
695 const Module* getModule() { return TheModule; }
698 void printModule(const Module *M);
699 void printTypeSymbolTable(const TypeSymbolTable &ST);
700 void printGlobal(const GlobalVariable *GV);
701 void printFunction(const Function *F);
702 void printArgument(const Argument *FA, uint16_t ParamAttrs);
703 void printBasicBlock(const BasicBlock *BB);
704 void printInstruction(const Instruction &I);
706 // printType - Go to extreme measures to attempt to print out a short,
707 // symbolic version of a type name.
709 std::ostream &printType(const Type *Ty) {
710 return printTypeInt(Out, Ty, TypeNames);
713 // printTypeAtLeastOneLevel - Print out one level of the possibly complex type
714 // without considering any symbolic types that we may have equal to it.
716 std::ostream &printTypeAtLeastOneLevel(const Type *Ty);
718 // printInfoComment - Print a little comment after the instruction indicating
719 // which slot it occupies.
720 void printInfoComment(const Value &V);
722 } // end of llvm namespace
724 /// printTypeAtLeastOneLevel - Print out one level of the possibly complex type
725 /// without considering any symbolic types that we may have equal to it.
727 std::ostream &AssemblyWriter::printTypeAtLeastOneLevel(const Type *Ty) {
728 if (const IntegerType *ITy = dyn_cast<IntegerType>(Ty))
729 Out << "i" << utostr(ITy->getBitWidth());
730 else if (const FunctionType *FTy = dyn_cast<FunctionType>(Ty)) {
731 printType(FTy->getReturnType());
734 const ParamAttrsList *Attrs = FTy->getParamAttrs();
735 for (FunctionType::param_iterator I = FTy->param_begin(),
736 E = FTy->param_end(); I != E; ++I) {
737 if (I != FTy->param_begin())
740 if (Attrs && Attrs->getParamAttrs(Idx) != ParamAttr::None) {
741 Out << " " << Attrs->getParamAttrsTextByIndex(Idx);
745 if (FTy->isVarArg()) {
746 if (FTy->getNumParams()) Out << ", ";
750 if (Attrs && Attrs->getParamAttrs(0) != ParamAttr::None)
751 Out << ' ' << Attrs->getParamAttrsTextByIndex(0);
752 } else if (const StructType *STy = dyn_cast<StructType>(Ty)) {
756 for (StructType::element_iterator I = STy->element_begin(),
757 E = STy->element_end(); I != E; ++I) {
758 if (I != STy->element_begin())
765 } else if (const PointerType *PTy = dyn_cast<PointerType>(Ty)) {
766 printType(PTy->getElementType()) << '*';
767 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
768 Out << '[' << ATy->getNumElements() << " x ";
769 printType(ATy->getElementType()) << ']';
770 } else if (const VectorType *PTy = dyn_cast<VectorType>(Ty)) {
771 Out << '<' << PTy->getNumElements() << " x ";
772 printType(PTy->getElementType()) << '>';
774 else if (isa<OpaqueType>(Ty)) {
777 if (!Ty->isPrimitiveType())
778 Out << "<unknown derived type>";
785 void AssemblyWriter::writeOperand(const Value *Operand, bool PrintType) {
787 Out << "<null operand!>";
789 if (PrintType) { Out << ' '; printType(Operand->getType()); }
790 WriteAsOperandInternal(Out, Operand, TypeNames, &Machine);
795 void AssemblyWriter::printModule(const Module *M) {
796 if (!M->getModuleIdentifier().empty() &&
797 // Don't print the ID if it will start a new line (which would
798 // require a comment char before it).
799 M->getModuleIdentifier().find('\n') == std::string::npos)
800 Out << "; ModuleID = '" << M->getModuleIdentifier() << "'\n";
802 if (!M->getDataLayout().empty())
803 Out << "target datalayout = \"" << M->getDataLayout() << "\"\n";
804 if (!M->getTargetTriple().empty())
805 Out << "target triple = \"" << M->getTargetTriple() << "\"\n";
807 if (!M->getModuleInlineAsm().empty()) {
808 // Split the string into lines, to make it easier to read the .ll file.
809 std::string Asm = M->getModuleInlineAsm();
811 size_t NewLine = Asm.find_first_of('\n', CurPos);
812 while (NewLine != std::string::npos) {
813 // We found a newline, print the portion of the asm string from the
814 // last newline up to this newline.
815 Out << "module asm \"";
816 PrintEscapedString(std::string(Asm.begin()+CurPos, Asm.begin()+NewLine),
820 NewLine = Asm.find_first_of('\n', CurPos);
822 Out << "module asm \"";
823 PrintEscapedString(std::string(Asm.begin()+CurPos, Asm.end()), Out);
827 // Loop over the dependent libraries and emit them.
828 Module::lib_iterator LI = M->lib_begin();
829 Module::lib_iterator LE = M->lib_end();
831 Out << "deplibs = [ ";
833 Out << '"' << *LI << '"';
841 // Loop over the symbol table, emitting all named constants.
842 printTypeSymbolTable(M->getTypeSymbolTable());
844 for (Module::const_global_iterator I = M->global_begin(), E = M->global_end();
848 // Output all of the functions.
849 for (Module::const_iterator I = M->begin(), E = M->end(); I != E; ++I)
853 void AssemblyWriter::printGlobal(const GlobalVariable *GV) {
854 if (GV->hasName()) Out << getLLVMName(GV->getName(), GlobalPrefix) << " = ";
856 if (!GV->hasInitializer())
857 switch (GV->getLinkage()) {
858 case GlobalValue::DLLImportLinkage: Out << "dllimport "; break;
859 case GlobalValue::ExternalWeakLinkage: Out << "extern_weak "; break;
860 default: Out << "external "; break;
862 switch (GV->getLinkage()) {
863 case GlobalValue::InternalLinkage: Out << "internal "; break;
864 case GlobalValue::LinkOnceLinkage: Out << "linkonce "; break;
865 case GlobalValue::WeakLinkage: Out << "weak "; break;
866 case GlobalValue::AppendingLinkage: Out << "appending "; break;
867 case GlobalValue::DLLImportLinkage: Out << "dllimport "; break;
868 case GlobalValue::DLLExportLinkage: Out << "dllexport "; break;
869 case GlobalValue::ExternalWeakLinkage: Out << "extern_weak "; break;
870 case GlobalValue::ExternalLinkage: break;
871 case GlobalValue::GhostLinkage:
872 cerr << "GhostLinkage not allowed in AsmWriter!\n";
875 switch (GV->getVisibility()) {
876 default: assert(0 && "Invalid visibility style!");
877 case GlobalValue::DefaultVisibility: break;
878 case GlobalValue::HiddenVisibility: Out << "hidden "; break;
882 if (GV->isThreadLocal()) Out << "thread_local ";
883 Out << (GV->isConstant() ? "constant " : "global ");
884 printType(GV->getType()->getElementType());
886 if (GV->hasInitializer()) {
887 Constant* C = cast<Constant>(GV->getInitializer());
888 assert(C && "GlobalVar initializer isn't constant?");
889 writeOperand(GV->getInitializer(), false);
892 if (GV->hasSection())
893 Out << ", section \"" << GV->getSection() << '"';
894 if (GV->getAlignment())
895 Out << ", align " << GV->getAlignment();
897 printInfoComment(*GV);
901 void AssemblyWriter::printTypeSymbolTable(const TypeSymbolTable &ST) {
903 for (TypeSymbolTable::const_iterator TI = ST.begin(), TE = ST.end();
905 Out << "\t" << getLLVMName(TI->first, LocalPrefix) << " = type ";
907 // Make sure we print out at least one level of the type structure, so
908 // that we do not get %FILE = type %FILE
910 printTypeAtLeastOneLevel(TI->second) << "\n";
914 /// printFunction - Print all aspects of a function.
916 void AssemblyWriter::printFunction(const Function *F) {
917 // Print out the return type and name...
920 if (AnnotationWriter) AnnotationWriter->emitFunctionAnnot(F, Out);
922 if (F->isDeclaration())
923 switch (F->getLinkage()) {
924 case GlobalValue::DLLImportLinkage: Out << "declare dllimport "; break;
925 case GlobalValue::ExternalWeakLinkage: Out << "declare extern_weak "; break;
926 default: Out << "declare ";
930 switch (F->getLinkage()) {
931 case GlobalValue::InternalLinkage: Out << "internal "; break;
932 case GlobalValue::LinkOnceLinkage: Out << "linkonce "; break;
933 case GlobalValue::WeakLinkage: Out << "weak "; break;
934 case GlobalValue::AppendingLinkage: Out << "appending "; break;
935 case GlobalValue::DLLImportLinkage: Out << "dllimport "; break;
936 case GlobalValue::DLLExportLinkage: Out << "dllexport "; break;
937 case GlobalValue::ExternalWeakLinkage: Out << "extern_weak "; break;
938 case GlobalValue::ExternalLinkage: break;
939 case GlobalValue::GhostLinkage:
940 cerr << "GhostLinkage not allowed in AsmWriter!\n";
943 switch (F->getVisibility()) {
944 default: assert(0 && "Invalid visibility style!");
945 case GlobalValue::DefaultVisibility: break;
946 case GlobalValue::HiddenVisibility: Out << "hidden "; break;
950 // Print the calling convention.
951 switch (F->getCallingConv()) {
952 case CallingConv::C: break; // default
953 case CallingConv::Fast: Out << "fastcc "; break;
954 case CallingConv::Cold: Out << "coldcc "; break;
955 case CallingConv::X86_StdCall: Out << "x86_stdcallcc "; break;
956 case CallingConv::X86_FastCall: Out << "x86_fastcallcc "; break;
957 default: Out << "cc" << F->getCallingConv() << " "; break;
960 const FunctionType *FT = F->getFunctionType();
961 const ParamAttrsList *Attrs = FT->getParamAttrs();
962 printType(F->getReturnType()) << ' ';
963 if (!F->getName().empty())
964 Out << getLLVMName(F->getName(), GlobalPrefix);
968 Machine.incorporateFunction(F);
970 // Loop over the arguments, printing them...
973 if (!F->isDeclaration()) {
974 // If this isn't a declaration, print the argument names as well.
975 for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
977 // Insert commas as we go... the first arg doesn't get a comma
978 if (I != F->arg_begin()) Out << ", ";
979 printArgument(I, (Attrs ? Attrs->getParamAttrs(Idx)
980 : uint16_t(ParamAttr::None)));
984 // Otherwise, print the types from the function type.
985 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
986 // Insert commas as we go... the first arg doesn't get a comma
990 printType(FT->getParamType(i));
992 unsigned ArgAttrs = ParamAttr::None;
993 if (Attrs) ArgAttrs = Attrs->getParamAttrs(i+1);
994 if (ArgAttrs != ParamAttr::None)
995 Out << ' ' << ParamAttrsList::getParamAttrsText(ArgAttrs);
999 // Finish printing arguments...
1000 if (FT->isVarArg()) {
1001 if (FT->getNumParams()) Out << ", ";
1002 Out << "..."; // Output varargs portion of signature!
1005 if (Attrs && Attrs->getParamAttrs(0) != ParamAttr::None)
1006 Out << ' ' << Attrs->getParamAttrsTextByIndex(0);
1007 if (F->hasSection())
1008 Out << " section \"" << F->getSection() << '"';
1009 if (F->getAlignment())
1010 Out << " align " << F->getAlignment();
1012 if (F->isDeclaration()) {
1017 // Output all of its basic blocks... for the function
1018 for (Function::const_iterator I = F->begin(), E = F->end(); I != E; ++I)
1024 Machine.purgeFunction();
1027 /// printArgument - This member is called for every argument that is passed into
1028 /// the function. Simply print it out
1030 void AssemblyWriter::printArgument(const Argument *Arg, uint16_t Attrs) {
1032 printType(Arg->getType());
1034 if (Attrs != ParamAttr::None)
1035 Out << ' ' << ParamAttrsList::getParamAttrsText(Attrs);
1037 // Output name, if available...
1039 Out << ' ' << getLLVMName(Arg->getName(), LocalPrefix);
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(), LabelPrefix) << ':';
1047 } else if (!BB->use_empty()) { // Don't print block # of no uses...
1048 Out << "\n; <label>:";
1049 int Slot = Machine.getLocalSlot(BB);
1056 if (BB->getParent() == 0)
1057 Out << "\t\t; Error: Block without parent!";
1059 if (BB != &BB->getParent()->getEntryBlock()) { // 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()) << '>';
1099 if (const GlobalValue *GV = dyn_cast<GlobalValue>(&V))
1100 SlotNum = Machine.getGlobalSlot(GV);
1102 SlotNum = Machine.getLocalSlot(&V);
1106 Out << ':' << SlotNum; // Print out the def slot taken.
1108 Out << " [#uses=" << V.getNumUses() << ']'; // Output # uses
1112 // This member is called for each Instruction in a function..
1113 void AssemblyWriter::printInstruction(const Instruction &I) {
1114 if (AnnotationWriter) AnnotationWriter->emitInstructionAnnot(&I, Out);
1118 // Print out name if it exists...
1120 Out << getLLVMName(I.getName(), LocalPrefix) << " = ";
1122 // If this is a volatile load or store, print out the volatile marker.
1123 if ((isa<LoadInst>(I) && cast<LoadInst>(I).isVolatile()) ||
1124 (isa<StoreInst>(I) && cast<StoreInst>(I).isVolatile())) {
1126 } else if (isa<CallInst>(I) && cast<CallInst>(I).isTailCall()) {
1127 // If this is a call, check if it's a tail call.
1131 // Print out the opcode...
1132 Out << I.getOpcodeName();
1134 // Print out the compare instruction predicates
1135 if (const FCmpInst *FCI = dyn_cast<FCmpInst>(&I)) {
1136 Out << " " << getPredicateText(FCI->getPredicate());
1137 } else if (const ICmpInst *ICI = dyn_cast<ICmpInst>(&I)) {
1138 Out << " " << getPredicateText(ICI->getPredicate());
1141 // Print out the type of the operands...
1142 const Value *Operand = I.getNumOperands() ? I.getOperand(0) : 0;
1144 // Special case conditional branches to swizzle the condition out to the front
1145 if (isa<BranchInst>(I) && I.getNumOperands() > 1) {
1146 writeOperand(I.getOperand(2), true);
1148 writeOperand(Operand, true);
1150 writeOperand(I.getOperand(1), true);
1152 } else if (isa<SwitchInst>(I)) {
1153 // Special case switch statement to get formatting nice and correct...
1154 writeOperand(Operand , true); Out << ',';
1155 writeOperand(I.getOperand(1), true); Out << " [";
1157 for (unsigned op = 2, Eop = I.getNumOperands(); op < Eop; op += 2) {
1159 writeOperand(I.getOperand(op ), true); Out << ',';
1160 writeOperand(I.getOperand(op+1), true);
1163 } else if (isa<PHINode>(I)) {
1165 printType(I.getType());
1168 for (unsigned op = 0, Eop = I.getNumOperands(); op < Eop; op += 2) {
1169 if (op) Out << ", ";
1171 writeOperand(I.getOperand(op ), false); Out << ',';
1172 writeOperand(I.getOperand(op+1), false); Out << " ]";
1174 } else if (isa<ReturnInst>(I) && !Operand) {
1176 } else if (const CallInst *CI = dyn_cast<CallInst>(&I)) {
1177 // Print the calling convention being used.
1178 switch (CI->getCallingConv()) {
1179 case CallingConv::C: break; // default
1180 case CallingConv::Fast: Out << " fastcc"; break;
1181 case CallingConv::Cold: Out << " coldcc"; break;
1182 case CallingConv::X86_StdCall: Out << "x86_stdcallcc "; break;
1183 case CallingConv::X86_FastCall: Out << "x86_fastcallcc "; break;
1184 default: Out << " cc" << CI->getCallingConv(); break;
1187 const PointerType *PTy = cast<PointerType>(Operand->getType());
1188 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
1189 const Type *RetTy = FTy->getReturnType();
1190 const ParamAttrsList *PAL = FTy->getParamAttrs();
1192 // If possible, print out the short form of the call instruction. We can
1193 // only do this if the first argument is a pointer to a nonvararg function,
1194 // and if the return type is not a pointer to a function.
1196 if (!FTy->isVarArg() &&
1197 (!isa<PointerType>(RetTy) ||
1198 !isa<FunctionType>(cast<PointerType>(RetTy)->getElementType()))) {
1199 Out << ' '; printType(RetTy);
1200 writeOperand(Operand, false);
1202 writeOperand(Operand, true);
1205 for (unsigned op = 1, Eop = I.getNumOperands(); op < Eop; ++op) {
1208 writeOperand(I.getOperand(op), true);
1209 if (PAL && PAL->getParamAttrs(op) != ParamAttr::None)
1210 Out << " " << PAL->getParamAttrsTextByIndex(op);
1213 if (PAL && PAL->getParamAttrs(0) != ParamAttr::None)
1214 Out << ' ' << PAL->getParamAttrsTextByIndex(0);
1215 } else if (const InvokeInst *II = dyn_cast<InvokeInst>(&I)) {
1216 const PointerType *PTy = cast<PointerType>(Operand->getType());
1217 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
1218 const Type *RetTy = FTy->getReturnType();
1219 const ParamAttrsList *PAL = FTy->getParamAttrs();
1221 // Print the calling convention being used.
1222 switch (II->getCallingConv()) {
1223 case CallingConv::C: break; // default
1224 case CallingConv::Fast: Out << " fastcc"; break;
1225 case CallingConv::Cold: Out << " coldcc"; break;
1226 case CallingConv::X86_StdCall: Out << "x86_stdcallcc "; break;
1227 case CallingConv::X86_FastCall: Out << "x86_fastcallcc "; break;
1228 default: Out << " cc" << II->getCallingConv(); break;
1231 // If possible, print out the short form of the invoke instruction. We can
1232 // only do this if the first argument is a pointer to a nonvararg function,
1233 // and if the return type is not a pointer to a function.
1235 if (!FTy->isVarArg() &&
1236 (!isa<PointerType>(RetTy) ||
1237 !isa<FunctionType>(cast<PointerType>(RetTy)->getElementType()))) {
1238 Out << ' '; printType(RetTy);
1239 writeOperand(Operand, false);
1241 writeOperand(Operand, true);
1245 for (unsigned op = 3, Eop = I.getNumOperands(); op < Eop; ++op) {
1248 writeOperand(I.getOperand(op), true);
1249 if (PAL && PAL->getParamAttrs(op-2) != ParamAttr::None)
1250 Out << " " << PAL->getParamAttrsTextByIndex(op-2);
1254 if (PAL && PAL->getParamAttrs(0) != ParamAttr::None)
1255 Out << " " << PAL->getParamAttrsTextByIndex(0);
1256 Out << "\n\t\t\tto";
1257 writeOperand(II->getNormalDest(), true);
1259 writeOperand(II->getUnwindDest(), true);
1261 } else if (const AllocationInst *AI = dyn_cast<AllocationInst>(&I)) {
1263 printType(AI->getType()->getElementType());
1264 if (AI->isArrayAllocation()) {
1266 writeOperand(AI->getArraySize(), true);
1268 if (AI->getAlignment()) {
1269 Out << ", align " << AI->getAlignment();
1271 } else if (isa<CastInst>(I)) {
1272 if (Operand) writeOperand(Operand, true); // Work with broken code
1274 printType(I.getType());
1275 } else if (isa<VAArgInst>(I)) {
1276 if (Operand) writeOperand(Operand, true); // Work with broken code
1278 printType(I.getType());
1279 } else if (Operand) { // Print the normal way...
1281 // PrintAllTypes - Instructions who have operands of all the same type
1282 // omit the type from all but the first operand. If the instruction has
1283 // different type operands (for example br), then they are all printed.
1284 bool PrintAllTypes = false;
1285 const Type *TheType = Operand->getType();
1287 // Select, Store and ShuffleVector always print all types.
1288 if (isa<SelectInst>(I) || isa<StoreInst>(I) || isa<ShuffleVectorInst>(I)) {
1289 PrintAllTypes = true;
1291 for (unsigned i = 1, E = I.getNumOperands(); i != E; ++i) {
1292 Operand = I.getOperand(i);
1293 if (Operand->getType() != TheType) {
1294 PrintAllTypes = true; // We have differing types! Print them all!
1300 if (!PrintAllTypes) {
1305 for (unsigned i = 0, E = I.getNumOperands(); i != E; ++i) {
1307 writeOperand(I.getOperand(i), PrintAllTypes);
1311 // Print post operand alignment for load/store
1312 if (isa<LoadInst>(I) && cast<LoadInst>(I).getAlignment()) {
1313 Out << ", align " << cast<LoadInst>(I).getAlignment();
1314 } else if (isa<StoreInst>(I) && cast<StoreInst>(I).getAlignment()) {
1315 Out << ", align " << cast<StoreInst>(I).getAlignment();
1318 printInfoComment(I);
1323 //===----------------------------------------------------------------------===//
1324 // External Interface declarations
1325 //===----------------------------------------------------------------------===//
1327 void Module::print(std::ostream &o, AssemblyAnnotationWriter *AAW) const {
1328 SlotMachine SlotTable(this);
1329 AssemblyWriter W(o, SlotTable, this, AAW);
1333 void GlobalVariable::print(std::ostream &o) const {
1334 SlotMachine SlotTable(getParent());
1335 AssemblyWriter W(o, SlotTable, getParent(), 0);
1339 void Function::print(std::ostream &o, AssemblyAnnotationWriter *AAW) const {
1340 SlotMachine SlotTable(getParent());
1341 AssemblyWriter W(o, SlotTable, getParent(), AAW);
1346 void InlineAsm::print(std::ostream &o, AssemblyAnnotationWriter *AAW) const {
1347 WriteAsOperand(o, this, true, 0);
1350 void BasicBlock::print(std::ostream &o, AssemblyAnnotationWriter *AAW) const {
1351 SlotMachine SlotTable(getParent());
1352 AssemblyWriter W(o, SlotTable,
1353 getParent() ? getParent()->getParent() : 0, AAW);
1357 void Instruction::print(std::ostream &o, AssemblyAnnotationWriter *AAW) const {
1358 const Function *F = getParent() ? getParent()->getParent() : 0;
1359 SlotMachine SlotTable(F);
1360 AssemblyWriter W(o, SlotTable, F ? F->getParent() : 0, AAW);
1365 void Constant::print(std::ostream &o) const {
1366 if (this == 0) { o << "<null> constant value\n"; return; }
1368 o << ' ' << getType()->getDescription() << ' ';
1370 std::map<const Type *, std::string> TypeTable;
1371 WriteConstantInt(o, this, TypeTable, 0);
1374 void Type::print(std::ostream &o) const {
1378 o << getDescription();
1381 void Argument::print(std::ostream &o) const {
1382 WriteAsOperand(o, this, true, getParent() ? getParent()->getParent() : 0);
1385 // Value::dump - allow easy printing of Values from the debugger.
1386 // Located here because so much of the needed functionality is here.
1387 void Value::dump() const { print(*cerr.stream()); cerr << '\n'; }
1389 // Type::dump - allow easy printing of Values from the debugger.
1390 // Located here because so much of the needed functionality is here.
1391 void Type::dump() const { print(*cerr.stream()); cerr << '\n'; }
1393 //===----------------------------------------------------------------------===//
1394 // SlotMachine Implementation
1395 //===----------------------------------------------------------------------===//
1398 #define SC_DEBUG(X) cerr << X
1403 // Module level constructor. Causes the contents of the Module (sans functions)
1404 // to be added to the slot table.
1405 SlotMachine::SlotMachine(const Module *M)
1406 : TheModule(M) ///< Saved for lazy initialization.
1408 , FunctionProcessed(false)
1409 , mMap(), mNext(0), fMap(), fNext(0)
1413 // Function level constructor. Causes the contents of the Module and the one
1414 // function provided to be added to the slot table.
1415 SlotMachine::SlotMachine(const Function *F)
1416 : TheModule(F ? F->getParent() : 0) ///< Saved for lazy initialization
1417 , TheFunction(F) ///< Saved for lazy initialization
1418 , FunctionProcessed(false)
1419 , mMap(), mNext(0), fMap(), fNext(0)
1423 inline void SlotMachine::initialize() {
1426 TheModule = 0; ///< Prevent re-processing next time we're called.
1428 if (TheFunction && !FunctionProcessed)
1432 // Iterate through all the global variables, functions, and global
1433 // variable initializers and create slots for them.
1434 void SlotMachine::processModule() {
1435 SC_DEBUG("begin processModule!\n");
1437 // Add all of the unnamed global variables to the value table.
1438 for (Module::const_global_iterator I = TheModule->global_begin(),
1439 E = TheModule->global_end(); I != E; ++I)
1441 CreateModuleSlot(I);
1443 // Add all the unnamed functions to the table.
1444 for (Module::const_iterator I = TheModule->begin(), E = TheModule->end();
1447 CreateModuleSlot(I);
1449 SC_DEBUG("end processModule!\n");
1453 // Process the arguments, basic blocks, and instructions of a function.
1454 void SlotMachine::processFunction() {
1455 SC_DEBUG("begin processFunction!\n");
1458 // Add all the function arguments with no names.
1459 for(Function::const_arg_iterator AI = TheFunction->arg_begin(),
1460 AE = TheFunction->arg_end(); AI != AE; ++AI)
1462 CreateFunctionSlot(AI);
1464 SC_DEBUG("Inserting Instructions:\n");
1466 // Add all of the basic blocks and instructions with no names.
1467 for (Function::const_iterator BB = TheFunction->begin(),
1468 E = TheFunction->end(); BB != E; ++BB) {
1470 CreateFunctionSlot(BB);
1471 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I != E; ++I)
1472 if (I->getType() != Type::VoidTy && !I->hasName())
1473 CreateFunctionSlot(I);
1476 FunctionProcessed = true;
1478 SC_DEBUG("end processFunction!\n");
1481 /// Clean up after incorporating a function. This is the only way to get out of
1482 /// the function incorporation state that affects get*Slot/Create*Slot. Function
1483 /// incorporation state is indicated by TheFunction != 0.
1484 void SlotMachine::purgeFunction() {
1485 SC_DEBUG("begin purgeFunction!\n");
1486 fMap.clear(); // Simply discard the function level map
1488 FunctionProcessed = false;
1489 SC_DEBUG("end purgeFunction!\n");
1492 /// getGlobalSlot - Get the slot number of a global value.
1493 int SlotMachine::getGlobalSlot(const GlobalValue *V) {
1494 // Check for uninitialized state and do lazy initialization.
1497 // Find the type plane in the module map
1498 ValueMap::const_iterator MI = mMap.find(V);
1499 if (MI == mMap.end()) return -1;
1505 /// getLocalSlot - Get the slot number for a value that is local to a function.
1506 int SlotMachine::getLocalSlot(const Value *V) {
1507 assert(!isa<Constant>(V) && "Can't get a constant or global slot with this!");
1509 // Check for uninitialized state and do lazy initialization.
1512 ValueMap::const_iterator FI = fMap.find(V);
1513 if (FI == fMap.end()) return -1;
1519 /// CreateModuleSlot - Insert the specified GlobalValue* into the slot table.
1520 void SlotMachine::CreateModuleSlot(const GlobalValue *V) {
1521 assert(V && "Can't insert a null Value into SlotMachine!");
1522 assert(V->getType() != Type::VoidTy && "Doesn't need a slot!");
1523 assert(!V->hasName() && "Doesn't need a slot!");
1525 unsigned DestSlot = mNext++;
1528 SC_DEBUG(" Inserting value [" << V->getType() << "] = " << V << " slot=" <<
1530 // G = Global, F = Function, o = other
1531 SC_DEBUG((isa<GlobalVariable>(V) ? 'G' : 'F') << "]\n");
1535 /// CreateSlot - Create a new slot for the specified value if it has no name.
1536 void SlotMachine::CreateFunctionSlot(const Value *V) {
1537 const Type *VTy = V->getType();
1538 assert(VTy != Type::VoidTy && !V->hasName() && "Doesn't need a slot!");
1540 unsigned DestSlot = fNext++;
1543 // G = Global, F = Function, o = other
1544 SC_DEBUG(" Inserting value [" << VTy << "] = " << V << " slot=" <<
1545 DestSlot << " [o]\n");