AsmWriter.cpp revision 8594d429e02c688d428036f8563f09572da3fbff
1//===-- AsmWriter.cpp - Printing LLVM as an assembly file -----------------===// 2// 3// The LLVM Compiler Infrastructure 4// 5// This file is distributed under the University of Illinois Open Source 6// License. See LICENSE.TXT for details. 7// 8//===----------------------------------------------------------------------===// 9// 10// This library implements the functionality defined in llvm/Assembly/Writer.h 11// 12// Note that these routines must be extremely tolerant of various errors in the 13// LLVM code, because it can be used for debugging transformations. 14// 15//===----------------------------------------------------------------------===// 16 17#include "llvm/Assembly/Writer.h" 18#include "llvm/Assembly/PrintModulePass.h" 19#include "llvm/Assembly/AssemblyAnnotationWriter.h" 20#include "llvm/LLVMContext.h" 21#include "llvm/CallingConv.h" 22#include "llvm/Constants.h" 23#include "llvm/DerivedTypes.h" 24#include "llvm/InlineAsm.h" 25#include "llvm/IntrinsicInst.h" 26#include "llvm/Operator.h" 27#include "llvm/Module.h" 28#include "llvm/ValueSymbolTable.h" 29#include "llvm/TypeSymbolTable.h" 30#include "llvm/ADT/DenseSet.h" 31#include "llvm/ADT/SmallString.h" 32#include "llvm/ADT/StringExtras.h" 33#include "llvm/ADT/STLExtras.h" 34#include "llvm/Support/CFG.h" 35#include "llvm/Support/CommandLine.h" 36#include "llvm/Support/Debug.h" 37#include "llvm/Support/Dwarf.h" 38#include "llvm/Support/ErrorHandling.h" 39#include "llvm/Support/MathExtras.h" 40#include "llvm/Support/FormattedStream.h" 41#include <algorithm> 42#include <cctype> 43using namespace llvm; 44 45static cl::opt<bool> 46EnableDebugInfoComment("enable-debug-info-comment", cl::Hidden, 47 cl::desc("Enable debug info comments")); 48 49 50// Make virtual table appear in this compilation unit. 51AssemblyAnnotationWriter::~AssemblyAnnotationWriter() {} 52 53//===----------------------------------------------------------------------===// 54// Helper Functions 55//===----------------------------------------------------------------------===// 56 57static const Module *getModuleFromVal(const Value *V) { 58 if (const Argument *MA = dyn_cast<Argument>(V)) 59 return MA->getParent() ? MA->getParent()->getParent() : 0; 60 61 if (const BasicBlock *BB = dyn_cast<BasicBlock>(V)) 62 return BB->getParent() ? BB->getParent()->getParent() : 0; 63 64 if (const Instruction *I = dyn_cast<Instruction>(V)) { 65 const Function *M = I->getParent() ? I->getParent()->getParent() : 0; 66 return M ? M->getParent() : 0; 67 } 68 69 if (const GlobalValue *GV = dyn_cast<GlobalValue>(V)) 70 return GV->getParent(); 71 return 0; 72} 73 74// PrintEscapedString - Print each character of the specified string, escaping 75// it if it is not printable or if it is an escape char. 76static void PrintEscapedString(StringRef Name, raw_ostream &Out) { 77 for (unsigned i = 0, e = Name.size(); i != e; ++i) { 78 unsigned char C = Name[i]; 79 if (isprint(C) && C != '\\' && C != '"') 80 Out << C; 81 else 82 Out << '\\' << hexdigit(C >> 4) << hexdigit(C & 0x0F); 83 } 84} 85 86enum PrefixType { 87 GlobalPrefix, 88 LabelPrefix, 89 LocalPrefix, 90 NoPrefix 91}; 92 93/// PrintLLVMName - Turn the specified name into an 'LLVM name', which is either 94/// prefixed with % (if the string only contains simple characters) or is 95/// surrounded with ""'s (if it has special chars in it). Print it out. 96static void PrintLLVMName(raw_ostream &OS, StringRef Name, PrefixType Prefix) { 97 assert(!Name.empty() && "Cannot get empty name!"); 98 switch (Prefix) { 99 default: llvm_unreachable("Bad prefix!"); 100 case NoPrefix: break; 101 case GlobalPrefix: OS << '@'; break; 102 case LabelPrefix: break; 103 case LocalPrefix: OS << '%'; break; 104 } 105 106 // Scan the name to see if it needs quotes first. 107 bool NeedsQuotes = isdigit(Name[0]); 108 if (!NeedsQuotes) { 109 for (unsigned i = 0, e = Name.size(); i != e; ++i) { 110 char C = Name[i]; 111 if (!isalnum(C) && C != '-' && C != '.' && C != '_') { 112 NeedsQuotes = true; 113 break; 114 } 115 } 116 } 117 118 // If we didn't need any quotes, just write out the name in one blast. 119 if (!NeedsQuotes) { 120 OS << Name; 121 return; 122 } 123 124 // Okay, we need quotes. Output the quotes and escape any scary characters as 125 // needed. 126 OS << '"'; 127 PrintEscapedString(Name, OS); 128 OS << '"'; 129} 130 131/// PrintLLVMName - Turn the specified name into an 'LLVM name', which is either 132/// prefixed with % (if the string only contains simple characters) or is 133/// surrounded with ""'s (if it has special chars in it). Print it out. 134static void PrintLLVMName(raw_ostream &OS, const Value *V) { 135 PrintLLVMName(OS, V->getName(), 136 isa<GlobalValue>(V) ? GlobalPrefix : LocalPrefix); 137} 138 139//===----------------------------------------------------------------------===// 140// TypePrinting Class: Type printing machinery 141//===----------------------------------------------------------------------===// 142 143/// TypePrinting - Type printing machinery. 144namespace { 145class TypePrinting { 146 DenseMap<const Type *, std::string> TypeNames; 147 TypePrinting(const TypePrinting &); // DO NOT IMPLEMENT 148 void operator=(const TypePrinting&); // DO NOT IMPLEMENT 149public: 150 TypePrinting() {} 151 ~TypePrinting() {} 152 153 void clear() { 154 TypeNames.clear(); 155 } 156 157 void print(const Type *Ty, raw_ostream &OS, bool IgnoreTopLevelName = false); 158 159 void printAtLeastOneLevel(const Type *Ty, raw_ostream &OS) { 160 print(Ty, OS, true); 161 } 162 163 /// hasTypeName - Return true if the type has a name in TypeNames, false 164 /// otherwise. 165 bool hasTypeName(const Type *Ty) const { 166 return TypeNames.count(Ty); 167 } 168 169 170 /// addTypeName - Add a name for the specified type if it doesn't already have 171 /// one. This name will be printed instead of the structural version of the 172 /// type in order to make the output more concise. 173 void addTypeName(const Type *Ty, const std::string &N) { 174 TypeNames.insert(std::make_pair(Ty, N)); 175 } 176 177private: 178 void CalcTypeName(const Type *Ty, SmallVectorImpl<const Type *> &TypeStack, 179 raw_ostream &OS, bool IgnoreTopLevelName = false); 180}; 181} // end anonymous namespace. 182 183/// CalcTypeName - Write the specified type to the specified raw_ostream, making 184/// use of type names or up references to shorten the type name where possible. 185void TypePrinting::CalcTypeName(const Type *Ty, 186 SmallVectorImpl<const Type *> &TypeStack, 187 raw_ostream &OS, bool IgnoreTopLevelName) { 188 // Check to see if the type is named. 189 if (!IgnoreTopLevelName) { 190 DenseMap<const Type *, std::string> &TM = TypeNames; 191 DenseMap<const Type *, std::string>::iterator I = TM.find(Ty); 192 if (I != TM.end()) { 193 OS << I->second; 194 return; 195 } 196 } 197 198 // Check to see if the Type is already on the stack... 199 unsigned Slot = 0, CurSize = TypeStack.size(); 200 while (Slot < CurSize && TypeStack[Slot] != Ty) ++Slot; // Scan for type 201 202 // This is another base case for the recursion. In this case, we know 203 // that we have looped back to a type that we have previously visited. 204 // Generate the appropriate upreference to handle this. 205 if (Slot < CurSize) { 206 OS << '\\' << unsigned(CurSize-Slot); // Here's the upreference 207 return; 208 } 209 210 TypeStack.push_back(Ty); // Recursive case: Add us to the stack.. 211 212 switch (Ty->getTypeID()) { 213 case Type::VoidTyID: OS << "void"; break; 214 case Type::FloatTyID: OS << "float"; break; 215 case Type::DoubleTyID: OS << "double"; break; 216 case Type::X86_FP80TyID: OS << "x86_fp80"; break; 217 case Type::FP128TyID: OS << "fp128"; break; 218 case Type::PPC_FP128TyID: OS << "ppc_fp128"; break; 219 case Type::LabelTyID: OS << "label"; break; 220 case Type::MetadataTyID: OS << "metadata"; break; 221 case Type::X86_MMXTyID: OS << "x86_mmx"; break; 222 case Type::IntegerTyID: 223 OS << 'i' << cast<IntegerType>(Ty)->getBitWidth(); 224 break; 225 226 case Type::FunctionTyID: { 227 const FunctionType *FTy = cast<FunctionType>(Ty); 228 CalcTypeName(FTy->getReturnType(), TypeStack, OS); 229 OS << " ("; 230 for (FunctionType::param_iterator I = FTy->param_begin(), 231 E = FTy->param_end(); I != E; ++I) { 232 if (I != FTy->param_begin()) 233 OS << ", "; 234 CalcTypeName(*I, TypeStack, OS); 235 } 236 if (FTy->isVarArg()) { 237 if (FTy->getNumParams()) OS << ", "; 238 OS << "..."; 239 } 240 OS << ')'; 241 break; 242 } 243 case Type::StructTyID: { 244 const StructType *STy = cast<StructType>(Ty); 245 if (STy->isPacked()) 246 OS << '<'; 247 OS << '{'; 248 for (StructType::element_iterator I = STy->element_begin(), 249 E = STy->element_end(); I != E; ++I) { 250 OS << ' '; 251 CalcTypeName(*I, TypeStack, OS); 252 if (llvm::next(I) == STy->element_end()) 253 OS << ' '; 254 else 255 OS << ','; 256 } 257 OS << '}'; 258 if (STy->isPacked()) 259 OS << '>'; 260 break; 261 } 262 case Type::PointerTyID: { 263 const PointerType *PTy = cast<PointerType>(Ty); 264 CalcTypeName(PTy->getElementType(), TypeStack, OS); 265 if (unsigned AddressSpace = PTy->getAddressSpace()) 266 OS << " addrspace(" << AddressSpace << ')'; 267 OS << '*'; 268 break; 269 } 270 case Type::ArrayTyID: { 271 const ArrayType *ATy = cast<ArrayType>(Ty); 272 OS << '[' << ATy->getNumElements() << " x "; 273 CalcTypeName(ATy->getElementType(), TypeStack, OS); 274 OS << ']'; 275 break; 276 } 277 case Type::VectorTyID: { 278 const VectorType *PTy = cast<VectorType>(Ty); 279 OS << "<" << PTy->getNumElements() << " x "; 280 CalcTypeName(PTy->getElementType(), TypeStack, OS); 281 OS << '>'; 282 break; 283 } 284 case Type::OpaqueTyID: 285 OS << "opaque"; 286 break; 287 default: 288 OS << "<unrecognized-type>"; 289 break; 290 } 291 292 TypeStack.pop_back(); // Remove self from stack. 293} 294 295/// printTypeInt - The internal guts of printing out a type that has a 296/// potentially named portion. 297/// 298void TypePrinting::print(const Type *Ty, raw_ostream &OS, 299 bool IgnoreTopLevelName) { 300 // Check to see if the type is named. 301 if (!IgnoreTopLevelName) { 302 DenseMap<const Type*, std::string>::iterator I = TypeNames.find(Ty); 303 if (I != TypeNames.end()) { 304 OS << I->second; 305 return; 306 } 307 } 308 309 // Otherwise we have a type that has not been named but is a derived type. 310 // Carefully recurse the type hierarchy to print out any contained symbolic 311 // names. 312 SmallVector<const Type *, 16> TypeStack; 313 std::string TypeName; 314 315 raw_string_ostream TypeOS(TypeName); 316 CalcTypeName(Ty, TypeStack, TypeOS, IgnoreTopLevelName); 317 OS << TypeOS.str(); 318 319 // Cache type name for later use. 320 if (!IgnoreTopLevelName) 321 TypeNames.insert(std::make_pair(Ty, TypeOS.str())); 322} 323 324namespace { 325 class TypeFinder { 326 // To avoid walking constant expressions multiple times and other IR 327 // objects, we keep several helper maps. 328 DenseSet<const Value*> VisitedConstants; 329 DenseSet<const Type*> VisitedTypes; 330 331 TypePrinting &TP; 332 std::vector<const Type*> &NumberedTypes; 333 public: 334 TypeFinder(TypePrinting &tp, std::vector<const Type*> &numberedTypes) 335 : TP(tp), NumberedTypes(numberedTypes) {} 336 337 void Run(const Module &M) { 338 // Get types from the type symbol table. This gets opaque types referened 339 // only through derived named types. 340 const TypeSymbolTable &ST = M.getTypeSymbolTable(); 341 for (TypeSymbolTable::const_iterator TI = ST.begin(), E = ST.end(); 342 TI != E; ++TI) 343 IncorporateType(TI->second); 344 345 // Get types from global variables. 346 for (Module::const_global_iterator I = M.global_begin(), 347 E = M.global_end(); I != E; ++I) { 348 IncorporateType(I->getType()); 349 if (I->hasInitializer()) 350 IncorporateValue(I->getInitializer()); 351 } 352 353 // Get types from aliases. 354 for (Module::const_alias_iterator I = M.alias_begin(), 355 E = M.alias_end(); I != E; ++I) { 356 IncorporateType(I->getType()); 357 IncorporateValue(I->getAliasee()); 358 } 359 360 // Get types from functions. 361 for (Module::const_iterator FI = M.begin(), E = M.end(); FI != E; ++FI) { 362 IncorporateType(FI->getType()); 363 364 for (Function::const_iterator BB = FI->begin(), E = FI->end(); 365 BB != E;++BB) 366 for (BasicBlock::const_iterator II = BB->begin(), 367 E = BB->end(); II != E; ++II) { 368 const Instruction &I = *II; 369 // Incorporate the type of the instruction and all its operands. 370 IncorporateType(I.getType()); 371 for (User::const_op_iterator OI = I.op_begin(), OE = I.op_end(); 372 OI != OE; ++OI) 373 IncorporateValue(*OI); 374 } 375 } 376 } 377 378 private: 379 void IncorporateType(const Type *Ty) { 380 // Check to see if we're already visited this type. 381 if (!VisitedTypes.insert(Ty).second) 382 return; 383 384 // If this is a structure or opaque type, add a name for the type. 385 if (((Ty->isStructTy() && cast<StructType>(Ty)->getNumElements()) 386 || Ty->isOpaqueTy()) && !TP.hasTypeName(Ty)) { 387 TP.addTypeName(Ty, "%"+utostr(unsigned(NumberedTypes.size()))); 388 NumberedTypes.push_back(Ty); 389 } 390 391 // Recursively walk all contained types. 392 for (Type::subtype_iterator I = Ty->subtype_begin(), 393 E = Ty->subtype_end(); I != E; ++I) 394 IncorporateType(*I); 395 } 396 397 /// IncorporateValue - This method is used to walk operand lists finding 398 /// types hiding in constant expressions and other operands that won't be 399 /// walked in other ways. GlobalValues, basic blocks, instructions, and 400 /// inst operands are all explicitly enumerated. 401 void IncorporateValue(const Value *V) { 402 if (V == 0 || !isa<Constant>(V) || isa<GlobalValue>(V)) return; 403 404 // Already visited? 405 if (!VisitedConstants.insert(V).second) 406 return; 407 408 // Check this type. 409 IncorporateType(V->getType()); 410 411 // Look in operands for types. 412 const Constant *C = cast<Constant>(V); 413 for (Constant::const_op_iterator I = C->op_begin(), 414 E = C->op_end(); I != E;++I) 415 IncorporateValue(*I); 416 } 417 }; 418} // end anonymous namespace 419 420 421/// AddModuleTypesToPrinter - Add all of the symbolic type names for types in 422/// the specified module to the TypePrinter and all numbered types to it and the 423/// NumberedTypes table. 424static void AddModuleTypesToPrinter(TypePrinting &TP, 425 std::vector<const Type*> &NumberedTypes, 426 const Module *M) { 427 if (M == 0) return; 428 429 // If the module has a symbol table, take all global types and stuff their 430 // names into the TypeNames map. 431 const TypeSymbolTable &ST = M->getTypeSymbolTable(); 432 for (TypeSymbolTable::const_iterator TI = ST.begin(), E = ST.end(); 433 TI != E; ++TI) { 434 const Type *Ty = cast<Type>(TI->second); 435 436 // As a heuristic, don't insert pointer to primitive types, because 437 // they are used too often to have a single useful name. 438 if (const PointerType *PTy = dyn_cast<PointerType>(Ty)) { 439 const Type *PETy = PTy->getElementType(); 440 if ((PETy->isPrimitiveType() || PETy->isIntegerTy()) && 441 !PETy->isOpaqueTy()) 442 continue; 443 } 444 445 // Likewise don't insert primitives either. 446 if (Ty->isIntegerTy() || Ty->isPrimitiveType()) 447 continue; 448 449 // Get the name as a string and insert it into TypeNames. 450 std::string NameStr; 451 raw_string_ostream NameROS(NameStr); 452 formatted_raw_ostream NameOS(NameROS); 453 PrintLLVMName(NameOS, TI->first, LocalPrefix); 454 NameOS.flush(); 455 TP.addTypeName(Ty, NameStr); 456 } 457 458 // Walk the entire module to find references to unnamed structure and opaque 459 // types. This is required for correctness by opaque types (because multiple 460 // uses of an unnamed opaque type needs to be referred to by the same ID) and 461 // it shrinks complex recursive structure types substantially in some cases. 462 TypeFinder(TP, NumberedTypes).Run(*M); 463} 464 465 466/// WriteTypeSymbolic - This attempts to write the specified type as a symbolic 467/// type, iff there is an entry in the modules symbol table for the specified 468/// type or one of it's component types. 469/// 470void llvm::WriteTypeSymbolic(raw_ostream &OS, const Type *Ty, const Module *M) { 471 TypePrinting Printer; 472 std::vector<const Type*> NumberedTypes; 473 AddModuleTypesToPrinter(Printer, NumberedTypes, M); 474 Printer.print(Ty, OS); 475} 476 477//===----------------------------------------------------------------------===// 478// SlotTracker Class: Enumerate slot numbers for unnamed values 479//===----------------------------------------------------------------------===// 480 481namespace { 482 483/// This class provides computation of slot numbers for LLVM Assembly writing. 484/// 485class SlotTracker { 486public: 487 /// ValueMap - A mapping of Values to slot numbers. 488 typedef DenseMap<const Value*, unsigned> ValueMap; 489 490private: 491 /// TheModule - The module for which we are holding slot numbers. 492 const Module* TheModule; 493 494 /// TheFunction - The function for which we are holding slot numbers. 495 const Function* TheFunction; 496 bool FunctionProcessed; 497 498 /// mMap - The TypePlanes map for the module level data. 499 ValueMap mMap; 500 unsigned mNext; 501 502 /// fMap - The TypePlanes map for the function level data. 503 ValueMap fMap; 504 unsigned fNext; 505 506 /// mdnMap - Map for MDNodes. 507 DenseMap<const MDNode*, unsigned> mdnMap; 508 unsigned mdnNext; 509public: 510 /// Construct from a module 511 explicit SlotTracker(const Module *M); 512 /// Construct from a function, starting out in incorp state. 513 explicit SlotTracker(const Function *F); 514 515 /// Return the slot number of the specified value in it's type 516 /// plane. If something is not in the SlotTracker, return -1. 517 int getLocalSlot(const Value *V); 518 int getGlobalSlot(const GlobalValue *V); 519 int getMetadataSlot(const MDNode *N); 520 521 /// If you'd like to deal with a function instead of just a module, use 522 /// this method to get its data into the SlotTracker. 523 void incorporateFunction(const Function *F) { 524 TheFunction = F; 525 FunctionProcessed = false; 526 } 527 528 /// After calling incorporateFunction, use this method to remove the 529 /// most recently incorporated function from the SlotTracker. This 530 /// will reset the state of the machine back to just the module contents. 531 void purgeFunction(); 532 533 /// MDNode map iterators. 534 typedef DenseMap<const MDNode*, unsigned>::iterator mdn_iterator; 535 mdn_iterator mdn_begin() { return mdnMap.begin(); } 536 mdn_iterator mdn_end() { return mdnMap.end(); } 537 unsigned mdn_size() const { return mdnMap.size(); } 538 bool mdn_empty() const { return mdnMap.empty(); } 539 540 /// This function does the actual initialization. 541 inline void initialize(); 542 543 // Implementation Details 544private: 545 /// CreateModuleSlot - Insert the specified GlobalValue* into the slot table. 546 void CreateModuleSlot(const GlobalValue *V); 547 548 /// CreateMetadataSlot - Insert the specified MDNode* into the slot table. 549 void CreateMetadataSlot(const MDNode *N); 550 551 /// CreateFunctionSlot - Insert the specified Value* into the slot table. 552 void CreateFunctionSlot(const Value *V); 553 554 /// Add all of the module level global variables (and their initializers) 555 /// and function declarations, but not the contents of those functions. 556 void processModule(); 557 558 /// Add all of the functions arguments, basic blocks, and instructions. 559 void processFunction(); 560 561 SlotTracker(const SlotTracker &); // DO NOT IMPLEMENT 562 void operator=(const SlotTracker &); // DO NOT IMPLEMENT 563}; 564 565} // end anonymous namespace 566 567 568static SlotTracker *createSlotTracker(const Value *V) { 569 if (const Argument *FA = dyn_cast<Argument>(V)) 570 return new SlotTracker(FA->getParent()); 571 572 if (const Instruction *I = dyn_cast<Instruction>(V)) 573 return new SlotTracker(I->getParent()->getParent()); 574 575 if (const BasicBlock *BB = dyn_cast<BasicBlock>(V)) 576 return new SlotTracker(BB->getParent()); 577 578 if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(V)) 579 return new SlotTracker(GV->getParent()); 580 581 if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(V)) 582 return new SlotTracker(GA->getParent()); 583 584 if (const Function *Func = dyn_cast<Function>(V)) 585 return new SlotTracker(Func); 586 587 if (const MDNode *MD = dyn_cast<MDNode>(V)) { 588 if (!MD->isFunctionLocal()) 589 return new SlotTracker(MD->getFunction()); 590 591 return new SlotTracker((Function *)0); 592 } 593 594 return 0; 595} 596 597#if 0 598#define ST_DEBUG(X) dbgs() << X 599#else 600#define ST_DEBUG(X) 601#endif 602 603// Module level constructor. Causes the contents of the Module (sans functions) 604// to be added to the slot table. 605SlotTracker::SlotTracker(const Module *M) 606 : TheModule(M), TheFunction(0), FunctionProcessed(false), 607 mNext(0), fNext(0), mdnNext(0) { 608} 609 610// Function level constructor. Causes the contents of the Module and the one 611// function provided to be added to the slot table. 612SlotTracker::SlotTracker(const Function *F) 613 : TheModule(F ? F->getParent() : 0), TheFunction(F), FunctionProcessed(false), 614 mNext(0), fNext(0), mdnNext(0) { 615} 616 617inline void SlotTracker::initialize() { 618 if (TheModule) { 619 processModule(); 620 TheModule = 0; ///< Prevent re-processing next time we're called. 621 } 622 623 if (TheFunction && !FunctionProcessed) 624 processFunction(); 625} 626 627// Iterate through all the global variables, functions, and global 628// variable initializers and create slots for them. 629void SlotTracker::processModule() { 630 ST_DEBUG("begin processModule!\n"); 631 632 // Add all of the unnamed global variables to the value table. 633 for (Module::const_global_iterator I = TheModule->global_begin(), 634 E = TheModule->global_end(); I != E; ++I) { 635 if (!I->hasName()) 636 CreateModuleSlot(I); 637 } 638 639 // Add metadata used by named metadata. 640 for (Module::const_named_metadata_iterator 641 I = TheModule->named_metadata_begin(), 642 E = TheModule->named_metadata_end(); I != E; ++I) { 643 const NamedMDNode *NMD = I; 644 for (unsigned i = 0, e = NMD->getNumOperands(); i != e; ++i) 645 CreateMetadataSlot(NMD->getOperand(i)); 646 } 647 648 // Add all the unnamed functions to the table. 649 for (Module::const_iterator I = TheModule->begin(), E = TheModule->end(); 650 I != E; ++I) 651 if (!I->hasName()) 652 CreateModuleSlot(I); 653 654 ST_DEBUG("end processModule!\n"); 655} 656 657// Process the arguments, basic blocks, and instructions of a function. 658void SlotTracker::processFunction() { 659 ST_DEBUG("begin processFunction!\n"); 660 fNext = 0; 661 662 // Add all the function arguments with no names. 663 for(Function::const_arg_iterator AI = TheFunction->arg_begin(), 664 AE = TheFunction->arg_end(); AI != AE; ++AI) 665 if (!AI->hasName()) 666 CreateFunctionSlot(AI); 667 668 ST_DEBUG("Inserting Instructions:\n"); 669 670 SmallVector<std::pair<unsigned, MDNode*>, 4> MDForInst; 671 672 // Add all of the basic blocks and instructions with no names. 673 for (Function::const_iterator BB = TheFunction->begin(), 674 E = TheFunction->end(); BB != E; ++BB) { 675 if (!BB->hasName()) 676 CreateFunctionSlot(BB); 677 678 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I != E; 679 ++I) { 680 if (!I->getType()->isVoidTy() && !I->hasName()) 681 CreateFunctionSlot(I); 682 683 // Intrinsics can directly use metadata. We allow direct calls to any 684 // llvm.foo function here, because the target may not be linked into the 685 // optimizer. 686 if (const CallInst *CI = dyn_cast<CallInst>(I)) { 687 if (Function *F = CI->getCalledFunction()) 688 if (F->getName().startswith("llvm.")) 689 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) 690 if (MDNode *N = dyn_cast_or_null<MDNode>(I->getOperand(i))) 691 CreateMetadataSlot(N); 692 } 693 694 // Process metadata attached with this instruction. 695 I->getAllMetadata(MDForInst); 696 for (unsigned i = 0, e = MDForInst.size(); i != e; ++i) 697 CreateMetadataSlot(MDForInst[i].second); 698 MDForInst.clear(); 699 } 700 } 701 702 FunctionProcessed = true; 703 704 ST_DEBUG("end processFunction!\n"); 705} 706 707/// Clean up after incorporating a function. This is the only way to get out of 708/// the function incorporation state that affects get*Slot/Create*Slot. Function 709/// incorporation state is indicated by TheFunction != 0. 710void SlotTracker::purgeFunction() { 711 ST_DEBUG("begin purgeFunction!\n"); 712 fMap.clear(); // Simply discard the function level map 713 TheFunction = 0; 714 FunctionProcessed = false; 715 ST_DEBUG("end purgeFunction!\n"); 716} 717 718/// getGlobalSlot - Get the slot number of a global value. 719int SlotTracker::getGlobalSlot(const GlobalValue *V) { 720 // Check for uninitialized state and do lazy initialization. 721 initialize(); 722 723 // Find the type plane in the module map 724 ValueMap::iterator MI = mMap.find(V); 725 return MI == mMap.end() ? -1 : (int)MI->second; 726} 727 728/// getMetadataSlot - Get the slot number of a MDNode. 729int SlotTracker::getMetadataSlot(const MDNode *N) { 730 // Check for uninitialized state and do lazy initialization. 731 initialize(); 732 733 // Find the type plane in the module map 734 mdn_iterator MI = mdnMap.find(N); 735 return MI == mdnMap.end() ? -1 : (int)MI->second; 736} 737 738 739/// getLocalSlot - Get the slot number for a value that is local to a function. 740int SlotTracker::getLocalSlot(const Value *V) { 741 assert(!isa<Constant>(V) && "Can't get a constant or global slot with this!"); 742 743 // Check for uninitialized state and do lazy initialization. 744 initialize(); 745 746 ValueMap::iterator FI = fMap.find(V); 747 return FI == fMap.end() ? -1 : (int)FI->second; 748} 749 750 751/// CreateModuleSlot - Insert the specified GlobalValue* into the slot table. 752void SlotTracker::CreateModuleSlot(const GlobalValue *V) { 753 assert(V && "Can't insert a null Value into SlotTracker!"); 754 assert(!V->getType()->isVoidTy() && "Doesn't need a slot!"); 755 assert(!V->hasName() && "Doesn't need a slot!"); 756 757 unsigned DestSlot = mNext++; 758 mMap[V] = DestSlot; 759 760 ST_DEBUG(" Inserting value [" << V->getType() << "] = " << V << " slot=" << 761 DestSlot << " ["); 762 // G = Global, F = Function, A = Alias, o = other 763 ST_DEBUG((isa<GlobalVariable>(V) ? 'G' : 764 (isa<Function>(V) ? 'F' : 765 (isa<GlobalAlias>(V) ? 'A' : 'o'))) << "]\n"); 766} 767 768/// CreateSlot - Create a new slot for the specified value if it has no name. 769void SlotTracker::CreateFunctionSlot(const Value *V) { 770 assert(!V->getType()->isVoidTy() && !V->hasName() && "Doesn't need a slot!"); 771 772 unsigned DestSlot = fNext++; 773 fMap[V] = DestSlot; 774 775 // G = Global, F = Function, o = other 776 ST_DEBUG(" Inserting value [" << V->getType() << "] = " << V << " slot=" << 777 DestSlot << " [o]\n"); 778} 779 780/// CreateModuleSlot - Insert the specified MDNode* into the slot table. 781void SlotTracker::CreateMetadataSlot(const MDNode *N) { 782 assert(N && "Can't insert a null Value into SlotTracker!"); 783 784 // Don't insert if N is a function-local metadata, these are always printed 785 // inline. 786 if (!N->isFunctionLocal()) { 787 mdn_iterator I = mdnMap.find(N); 788 if (I != mdnMap.end()) 789 return; 790 791 unsigned DestSlot = mdnNext++; 792 mdnMap[N] = DestSlot; 793 } 794 795 // Recursively add any MDNodes referenced by operands. 796 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) 797 if (const MDNode *Op = dyn_cast_or_null<MDNode>(N->getOperand(i))) 798 CreateMetadataSlot(Op); 799} 800 801//===----------------------------------------------------------------------===// 802// AsmWriter Implementation 803//===----------------------------------------------------------------------===// 804 805static void WriteAsOperandInternal(raw_ostream &Out, const Value *V, 806 TypePrinting *TypePrinter, 807 SlotTracker *Machine, 808 const Module *Context); 809 810 811 812static const char *getPredicateText(unsigned predicate) { 813 const char * pred = "unknown"; 814 switch (predicate) { 815 case FCmpInst::FCMP_FALSE: pred = "false"; break; 816 case FCmpInst::FCMP_OEQ: pred = "oeq"; break; 817 case FCmpInst::FCMP_OGT: pred = "ogt"; break; 818 case FCmpInst::FCMP_OGE: pred = "oge"; break; 819 case FCmpInst::FCMP_OLT: pred = "olt"; break; 820 case FCmpInst::FCMP_OLE: pred = "ole"; break; 821 case FCmpInst::FCMP_ONE: pred = "one"; break; 822 case FCmpInst::FCMP_ORD: pred = "ord"; break; 823 case FCmpInst::FCMP_UNO: pred = "uno"; break; 824 case FCmpInst::FCMP_UEQ: pred = "ueq"; break; 825 case FCmpInst::FCMP_UGT: pred = "ugt"; break; 826 case FCmpInst::FCMP_UGE: pred = "uge"; break; 827 case FCmpInst::FCMP_ULT: pred = "ult"; break; 828 case FCmpInst::FCMP_ULE: pred = "ule"; break; 829 case FCmpInst::FCMP_UNE: pred = "une"; break; 830 case FCmpInst::FCMP_TRUE: pred = "true"; break; 831 case ICmpInst::ICMP_EQ: pred = "eq"; break; 832 case ICmpInst::ICMP_NE: pred = "ne"; break; 833 case ICmpInst::ICMP_SGT: pred = "sgt"; break; 834 case ICmpInst::ICMP_SGE: pred = "sge"; break; 835 case ICmpInst::ICMP_SLT: pred = "slt"; break; 836 case ICmpInst::ICMP_SLE: pred = "sle"; break; 837 case ICmpInst::ICMP_UGT: pred = "ugt"; break; 838 case ICmpInst::ICMP_UGE: pred = "uge"; break; 839 case ICmpInst::ICMP_ULT: pred = "ult"; break; 840 case ICmpInst::ICMP_ULE: pred = "ule"; break; 841 } 842 return pred; 843} 844 845 846static void WriteOptimizationInfo(raw_ostream &Out, const User *U) { 847 if (const OverflowingBinaryOperator *OBO = 848 dyn_cast<OverflowingBinaryOperator>(U)) { 849 if (OBO->hasNoUnsignedWrap()) 850 Out << " nuw"; 851 if (OBO->hasNoSignedWrap()) 852 Out << " nsw"; 853 } else if (const PossiblyExactOperator *Div = 854 dyn_cast<PossiblyExactOperator>(U)) { 855 if (Div->isExact()) 856 Out << " exact"; 857 } else if (const GEPOperator *GEP = dyn_cast<GEPOperator>(U)) { 858 if (GEP->isInBounds()) 859 Out << " inbounds"; 860 } 861} 862 863static void WriteConstantInternal(raw_ostream &Out, const Constant *CV, 864 TypePrinting &TypePrinter, 865 SlotTracker *Machine, 866 const Module *Context) { 867 if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV)) { 868 if (CI->getType()->isIntegerTy(1)) { 869 Out << (CI->getZExtValue() ? "true" : "false"); 870 return; 871 } 872 Out << CI->getValue(); 873 return; 874 } 875 876 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CV)) { 877 if (&CFP->getValueAPF().getSemantics() == &APFloat::IEEEdouble || 878 &CFP->getValueAPF().getSemantics() == &APFloat::IEEEsingle) { 879 // We would like to output the FP constant value in exponential notation, 880 // but we cannot do this if doing so will lose precision. Check here to 881 // make sure that we only output it in exponential format if we can parse 882 // the value back and get the same value. 883 // 884 bool ignored; 885 bool isDouble = &CFP->getValueAPF().getSemantics()==&APFloat::IEEEdouble; 886 double Val = isDouble ? CFP->getValueAPF().convertToDouble() : 887 CFP->getValueAPF().convertToFloat(); 888 SmallString<128> StrVal; 889 raw_svector_ostream(StrVal) << Val; 890 891 // Check to make sure that the stringized number is not some string like 892 // "Inf" or NaN, that atof will accept, but the lexer will not. Check 893 // that the string matches the "[-+]?[0-9]" regex. 894 // 895 if ((StrVal[0] >= '0' && StrVal[0] <= '9') || 896 ((StrVal[0] == '-' || StrVal[0] == '+') && 897 (StrVal[1] >= '0' && StrVal[1] <= '9'))) { 898 // Reparse stringized version! 899 if (atof(StrVal.c_str()) == Val) { 900 Out << StrVal.str(); 901 return; 902 } 903 } 904 // Otherwise we could not reparse it to exactly the same value, so we must 905 // output the string in hexadecimal format! Note that loading and storing 906 // floating point types changes the bits of NaNs on some hosts, notably 907 // x86, so we must not use these types. 908 assert(sizeof(double) == sizeof(uint64_t) && 909 "assuming that double is 64 bits!"); 910 char Buffer[40]; 911 APFloat apf = CFP->getValueAPF(); 912 // Floats are represented in ASCII IR as double, convert. 913 if (!isDouble) 914 apf.convert(APFloat::IEEEdouble, APFloat::rmNearestTiesToEven, 915 &ignored); 916 Out << "0x" << 917 utohex_buffer(uint64_t(apf.bitcastToAPInt().getZExtValue()), 918 Buffer+40); 919 return; 920 } 921 922 // Some form of long double. These appear as a magic letter identifying 923 // the type, then a fixed number of hex digits. 924 Out << "0x"; 925 if (&CFP->getValueAPF().getSemantics() == &APFloat::x87DoubleExtended) { 926 Out << 'K'; 927 // api needed to prevent premature destruction 928 APInt api = CFP->getValueAPF().bitcastToAPInt(); 929 const uint64_t* p = api.getRawData(); 930 uint64_t word = p[1]; 931 int shiftcount=12; 932 int width = api.getBitWidth(); 933 for (int j=0; j<width; j+=4, shiftcount-=4) { 934 unsigned int nibble = (word>>shiftcount) & 15; 935 if (nibble < 10) 936 Out << (unsigned char)(nibble + '0'); 937 else 938 Out << (unsigned char)(nibble - 10 + 'A'); 939 if (shiftcount == 0 && j+4 < width) { 940 word = *p; 941 shiftcount = 64; 942 if (width-j-4 < 64) 943 shiftcount = width-j-4; 944 } 945 } 946 return; 947 } else if (&CFP->getValueAPF().getSemantics() == &APFloat::IEEEquad) 948 Out << 'L'; 949 else if (&CFP->getValueAPF().getSemantics() == &APFloat::PPCDoubleDouble) 950 Out << 'M'; 951 else 952 llvm_unreachable("Unsupported floating point type"); 953 // api needed to prevent premature destruction 954 APInt api = CFP->getValueAPF().bitcastToAPInt(); 955 const uint64_t* p = api.getRawData(); 956 uint64_t word = *p; 957 int shiftcount=60; 958 int width = api.getBitWidth(); 959 for (int j=0; j<width; j+=4, shiftcount-=4) { 960 unsigned int nibble = (word>>shiftcount) & 15; 961 if (nibble < 10) 962 Out << (unsigned char)(nibble + '0'); 963 else 964 Out << (unsigned char)(nibble - 10 + 'A'); 965 if (shiftcount == 0 && j+4 < width) { 966 word = *(++p); 967 shiftcount = 64; 968 if (width-j-4 < 64) 969 shiftcount = width-j-4; 970 } 971 } 972 return; 973 } 974 975 if (isa<ConstantAggregateZero>(CV)) { 976 Out << "zeroinitializer"; 977 return; 978 } 979 980 if (const BlockAddress *BA = dyn_cast<BlockAddress>(CV)) { 981 Out << "blockaddress("; 982 WriteAsOperandInternal(Out, BA->getFunction(), &TypePrinter, Machine, 983 Context); 984 Out << ", "; 985 WriteAsOperandInternal(Out, BA->getBasicBlock(), &TypePrinter, Machine, 986 Context); 987 Out << ")"; 988 return; 989 } 990 991 if (const ConstantArray *CA = dyn_cast<ConstantArray>(CV)) { 992 // As a special case, print the array as a string if it is an array of 993 // i8 with ConstantInt values. 994 // 995 const Type *ETy = CA->getType()->getElementType(); 996 if (CA->isString()) { 997 Out << "c\""; 998 PrintEscapedString(CA->getAsString(), Out); 999 Out << '"'; 1000 } else { // Cannot output in string format... 1001 Out << '['; 1002 if (CA->getNumOperands()) { 1003 TypePrinter.print(ETy, Out); 1004 Out << ' '; 1005 WriteAsOperandInternal(Out, CA->getOperand(0), 1006 &TypePrinter, Machine, 1007 Context); 1008 for (unsigned i = 1, e = CA->getNumOperands(); i != e; ++i) { 1009 Out << ", "; 1010 TypePrinter.print(ETy, Out); 1011 Out << ' '; 1012 WriteAsOperandInternal(Out, CA->getOperand(i), &TypePrinter, Machine, 1013 Context); 1014 } 1015 } 1016 Out << ']'; 1017 } 1018 return; 1019 } 1020 1021 if (const ConstantStruct *CS = dyn_cast<ConstantStruct>(CV)) { 1022 if (CS->getType()->isPacked()) 1023 Out << '<'; 1024 Out << '{'; 1025 unsigned N = CS->getNumOperands(); 1026 if (N) { 1027 Out << ' '; 1028 TypePrinter.print(CS->getOperand(0)->getType(), Out); 1029 Out << ' '; 1030 1031 WriteAsOperandInternal(Out, CS->getOperand(0), &TypePrinter, Machine, 1032 Context); 1033 1034 for (unsigned i = 1; i < N; i++) { 1035 Out << ", "; 1036 TypePrinter.print(CS->getOperand(i)->getType(), Out); 1037 Out << ' '; 1038 1039 WriteAsOperandInternal(Out, CS->getOperand(i), &TypePrinter, Machine, 1040 Context); 1041 } 1042 Out << ' '; 1043 } 1044 1045 Out << '}'; 1046 if (CS->getType()->isPacked()) 1047 Out << '>'; 1048 return; 1049 } 1050 1051 if (const ConstantVector *CP = dyn_cast<ConstantVector>(CV)) { 1052 const Type *ETy = CP->getType()->getElementType(); 1053 assert(CP->getNumOperands() > 0 && 1054 "Number of operands for a PackedConst must be > 0"); 1055 Out << '<'; 1056 TypePrinter.print(ETy, Out); 1057 Out << ' '; 1058 WriteAsOperandInternal(Out, CP->getOperand(0), &TypePrinter, Machine, 1059 Context); 1060 for (unsigned i = 1, e = CP->getNumOperands(); i != e; ++i) { 1061 Out << ", "; 1062 TypePrinter.print(ETy, Out); 1063 Out << ' '; 1064 WriteAsOperandInternal(Out, CP->getOperand(i), &TypePrinter, Machine, 1065 Context); 1066 } 1067 Out << '>'; 1068 return; 1069 } 1070 1071 if (isa<ConstantPointerNull>(CV)) { 1072 Out << "null"; 1073 return; 1074 } 1075 1076 if (isa<UndefValue>(CV)) { 1077 Out << "undef"; 1078 return; 1079 } 1080 1081 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV)) { 1082 Out << CE->getOpcodeName(); 1083 WriteOptimizationInfo(Out, CE); 1084 if (CE->isCompare()) 1085 Out << ' ' << getPredicateText(CE->getPredicate()); 1086 Out << " ("; 1087 1088 for (User::const_op_iterator OI=CE->op_begin(); OI != CE->op_end(); ++OI) { 1089 TypePrinter.print((*OI)->getType(), Out); 1090 Out << ' '; 1091 WriteAsOperandInternal(Out, *OI, &TypePrinter, Machine, Context); 1092 if (OI+1 != CE->op_end()) 1093 Out << ", "; 1094 } 1095 1096 if (CE->hasIndices()) { 1097 ArrayRef<unsigned> Indices = CE->getIndices(); 1098 for (unsigned i = 0, e = Indices.size(); i != e; ++i) 1099 Out << ", " << Indices[i]; 1100 } 1101 1102 if (CE->isCast()) { 1103 Out << " to "; 1104 TypePrinter.print(CE->getType(), Out); 1105 } 1106 1107 Out << ')'; 1108 return; 1109 } 1110 1111 Out << "<placeholder or erroneous Constant>"; 1112} 1113 1114static void WriteMDNodeBodyInternal(raw_ostream &Out, const MDNode *Node, 1115 TypePrinting *TypePrinter, 1116 SlotTracker *Machine, 1117 const Module *Context) { 1118 Out << "!{"; 1119 for (unsigned mi = 0, me = Node->getNumOperands(); mi != me; ++mi) { 1120 const Value *V = Node->getOperand(mi); 1121 if (V == 0) 1122 Out << "null"; 1123 else { 1124 TypePrinter->print(V->getType(), Out); 1125 Out << ' '; 1126 WriteAsOperandInternal(Out, Node->getOperand(mi), 1127 TypePrinter, Machine, Context); 1128 } 1129 if (mi + 1 != me) 1130 Out << ", "; 1131 } 1132 1133 Out << "}"; 1134} 1135 1136 1137/// WriteAsOperand - Write the name of the specified value out to the specified 1138/// ostream. This can be useful when you just want to print int %reg126, not 1139/// the whole instruction that generated it. 1140/// 1141static void WriteAsOperandInternal(raw_ostream &Out, const Value *V, 1142 TypePrinting *TypePrinter, 1143 SlotTracker *Machine, 1144 const Module *Context) { 1145 if (V->hasName()) { 1146 PrintLLVMName(Out, V); 1147 return; 1148 } 1149 1150 const Constant *CV = dyn_cast<Constant>(V); 1151 if (CV && !isa<GlobalValue>(CV)) { 1152 assert(TypePrinter && "Constants require TypePrinting!"); 1153 WriteConstantInternal(Out, CV, *TypePrinter, Machine, Context); 1154 return; 1155 } 1156 1157 if (const InlineAsm *IA = dyn_cast<InlineAsm>(V)) { 1158 Out << "asm "; 1159 if (IA->hasSideEffects()) 1160 Out << "sideeffect "; 1161 if (IA->isAlignStack()) 1162 Out << "alignstack "; 1163 Out << '"'; 1164 PrintEscapedString(IA->getAsmString(), Out); 1165 Out << "\", \""; 1166 PrintEscapedString(IA->getConstraintString(), Out); 1167 Out << '"'; 1168 return; 1169 } 1170 1171 if (const MDNode *N = dyn_cast<MDNode>(V)) { 1172 if (N->isFunctionLocal()) { 1173 // Print metadata inline, not via slot reference number. 1174 WriteMDNodeBodyInternal(Out, N, TypePrinter, Machine, Context); 1175 return; 1176 } 1177 1178 if (!Machine) { 1179 if (N->isFunctionLocal()) 1180 Machine = new SlotTracker(N->getFunction()); 1181 else 1182 Machine = new SlotTracker(Context); 1183 } 1184 int Slot = Machine->getMetadataSlot(N); 1185 if (Slot == -1) 1186 Out << "<badref>"; 1187 else 1188 Out << '!' << Slot; 1189 return; 1190 } 1191 1192 if (const MDString *MDS = dyn_cast<MDString>(V)) { 1193 Out << "!\""; 1194 PrintEscapedString(MDS->getString(), Out); 1195 Out << '"'; 1196 return; 1197 } 1198 1199 if (V->getValueID() == Value::PseudoSourceValueVal || 1200 V->getValueID() == Value::FixedStackPseudoSourceValueVal) { 1201 V->print(Out); 1202 return; 1203 } 1204 1205 char Prefix = '%'; 1206 int Slot; 1207 if (Machine) { 1208 if (const GlobalValue *GV = dyn_cast<GlobalValue>(V)) { 1209 Slot = Machine->getGlobalSlot(GV); 1210 Prefix = '@'; 1211 } else { 1212 Slot = Machine->getLocalSlot(V); 1213 } 1214 } else { 1215 Machine = createSlotTracker(V); 1216 if (Machine) { 1217 if (const GlobalValue *GV = dyn_cast<GlobalValue>(V)) { 1218 Slot = Machine->getGlobalSlot(GV); 1219 Prefix = '@'; 1220 } else { 1221 Slot = Machine->getLocalSlot(V); 1222 } 1223 delete Machine; 1224 } else { 1225 Slot = -1; 1226 } 1227 } 1228 1229 if (Slot != -1) 1230 Out << Prefix << Slot; 1231 else 1232 Out << "<badref>"; 1233} 1234 1235void llvm::WriteAsOperand(raw_ostream &Out, const Value *V, 1236 bool PrintType, const Module *Context) { 1237 1238 // Fast path: Don't construct and populate a TypePrinting object if we 1239 // won't be needing any types printed. 1240 if (!PrintType && 1241 ((!isa<Constant>(V) && !isa<MDNode>(V)) || 1242 V->hasName() || isa<GlobalValue>(V))) { 1243 WriteAsOperandInternal(Out, V, 0, 0, Context); 1244 return; 1245 } 1246 1247 if (Context == 0) Context = getModuleFromVal(V); 1248 1249 TypePrinting TypePrinter; 1250 std::vector<const Type*> NumberedTypes; 1251 AddModuleTypesToPrinter(TypePrinter, NumberedTypes, Context); 1252 if (PrintType) { 1253 TypePrinter.print(V->getType(), Out); 1254 Out << ' '; 1255 } 1256 1257 WriteAsOperandInternal(Out, V, &TypePrinter, 0, Context); 1258} 1259 1260namespace { 1261 1262class AssemblyWriter { 1263 formatted_raw_ostream &Out; 1264 SlotTracker &Machine; 1265 const Module *TheModule; 1266 TypePrinting TypePrinter; 1267 AssemblyAnnotationWriter *AnnotationWriter; 1268 std::vector<const Type*> NumberedTypes; 1269 1270public: 1271 inline AssemblyWriter(formatted_raw_ostream &o, SlotTracker &Mac, 1272 const Module *M, 1273 AssemblyAnnotationWriter *AAW) 1274 : Out(o), Machine(Mac), TheModule(M), AnnotationWriter(AAW) { 1275 AddModuleTypesToPrinter(TypePrinter, NumberedTypes, M); 1276 } 1277 1278 void printMDNodeBody(const MDNode *MD); 1279 void printNamedMDNode(const NamedMDNode *NMD); 1280 1281 void printModule(const Module *M); 1282 1283 void writeOperand(const Value *Op, bool PrintType); 1284 void writeParamOperand(const Value *Operand, Attributes Attrs); 1285 1286 void writeAllMDNodes(); 1287 1288 void printTypeSymbolTable(const TypeSymbolTable &ST); 1289 void printGlobal(const GlobalVariable *GV); 1290 void printAlias(const GlobalAlias *GV); 1291 void printFunction(const Function *F); 1292 void printArgument(const Argument *FA, Attributes Attrs); 1293 void printBasicBlock(const BasicBlock *BB); 1294 void printInstruction(const Instruction &I); 1295 1296private: 1297 // printInfoComment - Print a little comment after the instruction indicating 1298 // which slot it occupies. 1299 void printInfoComment(const Value &V); 1300}; 1301} // end of anonymous namespace 1302 1303void AssemblyWriter::writeOperand(const Value *Operand, bool PrintType) { 1304 if (Operand == 0) { 1305 Out << "<null operand!>"; 1306 return; 1307 } 1308 if (PrintType) { 1309 TypePrinter.print(Operand->getType(), Out); 1310 Out << ' '; 1311 } 1312 WriteAsOperandInternal(Out, Operand, &TypePrinter, &Machine, TheModule); 1313} 1314 1315void AssemblyWriter::writeParamOperand(const Value *Operand, 1316 Attributes Attrs) { 1317 if (Operand == 0) { 1318 Out << "<null operand!>"; 1319 return; 1320 } 1321 1322 // Print the type 1323 TypePrinter.print(Operand->getType(), Out); 1324 // Print parameter attributes list 1325 if (Attrs != Attribute::None) 1326 Out << ' ' << Attribute::getAsString(Attrs); 1327 Out << ' '; 1328 // Print the operand 1329 WriteAsOperandInternal(Out, Operand, &TypePrinter, &Machine, TheModule); 1330} 1331 1332void AssemblyWriter::printModule(const Module *M) { 1333 if (!M->getModuleIdentifier().empty() && 1334 // Don't print the ID if it will start a new line (which would 1335 // require a comment char before it). 1336 M->getModuleIdentifier().find('\n') == std::string::npos) 1337 Out << "; ModuleID = '" << M->getModuleIdentifier() << "'\n"; 1338 1339 if (!M->getDataLayout().empty()) 1340 Out << "target datalayout = \"" << M->getDataLayout() << "\"\n"; 1341 if (!M->getTargetTriple().empty()) 1342 Out << "target triple = \"" << M->getTargetTriple() << "\"\n"; 1343 1344 if (!M->getModuleInlineAsm().empty()) { 1345 // Split the string into lines, to make it easier to read the .ll file. 1346 std::string Asm = M->getModuleInlineAsm(); 1347 size_t CurPos = 0; 1348 size_t NewLine = Asm.find_first_of('\n', CurPos); 1349 Out << '\n'; 1350 while (NewLine != std::string::npos) { 1351 // We found a newline, print the portion of the asm string from the 1352 // last newline up to this newline. 1353 Out << "module asm \""; 1354 PrintEscapedString(std::string(Asm.begin()+CurPos, Asm.begin()+NewLine), 1355 Out); 1356 Out << "\"\n"; 1357 CurPos = NewLine+1; 1358 NewLine = Asm.find_first_of('\n', CurPos); 1359 } 1360 std::string rest(Asm.begin()+CurPos, Asm.end()); 1361 if (!rest.empty()) { 1362 Out << "module asm \""; 1363 PrintEscapedString(rest, Out); 1364 Out << "\"\n"; 1365 } 1366 } 1367 1368 // Loop over the dependent libraries and emit them. 1369 Module::lib_iterator LI = M->lib_begin(); 1370 Module::lib_iterator LE = M->lib_end(); 1371 if (LI != LE) { 1372 Out << '\n'; 1373 Out << "deplibs = [ "; 1374 while (LI != LE) { 1375 Out << '"' << *LI << '"'; 1376 ++LI; 1377 if (LI != LE) 1378 Out << ", "; 1379 } 1380 Out << " ]"; 1381 } 1382 1383 // Loop over the symbol table, emitting all id'd types. 1384 if (!M->getTypeSymbolTable().empty() || !NumberedTypes.empty()) Out << '\n'; 1385 printTypeSymbolTable(M->getTypeSymbolTable()); 1386 1387 // Output all globals. 1388 if (!M->global_empty()) Out << '\n'; 1389 for (Module::const_global_iterator I = M->global_begin(), E = M->global_end(); 1390 I != E; ++I) 1391 printGlobal(I); 1392 1393 // Output all aliases. 1394 if (!M->alias_empty()) Out << "\n"; 1395 for (Module::const_alias_iterator I = M->alias_begin(), E = M->alias_end(); 1396 I != E; ++I) 1397 printAlias(I); 1398 1399 // Output all of the functions. 1400 for (Module::const_iterator I = M->begin(), E = M->end(); I != E; ++I) 1401 printFunction(I); 1402 1403 // Output named metadata. 1404 if (!M->named_metadata_empty()) Out << '\n'; 1405 1406 for (Module::const_named_metadata_iterator I = M->named_metadata_begin(), 1407 E = M->named_metadata_end(); I != E; ++I) 1408 printNamedMDNode(I); 1409 1410 // Output metadata. 1411 if (!Machine.mdn_empty()) { 1412 Out << '\n'; 1413 writeAllMDNodes(); 1414 } 1415} 1416 1417void AssemblyWriter::printNamedMDNode(const NamedMDNode *NMD) { 1418 Out << '!'; 1419 StringRef Name = NMD->getName(); 1420 if (Name.empty()) { 1421 Out << "<empty name> "; 1422 } else { 1423 if (isalpha(Name[0]) || Name[0] == '-' || Name[0] == '$' || 1424 Name[0] == '.' || Name[0] == '_') 1425 Out << Name[0]; 1426 else 1427 Out << '\\' << hexdigit(Name[0] >> 4) << hexdigit(Name[0] & 0x0F); 1428 for (unsigned i = 1, e = Name.size(); i != e; ++i) { 1429 unsigned char C = Name[i]; 1430 if (isalnum(C) || C == '-' || C == '$' || C == '.' || C == '_') 1431 Out << C; 1432 else 1433 Out << '\\' << hexdigit(C >> 4) << hexdigit(C & 0x0F); 1434 } 1435 } 1436 Out << " = !{"; 1437 for (unsigned i = 0, e = NMD->getNumOperands(); i != e; ++i) { 1438 if (i) Out << ", "; 1439 int Slot = Machine.getMetadataSlot(NMD->getOperand(i)); 1440 if (Slot == -1) 1441 Out << "<badref>"; 1442 else 1443 Out << '!' << Slot; 1444 } 1445 Out << "}\n"; 1446} 1447 1448 1449static void PrintLinkage(GlobalValue::LinkageTypes LT, 1450 formatted_raw_ostream &Out) { 1451 switch (LT) { 1452 case GlobalValue::ExternalLinkage: break; 1453 case GlobalValue::PrivateLinkage: Out << "private "; break; 1454 case GlobalValue::LinkerPrivateLinkage: Out << "linker_private "; break; 1455 case GlobalValue::LinkerPrivateWeakLinkage: 1456 Out << "linker_private_weak "; 1457 break; 1458 case GlobalValue::LinkerPrivateWeakDefAutoLinkage: 1459 Out << "linker_private_weak_def_auto "; 1460 break; 1461 case GlobalValue::InternalLinkage: Out << "internal "; break; 1462 case GlobalValue::LinkOnceAnyLinkage: Out << "linkonce "; break; 1463 case GlobalValue::LinkOnceODRLinkage: Out << "linkonce_odr "; break; 1464 case GlobalValue::WeakAnyLinkage: Out << "weak "; break; 1465 case GlobalValue::WeakODRLinkage: Out << "weak_odr "; break; 1466 case GlobalValue::CommonLinkage: Out << "common "; break; 1467 case GlobalValue::AppendingLinkage: Out << "appending "; break; 1468 case GlobalValue::DLLImportLinkage: Out << "dllimport "; break; 1469 case GlobalValue::DLLExportLinkage: Out << "dllexport "; break; 1470 case GlobalValue::ExternalWeakLinkage: Out << "extern_weak "; break; 1471 case GlobalValue::AvailableExternallyLinkage: 1472 Out << "available_externally "; 1473 break; 1474 } 1475} 1476 1477 1478static void PrintVisibility(GlobalValue::VisibilityTypes Vis, 1479 formatted_raw_ostream &Out) { 1480 switch (Vis) { 1481 case GlobalValue::DefaultVisibility: break; 1482 case GlobalValue::HiddenVisibility: Out << "hidden "; break; 1483 case GlobalValue::ProtectedVisibility: Out << "protected "; break; 1484 } 1485} 1486 1487void AssemblyWriter::printGlobal(const GlobalVariable *GV) { 1488 if (GV->isMaterializable()) 1489 Out << "; Materializable\n"; 1490 1491 WriteAsOperandInternal(Out, GV, &TypePrinter, &Machine, GV->getParent()); 1492 Out << " = "; 1493 1494 if (!GV->hasInitializer() && GV->hasExternalLinkage()) 1495 Out << "external "; 1496 1497 PrintLinkage(GV->getLinkage(), Out); 1498 PrintVisibility(GV->getVisibility(), Out); 1499 1500 if (GV->isThreadLocal()) Out << "thread_local "; 1501 if (unsigned AddressSpace = GV->getType()->getAddressSpace()) 1502 Out << "addrspace(" << AddressSpace << ") "; 1503 if (GV->hasUnnamedAddr()) Out << "unnamed_addr "; 1504 Out << (GV->isConstant() ? "constant " : "global "); 1505 TypePrinter.print(GV->getType()->getElementType(), Out); 1506 1507 if (GV->hasInitializer()) { 1508 Out << ' '; 1509 writeOperand(GV->getInitializer(), false); 1510 } 1511 1512 if (GV->hasSection()) { 1513 Out << ", section \""; 1514 PrintEscapedString(GV->getSection(), Out); 1515 Out << '"'; 1516 } 1517 if (GV->getAlignment()) 1518 Out << ", align " << GV->getAlignment(); 1519 1520 printInfoComment(*GV); 1521 Out << '\n'; 1522} 1523 1524void AssemblyWriter::printAlias(const GlobalAlias *GA) { 1525 if (GA->isMaterializable()) 1526 Out << "; Materializable\n"; 1527 1528 // Don't crash when dumping partially built GA 1529 if (!GA->hasName()) 1530 Out << "<<nameless>> = "; 1531 else { 1532 PrintLLVMName(Out, GA); 1533 Out << " = "; 1534 } 1535 PrintVisibility(GA->getVisibility(), Out); 1536 1537 Out << "alias "; 1538 1539 PrintLinkage(GA->getLinkage(), Out); 1540 1541 const Constant *Aliasee = GA->getAliasee(); 1542 1543 if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(Aliasee)) { 1544 TypePrinter.print(GV->getType(), Out); 1545 Out << ' '; 1546 PrintLLVMName(Out, GV); 1547 } else if (const Function *F = dyn_cast<Function>(Aliasee)) { 1548 TypePrinter.print(F->getFunctionType(), Out); 1549 Out << "* "; 1550 1551 WriteAsOperandInternal(Out, F, &TypePrinter, &Machine, F->getParent()); 1552 } else if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(Aliasee)) { 1553 TypePrinter.print(GA->getType(), Out); 1554 Out << ' '; 1555 PrintLLVMName(Out, GA); 1556 } else { 1557 const ConstantExpr *CE = cast<ConstantExpr>(Aliasee); 1558 // The only valid GEP is an all zero GEP. 1559 assert((CE->getOpcode() == Instruction::BitCast || 1560 CE->getOpcode() == Instruction::GetElementPtr) && 1561 "Unsupported aliasee"); 1562 writeOperand(CE, false); 1563 } 1564 1565 printInfoComment(*GA); 1566 Out << '\n'; 1567} 1568 1569void AssemblyWriter::printTypeSymbolTable(const TypeSymbolTable &ST) { 1570 // Emit all numbered types. 1571 for (unsigned i = 0, e = NumberedTypes.size(); i != e; ++i) { 1572 Out << '%' << i << " = type "; 1573 1574 // Make sure we print out at least one level of the type structure, so 1575 // that we do not get %2 = type %2 1576 TypePrinter.printAtLeastOneLevel(NumberedTypes[i], Out); 1577 Out << '\n'; 1578 } 1579 1580 // Print the named types. 1581 for (TypeSymbolTable::const_iterator TI = ST.begin(), TE = ST.end(); 1582 TI != TE; ++TI) { 1583 PrintLLVMName(Out, TI->first, LocalPrefix); 1584 Out << " = type "; 1585 1586 // Make sure we print out at least one level of the type structure, so 1587 // that we do not get %FILE = type %FILE 1588 TypePrinter.printAtLeastOneLevel(TI->second, Out); 1589 Out << '\n'; 1590 } 1591} 1592 1593/// printFunction - Print all aspects of a function. 1594/// 1595void AssemblyWriter::printFunction(const Function *F) { 1596 // Print out the return type and name. 1597 Out << '\n'; 1598 1599 if (AnnotationWriter) AnnotationWriter->emitFunctionAnnot(F, Out); 1600 1601 if (F->isMaterializable()) 1602 Out << "; Materializable\n"; 1603 1604 if (F->isDeclaration()) 1605 Out << "declare "; 1606 else 1607 Out << "define "; 1608 1609 PrintLinkage(F->getLinkage(), Out); 1610 PrintVisibility(F->getVisibility(), Out); 1611 1612 // Print the calling convention. 1613 switch (F->getCallingConv()) { 1614 case CallingConv::C: break; // default 1615 case CallingConv::Fast: Out << "fastcc "; break; 1616 case CallingConv::Cold: Out << "coldcc "; break; 1617 case CallingConv::X86_StdCall: Out << "x86_stdcallcc "; break; 1618 case CallingConv::X86_FastCall: Out << "x86_fastcallcc "; break; 1619 case CallingConv::X86_ThisCall: Out << "x86_thiscallcc "; break; 1620 case CallingConv::ARM_APCS: Out << "arm_apcscc "; break; 1621 case CallingConv::ARM_AAPCS: Out << "arm_aapcscc "; break; 1622 case CallingConv::ARM_AAPCS_VFP:Out << "arm_aapcs_vfpcc "; break; 1623 case CallingConv::MSP430_INTR: Out << "msp430_intrcc "; break; 1624 case CallingConv::PTX_Kernel: Out << "ptx_kernel "; break; 1625 case CallingConv::PTX_Device: Out << "ptx_device "; break; 1626 default: Out << "cc" << F->getCallingConv() << " "; break; 1627 } 1628 1629 const FunctionType *FT = F->getFunctionType(); 1630 const AttrListPtr &Attrs = F->getAttributes(); 1631 Attributes RetAttrs = Attrs.getRetAttributes(); 1632 if (RetAttrs != Attribute::None) 1633 Out << Attribute::getAsString(Attrs.getRetAttributes()) << ' '; 1634 TypePrinter.print(F->getReturnType(), Out); 1635 Out << ' '; 1636 WriteAsOperandInternal(Out, F, &TypePrinter, &Machine, F->getParent()); 1637 Out << '('; 1638 Machine.incorporateFunction(F); 1639 1640 // Loop over the arguments, printing them... 1641 1642 unsigned Idx = 1; 1643 if (!F->isDeclaration()) { 1644 // If this isn't a declaration, print the argument names as well. 1645 for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end(); 1646 I != E; ++I) { 1647 // Insert commas as we go... the first arg doesn't get a comma 1648 if (I != F->arg_begin()) Out << ", "; 1649 printArgument(I, Attrs.getParamAttributes(Idx)); 1650 Idx++; 1651 } 1652 } else { 1653 // Otherwise, print the types from the function type. 1654 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) { 1655 // Insert commas as we go... the first arg doesn't get a comma 1656 if (i) Out << ", "; 1657 1658 // Output type... 1659 TypePrinter.print(FT->getParamType(i), Out); 1660 1661 Attributes ArgAttrs = Attrs.getParamAttributes(i+1); 1662 if (ArgAttrs != Attribute::None) 1663 Out << ' ' << Attribute::getAsString(ArgAttrs); 1664 } 1665 } 1666 1667 // Finish printing arguments... 1668 if (FT->isVarArg()) { 1669 if (FT->getNumParams()) Out << ", "; 1670 Out << "..."; // Output varargs portion of signature! 1671 } 1672 Out << ')'; 1673 if (F->hasUnnamedAddr()) 1674 Out << " unnamed_addr"; 1675 Attributes FnAttrs = Attrs.getFnAttributes(); 1676 if (FnAttrs != Attribute::None) 1677 Out << ' ' << Attribute::getAsString(Attrs.getFnAttributes()); 1678 if (F->hasSection()) { 1679 Out << " section \""; 1680 PrintEscapedString(F->getSection(), Out); 1681 Out << '"'; 1682 } 1683 if (F->getAlignment()) 1684 Out << " align " << F->getAlignment(); 1685 if (F->hasGC()) 1686 Out << " gc \"" << F->getGC() << '"'; 1687 if (F->isDeclaration()) { 1688 Out << '\n'; 1689 } else { 1690 Out << " {"; 1691 // Output all of the function's basic blocks. 1692 for (Function::const_iterator I = F->begin(), E = F->end(); I != E; ++I) 1693 printBasicBlock(I); 1694 1695 Out << "}\n"; 1696 } 1697 1698 Machine.purgeFunction(); 1699} 1700 1701/// printArgument - This member is called for every argument that is passed into 1702/// the function. Simply print it out 1703/// 1704void AssemblyWriter::printArgument(const Argument *Arg, 1705 Attributes Attrs) { 1706 // Output type... 1707 TypePrinter.print(Arg->getType(), Out); 1708 1709 // Output parameter attributes list 1710 if (Attrs != Attribute::None) 1711 Out << ' ' << Attribute::getAsString(Attrs); 1712 1713 // Output name, if available... 1714 if (Arg->hasName()) { 1715 Out << ' '; 1716 PrintLLVMName(Out, Arg); 1717 } 1718} 1719 1720/// printBasicBlock - This member is called for each basic block in a method. 1721/// 1722void AssemblyWriter::printBasicBlock(const BasicBlock *BB) { 1723 if (BB->hasName()) { // Print out the label if it exists... 1724 Out << "\n"; 1725 PrintLLVMName(Out, BB->getName(), LabelPrefix); 1726 Out << ':'; 1727 } else if (!BB->use_empty()) { // Don't print block # of no uses... 1728 Out << "\n; <label>:"; 1729 int Slot = Machine.getLocalSlot(BB); 1730 if (Slot != -1) 1731 Out << Slot; 1732 else 1733 Out << "<badref>"; 1734 } 1735 1736 if (BB->getParent() == 0) { 1737 Out.PadToColumn(50); 1738 Out << "; Error: Block without parent!"; 1739 } else if (BB != &BB->getParent()->getEntryBlock()) { // Not the entry block? 1740 // Output predecessors for the block. 1741 Out.PadToColumn(50); 1742 Out << ";"; 1743 const_pred_iterator PI = pred_begin(BB), PE = pred_end(BB); 1744 1745 if (PI == PE) { 1746 Out << " No predecessors!"; 1747 } else { 1748 Out << " preds = "; 1749 writeOperand(*PI, false); 1750 for (++PI; PI != PE; ++PI) { 1751 Out << ", "; 1752 writeOperand(*PI, false); 1753 } 1754 } 1755 } 1756 1757 Out << "\n"; 1758 1759 if (AnnotationWriter) AnnotationWriter->emitBasicBlockStartAnnot(BB, Out); 1760 1761 // Output all of the instructions in the basic block... 1762 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I != E; ++I) { 1763 printInstruction(*I); 1764 Out << '\n'; 1765 } 1766 1767 if (AnnotationWriter) AnnotationWriter->emitBasicBlockEndAnnot(BB, Out); 1768} 1769 1770/// printDebugLoc - Print DebugLoc. 1771static void printDebugLoc(const DebugLoc &DL, formatted_raw_ostream &OS) { 1772 OS << DL.getLine() << ":" << DL.getCol(); 1773 if (MDNode *N = DL.getInlinedAt(getGlobalContext())) { 1774 DebugLoc IDL = DebugLoc::getFromDILocation(N); 1775 if (!IDL.isUnknown()) { 1776 OS << "@"; 1777 printDebugLoc(IDL,OS); 1778 } 1779 } 1780} 1781 1782/// printInfoComment - Print a little comment after the instruction indicating 1783/// which slot it occupies. 1784/// 1785void AssemblyWriter::printInfoComment(const Value &V) { 1786 if (AnnotationWriter) { 1787 AnnotationWriter->printInfoComment(V, Out); 1788 return; 1789 } else if (EnableDebugInfoComment) { 1790 bool Padded = false; 1791 if (const Instruction *I = dyn_cast<Instruction>(&V)) { 1792 const DebugLoc &DL = I->getDebugLoc(); 1793 if (!DL.isUnknown()) { 1794 if (!Padded) { 1795 Out.PadToColumn(50); 1796 Padded = true; 1797 Out << ";"; 1798 } 1799 Out << " [debug line = "; 1800 printDebugLoc(DL,Out); 1801 Out << "]"; 1802 } 1803 if (const DbgDeclareInst *DDI = dyn_cast<DbgDeclareInst>(I)) { 1804 const MDNode *Var = DDI->getVariable(); 1805 if (!Padded) { 1806 Out.PadToColumn(50); 1807 Padded = true; 1808 Out << ";"; 1809 } 1810 if (Var && Var->getNumOperands() >= 2) 1811 if (MDString *MDS = dyn_cast_or_null<MDString>(Var->getOperand(2))) 1812 Out << " [debug variable = " << MDS->getString() << "]"; 1813 } 1814 else if (const DbgValueInst *DVI = dyn_cast<DbgValueInst>(I)) { 1815 const MDNode *Var = DVI->getVariable(); 1816 if (!Padded) { 1817 Out.PadToColumn(50); 1818 Padded = true; 1819 Out << ";"; 1820 } 1821 if (Var && Var->getNumOperands() >= 2) 1822 if (MDString *MDS = dyn_cast_or_null<MDString>(Var->getOperand(2))) 1823 Out << " [debug variable = " << MDS->getString() << "]"; 1824 } 1825 } 1826 } 1827} 1828 1829// This member is called for each Instruction in a function.. 1830void AssemblyWriter::printInstruction(const Instruction &I) { 1831 if (AnnotationWriter) AnnotationWriter->emitInstructionAnnot(&I, Out); 1832 1833 // Print out indentation for an instruction. 1834 Out << " "; 1835 1836 // Print out name if it exists... 1837 if (I.hasName()) { 1838 PrintLLVMName(Out, &I); 1839 Out << " = "; 1840 } else if (!I.getType()->isVoidTy()) { 1841 // Print out the def slot taken. 1842 int SlotNum = Machine.getLocalSlot(&I); 1843 if (SlotNum == -1) 1844 Out << "<badref> = "; 1845 else 1846 Out << '%' << SlotNum << " = "; 1847 } 1848 1849 // If this is a volatile load or store, print out the volatile marker. 1850 if ((isa<LoadInst>(I) && cast<LoadInst>(I).isVolatile()) || 1851 (isa<StoreInst>(I) && cast<StoreInst>(I).isVolatile())) { 1852 Out << "volatile "; 1853 } else if (isa<CallInst>(I) && cast<CallInst>(I).isTailCall()) { 1854 // If this is a call, check if it's a tail call. 1855 Out << "tail "; 1856 } 1857 1858 // Print out the opcode... 1859 Out << I.getOpcodeName(); 1860 1861 // Print out optimization information. 1862 WriteOptimizationInfo(Out, &I); 1863 1864 // Print out the compare instruction predicates 1865 if (const CmpInst *CI = dyn_cast<CmpInst>(&I)) 1866 Out << ' ' << getPredicateText(CI->getPredicate()); 1867 1868 // Print out the type of the operands... 1869 const Value *Operand = I.getNumOperands() ? I.getOperand(0) : 0; 1870 1871 // Special case conditional branches to swizzle the condition out to the front 1872 if (isa<BranchInst>(I) && cast<BranchInst>(I).isConditional()) { 1873 BranchInst &BI(cast<BranchInst>(I)); 1874 Out << ' '; 1875 writeOperand(BI.getCondition(), true); 1876 Out << ", "; 1877 writeOperand(BI.getSuccessor(0), true); 1878 Out << ", "; 1879 writeOperand(BI.getSuccessor(1), true); 1880 1881 } else if (isa<SwitchInst>(I)) { 1882 // Special case switch instruction to get formatting nice and correct. 1883 Out << ' '; 1884 writeOperand(Operand , true); 1885 Out << ", "; 1886 writeOperand(I.getOperand(1), true); 1887 Out << " ["; 1888 1889 for (unsigned op = 2, Eop = I.getNumOperands(); op < Eop; op += 2) { 1890 Out << "\n "; 1891 writeOperand(I.getOperand(op ), true); 1892 Out << ", "; 1893 writeOperand(I.getOperand(op+1), true); 1894 } 1895 Out << "\n ]"; 1896 } else if (isa<IndirectBrInst>(I)) { 1897 // Special case indirectbr instruction to get formatting nice and correct. 1898 Out << ' '; 1899 writeOperand(Operand, true); 1900 Out << ", ["; 1901 1902 for (unsigned i = 1, e = I.getNumOperands(); i != e; ++i) { 1903 if (i != 1) 1904 Out << ", "; 1905 writeOperand(I.getOperand(i), true); 1906 } 1907 Out << ']'; 1908 } else if (const PHINode *PN = dyn_cast<PHINode>(&I)) { 1909 Out << ' '; 1910 TypePrinter.print(I.getType(), Out); 1911 Out << ' '; 1912 1913 for (unsigned op = 0, Eop = PN->getNumIncomingValues(); op < Eop; ++op) { 1914 if (op) Out << ", "; 1915 Out << "[ "; 1916 writeOperand(PN->getIncomingValue(op), false); Out << ", "; 1917 writeOperand(PN->getIncomingBlock(op), false); Out << " ]"; 1918 } 1919 } else if (const ExtractValueInst *EVI = dyn_cast<ExtractValueInst>(&I)) { 1920 Out << ' '; 1921 writeOperand(I.getOperand(0), true); 1922 for (const unsigned *i = EVI->idx_begin(), *e = EVI->idx_end(); i != e; ++i) 1923 Out << ", " << *i; 1924 } else if (const InsertValueInst *IVI = dyn_cast<InsertValueInst>(&I)) { 1925 Out << ' '; 1926 writeOperand(I.getOperand(0), true); Out << ", "; 1927 writeOperand(I.getOperand(1), true); 1928 for (const unsigned *i = IVI->idx_begin(), *e = IVI->idx_end(); i != e; ++i) 1929 Out << ", " << *i; 1930 } else if (isa<ReturnInst>(I) && !Operand) { 1931 Out << " void"; 1932 } else if (const CallInst *CI = dyn_cast<CallInst>(&I)) { 1933 // Print the calling convention being used. 1934 switch (CI->getCallingConv()) { 1935 case CallingConv::C: break; // default 1936 case CallingConv::Fast: Out << " fastcc"; break; 1937 case CallingConv::Cold: Out << " coldcc"; break; 1938 case CallingConv::X86_StdCall: Out << " x86_stdcallcc"; break; 1939 case CallingConv::X86_FastCall: Out << " x86_fastcallcc"; break; 1940 case CallingConv::X86_ThisCall: Out << " x86_thiscallcc"; break; 1941 case CallingConv::ARM_APCS: Out << " arm_apcscc "; break; 1942 case CallingConv::ARM_AAPCS: Out << " arm_aapcscc "; break; 1943 case CallingConv::ARM_AAPCS_VFP:Out << " arm_aapcs_vfpcc "; break; 1944 case CallingConv::MSP430_INTR: Out << " msp430_intrcc "; break; 1945 case CallingConv::PTX_Kernel: Out << " ptx_kernel"; break; 1946 case CallingConv::PTX_Device: Out << " ptx_device"; break; 1947 default: Out << " cc" << CI->getCallingConv(); break; 1948 } 1949 1950 Operand = CI->getCalledValue(); 1951 const PointerType *PTy = cast<PointerType>(Operand->getType()); 1952 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType()); 1953 const Type *RetTy = FTy->getReturnType(); 1954 const AttrListPtr &PAL = CI->getAttributes(); 1955 1956 if (PAL.getRetAttributes() != Attribute::None) 1957 Out << ' ' << Attribute::getAsString(PAL.getRetAttributes()); 1958 1959 // If possible, print out the short form of the call instruction. We can 1960 // only do this if the first argument is a pointer to a nonvararg function, 1961 // and if the return type is not a pointer to a function. 1962 // 1963 Out << ' '; 1964 if (!FTy->isVarArg() && 1965 (!RetTy->isPointerTy() || 1966 !cast<PointerType>(RetTy)->getElementType()->isFunctionTy())) { 1967 TypePrinter.print(RetTy, Out); 1968 Out << ' '; 1969 writeOperand(Operand, false); 1970 } else { 1971 writeOperand(Operand, true); 1972 } 1973 Out << '('; 1974 for (unsigned op = 0, Eop = CI->getNumArgOperands(); op < Eop; ++op) { 1975 if (op > 0) 1976 Out << ", "; 1977 writeParamOperand(CI->getArgOperand(op), PAL.getParamAttributes(op + 1)); 1978 } 1979 Out << ')'; 1980 if (PAL.getFnAttributes() != Attribute::None) 1981 Out << ' ' << Attribute::getAsString(PAL.getFnAttributes()); 1982 } else if (const InvokeInst *II = dyn_cast<InvokeInst>(&I)) { 1983 Operand = II->getCalledValue(); 1984 const PointerType *PTy = cast<PointerType>(Operand->getType()); 1985 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType()); 1986 const Type *RetTy = FTy->getReturnType(); 1987 const AttrListPtr &PAL = II->getAttributes(); 1988 1989 // Print the calling convention being used. 1990 switch (II->getCallingConv()) { 1991 case CallingConv::C: break; // default 1992 case CallingConv::Fast: Out << " fastcc"; break; 1993 case CallingConv::Cold: Out << " coldcc"; break; 1994 case CallingConv::X86_StdCall: Out << " x86_stdcallcc"; break; 1995 case CallingConv::X86_FastCall: Out << " x86_fastcallcc"; break; 1996 case CallingConv::X86_ThisCall: Out << " x86_thiscallcc"; break; 1997 case CallingConv::ARM_APCS: Out << " arm_apcscc "; break; 1998 case CallingConv::ARM_AAPCS: Out << " arm_aapcscc "; break; 1999 case CallingConv::ARM_AAPCS_VFP:Out << " arm_aapcs_vfpcc "; break; 2000 case CallingConv::MSP430_INTR: Out << " msp430_intrcc "; break; 2001 case CallingConv::PTX_Kernel: Out << " ptx_kernel"; break; 2002 case CallingConv::PTX_Device: Out << " ptx_device"; break; 2003 default: Out << " cc" << II->getCallingConv(); break; 2004 } 2005 2006 if (PAL.getRetAttributes() != Attribute::None) 2007 Out << ' ' << Attribute::getAsString(PAL.getRetAttributes()); 2008 2009 // If possible, print out the short form of the invoke instruction. We can 2010 // only do this if the first argument is a pointer to a nonvararg function, 2011 // and if the return type is not a pointer to a function. 2012 // 2013 Out << ' '; 2014 if (!FTy->isVarArg() && 2015 (!RetTy->isPointerTy() || 2016 !cast<PointerType>(RetTy)->getElementType()->isFunctionTy())) { 2017 TypePrinter.print(RetTy, Out); 2018 Out << ' '; 2019 writeOperand(Operand, false); 2020 } else { 2021 writeOperand(Operand, true); 2022 } 2023 Out << '('; 2024 for (unsigned op = 0, Eop = II->getNumArgOperands(); op < Eop; ++op) { 2025 if (op) 2026 Out << ", "; 2027 writeParamOperand(II->getArgOperand(op), PAL.getParamAttributes(op + 1)); 2028 } 2029 2030 Out << ')'; 2031 if (PAL.getFnAttributes() != Attribute::None) 2032 Out << ' ' << Attribute::getAsString(PAL.getFnAttributes()); 2033 2034 Out << "\n to "; 2035 writeOperand(II->getNormalDest(), true); 2036 Out << " unwind "; 2037 writeOperand(II->getUnwindDest(), true); 2038 2039 } else if (const AllocaInst *AI = dyn_cast<AllocaInst>(&I)) { 2040 Out << ' '; 2041 TypePrinter.print(AI->getType()->getElementType(), Out); 2042 if (!AI->getArraySize() || AI->isArrayAllocation()) { 2043 Out << ", "; 2044 writeOperand(AI->getArraySize(), true); 2045 } 2046 if (AI->getAlignment()) { 2047 Out << ", align " << AI->getAlignment(); 2048 } 2049 } else if (isa<CastInst>(I)) { 2050 if (Operand) { 2051 Out << ' '; 2052 writeOperand(Operand, true); // Work with broken code 2053 } 2054 Out << " to "; 2055 TypePrinter.print(I.getType(), Out); 2056 } else if (isa<VAArgInst>(I)) { 2057 if (Operand) { 2058 Out << ' '; 2059 writeOperand(Operand, true); // Work with broken code 2060 } 2061 Out << ", "; 2062 TypePrinter.print(I.getType(), Out); 2063 } else if (Operand) { // Print the normal way. 2064 2065 // PrintAllTypes - Instructions who have operands of all the same type 2066 // omit the type from all but the first operand. If the instruction has 2067 // different type operands (for example br), then they are all printed. 2068 bool PrintAllTypes = false; 2069 const Type *TheType = Operand->getType(); 2070 2071 // Select, Store and ShuffleVector always print all types. 2072 if (isa<SelectInst>(I) || isa<StoreInst>(I) || isa<ShuffleVectorInst>(I) 2073 || isa<ReturnInst>(I)) { 2074 PrintAllTypes = true; 2075 } else { 2076 for (unsigned i = 1, E = I.getNumOperands(); i != E; ++i) { 2077 Operand = I.getOperand(i); 2078 // note that Operand shouldn't be null, but the test helps make dump() 2079 // more tolerant of malformed IR 2080 if (Operand && Operand->getType() != TheType) { 2081 PrintAllTypes = true; // We have differing types! Print them all! 2082 break; 2083 } 2084 } 2085 } 2086 2087 if (!PrintAllTypes) { 2088 Out << ' '; 2089 TypePrinter.print(TheType, Out); 2090 } 2091 2092 Out << ' '; 2093 for (unsigned i = 0, E = I.getNumOperands(); i != E; ++i) { 2094 if (i) Out << ", "; 2095 writeOperand(I.getOperand(i), PrintAllTypes); 2096 } 2097 } 2098 2099 // Print post operand alignment for load/store. 2100 if (isa<LoadInst>(I) && cast<LoadInst>(I).getAlignment()) { 2101 Out << ", align " << cast<LoadInst>(I).getAlignment(); 2102 } else if (isa<StoreInst>(I) && cast<StoreInst>(I).getAlignment()) { 2103 Out << ", align " << cast<StoreInst>(I).getAlignment(); 2104 } 2105 2106 // Print Metadata info. 2107 SmallVector<std::pair<unsigned, MDNode*>, 4> InstMD; 2108 I.getAllMetadata(InstMD); 2109 if (!InstMD.empty()) { 2110 SmallVector<StringRef, 8> MDNames; 2111 I.getType()->getContext().getMDKindNames(MDNames); 2112 for (unsigned i = 0, e = InstMD.size(); i != e; ++i) { 2113 unsigned Kind = InstMD[i].first; 2114 if (Kind < MDNames.size()) { 2115 Out << ", !" << MDNames[Kind]; 2116 } else { 2117 Out << ", !<unknown kind #" << Kind << ">"; 2118 } 2119 Out << ' '; 2120 WriteAsOperandInternal(Out, InstMD[i].second, &TypePrinter, &Machine, 2121 TheModule); 2122 } 2123 } 2124 printInfoComment(I); 2125} 2126 2127static void WriteMDNodeComment(const MDNode *Node, 2128 formatted_raw_ostream &Out) { 2129 if (Node->getNumOperands() < 1) 2130 return; 2131 ConstantInt *CI = dyn_cast_or_null<ConstantInt>(Node->getOperand(0)); 2132 if (!CI) return; 2133 APInt Val = CI->getValue(); 2134 APInt Tag = Val & ~APInt(Val.getBitWidth(), LLVMDebugVersionMask); 2135 if (Val.ult(LLVMDebugVersion)) 2136 return; 2137 2138 Out.PadToColumn(50); 2139 if (Tag == dwarf::DW_TAG_user_base) 2140 Out << "; [ DW_TAG_user_base ]"; 2141 else if (Tag.isIntN(32)) { 2142 if (const char *TagName = dwarf::TagString(Tag.getZExtValue())) 2143 Out << "; [ " << TagName << " ]"; 2144 } 2145} 2146 2147void AssemblyWriter::writeAllMDNodes() { 2148 SmallVector<const MDNode *, 16> Nodes; 2149 Nodes.resize(Machine.mdn_size()); 2150 for (SlotTracker::mdn_iterator I = Machine.mdn_begin(), E = Machine.mdn_end(); 2151 I != E; ++I) 2152 Nodes[I->second] = cast<MDNode>(I->first); 2153 2154 for (unsigned i = 0, e = Nodes.size(); i != e; ++i) { 2155 Out << '!' << i << " = metadata "; 2156 printMDNodeBody(Nodes[i]); 2157 } 2158} 2159 2160void AssemblyWriter::printMDNodeBody(const MDNode *Node) { 2161 WriteMDNodeBodyInternal(Out, Node, &TypePrinter, &Machine, TheModule); 2162 WriteMDNodeComment(Node, Out); 2163 Out << "\n"; 2164} 2165 2166//===----------------------------------------------------------------------===// 2167// External Interface declarations 2168//===----------------------------------------------------------------------===// 2169 2170void Module::print(raw_ostream &ROS, AssemblyAnnotationWriter *AAW) const { 2171 SlotTracker SlotTable(this); 2172 formatted_raw_ostream OS(ROS); 2173 AssemblyWriter W(OS, SlotTable, this, AAW); 2174 W.printModule(this); 2175} 2176 2177void NamedMDNode::print(raw_ostream &ROS, AssemblyAnnotationWriter *AAW) const { 2178 SlotTracker SlotTable(getParent()); 2179 formatted_raw_ostream OS(ROS); 2180 AssemblyWriter W(OS, SlotTable, getParent(), AAW); 2181 W.printNamedMDNode(this); 2182} 2183 2184void Type::print(raw_ostream &OS) const { 2185 if (this == 0) { 2186 OS << "<null Type>"; 2187 return; 2188 } 2189 TypePrinting().print(this, OS); 2190} 2191 2192void Value::print(raw_ostream &ROS, AssemblyAnnotationWriter *AAW) const { 2193 if (this == 0) { 2194 ROS << "printing a <null> value\n"; 2195 return; 2196 } 2197 formatted_raw_ostream OS(ROS); 2198 if (const Instruction *I = dyn_cast<Instruction>(this)) { 2199 const Function *F = I->getParent() ? I->getParent()->getParent() : 0; 2200 SlotTracker SlotTable(F); 2201 AssemblyWriter W(OS, SlotTable, getModuleFromVal(I), AAW); 2202 W.printInstruction(*I); 2203 } else if (const BasicBlock *BB = dyn_cast<BasicBlock>(this)) { 2204 SlotTracker SlotTable(BB->getParent()); 2205 AssemblyWriter W(OS, SlotTable, getModuleFromVal(BB), AAW); 2206 W.printBasicBlock(BB); 2207 } else if (const GlobalValue *GV = dyn_cast<GlobalValue>(this)) { 2208 SlotTracker SlotTable(GV->getParent()); 2209 AssemblyWriter W(OS, SlotTable, GV->getParent(), AAW); 2210 if (const GlobalVariable *V = dyn_cast<GlobalVariable>(GV)) 2211 W.printGlobal(V); 2212 else if (const Function *F = dyn_cast<Function>(GV)) 2213 W.printFunction(F); 2214 else 2215 W.printAlias(cast<GlobalAlias>(GV)); 2216 } else if (const MDNode *N = dyn_cast<MDNode>(this)) { 2217 const Function *F = N->getFunction(); 2218 SlotTracker SlotTable(F); 2219 AssemblyWriter W(OS, SlotTable, F ? F->getParent() : 0, AAW); 2220 W.printMDNodeBody(N); 2221 } else if (const Constant *C = dyn_cast<Constant>(this)) { 2222 TypePrinting TypePrinter; 2223 TypePrinter.print(C->getType(), OS); 2224 OS << ' '; 2225 WriteConstantInternal(OS, C, TypePrinter, 0, 0); 2226 } else if (isa<InlineAsm>(this) || isa<MDString>(this) || 2227 isa<Argument>(this)) { 2228 WriteAsOperand(OS, this, true, 0); 2229 } else { 2230 // Otherwise we don't know what it is. Call the virtual function to 2231 // allow a subclass to print itself. 2232 printCustom(OS); 2233 } 2234} 2235 2236// Value::printCustom - subclasses should override this to implement printing. 2237void Value::printCustom(raw_ostream &OS) const { 2238 llvm_unreachable("Unknown value to print out!"); 2239} 2240 2241// Value::dump - allow easy printing of Values from the debugger. 2242void Value::dump() const { print(dbgs()); dbgs() << '\n'; } 2243 2244// Type::dump - allow easy printing of Types from the debugger. 2245// This one uses type names from the given context module 2246void Type::dump(const Module *Context) const { 2247 WriteTypeSymbolic(dbgs(), this, Context); 2248 dbgs() << '\n'; 2249} 2250 2251// Type::dump - allow easy printing of Types from the debugger. 2252void Type::dump() const { dump(0); } 2253 2254// Module::dump() - Allow printing of Modules from the debugger. 2255void Module::dump() const { print(dbgs(), 0); } 2256