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 if (GA->hasComdat()) { 1532 Out << ", comdat "; 1533 PrintLLVMName(Out, GA->getComdat()->getName(), ComdatPrefix); 1534 } 1535 1536 printInfoComment(*GA); 1537 Out << '\n'; 1538 } 1539 1540 void AssemblyWriter::printComdat(const Comdat *C) { 1541 C->print(Out); 1542 } 1543 1544 void AssemblyWriter::printTypeIdentities() { 1545 if (TypePrinter.NumberedTypes.empty() && 1546 TypePrinter.NamedTypes.empty()) 1547 return; 1548 1549 Out << '\n'; 1550 1551 // We know all the numbers that each type is used and we know that it is a 1552 // dense assignment. Convert the map to an index table. 1553 std::vector<StructType*> NumberedTypes(TypePrinter.NumberedTypes.size()); 1554 for (DenseMap<StructType*, unsigned>::iterator I = 1555 TypePrinter.NumberedTypes.begin(), E = TypePrinter.NumberedTypes.end(); 1556 I != E; ++I) { 1557 assert(I->second < NumberedTypes.size() && "Didn't get a dense numbering?"); 1558 NumberedTypes[I->second] = I->first; 1559 } 1560 1561 // Emit all numbered types. 1562 for (unsigned i = 0, e = NumberedTypes.size(); i != e; ++i) { 1563 Out << '%' << i << " = type "; 1564 1565 // Make sure we print out at least one level of the type structure, so 1566 // that we do not get %2 = type %2 1567 TypePrinter.printStructBody(NumberedTypes[i], Out); 1568 Out << '\n'; 1569 } 1570 1571 for (unsigned i = 0, e = TypePrinter.NamedTypes.size(); i != e; ++i) { 1572 PrintLLVMName(Out, TypePrinter.NamedTypes[i]->getName(), LocalPrefix); 1573 Out << " = type "; 1574 1575 // Make sure we print out at least one level of the type structure, so 1576 // that we do not get %FILE = type %FILE 1577 TypePrinter.printStructBody(TypePrinter.NamedTypes[i], Out); 1578 Out << '\n'; 1579 } 1580 } 1581 1582 /// printFunction - Print all aspects of a function. 1583 /// 1584 void AssemblyWriter::printFunction(const Function *F) { 1585 // Print out the return type and name. 1586 Out << '\n'; 1587 1588 if (AnnotationWriter) AnnotationWriter->emitFunctionAnnot(F, Out); 1589 1590 if (F->isMaterializable()) 1591 Out << "; Materializable\n"; 1592 1593 const AttributeSet &Attrs = F->getAttributes(); 1594 if (Attrs.hasAttributes(AttributeSet::FunctionIndex)) { 1595 AttributeSet AS = Attrs.getFnAttributes(); 1596 std::string AttrStr; 1597 1598 unsigned Idx = 0; 1599 for (unsigned E = AS.getNumSlots(); Idx != E; ++Idx) 1600 if (AS.getSlotIndex(Idx) == AttributeSet::FunctionIndex) 1601 break; 1602 1603 for (AttributeSet::iterator I = AS.begin(Idx), E = AS.end(Idx); 1604 I != E; ++I) { 1605 Attribute Attr = *I; 1606 if (!Attr.isStringAttribute()) { 1607 if (!AttrStr.empty()) AttrStr += ' '; 1608 AttrStr += Attr.getAsString(); 1609 } 1610 } 1611 1612 if (!AttrStr.empty()) 1613 Out << "; Function Attrs: " << AttrStr << '\n'; 1614 } 1615 1616 if (F->isDeclaration()) 1617 Out << "declare "; 1618 else 1619 Out << "define "; 1620 1621 PrintLinkage(F->getLinkage(), Out); 1622 PrintVisibility(F->getVisibility(), Out); 1623 PrintDLLStorageClass(F->getDLLStorageClass(), Out); 1624 1625 // Print the calling convention. 1626 if (F->getCallingConv() != CallingConv::C) { 1627 PrintCallingConv(F->getCallingConv(), Out); 1628 Out << " "; 1629 } 1630 1631 FunctionType *FT = F->getFunctionType(); 1632 if (Attrs.hasAttributes(AttributeSet::ReturnIndex)) 1633 Out << Attrs.getAsString(AttributeSet::ReturnIndex) << ' '; 1634 TypePrinter.print(F->getReturnType(), Out); 1635 Out << ' '; 1636 WriteAsOperandInternal(Out, F, &TypePrinter, &Machine, F->getParent()); 1637 Out << '('; 1638 Machine.incorporateFunction(F); 1639 1640 // Loop over the arguments, printing them... 1641 1642 unsigned Idx = 1; 1643 if (!F->isDeclaration()) { 1644 // If this isn't a declaration, print the argument names as well. 1645 for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end(); 1646 I != E; ++I) { 1647 // Insert commas as we go... the first arg doesn't get a comma 1648 if (I != F->arg_begin()) Out << ", "; 1649 printArgument(I, Attrs, Idx); 1650 Idx++; 1651 } 1652 } else { 1653 // Otherwise, print the types from the function type. 1654 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) { 1655 // Insert commas as we go... the first arg doesn't get a comma 1656 if (i) Out << ", "; 1657 1658 // Output type... 1659 TypePrinter.print(FT->getParamType(i), Out); 1660 1661 if (Attrs.hasAttributes(i+1)) 1662 Out << ' ' << Attrs.getAsString(i+1); 1663 } 1664 } 1665 1666 // Finish printing arguments... 1667 if (FT->isVarArg()) { 1668 if (FT->getNumParams()) Out << ", "; 1669 Out << "..."; // Output varargs portion of signature! 1670 } 1671 Out << ')'; 1672 if (F->hasUnnamedAddr()) 1673 Out << " unnamed_addr"; 1674 if (Attrs.hasAttributes(AttributeSet::FunctionIndex)) 1675 Out << " #" << Machine.getAttributeGroupSlot(Attrs.getFnAttributes()); 1676 if (F->hasSection()) { 1677 Out << " section \""; 1678 PrintEscapedString(F->getSection(), Out); 1679 Out << '"'; 1680 } 1681 if (F->hasComdat()) { 1682 Out << " comdat "; 1683 PrintLLVMName(Out, F->getComdat()->getName(), ComdatPrefix); 1684 } 1685 if (F->getAlignment()) 1686 Out << " align " << F->getAlignment(); 1687 if (F->hasGC()) 1688 Out << " gc \"" << F->getGC() << '"'; 1689 if (F->hasPrefixData()) { 1690 Out << " prefix "; 1691 writeOperand(F->getPrefixData(), true); 1692 } 1693 if (F->isDeclaration()) { 1694 Out << '\n'; 1695 } else { 1696 Out << " {"; 1697 // Output all of the function's basic blocks. 1698 for (Function::const_iterator I = F->begin(), E = F->end(); I != E; ++I) 1699 printBasicBlock(I); 1700 1701 Out << "}\n"; 1702 } 1703 1704 Machine.purgeFunction(); 1705 } 1706 1707 /// printArgument - This member is called for every argument that is passed into 1708 /// the function. Simply print it out 1709 /// 1710 void AssemblyWriter::printArgument(const Argument *Arg, 1711 AttributeSet Attrs, unsigned Idx) { 1712 // Output type... 1713 TypePrinter.print(Arg->getType(), Out); 1714 1715 // Output parameter attributes list 1716 if (Attrs.hasAttributes(Idx)) 1717 Out << ' ' << Attrs.getAsString(Idx); 1718 1719 // Output name, if available... 1720 if (Arg->hasName()) { 1721 Out << ' '; 1722 PrintLLVMName(Out, Arg); 1723 } 1724 } 1725 1726 /// printBasicBlock - This member is called for each basic block in a method. 1727 /// 1728 void AssemblyWriter::printBasicBlock(const BasicBlock *BB) { 1729 if (BB->hasName()) { // Print out the label if it exists... 1730 Out << "\n"; 1731 PrintLLVMName(Out, BB->getName(), LabelPrefix); 1732 Out << ':'; 1733 } else if (!BB->use_empty()) { // Don't print block # of no uses... 1734 Out << "\n; <label>:"; 1735 int Slot = Machine.getLocalSlot(BB); 1736 if (Slot != -1) 1737 Out << Slot; 1738 else 1739 Out << "<badref>"; 1740 } 1741 1742 if (!BB->getParent()) { 1743 Out.PadToColumn(50); 1744 Out << "; Error: Block without parent!"; 1745 } else if (BB != &BB->getParent()->getEntryBlock()) { // Not the entry block? 1746 // Output predecessors for the block. 1747 Out.PadToColumn(50); 1748 Out << ";"; 1749 const_pred_iterator PI = pred_begin(BB), PE = pred_end(BB); 1750 1751 if (PI == PE) { 1752 Out << " No predecessors!"; 1753 } else { 1754 Out << " preds = "; 1755 writeOperand(*PI, false); 1756 for (++PI; PI != PE; ++PI) { 1757 Out << ", "; 1758 writeOperand(*PI, false); 1759 } 1760 } 1761 } 1762 1763 Out << "\n"; 1764 1765 if (AnnotationWriter) AnnotationWriter->emitBasicBlockStartAnnot(BB, Out); 1766 1767 // Output all of the instructions in the basic block... 1768 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I != E; ++I) { 1769 printInstructionLine(*I); 1770 } 1771 1772 if (AnnotationWriter) AnnotationWriter->emitBasicBlockEndAnnot(BB, Out); 1773 } 1774 1775 /// printInstructionLine - Print an instruction and a newline character. 1776 void AssemblyWriter::printInstructionLine(const Instruction &I) { 1777 printInstruction(I); 1778 Out << '\n'; 1779 } 1780 1781 /// printInfoComment - Print a little comment after the instruction indicating 1782 /// which slot it occupies. 1783 /// 1784 void AssemblyWriter::printInfoComment(const Value &V) { 1785 if (AnnotationWriter) 1786 AnnotationWriter->printInfoComment(V, Out); 1787 } 1788 1789 // This member is called for each Instruction in a function.. 1790 void AssemblyWriter::printInstruction(const Instruction &I) { 1791 if (AnnotationWriter) AnnotationWriter->emitInstructionAnnot(&I, Out); 1792 1793 // Print out indentation for an instruction. 1794 Out << " "; 1795 1796 // Print out name if it exists... 1797 if (I.hasName()) { 1798 PrintLLVMName(Out, &I); 1799 Out << " = "; 1800 } else if (!I.getType()->isVoidTy()) { 1801 // Print out the def slot taken. 1802 int SlotNum = Machine.getLocalSlot(&I); 1803 if (SlotNum == -1) 1804 Out << "<badref> = "; 1805 else 1806 Out << '%' << SlotNum << " = "; 1807 } 1808 1809 if (const CallInst *CI = dyn_cast<CallInst>(&I)) { 1810 if (CI->isMustTailCall()) 1811 Out << "musttail "; 1812 else if (CI->isTailCall()) 1813 Out << "tail "; 1814 } 1815 1816 // Print out the opcode... 1817 Out << I.getOpcodeName(); 1818 1819 // If this is an atomic load or store, print out the atomic marker. 1820 if ((isa<LoadInst>(I) && cast<LoadInst>(I).isAtomic()) || 1821 (isa<StoreInst>(I) && cast<StoreInst>(I).isAtomic())) 1822 Out << " atomic"; 1823 1824 if (isa<AtomicCmpXchgInst>(I) && cast<AtomicCmpXchgInst>(I).isWeak()) 1825 Out << " weak"; 1826 1827 // If this is a volatile operation, print out the volatile marker. 1828 if ((isa<LoadInst>(I) && cast<LoadInst>(I).isVolatile()) || 1829 (isa<StoreInst>(I) && cast<StoreInst>(I).isVolatile()) || 1830 (isa<AtomicCmpXchgInst>(I) && cast<AtomicCmpXchgInst>(I).isVolatile()) || 1831 (isa<AtomicRMWInst>(I) && cast<AtomicRMWInst>(I).isVolatile())) 1832 Out << " volatile"; 1833 1834 // Print out optimization information. 1835 WriteOptimizationInfo(Out, &I); 1836 1837 // Print out the compare instruction predicates 1838 if (const CmpInst *CI = dyn_cast<CmpInst>(&I)) 1839 Out << ' ' << getPredicateText(CI->getPredicate()); 1840 1841 // Print out the atomicrmw operation 1842 if (const AtomicRMWInst *RMWI = dyn_cast<AtomicRMWInst>(&I)) 1843 writeAtomicRMWOperation(Out, RMWI->getOperation()); 1844 1845 // Print out the type of the operands... 1846 const Value *Operand = I.getNumOperands() ? I.getOperand(0) : nullptr; 1847 1848 // Special case conditional branches to swizzle the condition out to the front 1849 if (isa<BranchInst>(I) && cast<BranchInst>(I).isConditional()) { 1850 const BranchInst &BI(cast<BranchInst>(I)); 1851 Out << ' '; 1852 writeOperand(BI.getCondition(), true); 1853 Out << ", "; 1854 writeOperand(BI.getSuccessor(0), true); 1855 Out << ", "; 1856 writeOperand(BI.getSuccessor(1), true); 1857 1858 } else if (isa<SwitchInst>(I)) { 1859 const SwitchInst& SI(cast<SwitchInst>(I)); 1860 // Special case switch instruction to get formatting nice and correct. 1861 Out << ' '; 1862 writeOperand(SI.getCondition(), true); 1863 Out << ", "; 1864 writeOperand(SI.getDefaultDest(), true); 1865 Out << " ["; 1866 for (SwitchInst::ConstCaseIt i = SI.case_begin(), e = SI.case_end(); 1867 i != e; ++i) { 1868 Out << "\n "; 1869 writeOperand(i.getCaseValue(), true); 1870 Out << ", "; 1871 writeOperand(i.getCaseSuccessor(), true); 1872 } 1873 Out << "\n ]"; 1874 } else if (isa<IndirectBrInst>(I)) { 1875 // Special case indirectbr instruction to get formatting nice and correct. 1876 Out << ' '; 1877 writeOperand(Operand, true); 1878 Out << ", ["; 1879 1880 for (unsigned i = 1, e = I.getNumOperands(); i != e; ++i) { 1881 if (i != 1) 1882 Out << ", "; 1883 writeOperand(I.getOperand(i), true); 1884 } 1885 Out << ']'; 1886 } else if (const PHINode *PN = dyn_cast<PHINode>(&I)) { 1887 Out << ' '; 1888 TypePrinter.print(I.getType(), Out); 1889 Out << ' '; 1890 1891 for (unsigned op = 0, Eop = PN->getNumIncomingValues(); op < Eop; ++op) { 1892 if (op) Out << ", "; 1893 Out << "[ "; 1894 writeOperand(PN->getIncomingValue(op), false); Out << ", "; 1895 writeOperand(PN->getIncomingBlock(op), false); Out << " ]"; 1896 } 1897 } else if (const ExtractValueInst *EVI = dyn_cast<ExtractValueInst>(&I)) { 1898 Out << ' '; 1899 writeOperand(I.getOperand(0), true); 1900 for (const unsigned *i = EVI->idx_begin(), *e = EVI->idx_end(); i != e; ++i) 1901 Out << ", " << *i; 1902 } else if (const InsertValueInst *IVI = dyn_cast<InsertValueInst>(&I)) { 1903 Out << ' '; 1904 writeOperand(I.getOperand(0), true); Out << ", "; 1905 writeOperand(I.getOperand(1), true); 1906 for (const unsigned *i = IVI->idx_begin(), *e = IVI->idx_end(); i != e; ++i) 1907 Out << ", " << *i; 1908 } else if (const LandingPadInst *LPI = dyn_cast<LandingPadInst>(&I)) { 1909 Out << ' '; 1910 TypePrinter.print(I.getType(), Out); 1911 Out << " personality "; 1912 writeOperand(I.getOperand(0), true); Out << '\n'; 1913 1914 if (LPI->isCleanup()) 1915 Out << " cleanup"; 1916 1917 for (unsigned i = 0, e = LPI->getNumClauses(); i != e; ++i) { 1918 if (i != 0 || LPI->isCleanup()) Out << "\n"; 1919 if (LPI->isCatch(i)) 1920 Out << " catch "; 1921 else 1922 Out << " filter "; 1923 1924 writeOperand(LPI->getClause(i), true); 1925 } 1926 } else if (isa<ReturnInst>(I) && !Operand) { 1927 Out << " void"; 1928 } else if (const CallInst *CI = dyn_cast<CallInst>(&I)) { 1929 // Print the calling convention being used. 1930 if (CI->getCallingConv() != CallingConv::C) { 1931 Out << " "; 1932 PrintCallingConv(CI->getCallingConv(), Out); 1933 } 1934 1935 Operand = CI->getCalledValue(); 1936 PointerType *PTy = cast<PointerType>(Operand->getType()); 1937 FunctionType *FTy = cast<FunctionType>(PTy->getElementType()); 1938 Type *RetTy = FTy->getReturnType(); 1939 const AttributeSet &PAL = CI->getAttributes(); 1940 1941 if (PAL.hasAttributes(AttributeSet::ReturnIndex)) 1942 Out << ' ' << PAL.getAsString(AttributeSet::ReturnIndex); 1943 1944 // If possible, print out the short form of the call instruction. We can 1945 // only do this if the first argument is a pointer to a nonvararg function, 1946 // and if the return type is not a pointer to a function. 1947 // 1948 Out << ' '; 1949 if (!FTy->isVarArg() && 1950 (!RetTy->isPointerTy() || 1951 !cast<PointerType>(RetTy)->getElementType()->isFunctionTy())) { 1952 TypePrinter.print(RetTy, Out); 1953 Out << ' '; 1954 writeOperand(Operand, false); 1955 } else { 1956 writeOperand(Operand, true); 1957 } 1958 Out << '('; 1959 for (unsigned op = 0, Eop = CI->getNumArgOperands(); op < Eop; ++op) { 1960 if (op > 0) 1961 Out << ", "; 1962 writeParamOperand(CI->getArgOperand(op), PAL, op + 1); 1963 } 1964 Out << ')'; 1965 if (PAL.hasAttributes(AttributeSet::FunctionIndex)) 1966 Out << " #" << Machine.getAttributeGroupSlot(PAL.getFnAttributes()); 1967 } else if (const InvokeInst *II = dyn_cast<InvokeInst>(&I)) { 1968 Operand = II->getCalledValue(); 1969 PointerType *PTy = cast<PointerType>(Operand->getType()); 1970 FunctionType *FTy = cast<FunctionType>(PTy->getElementType()); 1971 Type *RetTy = FTy->getReturnType(); 1972 const AttributeSet &PAL = II->getAttributes(); 1973 1974 // Print the calling convention being used. 1975 if (II->getCallingConv() != CallingConv::C) { 1976 Out << " "; 1977 PrintCallingConv(II->getCallingConv(), Out); 1978 } 1979 1980 if (PAL.hasAttributes(AttributeSet::ReturnIndex)) 1981 Out << ' ' << PAL.getAsString(AttributeSet::ReturnIndex); 1982 1983 // If possible, print out the short form of the invoke instruction. We can 1984 // only do this if the first argument is a pointer to a nonvararg function, 1985 // and if the return type is not a pointer to a function. 1986 // 1987 Out << ' '; 1988 if (!FTy->isVarArg() && 1989 (!RetTy->isPointerTy() || 1990 !cast<PointerType>(RetTy)->getElementType()->isFunctionTy())) { 1991 TypePrinter.print(RetTy, Out); 1992 Out << ' '; 1993 writeOperand(Operand, false); 1994 } else { 1995 writeOperand(Operand, true); 1996 } 1997 Out << '('; 1998 for (unsigned op = 0, Eop = II->getNumArgOperands(); op < Eop; ++op) { 1999 if (op) 2000 Out << ", "; 2001 writeParamOperand(II->getArgOperand(op), PAL, op + 1); 2002 } 2003 2004 Out << ')'; 2005 if (PAL.hasAttributes(AttributeSet::FunctionIndex)) 2006 Out << " #" << Machine.getAttributeGroupSlot(PAL.getFnAttributes()); 2007 2008 Out << "\n to "; 2009 writeOperand(II->getNormalDest(), true); 2010 Out << " unwind "; 2011 writeOperand(II->getUnwindDest(), true); 2012 2013 } else if (const AllocaInst *AI = dyn_cast<AllocaInst>(&I)) { 2014 Out << ' '; 2015 if (AI->isUsedWithInAlloca()) 2016 Out << "inalloca "; 2017 TypePrinter.print(AI->getAllocatedType(), Out); 2018 if (!AI->getArraySize() || AI->isArrayAllocation()) { 2019 Out << ", "; 2020 writeOperand(AI->getArraySize(), true); 2021 } 2022 if (AI->getAlignment()) { 2023 Out << ", align " << AI->getAlignment(); 2024 } 2025 } else if (isa<CastInst>(I)) { 2026 if (Operand) { 2027 Out << ' '; 2028 writeOperand(Operand, true); // Work with broken code 2029 } 2030 Out << " to "; 2031 TypePrinter.print(I.getType(), Out); 2032 } else if (isa<VAArgInst>(I)) { 2033 if (Operand) { 2034 Out << ' '; 2035 writeOperand(Operand, true); // Work with broken code 2036 } 2037 Out << ", "; 2038 TypePrinter.print(I.getType(), Out); 2039 } else if (Operand) { // Print the normal way. 2040 2041 // PrintAllTypes - Instructions who have operands of all the same type 2042 // omit the type from all but the first operand. If the instruction has 2043 // different type operands (for example br), then they are all printed. 2044 bool PrintAllTypes = false; 2045 Type *TheType = Operand->getType(); 2046 2047 // Select, Store and ShuffleVector always print all types. 2048 if (isa<SelectInst>(I) || isa<StoreInst>(I) || isa<ShuffleVectorInst>(I) 2049 || isa<ReturnInst>(I)) { 2050 PrintAllTypes = true; 2051 } else { 2052 for (unsigned i = 1, E = I.getNumOperands(); i != E; ++i) { 2053 Operand = I.getOperand(i); 2054 // note that Operand shouldn't be null, but the test helps make dump() 2055 // more tolerant of malformed IR 2056 if (Operand && Operand->getType() != TheType) { 2057 PrintAllTypes = true; // We have differing types! Print them all! 2058 break; 2059 } 2060 } 2061 } 2062 2063 if (!PrintAllTypes) { 2064 Out << ' '; 2065 TypePrinter.print(TheType, Out); 2066 } 2067 2068 Out << ' '; 2069 for (unsigned i = 0, E = I.getNumOperands(); i != E; ++i) { 2070 if (i) Out << ", "; 2071 writeOperand(I.getOperand(i), PrintAllTypes); 2072 } 2073 } 2074 2075 // Print atomic ordering/alignment for memory operations 2076 if (const LoadInst *LI = dyn_cast<LoadInst>(&I)) { 2077 if (LI->isAtomic()) 2078 writeAtomic(LI->getOrdering(), LI->getSynchScope()); 2079 if (LI->getAlignment()) 2080 Out << ", align " << LI->getAlignment(); 2081 } else if (const StoreInst *SI = dyn_cast<StoreInst>(&I)) { 2082 if (SI->isAtomic()) 2083 writeAtomic(SI->getOrdering(), SI->getSynchScope()); 2084 if (SI->getAlignment()) 2085 Out << ", align " << SI->getAlignment(); 2086 } else if (const AtomicCmpXchgInst *CXI = dyn_cast<AtomicCmpXchgInst>(&I)) { 2087 writeAtomicCmpXchg(CXI->getSuccessOrdering(), CXI->getFailureOrdering(), 2088 CXI->getSynchScope()); 2089 } else if (const AtomicRMWInst *RMWI = dyn_cast<AtomicRMWInst>(&I)) { 2090 writeAtomic(RMWI->getOrdering(), RMWI->getSynchScope()); 2091 } else if (const FenceInst *FI = dyn_cast<FenceInst>(&I)) { 2092 writeAtomic(FI->getOrdering(), FI->getSynchScope()); 2093 } 2094 2095 // Print Metadata info. 2096 SmallVector<std::pair<unsigned, MDNode*>, 4> InstMD; 2097 I.getAllMetadata(InstMD); 2098 if (!InstMD.empty()) { 2099 SmallVector<StringRef, 8> MDNames; 2100 I.getType()->getContext().getMDKindNames(MDNames); 2101 for (unsigned i = 0, e = InstMD.size(); i != e; ++i) { 2102 unsigned Kind = InstMD[i].first; 2103 if (Kind < MDNames.size()) { 2104 Out << ", !" << MDNames[Kind]; 2105 } else { 2106 Out << ", !<unknown kind #" << Kind << ">"; 2107 } 2108 Out << ' '; 2109 WriteAsOperandInternal(Out, InstMD[i].second, &TypePrinter, &Machine, 2110 TheModule); 2111 } 2112 } 2113 printInfoComment(I); 2114 } 2115 2116 static void WriteMDNodeComment(const MDNode *Node, 2117 formatted_raw_ostream &Out) { 2118 if (Node->getNumOperands() < 1) 2119 return; 2120 2121 Value *Op = Node->getOperand(0); 2122 if (!Op || !isa<ConstantInt>(Op) || cast<ConstantInt>(Op)->getBitWidth() < 32) 2123 return; 2124 2125 DIDescriptor Desc(Node); 2126 if (!Desc.Verify()) 2127 return; 2128 2129 unsigned Tag = Desc.getTag(); 2130 Out.PadToColumn(50); 2131 if (dwarf::TagString(Tag)) { 2132 Out << "; "; 2133 Desc.print(Out); 2134 } else if (Tag == dwarf::DW_TAG_user_base) { 2135 Out << "; [ DW_TAG_user_base ]"; 2136 } 2137 } 2138 2139 void AssemblyWriter::writeMDNode(unsigned Slot, const MDNode *Node) { 2140 Out << '!' << Slot << " = metadata "; 2141 printMDNodeBody(Node); 2142 } 2143 2144 void AssemblyWriter::writeAllMDNodes() { 2145 SmallVector<const MDNode *, 16> Nodes; 2146 Nodes.resize(Machine.mdn_size()); 2147 for (SlotTracker::mdn_iterator I = Machine.mdn_begin(), E = Machine.mdn_end(); 2148 I != E; ++I) 2149 Nodes[I->second] = cast<MDNode>(I->first); 2150 2151 for (unsigned i = 0, e = Nodes.size(); i != e; ++i) { 2152 writeMDNode(i, Nodes[i]); 2153 } 2154 } 2155 2156 void AssemblyWriter::printMDNodeBody(const MDNode *Node) { 2157 WriteMDNodeBodyInternal(Out, Node, &TypePrinter, &Machine, TheModule); 2158 WriteMDNodeComment(Node, Out); 2159 Out << "\n"; 2160 } 2161 2162 void AssemblyWriter::writeAllAttributeGroups() { 2163 std::vector<std::pair<AttributeSet, unsigned> > asVec; 2164 asVec.resize(Machine.as_size()); 2165 2166 for (SlotTracker::as_iterator I = Machine.as_begin(), E = Machine.as_end(); 2167 I != E; ++I) 2168 asVec[I->second] = *I; 2169 2170 for (std::vector<std::pair<AttributeSet, unsigned> >::iterator 2171 I = asVec.begin(), E = asVec.end(); I != E; ++I) 2172 Out << "attributes #" << I->second << " = { " 2173 << I->first.getAsString(AttributeSet::FunctionIndex, true) << " }\n"; 2174 } 2175 2176 } // namespace llvm 2177 2178 //===----------------------------------------------------------------------===// 2179 // External Interface declarations 2180 //===----------------------------------------------------------------------===// 2181 2182 void Module::print(raw_ostream &ROS, AssemblyAnnotationWriter *AAW) const { 2183 SlotTracker SlotTable(this); 2184 formatted_raw_ostream OS(ROS); 2185 AssemblyWriter W(OS, SlotTable, this, AAW); 2186 W.printModule(this); 2187 } 2188 2189 void NamedMDNode::print(raw_ostream &ROS) const { 2190 SlotTracker SlotTable(getParent()); 2191 formatted_raw_ostream OS(ROS); 2192 AssemblyWriter W(OS, SlotTable, getParent(), nullptr); 2193 W.printNamedMDNode(this); 2194 } 2195 2196 void Comdat::print(raw_ostream &ROS) const { 2197 PrintLLVMName(ROS, getName(), ComdatPrefix); 2198 ROS << " = comdat "; 2199 2200 switch (getSelectionKind()) { 2201 case Comdat::Any: 2202 ROS << "any"; 2203 break; 2204 case Comdat::ExactMatch: 2205 ROS << "exactmatch"; 2206 break; 2207 case Comdat::Largest: 2208 ROS << "largest"; 2209 break; 2210 case Comdat::NoDuplicates: 2211 ROS << "noduplicates"; 2212 break; 2213 case Comdat::SameSize: 2214 ROS << "samesize"; 2215 break; 2216 } 2217 2218 ROS << '\n'; 2219 } 2220 2221 void Type::print(raw_ostream &OS) const { 2222 TypePrinting TP; 2223 TP.print(const_cast<Type*>(this), OS); 2224 2225 // If the type is a named struct type, print the body as well. 2226 if (StructType *STy = dyn_cast<StructType>(const_cast<Type*>(this))) 2227 if (!STy->isLiteral()) { 2228 OS << " = type "; 2229 TP.printStructBody(STy, OS); 2230 } 2231 } 2232 2233 void Value::print(raw_ostream &ROS) const { 2234 formatted_raw_ostream OS(ROS); 2235 if (const Instruction *I = dyn_cast<Instruction>(this)) { 2236 const Function *F = I->getParent() ? I->getParent()->getParent() : nullptr; 2237 SlotTracker SlotTable(F); 2238 AssemblyWriter W(OS, SlotTable, getModuleFromVal(I), nullptr); 2239 W.printInstruction(*I); 2240 } else if (const BasicBlock *BB = dyn_cast<BasicBlock>(this)) { 2241 SlotTracker SlotTable(BB->getParent()); 2242 AssemblyWriter W(OS, SlotTable, getModuleFromVal(BB), nullptr); 2243 W.printBasicBlock(BB); 2244 } else if (const GlobalValue *GV = dyn_cast<GlobalValue>(this)) { 2245 SlotTracker SlotTable(GV->getParent()); 2246 AssemblyWriter W(OS, SlotTable, GV->getParent(), nullptr); 2247 if (const GlobalVariable *V = dyn_cast<GlobalVariable>(GV)) 2248 W.printGlobal(V); 2249 else if (const Function *F = dyn_cast<Function>(GV)) 2250 W.printFunction(F); 2251 else 2252 W.printAlias(cast<GlobalAlias>(GV)); 2253 } else if (const MDNode *N = dyn_cast<MDNode>(this)) { 2254 const Function *F = N->getFunction(); 2255 SlotTracker SlotTable(F); 2256 AssemblyWriter W(OS, SlotTable, F ? F->getParent() : nullptr, nullptr); 2257 W.printMDNodeBody(N); 2258 } else if (const Constant *C = dyn_cast<Constant>(this)) { 2259 TypePrinting TypePrinter; 2260 TypePrinter.print(C->getType(), OS); 2261 OS << ' '; 2262 WriteConstantInternal(OS, C, TypePrinter, nullptr, nullptr); 2263 } else if (isa<InlineAsm>(this) || isa<MDString>(this) || 2264 isa<Argument>(this)) { 2265 this->printAsOperand(OS); 2266 } else { 2267 llvm_unreachable("Unknown value to print out!"); 2268 } 2269 } 2270 2271 void Value::printAsOperand(raw_ostream &O, bool PrintType, const Module *M) const { 2272 // Fast path: Don't construct and populate a TypePrinting object if we 2273 // won't be needing any types printed. 2274 if (!PrintType && 2275 ((!isa<Constant>(this) && !isa<MDNode>(this)) || 2276 hasName() || isa<GlobalValue>(this))) { 2277 WriteAsOperandInternal(O, this, nullptr, nullptr, M); 2278 return; 2279 } 2280 2281 if (!M) 2282 M = getModuleFromVal(this); 2283 2284 TypePrinting TypePrinter; 2285 if (M) 2286 TypePrinter.incorporateTypes(*M); 2287 if (PrintType) { 2288 TypePrinter.print(getType(), O); 2289 O << ' '; 2290 } 2291 2292 WriteAsOperandInternal(O, this, &TypePrinter, nullptr, M); 2293 } 2294 2295 // Value::dump - allow easy printing of Values from the debugger. 2296 void Value::dump() const { print(dbgs()); dbgs() << '\n'; } 2297 2298 // Type::dump - allow easy printing of Types from the debugger. 2299 void Type::dump() const { print(dbgs()); } 2300 2301 // Module::dump() - Allow printing of Modules from the debugger. 2302 void Module::dump() const { print(dbgs(), nullptr); } 2303 2304 // \brief Allow printing of Comdats from the debugger. 2305 void Comdat::dump() const { print(dbgs()); } 2306 2307 // NamedMDNode::dump() - Allow printing of NamedMDNodes from the debugger. 2308 void NamedMDNode::dump() const { print(dbgs()); } 2309