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