1 //===-- PHIEliminationUtils.cpp - Helper functions for PHI elimination ----===//
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
7 //===----------------------------------------------------------------------===//
9 #include "PHIEliminationUtils.h"
10 #include "llvm/ADT/SmallPtrSet.h"
11 #include "llvm/CodeGen/MachineFunction.h"
12 #include "llvm/CodeGen/MachineRegisterInfo.h"
16 // findCopyInsertPoint - Find a safe place in MBB to insert a copy from SrcReg
17 // when following the CFG edge to SuccMBB. This needs to be after any def of
18 // SrcReg, but before any subsequent point where control flow might jump out of
20 MachineBasicBlock::iterator
21 llvm::findPHICopyInsertPoint(MachineBasicBlock
* MBB
, MachineBasicBlock
* SuccMBB
,
23 // Handle the trivial case trivially.
27 // Usually, we just want to insert the copy before the first terminator
28 // instruction. However, for the edge going to a landing pad, we must insert
29 // the copy before the call/invoke instruction. Similarly for an INLINEASM_BR
30 // going to an indirect target. This is similar to SplitKit.cpp's
31 // computeLastInsertPoint, and similarly assumes that there cannot be multiple
32 // instructions that are Calls with EHPad successors or INLINEASM_BR in a
34 bool EHPadSuccessor
= SuccMBB
->isEHPad();
35 if (!EHPadSuccessor
&& !SuccMBB
->isInlineAsmBrIndirectTarget())
36 return MBB
->getFirstTerminator();
38 // Discover any defs in this basic block.
39 SmallPtrSet
<MachineInstr
*, 8> DefsInMBB
;
40 MachineRegisterInfo
& MRI
= MBB
->getParent()->getRegInfo();
41 for (MachineInstr
&RI
: MRI
.def_instructions(SrcReg
))
42 if (RI
.getParent() == MBB
)
43 DefsInMBB
.insert(&RI
);
45 MachineBasicBlock::iterator InsertPoint
= MBB
->begin();
46 // Insert the copy at the _latest_ point of:
47 // 1. Immediately AFTER the last def
48 // 2. Immediately BEFORE a call/inlineasm_br.
49 for (auto I
= MBB
->rbegin(), E
= MBB
->rend(); I
!= E
; ++I
) {
50 if (DefsInMBB
.contains(&*I
)) {
51 InsertPoint
= std::next(I
.getReverse());
54 if ((EHPadSuccessor
&& I
->isCall()) ||
55 I
->getOpcode() == TargetOpcode::INLINEASM_BR
) {
56 InsertPoint
= I
.getReverse();
61 // Make sure the copy goes after any phi nodes but before
63 return MBB
->SkipPHIsAndLabels(InsertPoint
);