Bug Summary

File:llvm/lib/Target/BPF/BPFISelDAGToDAG.cpp
Warning:line 302, column 9
Assigned value is garbage or undefined

Annotated Source Code

Press '?' to see keyboard shortcuts

clang -cc1 -triple x86_64-pc-linux-gnu -analyze -disable-free -disable-llvm-verifier -discard-value-names -main-file-name BPFISelDAGToDAG.cpp -analyzer-store=region -analyzer-opt-analyze-nested-blocks -analyzer-checker=core -analyzer-checker=apiModeling -analyzer-checker=unix -analyzer-checker=deadcode -analyzer-checker=cplusplus -analyzer-checker=security.insecureAPI.UncheckedReturn -analyzer-checker=security.insecureAPI.getpw -analyzer-checker=security.insecureAPI.gets -analyzer-checker=security.insecureAPI.mktemp -analyzer-checker=security.insecureAPI.mkstemp -analyzer-checker=security.insecureAPI.vfork -analyzer-checker=nullability.NullPassedToNonnull -analyzer-checker=nullability.NullReturnedFromNonnull -analyzer-output plist -w -setup-static-analyzer -analyzer-config-compatibility-mode=true -mrelocation-model pic -pic-level 2 -mthread-model posix -mframe-pointer=none -fmath-errno -fno-rounding-math -masm-verbose -mconstructor-aliases -munwind-tables -target-cpu x86-64 -dwarf-column-info -fno-split-dwarf-inlining -debugger-tuning=gdb -ffunction-sections -fdata-sections -resource-dir /usr/lib/llvm-10/lib/clang/10.0.0 -D _DEBUG -D _GNU_SOURCE -D __STDC_CONSTANT_MACROS -D __STDC_FORMAT_MACROS -D __STDC_LIMIT_MACROS -I /build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/build-llvm/lib/Target/BPF -I /build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/llvm/lib/Target/BPF -I /build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/build-llvm/include -I /build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/llvm/include -U NDEBUG -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/c++/6.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/x86_64-linux-gnu/c++/6.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/x86_64-linux-gnu/c++/6.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/c++/6.3.0/backward -internal-isystem /usr/local/include -internal-isystem /usr/lib/llvm-10/lib/clang/10.0.0/include -internal-externc-isystem /usr/include/x86_64-linux-gnu -internal-externc-isystem /include -internal-externc-isystem /usr/include -O2 -Wno-unused-parameter -Wwrite-strings -Wno-missing-field-initializers -Wno-long-long -Wno-maybe-uninitialized -Wno-comment -std=c++14 -fdeprecated-macro -fdebug-compilation-dir /build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/build-llvm/lib/Target/BPF -fdebug-prefix-map=/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd=. -ferror-limit 19 -fmessage-length 0 -fvisibility-inlines-hidden -stack-protector 2 -fgnuc-version=4.2.1 -fobjc-runtime=gcc -fdiagnostics-show-option -vectorize-loops -vectorize-slp -analyzer-output=html -analyzer-config stable-report-filename=true -faddrsig -o /tmp/scan-build-2020-01-13-084841-49055-1 -x c++ /build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/llvm/lib/Target/BPF/BPFISelDAGToDAG.cpp

/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/llvm/lib/Target/BPF/BPFISelDAGToDAG.cpp

