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