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