1//===-- BPFISelDAGToDAG.cpp - A dag to dag inst selector for BPF ----------===//
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 a DAG pattern matching instruction selector for BPF,
10// converting from a legalized dag to a BPF dag.
11//
12//===----------------------------------------------------------------------===//
13
14#include "BPF.h"
15#include "BPFRegisterInfo.h"
16#include "BPFSubtarget.h"
17#include "BPFTargetMachine.h"
18#include "llvm/CodeGen/FunctionLoweringInfo.h"
19#include "llvm/CodeGen/MachineConstantPool.h"
20#include "llvm/CodeGen/MachineFrameInfo.h"
21#include "llvm/CodeGen/MachineFunction.h"
22#include "llvm/CodeGen/MachineInstrBuilder.h"
23#include "llvm/CodeGen/MachineRegisterInfo.h"
24#include "llvm/CodeGen/SelectionDAGISel.h"
25#include "llvm/IR/Constants.h"
26#include "llvm/IR/IntrinsicInst.h"
27#include "llvm/IR/IntrinsicsBPF.h"
28#include "llvm/Support/Debug.h"
29#include "llvm/Support/Endian.h"
30#include "llvm/Support/ErrorHandling.h"
31#include "llvm/Support/raw_ostream.h"
32#include "llvm/Target/TargetMachine.h"
33
34using namespace llvm;
35
36#define DEBUG_TYPE"bpf-isel" "bpf-isel"
37
38// Instruction Selector Implementation
39namespace {
40
41class BPFDAGToDAGISel : public SelectionDAGISel {
42
43 /// Subtarget - Keep a pointer to the BPFSubtarget around so that we can
44 /// make the right decision when generating code for different subtargets.
45 const BPFSubtarget *Subtarget;
46
47public:
48 explicit BPFDAGToDAGISel(BPFTargetMachine &TM)
49 : SelectionDAGISel(TM), Subtarget(nullptr) {}
50
51 StringRef getPassName() const override {
52 return "BPF DAG->DAG Pattern Instruction Selection";
53 }
54
55 bool runOnMachineFunction(MachineFunction &MF) override {
56 // Reset the subtarget each time through.
57 Subtarget = &MF.getSubtarget<BPFSubtarget>();
58 return SelectionDAGISel::runOnMachineFunction(MF);
59 }
60
61 void PreprocessISelDAG() override;
62
63 bool SelectInlineAsmMemoryOperand(const SDValue &Op, unsigned ConstraintCode,
64 std::vector<SDValue> &OutOps) override;
65
66
67private:
68// Include the pieces autogenerated from the target description.
69#include "BPFGenDAGISel.inc"
70
71 void Select(SDNode *N) override;
72
73 // Complex Pattern for address selection.
74 bool SelectAddr(SDValue Addr, SDValue &Base, SDValue &Offset);
75 bool SelectFIAddr(SDValue Addr, SDValue &Base, SDValue &Offset);
76
77 // Node preprocessing cases
78 void PreprocessLoad(SDNode *Node, SelectionDAG::allnodes_iterator &I);
79 void PreprocessCopyToReg(SDNode *Node);
80 void PreprocessTrunc(SDNode *Node, SelectionDAG::allnodes_iterator &I);
81
82 // Find constants from a constant structure
83 typedef std::vector<unsigned char> val_vec_type;
84 bool fillGenericConstant(const DataLayout &DL, const Constant *CV,
85 val_vec_type &Vals, uint64_t Offset);
86 bool fillConstantDataArray(const DataLayout &DL, const ConstantDataArray *CDA,
87 val_vec_type &Vals, int Offset);
88 bool fillConstantArray(const DataLayout &DL, const ConstantArray *CA,
89 val_vec_type &Vals, int Offset);
90 bool fillConstantStruct(const DataLayout &DL, const ConstantStruct *CS,
91 val_vec_type &Vals, int Offset);
92 bool getConstantFieldValue(const GlobalAddressSDNode *Node, uint64_t Offset,
93 uint64_t Size, unsigned char *ByteSeq);
94 // Mapping from ConstantStruct global value to corresponding byte-list values
95 std::map<const void *, val_vec_type> cs_vals_;
96};
97} // namespace
98
99// ComplexPattern used on BPF Load/Store instructions
100bool BPFDAGToDAGISel::SelectAddr(SDValue Addr, SDValue &Base, SDValue &Offset) {
101 // if Address is FI, get the TargetFrameIndex.
102 SDLoc DL(Addr);
103 if (FrameIndexSDNode *FIN = dyn_cast<FrameIndexSDNode>(Addr)) {
104 Base = CurDAG->getTargetFrameIndex(FIN->getIndex(), MVT::i64);
105 Offset = CurDAG->getTargetConstant(0, DL, MVT::i64);
106 return true;
107 }
108
109 if (Addr.getOpcode() == ISD::TargetExternalSymbol ||
110 Addr.getOpcode() == ISD::TargetGlobalAddress)
111 return false;
112
113 // Addresses of the form Addr+const or Addr|const
114 if (CurDAG->isBaseWithConstantOffset(Addr)) {
115 ConstantSDNode *CN = dyn_cast<ConstantSDNode>(Addr.getOperand(1));
116 if (isInt<16>(CN->getSExtValue())) {
117
118 // If the first operand is a FI, get the TargetFI Node
119 if (FrameIndexSDNode *FIN =
120 dyn_cast<FrameIndexSDNode>(Addr.getOperand(0)))
121 Base = CurDAG->getTargetFrameIndex(FIN->getIndex(), MVT::i64);
122 else
123 Base = Addr.getOperand(0);
124
125 Offset = CurDAG->getTargetConstant(CN->getSExtValue(), DL, MVT::i64);
126 return true;
127 }
128 }
129
130 Base = Addr;
131 Offset = CurDAG->getTargetConstant(0, DL, MVT::i64);
132 return true;
133}
134
135// ComplexPattern used on BPF FI instruction
136bool BPFDAGToDAGISel::SelectFIAddr(SDValue Addr, SDValue &Base,
137 SDValue &Offset) {
138 SDLoc DL(Addr);
139
140 if (!CurDAG->isBaseWithConstantOffset(Addr))
141 return false;
142
143 // Addresses of the form Addr+const or Addr|const
144 ConstantSDNode *CN = dyn_cast<ConstantSDNode>(Addr.getOperand(1));
145 if (isInt<16>(CN->getSExtValue())) {
146
147 // If the first operand is a FI, get the TargetFI Node
148 if (FrameIndexSDNode *FIN = dyn_cast<FrameIndexSDNode>(Addr.getOperand(0)))
149 Base = CurDAG->getTargetFrameIndex(FIN->getIndex(), MVT::i64);
150 else
151 return false;
152
153 Offset = CurDAG->getTargetConstant(CN->getSExtValue(), DL, MVT::i64);
154 return true;
155 }
156
157 return false;
158}
159
160bool BPFDAGToDAGISel::SelectInlineAsmMemoryOperand(
161 const SDValue &Op, unsigned ConstraintCode, std::vector<SDValue> &OutOps) {
162 SDValue Op0, Op1;
163 switch (ConstraintCode) {
164 default:
165 return true;
166 case InlineAsm::Constraint_m: // memory
167 if (!SelectAddr(Op, Op0, Op1))
168 return true;
169 break;
170 }
171
172 SDLoc DL(Op);
173 SDValue AluOp = CurDAG->getTargetConstant(ISD::ADD, DL, MVT::i32);;
174 OutOps.push_back(Op0);
175 OutOps.push_back(Op1);
176 OutOps.push_back(AluOp);
177 return false;
178}
179
180void BPFDAGToDAGISel::Select(SDNode *Node) {
181 unsigned Opcode = Node->getOpcode();
182
183 // If we have a custom node, we already have selected!
184 if (Node->isMachineOpcode()) {
185 LLVM_DEBUG(dbgs() << "== "; Node->dump(CurDAG); dbgs() << '\n')do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("bpf-isel")) { dbgs() << "== "; Node->dump(CurDAG);
dbgs() << '\n'; } } while (false)
;
186 return;
187 }
188
189 // tablegen selection should be handled here.
190 switch (Opcode) {
191 default:
192 break;
193 case ISD::SDIV: {
194 DebugLoc Empty;
195 const DebugLoc &DL = Node->getDebugLoc();
196 if (DL != Empty)
197 errs() << "Error at line " << DL.getLine() << ": ";
198 else
199 errs() << "Error: ";
200 errs() << "Unsupport signed division for DAG: ";
201 Node->print(errs(), CurDAG);
202 errs() << "Please convert to unsigned div/mod.\n";
203 break;
204 }
205 case ISD::INTRINSIC_W_CHAIN: {
206 unsigned IntNo = cast<ConstantSDNode>(Node->getOperand(1))->getZExtValue();
207 switch (IntNo) {
208 case Intrinsic::bpf_load_byte:
209 case Intrinsic::bpf_load_half:
210 case Intrinsic::bpf_load_word: {
211 SDLoc DL(Node);
212 SDValue Chain = Node->getOperand(0);
213 SDValue N1 = Node->getOperand(1);
214 SDValue Skb = Node->getOperand(2);
215 SDValue N3 = Node->getOperand(3);
216
217 SDValue R6Reg = CurDAG->getRegister(BPF::R6, MVT::i64);
218 Chain = CurDAG->getCopyToReg(Chain, DL, R6Reg, Skb, SDValue());
219 Node = CurDAG->UpdateNodeOperands(Node, Chain, N1, R6Reg, N3);
220 break;
221 }
222 }
223 break;
224 }
225
226 case ISD::FrameIndex: {
227 int FI = cast<FrameIndexSDNode>(Node)->getIndex();
228 EVT VT = Node->getValueType(0);
229 SDValue TFI = CurDAG->getTargetFrameIndex(FI, VT);
230 unsigned Opc = BPF::MOV_rr;
231 if (Node->hasOneUse()) {
232 CurDAG->SelectNodeTo(Node, Opc, VT, TFI);
233 return;
234 }
235 ReplaceNode(Node, CurDAG->getMachineNode(Opc, SDLoc(Node), VT, TFI));
236 return;
237 }
238 }
239
240 // Select the default instruction
241 SelectCode(Node);
242}
243
244void BPFDAGToDAGISel::PreprocessLoad(SDNode *Node,
245 SelectionDAG::allnodes_iterator &I) {
246 union {
247 uint8_t c[8];
248 uint16_t s;
249 uint32_t i;
250 uint64_t d;
251 } new_val; // hold up the constant values replacing loads.
252 bool to_replace = false;
253 SDLoc DL(Node);
254 const LoadSDNode *LD = cast<LoadSDNode>(Node);
5
'Node' is a 'LoadSDNode'
255 uint64_t size = LD->getMemOperand()->getSize();
256
257 if (!size || size > 8 || (size & (size - 1)))
6
Assuming 'size' is not equal to 0
7
Assuming 'size' is <= 8
8
Assuming the condition is false
9
Taking false branch
258 return;
259
260 SDNode *LDAddrNode = LD->getOperand(1).getNode();
261 // Match LDAddr against either global_addr or (global_addr + offset)
262 unsigned opcode = LDAddrNode->getOpcode();
263 if (opcode == ISD::ADD) {
10
Assuming 'opcode' is equal to ADD
11
Taking true branch
264 SDValue OP1 = LDAddrNode->getOperand(0);
265 SDValue OP2 = LDAddrNode->getOperand(1);
266
267 // We want to find the pattern global_addr + offset
268 SDNode *OP1N = OP1.getNode();
269 if (OP1N->getOpcode() <= ISD::BUILTIN_OP_END || OP1N->getNumOperands() == 0)
12
Assuming the condition is false
13
Assuming the condition is false
14
Taking false branch
270 return;
271
272 LLVM_DEBUG(dbgs() << "Check candidate load: "; LD->dump(); dbgs() << '\n')do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("bpf-isel")) { dbgs() << "Check candidate load: "; LD->
dump(); dbgs() << '\n'; } } while (false)
;
15
Assuming 'DebugFlag' is false
16
Loop condition is false. Exiting loop
273
274 const GlobalAddressSDNode *GADN =
275 dyn_cast<GlobalAddressSDNode>(OP1N->getOperand(0).getNode());
17
Assuming the object is a 'GlobalAddressSDNode'
276 const ConstantSDNode *CDN = dyn_cast<ConstantSDNode>(OP2.getNode());
18
Assuming the object is a 'ConstantSDNode'
277 if (GADN
18.1
'GADN' is non-null
18.1
'GADN' is non-null
&& CDN
18.2
'CDN' is non-null
18.2
'CDN' is non-null
)
19
Taking true branch
278 to_replace =
279 getConstantFieldValue(GADN, CDN->getZExtValue(), size, new_val.c);
20
Calling 'BPFDAGToDAGISel::getConstantFieldValue'
39
Returning from 'BPFDAGToDAGISel::getConstantFieldValue'
280 } else if (LDAddrNode->getOpcode() > ISD::BUILTIN_OP_END &&
281 LDAddrNode->getNumOperands() > 0) {
282 LLVM_DEBUG(dbgs() << "Check candidate load: "; LD->dump(); dbgs() << '\n')do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("bpf-isel")) { dbgs() << "Check candidate load: "; LD->
dump(); dbgs() << '\n'; } } while (false)
;
283
284 SDValue OP1 = LDAddrNode->getOperand(0);
285 if (const GlobalAddressSDNode *GADN =
286 dyn_cast<GlobalAddressSDNode>(OP1.getNode()))
287 to_replace = getConstantFieldValue(GADN, 0, size, new_val.c);
288 }
289
290 if (!to_replace
39.1
'to_replace' is true
39.1
'to_replace' is true
)
40
Taking false branch
291 return;
292
293 // replacing the old with a new value
294 uint64_t val;
295 if (size == 1)
41
Assuming 'size' is not equal to 1
42
Taking false branch
296 val = new_val.c[0];
297 else if (size == 2)
43
Assuming 'size' is not equal to 2
44
Taking false branch
298 val = new_val.s;
299 else if (size == 4)
45
Assuming 'size' is not equal to 4
46
Taking false branch
300 val = new_val.i;
301 else {
302 val = new_val.d;
47
Assigned value is garbage or undefined
303 }
304
305 LLVM_DEBUG(dbgs() << "Replacing load of size " << size << " with constant "do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("bpf-isel")) { dbgs() << "Replacing load of size " <<
size << " with constant " << val << '\n'; }
} while (false)
306 << val << '\n')do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("bpf-isel")) { dbgs() << "Replacing load of size " <<
size << " with constant " << val << '\n'; }
} while (false)
;
307 SDValue NVal = CurDAG->getConstant(val, DL, MVT::i64);
308
309 // After replacement, the current node is dead, we need to
310 // go backward one step to make iterator still work
311 I--;
312 SDValue From[] = {SDValue(Node, 0), SDValue(Node, 1)};
313 SDValue To[] = {NVal, NVal};
314 CurDAG->ReplaceAllUsesOfValuesWith(From, To, 2);
315 I++;
316 // It is safe to delete node now
317 CurDAG->DeleteNode(Node);
318}
319
320void BPFDAGToDAGISel::PreprocessISelDAG() {
321 // Iterate through all nodes, interested in the following case:
322 //
323 // . loads from ConstantStruct or ConstantArray of constructs
324 // which can be turns into constant itself, with this we can
325 // avoid reading from read-only section at runtime.
326 //
327 // . Removing redundant AND for intrinsic narrow loads.
328 for (SelectionDAG::allnodes_iterator I = CurDAG->allnodes_begin(),
1
Loop condition is true. Entering loop body
329 E = CurDAG->allnodes_end();
330 I != E;) {
331 SDNode *Node = &*I++;
332 unsigned Opcode = Node->getOpcode();
333 if (Opcode == ISD::LOAD)
2
Assuming 'Opcode' is equal to LOAD
3
Taking true branch
334 PreprocessLoad(Node, I);
4
Calling 'BPFDAGToDAGISel::PreprocessLoad'
335 else if (Opcode == ISD::AND)
336 PreprocessTrunc(Node, I);
337 }
338}
339
340bool BPFDAGToDAGISel::getConstantFieldValue(const GlobalAddressSDNode *Node,
341 uint64_t Offset, uint64_t Size,
342 unsigned char *ByteSeq) {
343 const GlobalVariable *V = dyn_cast<GlobalVariable>(Node->getGlobal());
21
Assuming the object is a 'GlobalVariable'
344
345 if (!V
21.1
'V' is non-null, which participates in a condition later
21.1
'V' is non-null, which participates in a condition later
|| !V->hasInitializer())
22
Calling 'GlobalVariable::hasInitializer'
25
Returning from 'GlobalVariable::hasInitializer'
26
Taking false branch
346 return false;
347
348 const Constant *Init = V->getInitializer();
349 const DataLayout &DL = CurDAG->getDataLayout();
350 val_vec_type TmpVal;
351
352 auto it = cs_vals_.find(static_cast<const void *>(Init));
353 if (it != cs_vals_.end()) {
27
Assuming the condition is false
28
Taking false branch
354 TmpVal = it->second;
355 } else {
356 uint64_t total_size = 0;
357 if (const ConstantStruct *CS
29.1
'CS' is null
29.1
'CS' is null
= dyn_cast<ConstantStruct>(Init))
29
Assuming 'Init' is not a 'ConstantStruct'
30
Taking false branch
358 total_size =
359 DL.getStructLayout(cast<StructType>(CS->getType()))->getSizeInBytes();
360 else if (const ConstantArray *CA
31.1
'CA' is non-null
31.1
'CA' is non-null
= dyn_cast<ConstantArray>(Init))
31
Assuming 'Init' is a 'ConstantArray'
32
Taking true branch
361 total_size = DL.getTypeAllocSize(CA->getType()->getElementType()) *
362 CA->getNumOperands();
363 else
364 return false;
365
366 val_vec_type Vals(total_size, 0);
367 if (fillGenericConstant(DL, Init, Vals, 0) == false)
33
Taking false branch
368 return false;
369 cs_vals_[static_cast<const void *>(Init)] = Vals;
370 TmpVal = std::move(Vals);
371 }
372
373 // test whether host endianness matches target
374 union {
375 uint8_t c[2];
376 uint16_t s;
377 } test_buf;
378 uint16_t test_val = 0x2345;
379 if (DL.isLittleEndian())
34
Taking false branch
380 support::endian::write16le(test_buf.c, test_val);
381 else
382 support::endian::write16be(test_buf.c, test_val);
383
384 bool endian_match = test_buf.s == test_val;
35
Assuming 'test_val' is not equal to field 's'
385 for (uint64_t i = Offset, j = 0; i < Offset + Size; i++, j++)
36
Assuming the condition is false
37
Loop condition is false. Execution continues on line 388
386 ByteSeq[j] = endian_match ? TmpVal[i] : TmpVal[Offset + Size - 1 - j];
387
388 return true;
38
Returning the value 1, which participates in a condition later
389}
390
391bool BPFDAGToDAGISel::fillGenericConstant(const DataLayout &DL,
392 const Constant *CV,
393 val_vec_type &Vals, uint64_t Offset) {
394 uint64_t Size = DL.getTypeAllocSize(CV->getType());
395
396 if (isa<ConstantAggregateZero>(CV) || isa<UndefValue>(CV))
397 return true; // already done
398
399 if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV)) {
400 uint64_t val = CI->getZExtValue();
401 LLVM_DEBUG(dbgs() << "Byte array at offset " << Offset << " with value "do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("bpf-isel")) { dbgs() << "Byte array at offset " <<
Offset << " with value " << val << '\n'; }
} while (false)
402 << val << '\n')do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("bpf-isel")) { dbgs() << "Byte array at offset " <<
Offset << " with value " << val << '\n'; }
} while (false)
;
403
404 if (Size > 8 || (Size & (Size - 1)))
405 return false;
406
407 // Store based on target endian
408 for (uint64_t i = 0; i < Size; ++i) {
409 Vals[Offset + i] = DL.isLittleEndian()
410 ? ((val >> (i * 8)) & 0xFF)
411 : ((val >> ((Size - i - 1) * 8)) & 0xFF);
412 }
413 return true;
414 }
415
416 if (const ConstantDataArray *CDA = dyn_cast<ConstantDataArray>(CV))
417 return fillConstantDataArray(DL, CDA, Vals, Offset);
418
419 if (const ConstantArray *CA = dyn_cast<ConstantArray>(CV))
420 return fillConstantArray(DL, CA, Vals, Offset);
421
422 if (const ConstantStruct *CVS = dyn_cast<ConstantStruct>(CV))
423 return fillConstantStruct(DL, CVS, Vals, Offset);
424
425 return false;
426}
427
428bool BPFDAGToDAGISel::fillConstantDataArray(const DataLayout &DL,
429 const ConstantDataArray *CDA,
430 val_vec_type &Vals, int Offset) {
431 for (unsigned i = 0, e = CDA->getNumElements(); i != e; ++i) {
432 if (fillGenericConstant(DL, CDA->getElementAsConstant(i), Vals, Offset) ==
433 false)
434 return false;
435 Offset += DL.getTypeAllocSize(CDA->getElementAsConstant(i)->getType());
436 }
437
438 return true;
439}
440
441bool BPFDAGToDAGISel::fillConstantArray(const DataLayout &DL,
442 const ConstantArray *CA,
443 val_vec_type &Vals, int Offset) {
444 for (unsigned i = 0, e = CA->getNumOperands(); i != e; ++i) {
445 if (fillGenericConstant(DL, CA->getOperand(i), Vals, Offset) == false)
446 return false;
447 Offset += DL.getTypeAllocSize(CA->getOperand(i)->getType());
448 }
449
450 return true;
451}
452
453bool BPFDAGToDAGISel::fillConstantStruct(const DataLayout &DL,
454 const ConstantStruct *CS,
455 val_vec_type &Vals, int Offset) {
456 const StructLayout *Layout = DL.getStructLayout(CS->getType());
457 for (unsigned i = 0, e = CS->getNumOperands(); i != e; ++i) {
458 const Constant *Field = CS->getOperand(i);
459 uint64_t SizeSoFar = Layout->getElementOffset(i);
460 if (fillGenericConstant(DL, Field, Vals, Offset + SizeSoFar) == false)
461 return false;
462 }
463 return true;
464}
465
466void BPFDAGToDAGISel::PreprocessTrunc(SDNode *Node,
467 SelectionDAG::allnodes_iterator &I) {
468 ConstantSDNode *MaskN = dyn_cast<ConstantSDNode>(Node->getOperand(1));
469 if (!MaskN)
470 return;
471
472 // The Reg operand should be a virtual register, which is defined
473 // outside the current basic block. DAG combiner has done a pretty
474 // good job in removing truncating inside a single basic block except
475 // when the Reg operand comes from bpf_load_[byte | half | word] for
476 // which the generic optimizer doesn't understand their results are
477 // zero extended.
478 SDValue BaseV = Node->getOperand(0);
479 if (BaseV.getOpcode() != ISD::INTRINSIC_W_CHAIN)
480 return;
481
482 unsigned IntNo = cast<ConstantSDNode>(BaseV->getOperand(1))->getZExtValue();
483 uint64_t MaskV = MaskN->getZExtValue();
484
485 if (!((IntNo == Intrinsic::bpf_load_byte && MaskV == 0xFF) ||
486 (IntNo == Intrinsic::bpf_load_half && MaskV == 0xFFFF) ||
487 (IntNo == Intrinsic::bpf_load_word && MaskV == 0xFFFFFFFF)))
488 return;
489
490 LLVM_DEBUG(dbgs() << "Remove the redundant AND operation in: ";do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("bpf-isel")) { dbgs() << "Remove the redundant AND operation in: "
; Node->dump(); dbgs() << '\n'; } } while (false)
491 Node->dump(); dbgs() << '\n')do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("bpf-isel")) { dbgs() << "Remove the redundant AND operation in: "
; Node->dump(); dbgs() << '\n'; } } while (false)
;
492
493 I--;
494 CurDAG->ReplaceAllUsesWith(SDValue(Node, 0), BaseV);
495 I++;
496 CurDAG->DeleteNode(Node);
497
498 return;
499}
500
501FunctionPass *llvm::createBPFISelDag(BPFTargetMachine &TM) {
502 return new BPFDAGToDAGISel(TM);
503}

