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