AsmWriter.cpp revision bd5db8e29b82f864c3d6525c6cfefa557fafdbb8
1//===-- AsmWriter.cpp - Printing LLVM as an assembly file -----------------===// 2// 3// The LLVM Compiler Infrastructure 4// 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. 7// 8//===----------------------------------------------------------------------===// 9// 10// This library implements the functionality defined in llvm/Assembly/Writer.h 11// 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. 14// 15//===----------------------------------------------------------------------===// 16 17#include "llvm/Assembly/Writer.h" 18#include "llvm/Assembly/PrintModulePass.h" 19#include "llvm/Assembly/AsmAnnotationWriter.h" 20#include "llvm/CallingConv.h" 21#include "llvm/Constants.h" 22#include "llvm/DerivedTypes.h" 23#include "llvm/InlineAsm.h" 24#include "llvm/Instruction.h" 25#include "llvm/Instructions.h" 26#include "llvm/Module.h" 27#include "llvm/SymbolTable.h" 28#include "llvm/ADT/StringExtras.h" 29#include "llvm/ADT/STLExtras.h" 30#include "llvm/Support/CFG.h" 31#include "llvm/Support/MathExtras.h" 32#include "llvm/Support/Streams.h" 33#include <algorithm> 34using namespace llvm; 35 36namespace llvm { 37 38// Make virtual table appear in this compilation unit. 39AssemblyAnnotationWriter::~AssemblyAnnotationWriter() {} 40 41/// This class provides computation of slot numbers for LLVM Assembly writing. 42/// @brief LLVM Assembly Writing Slot Computation. 43class SlotMachine { 44 45/// @name Types 46/// @{ 47public: 48 49 /// @brief A mapping of Values to slot numbers 50 typedef std::map<const Value*, unsigned> ValueMap; 51 52 /// @brief A plane with next slot number and ValueMap 53 struct ValuePlane { 54 unsigned next_slot; ///< The next slot number to use 55 ValueMap map; ///< The map of Value* -> unsigned 56 ValuePlane() { next_slot = 0; } ///< Make sure we start at 0 57 }; 58 59 /// @brief The map of planes by Type 60 typedef std::map<const Type*, ValuePlane> TypedPlanes; 61 62/// @} 63/// @name Constructors 64/// @{ 65public: 66 /// @brief Construct from a module 67 SlotMachine(const Module *M); 68 69 /// @brief Construct from a function, starting out in incorp state. 70 SlotMachine(const Function *F); 71 72/// @} 73/// @name Accessors 74/// @{ 75public: 76 /// Return the slot number of the specified value in it's type 77 /// plane. Its an error to ask for something not in the SlotMachine. 78 /// Its an error to ask for a Type* 79 int getSlot(const Value *V); 80 81/// @} 82/// @name Mutators 83/// @{ 84public: 85 /// If you'd like to deal with a function instead of just a module, use 86 /// this method to get its data into the SlotMachine. 87 void incorporateFunction(const Function *F) { 88 TheFunction = F; 89 FunctionProcessed = false; 90 } 91 92 /// After calling incorporateFunction, use this method to remove the 93 /// most recently incorporated function from the SlotMachine. This 94 /// will reset the state of the machine back to just the module contents. 95 void purgeFunction(); 96 97/// @} 98/// @name Implementation Details 99/// @{ 100private: 101 /// This function does the actual initialization. 102 inline void initialize(); 103 104 /// Values can be crammed into here at will. If they haven't 105 /// been inserted already, they get inserted, otherwise they are ignored. 106 /// Either way, the slot number for the Value* is returned. 107 unsigned getOrCreateSlot(const Value *V); 108 109 /// Insert a value into the value table. Return the slot number 110 /// that it now occupies. BadThings(TM) will happen if you insert a 111 /// Value that's already been inserted. 112 unsigned insertValue(const Value *V); 113 114 /// Add all of the module level global variables (and their initializers) 115 /// and function declarations, but not the contents of those functions. 116 void processModule(); 117 118 /// Add all of the functions arguments, basic blocks, and instructions 119 void processFunction(); 120 121 SlotMachine(const SlotMachine &); // DO NOT IMPLEMENT 122 void operator=(const SlotMachine &); // DO NOT IMPLEMENT 123 124/// @} 125/// @name Data 126/// @{ 127public: 128 129 /// @brief The module for which we are holding slot numbers 130 const Module* TheModule; 131 132 /// @brief The function for which we are holding slot numbers 133 const Function* TheFunction; 134 bool FunctionProcessed; 135 136 /// @brief The TypePlanes map for the module level data 137 TypedPlanes mMap; 138 139 /// @brief The TypePlanes map for the function level data 140 TypedPlanes fMap; 141 142/// @} 143 144}; 145 146} // end namespace llvm 147 148static RegisterPass<PrintModulePass> 149X("printm", "Print module to stderr"); 150static RegisterPass<PrintFunctionPass> 151Y("print","Print function to stderr"); 152 153static void WriteAsOperandInternal(std::ostream &Out, const Value *V, 154 std::map<const Type *, std::string> &TypeTable, 155 SlotMachine *Machine); 156 157static const Module *getModuleFromVal(const Value *V) { 158 if (const Argument *MA = dyn_cast<Argument>(V)) 159 return MA->getParent() ? MA->getParent()->getParent() : 0; 160 else if (const BasicBlock *BB = dyn_cast<BasicBlock>(V)) 161 return BB->getParent() ? BB->getParent()->getParent() : 0; 162 else if (const Instruction *I = dyn_cast<Instruction>(V)) { 163 const Function *M = I->getParent() ? I->getParent()->getParent() : 0; 164 return M ? M->getParent() : 0; 165 } else if (const GlobalValue *GV = dyn_cast<GlobalValue>(V)) 166 return GV->getParent(); 167 return 0; 168} 169 170static SlotMachine *createSlotMachine(const Value *V) { 171 if (const Argument *FA = dyn_cast<Argument>(V)) { 172 return new SlotMachine(FA->getParent()); 173 } else if (const Instruction *I = dyn_cast<Instruction>(V)) { 174 return new SlotMachine(I->getParent()->getParent()); 175 } else if (const BasicBlock *BB = dyn_cast<BasicBlock>(V)) { 176 return new SlotMachine(BB->getParent()); 177 } else if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(V)){ 178 return new SlotMachine(GV->getParent()); 179 } else if (const Function *Func = dyn_cast<Function>(V)) { 180 return new SlotMachine(Func); 181 } 182 return 0; 183} 184 185// getLLVMName - Turn the specified string into an 'LLVM name', which is either 186// prefixed with % (if the string only contains simple characters) or is 187// surrounded with ""'s (if it has special chars in it). 188static std::string getLLVMName(const std::string &Name, 189 bool prefixName = true) { 190 assert(!Name.empty() && "Cannot get empty name!"); 191 192 // First character cannot start with a number... 193 if (Name[0] >= '0' && Name[0] <= '9') 194 return "\"" + Name + "\""; 195 196 // Scan to see if we have any characters that are not on the "white list" 197 for (unsigned i = 0, e = Name.size(); i != e; ++i) { 198 char C = Name[i]; 199 assert(C != '"' && "Illegal character in LLVM value name!"); 200 if ((C < 'a' || C > 'z') && (C < 'A' || C > 'Z') && (C < '0' || C > '9') && 201 C != '-' && C != '.' && C != '_') 202 return "\"" + Name + "\""; 203 } 204 205 // If we get here, then the identifier is legal to use as a "VarID". 206 if (prefixName) 207 return "%"+Name; 208 else 209 return Name; 210} 211 212 213/// fillTypeNameTable - If the module has a symbol table, take all global types 214/// and stuff their names into the TypeNames map. 215/// 216static void fillTypeNameTable(const Module *M, 217 std::map<const Type *, std::string> &TypeNames) { 218 if (!M) return; 219 const SymbolTable &ST = M->getSymbolTable(); 220 SymbolTable::type_const_iterator TI = ST.type_begin(); 221 for (; TI != ST.type_end(); ++TI) { 222 // As a heuristic, don't insert pointer to primitive types, because 223 // they are used too often to have a single useful name. 224 // 225 const Type *Ty = cast<Type>(TI->second); 226 if (!isa<PointerType>(Ty) || 227 !cast<PointerType>(Ty)->getElementType()->isPrimitiveType() || 228 isa<OpaqueType>(cast<PointerType>(Ty)->getElementType())) 229 TypeNames.insert(std::make_pair(Ty, getLLVMName(TI->first))); 230 } 231} 232 233 234 235static void calcTypeName(const Type *Ty, 236 std::vector<const Type *> &TypeStack, 237 std::map<const Type *, std::string> &TypeNames, 238 std::string & Result){ 239 if (Ty->isPrimitiveType() && !isa<OpaqueType>(Ty)) { 240 Result += Ty->getDescription(); // Base case 241 return; 242 } 243 244 // Check to see if the type is named. 245 std::map<const Type *, std::string>::iterator I = TypeNames.find(Ty); 246 if (I != TypeNames.end()) { 247 Result += I->second; 248 return; 249 } 250 251 if (isa<OpaqueType>(Ty)) { 252 Result += "opaque"; 253 return; 254 } 255 256 // Check to see if the Type is already on the stack... 257 unsigned Slot = 0, CurSize = TypeStack.size(); 258 while (Slot < CurSize && TypeStack[Slot] != Ty) ++Slot; // Scan for type 259 260 // This is another base case for the recursion. In this case, we know 261 // that we have looped back to a type that we have previously visited. 262 // Generate the appropriate upreference to handle this. 263 if (Slot < CurSize) { 264 Result += "\\" + utostr(CurSize-Slot); // Here's the upreference 265 return; 266 } 267 268 TypeStack.push_back(Ty); // Recursive case: Add us to the stack.. 269 270 switch (Ty->getTypeID()) { 271 case Type::FunctionTyID: { 272 const FunctionType *FTy = cast<FunctionType>(Ty); 273 calcTypeName(FTy->getReturnType(), TypeStack, TypeNames, Result); 274 if (FTy->getParamAttrs(0)) { 275 Result += " "; 276 Result += FunctionType::getParamAttrsText(FTy->getParamAttrs(0)); 277 } 278 Result += " ("; 279 unsigned Idx = 1; 280 for (FunctionType::param_iterator I = FTy->param_begin(), 281 E = FTy->param_end(); I != E; ++I) { 282 if (I != FTy->param_begin()) 283 Result += ", "; 284 calcTypeName(*I, TypeStack, TypeNames, Result); 285 if (FTy->getParamAttrs(Idx)) { 286 Result += + " "; 287 Result += FunctionType::getParamAttrsText(FTy->getParamAttrs(Idx)); 288 } 289 Idx++; 290 } 291 if (FTy->isVarArg()) { 292 if (FTy->getNumParams()) Result += ", "; 293 Result += "..."; 294 } 295 Result += ")"; 296 break; 297 } 298 case Type::StructTyID: { 299 const StructType *STy = cast<StructType>(Ty); 300 if (STy->isPacked()) 301 Result += '<'; 302 Result += "{ "; 303 for (StructType::element_iterator I = STy->element_begin(), 304 E = STy->element_end(); I != E; ++I) { 305 if (I != STy->element_begin()) 306 Result += ", "; 307 calcTypeName(*I, TypeStack, TypeNames, Result); 308 } 309 Result += " }"; 310 if (STy->isPacked()) 311 Result += '>'; 312 break; 313 } 314 case Type::PointerTyID: 315 calcTypeName(cast<PointerType>(Ty)->getElementType(), 316 TypeStack, TypeNames, Result); 317 Result += "*"; 318 break; 319 case Type::ArrayTyID: { 320 const ArrayType *ATy = cast<ArrayType>(Ty); 321 Result += "[" + utostr(ATy->getNumElements()) + " x "; 322 calcTypeName(ATy->getElementType(), TypeStack, TypeNames, Result); 323 Result += "]"; 324 break; 325 } 326 case Type::PackedTyID: { 327 const PackedType *PTy = cast<PackedType>(Ty); 328 Result += "<" + utostr(PTy->getNumElements()) + " x "; 329 calcTypeName(PTy->getElementType(), TypeStack, TypeNames, Result); 330 Result += ">"; 331 break; 332 } 333 case Type::OpaqueTyID: 334 Result += "opaque"; 335 break; 336 default: 337 Result += "<unrecognized-type>"; 338 break; 339 } 340 341 TypeStack.pop_back(); // Remove self from stack... 342} 343 344 345/// printTypeInt - The internal guts of printing out a type that has a 346/// potentially named portion. 347/// 348static std::ostream &printTypeInt(std::ostream &Out, const Type *Ty, 349 std::map<const Type *, std::string> &TypeNames) { 350 // Primitive types always print out their description, regardless of whether 351 // they have been named or not. 352 // 353 if (Ty->isPrimitiveType() && !isa<OpaqueType>(Ty)) 354 return Out << Ty->getDescription(); 355 356 // Check to see if the type is named. 357 std::map<const Type *, std::string>::iterator I = TypeNames.find(Ty); 358 if (I != TypeNames.end()) return Out << I->second; 359 360 // Otherwise we have a type that has not been named but is a derived type. 361 // Carefully recurse the type hierarchy to print out any contained symbolic 362 // names. 363 // 364 std::vector<const Type *> TypeStack; 365 std::string TypeName; 366 calcTypeName(Ty, TypeStack, TypeNames, TypeName); 367 TypeNames.insert(std::make_pair(Ty, TypeName));//Cache type name for later use 368 return (Out << TypeName); 369} 370 371 372/// WriteTypeSymbolic - This attempts to write the specified type as a symbolic 373/// type, iff there is an entry in the modules symbol table for the specified 374/// type or one of it's component types. This is slower than a simple x << Type 375/// 376std::ostream &llvm::WriteTypeSymbolic(std::ostream &Out, const Type *Ty, 377 const Module *M) { 378 Out << ' '; 379 380 // If they want us to print out a type, but there is no context, we can't 381 // print it symbolically. 382 if (!M) 383 return Out << Ty->getDescription(); 384 385 std::map<const Type *, std::string> TypeNames; 386 fillTypeNameTable(M, TypeNames); 387 return printTypeInt(Out, Ty, TypeNames); 388} 389 390// PrintEscapedString - Print each character of the specified string, escaping 391// it if it is not printable or if it is an escape char. 392static void PrintEscapedString(const std::string &Str, std::ostream &Out) { 393 for (unsigned i = 0, e = Str.size(); i != e; ++i) { 394 unsigned char C = Str[i]; 395 if (isprint(C) && C != '"' && C != '\\') { 396 Out << C; 397 } else { 398 Out << '\\' 399 << (char) ((C/16 < 10) ? ( C/16 +'0') : ( C/16 -10+'A')) 400 << (char)(((C&15) < 10) ? ((C&15)+'0') : ((C&15)-10+'A')); 401 } 402 } 403} 404 405static const char *getPredicateText(unsigned predicate) { 406 const char * pred = "unknown"; 407 switch (predicate) { 408 case FCmpInst::FCMP_FALSE: pred = "false"; break; 409 case FCmpInst::FCMP_OEQ: pred = "oeq"; break; 410 case FCmpInst::FCMP_OGT: pred = "ogt"; break; 411 case FCmpInst::FCMP_OGE: pred = "oge"; break; 412 case FCmpInst::FCMP_OLT: pred = "olt"; break; 413 case FCmpInst::FCMP_OLE: pred = "ole"; break; 414 case FCmpInst::FCMP_ONE: pred = "one"; break; 415 case FCmpInst::FCMP_ORD: pred = "ord"; break; 416 case FCmpInst::FCMP_UNO: pred = "uno"; break; 417 case FCmpInst::FCMP_UEQ: pred = "ueq"; break; 418 case FCmpInst::FCMP_UGT: pred = "ugt"; break; 419 case FCmpInst::FCMP_UGE: pred = "uge"; break; 420 case FCmpInst::FCMP_ULT: pred = "ult"; break; 421 case FCmpInst::FCMP_ULE: pred = "ule"; break; 422 case FCmpInst::FCMP_UNE: pred = "une"; break; 423 case FCmpInst::FCMP_TRUE: pred = "true"; break; 424 case ICmpInst::ICMP_EQ: pred = "eq"; break; 425 case ICmpInst::ICMP_NE: pred = "ne"; break; 426 case ICmpInst::ICMP_SGT: pred = "sgt"; break; 427 case ICmpInst::ICMP_SGE: pred = "sge"; break; 428 case ICmpInst::ICMP_SLT: pred = "slt"; break; 429 case ICmpInst::ICMP_SLE: pred = "sle"; break; 430 case ICmpInst::ICMP_UGT: pred = "ugt"; break; 431 case ICmpInst::ICMP_UGE: pred = "uge"; break; 432 case ICmpInst::ICMP_ULT: pred = "ult"; break; 433 case ICmpInst::ICMP_ULE: pred = "ule"; break; 434 } 435 return pred; 436} 437 438/// @brief Internal constant writer. 439static void WriteConstantInt(std::ostream &Out, const Constant *CV, 440 std::map<const Type *, std::string> &TypeTable, 441 SlotMachine *Machine) { 442 const int IndentSize = 4; 443 static std::string Indent = "\n"; 444 if (const ConstantBool *CB = dyn_cast<ConstantBool>(CV)) { 445 Out << (CB->getValue() ? "true" : "false"); 446 } else if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV)) { 447 Out << CI->getSExtValue(); 448 } else if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CV)) { 449 // We would like to output the FP constant value in exponential notation, 450 // but we cannot do this if doing so will lose precision. Check here to 451 // make sure that we only output it in exponential format if we can parse 452 // the value back and get the same value. 453 // 454 std::string StrVal = ftostr(CFP->getValue()); 455 456 // Check to make sure that the stringized number is not some string like 457 // "Inf" or NaN, that atof will accept, but the lexer will not. Check that 458 // the string matches the "[-+]?[0-9]" regex. 459 // 460 if ((StrVal[0] >= '0' && StrVal[0] <= '9') || 461 ((StrVal[0] == '-' || StrVal[0] == '+') && 462 (StrVal[1] >= '0' && StrVal[1] <= '9'))) 463 // Reparse stringized version! 464 if (atof(StrVal.c_str()) == CFP->getValue()) { 465 Out << StrVal; 466 return; 467 } 468 469 // Otherwise we could not reparse it to exactly the same value, so we must 470 // output the string in hexadecimal format! 471 assert(sizeof(double) == sizeof(uint64_t) && 472 "assuming that double is 64 bits!"); 473 Out << "0x" << utohexstr(DoubleToBits(CFP->getValue())); 474 475 } else if (isa<ConstantAggregateZero>(CV)) { 476 Out << "zeroinitializer"; 477 } else if (const ConstantArray *CA = dyn_cast<ConstantArray>(CV)) { 478 // As a special case, print the array as a string if it is an array of 479 // ubytes or an array of sbytes with positive values. 480 // 481 const Type *ETy = CA->getType()->getElementType(); 482 if (CA->isString()) { 483 Out << "c\""; 484 PrintEscapedString(CA->getAsString(), Out); 485 Out << "\""; 486 487 } else { // Cannot output in string format... 488 Out << '['; 489 if (CA->getNumOperands()) { 490 Out << ' '; 491 printTypeInt(Out, ETy, TypeTable); 492 WriteAsOperandInternal(Out, CA->getOperand(0), 493 TypeTable, Machine); 494 for (unsigned i = 1, e = CA->getNumOperands(); i != e; ++i) { 495 Out << ", "; 496 printTypeInt(Out, ETy, TypeTable); 497 WriteAsOperandInternal(Out, CA->getOperand(i), TypeTable, Machine); 498 } 499 } 500 Out << " ]"; 501 } 502 } else if (const ConstantStruct *CS = dyn_cast<ConstantStruct>(CV)) { 503 Out << '{'; 504 unsigned N = CS->getNumOperands(); 505 if (N) { 506 if (N > 2) { 507 Indent += std::string(IndentSize, ' '); 508 Out << Indent; 509 } else { 510 Out << ' '; 511 } 512 printTypeInt(Out, CS->getOperand(0)->getType(), TypeTable); 513 514 WriteAsOperandInternal(Out, CS->getOperand(0), TypeTable, Machine); 515 516 for (unsigned i = 1; i < N; i++) { 517 Out << ", "; 518 if (N > 2) Out << Indent; 519 printTypeInt(Out, CS->getOperand(i)->getType(), TypeTable); 520 521 WriteAsOperandInternal(Out, CS->getOperand(i), TypeTable, Machine); 522 } 523 if (N > 2) Indent.resize(Indent.size() - IndentSize); 524 } 525 526 Out << " }"; 527 } else if (const ConstantPacked *CP = dyn_cast<ConstantPacked>(CV)) { 528 const Type *ETy = CP->getType()->getElementType(); 529 assert(CP->getNumOperands() > 0 && 530 "Number of operands for a PackedConst must be > 0"); 531 Out << '<'; 532 Out << ' '; 533 printTypeInt(Out, ETy, TypeTable); 534 WriteAsOperandInternal(Out, CP->getOperand(0), TypeTable, Machine); 535 for (unsigned i = 1, e = CP->getNumOperands(); i != e; ++i) { 536 Out << ", "; 537 printTypeInt(Out, ETy, TypeTable); 538 WriteAsOperandInternal(Out, CP->getOperand(i), TypeTable, Machine); 539 } 540 Out << " >"; 541 } else if (isa<ConstantPointerNull>(CV)) { 542 Out << "null"; 543 544 } else if (isa<UndefValue>(CV)) { 545 Out << "undef"; 546 547 } else if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV)) { 548 Out << CE->getOpcodeName(); 549 if (CE->isCompare()) 550 Out << " " << getPredicateText(CE->getPredicate()); 551 Out << " ("; 552 553 for (User::const_op_iterator OI=CE->op_begin(); OI != CE->op_end(); ++OI) { 554 printTypeInt(Out, (*OI)->getType(), TypeTable); 555 WriteAsOperandInternal(Out, *OI, TypeTable, Machine); 556 if (OI+1 != CE->op_end()) 557 Out << ", "; 558 } 559 560 if (CE->isCast()) { 561 Out << " to "; 562 printTypeInt(Out, CE->getType(), TypeTable); 563 } 564 565 Out << ')'; 566 567 } else { 568 Out << "<placeholder or erroneous Constant>"; 569 } 570} 571 572 573/// WriteAsOperand - Write the name of the specified value out to the specified 574/// ostream. This can be useful when you just want to print int %reg126, not 575/// the whole instruction that generated it. 576/// 577static void WriteAsOperandInternal(std::ostream &Out, const Value *V, 578 std::map<const Type*, std::string> &TypeTable, 579 SlotMachine *Machine) { 580 Out << ' '; 581 if (V->hasName()) 582 Out << getLLVMName(V->getName()); 583 else { 584 const Constant *CV = dyn_cast<Constant>(V); 585 if (CV && !isa<GlobalValue>(CV)) { 586 WriteConstantInt(Out, CV, TypeTable, Machine); 587 } else if (const InlineAsm *IA = dyn_cast<InlineAsm>(V)) { 588 Out << "asm "; 589 if (IA->hasSideEffects()) 590 Out << "sideeffect "; 591 Out << '"'; 592 PrintEscapedString(IA->getAsmString(), Out); 593 Out << "\", \""; 594 PrintEscapedString(IA->getConstraintString(), Out); 595 Out << '"'; 596 } else { 597 int Slot; 598 if (Machine) { 599 Slot = Machine->getSlot(V); 600 } else { 601 Machine = createSlotMachine(V); 602 if (Machine) 603 Slot = Machine->getSlot(V); 604 else 605 Slot = -1; 606 delete Machine; 607 } 608 if (Slot != -1) 609 Out << '%' << Slot; 610 else 611 Out << "<badref>"; 612 } 613 } 614} 615 616/// WriteAsOperand - Write the name of the specified value out to the specified 617/// ostream. This can be useful when you just want to print int %reg126, not 618/// the whole instruction that generated it. 619/// 620std::ostream &llvm::WriteAsOperand(std::ostream &Out, const Value *V, 621 bool PrintType, const Module *Context) { 622 std::map<const Type *, std::string> TypeNames; 623 if (Context == 0) Context = getModuleFromVal(V); 624 625 if (Context) 626 fillTypeNameTable(Context, TypeNames); 627 628 if (PrintType) 629 printTypeInt(Out, V->getType(), TypeNames); 630 631 WriteAsOperandInternal(Out, V, TypeNames, 0); 632 return Out; 633} 634 635 636namespace llvm { 637 638class AssemblyWriter { 639 std::ostream &Out; 640 SlotMachine &Machine; 641 const Module *TheModule; 642 std::map<const Type *, std::string> TypeNames; 643 AssemblyAnnotationWriter *AnnotationWriter; 644public: 645 inline AssemblyWriter(std::ostream &o, SlotMachine &Mac, const Module *M, 646 AssemblyAnnotationWriter *AAW) 647 : Out(o), Machine(Mac), TheModule(M), AnnotationWriter(AAW) { 648 649 // If the module has a symbol table, take all global types and stuff their 650 // names into the TypeNames map. 651 // 652 fillTypeNameTable(M, TypeNames); 653 } 654 655 inline void write(const Module *M) { printModule(M); } 656 inline void write(const GlobalVariable *G) { printGlobal(G); } 657 inline void write(const Function *F) { printFunction(F); } 658 inline void write(const BasicBlock *BB) { printBasicBlock(BB); } 659 inline void write(const Instruction *I) { printInstruction(*I); } 660 inline void write(const Constant *CPV) { printConstant(CPV); } 661 inline void write(const Type *Ty) { printType(Ty); } 662 663 void writeOperand(const Value *Op, bool PrintType); 664 665 const Module* getModule() { return TheModule; } 666 667private: 668 void printModule(const Module *M); 669 void printSymbolTable(const SymbolTable &ST); 670 void printConstant(const Constant *CPV); 671 void printGlobal(const GlobalVariable *GV); 672 void printFunction(const Function *F); 673 void printArgument(const Argument *FA, FunctionType::ParameterAttributes A); 674 void printBasicBlock(const BasicBlock *BB); 675 void printInstruction(const Instruction &I); 676 677 // printType - Go to extreme measures to attempt to print out a short, 678 // symbolic version of a type name. 679 // 680 std::ostream &printType(const Type *Ty) { 681 return printTypeInt(Out, Ty, TypeNames); 682 } 683 684 // printTypeAtLeastOneLevel - Print out one level of the possibly complex type 685 // without considering any symbolic types that we may have equal to it. 686 // 687 std::ostream &printTypeAtLeastOneLevel(const Type *Ty); 688 689 // printInfoComment - Print a little comment after the instruction indicating 690 // which slot it occupies. 691 void printInfoComment(const Value &V); 692}; 693} // end of llvm namespace 694 695/// printTypeAtLeastOneLevel - Print out one level of the possibly complex type 696/// without considering any symbolic types that we may have equal to it. 697/// 698std::ostream &AssemblyWriter::printTypeAtLeastOneLevel(const Type *Ty) { 699 if (const FunctionType *FTy = dyn_cast<FunctionType>(Ty)) { 700 printType(FTy->getReturnType()); 701 if (FTy->getParamAttrs(0)) 702 Out << ' ' << FunctionType::getParamAttrsText(FTy->getParamAttrs(0)); 703 Out << " ("; 704 unsigned Idx = 1; 705 for (FunctionType::param_iterator I = FTy->param_begin(), 706 E = FTy->param_end(); I != E; ++I) { 707 if (I != FTy->param_begin()) 708 Out << ", "; 709 printType(*I); 710 if (FTy->getParamAttrs(Idx)) { 711 Out << " " << FunctionType::getParamAttrsText(FTy->getParamAttrs(Idx)); 712 } 713 Idx++; 714 } 715 if (FTy->isVarArg()) { 716 if (FTy->getNumParams()) Out << ", "; 717 Out << "..."; 718 } 719 Out << ')'; 720 } else if (const StructType *STy = dyn_cast<StructType>(Ty)) { 721 if (STy->isPacked()) 722 Out << '<'; 723 Out << "{ "; 724 for (StructType::element_iterator I = STy->element_begin(), 725 E = STy->element_end(); I != E; ++I) { 726 if (I != STy->element_begin()) 727 Out << ", "; 728 printType(*I); 729 } 730 Out << " }"; 731 if (STy->isPacked()) 732 Out << '>'; 733 } else if (const PointerType *PTy = dyn_cast<PointerType>(Ty)) { 734 printType(PTy->getElementType()) << '*'; 735 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(Ty)) { 736 Out << '[' << ATy->getNumElements() << " x "; 737 printType(ATy->getElementType()) << ']'; 738 } else if (const PackedType *PTy = dyn_cast<PackedType>(Ty)) { 739 Out << '<' << PTy->getNumElements() << " x "; 740 printType(PTy->getElementType()) << '>'; 741 } 742 else if (isa<OpaqueType>(Ty)) { 743 Out << "opaque"; 744 } else { 745 if (!Ty->isPrimitiveType()) 746 Out << "<unknown derived type>"; 747 printType(Ty); 748 } 749 return Out; 750} 751 752 753void AssemblyWriter::writeOperand(const Value *Operand, bool PrintType) { 754 if (Operand == 0) { 755 Out << "<null operand!>"; 756 } else { 757 if (PrintType) { Out << ' '; printType(Operand->getType()); } 758 WriteAsOperandInternal(Out, Operand, TypeNames, &Machine); 759 } 760} 761 762 763void AssemblyWriter::printModule(const Module *M) { 764 if (!M->getModuleIdentifier().empty() && 765 // Don't print the ID if it will start a new line (which would 766 // require a comment char before it). 767 M->getModuleIdentifier().find('\n') == std::string::npos) 768 Out << "; ModuleID = '" << M->getModuleIdentifier() << "'\n"; 769 770 if (!M->getDataLayout().empty()) 771 Out << "target datalayout = \"" << M->getDataLayout() << "\"\n"; 772 773 switch (M->getEndianness()) { 774 case Module::LittleEndian: Out << "target endian = little\n"; break; 775 case Module::BigEndian: Out << "target endian = big\n"; break; 776 case Module::AnyEndianness: break; 777 } 778 switch (M->getPointerSize()) { 779 case Module::Pointer32: Out << "target pointersize = 32\n"; break; 780 case Module::Pointer64: Out << "target pointersize = 64\n"; break; 781 case Module::AnyPointerSize: break; 782 } 783 if (!M->getTargetTriple().empty()) 784 Out << "target triple = \"" << M->getTargetTriple() << "\"\n"; 785 786 if (!M->getModuleInlineAsm().empty()) { 787 // Split the string into lines, to make it easier to read the .ll file. 788 std::string Asm = M->getModuleInlineAsm(); 789 size_t CurPos = 0; 790 size_t NewLine = Asm.find_first_of('\n', CurPos); 791 while (NewLine != std::string::npos) { 792 // We found a newline, print the portion of the asm string from the 793 // last newline up to this newline. 794 Out << "module asm \""; 795 PrintEscapedString(std::string(Asm.begin()+CurPos, Asm.begin()+NewLine), 796 Out); 797 Out << "\"\n"; 798 CurPos = NewLine+1; 799 NewLine = Asm.find_first_of('\n', CurPos); 800 } 801 Out << "module asm \""; 802 PrintEscapedString(std::string(Asm.begin()+CurPos, Asm.end()), Out); 803 Out << "\"\n"; 804 } 805 806 // Loop over the dependent libraries and emit them. 807 Module::lib_iterator LI = M->lib_begin(); 808 Module::lib_iterator LE = M->lib_end(); 809 if (LI != LE) { 810 Out << "deplibs = [ "; 811 while (LI != LE) { 812 Out << '"' << *LI << '"'; 813 ++LI; 814 if (LI != LE) 815 Out << ", "; 816 } 817 Out << " ]\n"; 818 } 819 820 // Loop over the symbol table, emitting all named constants. 821 printSymbolTable(M->getSymbolTable()); 822 823 for (Module::const_global_iterator I = M->global_begin(), E = M->global_end(); 824 I != E; ++I) 825 printGlobal(I); 826 827 Out << "\nimplementation ; Functions:\n"; 828 829 // Output all of the functions. 830 for (Module::const_iterator I = M->begin(), E = M->end(); I != E; ++I) 831 printFunction(I); 832} 833 834void AssemblyWriter::printGlobal(const GlobalVariable *GV) { 835 if (GV->hasName()) Out << getLLVMName(GV->getName()) << " = "; 836 837 if (!GV->hasInitializer()) 838 switch (GV->getLinkage()) { 839 case GlobalValue::DLLImportLinkage: Out << "dllimport "; break; 840 case GlobalValue::ExternalWeakLinkage: Out << "extern_weak "; break; 841 default: Out << "external "; break; 842 } 843 else 844 switch (GV->getLinkage()) { 845 case GlobalValue::InternalLinkage: Out << "internal "; break; 846 case GlobalValue::LinkOnceLinkage: Out << "linkonce "; break; 847 case GlobalValue::WeakLinkage: Out << "weak "; break; 848 case GlobalValue::AppendingLinkage: Out << "appending "; break; 849 case GlobalValue::DLLImportLinkage: Out << "dllimport "; break; 850 case GlobalValue::DLLExportLinkage: Out << "dllexport "; break; 851 case GlobalValue::ExternalWeakLinkage: Out << "extern_weak "; break; 852 case GlobalValue::ExternalLinkage: break; 853 case GlobalValue::GhostLinkage: 854 cerr << "GhostLinkage not allowed in AsmWriter!\n"; 855 abort(); 856 } 857 858 Out << (GV->isConstant() ? "constant " : "global "); 859 printType(GV->getType()->getElementType()); 860 861 if (GV->hasInitializer()) { 862 Constant* C = cast<Constant>(GV->getInitializer()); 863 assert(C && "GlobalVar initializer isn't constant?"); 864 writeOperand(GV->getInitializer(), false); 865 } 866 867 if (GV->hasSection()) 868 Out << ", section \"" << GV->getSection() << '"'; 869 if (GV->getAlignment()) 870 Out << ", align " << GV->getAlignment(); 871 872 printInfoComment(*GV); 873 Out << "\n"; 874} 875 876 877// printSymbolTable - Run through symbol table looking for constants 878// and types. Emit their declarations. 879void AssemblyWriter::printSymbolTable(const SymbolTable &ST) { 880 881 // Print the types. 882 for (SymbolTable::type_const_iterator TI = ST.type_begin(); 883 TI != ST.type_end(); ++TI) { 884 Out << "\t" << getLLVMName(TI->first) << " = type "; 885 886 // Make sure we print out at least one level of the type structure, so 887 // that we do not get %FILE = type %FILE 888 // 889 printTypeAtLeastOneLevel(TI->second) << "\n"; 890 } 891 892 // Print the constants, in type plane order. 893 for (SymbolTable::plane_const_iterator PI = ST.plane_begin(); 894 PI != ST.plane_end(); ++PI) { 895 SymbolTable::value_const_iterator VI = ST.value_begin(PI->first); 896 SymbolTable::value_const_iterator VE = ST.value_end(PI->first); 897 898 for (; VI != VE; ++VI) { 899 const Value* V = VI->second; 900 const Constant *CPV = dyn_cast<Constant>(V) ; 901 if (CPV && !isa<GlobalValue>(V)) { 902 printConstant(CPV); 903 } 904 } 905 } 906} 907 908 909/// printConstant - Print out a constant pool entry... 910/// 911void AssemblyWriter::printConstant(const Constant *CPV) { 912 // Don't print out unnamed constants, they will be inlined 913 if (!CPV->hasName()) return; 914 915 // Print out name... 916 Out << "\t" << getLLVMName(CPV->getName()) << " ="; 917 918 // Write the value out now. 919 writeOperand(CPV, true); 920 921 printInfoComment(*CPV); 922 Out << "\n"; 923} 924 925/// printFunction - Print all aspects of a function. 926/// 927void AssemblyWriter::printFunction(const Function *F) { 928 // Print out the return type and name... 929 Out << "\n"; 930 931 // Ensure that no local symbols conflict with global symbols. 932 const_cast<Function*>(F)->renameLocalSymbols(); 933 934 if (AnnotationWriter) AnnotationWriter->emitFunctionAnnot(F, Out); 935 936 if (F->isExternal()) 937 switch (F->getLinkage()) { 938 case GlobalValue::DLLImportLinkage: Out << "declare dllimport "; break; 939 case GlobalValue::ExternalWeakLinkage: Out << "declare extern_weak "; break; 940 default: Out << "declare "; 941 } 942 else { 943 Out << "define "; 944 switch (F->getLinkage()) { 945 case GlobalValue::InternalLinkage: Out << "internal "; break; 946 case GlobalValue::LinkOnceLinkage: Out << "linkonce "; break; 947 case GlobalValue::WeakLinkage: Out << "weak "; break; 948 case GlobalValue::AppendingLinkage: Out << "appending "; break; 949 case GlobalValue::DLLImportLinkage: Out << "dllimport "; break; 950 case GlobalValue::DLLExportLinkage: Out << "dllexport "; break; 951 case GlobalValue::ExternalWeakLinkage: Out << "extern_weak "; break; 952 case GlobalValue::ExternalLinkage: break; 953 case GlobalValue::GhostLinkage: 954 cerr << "GhostLinkage not allowed in AsmWriter!\n"; 955 abort(); 956 } 957 } 958 959 // Print the calling convention. 960 switch (F->getCallingConv()) { 961 case CallingConv::C: break; // default 962 case CallingConv::CSRet: Out << "csretcc "; break; 963 case CallingConv::Fast: Out << "fastcc "; break; 964 case CallingConv::Cold: Out << "coldcc "; break; 965 case CallingConv::X86_StdCall: Out << "x86_stdcallcc "; break; 966 case CallingConv::X86_FastCall: Out << "x86_fastcallcc "; break; 967 default: Out << "cc" << F->getCallingConv() << " "; break; 968 } 969 970 const FunctionType *FT = F->getFunctionType(); 971 printType(F->getReturnType()) << ' '; 972 if (FT->getParamAttrs(0)) 973 Out << FunctionType::getParamAttrsText(FT->getParamAttrs(0)) << ' '; 974 if (!F->getName().empty()) 975 Out << getLLVMName(F->getName()); 976 else 977 Out << "\"\""; 978 Out << '('; 979 Machine.incorporateFunction(F); 980 981 // Loop over the arguments, printing them... 982 983 unsigned Idx = 1; 984 for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end(); 985 I != E; ++I) { 986 // Insert commas as we go... the first arg doesn't get a comma 987 if (I != F->arg_begin()) Out << ", "; 988 printArgument(I, FT->getParamAttrs(Idx)); 989 Idx++; 990 } 991 992 // Finish printing arguments... 993 if (FT->isVarArg()) { 994 if (FT->getNumParams()) Out << ", "; 995 Out << "..."; // Output varargs portion of signature! 996 } 997 Out << ')'; 998 999 if (F->hasSection()) 1000 Out << " section \"" << F->getSection() << '"'; 1001 if (F->getAlignment()) 1002 Out << " align " << F->getAlignment(); 1003 1004 if (F->isExternal()) { 1005 Out << "\n"; 1006 } else { 1007 Out << " {"; 1008 1009 // Output all of its basic blocks... for the function 1010 for (Function::const_iterator I = F->begin(), E = F->end(); I != E; ++I) 1011 printBasicBlock(I); 1012 1013 Out << "}\n"; 1014 } 1015 1016 Machine.purgeFunction(); 1017} 1018 1019/// printArgument - This member is called for every argument that is passed into 1020/// the function. Simply print it out 1021/// 1022void AssemblyWriter::printArgument(const Argument *Arg, 1023 FunctionType::ParameterAttributes attrs) { 1024 // Output type... 1025 printType(Arg->getType()); 1026 1027 if (attrs != FunctionType::NoAttributeSet) 1028 Out << ' ' << FunctionType::getParamAttrsText(attrs); 1029 1030 // Output name, if available... 1031 if (Arg->hasName()) 1032 Out << ' ' << getLLVMName(Arg->getName()); 1033} 1034 1035/// printBasicBlock - This member is called for each basic block in a method. 1036/// 1037void AssemblyWriter::printBasicBlock(const BasicBlock *BB) { 1038 if (BB->hasName()) { // Print out the label if it exists... 1039 Out << "\n" << getLLVMName(BB->getName(), false) << ':'; 1040 } else if (!BB->use_empty()) { // Don't print block # of no uses... 1041 Out << "\n; <label>:"; 1042 int Slot = Machine.getSlot(BB); 1043 if (Slot != -1) 1044 Out << Slot; 1045 else 1046 Out << "<badref>"; 1047 } 1048 1049 if (BB->getParent() == 0) 1050 Out << "\t\t; Error: Block without parent!"; 1051 else { 1052 if (BB != &BB->getParent()->front()) { // Not the entry block? 1053 // Output predecessors for the block... 1054 Out << "\t\t;"; 1055 pred_const_iterator PI = pred_begin(BB), PE = pred_end(BB); 1056 1057 if (PI == PE) { 1058 Out << " No predecessors!"; 1059 } else { 1060 Out << " preds ="; 1061 writeOperand(*PI, false); 1062 for (++PI; PI != PE; ++PI) { 1063 Out << ','; 1064 writeOperand(*PI, false); 1065 } 1066 } 1067 } 1068 } 1069 1070 Out << "\n"; 1071 1072 if (AnnotationWriter) AnnotationWriter->emitBasicBlockStartAnnot(BB, Out); 1073 1074 // Output all of the instructions in the basic block... 1075 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I != E; ++I) 1076 printInstruction(*I); 1077 1078 if (AnnotationWriter) AnnotationWriter->emitBasicBlockEndAnnot(BB, Out); 1079} 1080 1081 1082/// printInfoComment - Print a little comment after the instruction indicating 1083/// which slot it occupies. 1084/// 1085void AssemblyWriter::printInfoComment(const Value &V) { 1086 if (V.getType() != Type::VoidTy) { 1087 Out << "\t\t; <"; 1088 printType(V.getType()) << '>'; 1089 1090 if (!V.hasName()) { 1091 int SlotNum = Machine.getSlot(&V); 1092 if (SlotNum == -1) 1093 Out << ":<badref>"; 1094 else 1095 Out << ':' << SlotNum; // Print out the def slot taken. 1096 } 1097 Out << " [#uses=" << V.getNumUses() << ']'; // Output # uses 1098 } 1099} 1100 1101// This member is called for each Instruction in a function.. 1102void AssemblyWriter::printInstruction(const Instruction &I) { 1103 if (AnnotationWriter) AnnotationWriter->emitInstructionAnnot(&I, Out); 1104 1105 Out << "\t"; 1106 1107 // Print out name if it exists... 1108 if (I.hasName()) 1109 Out << getLLVMName(I.getName()) << " = "; 1110 1111 // If this is a volatile load or store, print out the volatile marker. 1112 if ((isa<LoadInst>(I) && cast<LoadInst>(I).isVolatile()) || 1113 (isa<StoreInst>(I) && cast<StoreInst>(I).isVolatile())) { 1114 Out << "volatile "; 1115 } else if (isa<CallInst>(I) && cast<CallInst>(I).isTailCall()) { 1116 // If this is a call, check if it's a tail call. 1117 Out << "tail "; 1118 } 1119 1120 // Print out the opcode... 1121 Out << I.getOpcodeName(); 1122 1123 // Print out the compare instruction predicates 1124 if (const FCmpInst *FCI = dyn_cast<FCmpInst>(&I)) { 1125 Out << " " << getPredicateText(FCI->getPredicate()); 1126 } else if (const ICmpInst *ICI = dyn_cast<ICmpInst>(&I)) { 1127 Out << " " << getPredicateText(ICI->getPredicate()); 1128 } 1129 1130 // Print out the type of the operands... 1131 const Value *Operand = I.getNumOperands() ? I.getOperand(0) : 0; 1132 1133 // Special case conditional branches to swizzle the condition out to the front 1134 if (isa<BranchInst>(I) && I.getNumOperands() > 1) { 1135 writeOperand(I.getOperand(2), true); 1136 Out << ','; 1137 writeOperand(Operand, true); 1138 Out << ','; 1139 writeOperand(I.getOperand(1), true); 1140 1141 } else if (isa<SwitchInst>(I)) { 1142 // Special case switch statement to get formatting nice and correct... 1143 writeOperand(Operand , true); Out << ','; 1144 writeOperand(I.getOperand(1), true); Out << " ["; 1145 1146 for (unsigned op = 2, Eop = I.getNumOperands(); op < Eop; op += 2) { 1147 Out << "\n\t\t"; 1148 writeOperand(I.getOperand(op ), true); Out << ','; 1149 writeOperand(I.getOperand(op+1), true); 1150 } 1151 Out << "\n\t]"; 1152 } else if (isa<PHINode>(I)) { 1153 Out << ' '; 1154 printType(I.getType()); 1155 Out << ' '; 1156 1157 for (unsigned op = 0, Eop = I.getNumOperands(); op < Eop; op += 2) { 1158 if (op) Out << ", "; 1159 Out << '['; 1160 writeOperand(I.getOperand(op ), false); Out << ','; 1161 writeOperand(I.getOperand(op+1), false); Out << " ]"; 1162 } 1163 } else if (isa<ReturnInst>(I) && !Operand) { 1164 Out << " void"; 1165 } else if (const CallInst *CI = dyn_cast<CallInst>(&I)) { 1166 // Print the calling convention being used. 1167 switch (CI->getCallingConv()) { 1168 case CallingConv::C: break; // default 1169 case CallingConv::CSRet: Out << " csretcc"; break; 1170 case CallingConv::Fast: Out << " fastcc"; break; 1171 case CallingConv::Cold: Out << " coldcc"; break; 1172 case CallingConv::X86_StdCall: Out << "x86_stdcallcc "; break; 1173 case CallingConv::X86_FastCall: Out << "x86_fastcallcc "; break; 1174 default: Out << " cc" << CI->getCallingConv(); break; 1175 } 1176 1177 const PointerType *PTy = cast<PointerType>(Operand->getType()); 1178 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType()); 1179 const Type *RetTy = FTy->getReturnType(); 1180 1181 // If possible, print out the short form of the call instruction. We can 1182 // only do this if the first argument is a pointer to a nonvararg function, 1183 // and if the return type is not a pointer to a function. 1184 // 1185 if (!FTy->isVarArg() && 1186 (!isa<PointerType>(RetTy) || 1187 !isa<FunctionType>(cast<PointerType>(RetTy)->getElementType()))) { 1188 Out << ' '; printType(RetTy); 1189 if (FTy->getParamAttrs(0) != FunctionType::NoAttributeSet) 1190 Out << " " << FTy->getParamAttrsText(FTy->getParamAttrs(0)); 1191 writeOperand(Operand, false); 1192 } else { 1193 writeOperand(Operand, true); 1194 } 1195 Out << '('; 1196 for (unsigned op = 1, Eop = I.getNumOperands(); op < Eop; ++op) { 1197 if (op > 1) 1198 Out << ','; 1199 writeOperand(I.getOperand(op), true); 1200 if (FTy->getParamAttrs(op) != FunctionType::NoAttributeSet) 1201 Out << " " << FTy->getParamAttrsText(FTy->getParamAttrs(op)); 1202 } 1203 Out << " )"; 1204 } else if (const InvokeInst *II = dyn_cast<InvokeInst>(&I)) { 1205 const PointerType *PTy = cast<PointerType>(Operand->getType()); 1206 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType()); 1207 const Type *RetTy = FTy->getReturnType(); 1208 1209 // Print the calling convention being used. 1210 switch (II->getCallingConv()) { 1211 case CallingConv::C: break; // default 1212 case CallingConv::CSRet: Out << " csretcc"; break; 1213 case CallingConv::Fast: Out << " fastcc"; break; 1214 case CallingConv::Cold: Out << " coldcc"; break; 1215 case CallingConv::X86_StdCall: Out << "x86_stdcallcc "; break; 1216 case CallingConv::X86_FastCall: Out << "x86_fastcallcc "; break; 1217 default: Out << " cc" << II->getCallingConv(); break; 1218 } 1219 1220 // If possible, print out the short form of the invoke instruction. We can 1221 // only do this if the first argument is a pointer to a nonvararg function, 1222 // and if the return type is not a pointer to a function. 1223 // 1224 if (!FTy->isVarArg() && 1225 (!isa<PointerType>(RetTy) || 1226 !isa<FunctionType>(cast<PointerType>(RetTy)->getElementType()))) { 1227 Out << ' '; printType(RetTy); 1228 if (FTy->getParamAttrs(0) != FunctionType::NoAttributeSet) 1229 Out << " " << FTy->getParamAttrsText(FTy->getParamAttrs(0)); 1230 writeOperand(Operand, false); 1231 } else { 1232 writeOperand(Operand, true); 1233 } 1234 1235 Out << '('; 1236 for (unsigned op = 3, Eop = I.getNumOperands(); op < Eop; ++op) { 1237 if (op > 3) 1238 Out << ','; 1239 writeOperand(I.getOperand(op), true); 1240 if (FTy->getParamAttrs(op) != FunctionType::NoAttributeSet) 1241 Out << " " << FTy->getParamAttrsText(FTy->getParamAttrs(op)); 1242 } 1243 1244 Out << " )\n\t\t\tto"; 1245 writeOperand(II->getNormalDest(), true); 1246 Out << " unwind"; 1247 writeOperand(II->getUnwindDest(), true); 1248 1249 } else if (const AllocationInst *AI = dyn_cast<AllocationInst>(&I)) { 1250 Out << ' '; 1251 printType(AI->getType()->getElementType()); 1252 if (AI->isArrayAllocation()) { 1253 Out << ','; 1254 writeOperand(AI->getArraySize(), true); 1255 } 1256 if (AI->getAlignment()) { 1257 Out << ", align " << AI->getAlignment(); 1258 } 1259 } else if (isa<CastInst>(I)) { 1260 if (Operand) writeOperand(Operand, true); // Work with broken code 1261 Out << " to "; 1262 printType(I.getType()); 1263 } else if (isa<VAArgInst>(I)) { 1264 if (Operand) writeOperand(Operand, true); // Work with broken code 1265 Out << ", "; 1266 printType(I.getType()); 1267 } else if (Operand) { // Print the normal way... 1268 1269 // PrintAllTypes - Instructions who have operands of all the same type 1270 // omit the type from all but the first operand. If the instruction has 1271 // different type operands (for example br), then they are all printed. 1272 bool PrintAllTypes = false; 1273 const Type *TheType = Operand->getType(); 1274 1275 // Shift Left & Right print both types even for Ubyte LHS, and select prints 1276 // types even if all operands are bools. 1277 if (isa<ShiftInst>(I) || isa<SelectInst>(I) || isa<StoreInst>(I) || 1278 isa<ShuffleVectorInst>(I)) { 1279 PrintAllTypes = true; 1280 } else { 1281 for (unsigned i = 1, E = I.getNumOperands(); i != E; ++i) { 1282 Operand = I.getOperand(i); 1283 if (Operand->getType() != TheType) { 1284 PrintAllTypes = true; // We have differing types! Print them all! 1285 break; 1286 } 1287 } 1288 } 1289 1290 if (!PrintAllTypes) { 1291 Out << ' '; 1292 printType(TheType); 1293 } 1294 1295 for (unsigned i = 0, E = I.getNumOperands(); i != E; ++i) { 1296 if (i) Out << ','; 1297 writeOperand(I.getOperand(i), PrintAllTypes); 1298 } 1299 } 1300 1301 printInfoComment(I); 1302 Out << "\n"; 1303} 1304 1305 1306//===----------------------------------------------------------------------===// 1307// External Interface declarations 1308//===----------------------------------------------------------------------===// 1309 1310void Module::print(std::ostream &o, AssemblyAnnotationWriter *AAW) const { 1311 SlotMachine SlotTable(this); 1312 AssemblyWriter W(o, SlotTable, this, AAW); 1313 W.write(this); 1314} 1315 1316void GlobalVariable::print(std::ostream &o) const { 1317 SlotMachine SlotTable(getParent()); 1318 AssemblyWriter W(o, SlotTable, getParent(), 0); 1319 W.write(this); 1320} 1321 1322void Function::print(std::ostream &o, AssemblyAnnotationWriter *AAW) const { 1323 SlotMachine SlotTable(getParent()); 1324 AssemblyWriter W(o, SlotTable, getParent(), AAW); 1325 1326 W.write(this); 1327} 1328 1329void InlineAsm::print(std::ostream &o, AssemblyAnnotationWriter *AAW) const { 1330 WriteAsOperand(o, this, true, 0); 1331} 1332 1333void BasicBlock::print(std::ostream &o, AssemblyAnnotationWriter *AAW) const { 1334 SlotMachine SlotTable(getParent()); 1335 AssemblyWriter W(o, SlotTable, 1336 getParent() ? getParent()->getParent() : 0, AAW); 1337 W.write(this); 1338} 1339 1340void Instruction::print(std::ostream &o, AssemblyAnnotationWriter *AAW) const { 1341 const Function *F = getParent() ? getParent()->getParent() : 0; 1342 SlotMachine SlotTable(F); 1343 AssemblyWriter W(o, SlotTable, F ? F->getParent() : 0, AAW); 1344 1345 W.write(this); 1346} 1347 1348void Constant::print(std::ostream &o) const { 1349 if (this == 0) { o << "<null> constant value\n"; return; } 1350 1351 o << ' ' << getType()->getDescription() << ' '; 1352 1353 std::map<const Type *, std::string> TypeTable; 1354 WriteConstantInt(o, this, TypeTable, 0); 1355} 1356 1357void Type::print(std::ostream &o) const { 1358 if (this == 0) 1359 o << "<null Type>"; 1360 else 1361 o << getDescription(); 1362} 1363 1364void Argument::print(std::ostream &o) const { 1365 WriteAsOperand(o, this, true, getParent() ? getParent()->getParent() : 0); 1366} 1367 1368// Value::dump - allow easy printing of Values from the debugger. 1369// Located here because so much of the needed functionality is here. 1370void Value::dump() const { print(*cerr.stream()); cerr << '\n'; } 1371 1372// Type::dump - allow easy printing of Values from the debugger. 1373// Located here because so much of the needed functionality is here. 1374void Type::dump() const { print(*cerr.stream()); cerr << '\n'; } 1375 1376//===----------------------------------------------------------------------===// 1377// SlotMachine Implementation 1378//===----------------------------------------------------------------------===// 1379 1380#if 0 1381#define SC_DEBUG(X) cerr << X 1382#else 1383#define SC_DEBUG(X) 1384#endif 1385 1386// Module level constructor. Causes the contents of the Module (sans functions) 1387// to be added to the slot table. 1388SlotMachine::SlotMachine(const Module *M) 1389 : TheModule(M) ///< Saved for lazy initialization. 1390 , TheFunction(0) 1391 , FunctionProcessed(false) 1392{ 1393} 1394 1395// Function level constructor. Causes the contents of the Module and the one 1396// function provided to be added to the slot table. 1397SlotMachine::SlotMachine(const Function *F) 1398 : TheModule(F ? F->getParent() : 0) ///< Saved for lazy initialization 1399 , TheFunction(F) ///< Saved for lazy initialization 1400 , FunctionProcessed(false) 1401{ 1402} 1403 1404inline void SlotMachine::initialize(void) { 1405 if (TheModule) { 1406 processModule(); 1407 TheModule = 0; ///< Prevent re-processing next time we're called. 1408 } 1409 if (TheFunction && !FunctionProcessed) 1410 processFunction(); 1411} 1412 1413// Iterate through all the global variables, functions, and global 1414// variable initializers and create slots for them. 1415void SlotMachine::processModule() { 1416 SC_DEBUG("begin processModule!\n"); 1417 1418 // Add all of the unnamed global variables to the value table. 1419 for (Module::const_global_iterator I = TheModule->global_begin(), 1420 E = TheModule->global_end(); I != E; ++I) 1421 if (!I->hasName()) 1422 getOrCreateSlot(I); 1423 1424 // Add all the unnamed functions to the table. 1425 for (Module::const_iterator I = TheModule->begin(), E = TheModule->end(); 1426 I != E; ++I) 1427 if (!I->hasName()) 1428 getOrCreateSlot(I); 1429 1430 SC_DEBUG("end processModule!\n"); 1431} 1432 1433 1434// Process the arguments, basic blocks, and instructions of a function. 1435void SlotMachine::processFunction() { 1436 SC_DEBUG("begin processFunction!\n"); 1437 1438 // Add all the function arguments with no names. 1439 for(Function::const_arg_iterator AI = TheFunction->arg_begin(), 1440 AE = TheFunction->arg_end(); AI != AE; ++AI) 1441 if (!AI->hasName()) 1442 getOrCreateSlot(AI); 1443 1444 SC_DEBUG("Inserting Instructions:\n"); 1445 1446 // Add all of the basic blocks and instructions with no names. 1447 for (Function::const_iterator BB = TheFunction->begin(), 1448 E = TheFunction->end(); BB != E; ++BB) { 1449 if (!BB->hasName()) 1450 getOrCreateSlot(BB); 1451 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I != E; ++I) 1452 if (I->getType() != Type::VoidTy && !I->hasName()) 1453 getOrCreateSlot(I); 1454 } 1455 1456 FunctionProcessed = true; 1457 1458 SC_DEBUG("end processFunction!\n"); 1459} 1460 1461/// Clean up after incorporating a function. This is the only way to get out of 1462/// the function incorporation state that affects the 1463/// getSlot/getOrCreateSlot lock. Function incorporation state is indicated 1464/// by TheFunction != 0. 1465void SlotMachine::purgeFunction() { 1466 SC_DEBUG("begin purgeFunction!\n"); 1467 fMap.clear(); // Simply discard the function level map 1468 TheFunction = 0; 1469 FunctionProcessed = false; 1470 SC_DEBUG("end purgeFunction!\n"); 1471} 1472 1473/// Get the slot number for a value. This function will assert if you 1474/// ask for a Value that hasn't previously been inserted with getOrCreateSlot. 1475/// Types are forbidden because Type does not inherit from Value (any more). 1476int SlotMachine::getSlot(const Value *V) { 1477 assert(V && "Can't get slot for null Value"); 1478 assert(!isa<Constant>(V) || isa<GlobalValue>(V) && 1479 "Can't insert a non-GlobalValue Constant into SlotMachine"); 1480 1481 // Check for uninitialized state and do lazy initialization 1482 this->initialize(); 1483 1484 // Get the type of the value 1485 const Type* VTy = V->getType(); 1486 1487 // Find the type plane in the module map 1488 TypedPlanes::const_iterator MI = mMap.find(VTy); 1489 1490 if (TheFunction) { 1491 // Lookup the type in the function map too 1492 TypedPlanes::const_iterator FI = fMap.find(VTy); 1493 // If there is a corresponding type plane in the function map 1494 if (FI != fMap.end()) { 1495 // Lookup the Value in the function map 1496 ValueMap::const_iterator FVI = FI->second.map.find(V); 1497 // If the value doesn't exist in the function map 1498 if (FVI == FI->second.map.end()) { 1499 // Look up the value in the module map. 1500 if (MI == mMap.end()) return -1; 1501 ValueMap::const_iterator MVI = MI->second.map.find(V); 1502 // If we didn't find it, it wasn't inserted 1503 if (MVI == MI->second.map.end()) return -1; 1504 assert(MVI != MI->second.map.end() && "Value not found"); 1505 // We found it only at the module level 1506 return MVI->second; 1507 1508 // else the value exists in the function map 1509 } else { 1510 // Return the slot number as the module's contribution to 1511 // the type plane plus the index in the function's contribution 1512 // to the type plane. 1513 if (MI != mMap.end()) 1514 return MI->second.next_slot + FVI->second; 1515 else 1516 return FVI->second; 1517 } 1518 } 1519 } 1520 1521 // N.B. Can get here only if either !TheFunction or the function doesn't 1522 // have a corresponding type plane for the Value 1523 1524 // Make sure the type plane exists 1525 if (MI == mMap.end()) return -1; 1526 // Lookup the value in the module's map 1527 ValueMap::const_iterator MVI = MI->second.map.find(V); 1528 // Make sure we found it. 1529 if (MVI == MI->second.map.end()) return -1; 1530 // Return it. 1531 return MVI->second; 1532} 1533 1534 1535// Create a new slot, or return the existing slot if it is already 1536// inserted. Note that the logic here parallels getSlot but instead 1537// of asserting when the Value* isn't found, it inserts the value. 1538unsigned SlotMachine::getOrCreateSlot(const Value *V) { 1539 const Type* VTy = V->getType(); 1540 assert(VTy != Type::VoidTy && !V->hasName() && "Doesn't need a slot!"); 1541 assert(!isa<Constant>(V) || isa<GlobalValue>(V) && 1542 "Can't insert a non-GlobalValue Constant into SlotMachine"); 1543 1544 // Look up the type plane for the Value's type from the module map 1545 TypedPlanes::const_iterator MI = mMap.find(VTy); 1546 1547 if (TheFunction) { 1548 // Get the type plane for the Value's type from the function map 1549 TypedPlanes::const_iterator FI = fMap.find(VTy); 1550 // If there is a corresponding type plane in the function map 1551 if (FI != fMap.end()) { 1552 // Lookup the Value in the function map 1553 ValueMap::const_iterator FVI = FI->second.map.find(V); 1554 // If the value doesn't exist in the function map 1555 if (FVI == FI->second.map.end()) { 1556 // If there is no corresponding type plane in the module map 1557 if (MI == mMap.end()) 1558 return insertValue(V); 1559 // Look up the value in the module map 1560 ValueMap::const_iterator MVI = MI->second.map.find(V); 1561 // If we didn't find it, it wasn't inserted 1562 if (MVI == MI->second.map.end()) 1563 return insertValue(V); 1564 else 1565 // We found it only at the module level 1566 return MVI->second; 1567 1568 // else the value exists in the function map 1569 } else { 1570 if (MI == mMap.end()) 1571 return FVI->second; 1572 else 1573 // Return the slot number as the module's contribution to 1574 // the type plane plus the index in the function's contribution 1575 // to the type plane. 1576 return MI->second.next_slot + FVI->second; 1577 } 1578 1579 // else there is not a corresponding type plane in the function map 1580 } else { 1581 // If the type plane doesn't exists at the module level 1582 if (MI == mMap.end()) { 1583 return insertValue(V); 1584 // else type plane exists at the module level, examine it 1585 } else { 1586 // Look up the value in the module's map 1587 ValueMap::const_iterator MVI = MI->second.map.find(V); 1588 // If we didn't find it there either 1589 if (MVI == MI->second.map.end()) 1590 // Return the slot number as the module's contribution to 1591 // the type plane plus the index of the function map insertion. 1592 return MI->second.next_slot + insertValue(V); 1593 else 1594 return MVI->second; 1595 } 1596 } 1597 } 1598 1599 // N.B. Can only get here if TheFunction == 0 1600 1601 // If the module map's type plane is not for the Value's type 1602 if (MI != mMap.end()) { 1603 // Lookup the value in the module's map 1604 ValueMap::const_iterator MVI = MI->second.map.find(V); 1605 if (MVI != MI->second.map.end()) 1606 return MVI->second; 1607 } 1608 1609 return insertValue(V); 1610} 1611 1612 1613// Low level insert function. Minimal checking is done. This 1614// function is just for the convenience of getOrCreateSlot (above). 1615unsigned SlotMachine::insertValue(const Value *V) { 1616 assert(V && "Can't insert a null Value into SlotMachine!"); 1617 assert(!isa<Constant>(V) || isa<GlobalValue>(V) && 1618 "Can't insert a non-GlobalValue Constant into SlotMachine"); 1619 assert(V->getType() != Type::VoidTy && !V->hasName()); 1620 1621 const Type *VTy = V->getType(); 1622 unsigned DestSlot = 0; 1623 1624 if (TheFunction) { 1625 TypedPlanes::iterator I = fMap.find(VTy); 1626 if (I == fMap.end()) 1627 I = fMap.insert(std::make_pair(VTy,ValuePlane())).first; 1628 DestSlot = I->second.map[V] = I->second.next_slot++; 1629 } else { 1630 TypedPlanes::iterator I = mMap.find(VTy); 1631 if (I == mMap.end()) 1632 I = mMap.insert(std::make_pair(VTy,ValuePlane())).first; 1633 DestSlot = I->second.map[V] = I->second.next_slot++; 1634 } 1635 1636 SC_DEBUG(" Inserting value [" << VTy << "] = " << V << " slot=" << 1637 DestSlot << " ["); 1638 // G = Global, F = Function, o = other 1639 SC_DEBUG((isa<GlobalVariable>(V) ? 'G' : (isa<Function>(V) ? 'F' : 'o'))); 1640 SC_DEBUG("]\n"); 1641 return DestSlot; 1642} 1643