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"
41 // Make virtual table appear in this compilation unit.
42 AssemblyAnnotationWriter::~AssemblyAnnotationWriter() {}
44 /// This class provides computation of slot numbers for LLVM Assembly writing.
45 /// @brief LLVM Assembly Writing Slot Computation.
52 /// @brief A mapping of Values to slot numbers
53 typedef std::map<const Value*,unsigned> ValueMap;
56 /// @name Constructors
59 /// @brief Construct from a module
60 SlotMachine(const Module *M);
62 /// @brief Construct from a function, starting out in incorp state.
63 SlotMachine(const Function *F);
69 /// Return the slot number of the specified value in it's type
70 /// plane. If something is not in the SlotMachine, return -1.
71 int getLocalSlot(const Value *V);
72 int getGlobalSlot(const GlobalValue *V);
78 /// If you'd like to deal with a function instead of just a module, use
79 /// this method to get its data into the SlotMachine.
80 void incorporateFunction(const Function *F) {
82 FunctionProcessed = false;
85 /// After calling incorporateFunction, use this method to remove the
86 /// most recently incorporated function from the SlotMachine. This
87 /// will reset the state of the machine back to just the module contents.
91 /// @name Implementation Details
94 /// This function does the actual initialization.
95 inline void initialize();
97 /// CreateModuleSlot - Insert the specified GlobalValue* into the slot table.
98 void CreateModuleSlot(const GlobalValue *V);
100 /// CreateFunctionSlot - Insert the specified Value* into the slot table.
101 void CreateFunctionSlot(const Value *V);
103 /// Add all of the module level global variables (and their initializers)
104 /// and function declarations, but not the contents of those functions.
105 void processModule();
107 /// Add all of the functions arguments, basic blocks, and instructions
108 void processFunction();
110 SlotMachine(const SlotMachine &); // DO NOT IMPLEMENT
111 void operator=(const SlotMachine &); // DO NOT IMPLEMENT
118 /// @brief The module for which we are holding slot numbers
119 const Module* TheModule;
121 /// @brief The function for which we are holding slot numbers
122 const Function* TheFunction;
123 bool FunctionProcessed;
125 /// @brief The TypePlanes map for the module level data
129 /// @brief The TypePlanes map for the function level data
137 } // end namespace llvm
139 char PrintModulePass::ID = 0;
140 static RegisterPass<PrintModulePass>
141 X("printm", "Print module to stderr");
142 char PrintFunctionPass::ID = 0;
143 static RegisterPass<PrintFunctionPass>
144 Y("print","Print function to stderr");
146 static void WriteAsOperandInternal(std::ostream &Out, const Value *V,
147 std::map<const Type *, std::string> &TypeTable,
148 SlotMachine *Machine);
150 static const Module *getModuleFromVal(const Value *V) {
151 if (const Argument *MA = dyn_cast<Argument>(V))
152 return MA->getParent() ? MA->getParent()->getParent() : 0;
153 else if (const BasicBlock *BB = dyn_cast<BasicBlock>(V))
154 return BB->getParent() ? BB->getParent()->getParent() : 0;
155 else if (const Instruction *I = dyn_cast<Instruction>(V)) {
156 const Function *M = I->getParent() ? I->getParent()->getParent() : 0;
157 return M ? M->getParent() : 0;
158 } else if (const GlobalValue *GV = dyn_cast<GlobalValue>(V))
159 return GV->getParent();
163 static SlotMachine *createSlotMachine(const Value *V) {
164 if (const Argument *FA = dyn_cast<Argument>(V)) {
165 return new SlotMachine(FA->getParent());
166 } else if (const Instruction *I = dyn_cast<Instruction>(V)) {
167 return new SlotMachine(I->getParent()->getParent());
168 } else if (const BasicBlock *BB = dyn_cast<BasicBlock>(V)) {
169 return new SlotMachine(BB->getParent());
170 } else if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(V)){
171 return new SlotMachine(GV->getParent());
172 } else if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(V)){
173 return new SlotMachine(GA->getParent());
174 } else if (const Function *Func = dyn_cast<Function>(V)) {
175 return new SlotMachine(Func);
180 /// NameNeedsQuotes - Return true if the specified llvm name should be wrapped
182 static std::string QuoteNameIfNeeded(const std::string &Name) {
184 bool needsQuotes = Name[0] >= '0' && Name[0] <= '9';
185 // Scan the name to see if it needs quotes and to replace funky chars with
186 // their octal equivalent.
187 for (unsigned i = 0, e = Name.size(); i != e; ++i) {
189 assert(C != '"' && "Illegal character in LLVM value name!");
190 if (isalnum(C) || C == '-' || C == '.' || C == '_')
192 else if (isprint(C)) {
198 char hex1 = C & 0x0F;
200 result += hex1 + '0';
202 result += hex1 - 10 + 'A';
203 char hex2 = (C >> 4) & 0x0F;
205 result += hex2 + '0';
207 result += hex2 - 10 + 'A';
211 result.insert(0,"\"");
223 /// getLLVMName - Turn the specified string into an 'LLVM name', which is either
224 /// prefixed with % (if the string only contains simple characters) or is
225 /// surrounded with ""'s (if it has special chars in it).
226 static std::string getLLVMName(const std::string &Name, PrefixType Prefix) {
227 assert(!Name.empty() && "Cannot get empty name!");
229 default: assert(0 && "Bad prefix!");
230 case GlobalPrefix: return '@' + QuoteNameIfNeeded(Name);
231 case LabelPrefix: return QuoteNameIfNeeded(Name);
232 case LocalPrefix: return '%' + QuoteNameIfNeeded(Name);
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 TypeSymbolTable &ST = M->getTypeSymbolTable();
244 TypeSymbolTable::const_iterator TI = ST.begin();
245 for (; TI != ST.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 !cast<PointerType>(Ty)->getElementType()->isInteger() ||
253 isa<OpaqueType>(cast<PointerType>(Ty)->getElementType()))
254 TypeNames.insert(std::make_pair(Ty, getLLVMName(TI->first, LocalPrefix)));
260 static void calcTypeName(const Type *Ty,
261 std::vector<const Type *> &TypeStack,
262 std::map<const Type *, std::string> &TypeNames,
263 std::string & Result){
264 if (Ty->isInteger() || (Ty->isPrimitiveType() && !isa<OpaqueType>(Ty))) {
265 Result += Ty->getDescription(); // Base case
269 // Check to see if the type is named.
270 std::map<const Type *, std::string>::iterator I = TypeNames.find(Ty);
271 if (I != TypeNames.end()) {
276 if (isa<OpaqueType>(Ty)) {
281 // Check to see if the Type is already on the stack...
282 unsigned Slot = 0, CurSize = TypeStack.size();
283 while (Slot < CurSize && TypeStack[Slot] != Ty) ++Slot; // Scan for type
285 // This is another base case for the recursion. In this case, we know
286 // that we have looped back to a type that we have previously visited.
287 // Generate the appropriate upreference to handle this.
288 if (Slot < CurSize) {
289 Result += "\\" + utostr(CurSize-Slot); // Here's the upreference
293 TypeStack.push_back(Ty); // Recursive case: Add us to the stack..
295 switch (Ty->getTypeID()) {
296 case Type::IntegerTyID: {
297 unsigned BitWidth = cast<IntegerType>(Ty)->getBitWidth();
298 Result += "i" + utostr(BitWidth);
301 case Type::FunctionTyID: {
302 const FunctionType *FTy = cast<FunctionType>(Ty);
303 calcTypeName(FTy->getReturnType(), TypeStack, TypeNames, Result);
306 const ParamAttrsList *Attrs = FTy->getParamAttrs();
307 for (FunctionType::param_iterator I = FTy->param_begin(),
308 E = FTy->param_end(); I != E; ++I) {
309 if (I != FTy->param_begin())
311 calcTypeName(*I, TypeStack, TypeNames, Result);
312 if (Attrs && Attrs->getParamAttrs(Idx) != ParamAttr::None) {
314 Result += Attrs->getParamAttrsTextByIndex(Idx);
318 if (FTy->isVarArg()) {
319 if (FTy->getNumParams()) Result += ", ";
323 if (Attrs && Attrs->getParamAttrs(0) != ParamAttr::None) {
325 Result += Attrs->getParamAttrsTextByIndex(0);
329 case Type::StructTyID: {
330 const StructType *STy = cast<StructType>(Ty);
334 for (StructType::element_iterator I = STy->element_begin(),
335 E = STy->element_end(); I != E; ++I) {
336 if (I != STy->element_begin())
338 calcTypeName(*I, TypeStack, TypeNames, Result);
345 case Type::PointerTyID:
346 calcTypeName(cast<PointerType>(Ty)->getElementType(),
347 TypeStack, TypeNames, Result);
350 case Type::ArrayTyID: {
351 const ArrayType *ATy = cast<ArrayType>(Ty);
352 Result += "[" + utostr(ATy->getNumElements()) + " x ";
353 calcTypeName(ATy->getElementType(), TypeStack, TypeNames, Result);
357 case Type::VectorTyID: {
358 const VectorType *PTy = cast<VectorType>(Ty);
359 Result += "<" + utostr(PTy->getNumElements()) + " x ";
360 calcTypeName(PTy->getElementType(), TypeStack, TypeNames, Result);
364 case Type::OpaqueTyID:
368 Result += "<unrecognized-type>";
372 TypeStack.pop_back(); // Remove self from stack...
376 /// printTypeInt - The internal guts of printing out a type that has a
377 /// potentially named portion.
379 static std::ostream &printTypeInt(std::ostream &Out, const Type *Ty,
380 std::map<const Type *, std::string> &TypeNames) {
381 // Primitive types always print out their description, regardless of whether
382 // they have been named or not.
384 if (Ty->isInteger() || (Ty->isPrimitiveType() && !isa<OpaqueType>(Ty)))
385 return Out << Ty->getDescription();
387 // Check to see if the type is named.
388 std::map<const Type *, std::string>::iterator I = TypeNames.find(Ty);
389 if (I != TypeNames.end()) return Out << I->second;
391 // Otherwise we have a type that has not been named but is a derived type.
392 // Carefully recurse the type hierarchy to print out any contained symbolic
395 std::vector<const Type *> TypeStack;
396 std::string TypeName;
397 calcTypeName(Ty, TypeStack, TypeNames, TypeName);
398 TypeNames.insert(std::make_pair(Ty, TypeName));//Cache type name for later use
399 return (Out << TypeName);
403 /// WriteTypeSymbolic - This attempts to write the specified type as a symbolic
404 /// type, iff there is an entry in the modules symbol table for the specified
405 /// type or one of it's component types. This is slower than a simple x << Type
407 std::ostream &llvm::WriteTypeSymbolic(std::ostream &Out, const Type *Ty,
411 // If they want us to print out a type, but there is no context, we can't
412 // print it symbolically.
414 return Out << Ty->getDescription();
416 std::map<const Type *, std::string> TypeNames;
417 fillTypeNameTable(M, TypeNames);
418 return printTypeInt(Out, Ty, TypeNames);
421 // PrintEscapedString - Print each character of the specified string, escaping
422 // it if it is not printable or if it is an escape char.
423 static void PrintEscapedString(const std::string &Str, std::ostream &Out) {
424 for (unsigned i = 0, e = Str.size(); i != e; ++i) {
425 unsigned char C = Str[i];
426 if (isprint(C) && C != '"' && C != '\\') {
430 << (char) ((C/16 < 10) ? ( C/16 +'0') : ( C/16 -10+'A'))
431 << (char)(((C&15) < 10) ? ((C&15)+'0') : ((C&15)-10+'A'));
436 static const char *getPredicateText(unsigned predicate) {
437 const char * pred = "unknown";
439 case FCmpInst::FCMP_FALSE: pred = "false"; break;
440 case FCmpInst::FCMP_OEQ: pred = "oeq"; break;
441 case FCmpInst::FCMP_OGT: pred = "ogt"; break;
442 case FCmpInst::FCMP_OGE: pred = "oge"; break;
443 case FCmpInst::FCMP_OLT: pred = "olt"; break;
444 case FCmpInst::FCMP_OLE: pred = "ole"; break;
445 case FCmpInst::FCMP_ONE: pred = "one"; break;
446 case FCmpInst::FCMP_ORD: pred = "ord"; break;
447 case FCmpInst::FCMP_UNO: pred = "uno"; break;
448 case FCmpInst::FCMP_UEQ: pred = "ueq"; break;
449 case FCmpInst::FCMP_UGT: pred = "ugt"; break;
450 case FCmpInst::FCMP_UGE: pred = "uge"; break;
451 case FCmpInst::FCMP_ULT: pred = "ult"; break;
452 case FCmpInst::FCMP_ULE: pred = "ule"; break;
453 case FCmpInst::FCMP_UNE: pred = "une"; break;
454 case FCmpInst::FCMP_TRUE: pred = "true"; break;
455 case ICmpInst::ICMP_EQ: pred = "eq"; break;
456 case ICmpInst::ICMP_NE: pred = "ne"; break;
457 case ICmpInst::ICMP_SGT: pred = "sgt"; break;
458 case ICmpInst::ICMP_SGE: pred = "sge"; break;
459 case ICmpInst::ICMP_SLT: pred = "slt"; break;
460 case ICmpInst::ICMP_SLE: pred = "sle"; break;
461 case ICmpInst::ICMP_UGT: pred = "ugt"; break;
462 case ICmpInst::ICMP_UGE: pred = "uge"; break;
463 case ICmpInst::ICMP_ULT: pred = "ult"; break;
464 case ICmpInst::ICMP_ULE: pred = "ule"; break;
469 /// @brief Internal constant writer.
470 static void WriteConstantInt(std::ostream &Out, const Constant *CV,
471 std::map<const Type *, std::string> &TypeTable,
472 SlotMachine *Machine) {
473 const int IndentSize = 4;
474 static std::string Indent = "\n";
475 if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV)) {
476 if (CI->getType() == Type::Int1Ty)
477 Out << (CI->getZExtValue() ? "true" : "false");
479 Out << CI->getValue().toStringSigned(10);
480 } else if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CV)) {
481 // We would like to output the FP constant value in exponential notation,
482 // but we cannot do this if doing so will lose precision. Check here to
483 // make sure that we only output it in exponential format if we can parse
484 // the value back and get the same value.
486 std::string StrVal = ftostr(CFP->getValue());
488 // Check to make sure that the stringized number is not some string like
489 // "Inf" or NaN, that atof will accept, but the lexer will not. Check that
490 // the string matches the "[-+]?[0-9]" regex.
492 if ((StrVal[0] >= '0' && StrVal[0] <= '9') ||
493 ((StrVal[0] == '-' || StrVal[0] == '+') &&
494 (StrVal[1] >= '0' && StrVal[1] <= '9')))
495 // Reparse stringized version!
496 if (atof(StrVal.c_str()) == CFP->getValue()) {
501 // Otherwise we could not reparse it to exactly the same value, so we must
502 // output the string in hexadecimal format!
503 assert(sizeof(double) == sizeof(uint64_t) &&
504 "assuming that double is 64 bits!");
505 Out << "0x" << utohexstr(DoubleToBits(CFP->getValue()));
507 } else if (isa<ConstantAggregateZero>(CV)) {
508 Out << "zeroinitializer";
509 } else if (const ConstantArray *CA = dyn_cast<ConstantArray>(CV)) {
510 // As a special case, print the array as a string if it is an array of
511 // ubytes or an array of sbytes with positive values.
513 const Type *ETy = CA->getType()->getElementType();
514 if (CA->isString()) {
516 PrintEscapedString(CA->getAsString(), Out);
519 } else { // Cannot output in string format...
521 if (CA->getNumOperands()) {
523 printTypeInt(Out, ETy, TypeTable);
524 WriteAsOperandInternal(Out, CA->getOperand(0),
526 for (unsigned i = 1, e = CA->getNumOperands(); i != e; ++i) {
528 printTypeInt(Out, ETy, TypeTable);
529 WriteAsOperandInternal(Out, CA->getOperand(i), TypeTable, Machine);
534 } else if (const ConstantStruct *CS = dyn_cast<ConstantStruct>(CV)) {
535 if (CS->getType()->isPacked())
538 unsigned N = CS->getNumOperands();
541 Indent += std::string(IndentSize, ' ');
546 printTypeInt(Out, CS->getOperand(0)->getType(), TypeTable);
548 WriteAsOperandInternal(Out, CS->getOperand(0), TypeTable, Machine);
550 for (unsigned i = 1; i < N; i++) {
552 if (N > 2) Out << Indent;
553 printTypeInt(Out, CS->getOperand(i)->getType(), TypeTable);
555 WriteAsOperandInternal(Out, CS->getOperand(i), TypeTable, Machine);
557 if (N > 2) Indent.resize(Indent.size() - IndentSize);
561 if (CS->getType()->isPacked())
563 } else if (const ConstantVector *CP = dyn_cast<ConstantVector>(CV)) {
564 const Type *ETy = CP->getType()->getElementType();
565 assert(CP->getNumOperands() > 0 &&
566 "Number of operands for a PackedConst must be > 0");
569 printTypeInt(Out, ETy, TypeTable);
570 WriteAsOperandInternal(Out, CP->getOperand(0), TypeTable, Machine);
571 for (unsigned i = 1, e = CP->getNumOperands(); i != e; ++i) {
573 printTypeInt(Out, ETy, TypeTable);
574 WriteAsOperandInternal(Out, CP->getOperand(i), TypeTable, Machine);
577 } else if (isa<ConstantPointerNull>(CV)) {
580 } else if (isa<UndefValue>(CV)) {
583 } else if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV)) {
584 Out << CE->getOpcodeName();
586 Out << " " << getPredicateText(CE->getPredicate());
589 for (User::const_op_iterator OI=CE->op_begin(); OI != CE->op_end(); ++OI) {
590 printTypeInt(Out, (*OI)->getType(), TypeTable);
591 WriteAsOperandInternal(Out, *OI, TypeTable, Machine);
592 if (OI+1 != CE->op_end())
598 printTypeInt(Out, CE->getType(), TypeTable);
604 Out << "<placeholder or erroneous Constant>";
609 /// WriteAsOperand - Write the name of the specified value out to the specified
610 /// ostream. This can be useful when you just want to print int %reg126, not
611 /// the whole instruction that generated it.
613 static void WriteAsOperandInternal(std::ostream &Out, const Value *V,
614 std::map<const Type*, std::string> &TypeTable,
615 SlotMachine *Machine) {
618 Out << getLLVMName(V->getName(),
619 isa<GlobalValue>(V) ? GlobalPrefix : LocalPrefix);
621 const Constant *CV = dyn_cast<Constant>(V);
622 if (CV && !isa<GlobalValue>(CV)) {
623 WriteConstantInt(Out, CV, TypeTable, Machine);
624 } else if (const InlineAsm *IA = dyn_cast<InlineAsm>(V)) {
626 if (IA->hasSideEffects())
627 Out << "sideeffect ";
629 PrintEscapedString(IA->getAsmString(), Out);
631 PrintEscapedString(IA->getConstraintString(), Out);
637 if (const GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
638 Slot = Machine->getGlobalSlot(GV);
641 Slot = Machine->getLocalSlot(V);
644 Machine = createSlotMachine(V);
646 if (const GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
647 Slot = Machine->getGlobalSlot(GV);
650 Slot = Machine->getLocalSlot(V);
658 Out << Prefix << Slot;
665 /// WriteAsOperand - Write the name of the specified value out to the specified
666 /// ostream. This can be useful when you just want to print int %reg126, not
667 /// the whole instruction that generated it.
669 std::ostream &llvm::WriteAsOperand(std::ostream &Out, const Value *V,
670 bool PrintType, const Module *Context) {
671 std::map<const Type *, std::string> TypeNames;
672 if (Context == 0) Context = getModuleFromVal(V);
675 fillTypeNameTable(Context, TypeNames);
678 printTypeInt(Out, V->getType(), TypeNames);
680 WriteAsOperandInternal(Out, V, TypeNames, 0);
687 class AssemblyWriter {
689 SlotMachine &Machine;
690 const Module *TheModule;
691 std::map<const Type *, std::string> TypeNames;
692 AssemblyAnnotationWriter *AnnotationWriter;
694 inline AssemblyWriter(std::ostream &o, SlotMachine &Mac, const Module *M,
695 AssemblyAnnotationWriter *AAW)
696 : Out(o), Machine(Mac), TheModule(M), AnnotationWriter(AAW) {
698 // If the module has a symbol table, take all global types and stuff their
699 // names into the TypeNames map.
701 fillTypeNameTable(M, TypeNames);
704 inline void write(const Module *M) { printModule(M); }
705 inline void write(const GlobalVariable *G) { printGlobal(G); }
706 inline void write(const GlobalAlias *G) { printAlias(G); }
707 inline void write(const Function *F) { printFunction(F); }
708 inline void write(const BasicBlock *BB) { printBasicBlock(BB); }
709 inline void write(const Instruction *I) { printInstruction(*I); }
710 inline void write(const Type *Ty) { printType(Ty); }
712 void writeOperand(const Value *Op, bool PrintType);
714 const Module* getModule() { return TheModule; }
717 void printModule(const Module *M);
718 void printTypeSymbolTable(const TypeSymbolTable &ST);
719 void printGlobal(const GlobalVariable *GV);
720 void printAlias(const GlobalAlias *GV);
721 void printFunction(const Function *F);
722 void printArgument(const Argument *FA, uint16_t ParamAttrs);
723 void printBasicBlock(const BasicBlock *BB);
724 void printInstruction(const Instruction &I);
726 // printType - Go to extreme measures to attempt to print out a short,
727 // symbolic version of a type name.
729 std::ostream &printType(const Type *Ty) {
730 return printTypeInt(Out, Ty, TypeNames);
733 // printTypeAtLeastOneLevel - Print out one level of the possibly complex type
734 // without considering any symbolic types that we may have equal to it.
736 std::ostream &printTypeAtLeastOneLevel(const Type *Ty);
738 // printInfoComment - Print a little comment after the instruction indicating
739 // which slot it occupies.
740 void printInfoComment(const Value &V);
742 } // end of llvm namespace
744 /// printTypeAtLeastOneLevel - Print out one level of the possibly complex type
745 /// without considering any symbolic types that we may have equal to it.
747 std::ostream &AssemblyWriter::printTypeAtLeastOneLevel(const Type *Ty) {
748 if (const IntegerType *ITy = dyn_cast<IntegerType>(Ty))
749 Out << "i" << utostr(ITy->getBitWidth());
750 else if (const FunctionType *FTy = dyn_cast<FunctionType>(Ty)) {
751 printType(FTy->getReturnType());
754 const ParamAttrsList *Attrs = FTy->getParamAttrs();
755 for (FunctionType::param_iterator I = FTy->param_begin(),
756 E = FTy->param_end(); I != E; ++I) {
757 if (I != FTy->param_begin())
760 if (Attrs && Attrs->getParamAttrs(Idx) != ParamAttr::None) {
761 Out << " " << Attrs->getParamAttrsTextByIndex(Idx);
765 if (FTy->isVarArg()) {
766 if (FTy->getNumParams()) Out << ", ";
770 if (Attrs && Attrs->getParamAttrs(0) != ParamAttr::None)
771 Out << ' ' << Attrs->getParamAttrsTextByIndex(0);
772 } else if (const StructType *STy = dyn_cast<StructType>(Ty)) {
776 for (StructType::element_iterator I = STy->element_begin(),
777 E = STy->element_end(); I != E; ++I) {
778 if (I != STy->element_begin())
785 } else if (const PointerType *PTy = dyn_cast<PointerType>(Ty)) {
786 printType(PTy->getElementType()) << '*';
787 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
788 Out << '[' << ATy->getNumElements() << " x ";
789 printType(ATy->getElementType()) << ']';
790 } else if (const VectorType *PTy = dyn_cast<VectorType>(Ty)) {
791 Out << '<' << PTy->getNumElements() << " x ";
792 printType(PTy->getElementType()) << '>';
794 else if (isa<OpaqueType>(Ty)) {
797 if (!Ty->isPrimitiveType())
798 Out << "<unknown derived type>";
805 void AssemblyWriter::writeOperand(const Value *Operand, bool PrintType) {
807 Out << "<null operand!>";
809 if (PrintType) { Out << ' '; printType(Operand->getType()); }
810 WriteAsOperandInternal(Out, Operand, TypeNames, &Machine);
815 void AssemblyWriter::printModule(const Module *M) {
816 if (!M->getModuleIdentifier().empty() &&
817 // Don't print the ID if it will start a new line (which would
818 // require a comment char before it).
819 M->getModuleIdentifier().find('\n') == std::string::npos)
820 Out << "; ModuleID = '" << M->getModuleIdentifier() << "'\n";
822 if (!M->getDataLayout().empty())
823 Out << "target datalayout = \"" << M->getDataLayout() << "\"\n";
824 if (!M->getTargetTriple().empty())
825 Out << "target triple = \"" << M->getTargetTriple() << "\"\n";
827 if (!M->getModuleInlineAsm().empty()) {
828 // Split the string into lines, to make it easier to read the .ll file.
829 std::string Asm = M->getModuleInlineAsm();
831 size_t NewLine = Asm.find_first_of('\n', CurPos);
832 while (NewLine != std::string::npos) {
833 // We found a newline, print the portion of the asm string from the
834 // last newline up to this newline.
835 Out << "module asm \"";
836 PrintEscapedString(std::string(Asm.begin()+CurPos, Asm.begin()+NewLine),
840 NewLine = Asm.find_first_of('\n', CurPos);
842 Out << "module asm \"";
843 PrintEscapedString(std::string(Asm.begin()+CurPos, Asm.end()), Out);
847 // Loop over the dependent libraries and emit them.
848 Module::lib_iterator LI = M->lib_begin();
849 Module::lib_iterator LE = M->lib_end();
851 Out << "deplibs = [ ";
853 Out << '"' << *LI << '"';
861 // Loop over the symbol table, emitting all named constants.
862 printTypeSymbolTable(M->getTypeSymbolTable());
864 for (Module::const_global_iterator I = M->global_begin(), E = M->global_end();
868 // Output all aliases.
869 if (!M->alias_empty()) Out << "\n";
870 for (Module::const_alias_iterator I = M->alias_begin(), E = M->alias_end();
874 // Output all of the functions.
875 for (Module::const_iterator I = M->begin(), E = M->end(); I != E; ++I)
879 void AssemblyWriter::printGlobal(const GlobalVariable *GV) {
880 if (GV->hasName()) Out << getLLVMName(GV->getName(), GlobalPrefix) << " = ";
882 if (!GV->hasInitializer())
883 switch (GV->getLinkage()) {
884 case GlobalValue::DLLImportLinkage: Out << "dllimport "; break;
885 case GlobalValue::ExternalWeakLinkage: Out << "extern_weak "; break;
886 default: Out << "external "; break;
888 switch (GV->getLinkage()) {
889 case GlobalValue::InternalLinkage: Out << "internal "; break;
890 case GlobalValue::LinkOnceLinkage: Out << "linkonce "; break;
891 case GlobalValue::WeakLinkage: Out << "weak "; break;
892 case GlobalValue::AppendingLinkage: Out << "appending "; break;
893 case GlobalValue::DLLImportLinkage: Out << "dllimport "; break;
894 case GlobalValue::DLLExportLinkage: Out << "dllexport "; break;
895 case GlobalValue::ExternalWeakLinkage: Out << "extern_weak "; break;
896 case GlobalValue::ExternalLinkage: break;
897 case GlobalValue::GhostLinkage:
898 cerr << "GhostLinkage not allowed in AsmWriter!\n";
901 switch (GV->getVisibility()) {
902 default: assert(0 && "Invalid visibility style!");
903 case GlobalValue::DefaultVisibility: break;
904 case GlobalValue::HiddenVisibility: Out << "hidden "; break;
905 case GlobalValue::ProtectedVisibility: Out << "protected "; break;
909 if (GV->isThreadLocal()) Out << "thread_local ";
910 Out << (GV->isConstant() ? "constant " : "global ");
911 printType(GV->getType()->getElementType());
913 if (GV->hasInitializer()) {
914 Constant* C = cast<Constant>(GV->getInitializer());
915 assert(C && "GlobalVar initializer isn't constant?");
916 writeOperand(GV->getInitializer(), false);
919 if (GV->hasSection())
920 Out << ", section \"" << GV->getSection() << '"';
921 if (GV->getAlignment())
922 Out << ", align " << GV->getAlignment();
924 printInfoComment(*GV);
928 void AssemblyWriter::printAlias(const GlobalAlias *GA) {
929 Out << getLLVMName(GA->getName(), GlobalPrefix) << " = ";
930 switch (GA->getVisibility()) {
931 default: assert(0 && "Invalid visibility style!");
932 case GlobalValue::DefaultVisibility: break;
933 case GlobalValue::HiddenVisibility: Out << "hidden "; break;
934 case GlobalValue::ProtectedVisibility: Out << "protected "; break;
939 switch (GA->getLinkage()) {
940 case GlobalValue::WeakLinkage: Out << "weak "; break;
941 case GlobalValue::InternalLinkage: Out << "internal "; break;
942 case GlobalValue::ExternalLinkage: break;
944 assert(0 && "Invalid alias linkage");
947 const Constant *Aliasee = GA->getAliasee();
949 if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(Aliasee)) {
950 printType(GV->getType());
951 Out << " " << getLLVMName(GV->getName(), GlobalPrefix);
952 } else if (const Function *F = dyn_cast<Function>(Aliasee)) {
953 printType(F->getFunctionType());
956 if (!F->getName().empty())
957 Out << getLLVMName(F->getName(), GlobalPrefix);
961 const ConstantExpr *CE = 0;
962 if ((CE = dyn_cast<ConstantExpr>(Aliasee)) &&
963 (CE->getOpcode() == Instruction::BitCast)) {
964 writeOperand(CE, false);
966 assert(0 && "Unsupported aliasee");
969 printInfoComment(*GA);
973 void AssemblyWriter::printTypeSymbolTable(const TypeSymbolTable &ST) {
975 for (TypeSymbolTable::const_iterator TI = ST.begin(), TE = ST.end();
977 Out << "\t" << getLLVMName(TI->first, LocalPrefix) << " = type ";
979 // Make sure we print out at least one level of the type structure, so
980 // that we do not get %FILE = type %FILE
982 printTypeAtLeastOneLevel(TI->second) << "\n";
986 /// printFunction - Print all aspects of a function.
988 void AssemblyWriter::printFunction(const Function *F) {
989 // Print out the return type and name...
992 if (AnnotationWriter) AnnotationWriter->emitFunctionAnnot(F, Out);
994 if (F->isDeclaration())
995 switch (F->getLinkage()) {
996 case GlobalValue::DLLImportLinkage: Out << "declare dllimport "; break;
997 case GlobalValue::ExternalWeakLinkage: Out << "declare extern_weak "; break;
998 default: Out << "declare ";
1002 switch (F->getLinkage()) {
1003 case GlobalValue::InternalLinkage: Out << "internal "; break;
1004 case GlobalValue::LinkOnceLinkage: Out << "linkonce "; break;
1005 case GlobalValue::WeakLinkage: Out << "weak "; break;
1006 case GlobalValue::AppendingLinkage: Out << "appending "; break;
1007 case GlobalValue::DLLImportLinkage: Out << "dllimport "; break;
1008 case GlobalValue::DLLExportLinkage: Out << "dllexport "; break;
1009 case GlobalValue::ExternalWeakLinkage: Out << "extern_weak "; break;
1010 case GlobalValue::ExternalLinkage: break;
1011 case GlobalValue::GhostLinkage:
1012 cerr << "GhostLinkage not allowed in AsmWriter!\n";
1015 switch (F->getVisibility()) {
1016 default: assert(0 && "Invalid visibility style!");
1017 case GlobalValue::DefaultVisibility: break;
1018 case GlobalValue::HiddenVisibility: Out << "hidden "; break;
1019 case GlobalValue::ProtectedVisibility: Out << "protected "; break;
1023 // Print the calling convention.
1024 switch (F->getCallingConv()) {
1025 case CallingConv::C: break; // default
1026 case CallingConv::Fast: Out << "fastcc "; break;
1027 case CallingConv::Cold: Out << "coldcc "; break;
1028 case CallingConv::X86_StdCall: Out << "x86_stdcallcc "; break;
1029 case CallingConv::X86_FastCall: Out << "x86_fastcallcc "; break;
1030 default: Out << "cc" << F->getCallingConv() << " "; break;
1033 const FunctionType *FT = F->getFunctionType();
1034 const ParamAttrsList *Attrs = FT->getParamAttrs();
1035 printType(F->getReturnType()) << ' ';
1036 if (!F->getName().empty())
1037 Out << getLLVMName(F->getName(), GlobalPrefix);
1041 Machine.incorporateFunction(F);
1043 // Loop over the arguments, printing them...
1046 if (!F->isDeclaration()) {
1047 // If this isn't a declaration, print the argument names as well.
1048 for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
1050 // Insert commas as we go... the first arg doesn't get a comma
1051 if (I != F->arg_begin()) Out << ", ";
1052 printArgument(I, (Attrs ? Attrs->getParamAttrs(Idx)
1053 : uint16_t(ParamAttr::None)));
1057 // Otherwise, print the types from the function type.
1058 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
1059 // Insert commas as we go... the first arg doesn't get a comma
1063 printType(FT->getParamType(i));
1065 unsigned ArgAttrs = ParamAttr::None;
1066 if (Attrs) ArgAttrs = Attrs->getParamAttrs(i+1);
1067 if (ArgAttrs != ParamAttr::None)
1068 Out << ' ' << ParamAttrsList::getParamAttrsText(ArgAttrs);
1072 // Finish printing arguments...
1073 if (FT->isVarArg()) {
1074 if (FT->getNumParams()) Out << ", ";
1075 Out << "..."; // Output varargs portion of signature!
1078 if (Attrs && Attrs->getParamAttrs(0) != ParamAttr::None)
1079 Out << ' ' << Attrs->getParamAttrsTextByIndex(0);
1080 if (F->hasSection())
1081 Out << " section \"" << F->getSection() << '"';
1082 if (F->getAlignment())
1083 Out << " align " << F->getAlignment();
1085 if (F->isDeclaration()) {
1090 // Output all of its basic blocks... for the function
1091 for (Function::const_iterator I = F->begin(), E = F->end(); I != E; ++I)
1097 Machine.purgeFunction();
1100 /// printArgument - This member is called for every argument that is passed into
1101 /// the function. Simply print it out
1103 void AssemblyWriter::printArgument(const Argument *Arg, uint16_t Attrs) {
1105 printType(Arg->getType());
1107 if (Attrs != ParamAttr::None)
1108 Out << ' ' << ParamAttrsList::getParamAttrsText(Attrs);
1110 // Output name, if available...
1112 Out << ' ' << getLLVMName(Arg->getName(), LocalPrefix);
1115 /// printBasicBlock - This member is called for each basic block in a method.
1117 void AssemblyWriter::printBasicBlock(const BasicBlock *BB) {
1118 if (BB->hasName()) { // Print out the label if it exists...
1119 Out << "\n" << getLLVMName(BB->getName(), LabelPrefix) << ':';
1120 } else if (!BB->use_empty()) { // Don't print block # of no uses...
1121 Out << "\n; <label>:";
1122 int Slot = Machine.getLocalSlot(BB);
1129 if (BB->getParent() == 0)
1130 Out << "\t\t; Error: Block without parent!";
1132 if (BB != &BB->getParent()->getEntryBlock()) { // Not the entry block?
1133 // Output predecessors for the block...
1135 pred_const_iterator PI = pred_begin(BB), PE = pred_end(BB);
1138 Out << " No predecessors!";
1141 writeOperand(*PI, false);
1142 for (++PI; PI != PE; ++PI) {
1144 writeOperand(*PI, false);
1152 if (AnnotationWriter) AnnotationWriter->emitBasicBlockStartAnnot(BB, Out);
1154 // Output all of the instructions in the basic block...
1155 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I != E; ++I)
1156 printInstruction(*I);
1158 if (AnnotationWriter) AnnotationWriter->emitBasicBlockEndAnnot(BB, Out);
1162 /// printInfoComment - Print a little comment after the instruction indicating
1163 /// which slot it occupies.
1165 void AssemblyWriter::printInfoComment(const Value &V) {
1166 if (V.getType() != Type::VoidTy) {
1168 printType(V.getType()) << '>';
1172 if (const GlobalValue *GV = dyn_cast<GlobalValue>(&V))
1173 SlotNum = Machine.getGlobalSlot(GV);
1175 SlotNum = Machine.getLocalSlot(&V);
1179 Out << ':' << SlotNum; // Print out the def slot taken.
1181 Out << " [#uses=" << V.getNumUses() << ']'; // Output # uses
1185 // This member is called for each Instruction in a function..
1186 void AssemblyWriter::printInstruction(const Instruction &I) {
1187 if (AnnotationWriter) AnnotationWriter->emitInstructionAnnot(&I, Out);
1191 // Print out name if it exists...
1193 Out << getLLVMName(I.getName(), LocalPrefix) << " = ";
1195 // If this is a volatile load or store, print out the volatile marker.
1196 if ((isa<LoadInst>(I) && cast<LoadInst>(I).isVolatile()) ||
1197 (isa<StoreInst>(I) && cast<StoreInst>(I).isVolatile())) {
1199 } else if (isa<CallInst>(I) && cast<CallInst>(I).isTailCall()) {
1200 // If this is a call, check if it's a tail call.
1204 // Print out the opcode...
1205 Out << I.getOpcodeName();
1207 // Print out the compare instruction predicates
1208 if (const FCmpInst *FCI = dyn_cast<FCmpInst>(&I)) {
1209 Out << " " << getPredicateText(FCI->getPredicate());
1210 } else if (const ICmpInst *ICI = dyn_cast<ICmpInst>(&I)) {
1211 Out << " " << getPredicateText(ICI->getPredicate());
1214 // Print out the type of the operands...
1215 const Value *Operand = I.getNumOperands() ? I.getOperand(0) : 0;
1217 // Special case conditional branches to swizzle the condition out to the front
1218 if (isa<BranchInst>(I) && I.getNumOperands() > 1) {
1219 writeOperand(I.getOperand(2), true);
1221 writeOperand(Operand, true);
1223 writeOperand(I.getOperand(1), true);
1225 } else if (isa<SwitchInst>(I)) {
1226 // Special case switch statement to get formatting nice and correct...
1227 writeOperand(Operand , true); Out << ',';
1228 writeOperand(I.getOperand(1), true); Out << " [";
1230 for (unsigned op = 2, Eop = I.getNumOperands(); op < Eop; op += 2) {
1232 writeOperand(I.getOperand(op ), true); Out << ',';
1233 writeOperand(I.getOperand(op+1), true);
1236 } else if (isa<PHINode>(I)) {
1238 printType(I.getType());
1241 for (unsigned op = 0, Eop = I.getNumOperands(); op < Eop; op += 2) {
1242 if (op) Out << ", ";
1244 writeOperand(I.getOperand(op ), false); Out << ',';
1245 writeOperand(I.getOperand(op+1), false); Out << " ]";
1247 } else if (isa<ReturnInst>(I) && !Operand) {
1249 } else if (const CallInst *CI = dyn_cast<CallInst>(&I)) {
1250 // Print the calling convention being used.
1251 switch (CI->getCallingConv()) {
1252 case CallingConv::C: break; // default
1253 case CallingConv::Fast: Out << " fastcc"; break;
1254 case CallingConv::Cold: Out << " coldcc"; break;
1255 case CallingConv::X86_StdCall: Out << "x86_stdcallcc "; break;
1256 case CallingConv::X86_FastCall: Out << "x86_fastcallcc "; break;
1257 default: Out << " cc" << CI->getCallingConv(); break;
1260 const PointerType *PTy = cast<PointerType>(Operand->getType());
1261 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
1262 const Type *RetTy = FTy->getReturnType();
1263 const ParamAttrsList *PAL = FTy->getParamAttrs();
1265 // If possible, print out the short form of the call instruction. We can
1266 // only do this if the first argument is a pointer to a nonvararg function,
1267 // and if the return type is not a pointer to a function.
1269 if (!FTy->isVarArg() &&
1270 (!isa<PointerType>(RetTy) ||
1271 !isa<FunctionType>(cast<PointerType>(RetTy)->getElementType()))) {
1272 Out << ' '; printType(RetTy);
1273 writeOperand(Operand, false);
1275 writeOperand(Operand, true);
1278 for (unsigned op = 1, Eop = I.getNumOperands(); op < Eop; ++op) {
1281 writeOperand(I.getOperand(op), true);
1282 if (PAL && PAL->getParamAttrs(op) != ParamAttr::None)
1283 Out << " " << PAL->getParamAttrsTextByIndex(op);
1286 if (PAL && PAL->getParamAttrs(0) != ParamAttr::None)
1287 Out << ' ' << PAL->getParamAttrsTextByIndex(0);
1288 } else if (const InvokeInst *II = dyn_cast<InvokeInst>(&I)) {
1289 const PointerType *PTy = cast<PointerType>(Operand->getType());
1290 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
1291 const Type *RetTy = FTy->getReturnType();
1292 const ParamAttrsList *PAL = FTy->getParamAttrs();
1294 // Print the calling convention being used.
1295 switch (II->getCallingConv()) {
1296 case CallingConv::C: break; // default
1297 case CallingConv::Fast: Out << " fastcc"; break;
1298 case CallingConv::Cold: Out << " coldcc"; break;
1299 case CallingConv::X86_StdCall: Out << "x86_stdcallcc "; break;
1300 case CallingConv::X86_FastCall: Out << "x86_fastcallcc "; break;
1301 default: Out << " cc" << II->getCallingConv(); break;
1304 // If possible, print out the short form of the invoke instruction. We can
1305 // only do this if the first argument is a pointer to a nonvararg function,
1306 // and if the return type is not a pointer to a function.
1308 if (!FTy->isVarArg() &&
1309 (!isa<PointerType>(RetTy) ||
1310 !isa<FunctionType>(cast<PointerType>(RetTy)->getElementType()))) {
1311 Out << ' '; printType(RetTy);
1312 writeOperand(Operand, false);
1314 writeOperand(Operand, true);
1318 for (unsigned op = 3, Eop = I.getNumOperands(); op < Eop; ++op) {
1321 writeOperand(I.getOperand(op), true);
1322 if (PAL && PAL->getParamAttrs(op-2) != ParamAttr::None)
1323 Out << " " << PAL->getParamAttrsTextByIndex(op-2);
1327 if (PAL && PAL->getParamAttrs(0) != ParamAttr::None)
1328 Out << " " << PAL->getParamAttrsTextByIndex(0);
1329 Out << "\n\t\t\tto";
1330 writeOperand(II->getNormalDest(), true);
1332 writeOperand(II->getUnwindDest(), true);
1334 } else if (const AllocationInst *AI = dyn_cast<AllocationInst>(&I)) {
1336 printType(AI->getType()->getElementType());
1337 if (AI->isArrayAllocation()) {
1339 writeOperand(AI->getArraySize(), true);
1341 if (AI->getAlignment()) {
1342 Out << ", align " << AI->getAlignment();
1344 } else if (isa<CastInst>(I)) {
1345 if (Operand) writeOperand(Operand, true); // Work with broken code
1347 printType(I.getType());
1348 } else if (isa<VAArgInst>(I)) {
1349 if (Operand) writeOperand(Operand, true); // Work with broken code
1351 printType(I.getType());
1352 } else if (Operand) { // Print the normal way...
1354 // PrintAllTypes - Instructions who have operands of all the same type
1355 // omit the type from all but the first operand. If the instruction has
1356 // different type operands (for example br), then they are all printed.
1357 bool PrintAllTypes = false;
1358 const Type *TheType = Operand->getType();
1360 // Select, Store and ShuffleVector always print all types.
1361 if (isa<SelectInst>(I) || isa<StoreInst>(I) || isa<ShuffleVectorInst>(I)) {
1362 PrintAllTypes = true;
1364 for (unsigned i = 1, E = I.getNumOperands(); i != E; ++i) {
1365 Operand = I.getOperand(i);
1366 if (Operand->getType() != TheType) {
1367 PrintAllTypes = true; // We have differing types! Print them all!
1373 if (!PrintAllTypes) {
1378 for (unsigned i = 0, E = I.getNumOperands(); i != E; ++i) {
1380 writeOperand(I.getOperand(i), PrintAllTypes);
1384 // Print post operand alignment for load/store
1385 if (isa<LoadInst>(I) && cast<LoadInst>(I).getAlignment()) {
1386 Out << ", align " << cast<LoadInst>(I).getAlignment();
1387 } else if (isa<StoreInst>(I) && cast<StoreInst>(I).getAlignment()) {
1388 Out << ", align " << cast<StoreInst>(I).getAlignment();
1391 printInfoComment(I);
1396 //===----------------------------------------------------------------------===//
1397 // External Interface declarations
1398 //===----------------------------------------------------------------------===//
1400 void Module::print(std::ostream &o, AssemblyAnnotationWriter *AAW) const {
1401 SlotMachine SlotTable(this);
1402 AssemblyWriter W(o, SlotTable, this, AAW);
1406 void GlobalVariable::print(std::ostream &o) const {
1407 SlotMachine SlotTable(getParent());
1408 AssemblyWriter W(o, SlotTable, getParent(), 0);
1412 void GlobalAlias::print(std::ostream &o) const {
1413 SlotMachine SlotTable(getParent());
1414 AssemblyWriter W(o, SlotTable, getParent(), 0);
1418 void Function::print(std::ostream &o, AssemblyAnnotationWriter *AAW) const {
1419 SlotMachine SlotTable(getParent());
1420 AssemblyWriter W(o, SlotTable, getParent(), AAW);
1425 void InlineAsm::print(std::ostream &o, AssemblyAnnotationWriter *AAW) const {
1426 WriteAsOperand(o, this, true, 0);
1429 void BasicBlock::print(std::ostream &o, AssemblyAnnotationWriter *AAW) const {
1430 SlotMachine SlotTable(getParent());
1431 AssemblyWriter W(o, SlotTable,
1432 getParent() ? getParent()->getParent() : 0, AAW);
1436 void Instruction::print(std::ostream &o, AssemblyAnnotationWriter *AAW) const {
1437 const Function *F = getParent() ? getParent()->getParent() : 0;
1438 SlotMachine SlotTable(F);
1439 AssemblyWriter W(o, SlotTable, F ? F->getParent() : 0, AAW);
1444 void Constant::print(std::ostream &o) const {
1445 if (this == 0) { o << "<null> constant value\n"; return; }
1447 o << ' ' << getType()->getDescription() << ' ';
1449 std::map<const Type *, std::string> TypeTable;
1450 WriteConstantInt(o, this, TypeTable, 0);
1453 void Type::print(std::ostream &o) const {
1457 o << getDescription();
1460 void Argument::print(std::ostream &o) const {
1461 WriteAsOperand(o, this, true, getParent() ? getParent()->getParent() : 0);
1464 // Value::dump - allow easy printing of Values from the debugger.
1465 // Located here because so much of the needed functionality is here.
1466 void Value::dump() const { print(*cerr.stream()); cerr << '\n'; }
1468 // Type::dump - allow easy printing of Values from the debugger.
1469 // Located here because so much of the needed functionality is here.
1470 void Type::dump() const { print(*cerr.stream()); cerr << '\n'; }
1473 ParamAttrsList::dump() const {
1475 for (unsigned i = 0; i < attrs.size(); ++i) {
1476 uint16_t index = getParamIndex(i);
1477 uint16_t attrs = getParamAttrs(index);
1478 cerr << "{" << index << "," << attrs << "} ";
1483 //===----------------------------------------------------------------------===//
1484 // SlotMachine Implementation
1485 //===----------------------------------------------------------------------===//
1488 #define SC_DEBUG(X) cerr << X
1493 // Module level constructor. Causes the contents of the Module (sans functions)
1494 // to be added to the slot table.
1495 SlotMachine::SlotMachine(const Module *M)
1496 : TheModule(M) ///< Saved for lazy initialization.
1498 , FunctionProcessed(false)
1499 , mMap(), mNext(0), fMap(), fNext(0)
1503 // Function level constructor. Causes the contents of the Module and the one
1504 // function provided to be added to the slot table.
1505 SlotMachine::SlotMachine(const Function *F)
1506 : TheModule(F ? F->getParent() : 0) ///< Saved for lazy initialization
1507 , TheFunction(F) ///< Saved for lazy initialization
1508 , FunctionProcessed(false)
1509 , mMap(), mNext(0), fMap(), fNext(0)
1513 inline void SlotMachine::initialize() {
1516 TheModule = 0; ///< Prevent re-processing next time we're called.
1518 if (TheFunction && !FunctionProcessed)
1522 // Iterate through all the global variables, functions, and global
1523 // variable initializers and create slots for them.
1524 void SlotMachine::processModule() {
1525 SC_DEBUG("begin processModule!\n");
1527 // Add all of the unnamed global variables to the value table.
1528 for (Module::const_global_iterator I = TheModule->global_begin(),
1529 E = TheModule->global_end(); I != E; ++I)
1531 CreateModuleSlot(I);
1533 // Add all the unnamed functions to the table.
1534 for (Module::const_iterator I = TheModule->begin(), E = TheModule->end();
1537 CreateModuleSlot(I);
1539 SC_DEBUG("end processModule!\n");
1543 // Process the arguments, basic blocks, and instructions of a function.
1544 void SlotMachine::processFunction() {
1545 SC_DEBUG("begin processFunction!\n");
1548 // Add all the function arguments with no names.
1549 for(Function::const_arg_iterator AI = TheFunction->arg_begin(),
1550 AE = TheFunction->arg_end(); AI != AE; ++AI)
1552 CreateFunctionSlot(AI);
1554 SC_DEBUG("Inserting Instructions:\n");
1556 // Add all of the basic blocks and instructions with no names.
1557 for (Function::const_iterator BB = TheFunction->begin(),
1558 E = TheFunction->end(); BB != E; ++BB) {
1560 CreateFunctionSlot(BB);
1561 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I != E; ++I)
1562 if (I->getType() != Type::VoidTy && !I->hasName())
1563 CreateFunctionSlot(I);
1566 FunctionProcessed = true;
1568 SC_DEBUG("end processFunction!\n");
1571 /// Clean up after incorporating a function. This is the only way to get out of
1572 /// the function incorporation state that affects get*Slot/Create*Slot. Function
1573 /// incorporation state is indicated by TheFunction != 0.
1574 void SlotMachine::purgeFunction() {
1575 SC_DEBUG("begin purgeFunction!\n");
1576 fMap.clear(); // Simply discard the function level map
1578 FunctionProcessed = false;
1579 SC_DEBUG("end purgeFunction!\n");
1582 /// getGlobalSlot - Get the slot number of a global value.
1583 int SlotMachine::getGlobalSlot(const GlobalValue *V) {
1584 // Check for uninitialized state and do lazy initialization.
1587 // Find the type plane in the module map
1588 ValueMap::const_iterator MI = mMap.find(V);
1589 if (MI == mMap.end()) return -1;
1595 /// getLocalSlot - Get the slot number for a value that is local to a function.
1596 int SlotMachine::getLocalSlot(const Value *V) {
1597 assert(!isa<Constant>(V) && "Can't get a constant or global slot with this!");
1599 // Check for uninitialized state and do lazy initialization.
1602 ValueMap::const_iterator FI = fMap.find(V);
1603 if (FI == fMap.end()) return -1;
1609 /// CreateModuleSlot - Insert the specified GlobalValue* into the slot table.
1610 void SlotMachine::CreateModuleSlot(const GlobalValue *V) {
1611 assert(V && "Can't insert a null Value into SlotMachine!");
1612 assert(V->getType() != Type::VoidTy && "Doesn't need a slot!");
1613 assert(!V->hasName() && "Doesn't need a slot!");
1615 unsigned DestSlot = mNext++;
1618 SC_DEBUG(" Inserting value [" << V->getType() << "] = " << V << " slot=" <<
1620 // G = Global, F = Function, A = Alias, o = other
1621 SC_DEBUG((isa<GlobalVariable>(V) ? 'G' :
1622 (isa<Function> ? 'F' :
1623 (isa<GlobalAlias> ? 'A' : 'o'))) << "]\n");
1627 /// CreateSlot - Create a new slot for the specified value if it has no name.
1628 void SlotMachine::CreateFunctionSlot(const Value *V) {
1629 const Type *VTy = V->getType();
1630 assert(VTy != Type::VoidTy && !V->hasName() && "Doesn't need a slot!");
1632 unsigned DestSlot = fNext++;
1635 // G = Global, F = Function, o = other
1636 SC_DEBUG(" Inserting value [" << VTy << "] = " << V << " slot=" <<
1637 DestSlot << " [o]\n");