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 if (&FPType == &APFloat::IEEEsingle()) { 277 Attribute Attr = F.getFnAttribute("denormal-fp-math-f32"); 278 StringRef Val = Attr.getValueAsString(); 279 if (!Val.empty()) 280 return parseDenormalFPAttribute(Val); 281 282 // If the f32 variant of the attribute isn't specified, try to use the 283 // generic one. 284 } 285 286 // TODO: Should probably avoid the connection to the IR and store directly 287 // in the MachineFunction. 288 Attribute Attr = F.getFnAttribute("denormal-fp-math"); 289 return parseDenormalFPAttribute(Attr.getValueAsString()); 290 } 291 292 /// Should we be emitting segmented stack stuff for the function 293 bool MachineFunction::shouldSplitStack() const { 294 return getFunction().hasFnAttribute("split-stack"); 295 } 296 297 LLVM_NODISCARD unsigned 298 MachineFunction::addFrameInst(const MCCFIInstruction &Inst) { 299 FrameInstructions.push_back(Inst); 300 return FrameInstructions.size() - 1; 301 } 302 303 /// This discards all of the MachineBasicBlock numbers and recomputes them. 304 /// This guarantees that the MBB numbers are sequential, dense, and match the 305 /// ordering of the blocks within the function. If a specific MachineBasicBlock 306 /// is specified, only that block and those after it are renumbered. 307 void MachineFunction::RenumberBlocks(MachineBasicBlock *MBB) { 308 if (empty()) { MBBNumbering.clear(); return; } 309 MachineFunction::iterator MBBI, E = end(); 310 if (MBB == nullptr) 311 MBBI = begin(); 312 else 313 MBBI = MBB->getIterator(); 314 315 // Figure out the block number this should have. 316 unsigned BlockNo = 0; 317 if (MBBI != begin()) 318 BlockNo = std::prev(MBBI)->getNumber() + 1; 319 320 for (; MBBI != E; ++MBBI, ++BlockNo) { 321 if (MBBI->getNumber() != (int)BlockNo) { 322 // Remove use of the old number. 323 if (MBBI->getNumber() != -1) { 324 assert(MBBNumbering[MBBI->getNumber()] == &*MBBI && 325 "MBB number mismatch!"); 326 MBBNumbering[MBBI->getNumber()] = nullptr; 327 } 328 329 // If BlockNo is already taken, set that block's number to -1. 330 if (MBBNumbering[BlockNo]) 331 MBBNumbering[BlockNo]->setNumber(-1); 332 333 MBBNumbering[BlockNo] = &*MBBI; 334 MBBI->setNumber(BlockNo); 335 } 336 } 337 338 // Okay, all the blocks are renumbered. If we have compactified the block 339 // numbering, shrink MBBNumbering now. 340 assert(BlockNo <= MBBNumbering.size() && "Mismatch!"); 341 MBBNumbering.resize(BlockNo); 342 } 343 344 /// This is used with -fbasic-block-sections or -fbasicblock-labels option. 345 /// A unary encoding of basic block labels is done to keep ".strtab" sizes 346 /// small. 347 void MachineFunction::createBBLabels() { 348 const TargetInstrInfo *TII = getSubtarget().getInstrInfo(); 349 this->BBSectionsSymbolPrefix.resize(getNumBlockIDs(), 'a'); 350 for (auto MBBI = begin(), E = end(); MBBI != E; ++MBBI) { 351 assert( 352 (MBBI->getNumber() >= 0 && MBBI->getNumber() < (int)getNumBlockIDs()) && 353 "BasicBlock number was out of range!"); 354 // 'a' - Normal block. 355 // 'r' - Return block. 356 // 'l' - Landing Pad. 357 // 'L' - Return and landing pad. 358 bool isEHPad = MBBI->isEHPad(); 359 bool isRetBlock = MBBI->isReturnBlock() && !TII->isTailCall(MBBI->back()); 360 char type = 'a'; 361 if (isEHPad && isRetBlock) 362 type = 'L'; 363 else if (isEHPad) 364 type = 'l'; 365 else if (isRetBlock) 366 type = 'r'; 367 BBSectionsSymbolPrefix[MBBI->getNumber()] = type; 368 } 369 } 370 371 /// This method iterates over the basic blocks and assigns their IsBeginSection 372 /// and IsEndSection fields. This must be called after MBB layout is finalized 373 /// and the SectionID's are assigned to MBBs. 374 void MachineFunction::assignBeginEndSections() { 375 front().setIsBeginSection(); 376 auto CurrentSectionID = front().getSectionID(); 377 for (auto MBBI = std::next(begin()), E = end(); MBBI != E; ++MBBI) { 378 if (MBBI->getSectionID() == CurrentSectionID) 379 continue; 380 MBBI->setIsBeginSection(); 381 std::prev(MBBI)->setIsEndSection(); 382 CurrentSectionID = MBBI->getSectionID(); 383 } 384 back().setIsEndSection(); 385 } 386 387 /// Allocate a new MachineInstr. Use this instead of `new MachineInstr'. 388 MachineInstr *MachineFunction::CreateMachineInstr(const MCInstrDesc &MCID, 389 const DebugLoc &DL, 390 bool NoImp) { 391 return new (InstructionRecycler.Allocate<MachineInstr>(Allocator)) 392 MachineInstr(*this, MCID, DL, NoImp); 393 } 394 395 /// Create a new MachineInstr which is a copy of the 'Orig' instruction, 396 /// identical in all ways except the instruction has no parent, prev, or next. 397 MachineInstr * 398 MachineFunction::CloneMachineInstr(const MachineInstr *Orig) { 399 return new (InstructionRecycler.Allocate<MachineInstr>(Allocator)) 400 MachineInstr(*this, *Orig); 401 } 402 403 MachineInstr &MachineFunction::CloneMachineInstrBundle(MachineBasicBlock &MBB, 404 MachineBasicBlock::iterator InsertBefore, const MachineInstr &Orig) { 405 MachineInstr *FirstClone = nullptr; 406 MachineBasicBlock::const_instr_iterator I = Orig.getIterator(); 407 while (true) { 408 MachineInstr *Cloned = CloneMachineInstr(&*I); 409 MBB.insert(InsertBefore, Cloned); 410 if (FirstClone == nullptr) { 411 FirstClone = Cloned; 412 } else { 413 Cloned->bundleWithPred(); 414 } 415 416 if (!I->isBundledWithSucc()) 417 break; 418 ++I; 419 } 420 // Copy over call site info to the cloned instruction if needed. If Orig is in 421 // a bundle, copyCallSiteInfo takes care of finding the call instruction in 422 // the bundle. 423 if (Orig.shouldUpdateCallSiteInfo()) 424 copyCallSiteInfo(&Orig, FirstClone); 425 return *FirstClone; 426 } 427 428 /// Delete the given MachineInstr. 429 /// 430 /// This function also serves as the MachineInstr destructor - the real 431 /// ~MachineInstr() destructor must be empty. 432 void 433 MachineFunction::DeleteMachineInstr(MachineInstr *MI) { 434 // Verify that a call site info is at valid state. This assertion should 435 // be triggered during the implementation of support for the 436 // call site info of a new architecture. If the assertion is triggered, 437 // back trace will tell where to insert a call to updateCallSiteInfo(). 438 assert((!MI->isCandidateForCallSiteEntry() || 439 CallSitesInfo.find(MI) == CallSitesInfo.end()) && 440 "Call site info was not updated!"); 441 // Strip it for parts. The operand array and the MI object itself are 442 // independently recyclable. 443 if (MI->Operands) 444 deallocateOperandArray(MI->CapOperands, MI->Operands); 445 // Don't call ~MachineInstr() which must be trivial anyway because 446 // ~MachineFunction drops whole lists of MachineInstrs wihout calling their 447 // destructors. 448 InstructionRecycler.Deallocate(Allocator, MI); 449 } 450 451 /// Allocate a new MachineBasicBlock. Use this instead of 452 /// `new MachineBasicBlock'. 453 MachineBasicBlock * 454 MachineFunction::CreateMachineBasicBlock(const BasicBlock *bb) { 455 return new (BasicBlockRecycler.Allocate<MachineBasicBlock>(Allocator)) 456 MachineBasicBlock(*this, bb); 457 } 458 459 /// Delete the given MachineBasicBlock. 460 void 461 MachineFunction::DeleteMachineBasicBlock(MachineBasicBlock *MBB) { 462 assert(MBB->getParent() == this && "MBB parent mismatch!"); 463 MBB->~MachineBasicBlock(); 464 BasicBlockRecycler.Deallocate(Allocator, MBB); 465 } 466 467 MachineMemOperand *MachineFunction::getMachineMemOperand( 468 MachinePointerInfo PtrInfo, MachineMemOperand::Flags f, uint64_t s, 469 Align base_alignment, const AAMDNodes &AAInfo, const MDNode *Ranges, 470 SyncScope::ID SSID, AtomicOrdering Ordering, 471 AtomicOrdering FailureOrdering) { 472 return new (Allocator) 473 MachineMemOperand(PtrInfo, f, s, base_alignment, AAInfo, Ranges, 474 SSID, Ordering, FailureOrdering); 475 } 476 477 MachineMemOperand *MachineFunction::getMachineMemOperand( 478 const MachineMemOperand *MMO, MachinePointerInfo &PtrInfo, uint64_t Size) { 479 return new (Allocator) MachineMemOperand( 480 PtrInfo, MMO->getFlags(), Size, Alignment, AAMDNodes(), nullptr, 481 MMO->getSyncScopeID(), MMO->getOrdering(), MMO->getFailureOrdering()); 482 } 483 484 MachineMemOperand * 485 MachineFunction::getMachineMemOperand(const MachineMemOperand *MMO, 486 int64_t Offset, uint64_t Size) { 487 const MachinePointerInfo &PtrInfo = MMO->getPointerInfo(); 488 489 // If there is no pointer value, the offset isn't tracked so we need to adjust 490 // the base alignment. 491 Align Alignment = PtrInfo.V.isNull() 492 ? commonAlignment(MMO->getBaseAlign(), Offset) 493 : MMO->getBaseAlign(); 494 495 return new (Allocator) 496 MachineMemOperand(PtrInfo.getWithOffset(Offset), MMO->getFlags(), Size, 497 Alignment, AAMDNodes(), nullptr, MMO->getSyncScopeID(), 498 MMO->getOrdering(), MMO->getFailureOrdering()); 499 } 500 501 MachineMemOperand * 502 MachineFunction::getMachineMemOperand(const MachineMemOperand *MMO, 503 const AAMDNodes &AAInfo) { 504 MachinePointerInfo MPI = MMO->getValue() ? 505 MachinePointerInfo(MMO->getValue(), MMO->getOffset()) : 506 MachinePointerInfo(MMO->getPseudoValue(), MMO->getOffset()); 507 508 return new (Allocator) MachineMemOperand( 509 MPI, MMO->getFlags(), MMO->getSize(), MMO->getBaseAlign(), AAInfo, 510 MMO->getRanges(), MMO->getSyncScopeID(), MMO->getOrdering(), 511 MMO->getFailureOrdering()); 512 } 513 514 MachineMemOperand * 515 MachineFunction::getMachineMemOperand(const MachineMemOperand *MMO, 516 MachineMemOperand::Flags Flags) { 517 return new (Allocator) MachineMemOperand( 518 MMO->getPointerInfo(), Flags, MMO->getSize(), MMO->getBaseAlign(), 519 MMO->getAAInfo(), MMO->getRanges(), MMO->getSyncScopeID(), 520 MMO->getOrdering(), MMO->getFailureOrdering()); 521 } 522 523 MachineInstr::ExtraInfo *MachineFunction::createMIExtraInfo( 524 ArrayRef<MachineMemOperand *> MMOs, MCSymbol *PreInstrSymbol, 525 MCSymbol *PostInstrSymbol, MDNode *HeapAllocMarker) { 526 return MachineInstr::ExtraInfo::create(Allocator, MMOs, PreInstrSymbol, 527 PostInstrSymbol, HeapAllocMarker); 528 } 529 530 const char *MachineFunction::createExternalSymbolName(StringRef Name) { 531 char *Dest = Allocator.Allocate<char>(Name.size() + 1); 532 llvm::copy(Name, Dest); 533 Dest[Name.size()] = 0; 534 return Dest; 535 } 536 537 uint32_t *MachineFunction::allocateRegMask() { 538 unsigned NumRegs = getSubtarget().getRegisterInfo()->getNumRegs(); 539 unsigned Size = MachineOperand::getRegMaskSize(NumRegs); 540 uint32_t *Mask = Allocator.Allocate<uint32_t>(Size); 541 memset(Mask, 0, Size * sizeof(Mask[0])); 542 return Mask; 543 } 544 545 ArrayRef<int> MachineFunction::allocateShuffleMask(ArrayRef<int> Mask) { 546 int* AllocMask = Allocator.Allocate<int>(Mask.size()); 547 copy(Mask, AllocMask); 548 return {AllocMask, Mask.size()}; 549 } 550 551 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) 552 LLVM_DUMP_METHOD void MachineFunction::dump() const { 553 print(dbgs()); 554 } 555 #endif 556 557 StringRef MachineFunction::getName() const { 558 return getFunction().getName(); 559 } 560 561 void MachineFunction::print(raw_ostream &OS, const SlotIndexes *Indexes) const { 562 OS << "# Machine code for function " << getName() << ": "; 563 getProperties().print(OS); 564 OS << '\n'; 565 566 // Print Frame Information 567 FrameInfo->print(*this, OS); 568 569 // Print JumpTable Information 570 if (JumpTableInfo) 571 JumpTableInfo->print(OS); 572 573 // Print Constant Pool 574 ConstantPool->print(OS); 575 576 const TargetRegisterInfo *TRI = getSubtarget().getRegisterInfo(); 577 578 if (RegInfo && !RegInfo->livein_empty()) { 579 OS << "Function Live Ins: "; 580 for (MachineRegisterInfo::livein_iterator 581 I = RegInfo->livein_begin(), E = RegInfo->livein_end(); I != E; ++I) { 582 OS << printReg(I->first, TRI); 583 if (I->second) 584 OS << " in " << printReg(I->second, TRI); 585 if (std::next(I) != E) 586 OS << ", "; 587 } 588 OS << '\n'; 589 } 590 591 ModuleSlotTracker MST(getFunction().getParent()); 592 MST.incorporateFunction(getFunction()); 593 for (const auto &BB : *this) { 594 OS << '\n'; 595 // If we print the whole function, print it at its most verbose level. 596 BB.print(OS, MST, Indexes, /*IsStandalone=*/true); 597 } 598 599 OS << "\n# End machine code for function " << getName() << ".\n\n"; 600 } 601 602 /// True if this function needs frame moves for debug or exceptions. 603 bool MachineFunction::needsFrameMoves() const { 604 return getMMI().hasDebugInfo() || 605 getTarget().Options.ForceDwarfFrameSection || 606 F.needsUnwindTableEntry(); 607 } 608 609 namespace llvm { 610 611 template<> 612 struct DOTGraphTraits<const MachineFunction*> : public DefaultDOTGraphTraits { 613 DOTGraphTraits(bool isSimple = false) : DefaultDOTGraphTraits(isSimple) {} 614 615 static std::string getGraphName(const MachineFunction *F) { 616 return ("CFG for '" + F->getName() + "' function").str(); 617 } 618 619 std::string getNodeLabel(const MachineBasicBlock *Node, 620 const MachineFunction *Graph) { 621 std::string OutStr; 622 { 623 raw_string_ostream OSS(OutStr); 624 625 if (isSimple()) { 626 OSS << printMBBReference(*Node); 627 if (const BasicBlock *BB = Node->getBasicBlock()) 628 OSS << ": " << BB->getName(); 629 } else 630 Node->print(OSS); 631 } 632 633 if (OutStr[0] == '\n') OutStr.erase(OutStr.begin()); 634 635 // Process string output to make it nicer... 636 for (unsigned i = 0; i != OutStr.length(); ++i) 637 if (OutStr[i] == '\n') { // Left justify 638 OutStr[i] = '\\'; 639 OutStr.insert(OutStr.begin()+i+1, 'l'); 640 } 641 return OutStr; 642 } 643 }; 644 645 } // end namespace llvm 646 647 void MachineFunction::viewCFG() const 648 { 649 #ifndef NDEBUG 650 ViewGraph(this, "mf" + getName()); 651 #else 652 errs() << "MachineFunction::viewCFG is only available in debug builds on " 653 << "systems with Graphviz or gv!\n"; 654 #endif // NDEBUG 655 } 656 657 void MachineFunction::viewCFGOnly() const 658 { 659 #ifndef NDEBUG 660 ViewGraph(this, "mf" + getName(), true); 661 #else 662 errs() << "MachineFunction::viewCFGOnly is only available in debug builds on " 663 << "systems with Graphviz or gv!\n"; 664 #endif // NDEBUG 665 } 666 667 /// Add the specified physical register as a live-in value and 668 /// create a corresponding virtual register for it. 669 Register MachineFunction::addLiveIn(MCRegister PReg, 670 const TargetRegisterClass *RC) { 671 MachineRegisterInfo &MRI = getRegInfo(); 672 Register VReg = MRI.getLiveInVirtReg(PReg); 673 if (VReg) { 674 const TargetRegisterClass *VRegRC = MRI.getRegClass(VReg); 675 (void)VRegRC; 676 // A physical register can be added several times. 677 // Between two calls, the register class of the related virtual register 678 // may have been constrained to match some operation constraints. 679 // In that case, check that the current register class includes the 680 // physical register and is a sub class of the specified RC. 681 assert((VRegRC == RC || (VRegRC->contains(PReg) && 682 RC->hasSubClassEq(VRegRC))) && 683 "Register class mismatch!"); 684 return VReg; 685 } 686 VReg = MRI.createVirtualRegister(RC); 687 MRI.addLiveIn(PReg, VReg); 688 return VReg; 689 } 690 691 /// Return the MCSymbol for the specified non-empty jump table. 692 /// If isLinkerPrivate is specified, an 'l' label is returned, otherwise a 693 /// normal 'L' label is returned. 694 MCSymbol *MachineFunction::getJTISymbol(unsigned JTI, MCContext &Ctx, 695 bool isLinkerPrivate) const { 696 const DataLayout &DL = getDataLayout(); 697 assert(JumpTableInfo && "No jump tables"); 698 assert(JTI < JumpTableInfo->getJumpTables().size() && "Invalid JTI!"); 699 700 StringRef Prefix = isLinkerPrivate ? DL.getLinkerPrivateGlobalPrefix() 701 : DL.getPrivateGlobalPrefix(); 702 SmallString<60> Name; 703 raw_svector_ostream(Name) 704 << Prefix << "JTI" << getFunctionNumber() << '_' << JTI; 705 return Ctx.getOrCreateSymbol(Name); 706 } 707 708 /// Return a function-local symbol to represent the PIC base. 709 MCSymbol *MachineFunction::getPICBaseSymbol() const { 710 const DataLayout &DL = getDataLayout(); 711 return Ctx.getOrCreateSymbol(Twine(DL.getPrivateGlobalPrefix()) + 712 Twine(getFunctionNumber()) + "$pb"); 713 } 714 715 /// \name Exception Handling 716 /// \{ 717 718 LandingPadInfo & 719 MachineFunction::getOrCreateLandingPadInfo(MachineBasicBlock *LandingPad) { 720 unsigned N = LandingPads.size(); 721 for (unsigned i = 0; i < N; ++i) { 722 LandingPadInfo &LP = LandingPads[i]; 723 if (LP.LandingPadBlock == LandingPad) 724 return LP; 725 } 726 727 LandingPads.push_back(LandingPadInfo(LandingPad)); 728 return LandingPads[N]; 729 } 730 731 void MachineFunction::addInvoke(MachineBasicBlock *LandingPad, 732 MCSymbol *BeginLabel, MCSymbol *EndLabel) { 733 LandingPadInfo &LP = getOrCreateLandingPadInfo(LandingPad); 734 LP.BeginLabels.push_back(BeginLabel); 735 LP.EndLabels.push_back(EndLabel); 736 } 737 738 MCSymbol *MachineFunction::addLandingPad(MachineBasicBlock *LandingPad) { 739 MCSymbol *LandingPadLabel = Ctx.createTempSymbol(); 740 LandingPadInfo &LP = getOrCreateLandingPadInfo(LandingPad); 741 LP.LandingPadLabel = LandingPadLabel; 742 743 const Instruction *FirstI = LandingPad->getBasicBlock()->getFirstNonPHI(); 744 if (const auto *LPI = dyn_cast<LandingPadInst>(FirstI)) { 745 if (const auto *PF = 746 dyn_cast<Function>(F.getPersonalityFn()->stripPointerCasts())) 747 getMMI().addPersonality(PF); 748 749 if (LPI->isCleanup()) 750 addCleanup(LandingPad); 751 752 // FIXME: New EH - Add the clauses in reverse order. This isn't 100% 753 // correct, but we need to do it this way because of how the DWARF EH 754 // emitter processes the clauses. 755 for (unsigned I = LPI->getNumClauses(); I != 0; --I) { 756 Value *Val = LPI->getClause(I - 1); 757 if (LPI->isCatch(I - 1)) { 758 addCatchTypeInfo(LandingPad, 759 dyn_cast<GlobalValue>(Val->stripPointerCasts())); 760 } else { 761 // Add filters in a list. 762 auto *CVal = cast<Constant>(Val); 763 SmallVector<const GlobalValue *, 4> FilterList; 764 for (User::op_iterator II = CVal->op_begin(), IE = CVal->op_end(); 765 II != IE; ++II) 766 FilterList.push_back(cast<GlobalValue>((*II)->stripPointerCasts())); 767 768 addFilterTypeInfo(LandingPad, FilterList); 769 } 770 } 771 772 } else if (const auto *CPI = dyn_cast<CatchPadInst>(FirstI)) { 773 for (unsigned I = CPI->getNumArgOperands(); I != 0; --I) { 774 Value *TypeInfo = CPI->getArgOperand(I - 1)->stripPointerCasts(); 775 addCatchTypeInfo(LandingPad, dyn_cast<GlobalValue>(TypeInfo)); 776 } 777 778 } else { 779 assert(isa<CleanupPadInst>(FirstI) && "Invalid landingpad!"); 780 } 781 782 return LandingPadLabel; 783 } 784 785 void MachineFunction::addCatchTypeInfo(MachineBasicBlock *LandingPad, 786 ArrayRef<const GlobalValue *> TyInfo) { 787 LandingPadInfo &LP = getOrCreateLandingPadInfo(LandingPad); 788 for (unsigned N = TyInfo.size(); N; --N) 789 LP.TypeIds.push_back(getTypeIDFor(TyInfo[N - 1])); 790 } 791 792 void MachineFunction::addFilterTypeInfo(MachineBasicBlock *LandingPad, 793 ArrayRef<const GlobalValue *> TyInfo) { 794 LandingPadInfo &LP = getOrCreateLandingPadInfo(LandingPad); 795 std::vector<unsigned> IdsInFilter(TyInfo.size()); 796 for (unsigned I = 0, E = TyInfo.size(); I != E; ++I) 797 IdsInFilter[I] = getTypeIDFor(TyInfo[I]); 798 LP.TypeIds.push_back(getFilterIDFor(IdsInFilter)); 799 } 800 801 void MachineFunction::tidyLandingPads(DenseMap<MCSymbol *, uintptr_t> *LPMap, 802 bool TidyIfNoBeginLabels) { 803 for (unsigned i = 0; i != LandingPads.size(); ) { 804 LandingPadInfo &LandingPad = LandingPads[i]; 805 if (LandingPad.LandingPadLabel && 806 !LandingPad.LandingPadLabel->isDefined() && 807 (!LPMap || (*LPMap)[LandingPad.LandingPadLabel] == 0)) 808 LandingPad.LandingPadLabel = nullptr; 809 810 // Special case: we *should* emit LPs with null LP MBB. This indicates 811 // "nounwind" case. 812 if (!LandingPad.LandingPadLabel && LandingPad.LandingPadBlock) { 813 LandingPads.erase(LandingPads.begin() + i); 814 continue; 815 } 816 817 if (TidyIfNoBeginLabels) { 818 for (unsigned j = 0, e = LandingPads[i].BeginLabels.size(); j != e; ++j) { 819 MCSymbol *BeginLabel = LandingPad.BeginLabels[j]; 820 MCSymbol *EndLabel = LandingPad.EndLabels[j]; 821 if ((BeginLabel->isDefined() || (LPMap && (*LPMap)[BeginLabel] != 0)) && 822 (EndLabel->isDefined() || (LPMap && (*LPMap)[EndLabel] != 0))) 823 continue; 824 825 LandingPad.BeginLabels.erase(LandingPad.BeginLabels.begin() + j); 826 LandingPad.EndLabels.erase(LandingPad.EndLabels.begin() + j); 827 --j; 828 --e; 829 } 830 831 // Remove landing pads with no try-ranges. 832 if (LandingPads[i].BeginLabels.empty()) { 833 LandingPads.erase(LandingPads.begin() + i); 834 continue; 835 } 836 } 837 838 // If there is no landing pad, ensure that the list of typeids is empty. 839 // If the only typeid is a cleanup, this is the same as having no typeids. 840 if (!LandingPad.LandingPadBlock || 841 (LandingPad.TypeIds.size() == 1 && !LandingPad.TypeIds[0])) 842 LandingPad.TypeIds.clear(); 843 ++i; 844 } 845 } 846 847 void MachineFunction::addCleanup(MachineBasicBlock *LandingPad) { 848 LandingPadInfo &LP = getOrCreateLandingPadInfo(LandingPad); 849 LP.TypeIds.push_back(0); 850 } 851 852 void MachineFunction::addSEHCatchHandler(MachineBasicBlock *LandingPad, 853 const Function *Filter, 854 const BlockAddress *RecoverBA) { 855 LandingPadInfo &LP = getOrCreateLandingPadInfo(LandingPad); 856 SEHHandler Handler; 857 Handler.FilterOrFinally = Filter; 858 Handler.RecoverBA = RecoverBA; 859 LP.SEHHandlers.push_back(Handler); 860 } 861 862 void MachineFunction::addSEHCleanupHandler(MachineBasicBlock *LandingPad, 863 const Function *Cleanup) { 864 LandingPadInfo &LP = getOrCreateLandingPadInfo(LandingPad); 865 SEHHandler Handler; 866 Handler.FilterOrFinally = Cleanup; 867 Handler.RecoverBA = nullptr; 868 LP.SEHHandlers.push_back(Handler); 869 } 870 871 void MachineFunction::setCallSiteLandingPad(MCSymbol *Sym, 872 ArrayRef<unsigned> Sites) { 873 LPadToCallSiteMap[Sym].append(Sites.begin(), Sites.end()); 874 } 875 876 unsigned MachineFunction::getTypeIDFor(const GlobalValue *TI) { 877 for (unsigned i = 0, N = TypeInfos.size(); i != N; ++i) 878 if (TypeInfos[i] == TI) return i + 1; 879 880 TypeInfos.push_back(TI); 881 return TypeInfos.size(); 882 } 883 884 int MachineFunction::getFilterIDFor(std::vector<unsigned> &TyIds) { 885 // If the new filter coincides with the tail of an existing filter, then 886 // re-use the existing filter. Folding filters more than this requires 887 // re-ordering filters and/or their elements - probably not worth it. 888 for (std::vector<unsigned>::iterator I = FilterEnds.begin(), 889 E = FilterEnds.end(); I != E; ++I) { 890 unsigned i = *I, j = TyIds.size(); 891 892 while (i && j) 893 if (FilterIds[--i] != TyIds[--j]) 894 goto try_next; 895 896 if (!j) 897 // The new filter coincides with range [i, end) of the existing filter. 898 return -(1 + i); 899 900 try_next:; 901 } 902 903 // Add the new filter. 904 int FilterID = -(1 + FilterIds.size()); 905 FilterIds.reserve(FilterIds.size() + TyIds.size() + 1); 906 FilterIds.insert(FilterIds.end(), TyIds.begin(), TyIds.end()); 907 FilterEnds.push_back(FilterIds.size()); 908 FilterIds.push_back(0); // terminator 909 return FilterID; 910 } 911 912 MachineFunction::CallSiteInfoMap::iterator 913 MachineFunction::getCallSiteInfo(const MachineInstr *MI) { 914 assert(MI->isCandidateForCallSiteEntry() && 915 "Call site info refers only to call (MI) candidates"); 916 917 if (!Target.Options.EmitCallSiteInfo) 918 return CallSitesInfo.end(); 919 return CallSitesInfo.find(MI); 920 } 921 922 /// Return the call machine instruction or find a call within bundle. 923 static const MachineInstr *getCallInstr(const MachineInstr *MI) { 924 if (!MI->isBundle()) 925 return MI; 926 927 for (auto &BMI : make_range(getBundleStart(MI->getIterator()), 928 getBundleEnd(MI->getIterator()))) 929 if (BMI.isCandidateForCallSiteEntry()) 930 return &BMI; 931 932 llvm_unreachable("Unexpected bundle without a call site candidate"); 933 } 934 935 void MachineFunction::eraseCallSiteInfo(const MachineInstr *MI) { 936 assert(MI->shouldUpdateCallSiteInfo() && 937 "Call site info refers only to call (MI) candidates or " 938 "candidates inside bundles"); 939 940 const MachineInstr *CallMI = getCallInstr(MI); 941 CallSiteInfoMap::iterator CSIt = getCallSiteInfo(CallMI); 942 if (CSIt == CallSitesInfo.end()) 943 return; 944 CallSitesInfo.erase(CSIt); 945 } 946 947 void MachineFunction::copyCallSiteInfo(const MachineInstr *Old, 948 const MachineInstr *New) { 949 assert(Old->shouldUpdateCallSiteInfo() && 950 "Call site info refers only to call (MI) candidates or " 951 "candidates inside bundles"); 952 953 if (!New->isCandidateForCallSiteEntry()) 954 return eraseCallSiteInfo(Old); 955 956 const MachineInstr *OldCallMI = getCallInstr(Old); 957 CallSiteInfoMap::iterator CSIt = getCallSiteInfo(OldCallMI); 958 if (CSIt == CallSitesInfo.end()) 959 return; 960 961 CallSiteInfo CSInfo = CSIt->second; 962 CallSitesInfo[New] = CSInfo; 963 } 964 965 void MachineFunction::moveCallSiteInfo(const MachineInstr *Old, 966 const MachineInstr *New) { 967 assert(Old->shouldUpdateCallSiteInfo() && 968 "Call site info refers only to call (MI) candidates or " 969 "candidates inside bundles"); 970 971 if (!New->isCandidateForCallSiteEntry()) 972 return eraseCallSiteInfo(Old); 973 974 const MachineInstr *OldCallMI = getCallInstr(Old); 975 CallSiteInfoMap::iterator CSIt = getCallSiteInfo(OldCallMI); 976 if (CSIt == CallSitesInfo.end()) 977 return; 978 979 CallSiteInfo CSInfo = std::move(CSIt->second); 980 CallSitesInfo.erase(CSIt); 981 CallSitesInfo[New] = CSInfo; 982 } 983 984 /// \} 985 986 //===----------------------------------------------------------------------===// 987 // MachineJumpTableInfo implementation 988 //===----------------------------------------------------------------------===// 989 990 /// Return the size of each entry in the jump table. 991 unsigned MachineJumpTableInfo::getEntrySize(const DataLayout &TD) const { 992 // The size of a jump table entry is 4 bytes unless the entry is just the 993 // address of a block, in which case it is the pointer size. 994 switch (getEntryKind()) { 995 case MachineJumpTableInfo::EK_BlockAddress: 996 return TD.getPointerSize(); 997 case MachineJumpTableInfo::EK_GPRel64BlockAddress: 998 return 8; 999 case MachineJumpTableInfo::EK_GPRel32BlockAddress: 1000 case MachineJumpTableInfo::EK_LabelDifference32: 1001 case MachineJumpTableInfo::EK_Custom32: 1002 return 4; 1003 case MachineJumpTableInfo::EK_Inline: 1004 return 0; 1005 } 1006 llvm_unreachable("Unknown jump table encoding!"); 1007 } 1008 1009 /// Return the alignment of each entry in the jump table. 1010 unsigned MachineJumpTableInfo::getEntryAlignment(const DataLayout &TD) const { 1011 // The alignment of a jump table entry is the alignment of int32 unless the 1012 // entry is just the address of a block, in which case it is the pointer 1013 // alignment. 1014 switch (getEntryKind()) { 1015 case MachineJumpTableInfo::EK_BlockAddress: 1016 return TD.getPointerABIAlignment(0).value(); 1017 case MachineJumpTableInfo::EK_GPRel64BlockAddress: 1018 return TD.getABIIntegerTypeAlignment(64).value(); 1019 case MachineJumpTableInfo::EK_GPRel32BlockAddress: 1020 case MachineJumpTableInfo::EK_LabelDifference32: 1021 case MachineJumpTableInfo::EK_Custom32: 1022 return TD.getABIIntegerTypeAlignment(32).value(); 1023 case MachineJumpTableInfo::EK_Inline: 1024 return 1; 1025 } 1026 llvm_unreachable("Unknown jump table encoding!"); 1027 } 1028 1029 /// Create a new jump table entry in the jump table info. 1030 unsigned MachineJumpTableInfo::createJumpTableIndex( 1031 const std::vector<MachineBasicBlock*> &DestBBs) { 1032 assert(!DestBBs.empty() && "Cannot create an empty jump table!"); 1033 JumpTables.push_back(MachineJumpTableEntry(DestBBs)); 1034 return JumpTables.size()-1; 1035 } 1036 1037 /// If Old is the target of any jump tables, update the jump tables to branch 1038 /// to New instead. 1039 bool MachineJumpTableInfo::ReplaceMBBInJumpTables(MachineBasicBlock *Old, 1040 MachineBasicBlock *New) { 1041 assert(Old != New && "Not making a change?"); 1042 bool MadeChange = false; 1043 for (size_t i = 0, e = JumpTables.size(); i != e; ++i) 1044 ReplaceMBBInJumpTable(i, Old, New); 1045 return MadeChange; 1046 } 1047 1048 /// If Old is a target of the jump tables, update the jump table to branch to 1049 /// New instead. 1050 bool MachineJumpTableInfo::ReplaceMBBInJumpTable(unsigned Idx, 1051 MachineBasicBlock *Old, 1052 MachineBasicBlock *New) { 1053 assert(Old != New && "Not making a change?"); 1054 bool MadeChange = false; 1055 MachineJumpTableEntry &JTE = JumpTables[Idx]; 1056 for (size_t j = 0, e = JTE.MBBs.size(); j != e; ++j) 1057 if (JTE.MBBs[j] == Old) { 1058 JTE.MBBs[j] = New; 1059 MadeChange = true; 1060 } 1061 return MadeChange; 1062 } 1063 1064 void MachineJumpTableInfo::print(raw_ostream &OS) const { 1065 if (JumpTables.empty()) return; 1066 1067 OS << "Jump Tables:\n"; 1068 1069 for (unsigned i = 0, e = JumpTables.size(); i != e; ++i) { 1070 OS << printJumpTableEntryReference(i) << ':'; 1071 for (unsigned j = 0, f = JumpTables[i].MBBs.size(); j != f; ++j) 1072 OS << ' ' << printMBBReference(*JumpTables[i].MBBs[j]); 1073 if (i != e) 1074 OS << '\n'; 1075 } 1076 1077 OS << '\n'; 1078 } 1079 1080 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) 1081 LLVM_DUMP_METHOD void MachineJumpTableInfo::dump() const { print(dbgs()); } 1082 #endif 1083 1084 Printable llvm::printJumpTableEntryReference(unsigned Idx) { 1085 return Printable([Idx](raw_ostream &OS) { OS << "%jump-table." << Idx; }); 1086 } 1087 1088 //===----------------------------------------------------------------------===// 1089 // MachineConstantPool implementation 1090 //===----------------------------------------------------------------------===// 1091 1092 void MachineConstantPoolValue::anchor() {} 1093 1094 Type *MachineConstantPoolEntry::getType() const { 1095 if (isMachineConstantPoolEntry()) 1096 return Val.MachineCPVal->getType(); 1097 return Val.ConstVal->getType(); 1098 } 1099 1100 bool MachineConstantPoolEntry::needsRelocation() const { 1101 if (isMachineConstantPoolEntry()) 1102 return true; 1103 return Val.ConstVal->needsRelocation(); 1104 } 1105 1106 SectionKind 1107 MachineConstantPoolEntry::getSectionKind(const DataLayout *DL) const { 1108 if (needsRelocation()) 1109 return SectionKind::getReadOnlyWithRel(); 1110 switch (DL->getTypeAllocSize(getType())) { 1111 case 4: 1112 return SectionKind::getMergeableConst4(); 1113 case 8: 1114 return SectionKind::getMergeableConst8(); 1115 case 16: 1116 return SectionKind::getMergeableConst16(); 1117 case 32: 1118 return SectionKind::getMergeableConst32(); 1119 default: 1120 return SectionKind::getReadOnly(); 1121 } 1122 } 1123 1124 MachineConstantPool::~MachineConstantPool() { 1125 // A constant may be a member of both Constants and MachineCPVsSharingEntries, 1126 // so keep track of which we've deleted to avoid double deletions. 1127 DenseSet<MachineConstantPoolValue*> Deleted; 1128 for (unsigned i = 0, e = Constants.size(); i != e; ++i) 1129 if (Constants[i].isMachineConstantPoolEntry()) { 1130 Deleted.insert(Constants[i].Val.MachineCPVal); 1131 delete Constants[i].Val.MachineCPVal; 1132 } 1133 for (DenseSet<MachineConstantPoolValue*>::iterator I = 1134 MachineCPVsSharingEntries.begin(), E = MachineCPVsSharingEntries.end(); 1135 I != E; ++I) { 1136 if (Deleted.count(*I) == 0) 1137 delete *I; 1138 } 1139 } 1140 1141 /// Test whether the given two constants can be allocated the same constant pool 1142 /// entry. 1143 static bool CanShareConstantPoolEntry(const Constant *A, const Constant *B, 1144 const DataLayout &DL) { 1145 // Handle the trivial case quickly. 1146 if (A == B) return true; 1147 1148 // If they have the same type but weren't the same constant, quickly 1149 // reject them. 1150 if (A->getType() == B->getType()) return false; 1151 1152 // We can't handle structs or arrays. 1153 if (isa<StructType>(A->getType()) || isa<ArrayType>(A->getType()) || 1154 isa<StructType>(B->getType()) || isa<ArrayType>(B->getType())) 1155 return false; 1156 1157 // For now, only support constants with the same size. 1158 uint64_t StoreSize = DL.getTypeStoreSize(A->getType()); 1159 if (StoreSize != DL.getTypeStoreSize(B->getType()) || StoreSize > 128) 1160 return false; 1161 1162 Type *IntTy = IntegerType::get(A->getContext(), StoreSize*8); 1163 1164 // Try constant folding a bitcast of both instructions to an integer. If we 1165 // get two identical ConstantInt's, then we are good to share them. We use 1166 // the constant folding APIs to do this so that we get the benefit of 1167 // DataLayout. 1168 if (isa<PointerType>(A->getType())) 1169 A = ConstantFoldCastOperand(Instruction::PtrToInt, 1170 const_cast<Constant *>(A), IntTy, DL); 1171 else if (A->getType() != IntTy) 1172 A = ConstantFoldCastOperand(Instruction::BitCast, const_cast<Constant *>(A), 1173 IntTy, DL); 1174 if (isa<PointerType>(B->getType())) 1175 B = ConstantFoldCastOperand(Instruction::PtrToInt, 1176 const_cast<Constant *>(B), IntTy, DL); 1177 else if (B->getType() != IntTy) 1178 B = ConstantFoldCastOperand(Instruction::BitCast, const_cast<Constant *>(B), 1179 IntTy, DL); 1180 1181 return A == B; 1182 } 1183 1184 /// Create a new entry in the constant pool or return an existing one. 1185 /// User must specify the log2 of the minimum required alignment for the object. 1186 unsigned MachineConstantPool::getConstantPoolIndex(const Constant *C, 1187 Align Alignment) { 1188 if (Alignment > PoolAlignment) PoolAlignment = Alignment; 1189 1190 // Check to see if we already have this constant. 1191 // 1192 // FIXME, this could be made much more efficient for large constant pools. 1193 for (unsigned i = 0, e = Constants.size(); i != e; ++i) 1194 if (!Constants[i].isMachineConstantPoolEntry() && 1195 CanShareConstantPoolEntry(Constants[i].Val.ConstVal, C, DL)) { 1196 if (Constants[i].getAlign() < Alignment) 1197 Constants[i].Alignment = Alignment; 1198 return i; 1199 } 1200 1201 Constants.push_back(MachineConstantPoolEntry(C, Alignment)); 1202 return Constants.size()-1; 1203 } 1204 1205 unsigned MachineConstantPool::getConstantPoolIndex(MachineConstantPoolValue *V, 1206 Align Alignment) { 1207 if (Alignment > PoolAlignment) PoolAlignment = Alignment; 1208 1209 // Check to see if we already have this constant. 1210 // 1211 // FIXME, this could be made much more efficient for large constant pools. 1212 int Idx = V->getExistingMachineCPValue(this, Alignment); 1213 if (Idx != -1) { 1214 MachineCPVsSharingEntries.insert(V); 1215 return (unsigned)Idx; 1216 } 1217 1218 Constants.push_back(MachineConstantPoolEntry(V, Alignment)); 1219 return Constants.size()-1; 1220 } 1221 1222 void MachineConstantPool::print(raw_ostream &OS) const { 1223 if (Constants.empty()) return; 1224 1225 OS << "Constant Pool:\n"; 1226 for (unsigned i = 0, e = Constants.size(); i != e; ++i) { 1227 OS << " cp#" << i << ": "; 1228 if (Constants[i].isMachineConstantPoolEntry()) 1229 Constants[i].Val.MachineCPVal->print(OS); 1230 else 1231 Constants[i].Val.ConstVal->printAsOperand(OS, /*PrintType=*/false); 1232 OS << ", align=" << Constants[i].getAlign().value(); 1233 OS << "\n"; 1234 } 1235 } 1236 1237 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) 1238 LLVM_DUMP_METHOD void MachineConstantPool::dump() const { print(dbgs()); } 1239 #endif 1240