LLVM 24.0.0git
CodeGenCommonISel.cpp
Go to the documentation of this file.
1//===-- CodeGenCommonISel.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// This file defines common utilies that are shared between SelectionDAG and
10// GlobalISel frameworks.
11//
12//===----------------------------------------------------------------------===//
13
22#include "llvm/IR/Instruction.h"
24
25#define DEBUG_TYPE "codegen-common"
26
27using namespace llvm;
28
29/// Add a successor MBB to ParentMBB< creating a new MachineBB for BB if SuccMBB
30/// is 0.
32StackProtectorDescriptor::addSuccessorMBB(
33 const BasicBlock *BB, MachineBasicBlock *ParentMBB, bool IsLikely,
34 MachineBasicBlock *SuccMBB) {
35 // If SuccBB has not been created yet, create it.
36 if (!SuccMBB) {
37 MachineFunction *MF = ParentMBB->getParent();
38 MachineFunction::iterator BBI(ParentMBB);
39 SuccMBB = MF->CreateMachineBasicBlock(BB);
40 MF->insert(++BBI, SuccMBB);
41 }
42 // Add it as a successor of ParentMBB.
43 ParentMBB->addSuccessor(
45 return SuccMBB;
46}
47
48/// Given that the input MI is before a partial terminator sequence TSeq, return
49/// true if M + TSeq also a partial terminator sequence.
50///
51/// A Terminator sequence is a sequence of MachineInstrs which at this point in
52/// lowering copy vregs into physical registers, which are then passed into
53/// terminator instructors so we can satisfy ABI constraints. A partial
54/// terminator sequence is an improper subset of a terminator sequence (i.e. it
55/// may be the whole terminator sequence).
57 // If we do not have a copy or an implicit def, we return true if and only if
58 // MI is a debug value.
59 if (!MI.isCopy() && !MI.isImplicitDef()) {
60 // Sometimes DBG_VALUE MI sneak in between the copies from the vregs to the
61 // physical registers if there is debug info associated with the terminator
62 // of our mbb. We want to include said debug info in our terminator
63 // sequence, so we return true in that case.
64 if (MI.isDebugInstr())
65 return true;
66
67 // For GlobalISel, we may have extension instructions for arguments within
68 // copy sequences. Allow these.
69 switch (MI.getOpcode()) {
70 case TargetOpcode::G_TRUNC:
71 case TargetOpcode::G_ZEXT:
72 case TargetOpcode::G_ANYEXT:
73 case TargetOpcode::G_SEXT:
74 case TargetOpcode::G_MERGE_VALUES:
75 case TargetOpcode::G_UNMERGE_VALUES:
76 case TargetOpcode::G_CONCAT_VECTORS:
77 case TargetOpcode::G_BUILD_VECTOR:
78 case TargetOpcode::G_EXTRACT:
79 return true;
80 default:
81 return false;
82 }
83 }
84
85 // We have left the terminator sequence if we are not doing one of the
86 // following:
87 //
88 // 1. Copying a vreg into a physical register.
89 // 2. Copying a vreg into a vreg.
90 // 3. Defining a register via an implicit def.
91
92 // OPI should always be a register definition...
93 MachineInstr::const_mop_iterator OPI = MI.operands_begin();
94 if (!OPI->isReg() || !OPI->isDef())
95 return false;
96
97 // Defining any register via an implicit def is always ok.
98 if (MI.isImplicitDef())
99 return true;
100
101 // Grab the copy source...
103 ++OPI2;
104 assert(OPI2 != MI.operands_end()
105 && "Should have a copy implying we should have 2 arguments.");
106
107 // Make sure that the copy dest is not a vreg when the copy source is a
108 // physical register.
109 if (!OPI2->isReg() ||
110 (!OPI->getReg().isPhysical() && OPI2->getReg().isPhysical()))
111 return false;
112
113 return true;
114}
115
116/// Find the split point at which to splice the end of BB into its success stack
117/// protector check machine basic block.
118///
119/// On many platforms, due to ABI constraints, terminators, even before register
120/// allocation, use physical registers. This creates an issue for us since
121/// physical registers at this point can not travel across basic
122/// blocks. Luckily, selectiondag always moves physical registers into vregs
123/// when they enter functions and moves them through a sequence of copies back
124/// into the physical registers right before the terminator creating a
125/// ``Terminator Sequence''. This function is searching for the beginning of the
126/// terminator sequence so that we can ensure that we splice off not just the
127/// terminator, but additionally the copies that move the vregs into the
128/// physical registers.
131 const TargetInstrInfo &TII) {
133 if (SplitPoint == BB->begin())
134 return SplitPoint;
135
137 MachineBasicBlock::iterator Previous = SplitPoint;
138 do {
139 --Previous;
140 } while (Previous != Start && Previous->isDebugInstr());
141
142 if (TII.isTailCall(*SplitPoint) &&
143 Previous->getOpcode() == TII.getCallFrameDestroyOpcode()) {
144 // Call frames cannot be nested, so if this frame is describing the tail
145 // call itself, then we must insert before the sequence even starts. For
146 // example:
147 // <split point>
148 // ADJCALLSTACKDOWN ...
149 // <Moves>
150 // ADJCALLSTACKUP ...
151 // TAILJMP somewhere
152 // On the other hand, it could be an unrelated call in which case this tail
153 // call has no register moves of its own and should be the split point. For
154 // example:
155 // ADJCALLSTACKDOWN
156 // CALL something_else
157 // ADJCALLSTACKUP
158 // <split point>
159 // TAILJMP somewhere
160 do {
161 --Previous;
162 if (Previous->isCall())
163 return SplitPoint;
164 } while(Previous->getOpcode() != TII.getCallFrameSetupOpcode());
165
166 return Previous;
167 }
168
169 while (MIIsInTerminatorSequence(*Previous)) {
170 SplitPoint = Previous;
171 if (Previous == Start)
172 break;
173 --Previous;
174 }
175
176 return SplitPoint;
177}
178
180 FPClassTest InvertedTest = ~Test;
181
182 // Pick the direction with fewer tests
183 // TODO: Handle more combinations of cases that can be handled together
184 switch (static_cast<unsigned>(InvertedTest)) {
185 case fcNan:
186 case fcSNan:
187 case fcQNan:
188 case fcInf:
189 case fcPosInf:
190 case fcNegInf:
191 case fcNormal:
192 case fcPosNormal:
193 case fcNegNormal:
194 case fcSubnormal:
195 case fcPosSubnormal:
196 case fcNegSubnormal:
197 case fcZero:
198 case fcPosZero:
199 case fcNegZero:
200 case fcFinite:
201 case fcPosFinite:
202 case fcNegFinite:
203 case fcZero | fcNan:
204 case fcSubnormal | fcZero:
205 case fcSubnormal | fcZero | fcNan:
206 return InvertedTest;
207 case fcInf | fcNan:
208 case fcPosInf | fcNan:
209 case fcNegInf | fcNan:
210 // If we're trying to use fcmp, we can take advantage of the nan check
211 // behavior of the compare (but this is more instructions in the integer
212 // expansion).
213 return UseFCmp ? InvertedTest : fcNone;
214 default:
215 return fcNone;
216 }
217
218 llvm_unreachable("covered FPClassTest");
219}
220
222 MachineInstr &Copy) {
223 assert((Copy.getOpcode() == TargetOpcode::COPY ||
224 Copy.getOpcode() == TargetOpcode::G_BITCAST) &&
225 "Must be a COPY or G_BITCAST");
226
227 return &Copy.getOperand(1);
228}
229
233 assert(Trunc.getOpcode() == TargetOpcode::G_TRUNC && "Must be a G_TRUNC");
234
235 const auto FromLLT = MRI.getType(Trunc.getOperand(1).getReg());
236 const auto ToLLT = MRI.getType(Trunc.defs().begin()->getReg());
237
238 // TODO: Support non-scalar types.
239 if (!FromLLT.isScalar()) {
240 return nullptr;
241 }
242
243 auto ExtOps = DIExpression::getExtOps(FromLLT.getSizeInBits(),
244 ToLLT.getSizeInBits(), false);
245 Ops.append(ExtOps.begin(), ExtOps.end());
246 return &Trunc.getOperand(1);
247}
248
252 switch (MI.getOpcode()) {
253 case TargetOpcode::G_TRUNC:
255 case TargetOpcode::COPY:
256 case TargetOpcode::G_BITCAST:
257 return getSalvageOpsForCopy(MRI, MI);
258 default:
259 return nullptr;
260 }
261}
262
263/// Replace \p DbgMI, which describes the result of \p BuildVector, with one
264/// fragment debug value per vector element.
266 MachineInstr &BuildVector, MachineInstr &DbgMI) {
267 const DIExpression *Expr = DbgMI.getDebugExpression();
268 if (DbgMI.getNumDebugOperands() != 1 || !Expr->isSingleLocationExpression() ||
269 Expr->isComplex())
270 return;
271
272 unsigned VecSize = MRI.getType(BuildVector.getOperand(0).getReg())
273 .getSizeInBits()
274 .getFixedValue();
275 if (auto Fragment = Expr->getFragmentInfo()) {
276 if (VecSize > Fragment->SizeInBits)
277 return;
278 } else if (auto VarSize = DbgMI.getDebugVariable()->getSizeInBits()) {
279 if (VecSize > *VarSize)
280 return;
281 }
282
283 unsigned NumElts = BuildVector.getNumOperands() - 1;
284 unsigned EltSize = VecSize / NumElts;
286 for (unsigned I = 0; I != NumElts; ++I) {
287 auto FragExpr =
288 DIExpression::createFragmentExpression(Expr, I * EltSize, EltSize);
289 if (!FragExpr)
290 return;
291 FragExprs.push_back(*FragExpr);
292 }
293
294 MachineBasicBlock &MBB = *DbgMI.getParent();
295 MachineFunction &MF = *MBB.getParent();
296 for (unsigned I = NumElts - 1; I != 0; --I) {
297 MachineInstr *NewMI = MF.CloneMachineInstr(&DbgMI);
298 NewMI->getDebugOperand(0).setReg(BuildVector.getOperand(I + 1).getReg());
299 NewMI->getDebugExpressionOp().setMetadata(FragExprs[I]);
300 MBB.insertAfter(DbgMI.getIterator(), NewMI);
301 LLVM_DEBUG(dbgs() << "SALVAGE: " << *NewMI << '\n');
302 }
303 DbgMI.getDebugOperand(0).setReg(BuildVector.getOperand(1).getReg());
304 DbgMI.getDebugExpressionOp().setMetadata(FragExprs[0]);
305 LLVM_DEBUG(dbgs() << "SALVAGE: " << DbgMI << '\n');
306}
307
311 // These are arbitrary chosen limits on the maximum number of values and the
312 // maximum size of a debug expression we can salvage up to, used for
313 // performance reasons.
314 const unsigned MaxExpressionSize = 128;
315
317 for (auto *DefMO : DbgUsers) {
318 MachineInstr *DbgMI = DefMO->getParent();
319 // A DBG_VALUE_LIST may use the salvaged register in several location
320 // operands; all of them are rewritten the first time it is seen.
321 if (!Visited.insert(DbgMI).second)
322 continue;
323 if (DbgMI->isIndirectDebugValue()) {
324 continue;
325 }
326
327 Register Reg = DefMO->getReg();
328 assert(DbgMI->hasDebugOperandForReg(Reg) &&
329 "Must use salvaged instruction as its location");
330
331 if (MI.getOpcode() == TargetOpcode::G_BUILD_VECTOR) {
332 assert(DbgMI->isDebugValue() &&
333 "Must be either DBG_VALUE or DBG_VALUE_LIST");
334 salvageBuildVector(MRI, MI, *DbgMI);
335 continue;
336 }
337
338 const DIExpression *SalvagedExpr = DbgMI->getDebugExpression();
339
341 auto Op0 = salvageDebugInfoImpl(MRI, MI, Ops);
342 if (!Op0)
343 continue;
344
347 for (MachineOperand *LocMO : LocMOs)
348 SalvagedExpr = DIExpression::appendOpsToArg(
349 SalvagedExpr, Ops, DbgMI->getDebugOperandIndex(LocMO), true);
350
351 bool IsValidSalvageExpr =
352 SalvagedExpr->getNumElements() <= MaxExpressionSize;
353 if (IsValidSalvageExpr) {
354 for (MachineOperand *LocMO : LocMOs) {
355 LocMO->setReg(Op0->getReg());
356 LocMO->setSubReg(Op0->getSubReg());
357 }
358 DbgMI->getDebugExpressionOp().setMetadata(SalvagedExpr);
359
360 LLVM_DEBUG(dbgs() << "SALVAGE: " << *DbgMI << '\n');
361 }
362 }
363}
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
MachineBasicBlock & MBB
static void salvageBuildVector(const MachineRegisterInfo &MRI, MachineInstr &BuildVector, MachineInstr &DbgMI)
Replace DbgMI, which describes the result of BuildVector, with one fragment debug value per vector el...
static MachineOperand * getSalvageOpsForTrunc(const MachineRegisterInfo &MRI, MachineInstr &Trunc, SmallVectorImpl< uint64_t > &Ops)
static MachineOperand * getSalvageOpsForCopy(const MachineRegisterInfo &MRI, MachineInstr &Copy)
static bool MIIsInTerminatorSequence(const MachineInstr &MI)
Given that the input MI is before a partial terminator sequence TSeq, return true if M + TSeq also a ...
const HexagonInstrInfo * TII
IRTranslator LLVM IR MI
const AbstractManglingParser< Derived, Alloc >::OperatorInfo AbstractManglingParser< Derived, Alloc >::Ops[]
#define I(x, y, z)
Definition MD5.cpp:57
MachineRegisterInfo & MRI
This file defines the SmallPtrSet class.
#define LLVM_DEBUG(...)
Definition Debug.h:119
Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:40
LLVM Basic Block Representation.
Definition BasicBlock.h:62
static BranchProbability getBranchProbStackProtector(bool IsLikely)
DWARF expression.
unsigned getNumElements() const
static LLVM_ABI ExtOps getExtOps(unsigned FromSize, unsigned ToSize, bool Signed)
Returns the ops for a zero- or sign-extension in a DIExpression.
static LLVM_ABI DIExpression * appendOpsToArg(const DIExpression *Expr, ArrayRef< uint64_t > Ops, unsigned ArgNo, bool StackValue=false)
Create a copy of Expr by appending the given list of Ops to each instance of the operand DW_OP_LLVM_a...
LLVM_ABI bool isComplex() const
Return whether the location is computed on the expression stack, meaning it cannot be a simple regist...
static LLVM_ABI std::optional< FragmentInfo > getFragmentInfo(expr_op_iterator Start, expr_op_iterator End)
Retrieve the details of this fragment expression.
static LLVM_ABI std::optional< DIExpression * > createFragmentExpression(const DIExpression *Expr, unsigned OffsetInBits, unsigned SizeInBits)
Create a DIExpression to describe one part of an aggregate variable that is fragmented across multipl...
LLVM_ABI bool isSingleLocationExpression() const
Return whether the evaluated expression makes use of a single location at the start of the expression...
LLVM_ABI std::optional< uint64_t > getSizeInBits() const
Determines the size of the variable's type.
LLVM_ABI iterator getFirstTerminator()
Returns an iterator to the first terminator instruction of this basic block.
LLVM_ABI void addSuccessor(MachineBasicBlock *Succ, BranchProbability Prob=BranchProbability::getUnknown())
Add Succ as a successor of this MachineBasicBlock.
const MachineFunction * getParent() const
Return the MachineFunction containing this basic block.
MachineInstrBundleIterator< MachineInstr > iterator
BasicBlockListType::iterator iterator
MachineBasicBlock * CreateMachineBasicBlock(const BasicBlock *BB=nullptr, std::optional< UniqueBBID > BBID=std::nullopt)
CreateMachineInstr - Allocate a new MachineInstr.
void insert(iterator MBBI, MachineBasicBlock *MBB)
Representation of each machine instruction.
bool hasDebugOperandForReg(Register Reg) const
Returns whether this debug value has at least one debug operand with the register Reg.
LLVM_ABI iterator_range< filter_iterator< const MachineOperand *, std::function< bool(const MachineOperand &Op)> > > getDebugOperandsForReg(Register Reg) const
Returns a range of all of the operands that correspond to a debug use of Reg.
const MachineBasicBlock * getParent() const
LLVM_ABI const MachineOperand & getDebugExpressionOp() const
Return the operand for the complex address expression referenced by this DBG_VALUE instruction.
unsigned getNumDebugOperands() const
Returns the total number of operands which are debug locations.
unsigned getNumOperands() const
Retuns the total number of operands.
const MachineOperand * const_mop_iterator
LLVM_ABI const DILocalVariable * getDebugVariable() const
Return the debug variable referenced by this DBG_VALUE instruction.
LLVM_ABI const DIExpression * getDebugExpression() const
Return the complex address expression referenced by this DBG_VALUE instruction.
bool isDebugValue() const
unsigned getDebugOperandIndex(const MachineOperand *Op) const
MachineOperand & getDebugOperand(unsigned Index)
const MachineOperand & getOperand(unsigned i) const
bool isIndirectDebugValue() const
A DBG_VALUE is indirect iff the location operand is a register and the offset operand is an immediate...
MachineOperand class - Representation of each machine instruction operand.
bool isReg() const
isReg - Tests if this is a MO_Register operand.
LLVM_ABI void setReg(Register Reg)
Change the register this operand corresponds to.
void setMetadata(const MDNode *MD)
Register getReg() const
getReg - Returns the register number.
MachineRegisterInfo - Keep track of information for virtual and physical registers,...
Wrapper class representing virtual and physical registers.
Definition Register.h:20
constexpr bool isPhysical() const
Return true if the specified register number is in the physical register namespace.
Definition Register.h:83
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements.
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
void push_back(const T &Elt)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
TargetInstrInfo - Interface to description of machine instruction set.
self_iterator getIterator()
Definition ilist_node.h:123
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
This is an optimization pass for GlobalISel generic memory operations.
LLVM_ABI FPClassTest invertFPClassTestIfSimpler(FPClassTest Test, bool UseFCmp)
Evaluates if the specified FP class test is better performed as the inverse (i.e.
LLVM_ABI MachineBasicBlock::iterator findSplitPointForStackProtector(MachineBasicBlock *BB, const TargetInstrInfo &TII)
Find the split point at which to splice the end of BB into its success stack protector check machine ...
FPClassTest
Floating-point class tests, supported by 'is_fpclass' intrinsic.
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition Debug.cpp:209
LLVM_ABI Value * salvageDebugInfoImpl(Instruction &I, uint64_t CurrentLocOps, SmallVectorImpl< uint64_t > &Ops, SmallVectorImpl< Value * > &AdditionalValues)
Definition Local.cpp:2353
iterator_range< pointer_iterator< WrappedIteratorT > > make_pointer_range(RangeT &&Range)
Definition iterator.h:368
LLVM_ABI void salvageDebugInfoForDbgValue(const MachineRegisterInfo &MRI, MachineInstr &MI, ArrayRef< MachineOperand * > DbgUsers)
Assuming the instruction MI is going to be deleted, attempt to salvage debug users of MI by writing t...