LLVM 24.0.0git
BPFAdjustOpt.cpp
Go to the documentation of this file.
1//===---------------- BPFAdjustOpt.cpp - Adjust Optimization --------------===//
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// Adjust optimization to make the code more kernel verifier friendly.
10//
11//===----------------------------------------------------------------------===//
12
13#include "BPF.h"
14#include "BPFCORE.h"
15#include "llvm/IR/Instruction.h"
17#include "llvm/IR/IntrinsicsBPF.h"
18#include "llvm/IR/Module.h"
20#include "llvm/IR/Type.h"
21#include "llvm/IR/User.h"
22#include "llvm/IR/Value.h"
23#include "llvm/Pass.h"
25
26#define DEBUG_TYPE "bpf-adjust-opt"
27
28using namespace llvm;
29using namespace llvm::PatternMatch;
30
31static cl::opt<bool>
32 DisableBPFserializeICMP("bpf-disable-serialize-icmp", cl::Hidden,
33 cl::desc("BPF: Disable Serializing ICMP insns."),
34 cl::init(false));
35
37 "bpf-disable-avoid-speculation", cl::Hidden,
38 cl::desc("BPF: Disable Avoiding Speculative Code Motion."),
39 cl::init(false));
40
41namespace {
42class BPFAdjustOptImpl {
43 struct PassThroughInfo {
45 Instruction *UsedInst;
46 uint32_t OpIdx;
47 PassThroughInfo(Instruction *I, Instruction *U, uint32_t Idx)
48 : Input(I), UsedInst(U), OpIdx(Idx) {}
49 };
50
51public:
52 BPFAdjustOptImpl(Module *M) : M(M) {}
53
54 bool run();
55
56private:
57 Module *M;
59
60 bool adjustICmpToBuiltin();
61 void adjustBasicBlock(BasicBlock &BB);
62 bool serializeICMPCrossBB(BasicBlock &BB);
63 void adjustInst(Instruction &I);
64 bool serializeICMPInBB(Instruction &I);
65 bool avoidSpeculation(Instruction &I);
66 bool insertPassThrough();
67};
68
69} // End anonymous namespace
70
71bool BPFAdjustOptImpl::run() {
72 bool Changed = adjustICmpToBuiltin();
73
74 // The verifier checks a global function on its own against its BTF type,
75 // and freplace can replace it. The callers know the prototype and no more.
76 for (Function &F : *M) {
77 if (F.isDeclaration() || F.hasLocalLinkage())
78 continue;
79 F.addFnAttr(Attribute::NoIPA);
80 Changed = true;
81 }
82
83 for (Function &F : *M)
84 for (auto &BB : F) {
85 adjustBasicBlock(BB);
86 for (auto &I : BB)
87 adjustInst(I);
88 }
89 return insertPassThrough() || Changed;
90}
91
92// Commit acabad9ff6bf ("[InstCombine] try to canonicalize icmp with
93// trunc op into mask and cmp") added a transformation to
94// convert "(conv)a < power_2_const" to "a & <const>" in certain
95// cases and bpf kernel verifier has to handle the resulted code
96// conservatively and this may reject otherwise legitimate program.
97// Here, we change related icmp code to a builtin which will
98// be restored to original icmp code later to prevent that
99// InstCombine transformatin.
100bool BPFAdjustOptImpl::adjustICmpToBuiltin() {
101 bool Changed = false;
102 ICmpInst *ToBeDeleted = nullptr;
103 for (Function &F : *M)
104 for (auto &BB : F)
105 for (auto &I : BB) {
106 if (ToBeDeleted) {
107 ToBeDeleted->eraseFromParent();
108 ToBeDeleted = nullptr;
109 }
110
111 auto *Icmp = dyn_cast<ICmpInst>(&I);
112 if (!Icmp)
113 continue;
114
115 Value *Op0 = Icmp->getOperand(0);
116 if (!isa<TruncInst>(Op0))
117 continue;
118
119 auto ConstOp1 = dyn_cast<ConstantInt>(Icmp->getOperand(1));
120 if (!ConstOp1)
121 continue;
122
123 auto ConstOp1Val = ConstOp1->getValue().getZExtValue();
124 auto Op = Icmp->getPredicate();
125 if (Op == ICmpInst::ICMP_ULT || Op == ICmpInst::ICMP_UGE) {
126 if ((ConstOp1Val - 1) & ConstOp1Val)
127 continue;
128 } else if (Op == ICmpInst::ICMP_ULE || Op == ICmpInst::ICMP_UGT) {
129 if (ConstOp1Val & (ConstOp1Val + 1))
130 continue;
131 } else {
132 continue;
133 }
134
135 Constant *Opcode =
136 ConstantInt::get(Type::getInt32Ty(BB.getContext()), Op);
138 M, Intrinsic::bpf_compare, {Op0->getType(), ConstOp1->getType()});
139 auto *NewInst = CallInst::Create(Fn, {Opcode, Op0, ConstOp1});
140 NewInst->insertBefore(I.getIterator());
141 Icmp->replaceAllUsesWith(NewInst);
142 Changed = true;
143 ToBeDeleted = Icmp;
144 }
145
146 return Changed;
147}
148
149bool BPFAdjustOptImpl::insertPassThrough() {
150 for (auto &Info : PassThroughs) {
152 M, Info.UsedInst->getParent(), Info.Input, Info.UsedInst);
153 Info.UsedInst->setOperand(Info.OpIdx, CI);
154 }
155
156 return !PassThroughs.empty();
157}
158
159// To avoid combining conditionals in the same basic block by
160// instrcombine optimization.
161bool BPFAdjustOptImpl::serializeICMPInBB(Instruction &I) {
162 // For:
163 // comp1 = icmp <opcode> ...;
164 // comp2 = icmp <opcode> ...;
165 // ... or comp1 comp2 ...
166 // changed to:
167 // comp1 = icmp <opcode> ...;
168 // comp2 = icmp <opcode> ...;
169 // new_comp1 = __builtin_bpf_passthrough(seq_num, comp1)
170 // ... or new_comp1 comp2 ...
171 Value *Op0, *Op1;
172 // Use LogicalOr (accept `or i1` as well as `select i1 Op0, true, Op1`)
173 if (!match(&I, m_LogicalOr(m_Value(Op0), m_Value(Op1))))
174 return false;
175 auto *Icmp1 = dyn_cast<ICmpInst>(Op0);
176 if (!Icmp1)
177 return false;
178 auto *Icmp2 = dyn_cast<ICmpInst>(Op1);
179 if (!Icmp2)
180 return false;
181
182 Value *Icmp1Op0 = Icmp1->getOperand(0);
183 Value *Icmp2Op0 = Icmp2->getOperand(0);
184 if (Icmp1Op0 != Icmp2Op0)
185 return false;
186
187 // Now we got two icmp instructions which feed into
188 // an "or" instruction.
189 PassThroughInfo Info(Icmp1, &I, 0);
190 PassThroughs.push_back(Info);
191 return true;
192}
193
194// To avoid combining conditionals in the same basic block by
195// instrcombine optimization.
196bool BPFAdjustOptImpl::serializeICMPCrossBB(BasicBlock &BB) {
197 // For:
198 // B1:
199 // comp1 = icmp <opcode> ...;
200 // if (comp1) goto B2 else B3;
201 // B2:
202 // comp2 = icmp <opcode> ...;
203 // if (comp2) goto B4 else B5;
204 // B4:
205 // ...
206 // changed to:
207 // B1:
208 // comp1 = icmp <opcode> ...;
209 // comp1 = __builtin_bpf_passthrough(seq_num, comp1);
210 // if (comp1) goto B2 else B3;
211 // B2:
212 // comp2 = icmp <opcode> ...;
213 // comp2 = __builtin_bpf_passthrough(seq_num, comp2);
214 // if (comp2) goto B4 else B5;
215 // B4:
216 // ...
217
218 // Check basic blocks, if two of them (say B1, B2) are using
219 // icmp instructions to generate conditions and one is the predecessor
220 // of another (e.g., B1 is the predecessor of B2). Add passthrough
221 // barriers after the icmp insts of blocks B1 and B2.
222 BasicBlock *B2 = &BB;
223 BasicBlock *B1 = B2->getSinglePredecessor();
224 if (!B1)
225 return false;
226
227 Instruction *TI2 = B2->getTerminator();
228 auto *BI2 = dyn_cast<CondBrInst>(TI2);
229 if (!BI2)
230 return false;
231 auto *Cond2 = dyn_cast<ICmpInst>(BI2->getCondition());
232 if (!Cond2 || &*B2->getFirstNonPHIIt() != Cond2)
233 return false;
234 Value *B2Op0 = Cond2->getOperand(0);
235 auto Cond2Op = Cond2->getPredicate();
236
237 Instruction *TI1 = B1->getTerminator();
238 auto *BI1 = dyn_cast<CondBrInst>(TI1);
239 if (!BI1)
240 return false;
241 auto *Cond1 = dyn_cast<ICmpInst>(BI1->getCondition());
242 if (!Cond1)
243 return false;
244 Value *B1Op0 = Cond1->getOperand(0);
245 auto Cond1Op = Cond1->getPredicate();
246
247 if (B1Op0 != B2Op0)
248 return false;
249
250 if (Cond1Op == ICmpInst::ICMP_SGT || Cond1Op == ICmpInst::ICMP_SGE) {
251 if (Cond2Op != ICmpInst::ICMP_SLT && Cond2Op != ICmpInst::ICMP_SLE)
252 return false;
253 } else if (Cond1Op == ICmpInst::ICMP_SLT || Cond1Op == ICmpInst::ICMP_SLE) {
254 if (Cond2Op != ICmpInst::ICMP_SGT && Cond2Op != ICmpInst::ICMP_SGE)
255 return false;
256 } else if (Cond1Op == ICmpInst::ICMP_ULT || Cond1Op == ICmpInst::ICMP_ULE) {
257 if (Cond2Op != ICmpInst::ICMP_UGT && Cond2Op != ICmpInst::ICMP_UGE)
258 return false;
259 } else if (Cond1Op == ICmpInst::ICMP_UGT || Cond1Op == ICmpInst::ICMP_UGE) {
260 if (Cond2Op != ICmpInst::ICMP_ULT && Cond2Op != ICmpInst::ICMP_ULE)
261 return false;
262 } else {
263 return false;
264 }
265
266 PassThroughs.emplace_back(Cond1, BI1, 0);
267 PassThroughs.emplace_back(Cond2, BI2, 0);
268
269 return true;
270}
271
272// To avoid speculative hoisting certain computations out of
273// a basic block.
274bool BPFAdjustOptImpl::avoidSpeculation(Instruction &I) {
275 if (auto *LdInst = dyn_cast<LoadInst>(&I)) {
276 if (auto *GV = dyn_cast<GlobalVariable>(LdInst->getOperand(0))) {
277 if (GV->hasAttribute(BPFCoreSharedInfo::AmaAttr) ||
278 GV->hasAttribute(BPFCoreSharedInfo::TypeIdAttr))
279 return false;
280 }
281 }
282
283 if (!isa<LoadInst>(&I) && !isa<CallInst>(&I))
284 return false;
285
286 // For:
287 // B1:
288 // var = ...
289 // ...
290 // /* icmp may not be in the same block as var = ... */
291 // comp1 = icmp <opcode> var, <const>;
292 // if (comp1) goto B2 else B3;
293 // B2:
294 // ... var ...
295 // change to:
296 // B1:
297 // var = ...
298 // ...
299 // /* icmp may not be in the same block as var = ... */
300 // comp1 = icmp <opcode> var, <const>;
301 // if (comp1) goto B2 else B3;
302 // B2:
303 // var = __builtin_bpf_passthrough(seq_num, var);
304 // ... var ...
305 bool isCandidate = false;
307 for (User *U : I.users()) {
309 if (!Inst)
310 continue;
311
312 // May cover a little bit more than the
313 // above pattern.
314 if (auto *Icmp1 = dyn_cast<ICmpInst>(Inst)) {
315 Value *Icmp1Op1 = Icmp1->getOperand(1);
316 if (!isa<Constant>(Icmp1Op1))
317 return false;
318 isCandidate = true;
319 continue;
320 }
321
322 // Ignore the use in the same basic block as the definition.
323 if (Inst->getParent() == I.getParent())
324 continue;
325
326 // use in a different basic block, If there is a call or
327 // load/store insn before this instruction in this basic
328 // block. Most likely it cannot be hoisted out. Skip it.
329 for (auto &I2 : *Inst->getParent()) {
330 if (isa<CallInst>(&I2))
331 return false;
332 if (isa<LoadInst>(&I2) || isa<StoreInst>(&I2))
333 return false;
334 if (&I2 == Inst)
335 break;
336 }
337
338 // It should be used in a GEP or a simple arithmetic like
339 // ZEXT/SEXT which is used for GEP.
340 if (Inst->getOpcode() == Instruction::ZExt ||
341 Inst->getOpcode() == Instruction::SExt) {
342 PassThroughInfo Info(&I, Inst, 0);
343 Candidates.push_back(Info);
344 } else if (auto *GI = dyn_cast<GetElementPtrInst>(Inst)) {
345 // traverse GEP inst to find Use operand index
346 unsigned i, e;
347 for (i = 1, e = GI->getNumOperands(); i != e; ++i) {
348 Value *V = GI->getOperand(i);
349 if (V == &I)
350 break;
351 }
352 if (i == e)
353 continue;
354
355 PassThroughInfo Info(&I, GI, i);
356 Candidates.push_back(Info);
357 }
358 }
359
360 if (!isCandidate || Candidates.empty())
361 return false;
362
363 llvm::append_range(PassThroughs, Candidates);
364 return true;
365}
366
367void BPFAdjustOptImpl::adjustBasicBlock(BasicBlock &BB) {
368 if (!DisableBPFserializeICMP && serializeICMPCrossBB(BB))
369 return;
370}
371
372void BPFAdjustOptImpl::adjustInst(Instruction &I) {
373 if (!DisableBPFserializeICMP && serializeICMPInBB(I))
374 return;
375 if (!DisableBPFavoidSpeculation && avoidSpeculation(I))
376 return;
377}
378
static cl::opt< bool > DisableBPFserializeICMP("bpf-disable-serialize-icmp", cl::Hidden, cl::desc("BPF: Disable Serializing ICMP insns."), cl::init(false))
static cl::opt< bool > DisableBPFavoidSpeculation("bpf-disable-avoid-speculation", cl::Hidden, cl::desc("BPF: Disable Avoiding Speculative Code Motion."), cl::init(false))
Module.h This file contains the declarations for the Module class.
#define F(x, y, z)
Definition MD5.cpp:54
#define I(x, y, z)
Definition MD5.cpp:57
static bool isCandidate(const MachineInstr *MI, Register &DefedReg, Register FrameReg)
The Input class is used to parse a yaml document into in-memory structs and vectors.
PreservedAnalyses run(Module &M, ModuleAnalysisManager &AM)
static constexpr StringRef TypeIdAttr
The attribute attached to globals representing a type id.
Definition BPFCORE.h:64
static Instruction * insertPassThrough(Module *M, BasicBlock *BB, Instruction *Input, Instruction *Before)
Insert a bpf passthrough builtin function.
static constexpr StringRef AmaAttr
The attribute attached to globals representing a field access.
Definition BPFCORE.h:62
static CallInst * Create(FunctionType *Ty, Value *F, const Twine &NameStr="", InsertPosition InsertBefore=nullptr)
LLVM_ABI void insertBefore(InstListType::iterator InsertPos)
Insert an unlinked instruction into a basic block immediately before the specified position.
LLVM_ABI InstListType::iterator eraseFromParent()
This method unlinks 'this' from the containing basic block and deletes it.
unsigned getOpcode() const
Returns a member of one of the enums like Instruction::Add.
A Module instance is used to store all the information related to an LLVM module.
Definition Module.h:68
A set of analyses that are preserved following a run of a transformation pass.
Definition Analysis.h:112
static PreservedAnalyses none()
Convenience factory function for the empty preserved set.
Definition Analysis.h:115
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
Definition Analysis.h:118
void push_back(const T &Elt)
Type * getType() const
All values are typed, get the type of this value.
Definition Value.h:257
const ParentTy * getParent() const
Definition ilist_node.h:34
@ BasicBlock
Various leaf nodes.
Definition ISDOpcodes.h:83
LLVM_ABI Function * getOrInsertDeclaration(Module *M, ID id, ArrayRef< Type * > OverloadTys={})
Look up the Function declaration of the intrinsic id in the Module M.
bool match(Val *V, const Pattern &P)
auto m_Value()
Match an arbitrary value and ignore it.
auto m_LogicalOr()
Matches L || R where L and R are arbitrary values.
initializer< Ty > init(const Ty &Val)
PointerTypeMap run(const Module &M)
Compute the PointerTypeMap for the module M.
constexpr double e
friend class Instruction
Iterator for Instructions in a `BasicBlock.
Definition BasicBlock.h:73
This is an optimization pass for GlobalISel generic memory operations.
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:643
void append_range(Container &C, Range &&R)
Wrapper function to append range R to container C.
Definition STLExtras.h:2224
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Value
Definition InstrProf.h:143
class LLVM_GSL_OWNER SmallVector
Forward declaration of SmallVector so that calculateSmallVectorDefaultInlinedElements can reference s...
bool isa(const From &Val)
isa<X> - Return true if the parameter to the template is an instance of one of the template type argu...
Definition Casting.h:547
DWARFExpression::Operation Op
AnalysisManager< Module > ModuleAnalysisManager
Convenience typedef for the Module analysis manager.
Definition MIRParser.h:39