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/STLExtras.h" 18 #include "llvm/ADT/SmallString.h" 19 #include "llvm/Analysis/ConstantFolding.h" 20 #include "llvm/Analysis/EHPersonalities.h" 21 #include "llvm/CodeGen/MachineConstantPool.h" 22 #include "llvm/CodeGen/MachineFrameInfo.h" 23 #include "llvm/CodeGen/MachineFunctionInitializer.h" 24 #include "llvm/CodeGen/MachineFunctionPass.h" 25 #include "llvm/CodeGen/MachineInstr.h" 26 #include "llvm/CodeGen/MachineJumpTableInfo.h" 27 #include "llvm/CodeGen/MachineModuleInfo.h" 28 #include "llvm/CodeGen/MachineRegisterInfo.h" 29 #include "llvm/CodeGen/Passes.h" 30 #include "llvm/CodeGen/PseudoSourceValue.h" 31 #include "llvm/CodeGen/WinEHFuncInfo.h" 32 #include "llvm/IR/DataLayout.h" 33 #include "llvm/IR/DebugInfo.h" 34 #include "llvm/IR/Function.h" 35 #include "llvm/IR/Module.h" 36 #include "llvm/IR/ModuleSlotTracker.h" 37 #include "llvm/MC/MCAsmInfo.h" 38 #include "llvm/MC/MCContext.h" 39 #include "llvm/Support/Debug.h" 40 #include "llvm/Support/GraphWriter.h" 41 #include "llvm/Support/raw_ostream.h" 42 #include "llvm/Target/TargetFrameLowering.h" 43 #include "llvm/Target/TargetLowering.h" 44 #include "llvm/Target/TargetMachine.h" 45 #include "llvm/Target/TargetSubtargetInfo.h" 46 using namespace llvm; 47 48 #define DEBUG_TYPE "codegen" 49 50 static cl::opt<unsigned> 51 AlignAllFunctions("align-all-functions", 52 cl::desc("Force the alignment of all functions."), 53 cl::init(0), cl::Hidden); 54 55 void MachineFunctionInitializer::anchor() {} 56 57 void MachineFunctionProperties::print(raw_ostream &ROS, bool OnlySet) const { 58 // Leave this function even in NDEBUG as an out-of-line anchor. 59 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) 60 for (BitVector::size_type i = 0; i < Properties.size(); ++i) { 61 bool HasProperty = Properties[i]; 62 if (OnlySet && !HasProperty) 63 continue; 64 switch(static_cast<Property>(i)) { 65 case Property::IsSSA: 66 ROS << (HasProperty ? "SSA, " : "Post SSA, "); 67 break; 68 case Property::TracksLiveness: 69 ROS << (HasProperty ? "" : "not ") << "tracking liveness, "; 70 break; 71 case Property::AllVRegsAllocated: 72 ROS << (HasProperty ? "AllVRegsAllocated" : "HasVRegs"); 73 break; 74 default: 75 break; 76 } 77 } 78 #endif 79 } 80 81 //===----------------------------------------------------------------------===// 82 // MachineFunction implementation 83 //===----------------------------------------------------------------------===// 84 85 // Out-of-line virtual method. 86 MachineFunctionInfo::~MachineFunctionInfo() {} 87 88 void ilist_traits<MachineBasicBlock>::deleteNode(MachineBasicBlock *MBB) { 89 MBB->getParent()->DeleteMachineBasicBlock(MBB); 90 } 91 92 static inline unsigned getFnStackAlignment(const TargetSubtargetInfo *STI, 93 const Function *Fn) { 94 if (Fn->hasFnAttribute(Attribute::StackAlignment)) 95 return Fn->getFnStackAlignment(); 96 return STI->getFrameLowering()->getStackAlignment(); 97 } 98 99 MachineFunction::MachineFunction(const Function *F, const TargetMachine &TM, 100 unsigned FunctionNum, MachineModuleInfo &mmi) 101 : Fn(F), Target(TM), STI(TM.getSubtargetImpl(*F)), Ctx(mmi.getContext()), 102 MMI(mmi) { 103 // Assume the function starts in SSA form with correct liveness. 104 Properties.set(MachineFunctionProperties::Property::IsSSA); 105 Properties.set(MachineFunctionProperties::Property::TracksLiveness); 106 if (STI->getRegisterInfo()) 107 RegInfo = new (Allocator) MachineRegisterInfo(this); 108 else 109 RegInfo = nullptr; 110 111 MFInfo = nullptr; 112 // We can realign the stack if the target supports it and the user hasn't 113 // explicitly asked us not to. 114 bool CanRealignSP = STI->getFrameLowering()->isStackRealignable() && 115 !F->hasFnAttribute("no-realign-stack"); 116 FrameInfo = new (Allocator) MachineFrameInfo( 117 getFnStackAlignment(STI, Fn), /*StackRealignable=*/CanRealignSP, 118 /*ForceRealign=*/CanRealignSP && 119 F->hasFnAttribute(Attribute::StackAlignment)); 120 121 if (Fn->hasFnAttribute(Attribute::StackAlignment)) 122 FrameInfo->ensureMaxAlignment(Fn->getFnStackAlignment()); 123 124 ConstantPool = new (Allocator) MachineConstantPool(getDataLayout()); 125 Alignment = STI->getTargetLowering()->getMinFunctionAlignment(); 126 127 // FIXME: Shouldn't use pref alignment if explicit alignment is set on Fn. 128 // FIXME: Use Function::optForSize(). 129 if (!Fn->hasFnAttribute(Attribute::OptimizeForSize)) 130 Alignment = std::max(Alignment, 131 STI->getTargetLowering()->getPrefFunctionAlignment()); 132 133 if (AlignAllFunctions) 134 Alignment = AlignAllFunctions; 135 136 FunctionNumber = FunctionNum; 137 JumpTableInfo = nullptr; 138 139 if (isFuncletEHPersonality(classifyEHPersonality( 140 F->hasPersonalityFn() ? F->getPersonalityFn() : nullptr))) { 141 WinEHInfo = new (Allocator) WinEHFuncInfo(); 142 } 143 144 assert(TM.isCompatibleDataLayout(getDataLayout()) && 145 "Can't create a MachineFunction using a Module with a " 146 "Target-incompatible DataLayout attached\n"); 147 148 PSVManager = llvm::make_unique<PseudoSourceValueManager>(); 149 } 150 151 MachineFunction::~MachineFunction() { 152 // Don't call destructors on MachineInstr and MachineOperand. All of their 153 // memory comes from the BumpPtrAllocator which is about to be purged. 154 // 155 // Do call MachineBasicBlock destructors, it contains std::vectors. 156 for (iterator I = begin(), E = end(); I != E; I = BasicBlocks.erase(I)) 157 I->Insts.clearAndLeakNodesUnsafely(); 158 159 InstructionRecycler.clear(Allocator); 160 OperandRecycler.clear(Allocator); 161 BasicBlockRecycler.clear(Allocator); 162 if (RegInfo) { 163 RegInfo->~MachineRegisterInfo(); 164 Allocator.Deallocate(RegInfo); 165 } 166 if (MFInfo) { 167 MFInfo->~MachineFunctionInfo(); 168 Allocator.Deallocate(MFInfo); 169 } 170 171 FrameInfo->~MachineFrameInfo(); 172 Allocator.Deallocate(FrameInfo); 173 174 ConstantPool->~MachineConstantPool(); 175 Allocator.Deallocate(ConstantPool); 176 177 if (JumpTableInfo) { 178 JumpTableInfo->~MachineJumpTableInfo(); 179 Allocator.Deallocate(JumpTableInfo); 180 } 181 182 if (WinEHInfo) { 183 WinEHInfo->~WinEHFuncInfo(); 184 Allocator.Deallocate(WinEHInfo); 185 } 186 } 187 188 const DataLayout &MachineFunction::getDataLayout() const { 189 return Fn->getParent()->getDataLayout(); 190 } 191 192 /// Get the JumpTableInfo for this function. 193 /// If it does not already exist, allocate one. 194 MachineJumpTableInfo *MachineFunction:: 195 getOrCreateJumpTableInfo(unsigned EntryKind) { 196 if (JumpTableInfo) return JumpTableInfo; 197 198 JumpTableInfo = new (Allocator) 199 MachineJumpTableInfo((MachineJumpTableInfo::JTEntryKind)EntryKind); 200 return JumpTableInfo; 201 } 202 203 /// Should we be emitting segmented stack stuff for the function 204 bool MachineFunction::shouldSplitStack() const { 205 return getFunction()->hasFnAttribute("split-stack"); 206 } 207 208 /// This discards all of the MachineBasicBlock numbers and recomputes them. 209 /// This guarantees that the MBB numbers are sequential, dense, and match the 210 /// ordering of the blocks within the function. If a specific MachineBasicBlock 211 /// is specified, only that block and those after it are renumbered. 212 void MachineFunction::RenumberBlocks(MachineBasicBlock *MBB) { 213 if (empty()) { MBBNumbering.clear(); return; } 214 MachineFunction::iterator MBBI, E = end(); 215 if (MBB == nullptr) 216 MBBI = begin(); 217 else 218 MBBI = MBB->getIterator(); 219 220 // Figure out the block number this should have. 221 unsigned BlockNo = 0; 222 if (MBBI != begin()) 223 BlockNo = std::prev(MBBI)->getNumber() + 1; 224 225 for (; MBBI != E; ++MBBI, ++BlockNo) { 226 if (MBBI->getNumber() != (int)BlockNo) { 227 // Remove use of the old number. 228 if (MBBI->getNumber() != -1) { 229 assert(MBBNumbering[MBBI->getNumber()] == &*MBBI && 230 "MBB number mismatch!"); 231 MBBNumbering[MBBI->getNumber()] = nullptr; 232 } 233 234 // If BlockNo is already taken, set that block's number to -1. 235 if (MBBNumbering[BlockNo]) 236 MBBNumbering[BlockNo]->setNumber(-1); 237 238 MBBNumbering[BlockNo] = &*MBBI; 239 MBBI->setNumber(BlockNo); 240 } 241 } 242 243 // Okay, all the blocks are renumbered. If we have compactified the block 244 // numbering, shrink MBBNumbering now. 245 assert(BlockNo <= MBBNumbering.size() && "Mismatch!"); 246 MBBNumbering.resize(BlockNo); 247 } 248 249 /// Allocate a new MachineInstr. Use this instead of `new MachineInstr'. 250 MachineInstr *MachineFunction::CreateMachineInstr(const MCInstrDesc &MCID, 251 const DebugLoc &DL, 252 bool NoImp) { 253 return new (InstructionRecycler.Allocate<MachineInstr>(Allocator)) 254 MachineInstr(*this, MCID, DL, NoImp); 255 } 256 257 /// Create a new MachineInstr which is a copy of the 'Orig' instruction, 258 /// identical in all ways except the instruction has no parent, prev, or next. 259 MachineInstr * 260 MachineFunction::CloneMachineInstr(const MachineInstr *Orig) { 261 return new (InstructionRecycler.Allocate<MachineInstr>(Allocator)) 262 MachineInstr(*this, *Orig); 263 } 264 265 /// Delete the given MachineInstr. 266 /// 267 /// This function also serves as the MachineInstr destructor - the real 268 /// ~MachineInstr() destructor must be empty. 269 void 270 MachineFunction::DeleteMachineInstr(MachineInstr *MI) { 271 // Strip it for parts. The operand array and the MI object itself are 272 // independently recyclable. 273 if (MI->Operands) 274 deallocateOperandArray(MI->CapOperands, MI->Operands); 275 // Don't call ~MachineInstr() which must be trivial anyway because 276 // ~MachineFunction drops whole lists of MachineInstrs wihout calling their 277 // destructors. 278 InstructionRecycler.Deallocate(Allocator, MI); 279 } 280 281 /// Allocate a new MachineBasicBlock. Use this instead of 282 /// `new MachineBasicBlock'. 283 MachineBasicBlock * 284 MachineFunction::CreateMachineBasicBlock(const BasicBlock *bb) { 285 return new (BasicBlockRecycler.Allocate<MachineBasicBlock>(Allocator)) 286 MachineBasicBlock(*this, bb); 287 } 288 289 /// Delete the given MachineBasicBlock. 290 void 291 MachineFunction::DeleteMachineBasicBlock(MachineBasicBlock *MBB) { 292 assert(MBB->getParent() == this && "MBB parent mismatch!"); 293 MBB->~MachineBasicBlock(); 294 BasicBlockRecycler.Deallocate(Allocator, MBB); 295 } 296 297 MachineMemOperand *MachineFunction::getMachineMemOperand( 298 MachinePointerInfo PtrInfo, MachineMemOperand::Flags f, uint64_t s, 299 unsigned base_alignment, const AAMDNodes &AAInfo, const MDNode *Ranges) { 300 return new (Allocator) 301 MachineMemOperand(PtrInfo, f, s, base_alignment, AAInfo, Ranges); 302 } 303 304 MachineMemOperand * 305 MachineFunction::getMachineMemOperand(const MachineMemOperand *MMO, 306 int64_t Offset, uint64_t Size) { 307 if (MMO->getValue()) 308 return new (Allocator) 309 MachineMemOperand(MachinePointerInfo(MMO->getValue(), 310 MMO->getOffset()+Offset), 311 MMO->getFlags(), Size, 312 MMO->getBaseAlignment()); 313 return new (Allocator) 314 MachineMemOperand(MachinePointerInfo(MMO->getPseudoValue(), 315 MMO->getOffset()+Offset), 316 MMO->getFlags(), Size, 317 MMO->getBaseAlignment()); 318 } 319 320 MachineInstr::mmo_iterator 321 MachineFunction::allocateMemRefsArray(unsigned long Num) { 322 return Allocator.Allocate<MachineMemOperand *>(Num); 323 } 324 325 std::pair<MachineInstr::mmo_iterator, MachineInstr::mmo_iterator> 326 MachineFunction::extractLoadMemRefs(MachineInstr::mmo_iterator Begin, 327 MachineInstr::mmo_iterator End) { 328 // Count the number of load mem refs. 329 unsigned Num = 0; 330 for (MachineInstr::mmo_iterator I = Begin; I != End; ++I) 331 if ((*I)->isLoad()) 332 ++Num; 333 334 // Allocate a new array and populate it with the load information. 335 MachineInstr::mmo_iterator Result = allocateMemRefsArray(Num); 336 unsigned Index = 0; 337 for (MachineInstr::mmo_iterator I = Begin; I != End; ++I) { 338 if ((*I)->isLoad()) { 339 if (!(*I)->isStore()) 340 // Reuse the MMO. 341 Result[Index] = *I; 342 else { 343 // Clone the MMO and unset the store flag. 344 MachineMemOperand *JustLoad = 345 getMachineMemOperand((*I)->getPointerInfo(), 346 (*I)->getFlags() & ~MachineMemOperand::MOStore, 347 (*I)->getSize(), (*I)->getBaseAlignment(), 348 (*I)->getAAInfo()); 349 Result[Index] = JustLoad; 350 } 351 ++Index; 352 } 353 } 354 return std::make_pair(Result, Result + Num); 355 } 356 357 std::pair<MachineInstr::mmo_iterator, MachineInstr::mmo_iterator> 358 MachineFunction::extractStoreMemRefs(MachineInstr::mmo_iterator Begin, 359 MachineInstr::mmo_iterator End) { 360 // Count the number of load mem refs. 361 unsigned Num = 0; 362 for (MachineInstr::mmo_iterator I = Begin; I != End; ++I) 363 if ((*I)->isStore()) 364 ++Num; 365 366 // Allocate a new array and populate it with the store information. 367 MachineInstr::mmo_iterator Result = allocateMemRefsArray(Num); 368 unsigned Index = 0; 369 for (MachineInstr::mmo_iterator I = Begin; I != End; ++I) { 370 if ((*I)->isStore()) { 371 if (!(*I)->isLoad()) 372 // Reuse the MMO. 373 Result[Index] = *I; 374 else { 375 // Clone the MMO and unset the load flag. 376 MachineMemOperand *JustStore = 377 getMachineMemOperand((*I)->getPointerInfo(), 378 (*I)->getFlags() & ~MachineMemOperand::MOLoad, 379 (*I)->getSize(), (*I)->getBaseAlignment(), 380 (*I)->getAAInfo()); 381 Result[Index] = JustStore; 382 } 383 ++Index; 384 } 385 } 386 return std::make_pair(Result, Result + Num); 387 } 388 389 const char *MachineFunction::createExternalSymbolName(StringRef Name) { 390 char *Dest = Allocator.Allocate<char>(Name.size() + 1); 391 std::copy(Name.begin(), Name.end(), Dest); 392 Dest[Name.size()] = 0; 393 return Dest; 394 } 395 396 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) 397 LLVM_DUMP_METHOD void MachineFunction::dump() const { 398 print(dbgs()); 399 } 400 #endif 401 402 StringRef MachineFunction::getName() const { 403 assert(getFunction() && "No function!"); 404 return getFunction()->getName(); 405 } 406 407 void MachineFunction::print(raw_ostream &OS, const SlotIndexes *Indexes) const { 408 OS << "# Machine code for function " << getName() << ": "; 409 OS << "Properties: <"; 410 getProperties().print(OS); 411 OS << ">\n"; 412 413 // Print Frame Information 414 FrameInfo->print(*this, OS); 415 416 // Print JumpTable Information 417 if (JumpTableInfo) 418 JumpTableInfo->print(OS); 419 420 // Print Constant Pool 421 ConstantPool->print(OS); 422 423 const TargetRegisterInfo *TRI = getSubtarget().getRegisterInfo(); 424 425 if (RegInfo && !RegInfo->livein_empty()) { 426 OS << "Function Live Ins: "; 427 for (MachineRegisterInfo::livein_iterator 428 I = RegInfo->livein_begin(), E = RegInfo->livein_end(); I != E; ++I) { 429 OS << PrintReg(I->first, TRI); 430 if (I->second) 431 OS << " in " << PrintReg(I->second, TRI); 432 if (std::next(I) != E) 433 OS << ", "; 434 } 435 OS << '\n'; 436 } 437 438 ModuleSlotTracker MST(getFunction()->getParent()); 439 MST.incorporateFunction(*getFunction()); 440 for (const auto &BB : *this) { 441 OS << '\n'; 442 BB.print(OS, MST, Indexes); 443 } 444 445 OS << "\n# End machine code for function " << getName() << ".\n\n"; 446 } 447 448 namespace llvm { 449 template<> 450 struct DOTGraphTraits<const MachineFunction*> : public DefaultDOTGraphTraits { 451 452 DOTGraphTraits (bool isSimple=false) : DefaultDOTGraphTraits(isSimple) {} 453 454 static std::string getGraphName(const MachineFunction *F) { 455 return ("CFG for '" + F->getName() + "' function").str(); 456 } 457 458 std::string getNodeLabel(const MachineBasicBlock *Node, 459 const MachineFunction *Graph) { 460 std::string OutStr; 461 { 462 raw_string_ostream OSS(OutStr); 463 464 if (isSimple()) { 465 OSS << "BB#" << Node->getNumber(); 466 if (const BasicBlock *BB = Node->getBasicBlock()) 467 OSS << ": " << BB->getName(); 468 } else 469 Node->print(OSS); 470 } 471 472 if (OutStr[0] == '\n') OutStr.erase(OutStr.begin()); 473 474 // Process string output to make it nicer... 475 for (unsigned i = 0; i != OutStr.length(); ++i) 476 if (OutStr[i] == '\n') { // Left justify 477 OutStr[i] = '\\'; 478 OutStr.insert(OutStr.begin()+i+1, 'l'); 479 } 480 return OutStr; 481 } 482 }; 483 } 484 485 void MachineFunction::viewCFG() const 486 { 487 #ifndef NDEBUG 488 ViewGraph(this, "mf" + getName()); 489 #else 490 errs() << "MachineFunction::viewCFG is only available in debug builds on " 491 << "systems with Graphviz or gv!\n"; 492 #endif // NDEBUG 493 } 494 495 void MachineFunction::viewCFGOnly() const 496 { 497 #ifndef NDEBUG 498 ViewGraph(this, "mf" + getName(), true); 499 #else 500 errs() << "MachineFunction::viewCFGOnly is only available in debug builds on " 501 << "systems with Graphviz or gv!\n"; 502 #endif // NDEBUG 503 } 504 505 /// Add the specified physical register as a live-in value and 506 /// create a corresponding virtual register for it. 507 unsigned MachineFunction::addLiveIn(unsigned PReg, 508 const TargetRegisterClass *RC) { 509 MachineRegisterInfo &MRI = getRegInfo(); 510 unsigned VReg = MRI.getLiveInVirtReg(PReg); 511 if (VReg) { 512 const TargetRegisterClass *VRegRC = MRI.getRegClass(VReg); 513 (void)VRegRC; 514 // A physical register can be added several times. 515 // Between two calls, the register class of the related virtual register 516 // may have been constrained to match some operation constraints. 517 // In that case, check that the current register class includes the 518 // physical register and is a sub class of the specified RC. 519 assert((VRegRC == RC || (VRegRC->contains(PReg) && 520 RC->hasSubClassEq(VRegRC))) && 521 "Register class mismatch!"); 522 return VReg; 523 } 524 VReg = MRI.createVirtualRegister(RC); 525 MRI.addLiveIn(PReg, VReg); 526 return VReg; 527 } 528 529 /// Return the MCSymbol for the specified non-empty jump table. 530 /// If isLinkerPrivate is specified, an 'l' label is returned, otherwise a 531 /// normal 'L' label is returned. 532 MCSymbol *MachineFunction::getJTISymbol(unsigned JTI, MCContext &Ctx, 533 bool isLinkerPrivate) const { 534 const DataLayout &DL = getDataLayout(); 535 assert(JumpTableInfo && "No jump tables"); 536 assert(JTI < JumpTableInfo->getJumpTables().size() && "Invalid JTI!"); 537 538 const char *Prefix = isLinkerPrivate ? DL.getLinkerPrivateGlobalPrefix() 539 : DL.getPrivateGlobalPrefix(); 540 SmallString<60> Name; 541 raw_svector_ostream(Name) 542 << Prefix << "JTI" << getFunctionNumber() << '_' << JTI; 543 return Ctx.getOrCreateSymbol(Name); 544 } 545 546 /// Return a function-local symbol to represent the PIC base. 547 MCSymbol *MachineFunction::getPICBaseSymbol() const { 548 const DataLayout &DL = getDataLayout(); 549 return Ctx.getOrCreateSymbol(Twine(DL.getPrivateGlobalPrefix()) + 550 Twine(getFunctionNumber()) + "$pb"); 551 } 552 553 //===----------------------------------------------------------------------===// 554 // MachineFrameInfo implementation 555 //===----------------------------------------------------------------------===// 556 557 /// Make sure the function is at least Align bytes aligned. 558 void MachineFrameInfo::ensureMaxAlignment(unsigned Align) { 559 if (!StackRealignable) 560 assert(Align <= StackAlignment && 561 "For targets without stack realignment, Align is out of limit!"); 562 if (MaxAlignment < Align) MaxAlignment = Align; 563 } 564 565 /// Clamp the alignment if requested and emit a warning. 566 static inline unsigned clampStackAlignment(bool ShouldClamp, unsigned Align, 567 unsigned StackAlign) { 568 if (!ShouldClamp || Align <= StackAlign) 569 return Align; 570 DEBUG(dbgs() << "Warning: requested alignment " << Align 571 << " exceeds the stack alignment " << StackAlign 572 << " when stack realignment is off" << '\n'); 573 return StackAlign; 574 } 575 576 /// Create a new statically sized stack object, returning a nonnegative 577 /// identifier to represent it. 578 int MachineFrameInfo::CreateStackObject(uint64_t Size, unsigned Alignment, 579 bool isSS, const AllocaInst *Alloca) { 580 assert(Size != 0 && "Cannot allocate zero size stack objects!"); 581 Alignment = clampStackAlignment(!StackRealignable, Alignment, StackAlignment); 582 Objects.push_back(StackObject(Size, Alignment, 0, false, isSS, Alloca, 583 !isSS)); 584 int Index = (int)Objects.size() - NumFixedObjects - 1; 585 assert(Index >= 0 && "Bad frame index!"); 586 ensureMaxAlignment(Alignment); 587 return Index; 588 } 589 590 /// Create a new statically sized stack object that represents a spill slot, 591 /// returning a nonnegative identifier to represent it. 592 int MachineFrameInfo::CreateSpillStackObject(uint64_t Size, 593 unsigned Alignment) { 594 Alignment = clampStackAlignment(!StackRealignable, Alignment, StackAlignment); 595 CreateStackObject(Size, Alignment, true); 596 int Index = (int)Objects.size() - NumFixedObjects - 1; 597 ensureMaxAlignment(Alignment); 598 return Index; 599 } 600 601 /// Notify the MachineFrameInfo object that a variable sized object has been 602 /// created. This must be created whenever a variable sized object is created, 603 /// whether or not the index returned is actually used. 604 int MachineFrameInfo::CreateVariableSizedObject(unsigned Alignment, 605 const AllocaInst *Alloca) { 606 HasVarSizedObjects = true; 607 Alignment = clampStackAlignment(!StackRealignable, Alignment, StackAlignment); 608 Objects.push_back(StackObject(0, Alignment, 0, false, false, Alloca, true)); 609 ensureMaxAlignment(Alignment); 610 return (int)Objects.size()-NumFixedObjects-1; 611 } 612 613 /// Create a new object at a fixed location on the stack. 614 /// All fixed objects should be created before other objects are created for 615 /// efficiency. By default, fixed objects are immutable. This returns an 616 /// index with a negative value. 617 int MachineFrameInfo::CreateFixedObject(uint64_t Size, int64_t SPOffset, 618 bool Immutable, bool isAliased) { 619 assert(Size != 0 && "Cannot allocate zero size fixed stack objects!"); 620 // The alignment of the frame index can be determined from its offset from 621 // the incoming frame position. If the frame object is at offset 32 and 622 // the stack is guaranteed to be 16-byte aligned, then we know that the 623 // object is 16-byte aligned. Note that unlike the non-fixed case, if the 624 // stack needs realignment, we can't assume that the stack will in fact be 625 // aligned. 626 unsigned Align = MinAlign(SPOffset, ForcedRealign ? 1 : StackAlignment); 627 Align = clampStackAlignment(!StackRealignable, Align, StackAlignment); 628 Objects.insert(Objects.begin(), StackObject(Size, Align, SPOffset, Immutable, 629 /*isSS*/ false, 630 /*Alloca*/ nullptr, isAliased)); 631 return -++NumFixedObjects; 632 } 633 634 /// Create a spill slot at a fixed location on the stack. 635 /// Returns an index with a negative value. 636 int MachineFrameInfo::CreateFixedSpillStackObject(uint64_t Size, 637 int64_t SPOffset) { 638 unsigned Align = MinAlign(SPOffset, ForcedRealign ? 1 : StackAlignment); 639 Align = clampStackAlignment(!StackRealignable, Align, StackAlignment); 640 Objects.insert(Objects.begin(), StackObject(Size, Align, SPOffset, 641 /*Immutable*/ true, 642 /*isSS*/ true, 643 /*Alloca*/ nullptr, 644 /*isAliased*/ false)); 645 return -++NumFixedObjects; 646 } 647 648 BitVector MachineFrameInfo::getPristineRegs(const MachineFunction &MF) const { 649 const TargetRegisterInfo *TRI = MF.getSubtarget().getRegisterInfo(); 650 BitVector BV(TRI->getNumRegs()); 651 652 // Before CSI is calculated, no registers are considered pristine. They can be 653 // freely used and PEI will make sure they are saved. 654 if (!isCalleeSavedInfoValid()) 655 return BV; 656 657 for (const MCPhysReg *CSR = TRI->getCalleeSavedRegs(&MF); CSR && *CSR; ++CSR) 658 BV.set(*CSR); 659 660 // Saved CSRs are not pristine. 661 for (auto &I : getCalleeSavedInfo()) 662 for (MCSubRegIterator S(I.getReg(), TRI, true); S.isValid(); ++S) 663 BV.reset(*S); 664 665 return BV; 666 } 667 668 unsigned MachineFrameInfo::estimateStackSize(const MachineFunction &MF) const { 669 const TargetFrameLowering *TFI = MF.getSubtarget().getFrameLowering(); 670 const TargetRegisterInfo *RegInfo = MF.getSubtarget().getRegisterInfo(); 671 unsigned MaxAlign = getMaxAlignment(); 672 int Offset = 0; 673 674 // This code is very, very similar to PEI::calculateFrameObjectOffsets(). 675 // It really should be refactored to share code. Until then, changes 676 // should keep in mind that there's tight coupling between the two. 677 678 for (int i = getObjectIndexBegin(); i != 0; ++i) { 679 int FixedOff = -getObjectOffset(i); 680 if (FixedOff > Offset) Offset = FixedOff; 681 } 682 for (unsigned i = 0, e = getObjectIndexEnd(); i != e; ++i) { 683 if (isDeadObjectIndex(i)) 684 continue; 685 Offset += getObjectSize(i); 686 unsigned Align = getObjectAlignment(i); 687 // Adjust to alignment boundary 688 Offset = (Offset+Align-1)/Align*Align; 689 690 MaxAlign = std::max(Align, MaxAlign); 691 } 692 693 if (adjustsStack() && TFI->hasReservedCallFrame(MF)) 694 Offset += getMaxCallFrameSize(); 695 696 // Round up the size to a multiple of the alignment. If the function has 697 // any calls or alloca's, align to the target's StackAlignment value to 698 // ensure that the callee's frame or the alloca data is suitably aligned; 699 // otherwise, for leaf functions, align to the TransientStackAlignment 700 // value. 701 unsigned StackAlign; 702 if (adjustsStack() || hasVarSizedObjects() || 703 (RegInfo->needsStackRealignment(MF) && getObjectIndexEnd() != 0)) 704 StackAlign = TFI->getStackAlignment(); 705 else 706 StackAlign = TFI->getTransientStackAlignment(); 707 708 // If the frame pointer is eliminated, all frame offsets will be relative to 709 // SP not FP. Align to MaxAlign so this works. 710 StackAlign = std::max(StackAlign, MaxAlign); 711 unsigned AlignMask = StackAlign - 1; 712 Offset = (Offset + AlignMask) & ~uint64_t(AlignMask); 713 714 return (unsigned)Offset; 715 } 716 717 void MachineFrameInfo::print(const MachineFunction &MF, raw_ostream &OS) const{ 718 if (Objects.empty()) return; 719 720 const TargetFrameLowering *FI = MF.getSubtarget().getFrameLowering(); 721 int ValOffset = (FI ? FI->getOffsetOfLocalArea() : 0); 722 723 OS << "Frame Objects:\n"; 724 725 for (unsigned i = 0, e = Objects.size(); i != e; ++i) { 726 const StackObject &SO = Objects[i]; 727 OS << " fi#" << (int)(i-NumFixedObjects) << ": "; 728 if (SO.Size == ~0ULL) { 729 OS << "dead\n"; 730 continue; 731 } 732 if (SO.Size == 0) 733 OS << "variable sized"; 734 else 735 OS << "size=" << SO.Size; 736 OS << ", align=" << SO.Alignment; 737 738 if (i < NumFixedObjects) 739 OS << ", fixed"; 740 if (i < NumFixedObjects || SO.SPOffset != -1) { 741 int64_t Off = SO.SPOffset - ValOffset; 742 OS << ", at location [SP"; 743 if (Off > 0) 744 OS << "+" << Off; 745 else if (Off < 0) 746 OS << Off; 747 OS << "]"; 748 } 749 OS << "\n"; 750 } 751 } 752 753 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) 754 void MachineFrameInfo::dump(const MachineFunction &MF) const { 755 print(MF, dbgs()); 756 } 757 #endif 758 759 //===----------------------------------------------------------------------===// 760 // MachineJumpTableInfo implementation 761 //===----------------------------------------------------------------------===// 762 763 /// Return the size of each entry in the jump table. 764 unsigned MachineJumpTableInfo::getEntrySize(const DataLayout &TD) const { 765 // The size of a jump table entry is 4 bytes unless the entry is just the 766 // address of a block, in which case it is the pointer size. 767 switch (getEntryKind()) { 768 case MachineJumpTableInfo::EK_BlockAddress: 769 return TD.getPointerSize(); 770 case MachineJumpTableInfo::EK_GPRel64BlockAddress: 771 return 8; 772 case MachineJumpTableInfo::EK_GPRel32BlockAddress: 773 case MachineJumpTableInfo::EK_LabelDifference32: 774 case MachineJumpTableInfo::EK_Custom32: 775 return 4; 776 case MachineJumpTableInfo::EK_Inline: 777 return 0; 778 } 779 llvm_unreachable("Unknown jump table encoding!"); 780 } 781 782 /// Return the alignment of each entry in the jump table. 783 unsigned MachineJumpTableInfo::getEntryAlignment(const DataLayout &TD) const { 784 // The alignment of a jump table entry is the alignment of int32 unless the 785 // entry is just the address of a block, in which case it is the pointer 786 // alignment. 787 switch (getEntryKind()) { 788 case MachineJumpTableInfo::EK_BlockAddress: 789 return TD.getPointerABIAlignment(); 790 case MachineJumpTableInfo::EK_GPRel64BlockAddress: 791 return TD.getABIIntegerTypeAlignment(64); 792 case MachineJumpTableInfo::EK_GPRel32BlockAddress: 793 case MachineJumpTableInfo::EK_LabelDifference32: 794 case MachineJumpTableInfo::EK_Custom32: 795 return TD.getABIIntegerTypeAlignment(32); 796 case MachineJumpTableInfo::EK_Inline: 797 return 1; 798 } 799 llvm_unreachable("Unknown jump table encoding!"); 800 } 801 802 /// Create a new jump table entry in the jump table info. 803 unsigned MachineJumpTableInfo::createJumpTableIndex( 804 const std::vector<MachineBasicBlock*> &DestBBs) { 805 assert(!DestBBs.empty() && "Cannot create an empty jump table!"); 806 JumpTables.push_back(MachineJumpTableEntry(DestBBs)); 807 return JumpTables.size()-1; 808 } 809 810 /// If Old is the target of any jump tables, update the jump tables to branch 811 /// to New instead. 812 bool MachineJumpTableInfo::ReplaceMBBInJumpTables(MachineBasicBlock *Old, 813 MachineBasicBlock *New) { 814 assert(Old != New && "Not making a change?"); 815 bool MadeChange = false; 816 for (size_t i = 0, e = JumpTables.size(); i != e; ++i) 817 ReplaceMBBInJumpTable(i, Old, New); 818 return MadeChange; 819 } 820 821 /// If Old is a target of the jump tables, update the jump table to branch to 822 /// New instead. 823 bool MachineJumpTableInfo::ReplaceMBBInJumpTable(unsigned Idx, 824 MachineBasicBlock *Old, 825 MachineBasicBlock *New) { 826 assert(Old != New && "Not making a change?"); 827 bool MadeChange = false; 828 MachineJumpTableEntry &JTE = JumpTables[Idx]; 829 for (size_t j = 0, e = JTE.MBBs.size(); j != e; ++j) 830 if (JTE.MBBs[j] == Old) { 831 JTE.MBBs[j] = New; 832 MadeChange = true; 833 } 834 return MadeChange; 835 } 836 837 void MachineJumpTableInfo::print(raw_ostream &OS) const { 838 if (JumpTables.empty()) return; 839 840 OS << "Jump Tables:\n"; 841 842 for (unsigned i = 0, e = JumpTables.size(); i != e; ++i) { 843 OS << " jt#" << i << ": "; 844 for (unsigned j = 0, f = JumpTables[i].MBBs.size(); j != f; ++j) 845 OS << " BB#" << JumpTables[i].MBBs[j]->getNumber(); 846 } 847 848 OS << '\n'; 849 } 850 851 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) 852 LLVM_DUMP_METHOD void MachineJumpTableInfo::dump() const { print(dbgs()); } 853 #endif 854 855 856 //===----------------------------------------------------------------------===// 857 // MachineConstantPool implementation 858 //===----------------------------------------------------------------------===// 859 860 void MachineConstantPoolValue::anchor() { } 861 862 Type *MachineConstantPoolEntry::getType() const { 863 if (isMachineConstantPoolEntry()) 864 return Val.MachineCPVal->getType(); 865 return Val.ConstVal->getType(); 866 } 867 868 bool MachineConstantPoolEntry::needsRelocation() const { 869 if (isMachineConstantPoolEntry()) 870 return true; 871 return Val.ConstVal->needsRelocation(); 872 } 873 874 SectionKind 875 MachineConstantPoolEntry::getSectionKind(const DataLayout *DL) const { 876 if (needsRelocation()) 877 return SectionKind::getReadOnlyWithRel(); 878 switch (DL->getTypeAllocSize(getType())) { 879 case 4: 880 return SectionKind::getMergeableConst4(); 881 case 8: 882 return SectionKind::getMergeableConst8(); 883 case 16: 884 return SectionKind::getMergeableConst16(); 885 case 32: 886 return SectionKind::getMergeableConst32(); 887 default: 888 return SectionKind::getReadOnly(); 889 } 890 } 891 892 MachineConstantPool::~MachineConstantPool() { 893 for (unsigned i = 0, e = Constants.size(); i != e; ++i) 894 if (Constants[i].isMachineConstantPoolEntry()) 895 delete Constants[i].Val.MachineCPVal; 896 for (DenseSet<MachineConstantPoolValue*>::iterator I = 897 MachineCPVsSharingEntries.begin(), E = MachineCPVsSharingEntries.end(); 898 I != E; ++I) 899 delete *I; 900 } 901 902 /// Test whether the given two constants can be allocated the same constant pool 903 /// entry. 904 static bool CanShareConstantPoolEntry(const Constant *A, const Constant *B, 905 const DataLayout &DL) { 906 // Handle the trivial case quickly. 907 if (A == B) return true; 908 909 // If they have the same type but weren't the same constant, quickly 910 // reject them. 911 if (A->getType() == B->getType()) return false; 912 913 // We can't handle structs or arrays. 914 if (isa<StructType>(A->getType()) || isa<ArrayType>(A->getType()) || 915 isa<StructType>(B->getType()) || isa<ArrayType>(B->getType())) 916 return false; 917 918 // For now, only support constants with the same size. 919 uint64_t StoreSize = DL.getTypeStoreSize(A->getType()); 920 if (StoreSize != DL.getTypeStoreSize(B->getType()) || StoreSize > 128) 921 return false; 922 923 Type *IntTy = IntegerType::get(A->getContext(), StoreSize*8); 924 925 // Try constant folding a bitcast of both instructions to an integer. If we 926 // get two identical ConstantInt's, then we are good to share them. We use 927 // the constant folding APIs to do this so that we get the benefit of 928 // DataLayout. 929 if (isa<PointerType>(A->getType())) 930 A = ConstantFoldCastOperand(Instruction::PtrToInt, 931 const_cast<Constant *>(A), IntTy, DL); 932 else if (A->getType() != IntTy) 933 A = ConstantFoldCastOperand(Instruction::BitCast, const_cast<Constant *>(A), 934 IntTy, DL); 935 if (isa<PointerType>(B->getType())) 936 B = ConstantFoldCastOperand(Instruction::PtrToInt, 937 const_cast<Constant *>(B), IntTy, DL); 938 else if (B->getType() != IntTy) 939 B = ConstantFoldCastOperand(Instruction::BitCast, const_cast<Constant *>(B), 940 IntTy, DL); 941 942 return A == B; 943 } 944 945 /// Create a new entry in the constant pool or return an existing one. 946 /// User must specify the log2 of the minimum required alignment for the object. 947 unsigned MachineConstantPool::getConstantPoolIndex(const Constant *C, 948 unsigned Alignment) { 949 assert(Alignment && "Alignment must be specified!"); 950 if (Alignment > PoolAlignment) PoolAlignment = Alignment; 951 952 // Check to see if we already have this constant. 953 // 954 // FIXME, this could be made much more efficient for large constant pools. 955 for (unsigned i = 0, e = Constants.size(); i != e; ++i) 956 if (!Constants[i].isMachineConstantPoolEntry() && 957 CanShareConstantPoolEntry(Constants[i].Val.ConstVal, C, DL)) { 958 if ((unsigned)Constants[i].getAlignment() < Alignment) 959 Constants[i].Alignment = Alignment; 960 return i; 961 } 962 963 Constants.push_back(MachineConstantPoolEntry(C, Alignment)); 964 return Constants.size()-1; 965 } 966 967 unsigned MachineConstantPool::getConstantPoolIndex(MachineConstantPoolValue *V, 968 unsigned Alignment) { 969 assert(Alignment && "Alignment must be specified!"); 970 if (Alignment > PoolAlignment) PoolAlignment = Alignment; 971 972 // Check to see if we already have this constant. 973 // 974 // FIXME, this could be made much more efficient for large constant pools. 975 int Idx = V->getExistingMachineCPValue(this, Alignment); 976 if (Idx != -1) { 977 MachineCPVsSharingEntries.insert(V); 978 return (unsigned)Idx; 979 } 980 981 Constants.push_back(MachineConstantPoolEntry(V, Alignment)); 982 return Constants.size()-1; 983 } 984 985 void MachineConstantPool::print(raw_ostream &OS) const { 986 if (Constants.empty()) return; 987 988 OS << "Constant Pool:\n"; 989 for (unsigned i = 0, e = Constants.size(); i != e; ++i) { 990 OS << " cp#" << i << ": "; 991 if (Constants[i].isMachineConstantPoolEntry()) 992 Constants[i].Val.MachineCPVal->print(OS); 993 else 994 Constants[i].Val.ConstVal->printAsOperand(OS, /*PrintType=*/false); 995 OS << ", align=" << Constants[i].getAlignment(); 996 OS << "\n"; 997 } 998 } 999 1000 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) 1001 LLVM_DUMP_METHOD void MachineConstantPool::dump() const { print(dbgs()); } 1002 #endif 1003