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