/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/llvm/include/llvm/IR/GlobalVariable.h

1//===-- llvm/GlobalVariable.h - GlobalVariable class ------------*- C++ -*-===//
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 contains the declaration of the GlobalVariable class, which
10// represents a single global variable (or constant) in the VM.
11//
12// Global variables are constant pointers that refer to hunks of space that are
13// allocated by either the VM, or by the linker in a static compiler. A global
14// variable may have an initial value, which is copied into the executables .data
15// area. Global Constants are required to have initializers.
16//
17//===----------------------------------------------------------------------===//
18
19#ifndef LLVM_IR_GLOBALVARIABLE_H
20#define LLVM_IR_GLOBALVARIABLE_H
21
22#include "llvm/ADT/PointerUnion.h"
23#include "llvm/ADT/Twine.h"
24#include "llvm/ADT/ilist_node.h"
25#include "llvm/IR/Attributes.h"
26#include "llvm/IR/GlobalObject.h"
27#include "llvm/IR/OperandTraits.h"
28#include "llvm/IR/Value.h"
29#include <cassert>
30#include <cstddef>
31
32namespace llvm {
33
34class Constant;
35class Module;
36
37template <typename ValueSubClass> class SymbolTableListTraits;
38class DIGlobalVariable;
39class DIGlobalVariableExpression;
40
41class GlobalVariable : public GlobalObject, public ilist_node<GlobalVariable> {
42 friend class SymbolTableListTraits<GlobalVariable>;
43
44 AttributeSet Attrs;
45 bool isConstantGlobal : 1; // Is this a global constant?
46 bool isExternallyInitializedConstant : 1; // Is this a global whose value
47 // can change from its initial
48 // value before global
49 // initializers are run?
50
51public:
52 /// GlobalVariable ctor - If a parent module is specified, the global is
53 /// automatically inserted into the end of the specified modules global list.
54 GlobalVariable(Type *Ty, bool isConstant, LinkageTypes Linkage,
55 Constant *Initializer = nullptr, const Twine &Name = "",
56 ThreadLocalMode = NotThreadLocal, unsigned AddressSpace = 0,
57 bool isExternallyInitialized = false);
58 /// GlobalVariable ctor - This creates a global and inserts it before the
59 /// specified other global.
60 GlobalVariable(Module &M, Type *Ty, bool isConstant,
61 LinkageTypes Linkage, Constant *Initializer,
62 const Twine &Name = "", GlobalVariable *InsertBefore = nullptr,
63 ThreadLocalMode = NotThreadLocal, unsigned AddressSpace = 0,
64 bool isExternallyInitialized = false);
65 GlobalVariable(const GlobalVariable &) = delete;
66 GlobalVariable &operator=(const GlobalVariable &) = delete;
67
68 ~GlobalVariable() {
69 dropAllReferences();
70 }
71
72 // allocate space for exactly one operand
73 void *operator new(size_t s) {
74 return User::operator new(s, 1);
75 }
76
77 // delete space for exactly one operand as created in the corresponding new operator
78 void operator delete(void *ptr){
79 assert(ptr != nullptr && "must not be nullptr")((ptr != nullptr && "must not be nullptr") ? static_cast
<void> (0) : __assert_fail ("ptr != nullptr && \"must not be nullptr\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/llvm/include/llvm/IR/GlobalVariable.h"
, 79, __PRETTY_FUNCTION__))
;
80 User *Obj = static_cast<User *>(ptr);
81 // Number of operands can be set to 0 after construction and initialization. Make sure
82 // that number of operands is reset to 1, as this is needed in User::operator delete
83 Obj->setGlobalVariableNumOperands(1);
84 User::operator delete(Obj);
85 }
86
87 /// Provide fast operand accessors
88 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value)public: inline Value *getOperand(unsigned) const; inline void
setOperand(unsigned, Value*); inline op_iterator op_begin();
inline const_op_iterator op_begin() const; inline op_iterator
op_end(); inline const_op_iterator op_end() const; protected
: template <int> inline Use &Op(); template <int
> inline const Use &Op() const; public: inline unsigned
getNumOperands() const
;
89
90 /// Definitions have initializers, declarations don't.
91 ///
92 inline bool hasInitializer() const { return !isDeclaration(); }
23
Assuming the condition is true
24
Returning the value 1, which participates in a condition later
93
94 /// hasDefinitiveInitializer - Whether the global variable has an initializer,
95 /// and any other instances of the global (this can happen due to weak
96 /// linkage) are guaranteed to have the same initializer.
97 ///
98 /// Note that if you want to transform a global, you must use
99 /// hasUniqueInitializer() instead, because of the *_odr linkage type.
100 ///
101 /// Example:
102 ///
103 /// @a = global SomeType* null - Initializer is both definitive and unique.
104 ///
105 /// @b = global weak SomeType* null - Initializer is neither definitive nor
106 /// unique.
107 ///
108 /// @c = global weak_odr SomeType* null - Initializer is definitive, but not
109 /// unique.
110 inline bool hasDefinitiveInitializer() const {
111 return hasInitializer() &&
112 // The initializer of a global variable may change to something arbitrary
113 // at link time.
114 !isInterposable() &&
115 // The initializer of a global variable with the externally_initialized
116 // marker may change at runtime before C++ initializers are evaluated.
117 !isExternallyInitialized();
118 }
119
120 /// hasUniqueInitializer - Whether the global variable has an initializer, and
121 /// any changes made to the initializer will turn up in the final executable.
122 inline bool hasUniqueInitializer() const {
123 return
124 // We need to be sure this is the definition that will actually be used
125 isStrongDefinitionForLinker() &&
126 // It is not safe to modify initializers of global variables with the
127 // external_initializer marker since the value may be changed at runtime
128 // before C++ initializers are evaluated.
129 !isExternallyInitialized();
130 }
131
132 /// getInitializer - Return the initializer for this global variable. It is
133 /// illegal to call this method if the global is external, because we cannot
134 /// tell what the value is initialized to!
135 ///
136 inline const Constant *getInitializer() const {
137 assert(hasInitializer() && "GV doesn't have initializer!")((hasInitializer() && "GV doesn't have initializer!")
? static_cast<void> (0) : __assert_fail ("hasInitializer() && \"GV doesn't have initializer!\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/llvm/include/llvm/IR/GlobalVariable.h"
, 137, __PRETTY_FUNCTION__))
;
138 return static_cast<Constant*>(Op<0>().get());
139 }
140 inline Constant *getInitializer() {
141 assert(hasInitializer() && "GV doesn't have initializer!")((hasInitializer() && "GV doesn't have initializer!")
? static_cast<void> (0) : __assert_fail ("hasInitializer() && \"GV doesn't have initializer!\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/llvm/include/llvm/IR/GlobalVariable.h"
, 141, __PRETTY_FUNCTION__))
;
142 return static_cast<Constant*>(Op<0>().get());
143 }
144 /// setInitializer - Sets the initializer for this global variable, removing
145 /// any existing initializer if InitVal==NULL. If this GV has type T*, the
146 /// initializer must have type T.
147 void setInitializer(Constant *InitVal);
148
149 /// If the value is a global constant, its value is immutable throughout the
150 /// runtime execution of the program. Assigning a value into the constant
151 /// leads to undefined behavior.
152 ///
153 bool isConstant() const { return isConstantGlobal; }
154 void setConstant(bool Val) { isConstantGlobal = Val; }
155
156 bool isExternallyInitialized() const {
157 return isExternallyInitializedConstant;
158 }
159 void setExternallyInitialized(bool Val) {
160 isExternallyInitializedConstant = Val;
161 }
162
163 /// copyAttributesFrom - copy all additional attributes (those not needed to
164 /// create a GlobalVariable) from the GlobalVariable Src to this one.
165 void copyAttributesFrom(const GlobalVariable *Src);
166
167 /// removeFromParent - This method unlinks 'this' from the containing module,
168 /// but does not delete it.
169 ///
170 void removeFromParent();
171
172 /// eraseFromParent - This method unlinks 'this' from the containing module
173 /// and deletes it.
174 ///
175 void eraseFromParent();
176
177 /// Drop all references in preparation to destroy the GlobalVariable. This
178 /// drops not only the reference to the initializer but also to any metadata.
179 void dropAllReferences();
180
181 /// Attach a DIGlobalVariableExpression.
182 void addDebugInfo(DIGlobalVariableExpression *GV);
183
184 /// Fill the vector with all debug info attachements.
185 void getDebugInfo(SmallVectorImpl<DIGlobalVariableExpression *> &GVs) const;
186
187 /// Add attribute to this global.
188 void addAttribute(Attribute::AttrKind Kind) {
189 Attrs = Attrs.addAttribute(getContext(), Kind);
190 }
191
192 /// Add attribute to this global.
193 void addAttribute(StringRef Kind, StringRef Val = StringRef()) {
194 Attrs = Attrs.addAttribute(getContext(), Kind, Val);
195 }
196
197 /// Return true if the attribute exists.
198 bool hasAttribute(Attribute::AttrKind Kind) const {
199 return Attrs.hasAttribute(Kind);
200 }
201
202 /// Return true if the attribute exists.
203 bool hasAttribute(StringRef Kind) const {
204 return Attrs.hasAttribute(Kind);
205 }
206
207 /// Return true if any attributes exist.
208 bool hasAttributes() const {
209 return Attrs.hasAttributes();
210 }
211
212 /// Return the attribute object.
213 Attribute getAttribute(Attribute::AttrKind Kind) const {
214 return Attrs.getAttribute(Kind);
215 }
216
217 /// Return the attribute object.
218 Attribute getAttribute(StringRef Kind) const {
219 return Attrs.getAttribute(Kind);
220 }
221
222 /// Return the attribute set for this global
223 AttributeSet getAttributes() const {
224 return Attrs;
225 }
226
227 /// Return attribute set as list with index.
228 /// FIXME: This may not be required once ValueEnumerators
229 /// in bitcode-writer can enumerate attribute-set.
230 AttributeList getAttributesAsList(unsigned index) const {
231 if (!hasAttributes())
232 return AttributeList();
233 std::pair<unsigned, AttributeSet> AS[1] = {{index, Attrs}};
234 return AttributeList::get(getContext(), AS);
235 }
236
237 /// Set attribute list for this global
238 void setAttributes(AttributeSet A) {
239 Attrs = A;
240 }
241
242 /// Check if section name is present
243 bool hasImplicitSection() const {
244 return getAttributes().hasAttribute("bss-section") ||
245 getAttributes().hasAttribute("data-section") ||
246 getAttributes().hasAttribute("relro-section") ||
247 getAttributes().hasAttribute("rodata-section");
248 }
249
250 // Methods for support type inquiry through isa, cast, and dyn_cast:
251 static bool classof(const Value *V) {
252 return V->getValueID() == Value::GlobalVariableVal;
253 }
254};
255
256template <>
257struct OperandTraits<GlobalVariable> :
258 public OptionalOperandTraits<GlobalVariable> {
259};
260
261DEFINE_TRANSPARENT_OPERAND_ACCESSORS(GlobalVariable, Value)GlobalVariable::op_iterator GlobalVariable::op_begin() { return
OperandTraits<GlobalVariable>::op_begin(this); } GlobalVariable
::const_op_iterator GlobalVariable::op_begin() const { return
OperandTraits<GlobalVariable>::op_begin(const_cast<
GlobalVariable*>(this)); } GlobalVariable::op_iterator GlobalVariable
::op_end() { return OperandTraits<GlobalVariable>::op_end
(this); } GlobalVariable::const_op_iterator GlobalVariable::op_end
() const { return OperandTraits<GlobalVariable>::op_end
(const_cast<GlobalVariable*>(this)); } Value *GlobalVariable
::getOperand(unsigned i_nocapture) const { ((i_nocapture <
OperandTraits<GlobalVariable>::operands(this) &&
"getOperand() out of range!") ? static_cast<void> (0) :
__assert_fail ("i_nocapture < OperandTraits<GlobalVariable>::operands(this) && \"getOperand() out of range!\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/llvm/include/llvm/IR/GlobalVariable.h"
, 261, __PRETTY_FUNCTION__)); return cast_or_null<Value>
( OperandTraits<GlobalVariable>::op_begin(const_cast<
GlobalVariable*>(this))[i_nocapture].get()); } void GlobalVariable
::setOperand(unsigned i_nocapture, Value *Val_nocapture) { ((
i_nocapture < OperandTraits<GlobalVariable>::operands
(this) && "setOperand() out of range!") ? static_cast
<void> (0) : __assert_fail ("i_nocapture < OperandTraits<GlobalVariable>::operands(this) && \"setOperand() out of range!\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/llvm/include/llvm/IR/GlobalVariable.h"
, 261, __PRETTY_FUNCTION__)); OperandTraits<GlobalVariable
>::op_begin(this)[i_nocapture] = Val_nocapture; } unsigned
GlobalVariable::getNumOperands() const { return OperandTraits
<GlobalVariable>::operands(this); } template <int Idx_nocapture
> Use &GlobalVariable::Op() { return this->OpFrom<
Idx_nocapture>(this); } template <int Idx_nocapture>
const Use &GlobalVariable::Op() const { return this->
OpFrom<Idx_nocapture>(this); }
262
263} // end namespace llvm
264
265#endif // LLVM_IR_GLOBALVARIABLE_H