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