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