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