1 //===- MachineFunction.cpp ------------------------------------------------===// 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 // Collect native machine code information for a function. This allows 11 // target-specific information about the generated code to be stored with each 12 // function. 13 // 14 //===----------------------------------------------------------------------===// 15 16 #include "llvm/CodeGen/MachineFunction.h" 17 #include "llvm/ADT/BitVector.h" 18 #include "llvm/ADT/DenseMap.h" 19 #include "llvm/ADT/DenseSet.h" 20 #include "llvm/ADT/STLExtras.h" 21 #include "llvm/ADT/SmallString.h" 22 #include "llvm/ADT/SmallVector.h" 23 #include "llvm/ADT/StringRef.h" 24 #include "llvm/ADT/Twine.h" 25 #include "llvm/Analysis/ConstantFolding.h" 26 #include "llvm/Analysis/EHPersonalities.h" 27 #include "llvm/CodeGen/MachineBasicBlock.h" 28 #include "llvm/CodeGen/MachineConstantPool.h" 29 #include "llvm/CodeGen/MachineFrameInfo.h" 30 #include "llvm/CodeGen/MachineInstr.h" 31 #include "llvm/CodeGen/MachineJumpTableInfo.h" 32 #include "llvm/CodeGen/MachineMemOperand.h" 33 #include "llvm/CodeGen/MachineModuleInfo.h" 34 #include "llvm/CodeGen/MachineRegisterInfo.h" 35 #include "llvm/CodeGen/PseudoSourceValue.h" 36 #include "llvm/CodeGen/TargetFrameLowering.h" 37 #include "llvm/CodeGen/TargetLowering.h" 38 #include "llvm/CodeGen/TargetRegisterInfo.h" 39 #include "llvm/CodeGen/TargetSubtargetInfo.h" 40 #include "llvm/CodeGen/WinEHFuncInfo.h" 41 #include "llvm/Config/llvm-config.h" 42 #include "llvm/IR/Attributes.h" 43 #include "llvm/IR/BasicBlock.h" 44 #include "llvm/IR/Constant.h" 45 #include "llvm/IR/DataLayout.h" 46 #include "llvm/IR/DerivedTypes.h" 47 #include "llvm/IR/Function.h" 48 #include "llvm/IR/GlobalValue.h" 49 #include "llvm/IR/Instruction.h" 50 #include "llvm/IR/Instructions.h" 51 #include "llvm/IR/Metadata.h" 52 #include "llvm/IR/Module.h" 53 #include "llvm/IR/ModuleSlotTracker.h" 54 #include "llvm/IR/Value.h" 55 #include "llvm/MC/MCContext.h" 56 #include "llvm/MC/MCSymbol.h" 57 #include "llvm/MC/SectionKind.h" 58 #include "llvm/Support/Casting.h" 59 #include "llvm/Support/CommandLine.h" 60 #include "llvm/Support/Compiler.h" 61 #include "llvm/Support/DOTGraphTraits.h" 62 #include "llvm/Support/Debug.h" 63 #include "llvm/Support/ErrorHandling.h" 64 #include "llvm/Support/GraphWriter.h" 65 #include "llvm/Support/raw_ostream.h" 66 #include "llvm/Target/TargetMachine.h" 67 #include <algorithm> 68 #include <cassert> 69 #include <cstddef> 70 #include <cstdint> 71 #include <iterator> 72 #include <string> 73 #include <utility> 74 #include <vector> 75 76 using namespace llvm; 77 78 #define DEBUG_TYPE "codegen" 79 80 static cl::opt<unsigned> 81 AlignAllFunctions("align-all-functions", 82 cl::desc("Force the alignment of all functions."), 83 cl::init(0), cl::Hidden); 84 85 static const char *getPropertyName(MachineFunctionProperties::Property Prop) { 86 using P = MachineFunctionProperties::Property; 87 88 switch(Prop) { 89 case P::FailedISel: return "FailedISel"; 90 case P::IsSSA: return "IsSSA"; 91 case P::Legalized: return "Legalized"; 92 case P::NoPHIs: return "NoPHIs"; 93 case P::NoVRegs: return "NoVRegs"; 94 case P::RegBankSelected: return "RegBankSelected"; 95 case P::Selected: return "Selected"; 96 case P::TracksLiveness: return "TracksLiveness"; 97 } 98 llvm_unreachable("Invalid machine function property"); 99 } 100 101 void MachineFunctionProperties::print(raw_ostream &OS) const { 102 const char *Separator = ""; 103 for (BitVector::size_type I = 0; I < Properties.size(); ++I) { 104 if (!Properties[I]) 105 continue; 106 OS << Separator << getPropertyName(static_cast<Property>(I)); 107 Separator = ", "; 108 } 109 } 110 111 //===----------------------------------------------------------------------===// 112 // MachineFunction implementation 113 //===----------------------------------------------------------------------===// 114 115 // Out-of-line virtual method. 116 MachineFunctionInfo::~MachineFunctionInfo() = default; 117 118 void ilist_alloc_traits<MachineBasicBlock>::deleteNode(MachineBasicBlock *MBB) { 119 MBB->getParent()->DeleteMachineBasicBlock(MBB); 120 } 121 122 static inline unsigned getFnStackAlignment(const TargetSubtargetInfo *STI, 123 const Function &F) { 124 if (F.hasFnAttribute(Attribute::StackAlignment)) 125 return F.getFnStackAlignment(); 126 return STI->getFrameLowering()->getStackAlignment(); 127 } 128 129 MachineFunction::MachineFunction(const Function &F, const TargetMachine &Target, 130 const TargetSubtargetInfo &STI, 131 unsigned FunctionNum, MachineModuleInfo &mmi) 132 : F(F), Target(Target), STI(&STI), Ctx(mmi.getContext()), MMI(mmi) { 133 FunctionNumber = FunctionNum; 134 init(); 135 } 136 137 void MachineFunction::init() { 138 // Assume the function starts in SSA form with correct liveness. 139 Properties.set(MachineFunctionProperties::Property::IsSSA); 140 Properties.set(MachineFunctionProperties::Property::TracksLiveness); 141 if (STI->getRegisterInfo()) 142 RegInfo = new (Allocator) MachineRegisterInfo(this); 143 else 144 RegInfo = nullptr; 145 146 MFInfo = nullptr; 147 // We can realign the stack if the target supports it and the user hasn't 148 // explicitly asked us not to. 149 bool CanRealignSP = STI->getFrameLowering()->isStackRealignable() && 150 !F.hasFnAttribute("no-realign-stack"); 151 FrameInfo = new (Allocator) MachineFrameInfo( 152 getFnStackAlignment(STI, F), /*StackRealignable=*/CanRealignSP, 153 /*ForceRealign=*/CanRealignSP && 154 F.hasFnAttribute(Attribute::StackAlignment)); 155 156 if (F.hasFnAttribute(Attribute::StackAlignment)) 157 FrameInfo->ensureMaxAlignment(F.getFnStackAlignment()); 158 159 ConstantPool = new (Allocator) MachineConstantPool(getDataLayout()); 160 Alignment = STI->getTargetLowering()->getMinFunctionAlignment(); 161 162 // FIXME: Shouldn't use pref alignment if explicit alignment is set on F. 163 // FIXME: Use Function::optForSize(). 164 if (!F.hasFnAttribute(Attribute::OptimizeForSize)) 165 Alignment = std::max(Alignment, 166 STI->getTargetLowering()->getPrefFunctionAlignment()); 167 168 if (AlignAllFunctions) 169 Alignment = AlignAllFunctions; 170 171 JumpTableInfo = nullptr; 172 173 if (isFuncletEHPersonality(classifyEHPersonality( 174 F.hasPersonalityFn() ? F.getPersonalityFn() : nullptr))) { 175 WinEHInfo = new (Allocator) WinEHFuncInfo(); 176 } 177 178 assert(Target.isCompatibleDataLayout(getDataLayout()) && 179 "Can't create a MachineFunction using a Module with a " 180 "Target-incompatible DataLayout attached\n"); 181 182 PSVManager = 183 llvm::make_unique<PseudoSourceValueManager>(*(getSubtarget(). 184 getInstrInfo())); 185 } 186 187 MachineFunction::~MachineFunction() { 188 clear(); 189 } 190 191 void MachineFunction::clear() { 192 Properties.reset(); 193 // Don't call destructors on MachineInstr and MachineOperand. All of their 194 // memory comes from the BumpPtrAllocator which is about to be purged. 195 // 196 // Do call MachineBasicBlock destructors, it contains std::vectors. 197 for (iterator I = begin(), E = end(); I != E; I = BasicBlocks.erase(I)) 198 I->Insts.clearAndLeakNodesUnsafely(); 199 MBBNumbering.clear(); 200 201 InstructionRecycler.clear(Allocator); 202 OperandRecycler.clear(Allocator); 203 BasicBlockRecycler.clear(Allocator); 204 CodeViewAnnotations.clear(); 205 VariableDbgInfos.clear(); 206 if (RegInfo) { 207 RegInfo->~MachineRegisterInfo(); 208 Allocator.Deallocate(RegInfo); 209 } 210 if (MFInfo) { 211 MFInfo->~MachineFunctionInfo(); 212 Allocator.Deallocate(MFInfo); 213 } 214 215 FrameInfo->~MachineFrameInfo(); 216 Allocator.Deallocate(FrameInfo); 217 218 ConstantPool->~MachineConstantPool(); 219 Allocator.Deallocate(ConstantPool); 220 221 if (JumpTableInfo) { 222 JumpTableInfo->~MachineJumpTableInfo(); 223 Allocator.Deallocate(JumpTableInfo); 224 } 225 226 if (WinEHInfo) { 227 WinEHInfo->~WinEHFuncInfo(); 228 Allocator.Deallocate(WinEHInfo); 229 } 230 } 231 232 const DataLayout &MachineFunction::getDataLayout() const { 233 return F.getParent()->getDataLayout(); 234 } 235 236 /// Get the JumpTableInfo for this function. 237 /// If it does not already exist, allocate one. 238 MachineJumpTableInfo *MachineFunction:: 239 getOrCreateJumpTableInfo(unsigned EntryKind) { 240 if (JumpTableInfo) return JumpTableInfo; 241 242 JumpTableInfo = new (Allocator) 243 MachineJumpTableInfo((MachineJumpTableInfo::JTEntryKind)EntryKind); 244 return JumpTableInfo; 245 } 246 247 /// Should we be emitting segmented stack stuff for the function 248 bool MachineFunction::shouldSplitStack() const { 249 return getFunction().hasFnAttribute("split-stack"); 250 } 251 252 /// This discards all of the MachineBasicBlock numbers and recomputes them. 253 /// This guarantees that the MBB numbers are sequential, dense, and match the 254 /// ordering of the blocks within the function. If a specific MachineBasicBlock 255 /// is specified, only that block and those after it are renumbered. 256 void MachineFunction::RenumberBlocks(MachineBasicBlock *MBB) { 257 if (empty()) { MBBNumbering.clear(); return; } 258 MachineFunction::iterator MBBI, E = end(); 259 if (MBB == nullptr) 260 MBBI = begin(); 261 else 262 MBBI = MBB->getIterator(); 263 264 // Figure out the block number this should have. 265 unsigned BlockNo = 0; 266 if (MBBI != begin()) 267 BlockNo = std::prev(MBBI)->getNumber() + 1; 268 269 for (; MBBI != E; ++MBBI, ++BlockNo) { 270 if (MBBI->getNumber() != (int)BlockNo) { 271 // Remove use of the old number. 272 if (MBBI->getNumber() != -1) { 273 assert(MBBNumbering[MBBI->getNumber()] == &*MBBI && 274 "MBB number mismatch!"); 275 MBBNumbering[MBBI->getNumber()] = nullptr; 276 } 277 278 // If BlockNo is already taken, set that block's number to -1. 279 if (MBBNumbering[BlockNo]) 280 MBBNumbering[BlockNo]->setNumber(-1); 281 282 MBBNumbering[BlockNo] = &*MBBI; 283 MBBI->setNumber(BlockNo); 284 } 285 } 286 287 // Okay, all the blocks are renumbered. If we have compactified the block 288 // numbering, shrink MBBNumbering now. 289 assert(BlockNo <= MBBNumbering.size() && "Mismatch!"); 290 MBBNumbering.resize(BlockNo); 291 } 292 293 /// Allocate a new MachineInstr. Use this instead of `new MachineInstr'. 294 MachineInstr *MachineFunction::CreateMachineInstr(const MCInstrDesc &MCID, 295 const DebugLoc &DL, 296 bool NoImp) { 297 return new (InstructionRecycler.Allocate<MachineInstr>(Allocator)) 298 MachineInstr(*this, MCID, DL, NoImp); 299 } 300 301 /// Create a new MachineInstr which is a copy of the 'Orig' instruction, 302 /// identical in all ways except the instruction has no parent, prev, or next. 303 MachineInstr * 304 MachineFunction::CloneMachineInstr(const MachineInstr *Orig) { 305 return new (InstructionRecycler.Allocate<MachineInstr>(Allocator)) 306 MachineInstr(*this, *Orig); 307 } 308 309 MachineInstr &MachineFunction::CloneMachineInstrBundle(MachineBasicBlock &MBB, 310 MachineBasicBlock::iterator InsertBefore, const MachineInstr &Orig) { 311 MachineInstr *FirstClone = nullptr; 312 MachineBasicBlock::const_instr_iterator I = Orig.getIterator(); 313 while (true) { 314 MachineInstr *Cloned = CloneMachineInstr(&*I); 315 MBB.insert(InsertBefore, Cloned); 316 if (FirstClone == nullptr) { 317 FirstClone = Cloned; 318 } else { 319 Cloned->bundleWithPred(); 320 } 321 322 if (!I->isBundledWithSucc()) 323 break; 324 ++I; 325 } 326 return *FirstClone; 327 } 328 329 /// Delete the given MachineInstr. 330 /// 331 /// This function also serves as the MachineInstr destructor - the real 332 /// ~MachineInstr() destructor must be empty. 333 void 334 MachineFunction::DeleteMachineInstr(MachineInstr *MI) { 335 // Strip it for parts. The operand array and the MI object itself are 336 // independently recyclable. 337 if (MI->Operands) 338 deallocateOperandArray(MI->CapOperands, MI->Operands); 339 // Don't call ~MachineInstr() which must be trivial anyway because 340 // ~MachineFunction drops whole lists of MachineInstrs wihout calling their 341 // destructors. 342 InstructionRecycler.Deallocate(Allocator, MI); 343 } 344 345 /// Allocate a new MachineBasicBlock. Use this instead of 346 /// `new MachineBasicBlock'. 347 MachineBasicBlock * 348 MachineFunction::CreateMachineBasicBlock(const BasicBlock *bb) { 349 return new (BasicBlockRecycler.Allocate<MachineBasicBlock>(Allocator)) 350 MachineBasicBlock(*this, bb); 351 } 352 353 /// Delete the given MachineBasicBlock. 354 void 355 MachineFunction::DeleteMachineBasicBlock(MachineBasicBlock *MBB) { 356 assert(MBB->getParent() == this && "MBB parent mismatch!"); 357 MBB->~MachineBasicBlock(); 358 BasicBlockRecycler.Deallocate(Allocator, MBB); 359 } 360 361 MachineMemOperand *MachineFunction::getMachineMemOperand( 362 MachinePointerInfo PtrInfo, MachineMemOperand::Flags f, uint64_t s, 363 unsigned base_alignment, const AAMDNodes &AAInfo, const MDNode *Ranges, 364 SyncScope::ID SSID, AtomicOrdering Ordering, 365 AtomicOrdering FailureOrdering) { 366 return new (Allocator) 367 MachineMemOperand(PtrInfo, f, s, base_alignment, AAInfo, Ranges, 368 SSID, Ordering, FailureOrdering); 369 } 370 371 MachineMemOperand * 372 MachineFunction::getMachineMemOperand(const MachineMemOperand *MMO, 373 int64_t Offset, uint64_t Size) { 374 if (MMO->getValue()) 375 return new (Allocator) 376 MachineMemOperand(MachinePointerInfo(MMO->getValue(), 377 MMO->getOffset()+Offset), 378 MMO->getFlags(), Size, MMO->getBaseAlignment(), 379 AAMDNodes(), nullptr, MMO->getSyncScopeID(), 380 MMO->getOrdering(), MMO->getFailureOrdering()); 381 return new (Allocator) 382 MachineMemOperand(MachinePointerInfo(MMO->getPseudoValue(), 383 MMO->getOffset()+Offset), 384 MMO->getFlags(), Size, MMO->getBaseAlignment(), 385 AAMDNodes(), nullptr, MMO->getSyncScopeID(), 386 MMO->getOrdering(), MMO->getFailureOrdering()); 387 } 388 389 MachineMemOperand * 390 MachineFunction::getMachineMemOperand(const MachineMemOperand *MMO, 391 const AAMDNodes &AAInfo) { 392 MachinePointerInfo MPI = MMO->getValue() ? 393 MachinePointerInfo(MMO->getValue(), MMO->getOffset()) : 394 MachinePointerInfo(MMO->getPseudoValue(), MMO->getOffset()); 395 396 return new (Allocator) 397 MachineMemOperand(MPI, MMO->getFlags(), MMO->getSize(), 398 MMO->getBaseAlignment(), AAInfo, 399 MMO->getRanges(), MMO->getSyncScopeID(), 400 MMO->getOrdering(), MMO->getFailureOrdering()); 401 } 402 403 MachineInstr::mmo_iterator 404 MachineFunction::allocateMemRefsArray(unsigned long Num) { 405 return Allocator.Allocate<MachineMemOperand *>(Num); 406 } 407 408 std::pair<MachineInstr::mmo_iterator, MachineInstr::mmo_iterator> 409 MachineFunction::extractLoadMemRefs(MachineInstr::mmo_iterator Begin, 410 MachineInstr::mmo_iterator End) { 411 // Count the number of load mem refs. 412 unsigned Num = 0; 413 for (MachineInstr::mmo_iterator I = Begin; I != End; ++I) 414 if ((*I)->isLoad()) 415 ++Num; 416 417 // Allocate a new array and populate it with the load information. 418 MachineInstr::mmo_iterator Result = allocateMemRefsArray(Num); 419 unsigned Index = 0; 420 for (MachineInstr::mmo_iterator I = Begin; I != End; ++I) { 421 if ((*I)->isLoad()) { 422 if (!(*I)->isStore()) 423 // Reuse the MMO. 424 Result[Index] = *I; 425 else { 426 // Clone the MMO and unset the store flag. 427 MachineMemOperand *JustLoad = 428 getMachineMemOperand((*I)->getPointerInfo(), 429 (*I)->getFlags() & ~MachineMemOperand::MOStore, 430 (*I)->getSize(), (*I)->getBaseAlignment(), 431 (*I)->getAAInfo(), nullptr, 432 (*I)->getSyncScopeID(), (*I)->getOrdering(), 433 (*I)->getFailureOrdering()); 434 Result[Index] = JustLoad; 435 } 436 ++Index; 437 } 438 } 439 return std::make_pair(Result, Result + Num); 440 } 441 442 std::pair<MachineInstr::mmo_iterator, MachineInstr::mmo_iterator> 443 MachineFunction::extractStoreMemRefs(MachineInstr::mmo_iterator Begin, 444 MachineInstr::mmo_iterator End) { 445 // Count the number of load mem refs. 446 unsigned Num = 0; 447 for (MachineInstr::mmo_iterator I = Begin; I != End; ++I) 448 if ((*I)->isStore()) 449 ++Num; 450 451 // Allocate a new array and populate it with the store information. 452 MachineInstr::mmo_iterator Result = allocateMemRefsArray(Num); 453 unsigned Index = 0; 454 for (MachineInstr::mmo_iterator I = Begin; I != End; ++I) { 455 if ((*I)->isStore()) { 456 if (!(*I)->isLoad()) 457 // Reuse the MMO. 458 Result[Index] = *I; 459 else { 460 // Clone the MMO and unset the load flag. 461 MachineMemOperand *JustStore = 462 getMachineMemOperand((*I)->getPointerInfo(), 463 (*I)->getFlags() & ~MachineMemOperand::MOLoad, 464 (*I)->getSize(), (*I)->getBaseAlignment(), 465 (*I)->getAAInfo(), nullptr, 466 (*I)->getSyncScopeID(), (*I)->getOrdering(), 467 (*I)->getFailureOrdering()); 468 Result[Index] = JustStore; 469 } 470 ++Index; 471 } 472 } 473 return std::make_pair(Result, Result + Num); 474 } 475 476 const char *MachineFunction::createExternalSymbolName(StringRef Name) { 477 char *Dest = Allocator.Allocate<char>(Name.size() + 1); 478 std::copy(Name.begin(), Name.end(), Dest); 479 Dest[Name.size()] = 0; 480 return Dest; 481 } 482 483 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) 484 LLVM_DUMP_METHOD void MachineFunction::dump() const { 485 print(dbgs()); 486 } 487 #endif 488 489 StringRef MachineFunction::getName() const { 490 return getFunction().getName(); 491 } 492 493 void MachineFunction::print(raw_ostream &OS, const SlotIndexes *Indexes) const { 494 OS << "# Machine code for function " << getName() << ": "; 495 getProperties().print(OS); 496 OS << '\n'; 497 498 // Print Frame Information 499 FrameInfo->print(*this, OS); 500 501 // Print JumpTable Information 502 if (JumpTableInfo) 503 JumpTableInfo->print(OS); 504 505 // Print Constant Pool 506 ConstantPool->print(OS); 507 508 const TargetRegisterInfo *TRI = getSubtarget().getRegisterInfo(); 509 510 if (RegInfo && !RegInfo->livein_empty()) { 511 OS << "Function Live Ins: "; 512 for (MachineRegisterInfo::livein_iterator 513 I = RegInfo->livein_begin(), E = RegInfo->livein_end(); I != E; ++I) { 514 OS << printReg(I->first, TRI); 515 if (I->second) 516 OS << " in " << printReg(I->second, TRI); 517 if (std::next(I) != E) 518 OS << ", "; 519 } 520 OS << '\n'; 521 } 522 523 ModuleSlotTracker MST(getFunction().getParent()); 524 MST.incorporateFunction(getFunction()); 525 for (const auto &BB : *this) { 526 OS << '\n'; 527 // If we print the whole function, print it at its most verbose level. 528 BB.print(OS, MST, Indexes, /*IsStandalone=*/true); 529 } 530 531 OS << "\n# End machine code for function " << getName() << ".\n\n"; 532 } 533 534 namespace llvm { 535 536 template<> 537 struct DOTGraphTraits<const MachineFunction*> : public DefaultDOTGraphTraits { 538 DOTGraphTraits(bool isSimple = false) : DefaultDOTGraphTraits(isSimple) {} 539 540 static std::string getGraphName(const MachineFunction *F) { 541 return ("CFG for '" + F->getName() + "' function").str(); 542 } 543 544 std::string getNodeLabel(const MachineBasicBlock *Node, 545 const MachineFunction *Graph) { 546 std::string OutStr; 547 { 548 raw_string_ostream OSS(OutStr); 549 550 if (isSimple()) { 551 OSS << printMBBReference(*Node); 552 if (const BasicBlock *BB = Node->getBasicBlock()) 553 OSS << ": " << BB->getName(); 554 } else 555 Node->print(OSS); 556 } 557 558 if (OutStr[0] == '\n') OutStr.erase(OutStr.begin()); 559 560 // Process string output to make it nicer... 561 for (unsigned i = 0; i != OutStr.length(); ++i) 562 if (OutStr[i] == '\n') { // Left justify 563 OutStr[i] = '\\'; 564 OutStr.insert(OutStr.begin()+i+1, 'l'); 565 } 566 return OutStr; 567 } 568 }; 569 570 } // end namespace llvm 571 572 void MachineFunction::viewCFG() const 573 { 574 #ifndef NDEBUG 575 ViewGraph(this, "mf" + getName()); 576 #else 577 errs() << "MachineFunction::viewCFG is only available in debug builds on " 578 << "systems with Graphviz or gv!\n"; 579 #endif // NDEBUG 580 } 581 582 void MachineFunction::viewCFGOnly() const 583 { 584 #ifndef NDEBUG 585 ViewGraph(this, "mf" + getName(), true); 586 #else 587 errs() << "MachineFunction::viewCFGOnly is only available in debug builds on " 588 << "systems with Graphviz or gv!\n"; 589 #endif // NDEBUG 590 } 591 592 /// Add the specified physical register as a live-in value and 593 /// create a corresponding virtual register for it. 594 unsigned MachineFunction::addLiveIn(unsigned PReg, 595 const TargetRegisterClass *RC) { 596 MachineRegisterInfo &MRI = getRegInfo(); 597 unsigned VReg = MRI.getLiveInVirtReg(PReg); 598 if (VReg) { 599 const TargetRegisterClass *VRegRC = MRI.getRegClass(VReg); 600 (void)VRegRC; 601 // A physical register can be added several times. 602 // Between two calls, the register class of the related virtual register 603 // may have been constrained to match some operation constraints. 604 // In that case, check that the current register class includes the 605 // physical register and is a sub class of the specified RC. 606 assert((VRegRC == RC || (VRegRC->contains(PReg) && 607 RC->hasSubClassEq(VRegRC))) && 608 "Register class mismatch!"); 609 return VReg; 610 } 611 VReg = MRI.createVirtualRegister(RC); 612 MRI.addLiveIn(PReg, VReg); 613 return VReg; 614 } 615 616 /// Return the MCSymbol for the specified non-empty jump table. 617 /// If isLinkerPrivate is specified, an 'l' label is returned, otherwise a 618 /// normal 'L' label is returned. 619 MCSymbol *MachineFunction::getJTISymbol(unsigned JTI, MCContext &Ctx, 620 bool isLinkerPrivate) const { 621 const DataLayout &DL = getDataLayout(); 622 assert(JumpTableInfo && "No jump tables"); 623 assert(JTI < JumpTableInfo->getJumpTables().size() && "Invalid JTI!"); 624 625 StringRef Prefix = isLinkerPrivate ? DL.getLinkerPrivateGlobalPrefix() 626 : DL.getPrivateGlobalPrefix(); 627 SmallString<60> Name; 628 raw_svector_ostream(Name) 629 << Prefix << "JTI" << getFunctionNumber() << '_' << JTI; 630 return Ctx.getOrCreateSymbol(Name); 631 } 632 633 /// Return a function-local symbol to represent the PIC base. 634 MCSymbol *MachineFunction::getPICBaseSymbol() const { 635 const DataLayout &DL = getDataLayout(); 636 return Ctx.getOrCreateSymbol(Twine(DL.getPrivateGlobalPrefix()) + 637 Twine(getFunctionNumber()) + "$pb"); 638 } 639 640 /// \name Exception Handling 641 /// \{ 642 643 LandingPadInfo & 644 MachineFunction::getOrCreateLandingPadInfo(MachineBasicBlock *LandingPad) { 645 unsigned N = LandingPads.size(); 646 for (unsigned i = 0; i < N; ++i) { 647 LandingPadInfo &LP = LandingPads[i]; 648 if (LP.LandingPadBlock == LandingPad) 649 return LP; 650 } 651 652 LandingPads.push_back(LandingPadInfo(LandingPad)); 653 return LandingPads[N]; 654 } 655 656 void MachineFunction::addInvoke(MachineBasicBlock *LandingPad, 657 MCSymbol *BeginLabel, MCSymbol *EndLabel) { 658 LandingPadInfo &LP = getOrCreateLandingPadInfo(LandingPad); 659 LP.BeginLabels.push_back(BeginLabel); 660 LP.EndLabels.push_back(EndLabel); 661 } 662 663 MCSymbol *MachineFunction::addLandingPad(MachineBasicBlock *LandingPad) { 664 MCSymbol *LandingPadLabel = Ctx.createTempSymbol(); 665 LandingPadInfo &LP = getOrCreateLandingPadInfo(LandingPad); 666 LP.LandingPadLabel = LandingPadLabel; 667 return LandingPadLabel; 668 } 669 670 void MachineFunction::addCatchTypeInfo(MachineBasicBlock *LandingPad, 671 ArrayRef<const GlobalValue *> TyInfo) { 672 LandingPadInfo &LP = getOrCreateLandingPadInfo(LandingPad); 673 for (unsigned N = TyInfo.size(); N; --N) 674 LP.TypeIds.push_back(getTypeIDFor(TyInfo[N - 1])); 675 } 676 677 void MachineFunction::addFilterTypeInfo(MachineBasicBlock *LandingPad, 678 ArrayRef<const GlobalValue *> TyInfo) { 679 LandingPadInfo &LP = getOrCreateLandingPadInfo(LandingPad); 680 std::vector<unsigned> IdsInFilter(TyInfo.size()); 681 for (unsigned I = 0, E = TyInfo.size(); I != E; ++I) 682 IdsInFilter[I] = getTypeIDFor(TyInfo[I]); 683 LP.TypeIds.push_back(getFilterIDFor(IdsInFilter)); 684 } 685 686 void MachineFunction::tidyLandingPads(DenseMap<MCSymbol*, uintptr_t> *LPMap) { 687 for (unsigned i = 0; i != LandingPads.size(); ) { 688 LandingPadInfo &LandingPad = LandingPads[i]; 689 if (LandingPad.LandingPadLabel && 690 !LandingPad.LandingPadLabel->isDefined() && 691 (!LPMap || (*LPMap)[LandingPad.LandingPadLabel] == 0)) 692 LandingPad.LandingPadLabel = nullptr; 693 694 // Special case: we *should* emit LPs with null LP MBB. This indicates 695 // "nounwind" case. 696 if (!LandingPad.LandingPadLabel && LandingPad.LandingPadBlock) { 697 LandingPads.erase(LandingPads.begin() + i); 698 continue; 699 } 700 701 for (unsigned j = 0, e = LandingPads[i].BeginLabels.size(); j != e; ++j) { 702 MCSymbol *BeginLabel = LandingPad.BeginLabels[j]; 703 MCSymbol *EndLabel = LandingPad.EndLabels[j]; 704 if ((BeginLabel->isDefined() || 705 (LPMap && (*LPMap)[BeginLabel] != 0)) && 706 (EndLabel->isDefined() || 707 (LPMap && (*LPMap)[EndLabel] != 0))) continue; 708 709 LandingPad.BeginLabels.erase(LandingPad.BeginLabels.begin() + j); 710 LandingPad.EndLabels.erase(LandingPad.EndLabels.begin() + j); 711 --j; 712 --e; 713 } 714 715 // Remove landing pads with no try-ranges. 716 if (LandingPads[i].BeginLabels.empty()) { 717 LandingPads.erase(LandingPads.begin() + i); 718 continue; 719 } 720 721 // If there is no landing pad, ensure that the list of typeids is empty. 722 // If the only typeid is a cleanup, this is the same as having no typeids. 723 if (!LandingPad.LandingPadBlock || 724 (LandingPad.TypeIds.size() == 1 && !LandingPad.TypeIds[0])) 725 LandingPad.TypeIds.clear(); 726 ++i; 727 } 728 } 729 730 void MachineFunction::addCleanup(MachineBasicBlock *LandingPad) { 731 LandingPadInfo &LP = getOrCreateLandingPadInfo(LandingPad); 732 LP.TypeIds.push_back(0); 733 } 734 735 void MachineFunction::addSEHCatchHandler(MachineBasicBlock *LandingPad, 736 const Function *Filter, 737 const BlockAddress *RecoverBA) { 738 LandingPadInfo &LP = getOrCreateLandingPadInfo(LandingPad); 739 SEHHandler Handler; 740 Handler.FilterOrFinally = Filter; 741 Handler.RecoverBA = RecoverBA; 742 LP.SEHHandlers.push_back(Handler); 743 } 744 745 void MachineFunction::addSEHCleanupHandler(MachineBasicBlock *LandingPad, 746 const Function *Cleanup) { 747 LandingPadInfo &LP = getOrCreateLandingPadInfo(LandingPad); 748 SEHHandler Handler; 749 Handler.FilterOrFinally = Cleanup; 750 Handler.RecoverBA = nullptr; 751 LP.SEHHandlers.push_back(Handler); 752 } 753 754 void MachineFunction::setCallSiteLandingPad(MCSymbol *Sym, 755 ArrayRef<unsigned> Sites) { 756 LPadToCallSiteMap[Sym].append(Sites.begin(), Sites.end()); 757 } 758 759 unsigned MachineFunction::getTypeIDFor(const GlobalValue *TI) { 760 for (unsigned i = 0, N = TypeInfos.size(); i != N; ++i) 761 if (TypeInfos[i] == TI) return i + 1; 762 763 TypeInfos.push_back(TI); 764 return TypeInfos.size(); 765 } 766 767 int MachineFunction::getFilterIDFor(std::vector<unsigned> &TyIds) { 768 // If the new filter coincides with the tail of an existing filter, then 769 // re-use the existing filter. Folding filters more than this requires 770 // re-ordering filters and/or their elements - probably not worth it. 771 for (std::vector<unsigned>::iterator I = FilterEnds.begin(), 772 E = FilterEnds.end(); I != E; ++I) { 773 unsigned i = *I, j = TyIds.size(); 774 775 while (i && j) 776 if (FilterIds[--i] != TyIds[--j]) 777 goto try_next; 778 779 if (!j) 780 // The new filter coincides with range [i, end) of the existing filter. 781 return -(1 + i); 782 783 try_next:; 784 } 785 786 // Add the new filter. 787 int FilterID = -(1 + FilterIds.size()); 788 FilterIds.reserve(FilterIds.size() + TyIds.size() + 1); 789 FilterIds.insert(FilterIds.end(), TyIds.begin(), TyIds.end()); 790 FilterEnds.push_back(FilterIds.size()); 791 FilterIds.push_back(0); // terminator 792 return FilterID; 793 } 794 795 void llvm::addLandingPadInfo(const LandingPadInst &I, MachineBasicBlock &MBB) { 796 MachineFunction &MF = *MBB.getParent(); 797 if (const auto *PF = dyn_cast<Function>( 798 I.getParent()->getParent()->getPersonalityFn()->stripPointerCasts())) 799 MF.getMMI().addPersonality(PF); 800 801 if (I.isCleanup()) 802 MF.addCleanup(&MBB); 803 804 // FIXME: New EH - Add the clauses in reverse order. This isn't 100% correct, 805 // but we need to do it this way because of how the DWARF EH emitter 806 // processes the clauses. 807 for (unsigned i = I.getNumClauses(); i != 0; --i) { 808 Value *Val = I.getClause(i - 1); 809 if (I.isCatch(i - 1)) { 810 MF.addCatchTypeInfo(&MBB, 811 dyn_cast<GlobalValue>(Val->stripPointerCasts())); 812 } else { 813 // Add filters in a list. 814 Constant *CVal = cast<Constant>(Val); 815 SmallVector<const GlobalValue *, 4> FilterList; 816 for (User::op_iterator II = CVal->op_begin(), IE = CVal->op_end(); 817 II != IE; ++II) 818 FilterList.push_back(cast<GlobalValue>((*II)->stripPointerCasts())); 819 820 MF.addFilterTypeInfo(&MBB, FilterList); 821 } 822 } 823 } 824 825 /// \} 826 827 //===----------------------------------------------------------------------===// 828 // MachineJumpTableInfo implementation 829 //===----------------------------------------------------------------------===// 830 831 /// Return the size of each entry in the jump table. 832 unsigned MachineJumpTableInfo::getEntrySize(const DataLayout &TD) const { 833 // The size of a jump table entry is 4 bytes unless the entry is just the 834 // address of a block, in which case it is the pointer size. 835 switch (getEntryKind()) { 836 case MachineJumpTableInfo::EK_BlockAddress: 837 return TD.getPointerSize(); 838 case MachineJumpTableInfo::EK_GPRel64BlockAddress: 839 return 8; 840 case MachineJumpTableInfo::EK_GPRel32BlockAddress: 841 case MachineJumpTableInfo::EK_LabelDifference32: 842 case MachineJumpTableInfo::EK_Custom32: 843 return 4; 844 case MachineJumpTableInfo::EK_Inline: 845 return 0; 846 } 847 llvm_unreachable("Unknown jump table encoding!"); 848 } 849 850 /// Return the alignment of each entry in the jump table. 851 unsigned MachineJumpTableInfo::getEntryAlignment(const DataLayout &TD) const { 852 // The alignment of a jump table entry is the alignment of int32 unless the 853 // entry is just the address of a block, in which case it is the pointer 854 // alignment. 855 switch (getEntryKind()) { 856 case MachineJumpTableInfo::EK_BlockAddress: 857 return TD.getPointerABIAlignment(0); 858 case MachineJumpTableInfo::EK_GPRel64BlockAddress: 859 return TD.getABIIntegerTypeAlignment(64); 860 case MachineJumpTableInfo::EK_GPRel32BlockAddress: 861 case MachineJumpTableInfo::EK_LabelDifference32: 862 case MachineJumpTableInfo::EK_Custom32: 863 return TD.getABIIntegerTypeAlignment(32); 864 case MachineJumpTableInfo::EK_Inline: 865 return 1; 866 } 867 llvm_unreachable("Unknown jump table encoding!"); 868 } 869 870 /// Create a new jump table entry in the jump table info. 871 unsigned MachineJumpTableInfo::createJumpTableIndex( 872 const std::vector<MachineBasicBlock*> &DestBBs) { 873 assert(!DestBBs.empty() && "Cannot create an empty jump table!"); 874 JumpTables.push_back(MachineJumpTableEntry(DestBBs)); 875 return JumpTables.size()-1; 876 } 877 878 /// If Old is the target of any jump tables, update the jump tables to branch 879 /// to New instead. 880 bool MachineJumpTableInfo::ReplaceMBBInJumpTables(MachineBasicBlock *Old, 881 MachineBasicBlock *New) { 882 assert(Old != New && "Not making a change?"); 883 bool MadeChange = false; 884 for (size_t i = 0, e = JumpTables.size(); i != e; ++i) 885 ReplaceMBBInJumpTable(i, Old, New); 886 return MadeChange; 887 } 888 889 /// If Old is a target of the jump tables, update the jump table to branch to 890 /// New instead. 891 bool MachineJumpTableInfo::ReplaceMBBInJumpTable(unsigned Idx, 892 MachineBasicBlock *Old, 893 MachineBasicBlock *New) { 894 assert(Old != New && "Not making a change?"); 895 bool MadeChange = false; 896 MachineJumpTableEntry &JTE = JumpTables[Idx]; 897 for (size_t j = 0, e = JTE.MBBs.size(); j != e; ++j) 898 if (JTE.MBBs[j] == Old) { 899 JTE.MBBs[j] = New; 900 MadeChange = true; 901 } 902 return MadeChange; 903 } 904 905 void MachineJumpTableInfo::print(raw_ostream &OS) const { 906 if (JumpTables.empty()) return; 907 908 OS << "Jump Tables:\n"; 909 910 for (unsigned i = 0, e = JumpTables.size(); i != e; ++i) { 911 OS << printJumpTableEntryReference(i) << ": "; 912 for (unsigned j = 0, f = JumpTables[i].MBBs.size(); j != f; ++j) 913 OS << ' ' << printMBBReference(*JumpTables[i].MBBs[j]); 914 } 915 916 OS << '\n'; 917 } 918 919 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) 920 LLVM_DUMP_METHOD void MachineJumpTableInfo::dump() const { print(dbgs()); } 921 #endif 922 923 Printable llvm::printJumpTableEntryReference(unsigned Idx) { 924 return Printable([Idx](raw_ostream &OS) { OS << "%jump-table." << Idx; }); 925 } 926 927 //===----------------------------------------------------------------------===// 928 // MachineConstantPool implementation 929 //===----------------------------------------------------------------------===// 930 931 void MachineConstantPoolValue::anchor() {} 932 933 Type *MachineConstantPoolEntry::getType() const { 934 if (isMachineConstantPoolEntry()) 935 return Val.MachineCPVal->getType(); 936 return Val.ConstVal->getType(); 937 } 938 939 bool MachineConstantPoolEntry::needsRelocation() const { 940 if (isMachineConstantPoolEntry()) 941 return true; 942 return Val.ConstVal->needsRelocation(); 943 } 944 945 SectionKind 946 MachineConstantPoolEntry::getSectionKind(const DataLayout *DL) const { 947 if (needsRelocation()) 948 return SectionKind::getReadOnlyWithRel(); 949 switch (DL->getTypeAllocSize(getType())) { 950 case 4: 951 return SectionKind::getMergeableConst4(); 952 case 8: 953 return SectionKind::getMergeableConst8(); 954 case 16: 955 return SectionKind::getMergeableConst16(); 956 case 32: 957 return SectionKind::getMergeableConst32(); 958 default: 959 return SectionKind::getReadOnly(); 960 } 961 } 962 963 MachineConstantPool::~MachineConstantPool() { 964 // A constant may be a member of both Constants and MachineCPVsSharingEntries, 965 // so keep track of which we've deleted to avoid double deletions. 966 DenseSet<MachineConstantPoolValue*> Deleted; 967 for (unsigned i = 0, e = Constants.size(); i != e; ++i) 968 if (Constants[i].isMachineConstantPoolEntry()) { 969 Deleted.insert(Constants[i].Val.MachineCPVal); 970 delete Constants[i].Val.MachineCPVal; 971 } 972 for (DenseSet<MachineConstantPoolValue*>::iterator I = 973 MachineCPVsSharingEntries.begin(), E = MachineCPVsSharingEntries.end(); 974 I != E; ++I) { 975 if (Deleted.count(*I) == 0) 976 delete *I; 977 } 978 } 979 980 /// Test whether the given two constants can be allocated the same constant pool 981 /// entry. 982 static bool CanShareConstantPoolEntry(const Constant *A, const Constant *B, 983 const DataLayout &DL) { 984 // Handle the trivial case quickly. 985 if (A == B) return true; 986 987 // If they have the same type but weren't the same constant, quickly 988 // reject them. 989 if (A->getType() == B->getType()) return false; 990 991 // We can't handle structs or arrays. 992 if (isa<StructType>(A->getType()) || isa<ArrayType>(A->getType()) || 993 isa<StructType>(B->getType()) || isa<ArrayType>(B->getType())) 994 return false; 995 996 // For now, only support constants with the same size. 997 uint64_t StoreSize = DL.getTypeStoreSize(A->getType()); 998 if (StoreSize != DL.getTypeStoreSize(B->getType()) || StoreSize > 128) 999 return false; 1000 1001 Type *IntTy = IntegerType::get(A->getContext(), StoreSize*8); 1002 1003 // Try constant folding a bitcast of both instructions to an integer. If we 1004 // get two identical ConstantInt's, then we are good to share them. We use 1005 // the constant folding APIs to do this so that we get the benefit of 1006 // DataLayout. 1007 if (isa<PointerType>(A->getType())) 1008 A = ConstantFoldCastOperand(Instruction::PtrToInt, 1009 const_cast<Constant *>(A), IntTy, DL); 1010 else if (A->getType() != IntTy) 1011 A = ConstantFoldCastOperand(Instruction::BitCast, const_cast<Constant *>(A), 1012 IntTy, DL); 1013 if (isa<PointerType>(B->getType())) 1014 B = ConstantFoldCastOperand(Instruction::PtrToInt, 1015 const_cast<Constant *>(B), IntTy, DL); 1016 else if (B->getType() != IntTy) 1017 B = ConstantFoldCastOperand(Instruction::BitCast, const_cast<Constant *>(B), 1018 IntTy, DL); 1019 1020 return A == B; 1021 } 1022 1023 /// Create a new entry in the constant pool or return an existing one. 1024 /// User must specify the log2 of the minimum required alignment for the object. 1025 unsigned MachineConstantPool::getConstantPoolIndex(const Constant *C, 1026 unsigned Alignment) { 1027 assert(Alignment && "Alignment must be specified!"); 1028 if (Alignment > PoolAlignment) PoolAlignment = Alignment; 1029 1030 // Check to see if we already have this constant. 1031 // 1032 // FIXME, this could be made much more efficient for large constant pools. 1033 for (unsigned i = 0, e = Constants.size(); i != e; ++i) 1034 if (!Constants[i].isMachineConstantPoolEntry() && 1035 CanShareConstantPoolEntry(Constants[i].Val.ConstVal, C, DL)) { 1036 if ((unsigned)Constants[i].getAlignment() < Alignment) 1037 Constants[i].Alignment = Alignment; 1038 return i; 1039 } 1040 1041 Constants.push_back(MachineConstantPoolEntry(C, Alignment)); 1042 return Constants.size()-1; 1043 } 1044 1045 unsigned MachineConstantPool::getConstantPoolIndex(MachineConstantPoolValue *V, 1046 unsigned Alignment) { 1047 assert(Alignment && "Alignment must be specified!"); 1048 if (Alignment > PoolAlignment) PoolAlignment = Alignment; 1049 1050 // Check to see if we already have this constant. 1051 // 1052 // FIXME, this could be made much more efficient for large constant pools. 1053 int Idx = V->getExistingMachineCPValue(this, Alignment); 1054 if (Idx != -1) { 1055 MachineCPVsSharingEntries.insert(V); 1056 return (unsigned)Idx; 1057 } 1058 1059 Constants.push_back(MachineConstantPoolEntry(V, Alignment)); 1060 return Constants.size()-1; 1061 } 1062 1063 void MachineConstantPool::print(raw_ostream &OS) const { 1064 if (Constants.empty()) return; 1065 1066 OS << "Constant Pool:\n"; 1067 for (unsigned i = 0, e = Constants.size(); i != e; ++i) { 1068 OS << " cp#" << i << ": "; 1069 if (Constants[i].isMachineConstantPoolEntry()) 1070 Constants[i].Val.MachineCPVal->print(OS); 1071 else 1072 Constants[i].Val.ConstVal->printAsOperand(OS, /*PrintType=*/false); 1073 OS << ", align=" << Constants[i].getAlignment(); 1074 OS << "\n"; 1075 } 1076 } 1077 1078 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) 1079 LLVM_DUMP_METHOD void MachineConstantPool::dump() const { print(dbgs()); } 1080 #endif 1081