Revert r354244 "[DAGCombiner] Eliminate dead stores to stack."
[llvm-complete.git] / lib / CodeGen / MachineFunction.cpp
blob84a20762d62b5f196cfd4fb163bf5b1ad62bbc8e
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.
13 //===----------------------------------------------------------------------===//
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/TargetLowering.h"
37 #include "llvm/CodeGen/TargetRegisterInfo.h"
38 #include "llvm/CodeGen/TargetSubtargetInfo.h"
39 #include "llvm/CodeGen/WasmEHFuncInfo.h"
40 #include "llvm/CodeGen/WinEHFuncInfo.h"
41 #include "llvm/Config/llvm-config.h"
42 #include "llvm/IR/Attributes.h"
43 #include "llvm/IR/BasicBlock.h"
44 #include "llvm/IR/Constant.h"
45 #include "llvm/IR/DataLayout.h"
46 #include "llvm/IR/DerivedTypes.h"
47 #include "llvm/IR/Function.h"
48 #include "llvm/IR/GlobalValue.h"
49 #include "llvm/IR/Instruction.h"
50 #include "llvm/IR/Instructions.h"
51 #include "llvm/IR/Metadata.h"
52 #include "llvm/IR/Module.h"
53 #include "llvm/IR/ModuleSlotTracker.h"
54 #include "llvm/IR/Value.h"
55 #include "llvm/MC/MCContext.h"
56 #include "llvm/MC/MCSymbol.h"
57 #include "llvm/MC/SectionKind.h"
58 #include "llvm/Support/Casting.h"
59 #include "llvm/Support/CommandLine.h"
60 #include "llvm/Support/Compiler.h"
61 #include "llvm/Support/DOTGraphTraits.h"
62 #include "llvm/Support/Debug.h"
63 #include "llvm/Support/ErrorHandling.h"
64 #include "llvm/Support/GraphWriter.h"
65 #include "llvm/Support/raw_ostream.h"
66 #include "llvm/Target/TargetMachine.h"
67 #include <algorithm>
68 #include <cassert>
69 #include <cstddef>
70 #include <cstdint>
71 #include <iterator>
72 #include <string>
73 #include <utility>
74 #include <vector>
76 using namespace llvm;
78 #define DEBUG_TYPE "codegen"
80 static cl::opt<unsigned>
81 AlignAllFunctions("align-all-functions",
82 cl::desc("Force the alignment of all functions."),
83 cl::init(0), cl::Hidden);
85 static const char *getPropertyName(MachineFunctionProperties::Property Prop) {
86 using P = MachineFunctionProperties::Property;
88 switch(Prop) {
89 case P::FailedISel: return "FailedISel";
90 case P::IsSSA: return "IsSSA";
91 case P::Legalized: return "Legalized";
92 case P::NoPHIs: return "NoPHIs";
93 case P::NoVRegs: return "NoVRegs";
94 case P::RegBankSelected: return "RegBankSelected";
95 case P::Selected: return "Selected";
96 case P::TracksLiveness: return "TracksLiveness";
98 llvm_unreachable("Invalid machine function property");
101 // Pin the vtable to this file.
102 void MachineFunction::Delegate::anchor() {}
104 void MachineFunctionProperties::print(raw_ostream &OS) const {
105 const char *Separator = "";
106 for (BitVector::size_type I = 0; I < Properties.size(); ++I) {
107 if (!Properties[I])
108 continue;
109 OS << Separator << getPropertyName(static_cast<Property>(I));
110 Separator = ", ";
114 //===----------------------------------------------------------------------===//
115 // MachineFunction implementation
116 //===----------------------------------------------------------------------===//
118 // Out-of-line virtual method.
119 MachineFunctionInfo::~MachineFunctionInfo() = default;
121 void ilist_alloc_traits<MachineBasicBlock>::deleteNode(MachineBasicBlock *MBB) {
122 MBB->getParent()->DeleteMachineBasicBlock(MBB);
125 static inline unsigned getFnStackAlignment(const TargetSubtargetInfo *STI,
126 const Function &F) {
127 if (F.hasFnAttribute(Attribute::StackAlignment))
128 return F.getFnStackAlignment();
129 return STI->getFrameLowering()->getStackAlignment();
132 MachineFunction::MachineFunction(const Function &F,
133 const LLVMTargetMachine &Target,
134 const TargetSubtargetInfo &STI,
135 unsigned FunctionNum, MachineModuleInfo &mmi)
136 : F(F), Target(Target), STI(&STI), Ctx(mmi.getContext()), MMI(mmi) {
137 FunctionNumber = FunctionNum;
138 init();
141 void MachineFunction::handleInsertion(MachineInstr &MI) {
142 if (TheDelegate)
143 TheDelegate->MF_HandleInsertion(MI);
146 void MachineFunction::handleRemoval(MachineInstr &MI) {
147 if (TheDelegate)
148 TheDelegate->MF_HandleRemoval(MI);
151 void MachineFunction::init() {
152 // Assume the function starts in SSA form with correct liveness.
153 Properties.set(MachineFunctionProperties::Property::IsSSA);
154 Properties.set(MachineFunctionProperties::Property::TracksLiveness);
155 if (STI->getRegisterInfo())
156 RegInfo = new (Allocator) MachineRegisterInfo(this);
157 else
158 RegInfo = nullptr;
160 MFInfo = nullptr;
161 // We can realign the stack if the target supports it and the user hasn't
162 // explicitly asked us not to.
163 bool CanRealignSP = STI->getFrameLowering()->isStackRealignable() &&
164 !F.hasFnAttribute("no-realign-stack");
165 FrameInfo = new (Allocator) MachineFrameInfo(
166 getFnStackAlignment(STI, F), /*StackRealignable=*/CanRealignSP,
167 /*ForceRealign=*/CanRealignSP &&
168 F.hasFnAttribute(Attribute::StackAlignment));
170 if (F.hasFnAttribute(Attribute::StackAlignment))
171 FrameInfo->ensureMaxAlignment(F.getFnStackAlignment());
173 ConstantPool = new (Allocator) MachineConstantPool(getDataLayout());
174 Alignment = STI->getTargetLowering()->getMinFunctionAlignment();
176 // FIXME: Shouldn't use pref alignment if explicit alignment is set on F.
177 // FIXME: Use Function::optForSize().
178 if (!F.hasFnAttribute(Attribute::OptimizeForSize))
179 Alignment = std::max(Alignment,
180 STI->getTargetLowering()->getPrefFunctionAlignment());
182 if (AlignAllFunctions)
183 Alignment = AlignAllFunctions;
185 JumpTableInfo = nullptr;
187 if (isFuncletEHPersonality(classifyEHPersonality(
188 F.hasPersonalityFn() ? F.getPersonalityFn() : nullptr))) {
189 WinEHInfo = new (Allocator) WinEHFuncInfo();
192 if (isScopedEHPersonality(classifyEHPersonality(
193 F.hasPersonalityFn() ? F.getPersonalityFn() : nullptr))) {
194 WasmEHInfo = new (Allocator) WasmEHFuncInfo();
197 assert(Target.isCompatibleDataLayout(getDataLayout()) &&
198 "Can't create a MachineFunction using a Module with a "
199 "Target-incompatible DataLayout attached\n");
201 PSVManager =
202 llvm::make_unique<PseudoSourceValueManager>(*(getSubtarget().
203 getInstrInfo()));
206 MachineFunction::~MachineFunction() {
207 clear();
210 void MachineFunction::clear() {
211 Properties.reset();
212 // Don't call destructors on MachineInstr and MachineOperand. All of their
213 // memory comes from the BumpPtrAllocator which is about to be purged.
215 // Do call MachineBasicBlock destructors, it contains std::vectors.
216 for (iterator I = begin(), E = end(); I != E; I = BasicBlocks.erase(I))
217 I->Insts.clearAndLeakNodesUnsafely();
218 MBBNumbering.clear();
220 InstructionRecycler.clear(Allocator);
221 OperandRecycler.clear(Allocator);
222 BasicBlockRecycler.clear(Allocator);
223 CodeViewAnnotations.clear();
224 VariableDbgInfos.clear();
225 if (RegInfo) {
226 RegInfo->~MachineRegisterInfo();
227 Allocator.Deallocate(RegInfo);
229 if (MFInfo) {
230 MFInfo->~MachineFunctionInfo();
231 Allocator.Deallocate(MFInfo);
234 FrameInfo->~MachineFrameInfo();
235 Allocator.Deallocate(FrameInfo);
237 ConstantPool->~MachineConstantPool();
238 Allocator.Deallocate(ConstantPool);
240 if (JumpTableInfo) {
241 JumpTableInfo->~MachineJumpTableInfo();
242 Allocator.Deallocate(JumpTableInfo);
245 if (WinEHInfo) {
246 WinEHInfo->~WinEHFuncInfo();
247 Allocator.Deallocate(WinEHInfo);
250 if (WasmEHInfo) {
251 WasmEHInfo->~WasmEHFuncInfo();
252 Allocator.Deallocate(WasmEHInfo);
256 const DataLayout &MachineFunction::getDataLayout() const {
257 return F.getParent()->getDataLayout();
260 /// Get the JumpTableInfo for this function.
261 /// If it does not already exist, allocate one.
262 MachineJumpTableInfo *MachineFunction::
263 getOrCreateJumpTableInfo(unsigned EntryKind) {
264 if (JumpTableInfo) return JumpTableInfo;
266 JumpTableInfo = new (Allocator)
267 MachineJumpTableInfo((MachineJumpTableInfo::JTEntryKind)EntryKind);
268 return JumpTableInfo;
271 /// Should we be emitting segmented stack stuff for the function
272 bool MachineFunction::shouldSplitStack() const {
273 return getFunction().hasFnAttribute("split-stack");
276 /// This discards all of the MachineBasicBlock numbers and recomputes them.
277 /// This guarantees that the MBB numbers are sequential, dense, and match the
278 /// ordering of the blocks within the function. If a specific MachineBasicBlock
279 /// is specified, only that block and those after it are renumbered.
280 void MachineFunction::RenumberBlocks(MachineBasicBlock *MBB) {
281 if (empty()) { MBBNumbering.clear(); return; }
282 MachineFunction::iterator MBBI, E = end();
283 if (MBB == nullptr)
284 MBBI = begin();
285 else
286 MBBI = MBB->getIterator();
288 // Figure out the block number this should have.
289 unsigned BlockNo = 0;
290 if (MBBI != begin())
291 BlockNo = std::prev(MBBI)->getNumber() + 1;
293 for (; MBBI != E; ++MBBI, ++BlockNo) {
294 if (MBBI->getNumber() != (int)BlockNo) {
295 // Remove use of the old number.
296 if (MBBI->getNumber() != -1) {
297 assert(MBBNumbering[MBBI->getNumber()] == &*MBBI &&
298 "MBB number mismatch!");
299 MBBNumbering[MBBI->getNumber()] = nullptr;
302 // If BlockNo is already taken, set that block's number to -1.
303 if (MBBNumbering[BlockNo])
304 MBBNumbering[BlockNo]->setNumber(-1);
306 MBBNumbering[BlockNo] = &*MBBI;
307 MBBI->setNumber(BlockNo);
311 // Okay, all the blocks are renumbered. If we have compactified the block
312 // numbering, shrink MBBNumbering now.
313 assert(BlockNo <= MBBNumbering.size() && "Mismatch!");
314 MBBNumbering.resize(BlockNo);
317 /// Allocate a new MachineInstr. Use this instead of `new MachineInstr'.
318 MachineInstr *MachineFunction::CreateMachineInstr(const MCInstrDesc &MCID,
319 const DebugLoc &DL,
320 bool NoImp) {
321 return new (InstructionRecycler.Allocate<MachineInstr>(Allocator))
322 MachineInstr(*this, MCID, DL, NoImp);
325 /// Create a new MachineInstr which is a copy of the 'Orig' instruction,
326 /// identical in all ways except the instruction has no parent, prev, or next.
327 MachineInstr *
328 MachineFunction::CloneMachineInstr(const MachineInstr *Orig) {
329 return new (InstructionRecycler.Allocate<MachineInstr>(Allocator))
330 MachineInstr(*this, *Orig);
333 MachineInstr &MachineFunction::CloneMachineInstrBundle(MachineBasicBlock &MBB,
334 MachineBasicBlock::iterator InsertBefore, const MachineInstr &Orig) {
335 MachineInstr *FirstClone = nullptr;
336 MachineBasicBlock::const_instr_iterator I = Orig.getIterator();
337 while (true) {
338 MachineInstr *Cloned = CloneMachineInstr(&*I);
339 MBB.insert(InsertBefore, Cloned);
340 if (FirstClone == nullptr) {
341 FirstClone = Cloned;
342 } else {
343 Cloned->bundleWithPred();
346 if (!I->isBundledWithSucc())
347 break;
348 ++I;
350 return *FirstClone;
353 /// Delete the given MachineInstr.
355 /// This function also serves as the MachineInstr destructor - the real
356 /// ~MachineInstr() destructor must be empty.
357 void
358 MachineFunction::DeleteMachineInstr(MachineInstr *MI) {
359 // Strip it for parts. The operand array and the MI object itself are
360 // independently recyclable.
361 if (MI->Operands)
362 deallocateOperandArray(MI->CapOperands, MI->Operands);
363 // Don't call ~MachineInstr() which must be trivial anyway because
364 // ~MachineFunction drops whole lists of MachineInstrs wihout calling their
365 // destructors.
366 InstructionRecycler.Deallocate(Allocator, MI);
369 /// Allocate a new MachineBasicBlock. Use this instead of
370 /// `new MachineBasicBlock'.
371 MachineBasicBlock *
372 MachineFunction::CreateMachineBasicBlock(const BasicBlock *bb) {
373 return new (BasicBlockRecycler.Allocate<MachineBasicBlock>(Allocator))
374 MachineBasicBlock(*this, bb);
377 /// Delete the given MachineBasicBlock.
378 void
379 MachineFunction::DeleteMachineBasicBlock(MachineBasicBlock *MBB) {
380 assert(MBB->getParent() == this && "MBB parent mismatch!");
381 MBB->~MachineBasicBlock();
382 BasicBlockRecycler.Deallocate(Allocator, MBB);
385 MachineMemOperand *MachineFunction::getMachineMemOperand(
386 MachinePointerInfo PtrInfo, MachineMemOperand::Flags f, uint64_t s,
387 unsigned base_alignment, const AAMDNodes &AAInfo, const MDNode *Ranges,
388 SyncScope::ID SSID, AtomicOrdering Ordering,
389 AtomicOrdering FailureOrdering) {
390 return new (Allocator)
391 MachineMemOperand(PtrInfo, f, s, base_alignment, AAInfo, Ranges,
392 SSID, Ordering, FailureOrdering);
395 MachineMemOperand *
396 MachineFunction::getMachineMemOperand(const MachineMemOperand *MMO,
397 int64_t Offset, uint64_t Size) {
398 const MachinePointerInfo &PtrInfo = MMO->getPointerInfo();
400 // If there is no pointer value, the offset isn't tracked so we need to adjust
401 // the base alignment.
402 unsigned Align = PtrInfo.V.isNull()
403 ? MinAlign(MMO->getBaseAlignment(), Offset)
404 : MMO->getBaseAlignment();
406 return new (Allocator)
407 MachineMemOperand(PtrInfo.getWithOffset(Offset), MMO->getFlags(), Size,
408 Align, AAMDNodes(), nullptr, MMO->getSyncScopeID(),
409 MMO->getOrdering(), MMO->getFailureOrdering());
412 MachineMemOperand *
413 MachineFunction::getMachineMemOperand(const MachineMemOperand *MMO,
414 const AAMDNodes &AAInfo) {
415 MachinePointerInfo MPI = MMO->getValue() ?
416 MachinePointerInfo(MMO->getValue(), MMO->getOffset()) :
417 MachinePointerInfo(MMO->getPseudoValue(), MMO->getOffset());
419 return new (Allocator)
420 MachineMemOperand(MPI, MMO->getFlags(), MMO->getSize(),
421 MMO->getBaseAlignment(), AAInfo,
422 MMO->getRanges(), MMO->getSyncScopeID(),
423 MMO->getOrdering(), MMO->getFailureOrdering());
426 MachineInstr::ExtraInfo *
427 MachineFunction::createMIExtraInfo(ArrayRef<MachineMemOperand *> MMOs,
428 MCSymbol *PreInstrSymbol,
429 MCSymbol *PostInstrSymbol) {
430 return MachineInstr::ExtraInfo::create(Allocator, MMOs, PreInstrSymbol,
431 PostInstrSymbol);
434 const char *MachineFunction::createExternalSymbolName(StringRef Name) {
435 char *Dest = Allocator.Allocate<char>(Name.size() + 1);
436 llvm::copy(Name, Dest);
437 Dest[Name.size()] = 0;
438 return Dest;
441 uint32_t *MachineFunction::allocateRegMask() {
442 unsigned NumRegs = getSubtarget().getRegisterInfo()->getNumRegs();
443 unsigned Size = MachineOperand::getRegMaskSize(NumRegs);
444 uint32_t *Mask = Allocator.Allocate<uint32_t>(Size);
445 memset(Mask, 0, Size * sizeof(Mask[0]));
446 return Mask;
449 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
450 LLVM_DUMP_METHOD void MachineFunction::dump() const {
451 print(dbgs());
453 #endif
455 StringRef MachineFunction::getName() const {
456 return getFunction().getName();
459 void MachineFunction::print(raw_ostream &OS, const SlotIndexes *Indexes) const {
460 OS << "# Machine code for function " << getName() << ": ";
461 getProperties().print(OS);
462 OS << '\n';
464 // Print Frame Information
465 FrameInfo->print(*this, OS);
467 // Print JumpTable Information
468 if (JumpTableInfo)
469 JumpTableInfo->print(OS);
471 // Print Constant Pool
472 ConstantPool->print(OS);
474 const TargetRegisterInfo *TRI = getSubtarget().getRegisterInfo();
476 if (RegInfo && !RegInfo->livein_empty()) {
477 OS << "Function Live Ins: ";
478 for (MachineRegisterInfo::livein_iterator
479 I = RegInfo->livein_begin(), E = RegInfo->livein_end(); I != E; ++I) {
480 OS << printReg(I->first, TRI);
481 if (I->second)
482 OS << " in " << printReg(I->second, TRI);
483 if (std::next(I) != E)
484 OS << ", ";
486 OS << '\n';
489 ModuleSlotTracker MST(getFunction().getParent());
490 MST.incorporateFunction(getFunction());
491 for (const auto &BB : *this) {
492 OS << '\n';
493 // If we print the whole function, print it at its most verbose level.
494 BB.print(OS, MST, Indexes, /*IsStandalone=*/true);
497 OS << "\n# End machine code for function " << getName() << ".\n\n";
500 namespace llvm {
502 template<>
503 struct DOTGraphTraits<const MachineFunction*> : public DefaultDOTGraphTraits {
504 DOTGraphTraits(bool isSimple = false) : DefaultDOTGraphTraits(isSimple) {}
506 static std::string getGraphName(const MachineFunction *F) {
507 return ("CFG for '" + F->getName() + "' function").str();
510 std::string getNodeLabel(const MachineBasicBlock *Node,
511 const MachineFunction *Graph) {
512 std::string OutStr;
514 raw_string_ostream OSS(OutStr);
516 if (isSimple()) {
517 OSS << printMBBReference(*Node);
518 if (const BasicBlock *BB = Node->getBasicBlock())
519 OSS << ": " << BB->getName();
520 } else
521 Node->print(OSS);
524 if (OutStr[0] == '\n') OutStr.erase(OutStr.begin());
526 // Process string output to make it nicer...
527 for (unsigned i = 0; i != OutStr.length(); ++i)
528 if (OutStr[i] == '\n') { // Left justify
529 OutStr[i] = '\\';
530 OutStr.insert(OutStr.begin()+i+1, 'l');
532 return OutStr;
536 } // end namespace llvm
538 void MachineFunction::viewCFG() const
540 #ifndef NDEBUG
541 ViewGraph(this, "mf" + getName());
542 #else
543 errs() << "MachineFunction::viewCFG is only available in debug builds on "
544 << "systems with Graphviz or gv!\n";
545 #endif // NDEBUG
548 void MachineFunction::viewCFGOnly() const
550 #ifndef NDEBUG
551 ViewGraph(this, "mf" + getName(), true);
552 #else
553 errs() << "MachineFunction::viewCFGOnly is only available in debug builds on "
554 << "systems with Graphviz or gv!\n";
555 #endif // NDEBUG
558 /// Add the specified physical register as a live-in value and
559 /// create a corresponding virtual register for it.
560 unsigned MachineFunction::addLiveIn(unsigned PReg,
561 const TargetRegisterClass *RC) {
562 MachineRegisterInfo &MRI = getRegInfo();
563 unsigned VReg = MRI.getLiveInVirtReg(PReg);
564 if (VReg) {
565 const TargetRegisterClass *VRegRC = MRI.getRegClass(VReg);
566 (void)VRegRC;
567 // A physical register can be added several times.
568 // Between two calls, the register class of the related virtual register
569 // may have been constrained to match some operation constraints.
570 // In that case, check that the current register class includes the
571 // physical register and is a sub class of the specified RC.
572 assert((VRegRC == RC || (VRegRC->contains(PReg) &&
573 RC->hasSubClassEq(VRegRC))) &&
574 "Register class mismatch!");
575 return VReg;
577 VReg = MRI.createVirtualRegister(RC);
578 MRI.addLiveIn(PReg, VReg);
579 return VReg;
582 /// Return the MCSymbol for the specified non-empty jump table.
583 /// If isLinkerPrivate is specified, an 'l' label is returned, otherwise a
584 /// normal 'L' label is returned.
585 MCSymbol *MachineFunction::getJTISymbol(unsigned JTI, MCContext &Ctx,
586 bool isLinkerPrivate) const {
587 const DataLayout &DL = getDataLayout();
588 assert(JumpTableInfo && "No jump tables");
589 assert(JTI < JumpTableInfo->getJumpTables().size() && "Invalid JTI!");
591 StringRef Prefix = isLinkerPrivate ? DL.getLinkerPrivateGlobalPrefix()
592 : DL.getPrivateGlobalPrefix();
593 SmallString<60> Name;
594 raw_svector_ostream(Name)
595 << Prefix << "JTI" << getFunctionNumber() << '_' << JTI;
596 return Ctx.getOrCreateSymbol(Name);
599 /// Return a function-local symbol to represent the PIC base.
600 MCSymbol *MachineFunction::getPICBaseSymbol() const {
601 const DataLayout &DL = getDataLayout();
602 return Ctx.getOrCreateSymbol(Twine(DL.getPrivateGlobalPrefix()) +
603 Twine(getFunctionNumber()) + "$pb");
606 /// \name Exception Handling
607 /// \{
609 LandingPadInfo &
610 MachineFunction::getOrCreateLandingPadInfo(MachineBasicBlock *LandingPad) {
611 unsigned N = LandingPads.size();
612 for (unsigned i = 0; i < N; ++i) {
613 LandingPadInfo &LP = LandingPads[i];
614 if (LP.LandingPadBlock == LandingPad)
615 return LP;
618 LandingPads.push_back(LandingPadInfo(LandingPad));
619 return LandingPads[N];
622 void MachineFunction::addInvoke(MachineBasicBlock *LandingPad,
623 MCSymbol *BeginLabel, MCSymbol *EndLabel) {
624 LandingPadInfo &LP = getOrCreateLandingPadInfo(LandingPad);
625 LP.BeginLabels.push_back(BeginLabel);
626 LP.EndLabels.push_back(EndLabel);
629 MCSymbol *MachineFunction::addLandingPad(MachineBasicBlock *LandingPad) {
630 MCSymbol *LandingPadLabel = Ctx.createTempSymbol();
631 LandingPadInfo &LP = getOrCreateLandingPadInfo(LandingPad);
632 LP.LandingPadLabel = LandingPadLabel;
634 const Instruction *FirstI = LandingPad->getBasicBlock()->getFirstNonPHI();
635 if (const auto *LPI = dyn_cast<LandingPadInst>(FirstI)) {
636 if (const auto *PF =
637 dyn_cast<Function>(F.getPersonalityFn()->stripPointerCasts()))
638 getMMI().addPersonality(PF);
640 if (LPI->isCleanup())
641 addCleanup(LandingPad);
643 // FIXME: New EH - Add the clauses in reverse order. This isn't 100%
644 // correct, but we need to do it this way because of how the DWARF EH
645 // emitter processes the clauses.
646 for (unsigned I = LPI->getNumClauses(); I != 0; --I) {
647 Value *Val = LPI->getClause(I - 1);
648 if (LPI->isCatch(I - 1)) {
649 addCatchTypeInfo(LandingPad,
650 dyn_cast<GlobalValue>(Val->stripPointerCasts()));
651 } else {
652 // Add filters in a list.
653 auto *CVal = cast<Constant>(Val);
654 SmallVector<const GlobalValue *, 4> FilterList;
655 for (User::op_iterator II = CVal->op_begin(), IE = CVal->op_end();
656 II != IE; ++II)
657 FilterList.push_back(cast<GlobalValue>((*II)->stripPointerCasts()));
659 addFilterTypeInfo(LandingPad, FilterList);
663 } else if (const auto *CPI = dyn_cast<CatchPadInst>(FirstI)) {
664 for (unsigned I = CPI->getNumArgOperands(); I != 0; --I) {
665 Value *TypeInfo = CPI->getArgOperand(I - 1)->stripPointerCasts();
666 addCatchTypeInfo(LandingPad, dyn_cast<GlobalValue>(TypeInfo));
669 } else {
670 assert(isa<CleanupPadInst>(FirstI) && "Invalid landingpad!");
673 return LandingPadLabel;
676 void MachineFunction::addCatchTypeInfo(MachineBasicBlock *LandingPad,
677 ArrayRef<const GlobalValue *> TyInfo) {
678 LandingPadInfo &LP = getOrCreateLandingPadInfo(LandingPad);
679 for (unsigned N = TyInfo.size(); N; --N)
680 LP.TypeIds.push_back(getTypeIDFor(TyInfo[N - 1]));
683 void MachineFunction::addFilterTypeInfo(MachineBasicBlock *LandingPad,
684 ArrayRef<const GlobalValue *> TyInfo) {
685 LandingPadInfo &LP = getOrCreateLandingPadInfo(LandingPad);
686 std::vector<unsigned> IdsInFilter(TyInfo.size());
687 for (unsigned I = 0, E = TyInfo.size(); I != E; ++I)
688 IdsInFilter[I] = getTypeIDFor(TyInfo[I]);
689 LP.TypeIds.push_back(getFilterIDFor(IdsInFilter));
692 void MachineFunction::tidyLandingPads(DenseMap<MCSymbol *, uintptr_t> *LPMap,
693 bool TidyIfNoBeginLabels) {
694 for (unsigned i = 0; i != LandingPads.size(); ) {
695 LandingPadInfo &LandingPad = LandingPads[i];
696 if (LandingPad.LandingPadLabel &&
697 !LandingPad.LandingPadLabel->isDefined() &&
698 (!LPMap || (*LPMap)[LandingPad.LandingPadLabel] == 0))
699 LandingPad.LandingPadLabel = nullptr;
701 // Special case: we *should* emit LPs with null LP MBB. This indicates
702 // "nounwind" case.
703 if (!LandingPad.LandingPadLabel && LandingPad.LandingPadBlock) {
704 LandingPads.erase(LandingPads.begin() + i);
705 continue;
708 if (TidyIfNoBeginLabels) {
709 for (unsigned j = 0, e = LandingPads[i].BeginLabels.size(); j != e; ++j) {
710 MCSymbol *BeginLabel = LandingPad.BeginLabels[j];
711 MCSymbol *EndLabel = LandingPad.EndLabels[j];
712 if ((BeginLabel->isDefined() || (LPMap && (*LPMap)[BeginLabel] != 0)) &&
713 (EndLabel->isDefined() || (LPMap && (*LPMap)[EndLabel] != 0)))
714 continue;
716 LandingPad.BeginLabels.erase(LandingPad.BeginLabels.begin() + j);
717 LandingPad.EndLabels.erase(LandingPad.EndLabels.begin() + j);
718 --j;
719 --e;
722 // Remove landing pads with no try-ranges.
723 if (LandingPads[i].BeginLabels.empty()) {
724 LandingPads.erase(LandingPads.begin() + i);
725 continue;
729 // If there is no landing pad, ensure that the list of typeids is empty.
730 // If the only typeid is a cleanup, this is the same as having no typeids.
731 if (!LandingPad.LandingPadBlock ||
732 (LandingPad.TypeIds.size() == 1 && !LandingPad.TypeIds[0]))
733 LandingPad.TypeIds.clear();
734 ++i;
738 void MachineFunction::addCleanup(MachineBasicBlock *LandingPad) {
739 LandingPadInfo &LP = getOrCreateLandingPadInfo(LandingPad);
740 LP.TypeIds.push_back(0);
743 void MachineFunction::addSEHCatchHandler(MachineBasicBlock *LandingPad,
744 const Function *Filter,
745 const BlockAddress *RecoverBA) {
746 LandingPadInfo &LP = getOrCreateLandingPadInfo(LandingPad);
747 SEHHandler Handler;
748 Handler.FilterOrFinally = Filter;
749 Handler.RecoverBA = RecoverBA;
750 LP.SEHHandlers.push_back(Handler);
753 void MachineFunction::addSEHCleanupHandler(MachineBasicBlock *LandingPad,
754 const Function *Cleanup) {
755 LandingPadInfo &LP = getOrCreateLandingPadInfo(LandingPad);
756 SEHHandler Handler;
757 Handler.FilterOrFinally = Cleanup;
758 Handler.RecoverBA = nullptr;
759 LP.SEHHandlers.push_back(Handler);
762 void MachineFunction::setCallSiteLandingPad(MCSymbol *Sym,
763 ArrayRef<unsigned> Sites) {
764 LPadToCallSiteMap[Sym].append(Sites.begin(), Sites.end());
767 unsigned MachineFunction::getTypeIDFor(const GlobalValue *TI) {
768 for (unsigned i = 0, N = TypeInfos.size(); i != N; ++i)
769 if (TypeInfos[i] == TI) return i + 1;
771 TypeInfos.push_back(TI);
772 return TypeInfos.size();
775 int MachineFunction::getFilterIDFor(std::vector<unsigned> &TyIds) {
776 // If the new filter coincides with the tail of an existing filter, then
777 // re-use the existing filter. Folding filters more than this requires
778 // re-ordering filters and/or their elements - probably not worth it.
779 for (std::vector<unsigned>::iterator I = FilterEnds.begin(),
780 E = FilterEnds.end(); I != E; ++I) {
781 unsigned i = *I, j = TyIds.size();
783 while (i && j)
784 if (FilterIds[--i] != TyIds[--j])
785 goto try_next;
787 if (!j)
788 // The new filter coincides with range [i, end) of the existing filter.
789 return -(1 + i);
791 try_next:;
794 // Add the new filter.
795 int FilterID = -(1 + FilterIds.size());
796 FilterIds.reserve(FilterIds.size() + TyIds.size() + 1);
797 FilterIds.insert(FilterIds.end(), TyIds.begin(), TyIds.end());
798 FilterEnds.push_back(FilterIds.size());
799 FilterIds.push_back(0); // terminator
800 return FilterID;
803 /// \}
805 //===----------------------------------------------------------------------===//
806 // MachineJumpTableInfo implementation
807 //===----------------------------------------------------------------------===//
809 /// Return the size of each entry in the jump table.
810 unsigned MachineJumpTableInfo::getEntrySize(const DataLayout &TD) const {
811 // The size of a jump table entry is 4 bytes unless the entry is just the
812 // address of a block, in which case it is the pointer size.
813 switch (getEntryKind()) {
814 case MachineJumpTableInfo::EK_BlockAddress:
815 return TD.getPointerSize();
816 case MachineJumpTableInfo::EK_GPRel64BlockAddress:
817 return 8;
818 case MachineJumpTableInfo::EK_GPRel32BlockAddress:
819 case MachineJumpTableInfo::EK_LabelDifference32:
820 case MachineJumpTableInfo::EK_Custom32:
821 return 4;
822 case MachineJumpTableInfo::EK_Inline:
823 return 0;
825 llvm_unreachable("Unknown jump table encoding!");
828 /// Return the alignment of each entry in the jump table.
829 unsigned MachineJumpTableInfo::getEntryAlignment(const DataLayout &TD) const {
830 // The alignment of a jump table entry is the alignment of int32 unless the
831 // entry is just the address of a block, in which case it is the pointer
832 // alignment.
833 switch (getEntryKind()) {
834 case MachineJumpTableInfo::EK_BlockAddress:
835 return TD.getPointerABIAlignment(0);
836 case MachineJumpTableInfo::EK_GPRel64BlockAddress:
837 return TD.getABIIntegerTypeAlignment(64);
838 case MachineJumpTableInfo::EK_GPRel32BlockAddress:
839 case MachineJumpTableInfo::EK_LabelDifference32:
840 case MachineJumpTableInfo::EK_Custom32:
841 return TD.getABIIntegerTypeAlignment(32);
842 case MachineJumpTableInfo::EK_Inline:
843 return 1;
845 llvm_unreachable("Unknown jump table encoding!");
848 /// Create a new jump table entry in the jump table info.
849 unsigned MachineJumpTableInfo::createJumpTableIndex(
850 const std::vector<MachineBasicBlock*> &DestBBs) {
851 assert(!DestBBs.empty() && "Cannot create an empty jump table!");
852 JumpTables.push_back(MachineJumpTableEntry(DestBBs));
853 return JumpTables.size()-1;
856 /// If Old is the target of any jump tables, update the jump tables to branch
857 /// to New instead.
858 bool MachineJumpTableInfo::ReplaceMBBInJumpTables(MachineBasicBlock *Old,
859 MachineBasicBlock *New) {
860 assert(Old != New && "Not making a change?");
861 bool MadeChange = false;
862 for (size_t i = 0, e = JumpTables.size(); i != e; ++i)
863 ReplaceMBBInJumpTable(i, Old, New);
864 return MadeChange;
867 /// If Old is a target of the jump tables, update the jump table to branch to
868 /// New instead.
869 bool MachineJumpTableInfo::ReplaceMBBInJumpTable(unsigned Idx,
870 MachineBasicBlock *Old,
871 MachineBasicBlock *New) {
872 assert(Old != New && "Not making a change?");
873 bool MadeChange = false;
874 MachineJumpTableEntry &JTE = JumpTables[Idx];
875 for (size_t j = 0, e = JTE.MBBs.size(); j != e; ++j)
876 if (JTE.MBBs[j] == Old) {
877 JTE.MBBs[j] = New;
878 MadeChange = true;
880 return MadeChange;
883 void MachineJumpTableInfo::print(raw_ostream &OS) const {
884 if (JumpTables.empty()) return;
886 OS << "Jump Tables:\n";
888 for (unsigned i = 0, e = JumpTables.size(); i != e; ++i) {
889 OS << printJumpTableEntryReference(i) << ": ";
890 for (unsigned j = 0, f = JumpTables[i].MBBs.size(); j != f; ++j)
891 OS << ' ' << printMBBReference(*JumpTables[i].MBBs[j]);
894 OS << '\n';
897 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
898 LLVM_DUMP_METHOD void MachineJumpTableInfo::dump() const { print(dbgs()); }
899 #endif
901 Printable llvm::printJumpTableEntryReference(unsigned Idx) {
902 return Printable([Idx](raw_ostream &OS) { OS << "%jump-table." << Idx; });
905 //===----------------------------------------------------------------------===//
906 // MachineConstantPool implementation
907 //===----------------------------------------------------------------------===//
909 void MachineConstantPoolValue::anchor() {}
911 Type *MachineConstantPoolEntry::getType() const {
912 if (isMachineConstantPoolEntry())
913 return Val.MachineCPVal->getType();
914 return Val.ConstVal->getType();
917 bool MachineConstantPoolEntry::needsRelocation() const {
918 if (isMachineConstantPoolEntry())
919 return true;
920 return Val.ConstVal->needsRelocation();
923 SectionKind
924 MachineConstantPoolEntry::getSectionKind(const DataLayout *DL) const {
925 if (needsRelocation())
926 return SectionKind::getReadOnlyWithRel();
927 switch (DL->getTypeAllocSize(getType())) {
928 case 4:
929 return SectionKind::getMergeableConst4();
930 case 8:
931 return SectionKind::getMergeableConst8();
932 case 16:
933 return SectionKind::getMergeableConst16();
934 case 32:
935 return SectionKind::getMergeableConst32();
936 default:
937 return SectionKind::getReadOnly();
941 MachineConstantPool::~MachineConstantPool() {
942 // A constant may be a member of both Constants and MachineCPVsSharingEntries,
943 // so keep track of which we've deleted to avoid double deletions.
944 DenseSet<MachineConstantPoolValue*> Deleted;
945 for (unsigned i = 0, e = Constants.size(); i != e; ++i)
946 if (Constants[i].isMachineConstantPoolEntry()) {
947 Deleted.insert(Constants[i].Val.MachineCPVal);
948 delete Constants[i].Val.MachineCPVal;
950 for (DenseSet<MachineConstantPoolValue*>::iterator I =
951 MachineCPVsSharingEntries.begin(), E = MachineCPVsSharingEntries.end();
952 I != E; ++I) {
953 if (Deleted.count(*I) == 0)
954 delete *I;
958 /// Test whether the given two constants can be allocated the same constant pool
959 /// entry.
960 static bool CanShareConstantPoolEntry(const Constant *A, const Constant *B,
961 const DataLayout &DL) {
962 // Handle the trivial case quickly.
963 if (A == B) return true;
965 // If they have the same type but weren't the same constant, quickly
966 // reject them.
967 if (A->getType() == B->getType()) return false;
969 // We can't handle structs or arrays.
970 if (isa<StructType>(A->getType()) || isa<ArrayType>(A->getType()) ||
971 isa<StructType>(B->getType()) || isa<ArrayType>(B->getType()))
972 return false;
974 // For now, only support constants with the same size.
975 uint64_t StoreSize = DL.getTypeStoreSize(A->getType());
976 if (StoreSize != DL.getTypeStoreSize(B->getType()) || StoreSize > 128)
977 return false;
979 Type *IntTy = IntegerType::get(A->getContext(), StoreSize*8);
981 // Try constant folding a bitcast of both instructions to an integer. If we
982 // get two identical ConstantInt's, then we are good to share them. We use
983 // the constant folding APIs to do this so that we get the benefit of
984 // DataLayout.
985 if (isa<PointerType>(A->getType()))
986 A = ConstantFoldCastOperand(Instruction::PtrToInt,
987 const_cast<Constant *>(A), IntTy, DL);
988 else if (A->getType() != IntTy)
989 A = ConstantFoldCastOperand(Instruction::BitCast, const_cast<Constant *>(A),
990 IntTy, DL);
991 if (isa<PointerType>(B->getType()))
992 B = ConstantFoldCastOperand(Instruction::PtrToInt,
993 const_cast<Constant *>(B), IntTy, DL);
994 else if (B->getType() != IntTy)
995 B = ConstantFoldCastOperand(Instruction::BitCast, const_cast<Constant *>(B),
996 IntTy, DL);
998 return A == B;
1001 /// Create a new entry in the constant pool or return an existing one.
1002 /// User must specify the log2 of the minimum required alignment for the object.
1003 unsigned MachineConstantPool::getConstantPoolIndex(const Constant *C,
1004 unsigned Alignment) {
1005 assert(Alignment && "Alignment must be specified!");
1006 if (Alignment > PoolAlignment) PoolAlignment = Alignment;
1008 // Check to see if we already have this constant.
1010 // FIXME, this could be made much more efficient for large constant pools.
1011 for (unsigned i = 0, e = Constants.size(); i != e; ++i)
1012 if (!Constants[i].isMachineConstantPoolEntry() &&
1013 CanShareConstantPoolEntry(Constants[i].Val.ConstVal, C, DL)) {
1014 if ((unsigned)Constants[i].getAlignment() < Alignment)
1015 Constants[i].Alignment = Alignment;
1016 return i;
1019 Constants.push_back(MachineConstantPoolEntry(C, Alignment));
1020 return Constants.size()-1;
1023 unsigned MachineConstantPool::getConstantPoolIndex(MachineConstantPoolValue *V,
1024 unsigned Alignment) {
1025 assert(Alignment && "Alignment must be specified!");
1026 if (Alignment > PoolAlignment) PoolAlignment = Alignment;
1028 // Check to see if we already have this constant.
1030 // FIXME, this could be made much more efficient for large constant pools.
1031 int Idx = V->getExistingMachineCPValue(this, Alignment);
1032 if (Idx != -1) {
1033 MachineCPVsSharingEntries.insert(V);
1034 return (unsigned)Idx;
1037 Constants.push_back(MachineConstantPoolEntry(V, Alignment));
1038 return Constants.size()-1;
1041 void MachineConstantPool::print(raw_ostream &OS) const {
1042 if (Constants.empty()) return;
1044 OS << "Constant Pool:\n";
1045 for (unsigned i = 0, e = Constants.size(); i != e; ++i) {
1046 OS << " cp#" << i << ": ";
1047 if (Constants[i].isMachineConstantPoolEntry())
1048 Constants[i].Val.MachineCPVal->print(OS);
1049 else
1050 Constants[i].Val.ConstVal->printAsOperand(OS, /*PrintType=*/false);
1051 OS << ", align=" << Constants[i].getAlignment();
1052 OS << "\n";
1056 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1057 LLVM_DUMP_METHOD void MachineConstantPool::dump() const { print(dbgs()); }
1058 #endif