LLVM 24.0.0git
Interpreter.cpp
Go to the documentation of this file.
1//===- Interpreter.cpp - Interpreter Loop for llubi -----------------------===//
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 implements the evaluation loop for each kind of instruction.
10//
11//===----------------------------------------------------------------------===//
12
13#include "ExecutorBase.h"
14#include "Library.h"
15#include "llvm/ADT/STLExtras.h"
19#include "llvm/IR/InlineAsm.h"
20#include "llvm/IR/InstVisitor.h"
21#include "llvm/IR/Intrinsics.h"
22#include "llvm/IR/Operator.h"
27
28#include <cassert>
29#include <limits>
30#include <list>
31
32namespace llvm::ubi {
33
34using namespace PatternMatch;
35
36/// Visit the scalar values recursively. The callback function may modify the
37/// value in-place.
39 function_ref<void(AnyValue &)> Visit) {
40 if (V.isNone())
41 return;
42
43 if (V.isAggregate()) {
44 for (auto &SubValue : V.asAggregate())
45 forEachScalarValue(SubValue, Visit);
46 return;
47 }
48
49 Visit(V);
50}
51
52static void applyRangeAttr(AnyValue &V, const ConstantRange &CR) {
53 forEachScalarValue(V, [&](AnyValue &Scalar) {
54 if (Scalar.isInteger() && !CR.contains(Scalar.asInteger()))
55 Scalar = AnyValue::poison();
56 });
57}
58
59static void applyNoFPClassAttr(AnyValue &V, FPClassTest NoFPClass) {
60 forEachScalarValue(V, [NoFPClass](AnyValue &Scalar) {
61 if (Scalar.isFloat() && (Scalar.asFloat().classify() & NoFPClass))
62 Scalar = AnyValue::poison();
63 });
64}
65
66static void applyNonNullAttr(AnyValue &V, unsigned AS, const DataLayout &DL) {
67 if (V.isPointer() && V.asPointer().isNullPtr(AS, DL))
69}
70
71static void applyAlignAttr(AnyValue &V, Align Alignment) {
72 forEachScalarValue(V, [Alignment](AnyValue &Scalar) {
73 if (Scalar.isPointer() &&
74 Scalar.asPointer().address().countr_zero() < Log2(Alignment))
75 Scalar = AnyValue::poison();
76 });
77}
78
79static bool violatesNoUndefAttr(const AnyValue &V) {
80 bool ContainsPoison = false;
81 forEachScalarValue(const_cast<AnyValue &>(V), [&](const AnyValue &Scalar) {
82 if (Scalar.isPoison()) {
83 ContainsPoison = true;
84 return;
85 }
86 if (Scalar.isByte() && !ContainsPoison) {
87 // For non-byte-sized values, padding bits are poison if and only if all
88 // non-padding bits in the padding byte are poison.
89 ContainsPoison = any_of(Scalar.asByte().bytes(), [](const Byte &V) {
90 return V.ConcreteMask != 255;
91 });
92 }
93 });
94 return ContainsPoison;
95}
96
97/// Assumes V is either a poison or a pointer.
99 bool OrNull, unsigned AS,
100 Context &Ctx) {
101 if (V.isPoison())
102 return true;
103
104 auto &Ptr = V.asPointer();
105 if (Ptr.isNullPtr(AS, Ctx.getDataLayout())) {
106 if (OrNull)
107 return false;
108 return true;
109 }
110
111 auto *MO = Ctx.checkProvenance(Ptr, [&](const Provenance &) {
112 // TODO: check read_provenance
113 // TODO: check nofree for attributes/metadata.
114 return true;
115 });
116 if (!MO)
117 return true;
118
119 if (MO->getState() == MemoryObjectState::Freed || MO->isInaccessible())
120 return true;
121
122 const APInt &PtrAddr = Ptr.address();
123 return Bytes > MO->getSize() || PtrAddr.ult(MO->getAddress()) ||
124 PtrAddr.ugt(MO->getAddress() + MO->getSize() - Bytes);
125}
126
127/// Instruction executor using the visitor pattern.
128/// Unlike the Context class that manages the global state,
129/// InstExecutor only maintains the state for call frames.
130class InstExecutor : public InstVisitor<InstExecutor, void>,
131 public ExecutorBase {
132 const DataLayout &DL;
133 std::list<Frame> CallStack;
134 AnyValue None;
135 std::list<AnyValue> UnsupportedConstantValues;
136 Library Lib;
137
138 const AnyValue &getValue(Value *V) {
139 if (auto *C = dyn_cast<Constant>(V)) {
140 if (const AnyValue *Val = Ctx.getConstantValue(C))
141 return *Val;
142 reportError() << "Unsupported constant: " << *C << ".";
143 UnsupportedConstantValues.push_back(
144 AnyValue::getPoisonValue(Ctx, C->getType()));
145 return UnsupportedConstantValues.back();
146 }
148 return None;
149 return CurrentFrame->ValueMap.at(V);
150 }
151
152 void setResult(Instruction &I, AnyValue V) {
153 if (!hasProgramExited() && !Handler.onInstructionExecuted(I, V))
154 setFailed();
155 if (hasProgramExited())
156 return;
157 assert(V.isCompatibleWith(I.getType()) && "Unexpected value storage kind.");
158 if (!V.isNone())
159 CurrentFrame->ValueMap.insert_or_assign(&I, std::move(V));
160 }
161
163 bool IsInput) {
164 if (!Val.isDenormal())
165 return Val;
166 if (IsInput) {
167 // Non-deterministically choose between flushing or preserving the
168 // denormal value.
169 if (Ctx.getRandomBool())
170 return Val;
171 }
173 return APFloat::getZero(Val.getSemantics(), false);
175 return APFloat::getZero(Val.getSemantics(), Val.isNegative());
176 // Default case for IEEE, Dynamic, and Invalid
177 // Currently we treat Dynamic the same as IEEE, since we don't support
178 // changing the mode at this point.
179 return Val;
180 }
181
182 AnyValue handleFMFFlags(AnyValue Val, FastMathFlags FMF, bool IsInput) {
183 if (Val.isPoison())
184 return AnyValue::poison();
185
186 if (Val.isAggregate()) {
187 std::vector<AnyValue> ResVec;
188 ResVec.reserve(Val.asAggregate().size());
189 for (const auto &A : Val.asAggregate())
190 ResVec.push_back(handleFMFFlags(A, FMF, IsInput));
191 return AnyValue(ResVec);
192 }
193
194 const APFloat &APVal = Val.asFloat();
195 if (FMF.noNaNs() && APVal.isNaN())
196 return AnyValue::poison();
197 if (FMF.noInfs() && APVal.isInfinity())
198 return AnyValue::poison();
199 if (IsInput && FMF.noSignedZeros() && APVal.isZero())
201 APVal.getSemantics(), APVal.isNegative() ^ Ctx.getRandomBool()));
202 return Val;
203 }
204
205 void addNaNCandidate(SmallVectorImpl<APFloat> &Candidates,
206 APFloat Candidate) {
207 if (any_of(Candidates, [&](const APFloat &Existing) {
208 return Existing.bitwiseIsEqual(Candidate);
209 }))
210 return;
211 Candidates.push_back(std::move(Candidate));
212 }
213
214 APFloat pickNaNCandidate(ArrayRef<APFloat> Candidates) {
215 assert(!Candidates.empty() && "Need at least one NaN candidate.");
216 return Candidates[Ctx.getRandomUInt64() % Candidates.size()];
217 }
218
219 APInt getRandomNaNPayload(const fltSemantics &Sem) {
220 const unsigned NumBits = Sem.precision - 1;
222 const unsigned NumWords = APInt::getNumWords(NumBits);
223 RandomWords.reserve(NumWords);
224 for (unsigned I = 0; I != NumWords; ++I)
225 RandomWords.push_back(Ctx.getRandomUInt64());
226 return APInt(NumBits, RandomWords);
227 }
228
229 bool isPreferredNaN(const APFloat &Val) {
230 assert(Val.isNaN() && "Expected NaN.");
231 const APFloat Preferred =
233 return Val.bitwiseIsEqual(Preferred);
234 }
235
236 bool wasmMayProduceExtraNaNPayload(ArrayRef<const APFloat *> Inputs) {
237 for (const APFloat *Input : Inputs) {
238 if (!Input->isNaN())
239 continue;
240 if (Input->isSignaling() || !isPreferredNaN(*Input))
241 return true;
242 }
243 return false;
244 }
245
246 APFloat propagateInputNaN(const APFloat &InputNaN, const fltSemantics &DstSem,
247 bool QuietingMode, bool FlipSign) {
248 APFloat Res = InputNaN;
249 bool LosesInfo;
250 Res.convert(DstSem, APFloat::rmNearestTiesToEven, &LosesInfo);
251 if (FlipSign)
252 Res.changeSign();
253 if (QuietingMode && Res.isSignaling())
254 Res = Res.makeQuiet();
255 return Res;
256 }
257
258 APFloat maybeQuietSNaN(APFloat Val) const {
259 if (Val.isSignaling() && Ctx.getRandomBool())
260 return Val.makeQuiet();
261 return Val;
262 }
263
264 APFloat applyFPMinMax(Intrinsic::ID IID, const APFloat &LHS,
265 const APFloat &RHS, bool NoSignedZeros) {
266 if (NoSignedZeros && LHS.isZero() && RHS.isZero() &&
267 LHS.isNegative() != RHS.isNegative() && Ctx.mayUseNonDeterminism())
268 return Ctx.getRandomBool() ? LHS : RHS;
269 switch (IID) {
270 case Intrinsic::maximum:
271 case Intrinsic::vector_reduce_fmaximum:
272 return maximum(LHS, RHS);
273 case Intrinsic::minimum:
274 case Intrinsic::vector_reduce_fminimum:
275 return minimum(LHS, RHS);
276 case Intrinsic::maximumnum:
277 case Intrinsic::vector_reduce_fmaximumnum:
278 return maximumnum(LHS, RHS);
279 case Intrinsic::minimumnum:
280 case Intrinsic::vector_reduce_fminimumnum:
281 return minimumnum(LHS, RHS);
282 case Intrinsic::maxnum:
283 case Intrinsic::vector_reduce_fmax:
284 return maxnum(maybeQuietSNaN(LHS), maybeQuietSNaN(RHS));
285 case Intrinsic::minnum:
286 case Intrinsic::vector_reduce_fmin:
287 return minnum(maybeQuietSNaN(LHS), maybeQuietSNaN(RHS));
288 default:
289 llvm_unreachable("Unexpected FP min/max intrinsic ID");
290 }
291 }
292
293 void addPropagatedNaNCandidates(SmallVectorImpl<APFloat> &Candidates,
295 const fltSemantics &DstSem, bool QuietingMode,
296 bool SignChoice) {
297 for (const APFloat *Input : Inputs) {
298 if (!Input->isNaN())
299 continue;
300 addNaNCandidate(Candidates, propagateInputNaN(*Input, DstSem,
301 QuietingMode, SignChoice));
302 }
303 }
304
305 void addTargetSpecificNaNCandidates(SmallVectorImpl<APFloat> &Candidates,
306 const APFloat &Result,
308 bool SignChoice) {
309 const Triple &TT = Ctx.getTargetTriple();
310 if (TT.isWasm()) {
311 if (!wasmMayProduceExtraNaNPayload(Inputs))
312 return;
313 APInt Payload = getRandomNaNPayload(Result.getSemantics());
314 addNaNCandidate(Candidates, APFloat::getQNaN(Result.getSemantics(),
315 SignChoice, &Payload));
316 return;
317 }
318
319 if (TT.isSPARC32() || TT.isSPARC64()) {
320 APInt Payload = APInt::getAllOnes(Result.getSemantics().precision - 1);
321 addNaNCandidate(Candidates, APFloat::getQNaN(Result.getSemantics(),
322 SignChoice, &Payload));
323 }
324 }
325
326 APFloat applyNaNPropagation(const APFloat &Result,
328 if (!Result.isNaN())
329 return Result;
330
331 const NaNPropagationBehavior Choice =
332 Ctx.getEffectiveNaNPropagationBehavior();
333 const bool SignChoice = Ctx.getRandomBool();
334 const fltSemantics &ResultSem = Result.getSemantics();
335 auto PreferredNaN = [&]() {
336 return APFloat::getQNaN(ResultSem, SignChoice);
337 };
338
339 SmallVector<APFloat, 4> Candidates;
340 switch (Choice) {
342 return PreferredNaN();
344 addPropagatedNaNCandidates(Candidates, Inputs, ResultSem,
345 /*QuietingMode=*/true, SignChoice);
346 return Candidates.empty() ? PreferredNaN() : pickNaNCandidate(Candidates);
348 addPropagatedNaNCandidates(Candidates, Inputs, ResultSem,
349 /*QuietingMode=*/false, SignChoice);
350 return Candidates.empty() ? PreferredNaN() : pickNaNCandidate(Candidates);
352 addTargetSpecificNaNCandidates(Candidates, Result, Inputs, SignChoice);
353 return Candidates.empty() ? PreferredNaN() : pickNaNCandidate(Candidates);
355 addNaNCandidate(Candidates, PreferredNaN());
356 addPropagatedNaNCandidates(Candidates, Inputs, ResultSem,
357 /*QuietingMode=*/true, SignChoice);
358 addPropagatedNaNCandidates(Candidates, Inputs, ResultSem,
359 /*QuietingMode=*/false, SignChoice);
360 addTargetSpecificNaNCandidates(Candidates, Result, Inputs, SignChoice);
361 return pickNaNCandidate(Candidates);
362 }
363 llvm_unreachable("Unhandled NaN propagation behavior.");
364 }
365
366 AnyValue computeUnOp(Type *Ty, const AnyValue &Operand,
367 function_ref<AnyValue(const AnyValue &)> ScalarFn) {
368 if (Ty->isVectorTy()) {
369 auto &OperandVec = Operand.asAggregate();
370 std::vector<AnyValue> ResVec;
371 ResVec.reserve(OperandVec.size());
372 for (const auto &Scalar : OperandVec)
373 ResVec.push_back(ScalarFn(Scalar));
374 return std::move(ResVec);
375 }
376 return ScalarFn(Operand);
377 }
378
379 void visitUnOp(Instruction &I,
380 function_ref<AnyValue(const AnyValue &)> ScalarFn) {
381 setResult(I, computeUnOp(I.getType(), getValue(I.getOperand(0)), ScalarFn));
382 }
383
384 void visitIntUnOp(Instruction &I,
385 function_ref<AnyValue(const APInt &)> ScalarFn) {
386 visitUnOp(I, [&](const AnyValue &Operand) -> AnyValue {
387 if (Operand.isPoison())
388 return AnyValue::poison();
389 return ScalarFn(Operand.asInteger());
390 });
391 }
392
393 void visitBitwiseFPUnOp(Instruction &I,
394 function_ref<APFloat(const APFloat &)> ScalarFn) {
395 setResult(I, visitBitwiseFPUnOpWithResult(
396 I.getType(), cast<FPMathOperator>(I).getFastMathFlags(),
397 getValue(I.getOperand(0)), ScalarFn));
398 }
399
401 visitIntUnOpWithResult(Type *RetTy, const AnyValue &Operand,
402 function_ref<AnyValue(const APInt &)> ScalarFn) {
403 return computeUnOp(RetTy, Operand,
404 [&](const AnyValue &OperandInner) -> AnyValue {
405 if (OperandInner.isPoison())
406 return AnyValue::poison();
407 return ScalarFn(OperandInner.asInteger());
408 });
409 }
410
411 AnyValue visitBitwiseFPUnOpWithResult(
412 Type *RetTy, const FastMathFlags &FMF, const AnyValue &Operand,
413 function_ref<APFloat(const APFloat &)> ScalarFn) {
414 return computeUnOp(
415 RetTy, Operand, [&](const AnyValue &OperandInner) -> AnyValue {
416 if (OperandInner.isPoison())
417 return AnyValue::poison();
418
419 // We don't flush denormals here since bitwise floating-point
420 // operations only manipulate on certain bits of the operand.
421
422 AnyValue ValidatedOperand =
423 handleFMFFlags(OperandInner, FMF, /*IsInput=*/true);
424 if (ValidatedOperand.isPoison())
425 return ValidatedOperand;
426
427 APFloat Result = ScalarFn(ValidatedOperand.asFloat());
428
429 return handleFMFFlags(Result, FMF, /*IsInput=*/false);
430 });
431 }
432
433 AnyValue computeBinOp(
434 Type *Ty, const AnyValue &LHS, const AnyValue &RHS,
435 function_ref<AnyValue(const AnyValue &, const AnyValue &)> ScalarFn) {
436 if (Ty->isVectorTy()) {
437 auto &LHSVec = LHS.asAggregate();
438 auto &RHSVec = RHS.asAggregate();
439 std::vector<AnyValue> ResVec;
440 ResVec.reserve(LHSVec.size());
441 for (const auto &[ScalarLHS, ScalarRHS] : zip(LHSVec, RHSVec))
442 ResVec.push_back(ScalarFn(ScalarLHS, ScalarRHS));
443 return std::move(ResVec);
444 }
445 return ScalarFn(LHS, RHS);
446 }
447
448 void visitBinOp(
449 Instruction &I,
450 function_ref<AnyValue(const AnyValue &, const AnyValue &)> ScalarFn) {
451 setResult(I, computeBinOp(I.getType(), getValue(I.getOperand(0)),
452 getValue(I.getOperand(1)), ScalarFn));
453 }
454
455 void
456 visitIntBinOp(Instruction &I,
457 function_ref<AnyValue(const APInt &, const APInt &)> ScalarFn) {
458 visitBinOp(I, [&](const AnyValue &LHS, const AnyValue &RHS) -> AnyValue {
459 if (LHS.isPoison() || RHS.isPoison())
460 return AnyValue::poison();
461 return ScalarFn(LHS.asInteger(), RHS.asInteger());
462 });
463 }
464
465 void visitFPBinOp(
466 Instruction &I,
467 function_ref<APFloat(const APFloat &, const APFloat &)> ScalarFn) {
468 setResult(I, visitFPBinOpWithResult(
469 I.getType(), cast<FPMathOperator>(I).getFastMathFlags(),
470 getValue(I.getOperand(0)), getValue(I.getOperand(1)),
471 ScalarFn));
472 }
473
474 AnyValue visitIntBinOpWithResult(
475 Type *RetTy, const AnyValue &LHS, const AnyValue &RHS,
476 function_ref<AnyValue(const APInt &, const APInt &)> ScalarFn) {
477 return computeBinOp(
478 RetTy, LHS, RHS,
479 [&](const AnyValue &LHSInner, const AnyValue &RHSInner) -> AnyValue {
480 if (LHSInner.isPoison() || RHSInner.isPoison())
481 return AnyValue::poison();
482 return ScalarFn(LHSInner.asInteger(), RHSInner.asInteger());
483 });
484 }
485
486 AnyValue visitOverflowIntBinOpWithResult(
487 Type *RetTy, const AnyValue &LHS, const AnyValue &RHS,
488 function_ref<std::pair<APInt, bool>(const APInt &, const APInt &)>
489 ScalarFn) {
490 if (!LHS.isAggregate()) {
491 if (LHS.isPoison() || RHS.isPoison())
492 return std::vector<AnyValue>{AnyValue::poison(), AnyValue::poison()};
493 auto [Res, Overflow] = ScalarFn(LHS.asInteger(), RHS.asInteger());
494 return std::vector<AnyValue>{AnyValue(Res), AnyValue::boolean(Overflow)};
495 }
496
497 auto &LHSVec = LHS.asAggregate();
498 auto &RHSVec = RHS.asAggregate();
499 std::vector<AnyValue> ResVec;
500 std::vector<AnyValue> OverflowVec;
501 ResVec.reserve(LHSVec.size());
502 OverflowVec.reserve(LHSVec.size());
503 for (const auto &[ScalarLHS, ScalarRHS] : zip(LHSVec, RHSVec)) {
504 if (ScalarLHS.isPoison() || ScalarRHS.isPoison()) {
505 ResVec.push_back(AnyValue::poison());
506 OverflowVec.push_back(AnyValue::poison());
507 continue;
508 }
509 auto [Res, Overflow] =
510 ScalarFn(ScalarLHS.asInteger(), ScalarRHS.asInteger());
511 ResVec.push_back(AnyValue(Res));
512 OverflowVec.push_back(AnyValue::boolean(Overflow));
513 }
514 return std::vector<AnyValue>{AnyValue(std::move(ResVec)),
515 AnyValue(std::move(OverflowVec))};
516 }
517
518 AnyValue visitFPBinOpWithResult(
519 Type *RetTy, const FastMathFlags &FMF, const AnyValue &LHS,
520 const AnyValue &RHS,
521 function_ref<APFloat(const APFloat &, const APFloat &)> ScalarFn) {
522 DenormalMode DenormMode = getCurrentDenormalMode(RetTy);
523
524 if (!Ctx.isDefaultFPEnv())
525 reportImmediateUB() << "Non-constrained floating-point operation assumes "
526 "default floating-point environment";
527
528 return computeBinOp(
529 RetTy, LHS, RHS,
530 [&](const AnyValue &LHSInner, const AnyValue &RHSInner) -> AnyValue {
531 if (LHSInner.isPoison() || RHSInner.isPoison())
532 return AnyValue::poison();
533
534 AnyValue ValidatedLHS =
535 handleFMFFlags(LHSInner, FMF, /*IsInput=*/true);
536 AnyValue ValidatedRHS =
537 handleFMFFlags(RHSInner, FMF, /*IsInput=*/true);
538 if (ValidatedLHS.isPoison())
539 return ValidatedLHS;
540 if (ValidatedRHS.isPoison())
541 return ValidatedRHS;
542
543 // Flush input denormals
544 APFloat FLHS = handleDenormal(ValidatedLHS.asFloat(),
545 DenormMode.Input, /*IsInput=*/true);
546 APFloat FRHS = handleDenormal(ValidatedRHS.asFloat(),
547 DenormMode.Input, /*IsInput=*/true);
548
549 APFloat RawResult = ScalarFn(FLHS, FRHS);
550
551 // Flush output denormals and handle fast-math flags.
552 AnyValue FResult = handleFMFFlags(
553 handleDenormal(RawResult, DenormMode.Output, /*IsInput=*/false),
554 FMF,
555 /*IsInput=*/false);
556
557 if (FResult.isPoison())
558 return FResult;
559
560 APFloat Result = FResult.asFloat();
561 return applyNaNPropagation(Result, {&FLHS, &FRHS});
562 });
563 }
564
566 computeTriOp(Type *Ty, const AnyValue &Op1, const AnyValue &Op2,
567 const AnyValue &Op3,
568 function_ref<AnyValue(const AnyValue &, const AnyValue &,
569 const AnyValue &)>
570 ScalarFn) {
571 if (Ty->isVectorTy()) {
572 auto &Op1Vec = Op1.asAggregate();
573 auto &Op2Vec = Op2.asAggregate();
574 auto &Op3Vec = Op3.asAggregate();
575 std::vector<AnyValue> ResVec;
576 ResVec.reserve(Op1Vec.size());
577 for (const auto &[ScalarOp1, ScalarOp2, ScalarOp3] :
578 zip(Op1Vec, Op2Vec, Op3Vec))
579 ResVec.push_back(ScalarFn(ScalarOp1, ScalarOp2, ScalarOp3));
580 return std::move(ResVec);
581 }
582 return ScalarFn(Op1, Op2, Op3);
583 }
584
585 void visitTriOp(Instruction &I,
586 function_ref<AnyValue(const AnyValue &, const AnyValue &,
587 const AnyValue &)>
588 ScalarFn) {
589 setResult(I, computeTriOp(I.getType(), getValue(I.getOperand(0)),
590 getValue(I.getOperand(1)),
591 getValue(I.getOperand(2)), ScalarFn));
592 }
593
594 void visitIntTriOp(
595 Instruction &I,
596 function_ref<AnyValue(const APInt &, const APInt &, const APInt &)>
597 ScalarFn) {
598 visitTriOp(I,
599 [&](const AnyValue &Op1, const AnyValue &Op2,
600 const AnyValue &Op3) -> AnyValue {
601 if (Op1.isPoison() || Op2.isPoison() || Op3.isPoison())
602 return AnyValue::poison();
603 return ScalarFn(Op1.asInteger(), Op2.asInteger(),
604 Op3.asInteger());
605 });
606 }
607
608 AnyValue visitIntTriOpWithResult(
609 Type *RetTy, const AnyValue &Op1, const AnyValue &Op2,
610 const AnyValue &Op3,
611 function_ref<AnyValue(const APInt &, const APInt &, const APInt &)>
612 ScalarFn) {
613 return computeTriOp(
614 RetTy, Op1, Op2, Op3,
615 [&](const AnyValue &Op1Inner, const AnyValue &Op2Inner,
616 const AnyValue &Op3Inner) -> AnyValue {
617 if (Op1Inner.isPoison() || Op2Inner.isPoison() || Op3Inner.isPoison())
618 return AnyValue::poison();
619 return ScalarFn(Op1Inner.asInteger(), Op2Inner.asInteger(),
620 Op3Inner.asInteger());
621 });
622 }
623
624 AnyValue visitFPTriOpWithResult(
625 Type *RetTy, const FastMathFlags &FMF, const AnyValue &Op1,
626 const AnyValue &Op2, const AnyValue &Op3,
627 function_ref<APFloat(const APFloat &, const APFloat &, const APFloat &)>
628 ScalarFn) {
629 DenormalMode DenormMode = getCurrentDenormalMode(RetTy);
630
631 if (!Ctx.isDefaultFPEnv())
632 reportImmediateUB() << "Non-constrained floating-point operation assumes "
633 "default floating-point environment";
634
635 return computeTriOp(
636 RetTy, Op1, Op2, Op3,
637 [&](const AnyValue &Op1Inner, const AnyValue &Op2Inner,
638 const AnyValue &Op3Inner) -> AnyValue {
639 if (Op1Inner.isPoison() || Op2Inner.isPoison() || Op3Inner.isPoison())
640 return AnyValue::poison();
641
642 AnyValue ValidatedOp1 =
643 handleFMFFlags(Op1Inner, FMF, /*IsInput=*/true);
644 AnyValue ValidatedOp2 =
645 handleFMFFlags(Op2Inner, FMF, /*IsInput=*/true);
646 AnyValue ValidatedOp3 =
647 handleFMFFlags(Op3Inner, FMF, /*IsInput=*/true);
648 if (ValidatedOp1.isPoison())
649 return ValidatedOp1;
650 if (ValidatedOp2.isPoison())
651 return ValidatedOp2;
652 if (ValidatedOp3.isPoison())
653 return ValidatedOp3;
654
655 // Flush input denormals
656 APFloat FOp1 = handleDenormal(ValidatedOp1.asFloat(),
657 DenormMode.Input, /*IsInput=*/true);
658 APFloat FOp2 = handleDenormal(ValidatedOp2.asFloat(),
659 DenormMode.Input, /*IsInput=*/true);
660 APFloat FOp3 = handleDenormal(ValidatedOp3.asFloat(),
661 DenormMode.Input, /*IsInput=*/true);
662
663 APFloat RawResult = ScalarFn(FOp1, FOp2, FOp3);
664
665 // Flush output denormals and handle fast-math flags.
666 AnyValue FResult = handleFMFFlags(
667 handleDenormal(RawResult, DenormMode.Output, /*IsInput=*/false),
668 FMF,
669 /*IsInput=*/false);
670
671 if (FResult.isPoison())
672 return FResult;
673
674 APFloat Result = FResult.asFloat();
675 return applyNaNPropagation(Result, {&FOp1, &FOp2, &FOp3});
676 });
677 }
678
679 void jumpTo(Instruction &Terminator, BasicBlock *DestBB) {
680 if (!Handler.onBBJump(Terminator, *DestBB)) {
681 setFailed();
682 return;
683 }
684 BasicBlock *From = CurrentFrame->BB;
685 CurrentFrame->BB = DestBB;
686 CurrentFrame->PC = DestBB->begin();
687 // Update PHI nodes in batch to avoid the interference between PHI nodes.
688 // We need to store the incoming values into a temporary buffer.
689 // Otherwise, the incoming value may be overwritten before it is
690 // used by other PHI nodes.
692 PHINode *PHI = nullptr;
693 while ((PHI = dyn_cast<PHINode>(CurrentFrame->PC))) {
694 AnyValue IncomingVal = getValue(PHI->getIncomingValueForBlock(From));
695
696 // Fast-math flags validation
698 FastMathFlags FMF = PHI->getFastMathFlags();
699 if (FMF.any())
700 IncomingVal =
701 handleFMFFlags(std::move(IncomingVal), FMF, /*IsInput=*/true);
702 }
703
704 handleMetadata(PHI->getType(), IncomingVal, *PHI);
705 if (hasProgramExited())
706 return;
707
708 IncomingValues.emplace_back(PHI, IncomingVal);
709 ++CurrentFrame->PC;
710 }
711 for (auto &[K, V] : IncomingValues)
712 setResult(*K, std::move(V));
713 }
714
715 /// Helper function to determine whether an inline asm is a no-op, which is
716 /// used to implement black_box style optimization blockers.
717 bool isNoopInlineAsm(Value *V, Type *RetTy) {
718 if (auto *Asm = dyn_cast<InlineAsm>(V))
719 return Asm->getAsmString().empty() && RetTy->isVoidTy();
720 return false;
721 }
722
723 DenormalMode getCurrentDenormalMode(Type *Ty) {
724 return CurrentFrame->Func.getDenormalMode(
725 Ty->getScalarType()->getFltSemantics());
726 }
727
728 // Helper function to convert BooleanKind to bool. Report an immediate UB if
729 // a poison is found.
730 bool getBooleanNonPoison(BooleanKind Boolean) {
732 reportImmediateUB() << "Unexpected poison boolean value";
733 return Boolean == BooleanKind::True;
734 }
735
736 APInt getIntNonPoison(const AnyValue &V) {
737 if (V.isPoison()) {
738 reportImmediateUB() << "Unexpected poison integer value.";
739 return APInt::getZero(64);
740 }
741 return V.asInteger();
742 }
743
744 static BooleanKind getMaskLane(const AnyValue &Mask, size_t I) {
745 return Mask.asAggregate()[I].asBoolean();
746 }
747
748 AnyValue callExperimentalVectorHistogramIntrinsic(CallBase &CB,
750 Intrinsic::ID IID) {
751 struct LaneUpdate {
752 MemoryObject *MO;
755 AnyValue Old;
757 };
758
759 const auto &Ptrs = Args[0].asAggregate();
760 const AnyValue &Update = Args[1];
761 const AnyValue &Mask = Args[2];
762 Type *ElemTy = CB.getArgOperand(1)->getType();
763 const uint64_t AccessSize = Ctx.getEffectiveTypeStoreSize(ElemTy);
764
766 Lanes.reserve(Ptrs.size());
767 for (size_t I = 0, E = Ptrs.size(); I != E; ++I) {
768 switch (getMaskLane(Mask, I)) {
770 continue;
773 << "Poison mask lane in experimental vector histogram intrinsic.";
774 return AnyValue();
776 break;
777 }
778
779 if (Ptrs[I].isPoison()) {
780 reportImmediateUB() << "Poison pointer lane in experimental vector "
781 "histogram intrinsic.";
782 return AnyValue();
783 }
784
785 auto [MO, Offset] =
786 verifyMemAccess(Ptrs[I].asPointer(), AccessSize, Align(1),
787 /*IsStore=*/true);
788 if (!MO)
789 return AnyValue();
790
791 Lanes.push_back({MO, Offset, 0, AnyValue(), AnyValue()});
792 }
793
794 for (LaneUpdate &Lane : Lanes) {
795 Lane.Count = count_if(Lanes, [&](const LaneUpdate &Other) {
796 return Other.MO == Lane.MO && Other.Offset == Lane.Offset;
797 });
798 Lane.Old = Ctx.load(*Lane.MO, Lane.Offset, ElemTy);
799 }
800
801 for (LaneUpdate &Lane : Lanes) {
802 const AnyValue &Old = Lane.Old;
803 AnyValue &New = Lane.New;
804
805 if (Old.isPoison() || Update.isPoison()) {
807 } else {
808 const APInt &OldInt = Old.asInteger();
809 const APInt &UpdateInt = Update.asInteger();
810
811 switch (IID) {
812 case Intrinsic::experimental_vector_histogram_add:
813 New = OldInt + UpdateInt * APInt(UpdateInt.getBitWidth(), Lane.Count,
814 /*isSigned=*/false,
815 /*implicitTrunc=*/true);
816 break;
817 case Intrinsic::experimental_vector_histogram_uadd_sat: {
818 APInt Acc = OldInt;
819 for (uint64_t I = 0; I != Lane.Count; ++I)
820 Acc = Acc.uadd_sat(UpdateInt);
821 New = Acc;
822 break;
823 }
824 case Intrinsic::experimental_vector_histogram_umax:
825 New = APIntOps::umax(OldInt, UpdateInt);
826 break;
827 case Intrinsic::experimental_vector_histogram_umin:
828 New = APIntOps::umin(OldInt, UpdateInt);
829 break;
830 default:
831 llvm_unreachable("Unexpected histogram intrinsic ID");
832 }
833 }
834 }
835
836 for (const LaneUpdate &Lane : Lanes)
837 Ctx.store(*Lane.MO, Lane.Offset, Lane.New, ElemTy);
838
839 return AnyValue();
840 }
841
842 /// Returns the oracle function if \p CB is an llvm.speculative.load in
843 /// oracle form, nullptr otherwise.
844 static Function *getSpeculativeLoadOracle(const CallBase &CB) {
845 return CB.getIntrinsicID() == Intrinsic::speculative_load
847 : nullptr;
848 }
849
850 AnyValue callSpeculativeLoadIntrinsic(CallBase &CB, const AnyValue &Ptr,
851 const AnyValue &NumBytes) {
852 Type *RetTy = CB.getType();
853 if (Ptr.isPoison()) {
854 reportImmediateUB() << "llvm.speculative.load with poison pointer.";
855 return AnyValue();
856 }
857 if (NumBytes.isPoison()) {
859 << "llvm.speculative.load with poison number of accessible bytes.";
860 return AnyValue();
861 }
862
863 const uint64_t Size = Ctx.getEffectiveTypeStoreSize(RetTy);
864 const APInt &NumBytesInt = NumBytes.asInteger();
865 if (NumBytesInt.ugt(Size)) {
866 reportImmediateUB() << "llvm.speculative.load number of accessible bytes "
867 << NumBytesInt.getZExtValue()
868 << " exceeds the loaded size " << Size << ".";
869 return AnyValue();
870 }
871
872 // Only the accessible bytes are read from memory and must be in bounds of
873 // the underlying object. All other bytes are poison.
874 const uint64_t N = NumBytesInt.getZExtValue();
876 if (N != 0) {
877 const bool FromEnd = cast<ConstantInt>(CB.getArgOperand(1))->isOne();
878 const uint64_t Start = FromEnd ? Size - N : 0;
879 const Pointer &PtrVal = Ptr.asPointer();
880 auto [MO, Offset] =
881 verifyMemAccess(PtrVal.getWithNewAddr(PtrVal.address() + Start), N,
882 Align(1), /*IsStore=*/false);
883 if (!MO)
884 return AnyValue();
885 copy(MO->getBytes().slice(Offset, N), Bytes.begin() + Start);
886 }
887 return Ctx.fromBytes(Bytes, RetTy);
888 }
889
890 /// How masked memory intrinsics compute the address of each lane.
891 enum class MaskedAddrMode {
892 /// \p Ptr is the base pointer and lane I accesses element I after it.
893 Consecutive,
894 /// \p Ptr holds a separate pointer for each lane.
895 PerLane,
896 /// \p Ptr is the base pointer and the offset increases on each active lane.
897 Compressed,
898 };
899
900 /// Implements the masked intrinsic family. For loads, \p Data holds the
901 /// pass-through values and is updated with the loaded lanes; for stores, it
902 /// holds the values to store. Lane addresses are computed according to \p
903 /// Mode.
904 AnyValue callMaskedLoadStoreIntrinsic(CallBase &CB, const AnyValue &Ptr,
905 const AnyValue &Mask, AnyValue Data,
906 MaskedAddrMode Mode, bool IsStore) {
907 StringRef IntrinsicName = Intrinsic::getBaseName(CB.getIntrinsicID());
908 Type *ElemTy = (IsStore ? CB.getArgOperand(0)->getType() : CB.getType())
909 ->getScalarType();
910 // TODO: Support element types that are not a whole number of bytes.
911 if (Mode != MaskedAddrMode::PerLane &&
912 !DL.typeSizeEqualsStoreSize(ElemTy)) {
913 reportError() << IntrinsicName << " with element type " << *ElemTy
914 << " is not supported.";
915 return AnyValue();
916 }
917
918 const uint64_t AccessSize = Ctx.getEffectiveTypeStoreSize(ElemTy);
919 const unsigned IndexBW =
920 DL.getIndexTypeSizeInBits(CB.getArgOperand(IsStore ? 1 : 0)->getType());
921 AnyValue LanePtr;
922 if (Mode != MaskedAddrMode::PerLane)
923 LanePtr = Ptr;
925
926 for (auto [I, Lane] : enumerate(Data.asAggregate())) {
927 if (Mode == MaskedAddrMode::PerLane)
928 LanePtr = Ptr.asAggregate()[I];
929 BooleanKind MaskLane = getMaskLane(Mask, I);
930
931 if (MaskLane == BooleanKind::Poison) {
932 reportImmediateUB() << "Poison mask lane in " << IntrinsicName << '.';
933 return AnyValue();
934 }
935
936 assert(MaskLane == BooleanKind::True || MaskLane == BooleanKind::False);
937
938 if (MaskLane == BooleanKind::True) {
939 if (IsStore)
940 store(LanePtr, Align(1), Lane, ElemTy);
941 else
942 Lane = load(LanePtr, Align(1), ElemTy, /*NoUndef=*/false);
943 // The first enabled base pointer may not be inbounds, but pointers
944 // after that must be inbounds.
945 Flags = GEPNoWrapFlags::inBounds();
946 }
947
948 if (Mode == MaskedAddrMode::Consecutive ||
949 (Mode == MaskedAddrMode::Compressed &&
950 MaskLane == BooleanKind::True)) {
951 AnyValue AccumulatedOffset = AnyValue::poison();
952 LanePtr = Ctx.computePtrAdd(LanePtr, APInt(IndexBW, AccessSize), Flags,
953 AccumulatedOffset);
954 }
955 }
956
957 return IsStore ? AnyValue() : Data;
958 }
959
960 /// Returns \p Ptr, the pointer argument of the VP memory intrinsic \p CB.
961 /// Without an align attribute it must have the ABI alignment of \p Ty.
962 AnyValue withVPDefaultAlign(CallBase &CB, AnyValue Ptr, Type *Ty) {
963 if (!cast<VPIntrinsic>(CB).getPointerAlignment())
964 applyAlignAttr(Ptr, DL.getABITypeAlign(Ty));
965 return Ptr;
966 }
967
968 /// Implements llvm.vp.{load,store,gather,scatter} as the corresponding masked
969 /// intrinsic. Lanes at or past \p EVL are disabled even if their \p Mask lane
970 /// is poison.
971 AnyValue callVPLoadStoreIntrinsic(CallBase &CB, const AnyValue &Ptr,
972 const AnyValue &Mask, const AnyValue &EVL,
973 AnyValue Data, MaskedAddrMode Mode,
974 bool IsStore) {
975 StringRef IntrinsicName = Intrinsic::getBaseName(CB.getIntrinsicID());
976 if (EVL.isPoison()) {
977 reportImmediateUB() << IntrinsicName
978 << " with poison explicit vector length.";
979 return AnyValue();
980 }
981 std::vector<AnyValue> EnabledMask(Mask.asAggregate());
982 const APInt &EVLInt = EVL.asInteger();
983 if (EVLInt.ugt(EnabledMask.size())) {
984 reportImmediateUB() << IntrinsicName << " with explicit vector length "
985 << EVLInt << " greater than the number of elements "
986 << EnabledMask.size() << '.';
987 return AnyValue();
988 }
989 for (uint64_t I = EVLInt.getZExtValue(); I != EnabledMask.size(); ++I)
990 EnabledMask[I] = AnyValue::boolean(false);
991
992 return callMaskedLoadStoreIntrinsic(CB, Ptr, std::move(EnabledMask),
993 std::move(Data), Mode, IsStore);
994 }
995
996 /// Implements llvm.experimental.vp.strided.{load,store} as a vp.gather or
997 /// vp.scatter of the pointers <Ptr, Ptr + Stride, Ptr + 2 * Stride, ...>,
998 /// where \p Stride is signed and the arithmetic wraps in the pointer index
999 /// type. Lane 0 is \p Ptr even if \p Stride is poison. The alignment, from
1000 /// an align attribute or else the element type's ABI alignment, only applies
1001 /// to \p Ptr, not to the other lanes' pointers.
1002 AnyValue callVPStridedLoadStoreIntrinsic(CallBase &CB, const AnyValue &Ptr,
1003 const AnyValue &Stride,
1004 const AnyValue &Mask,
1005 const AnyValue &EVL, AnyValue Data,
1006 bool IsStore) {
1007 const unsigned IndexBW =
1008 DL.getIndexTypeSizeInBits(CB.getArgOperand(IsStore ? 1 : 0)->getType());
1009 const AnyValue StrideIdx =
1011 std::vector<AnyValue> LanePtrs(Mask.asAggregate().size(), Ptr);
1012 for (auto [I, LanePtr] : drop_begin(enumerate(LanePtrs))) {
1013 AnyValue AccumulatedOffset = AnyValue::poison();
1014 LanePtr = Ctx.computeScaledPtrAdd(
1015 Ptr, StrideIdx,
1016 APInt(IndexBW, I, /*isSigned=*/false, /*implicitTrunc=*/true),
1017 GEPNoWrapFlags::none(), AccumulatedOffset);
1018 }
1019 return callVPLoadStoreIntrinsic(CB, std::move(LanePtrs), Mask, EVL,
1020 std::move(Data), MaskedAddrMode::PerLane,
1021 IsStore);
1022 }
1023
1024 /// Implements llvm.matrix.column.major.store. Column C of \p Data is stored
1025 /// as a <Rows x ElemTy> vector at an inbounds nuw GEP of C * \p Stride
1026 /// elements from \p Ptr.
1027 AnyValue callMatrixColumnMajorStoreIntrinsic(CallBase &CB,
1028 const AnyValue &Ptr,
1029 const AnyValue &Stride,
1030 const AnyValue &Data) {
1031 // TODO: Handle isvolatile argument.
1032 StringRef IntrinsicName = Intrinsic::getBaseName(CB.getIntrinsicID());
1033 const unsigned Rows =
1034 cast<ConstantInt>(CB.getArgOperand(4))->getZExtValue();
1035 const unsigned Cols =
1036 cast<ConstantInt>(CB.getArgOperand(5))->getZExtValue();
1037 if (Stride.isPoison()) {
1038 reportImmediateUB() << IntrinsicName << " with poison stride.";
1039 return AnyValue();
1040 }
1041 const APInt &StrideInt = Stride.asInteger();
1042 if (StrideInt.ult(Rows)) {
1043 reportImmediateUB() << IntrinsicName << " with stride "
1044 << StrideInt.getZExtValue()
1045 << " less than the number of rows " << Rows << '.';
1046 return AnyValue();
1047 }
1048
1050 auto *ColTy = FixedVectorType::get(ElemTy, Rows);
1051 const unsigned IndexBW =
1052 DL.getIndexTypeSizeInBits(CB.getArgOperand(1)->getType());
1053 const APInt StrideIdx = StrideInt.zextOrTrunc(IndexBW);
1054 const APInt ElemSize(IndexBW, Ctx.getEffectiveTypeAllocSize(ElemTy),
1055 /*isSigned=*/false, /*implicitTrunc=*/true);
1056 ArrayRef<AnyValue> Elems = Data.asAggregate();
1057 for (unsigned C = 0; C != Cols; ++C) {
1058 AnyValue AccumulatedOffset = AnyValue::poison();
1059 // C * Stride is part of the nuw GEP index: overflow yields poison.
1060 AnyValue ColIdx = mulNoWrap(StrideIdx,
1061 APInt(IndexBW, C, /*IsSigned=*/false,
1062 /*ImplicitTrunc=*/true),
1063 /*HasNSW=*/false, /*HasNUW=*/true);
1064 AnyValue ColPtr = Ctx.computeScaledPtrAdd(
1065 Ptr, ColIdx, ElemSize, GEPNoWrapFlags::all(), AccumulatedOffset);
1066 store(ColPtr, Align(1), Elems.slice(C * Rows, Rows).vec(), ColTy);
1067 }
1068 return AnyValue();
1069 }
1070
1071public:
1073 ArrayRef<AnyValue> Args, AnyValue &RetVal)
1074 : ExecutorBase(C, H), DL(Ctx.getDataLayout()),
1075 Lib(Ctx, Handler, DL, static_cast<ExecutorBase &>(*this)) {
1076 CallStack.emplace_back(F, /*CallSite=*/nullptr, /*LastFrame=*/nullptr, Args,
1077 RetVal, Ctx.getTLIImpl());
1078 }
1079
1081 if (auto *RV = RI.getReturnValue())
1082 CurrentFrame->RetVal = getValue(RV);
1083 else
1084 CurrentFrame->RetVal = AnyValue();
1086 if (!Handler.onInstructionExecuted(RI, None))
1087 setFailed();
1088 }
1089
1090 void visitUncondBrInst(UncondBrInst &BI) { jumpTo(BI, BI.getSuccessor()); }
1091
1093 switch (getValue(BI.getCondition()).asBoolean()) {
1094 case BooleanKind::True:
1095 jumpTo(BI, BI.getSuccessor(0));
1096 return;
1097 case BooleanKind::False:
1098 jumpTo(BI, BI.getSuccessor(1));
1099 return;
1101 reportImmediateUB() << "Branch on poison condition.";
1102 return;
1103 }
1104 }
1105
1107 auto &Cond = getValue(SI.getCondition());
1108 if (Cond.isPoison()) {
1109 reportImmediateUB() << "Switch on poison condition.";
1110 return;
1111 }
1112 for (auto &Case : SI.cases()) {
1113 if (Case.getCaseValue()->getValue() == Cond.asInteger()) {
1114 jumpTo(SI, Case.getCaseSuccessor());
1115 return;
1116 }
1117 }
1118 jumpTo(SI, SI.getDefaultDest());
1119 }
1120
1122 reportImmediateUB() << "Unreachable code.";
1123 }
1124
1126 if (isNoopInlineAsm(CI.getCalledOperand(), CI.getType())) {
1127 jumpTo(CI, CI.getDefaultDest());
1128 return;
1129 }
1130
1131 Handler.onUnrecognizedInstruction(CI);
1132 setFailed();
1133 }
1134
1136 auto &Target = getValue(IBI.getAddress());
1137 if (Target.isPoison()) {
1138 reportImmediateUB() << "Indirect branch on poison.";
1139 return;
1140 }
1141 if (BasicBlock *DestBB = Ctx.getTargetBlock(Target.asPointer())) {
1142 if (any_of(IBI.successors(),
1143 [DestBB](BasicBlock *Succ) { return Succ == DestBB; }))
1144 jumpTo(IBI, DestBB);
1145 else
1146 reportImmediateUB() << "Indirect branch on unlisted target BB.";
1147
1148 return;
1149 }
1150 reportImmediateUB() << "Indirect branch on invalid target BB.";
1151 }
1152
1154 if (hasProgramExited())
1155 return;
1156
1157 auto &CB = cast<CallBase>(*CurrentFrame->PC);
1158 if (CB.doesNotReturn() || (CurrentFrame->ResolvedCallee &&
1159 CurrentFrame->ResolvedCallee->doesNotReturn()))
1160 reportImmediateUB() << "Return from a noreturn function/callsite.";
1161
1162 AnyValue &RetVal = CurrentFrame->CalleeRetVal;
1163 if (Function *Oracle = getSpeculativeLoadOracle(CB)) {
1164 // RetVal is the oracle's result; use it to complete the load.
1165 handleAttributes(Oracle->getReturnType(), RetVal, AttributeSet(),
1166 Oracle->getAttributes().getRetAttrs());
1167 RetVal =
1168 callSpeculativeLoadIntrinsic(CB, CurrentFrame->CalleeArgs[0], RetVal);
1169 if (hasProgramExited())
1170 return;
1171 }
1172 CurrentFrame->CalleeArgs.clear();
1173 if (Type *RetTy = CB.getType(); !RetTy->isVoidTy()) {
1174 // Handle attributes on the return value (Attributes from resolved callee
1175 // should be applied if available).
1176 AttributeSet AttrsAtCallSite = CB.getRetAttributes();
1177 AttributeSet AttrsAtCallee =
1178 CurrentFrame->ResolvedCallee->getAttributes().getRetAttrs();
1179 if (auto *FPMO = dyn_cast<FPMathOperator>(&CB)) {
1180 if (FastMathFlags FMF = FPMO->getFastMathFlags(); FMF.any())
1181 RetVal = handleFMFFlags(std::move(RetVal), FMF, /*IsInput=*/false);
1182 }
1183 handleAttributes(RetTy, RetVal, AttrsAtCallSite, AttrsAtCallee);
1184 handleMetadata(RetTy, RetVal, CB);
1185 }
1186 if (CurrentFrame->HasInaccessibleStackObjects) {
1188 CurrentFrame->HasInaccessibleStackObjects = false;
1189 }
1190 setResult(CB, std::move(RetVal));
1191
1192 for (auto &ByValArg : CurrentFrame->CalleeByValArgs)
1193 Ctx.free(*ByValArg);
1194 CurrentFrame->CalleeByValArgs.clear();
1195
1196 if (auto *II = dyn_cast<InvokeInst>(&CB))
1197 jumpTo(*II, II->getNormalDest());
1198 else if (CurrentFrame->State == FrameState::Pending)
1199 ++CurrentFrame->PC;
1200 }
1201
1202 AnyValue computeDivRem(unsigned Opcode, const AnyValue &LHS,
1203 const AnyValue &RHS, bool IsExact = false) {
1204 const bool IsSigned =
1205 Opcode == Instruction::SDiv || Opcode == Instruction::SRem;
1206 // Priority: Immediate UB > poison > normal value.
1207 if (RHS.isPoison()) {
1208 reportImmediateUB() << "Division by zero (refine RHS to 0).";
1209 return AnyValue::poison();
1210 }
1211 const APInt &RHSVal = RHS.asInteger();
1212 if (RHSVal.isZero()) {
1213 reportImmediateUB() << "Division by zero.";
1214 return AnyValue::poison();
1215 }
1216 if (LHS.isPoison()) {
1217 if (IsSigned && RHSVal.isAllOnes())
1219 << "Signed division overflow (refine LHS to INT_MIN).";
1220 return AnyValue::poison();
1221 }
1222 const APInt &LHSVal = LHS.asInteger();
1223 if (IsSigned && LHSVal.isMinSignedValue() && RHSVal.isAllOnes()) {
1224 if (Opcode == Instruction::SRem)
1225 reportImmediateUB() << "Signed division overflow. LHS: " << LHSVal
1226 << ", RHS: " << RHSVal;
1227 else
1228 reportImmediateUB() << "Signed division overflow.";
1229 return AnyValue::poison();
1230 }
1231
1232 APInt Q, R;
1233 if (IsSigned)
1234 APInt::sdivrem(LHSVal, RHSVal, Q, R);
1235 else
1236 APInt::udivrem(LHSVal, RHSVal, Q, R);
1237 if (Opcode == Instruction::SRem || Opcode == Instruction::URem)
1238 return R;
1239 if (IsExact && !R.isZero())
1240 return AnyValue::poison();
1241 return Q;
1242 }
1243
1246 switch (IID) {
1247 case Intrinsic::vector_reduce_add:
1248 case Intrinsic::vector_reduce_mul:
1249 case Intrinsic::vector_reduce_and:
1250 case Intrinsic::vector_reduce_or:
1251 case Intrinsic::vector_reduce_xor:
1252 case Intrinsic::vector_reduce_smax:
1253 case Intrinsic::vector_reduce_smin:
1254 case Intrinsic::vector_reduce_umax:
1255 case Intrinsic::vector_reduce_umin: {
1256 std::optional<APInt> Res;
1257 for (const auto &V : Args[0].asAggregate()) {
1258 if (V.isPoison()) {
1259 Res.reset();
1260 break;
1261 }
1262 const auto &IntV = V.asInteger();
1263 if (!Res) {
1264 Res = IntV;
1265 continue;
1266 }
1267 switch (IID) {
1268 case Intrinsic::vector_reduce_add:
1269 *Res += IntV;
1270 break;
1271 case Intrinsic::vector_reduce_mul:
1272 *Res *= IntV;
1273 break;
1274 case Intrinsic::vector_reduce_and:
1275 *Res &= IntV;
1276 break;
1277 case Intrinsic::vector_reduce_or:
1278 *Res |= IntV;
1279 break;
1280 case Intrinsic::vector_reduce_xor:
1281 *Res ^= IntV;
1282 break;
1283 case Intrinsic::vector_reduce_smax:
1284 *Res = APIntOps::smax(*Res, IntV);
1285 break;
1286 case Intrinsic::vector_reduce_smin:
1287 *Res = APIntOps::smin(*Res, IntV);
1288 break;
1289 case Intrinsic::vector_reduce_umax:
1290 *Res = APIntOps::umax(*Res, IntV);
1291 break;
1292 case Intrinsic::vector_reduce_umin:
1293 *Res = APIntOps::umin(*Res, IntV);
1294 break;
1295 default:
1296 llvm_unreachable("Unexpected intrinsic ID");
1297 }
1298 }
1299 return Res ? *Res : AnyValue::poison();
1300 }
1301 case Intrinsic::vector_reduce_fadd:
1302 case Intrinsic::vector_reduce_fmul: {
1303 AnyValue Res = Args[0];
1304 for (const auto &V : Args[1].asAggregate()) {
1305 Res = visitFPBinOpWithResult(
1306 RetTy, FMF, Res, V,
1307 [IID](const APFloat &LHS, const APFloat &RHS) -> APFloat {
1308 return IID == Intrinsic::vector_reduce_fadd ? LHS + RHS
1309 : LHS * RHS;
1310 });
1311 if (Res.isPoison())
1312 return Res;
1313 }
1314 return Res;
1315 }
1316 case Intrinsic::vector_reduce_fmaximum:
1317 case Intrinsic::vector_reduce_fminimum:
1318 case Intrinsic::vector_reduce_fmaximumnum:
1319 case Intrinsic::vector_reduce_fminimumnum: {
1320 const auto DenormMode = getCurrentDenormalMode(RetTy);
1321 FastMathFlags InputFMF = FMF;
1322 // FP min/max reductions handle nsz during pairwise comparison.
1323 InputFMF.setNoSignedZeros(false);
1324 std::optional<APFloat> Res;
1325 for (const auto &V : Args[0].asAggregate()) {
1326 if (V.isPoison())
1327 return AnyValue::poison();
1328 const AnyValue ValidatedOp =
1329 handleFMFFlags(V, InputFMF, /*IsInput=*/true);
1330 if (ValidatedOp.isPoison())
1331 return AnyValue::poison();
1332 APFloat Op = handleDenormal(ValidatedOp.asFloat(), DenormMode.Input,
1333 /*IsInput=*/true);
1334 if (!Res) {
1335 Res = std::move(Op);
1336 continue;
1337 }
1338 *Res = applyFPMinMax(IID, *Res, Op, FMF.noSignedZeros());
1339 }
1340 assert(Res.has_value());
1341 const AnyValue ValidatedRes =
1342 handleFMFFlags(*Res, FMF, /*IsInput=*/false);
1343 if (ValidatedRes.isPoison())
1344 return AnyValue::poison();
1345 const APFloat FRes =
1346 handleDenormal(ValidatedRes.asFloat(), DenormMode.Output,
1347 /*IsInput=*/false);
1349 InputVec.reserve(Args[0].asAggregate().size());
1350 transform(
1351 Args[0].asAggregate(), std::back_inserter(InputVec),
1352 [](const AnyValue &V) -> const APFloat * { return &V.asFloat(); });
1353 return applyNaNPropagation(FRes, InputVec);
1354 }
1355 case Intrinsic::vector_reduce_fmax:
1356 case Intrinsic::vector_reduce_fmin: {
1357 const auto DenormMode = getCurrentDenormalMode(RetTy);
1358 FastMathFlags InputFMF = FMF;
1359 InputFMF.setNoSignedZeros(false);
1360 const auto &Vector = Args[0].asAggregate();
1361 SmallVector<APFloat, 8> InputFloats;
1363 InputFloats.reserve(Vector.size());
1364 InputVec.reserve(Vector.size());
1365 for (const auto &V : Vector) {
1366 if (V.isPoison())
1367 return AnyValue::poison();
1368 const AnyValue ValidatedOp =
1369 handleFMFFlags(V, InputFMF, /*IsInput=*/true);
1370 if (ValidatedOp.isPoison())
1371 return AnyValue::poison();
1372 InputFloats.push_back(handleDenormal(
1373 ValidatedOp.asFloat(), DenormMode.Input, /*IsInput=*/true));
1374 InputVec.push_back(&InputFloats.back());
1375 }
1376 assert(!InputVec.empty());
1377 SmallVector<APFloat, 8> Worklist(InputFloats);
1378 const bool HasSNaN =
1379 any_of(InputVec, [](const APFloat *V) { return V->isSignaling(); });
1380 while (Worklist.size() > 1) {
1381 size_t LHSIdx = 0;
1382 size_t RHSIdx = 1;
1383 if (HasSNaN) {
1384 LHSIdx = Ctx.getRandomUInt64() % Worklist.size();
1385 RHSIdx = Ctx.getRandomUInt64() % (Worklist.size() - 1);
1386 if (RHSIdx >= LHSIdx)
1387 ++RHSIdx;
1388 }
1389
1390 APFloat Res = applyFPMinMax(IID, Worklist[LHSIdx], Worklist[RHSIdx],
1391 FMF.noSignedZeros());
1392 if (LHSIdx < RHSIdx)
1393 std::swap(LHSIdx, RHSIdx);
1394 Worklist.erase(Worklist.begin() + LHSIdx);
1395 Worklist.erase(Worklist.begin() + RHSIdx);
1396 Worklist.push_back(std::move(Res));
1397 }
1398
1399 AnyValue ValidatedRes =
1400 handleFMFFlags(Worklist.front(), FMF, /*IsInput=*/false);
1401 if (ValidatedRes.isPoison())
1402 return AnyValue::poison();
1403 APFloat FRes = handleDenormal(ValidatedRes.asFloat(), DenormMode.Output,
1404 /*IsInput=*/false);
1405
1406 return applyNaNPropagation(FRes, InputVec);
1407 }
1408 default:
1409 llvm_unreachable("Unexpected vector reduction intrinsic ID");
1410 }
1411 }
1412
1414 bool IsZeroPoison, size_t Length) {
1415 const unsigned RetBW = RetTy->getIntegerBitWidth();
1416 if (!isUIntN(RetBW, Vec.size()))
1417 return AnyValue::poison();
1418 for (const AnyValue &V : Vec.take_front(Length))
1419 if (V.isPoison())
1420 return AnyValue::poison();
1421 for (size_t I = 0; I != Length; ++I)
1422 if (!Vec[I].asInteger().isZero())
1423 return APInt(RetBW, I);
1424 return IsZeroPoison ? AnyValue::poison() : AnyValue(APInt(RetBW, Length));
1425 }
1426
1428 Intrinsic::ID IID = CB.getIntrinsicID();
1429 Type *RetTy = CB.getType();
1430 const FastMathFlags FMF = CB.getFastMathFlagsOrNone();
1431
1432 switch (IID) {
1433 case Intrinsic::assume:
1434 switch (Args[0].asBoolean()) {
1435 case BooleanKind::True:
1436 for (unsigned Idx = 0; Idx < CB.getNumOperandBundles(); Idx++) {
1438 auto GetBundleArg = [&](uint32_t Offset) -> Value * {
1439 return OBU.Inputs[Offset];
1440 };
1441 // Bail out on "cold"()
1442 if (OBU.Inputs.empty())
1443 continue;
1444 Value *WasOnVal = GetBundleArg(0);
1445 const AnyValue &WasOn = getValue(WasOnVal);
1446 auto Kind = getBundleAttrFromOBU(OBU);
1447 switch (Kind) {
1448 case BundleAttr::Ignore:
1449 continue;
1450 case BundleAttr::NoUndef:
1451 if (violatesNoUndefAttr(WasOn))
1453 << "The value " << WasOn << " violates noundef assumption.";
1454 break;
1455 case BundleAttr::Range: {
1456 AnyValue V = WasOn;
1457 const APInt &Lower = cast<ConstantInt>(OBU.Inputs[1])->getValue();
1458 const APInt &Upper = cast<ConstantInt>(OBU.Inputs[2])->getValue();
1461 reportImmediateUB() << "The value " << WasOn << " violates range("
1462 << Lower << ", " << Upper << ") assumption.";
1463 break;
1464 }
1465 default:
1466 // Other assumptions on pointers or
1467 // unrecognized ones.
1468 break;
1469 }
1470 if (hasProgramExited())
1471 break;
1472
1473 // Bail out on unrecognized operand bundles.
1474 if (!WasOnVal->getType()->isPointerTy())
1475 continue;
1476 unsigned AS = WasOnVal->getType()->getPointerAddressSpace();
1477 if (WasOn.isPoison()) {
1478 reportImmediateUB() << "Assume on poison pointer.";
1479 break;
1480 }
1481 const Pointer &WasOnPtr = WasOn.asPointer();
1482 switch (Kind) {
1483 case BundleAttr::Align: {
1484 // Alignment assumptions should have 2 or 3 arguments.
1485 APInt Alignment = getIntNonPoison(getValue(GetBundleArg(1)));
1486 APInt CheckedAddr = WasOnPtr.address();
1487 if (OBU.Inputs.size() == 3) {
1488 APInt Offset = getIntNonPoison(getValue(GetBundleArg(2)));
1489 CheckedAddr -= Offset.sextOrTrunc(CheckedAddr.getBitWidth());
1490 }
1491 if (!Alignment.isPowerOf2()) {
1492 if (!CheckedAddr.isZero())
1493 reportImmediateUB() << "Assume on pointer " << WasOn
1494 << " with a nonzero adjusted address and a "
1495 "non-power-of-two alignment "
1496 << Alignment << '.';
1497 break;
1498 }
1499 if (CheckedAddr.countr_zero() < Alignment.logBase2())
1501 << "The pointer " << WasOn << " violates align(" << Alignment
1502 << ") assumption.";
1503 break;
1504 }
1505 case BundleAttr::NonNull:
1506 if (WasOnPtr.isNullPtr(AS, DL))
1508 << "The pointer " << WasOn << " violates nonnull assumption.";
1509 break;
1510 case BundleAttr::Dereferenceable:
1511 case BundleAttr::DereferenceableOrNull: {
1512 APInt DereferenceableBytes =
1513 getIntNonPoison(getValue(GetBundleArg(1)));
1514 // Only n > 0 implies that the pointer is dereferenceable.
1515 if (DereferenceableBytes.isZero())
1516 break;
1518 WasOn, DereferenceableBytes.getLimitedValue(),
1519 Kind == BundleAttr::DereferenceableOrNull, AS, Ctx))
1520 reportImmediateUB() << "The pointer " << WasOn << " violates "
1521 << (Kind == BundleAttr::DereferenceableOrNull
1522 ? "dereferenceable_or_null("
1523 : "dereferenceable(")
1524 << DereferenceableBytes << ") assumption.";
1525 break;
1526 }
1527 default:
1528 // TODO: handle other operand bundles like separate_storage.
1529 break;
1530 }
1531 }
1532 break;
1533 case BooleanKind::False:
1535 reportImmediateUB() << "Assume on false or poison condition.";
1536 break;
1537 }
1538 return AnyValue();
1539 case Intrinsic::lifetime_start:
1540 case Intrinsic::lifetime_end: {
1541 auto Ptr = Args[0];
1542 if (Ptr.isPoison())
1543 return AnyValue();
1544 auto *MO = Ctx.checkProvenance(Ptr.asPointer(),
1545 [](const Provenance &) { return true; });
1546 assert(MO && "Memory object accessed by lifetime intrinsic should be "
1547 "always valid.");
1548 if (MO->isInaccessible()) {
1549 reportImmediateUB() << "Try to access an inaccessible memory object: "
1550 << Ptr.asPointer() << ".";
1551 return AnyValue();
1552 }
1553 if (IID == Intrinsic::lifetime_start) {
1554 MO->setState(MemoryObjectState::Alive);
1555 fill(MO->getBytes(), Byte::undef());
1556 } else {
1557 fill(MO->getBytes(), Byte::poison());
1558 MO->setState(MemoryObjectState::Dead);
1559 }
1560 return AnyValue();
1561 }
1562 case Intrinsic::ssa_copy:
1563 case Intrinsic::expect:
1564 case Intrinsic::expect_with_probability:
1565 return Args[0];
1566 case Intrinsic::donothing:
1567 return AnyValue();
1568 case Intrinsic::vscale: {
1569 const unsigned BitWidth = RetTy->getScalarSizeInBits();
1570 const APInt VScale(64, Ctx.getVScale());
1571 if (!VScale.isIntN(BitWidth))
1572 return AnyValue::poison();
1573 return VScale.zextOrTrunc(BitWidth);
1574 }
1575 case Intrinsic::abs: {
1576 const bool IsIntMinPoison = getBooleanNonPoison(Args[1].asBoolean());
1577 return visitIntUnOpWithResult(
1578 RetTy, Args[0], [&](const APInt &Operand) -> AnyValue {
1579 if (IsIntMinPoison && Operand.isMinSignedValue())
1580 return AnyValue::poison();
1581 return Operand.abs();
1582 });
1583 }
1584 case Intrinsic::smax: {
1585 return visitIntBinOpWithResult(
1586 RetTy, Args[0], Args[1],
1587 [](const APInt &LHS, const APInt &RHS) -> AnyValue {
1588 return APIntOps::smax(LHS, RHS);
1589 });
1590 }
1591 case Intrinsic::smin: {
1592 return visitIntBinOpWithResult(
1593 RetTy, Args[0], Args[1],
1594 [](const APInt &LHS, const APInt &RHS) -> AnyValue {
1595 return APIntOps::smin(LHS, RHS);
1596 });
1597 }
1598 case Intrinsic::umax: {
1599 return visitIntBinOpWithResult(
1600 RetTy, Args[0], Args[1],
1601 [](const APInt &LHS, const APInt &RHS) -> AnyValue {
1602 return APIntOps::umax(LHS, RHS);
1603 });
1604 }
1605 case Intrinsic::umin: {
1606 return visitIntBinOpWithResult(
1607 RetTy, Args[0], Args[1],
1608 [](const APInt &LHS, const APInt &RHS) -> AnyValue {
1609 return APIntOps::umin(LHS, RHS);
1610 });
1611 }
1612 case Intrinsic::scmp:
1613 case Intrinsic::ucmp: {
1614 const unsigned BitWidth = RetTy->getScalarSizeInBits();
1615 return visitIntBinOpWithResult(
1616 RetTy, Args[0], Args[1],
1617 [&](const APInt &LHS, const APInt &RHS) -> AnyValue {
1618 if (LHS == RHS)
1619 return APInt::getZero(BitWidth);
1620 if (IID == Intrinsic::scmp)
1621 return LHS.slt(RHS) ? APInt::getAllOnes(BitWidth)
1622 : APInt(BitWidth, 1);
1623 return LHS.ult(RHS) ? APInt::getAllOnes(BitWidth)
1624 : APInt(BitWidth, 1);
1625 });
1626 }
1627 case Intrinsic::bitreverse: {
1628 return visitIntUnOpWithResult(RetTy, Args[0],
1629 [](const APInt &Operand) -> AnyValue {
1630 return Operand.reverseBits();
1631 });
1632 }
1633 case Intrinsic::bswap: {
1634 return visitIntUnOpWithResult(
1635 RetTy, Args[0],
1636 [](const APInt &Operand) -> AnyValue { return Operand.byteSwap(); });
1637 }
1638 case Intrinsic::ctpop: {
1639 return visitIntUnOpWithResult(
1640 RetTy, Args[0], [](const APInt &Operand) -> AnyValue {
1641 return APInt(Operand.getBitWidth(), Operand.popcount());
1642 });
1643 }
1644 case Intrinsic::ctlz:
1645 case Intrinsic::cttz: {
1646 const bool IsZeroPoison = getBooleanNonPoison(Args[1].asBoolean());
1647 return visitIntUnOpWithResult(
1648 RetTy, Args[0], [&](const APInt &Operand) -> AnyValue {
1649 if (IsZeroPoison && Operand.isZero())
1650 return AnyValue::poison();
1651 if (IID == Intrinsic::ctlz)
1652 return APInt(Operand.getBitWidth(), Operand.countl_zero());
1653 return APInt(Operand.getBitWidth(), Operand.countr_zero());
1654 });
1655 }
1656 case Intrinsic::fshl:
1657 case Intrinsic::fshr: {
1658 return visitIntTriOpWithResult(
1659 RetTy, Args[0], Args[1], Args[2],
1660 [IID](const APInt &Op1, const APInt &Op2,
1661 const APInt &Op3) -> AnyValue {
1662 const unsigned BitWidth = Op1.getBitWidth();
1663 const uint64_t ShiftAmount = Op3.urem(BitWidth);
1664 const bool IsFShr = IID == Intrinsic::fshr;
1665 if (ShiftAmount == 0)
1666 return IsFShr ? Op2 : Op1;
1667 const uint64_t LShrAmount =
1668 IsFShr ? ShiftAmount : BitWidth - ShiftAmount;
1669 const uint64_t ShlAmount =
1670 !IsFShr ? ShiftAmount : BitWidth - ShiftAmount;
1671 return Op1.shl(ShlAmount) | Op2.lshr(LShrAmount);
1672 });
1673 }
1674 case Intrinsic::clmul: {
1675 return visitIntBinOpWithResult(
1676 RetTy, Args[0], Args[1],
1677 [](const APInt &LHS, const APInt &RHS) -> AnyValue {
1678 return APIntOps::clmul(LHS, RHS);
1679 });
1680 }
1681 case Intrinsic::sadd_with_overflow:
1682 case Intrinsic::uadd_with_overflow:
1683 case Intrinsic::ssub_with_overflow:
1684 case Intrinsic::usub_with_overflow:
1685 case Intrinsic::smul_with_overflow:
1686 case Intrinsic::umul_with_overflow: {
1687 return visitOverflowIntBinOpWithResult(
1688 RetTy, Args[0], Args[1],
1689 [IID](const APInt &LHS, const APInt &RHS) -> std::pair<APInt, bool> {
1690 APInt Res;
1691 bool Overflow = false;
1692 switch (IID) {
1693 case Intrinsic::sadd_with_overflow:
1694 Res = LHS.sadd_ov(RHS, Overflow);
1695 break;
1696 case Intrinsic::uadd_with_overflow:
1697 Res = LHS.uadd_ov(RHS, Overflow);
1698 break;
1699 case Intrinsic::ssub_with_overflow:
1700 Res = LHS.ssub_ov(RHS, Overflow);
1701 break;
1702 case Intrinsic::usub_with_overflow:
1703 Res = LHS.usub_ov(RHS, Overflow);
1704 break;
1705 case Intrinsic::smul_with_overflow:
1706 Res = LHS.smul_ov(RHS, Overflow);
1707 break;
1708 case Intrinsic::umul_with_overflow:
1709 Res = LHS.umul_ov(RHS, Overflow);
1710 break;
1711 default:
1712 llvm_unreachable("Unexpected intrinsic ID");
1713 }
1714 return {Res, Overflow};
1715 });
1716 }
1717 case Intrinsic::sadd_sat:
1718 case Intrinsic::uadd_sat:
1719 case Intrinsic::ssub_sat:
1720 case Intrinsic::usub_sat:
1721 case Intrinsic::sshl_sat:
1722 case Intrinsic::ushl_sat: {
1723 return visitIntBinOpWithResult(
1724 RetTy, Args[0], Args[1],
1725 [IID](const APInt &LHS, const APInt &RHS) -> AnyValue {
1726 switch (IID) {
1727 case Intrinsic::sadd_sat:
1728 return LHS.sadd_sat(RHS);
1729 case Intrinsic::uadd_sat:
1730 return LHS.uadd_sat(RHS);
1731 case Intrinsic::ssub_sat:
1732 return LHS.ssub_sat(RHS);
1733 case Intrinsic::usub_sat:
1734 return LHS.usub_sat(RHS);
1735 case Intrinsic::sshl_sat: {
1736 if (RHS.uge(LHS.getBitWidth()))
1737 return AnyValue::poison();
1738 return LHS.sshl_sat(RHS);
1739 }
1740 case Intrinsic::ushl_sat: {
1741 if (RHS.uge(LHS.getBitWidth()))
1742 return AnyValue::poison();
1743 return LHS.ushl_sat(RHS);
1744 }
1745 default:
1746 llvm_unreachable("Unexpected intrinsic ID");
1747 }
1748 });
1749 }
1750 case Intrinsic::smulh:
1751 case Intrinsic::umulh:
1752 return visitIntBinOpWithResult(
1753 RetTy, Args[0], Args[1],
1754 [IID](const APInt &LHS, const APInt &RHS) -> AnyValue {
1755 return IID == Intrinsic::smulh ? APIntOps::mulhs(LHS, RHS)
1757 });
1758 case Intrinsic::pdep:
1759 case Intrinsic::pext:
1760 return visitIntBinOpWithResult(
1761 RetTy, Args[0], Args[1],
1762 [IID](const APInt &Val, const APInt &Mask) -> AnyValue {
1763 return IID == Intrinsic::pdep ? APIntOps::pdep(Val, Mask)
1764 : APIntOps::pext(Val, Mask);
1765 });
1766 case Intrinsic::vector_reduce_add:
1767 case Intrinsic::vector_reduce_mul:
1768 case Intrinsic::vector_reduce_and:
1769 case Intrinsic::vector_reduce_or:
1770 case Intrinsic::vector_reduce_xor:
1771 case Intrinsic::vector_reduce_smax:
1772 case Intrinsic::vector_reduce_smin:
1773 case Intrinsic::vector_reduce_umax:
1774 case Intrinsic::vector_reduce_umin:
1775 return callVectorReduction(RetTy, FMF, IID, Args);
1776 case Intrinsic::vector_insert: {
1777 assert(!Args[2].isPoison() &&
1778 "Verifier should reject poison vector_insert immarg.");
1779 const auto &Vec = Args[0].asAggregate();
1780 const auto &SubVec = Args[1].asAggregate();
1781 const auto &Idx = Args[2].asInteger();
1782 auto EC =
1783 cast<VectorType>(CB.getArgOperand(1)->getType())->getElementCount();
1784 const uint64_t RawOffset = Idx.getZExtValue();
1785 const uint32_t MinSize = EC.getKnownMinValue();
1786 assert(RawOffset % MinSize == 0 &&
1787 "Verifier should reject misaligned vector_insert index.");
1788 const uint64_t Chunk = RawOffset / MinSize;
1789 const uint64_t EVL = Ctx.getEVL(EC);
1790 if (Chunk > std::numeric_limits<uint64_t>::max() / EVL)
1791 return AnyValue::getPoisonValue(Ctx, RetTy);
1792 const uint64_t Offset = Chunk * EVL;
1793 if (Offset > Vec.size() || SubVec.size() > Vec.size() - Offset)
1794 return AnyValue::getPoisonValue(Ctx, RetTy);
1795 std::vector<AnyValue> Res;
1796 Res.reserve(Vec.size());
1797 for (size_t I = 0; I != Vec.size(); ++I) {
1798 if (I >= Offset && I < Offset + SubVec.size())
1799 Res.push_back(SubVec[I - Offset]);
1800 else
1801 Res.push_back(Vec[I]);
1802 }
1803 return std::move(Res);
1804 }
1805 case Intrinsic::vector_extract: {
1806 assert(!Args[1].isPoison() &&
1807 "Verifier should reject poison vector_extract immarg.");
1808 const auto &Vec = Args[0].asAggregate();
1809 const auto &Idx = Args[1].asInteger();
1810 auto EC = cast<VectorType>(RetTy)->getElementCount();
1811 const uint64_t RawOffset = Idx.getZExtValue();
1812 const uint32_t MinSize = EC.getKnownMinValue();
1813 assert(RawOffset % MinSize == 0 &&
1814 "Verifier should reject misaligned vector_extract index.");
1815 const uint64_t Chunk = RawOffset / MinSize;
1816 const uint64_t EVL = Ctx.getEVL(EC);
1817 if (Chunk > std::numeric_limits<uint64_t>::max() / EVL)
1818 return AnyValue::getPoisonValue(Ctx, RetTy);
1819 const uint64_t Offset = Chunk * EVL;
1820 if (Offset > Vec.size() || EVL > Vec.size() - Offset)
1821 return AnyValue::getPoisonValue(Ctx, RetTy);
1822 return std::vector<AnyValue>(Vec.begin() + Offset,
1823 Vec.begin() + Offset + EVL);
1824 }
1825 case Intrinsic::vector_reverse: {
1826 auto Vec = Args[0].asAggregate();
1827 std::reverse(Vec.begin(), Vec.end());
1828 return std::move(Vec);
1829 }
1830 case Intrinsic::vector_deinterleave2:
1831 case Intrinsic::vector_deinterleave3:
1832 case Intrinsic::vector_deinterleave4:
1833 case Intrinsic::vector_deinterleave5:
1834 case Intrinsic::vector_deinterleave6:
1835 case Intrinsic::vector_deinterleave7:
1836 case Intrinsic::vector_deinterleave8: {
1837 const unsigned Factor = getDeinterleaveIntrinsicFactor(IID);
1838 if (Factor == 0)
1839 llvm_unreachable("Unexpected intrinsic ID");
1840 const auto &Vec = Args[0].asAggregate();
1841 std::vector<std::vector<AnyValue>> Res(Factor);
1842 for (auto &SubVec : Res)
1843 SubVec.reserve(Vec.size() / Factor);
1844 for (size_t I = 0, E = Vec.size(); I != E; ++I)
1845 Res[I % Factor].push_back(Vec[I]);
1846
1847 std::vector<AnyValue> AggRes;
1848 AggRes.reserve(Factor);
1849 for (auto &SubVec : Res)
1850 AggRes.emplace_back(std::move(SubVec));
1851 return AnyValue(std::move(AggRes));
1852 }
1853 case Intrinsic::vector_interleave2:
1854 case Intrinsic::vector_interleave3:
1855 case Intrinsic::vector_interleave4:
1856 case Intrinsic::vector_interleave5:
1857 case Intrinsic::vector_interleave6:
1858 case Intrinsic::vector_interleave7:
1859 case Intrinsic::vector_interleave8: {
1860 const unsigned Factor = getInterleaveIntrinsicFactor(IID);
1861 if (Factor == 0)
1862 llvm_unreachable("Unexpected intrinsic ID");
1863 const auto &Vec = Args[0].asAggregate();
1864 std::vector<AnyValue> Res;
1865 Res.reserve(Vec.size() * Factor);
1866 for (size_t I = 0, E = Vec.size(); I != E; ++I) {
1867 for (unsigned J = 0; J != Factor; ++J)
1868 Res.push_back(Args[J].asAggregate()[I]);
1869 }
1870 return std::move(Res);
1871 }
1872 case Intrinsic::vector_splice_left: {
1873 if (Args[2].isPoison())
1874 return AnyValue::getPoisonValue(Ctx, RetTy);
1875 const auto &LHS = Args[0].asAggregate();
1876 const auto &RHS = Args[1].asAggregate();
1877 const auto &Off = Args[2].asInteger();
1878 const size_t Len = LHS.size();
1879 if (Off.ugt(Len))
1880 return AnyValue::getPoisonValue(Ctx, RetTy);
1881 uint64_t Offset = Off.getZExtValue();
1882 std::vector<AnyValue> Res;
1883 Res.reserve(Len);
1884 for (size_t I = 0; I != Len; ++I) {
1885 size_t Pos = I + Offset;
1886 Res.push_back(Pos < Len ? LHS[Pos] : RHS[Pos - Len]);
1887 }
1888 return std::move(Res);
1889 }
1890 case Intrinsic::vector_splice_right: {
1891 if (Args[2].isPoison())
1892 return AnyValue::getPoisonValue(Ctx, RetTy);
1893 const auto &LHS = Args[0].asAggregate();
1894 const auto &RHS = Args[1].asAggregate();
1895 const auto &Off = Args[2].asInteger();
1896 const size_t Len = LHS.size();
1897 if (Off.ugt(Len))
1898 return AnyValue::getPoisonValue(Ctx, RetTy);
1899 uint64_t Offset = Len - Off.getZExtValue();
1900 std::vector<AnyValue> Res;
1901 Res.reserve(Len);
1902 for (size_t I = 0; I != Len; ++I) {
1903 size_t Pos = I + Offset;
1904 Res.push_back(Pos < Len ? LHS[Pos] : RHS[Pos - Len]);
1905 }
1906 return std::move(Res);
1907 }
1908 case Intrinsic::stepvector: {
1909 std::vector<AnyValue> Res;
1910 const uint32_t Len =
1911 Ctx.getEVL(cast<VectorType>(RetTy)->getElementCount());
1912 const unsigned BitWidth = RetTy->getScalarSizeInBits();
1913 Res.reserve(Len);
1914 for (uint64_t I = 0; I != Len; ++I) {
1915 Res.push_back(
1916 APInt(BitWidth, I, /*IsSigned=*/false, /*ImplicitTrunc=*/true));
1917 }
1918 return std::move(Res);
1919 }
1920 case Intrinsic::get_active_lane_mask: {
1921 if (Args[0].isPoison() || Args[1].isPoison())
1922 return AnyValue::getPoisonValue(Ctx, RetTy);
1923 // Lane I is active iff Base + I < N without wrapping, i.e. iff Base < N
1924 // and I < N - Base, where N - Base cannot wrap.
1925 const APInt &Base = Args[0].asInteger();
1926 const APInt &N = Args[1].asInteger();
1927 const uint32_t Len =
1928 Ctx.getEVL(cast<VectorType>(RetTy)->getElementCount());
1929 const uint32_t NumActive =
1930 Base.uge(N) ? 0 : (N - Base).getLimitedValue(Len);
1931 std::vector<AnyValue> Res;
1932 Res.reserve(Len);
1933 Res.insert(Res.end(), NumActive, AnyValue::boolean(true));
1934 Res.insert(Res.end(), Len - NumActive, AnyValue::boolean(false));
1935 return std::move(Res);
1936 }
1937 case Intrinsic::mask_beforefirst: {
1938 const auto &Mask = Args[0].asAggregate();
1939 std::vector<AnyValue> Res;
1940 Res.reserve(Mask.size());
1941 bool SeenActive = false;
1942 for (const AnyValue &Lane : Mask) {
1943 switch (Lane.asBoolean()) {
1944 case BooleanKind::True:
1945 SeenActive = true;
1946 break;
1947 case BooleanKind::False:
1948 break;
1950 return AnyValue::getPoisonValue(Ctx, RetTy);
1951 }
1952 Res.push_back(AnyValue::boolean(!SeenActive));
1953 }
1954 return std::move(Res);
1955 }
1956 case Intrinsic::vector_reduce_fadd:
1957 case Intrinsic::vector_reduce_fmul:
1958 case Intrinsic::vector_reduce_fmaximum:
1959 case Intrinsic::vector_reduce_fminimum:
1960 case Intrinsic::vector_reduce_fmaximumnum:
1961 case Intrinsic::vector_reduce_fminimumnum:
1962 case Intrinsic::vector_reduce_fmax:
1963 case Intrinsic::vector_reduce_fmin:
1964 return callVectorReduction(RetTy, FMF, IID, Args);
1965 case Intrinsic::fabs: {
1966 return visitBitwiseFPUnOpWithResult(
1967 RetTy, FMF, Args[0],
1968 [](const APFloat &Operand) -> APFloat { return abs(Operand); });
1969 }
1970 case Intrinsic::fma: {
1971 return visitFPTriOpWithResult(
1972 RetTy, FMF, Args[0], Args[1], Args[2],
1973 [](const APFloat &Op1, const APFloat &Op2,
1974 const APFloat &Op3) -> APFloat {
1975 auto Res = Op1;
1977 return Res;
1978 });
1979 }
1980 case Intrinsic::fmuladd: {
1981 return visitFPTriOpWithResult(
1982 RetTy, FMF, Args[0], Args[1], Args[2],
1983 [&](const APFloat &Op1, const APFloat &Op2,
1984 const APFloat &Op3) -> APFloat {
1985 if (Ctx.fuseMultiplyAdd()) {
1986 auto Res = Op1;
1988 return Res;
1989 }
1990 return Op1 * Op2 + Op3;
1991 });
1992 }
1993 case Intrinsic::is_fpclass: {
1994 const FPClassTest Mask =
1995 static_cast<FPClassTest>(Args[1].asInteger().getZExtValue());
1996 return computeUnOp(RetTy, Args[0], [&](const AnyValue &Op) -> AnyValue {
1997 if (Op.isPoison())
1998 return AnyValue::poison();
1999 return AnyValue::boolean(
2000 static_cast<bool>(Op.asFloat().classify() & Mask));
2001 });
2002 }
2003 case Intrinsic::copysign: {
2004 return computeBinOp(
2005 RetTy, Args[0], Args[1],
2006 [&](const AnyValue &LHS, const AnyValue &RHS) -> AnyValue {
2007 if (LHS.isPoison() || RHS.isPoison())
2008 return AnyValue::poison();
2009 const AnyValue ValidatedLHS =
2010 handleFMFFlags(LHS, FMF, /*IsInput=*/true);
2011 const AnyValue ValidatedRHS =
2012 handleFMFFlags(RHS, FMF, /*IsInput=*/true);
2013 if (ValidatedLHS.isPoison() || ValidatedRHS.isPoison())
2014 return AnyValue::poison();
2015
2016 return handleFMFFlags(APFloat::copySign(ValidatedLHS.asFloat(),
2017 ValidatedRHS.asFloat()),
2018 FMF, /*IsInput=*/false);
2019 });
2020 }
2021 case Intrinsic::maxnum:
2022 case Intrinsic::minnum:
2023 case Intrinsic::maximum:
2024 case Intrinsic::minimum:
2025 case Intrinsic::maximumnum:
2026 case Intrinsic::minimumnum: {
2027 FastMathFlags InputFMF = FMF;
2028 InputFMF.setNoSignedZeros(false);
2029 return visitFPBinOpWithResult(
2030 RetTy, InputFMF, Args[0], Args[1],
2031 [&](const APFloat &LHS, const APFloat &RHS) -> APFloat {
2032 return applyFPMinMax(IID, LHS, RHS, FMF.noSignedZeros());
2033 });
2034 }
2035 case Intrinsic::fptosi_sat:
2036 case Intrinsic::fptoui_sat: {
2037 const auto BitWidth = RetTy->getScalarSizeInBits();
2038 return computeUnOp(RetTy, Args[0], [&](const AnyValue &Op) -> AnyValue {
2039 if (Op.isPoison())
2040 return AnyValue::poison();
2041 const APFloat &Operand = Op.asFloat();
2042 APSInt V(BitWidth, IID == Intrinsic::fptoui_sat);
2043 [[maybe_unused]] bool IsExact;
2044 Operand.convertToInteger(V, APFloat::rmTowardZero, &IsExact);
2045 return V;
2046 });
2047 }
2048 case Intrinsic::memcpy:
2049 case Intrinsic::memcpy_inline:
2050 case Intrinsic::memmove:
2051 // TODO: Handle isvolatile argument.
2052 executeMemTransfer(Args[0], Args[1], Args[2], IID,
2053 /*IsLibCall=*/false);
2054 return AnyValue();
2055 case Intrinsic::memset:
2056 case Intrinsic::memset_inline:
2057 executeMemSet(Args[0], Args[1], Args[2]);
2058 return AnyValue();
2059 case Intrinsic::speculative_load:
2060 assert(!getSpeculativeLoadOracle(CB) &&
2061 "oracle form must be handled earlier");
2062 return callSpeculativeLoadIntrinsic(CB, Args[0], Args[2]);
2063 case Intrinsic::masked_load:
2064 return callMaskedLoadStoreIntrinsic(CB, Args[0], Args[1], Args[2],
2065 MaskedAddrMode::Consecutive,
2066 /*IsStore=*/false);
2067 case Intrinsic::masked_store:
2068 return callMaskedLoadStoreIntrinsic(CB, Args[1], Args[2], Args[0],
2069 MaskedAddrMode::Consecutive,
2070 /*IsStore=*/true);
2071 case Intrinsic::masked_gather:
2072 return callMaskedLoadStoreIntrinsic(CB, Args[0], Args[1], Args[2],
2073 MaskedAddrMode::PerLane,
2074 /*IsStore=*/false);
2075 case Intrinsic::masked_scatter:
2076 return callMaskedLoadStoreIntrinsic(CB, Args[1], Args[2], Args[0],
2077 MaskedAddrMode::PerLane,
2078 /*IsStore=*/true);
2079 case Intrinsic::masked_expandload:
2080 return callMaskedLoadStoreIntrinsic(CB, Args[0], Args[1], Args[2],
2081 MaskedAddrMode::Compressed,
2082 /*IsStore=*/false);
2083 case Intrinsic::masked_compressstore:
2084 return callMaskedLoadStoreIntrinsic(CB, Args[1], Args[2], Args[0],
2085 MaskedAddrMode::Compressed,
2086 /*IsStore=*/true);
2087 case Intrinsic::vp_load:
2088 return callVPLoadStoreIntrinsic(
2089 CB, withVPDefaultAlign(CB, Args[0], RetTy), Args[1], Args[2],
2090 AnyValue::getPoisonValue(Ctx, RetTy), MaskedAddrMode::Consecutive,
2091 /*IsStore=*/false);
2092 case Intrinsic::vp_store:
2093 return callVPLoadStoreIntrinsic(
2094 CB, withVPDefaultAlign(CB, Args[1], CB.getArgOperand(0)->getType()),
2095 Args[2], Args[3], Args[0], MaskedAddrMode::Consecutive,
2096 /*IsStore=*/true);
2097 case Intrinsic::vp_gather:
2098 return callVPLoadStoreIntrinsic(
2099 CB, withVPDefaultAlign(CB, Args[0], RetTy->getScalarType()), Args[1],
2100 Args[2], AnyValue::getPoisonValue(Ctx, RetTy),
2101 MaskedAddrMode::PerLane,
2102 /*IsStore=*/false);
2103 case Intrinsic::vp_scatter:
2104 return callVPLoadStoreIntrinsic(
2105 CB,
2106 withVPDefaultAlign(CB, Args[1],
2107 CB.getArgOperand(0)->getType()->getScalarType()),
2108 Args[2], Args[3], Args[0], MaskedAddrMode::PerLane,
2109 /*IsStore=*/true);
2110 case Intrinsic::experimental_vp_strided_load:
2111 return callVPStridedLoadStoreIntrinsic(
2112 CB, withVPDefaultAlign(CB, Args[0], RetTy->getScalarType()), Args[1],
2113 Args[2], Args[3], AnyValue::getPoisonValue(Ctx, RetTy),
2114 /*IsStore=*/false);
2115 case Intrinsic::experimental_vp_strided_store:
2116 return callVPStridedLoadStoreIntrinsic(
2117 CB,
2118 withVPDefaultAlign(CB, Args[1],
2119 CB.getArgOperand(0)->getType()->getScalarType()),
2120 Args[2], Args[3], Args[4], Args[0],
2121 /*IsStore=*/true);
2122 case Intrinsic::vp_merge: {
2123 std::vector<AnyValue> Cond(Args[0].asAggregate());
2124 const AnyValue &EVL = Args[3];
2125 if (EVL.isPoison() || EVL.asInteger().ugt(Cond.size()))
2126 return AnyValue::getPoisonValue(Ctx, RetTy);
2127 for (uint64_t I = EVL.asInteger().getZExtValue(); I != Cond.size(); ++I)
2128 Cond[I] = AnyValue::boolean(false);
2129 return computeSelect(std::move(Cond), Args[1], Args[2], RetTy, FMF);
2130 }
2131 case Intrinsic::matrix_transpose: {
2132 const auto &Vec = Args[0].asAggregate();
2133 const unsigned Rows =
2134 cast<ConstantInt>(CB.getArgOperand(1))->getZExtValue();
2135 const unsigned Cols =
2136 cast<ConstantInt>(CB.getArgOperand(2))->getZExtValue();
2137 // Column I of the result is row I of the column-major input.
2138 std::vector<AnyValue> Res;
2139 Res.reserve(Vec.size());
2140 for (unsigned I = 0; I != Rows; ++I)
2141 for (unsigned J = 0; J != Cols; ++J)
2142 Res.push_back(Vec[J * Rows + I]);
2143 return std::move(Res);
2144 }
2145 case Intrinsic::matrix_column_major_store:
2146 return callMatrixColumnMajorStoreIntrinsic(CB, Args[1], Args[2], Args[0]);
2147 case Intrinsic::experimental_noalias_scope_decl:
2148 // FIXME: Not implemented yet. Currently it acts as a noop.
2149 return AnyValue();
2150 case Intrinsic::experimental_cttz_elts: {
2151 const auto &Vec = Args[0].asAggregate();
2152 return countTrailingZeroElements(RetTy, Vec, Args[1].asInteger().isOne(),
2153 Vec.size());
2154 }
2155 case Intrinsic::experimental_get_vector_length: {
2156 auto *VFC = cast<ConstantInt>(CB.getArgOperand(1));
2157 auto *ScalableC = cast<ConstantInt>(CB.getArgOperand(2));
2158
2159 if (Args[0].isPoison())
2160 return AnyValue::poison();
2161
2162 const APInt &Cnt = Args[0].asInteger();
2163 uint64_t MaxLanes = VFC->getZExtValue();
2164 if (ScalableC->isOne())
2165 MaxLanes *= Ctx.getVScale();
2166
2167 uint64_t Res = 0;
2168 if (!Cnt.isZero()) {
2169 if (Cnt.getActiveBits() <= 64 && Cnt.getZExtValue() <= MaxLanes) {
2170 Res = Cnt.getZExtValue();
2171 } else {
2172 APInt Max(Cnt.getBitWidth(), MaxLanes);
2173 APInt NumIters =
2175 uint64_t Lower =
2177 .getZExtValue();
2178 uint64_t Range = MaxLanes - Lower + 1;
2179 Res = Lower + Ctx.getRandomUInt64() % Range;
2180 }
2181 }
2182
2183 if (isIntN(32, Res))
2184 return APInt(32, Res);
2185 return AnyValue::poison();
2186 }
2187
2188 case Intrinsic::experimental_vector_extract_last_active: {
2189 const auto &Data = Args[0].asAggregate();
2190 const AnyValue &Mask = Args[1];
2191
2192 for (size_t I = Data.size(); I != 0; --I) {
2193 switch (getMaskLane(Mask, I - 1)) {
2194 case BooleanKind::True:
2195 return Data[I - 1];
2196 case BooleanKind::False:
2197 break;
2199 return AnyValue::getPoisonValue(Ctx, RetTy);
2200 }
2201 }
2202
2203 return Args[2];
2204 }
2205
2206 case Intrinsic::experimental_vector_compress: {
2207 const auto &Val = Args[0].asAggregate();
2208 const AnyValue &Mask = Args[1];
2209 const auto &Passthru = Args[2].asAggregate();
2210
2211 std::vector<AnyValue> Res;
2212 Res.reserve(Val.size());
2213
2214 for (size_t I = 0, E = Val.size(); I != E; ++I) {
2215 switch (getMaskLane(Mask, I)) {
2216 case BooleanKind::True:
2217 Res.push_back(Val[I]);
2218 break;
2219 case BooleanKind::False:
2220 break;
2222 return AnyValue::getPoisonValue(Ctx, RetTy);
2223 }
2224 }
2225
2226 for (size_t I = Res.size(), E = Val.size(); I != E; ++I)
2227 Res.push_back(Passthru[I]);
2228 return std::move(Res);
2229 }
2230
2231 case Intrinsic::experimental_vector_match: {
2232 const auto &Search = Args[0].asAggregate();
2233 const auto &Needles = Args[1].asAggregate();
2234 const auto &Mask = Args[2].asAggregate();
2235
2236 std::vector<AnyValue> Res;
2237 Res.reserve(Search.size());
2238
2239 for (size_t I = 0, E = Search.size(); I != E; ++I) {
2240 switch (Mask[I].asBoolean()) {
2241 case BooleanKind::False:
2242 Res.push_back(AnyValue::boolean(false));
2243 continue;
2245 Res.push_back(AnyValue::poison());
2246 continue;
2247 case BooleanKind::True:
2248 break;
2249 }
2250
2251 if (Search[I].isPoison()) {
2252 Res.push_back(AnyValue::poison());
2253 continue;
2254 }
2255
2256 bool Found = false;
2257 bool SawPoison = false;
2258 for (const AnyValue &Needle : Needles) {
2259 if (Needle.isPoison()) {
2260 SawPoison = true;
2261 break;
2262 }
2263 if (Search[I].asInteger() == Needle.asInteger())
2264 Found = true;
2265 }
2266
2267 if (SawPoison)
2268 Res.push_back(AnyValue::poison());
2269 else
2270 Res.push_back(AnyValue::boolean(Found));
2271 }
2272
2273 return std::move(Res);
2274 }
2275 case Intrinsic::experimental_vector_histogram_add:
2276 case Intrinsic::experimental_vector_histogram_uadd_sat:
2277 case Intrinsic::experimental_vector_histogram_umax:
2278 case Intrinsic::experimental_vector_histogram_umin:
2279 return callExperimentalVectorHistogramIntrinsic(CB, Args, IID);
2280 default:
2281 Handler.onUnrecognizedInstruction(CB);
2282 setFailed();
2283 return AnyValue();
2284 }
2285 }
2286
2288 ArrayRef<AnyValue> CalleeArgs) {
2289 LibFunc LF = CurrentFrame->TLI.getLibFunc(*ResolvedCallee);
2290 // Respect nobuiltin attributes on call site.
2291 if (CB.isNoBuiltin() || LF == NotLibFunc) {
2292 Handler.onUnrecognizedInstruction(CB);
2293 setFailed();
2294 return AnyValue();
2295 }
2296
2297 if (auto LibCallRes = Lib.executeLibcall(LF, CB.getName(),
2298 CB.getFunctionType(), CalleeArgs))
2299 return *LibCallRes;
2300
2301 if (ExitInfo)
2302 return AnyValue();
2303
2304 Handler.onUnrecognizedInstruction(CB);
2305 setFailed();
2306 return AnyValue();
2307 }
2308
2309 /// Handle both poison-generating and UB-implying attributes for parameters
2310 /// and return values.
2311 void handleAttributes(Type *Ty, AnyValue &V, AttributeSet AttrsAtCallSite,
2312 AttributeSet AttrsAtCallee) {
2313 if (Ty->isIntOrIntVectorTy()) {
2314 if (auto CRAttr = AttrsAtCallSite.getAttribute(Attribute::Range);
2315 CRAttr.isValid())
2316 applyRangeAttr(V, CRAttr.getRange());
2317 if (auto CRAttr = AttrsAtCallee.getAttribute(Attribute::Range);
2318 CRAttr.isValid())
2319 applyRangeAttr(V, CRAttr.getRange());
2320 }
2321 if (AttributeFuncs::isNoFPClassCompatibleType(Ty)) {
2322 if (auto CRAttr = AttrsAtCallSite.getAttribute(Attribute::NoFPClass);
2323 CRAttr.isValid())
2324 applyNoFPClassAttr(V, CRAttr.getNoFPClass());
2325 if (auto CRAttr = AttrsAtCallee.getAttribute(Attribute::NoFPClass);
2326 CRAttr.isValid())
2327 applyNoFPClassAttr(V, CRAttr.getNoFPClass());
2328 }
2329 if (Ty->isPointerTy()) {
2330 if (AttrsAtCallSite.hasAttribute(Attribute::NonNull) ||
2331 AttrsAtCallee.hasAttribute(Attribute::NonNull))
2332 applyNonNullAttr(V, Ty->getPointerAddressSpace(), DL);
2333 }
2334 if (Ty->isPtrOrPtrVectorTy()) {
2335 if (MaybeAlign Align = AttrsAtCallSite.getAlignment())
2337 if (MaybeAlign Align = AttrsAtCallee.getAlignment())
2339 }
2340 if ((AttrsAtCallSite.hasAttribute(Attribute::NoUndef) ||
2341 AttrsAtCallee.hasAttribute(Attribute::NoUndef)) &&
2343 reportImmediateUB() << "The value " << V
2344 << " violates noundef attribute.";
2345 return;
2346 }
2347 if (Ty->isPointerTy()) {
2348 unsigned AS = Ty->getPointerAddressSpace();
2349 if (uint64_t DereferenceableBytes =
2350 std::max(AttrsAtCallSite.getDereferenceableBytes(),
2351 AttrsAtCallee.getDereferenceableBytes())) {
2352 if (violatesDereferenceableBytesAttr(V, DereferenceableBytes,
2353 /*OrNull=*/false, AS, Ctx))
2355 << "The value " << V << " violates dereferenceable("
2356 << DereferenceableBytes << ") attribute.";
2357 }
2358 if (uint64_t DereferenceableOrNullBytes =
2359 std::max(AttrsAtCallSite.getDereferenceableOrNullBytes(),
2360 AttrsAtCallee.getDereferenceableOrNullBytes())) {
2361 if (violatesDereferenceableBytesAttr(V, DereferenceableOrNullBytes,
2362 /*OrNull=*/true, AS, Ctx))
2363 reportImmediateUB() << "The value " << V
2364 << " violates "
2365 "dereferenceable_or_null("
2366 << DereferenceableOrNullBytes << ") attribute.";
2367 }
2368 }
2369 }
2370
2371 /// Handle both poison-generating and UB-implying metadata on instructions.
2373 auto ExtractFirstIntOperand = [](const MDNode *Node) {
2374 return mdconst::extract<ConstantInt>(Node->getOperand(0))->getZExtValue();
2375 };
2376
2377 if (Ty->isIntOrIntVectorTy()) {
2378 if (MDNode *Ranges = I.getMetadata(LLVMContext::MD_range)) {
2380 for (uint32_t I = 0; I < Ranges->getNumOperands(); I += 2) {
2381 RangeList.emplace_back(
2382 mdconst::extract<ConstantInt>(Ranges->getOperand(I))->getValue(),
2383 mdconst::extract<ConstantInt>(Ranges->getOperand(I + 1))
2384 ->getValue());
2385 }
2386 forEachScalarValue(V, [&](AnyValue &Scalar) {
2387 if (!Scalar.isInteger())
2388 return;
2389 for (auto &CR : RangeList)
2390 if (CR.contains(Scalar.asInteger()))
2391 return;
2392 Scalar = AnyValue::poison();
2393 });
2394 }
2395 }
2396 if (AttributeFuncs::isNoFPClassCompatibleType(Ty)) {
2397 if (const MDNode *NoFPClass = I.getMetadata(LLVMContext::MD_nofpclass)) {
2399 V, static_cast<FPClassTest>(ExtractFirstIntOperand(NoFPClass)));
2400 }
2401 }
2402 if (Ty->isPointerTy()) {
2403 if (I.hasMetadata(LLVMContext::MD_nonnull))
2404 applyNonNullAttr(V, Ty->getPointerAddressSpace(), DL);
2405 // Unlike align attributes, !align is only defined for pointer types.
2406 if (const MDNode *Alignment = I.getMetadata(LLVMContext::MD_align))
2407 applyAlignAttr(V, Align(ExtractFirstIntOperand(Alignment)));
2408 }
2409 if (I.hasMetadata(LLVMContext::MD_noundef) && violatesNoUndefAttr(V)) {
2410 reportImmediateUB() << "The value " << V
2411 << " violates !noundef metadata.";
2412 return;
2413 }
2414 if (Ty->isPointerTy()) {
2415 unsigned AS = Ty->getPointerAddressSpace();
2416 if (const MDNode *DereferenceableBytes =
2417 I.getMetadata(LLVMContext::MD_dereferenceable)) {
2418 uint64_t Bytes = ExtractFirstIntOperand(DereferenceableBytes);
2420 /*OrNull=*/false, AS, Ctx))
2422 << "The value " << V << " violates !dereferenceable !{i64 "
2423 << Bytes << "} metadata.";
2424 } else if (const MDNode *DereferenceableOrNullBytes =
2425 I.getMetadata(LLVMContext::MD_dereferenceable_or_null)) {
2426 uint64_t Bytes = ExtractFirstIntOperand(DereferenceableOrNullBytes);
2428 /*OrNull=*/true, AS, Ctx))
2430 << "The value " << V << " violates !dereferenceable_or_null!{i64 "
2431 << Bytes << "} metadata.";
2432 }
2433 }
2434 }
2435
2436 void setFrameStackInaccessible(Frame &F, bool Inaccessible) {
2437 for (auto &Obj : F.Allocas) {
2438 assert(Obj->isInaccessible() != Inaccessible &&
2439 "Unexpected stack object accessibility state.");
2440 Obj->setIsInaccessible(Inaccessible);
2441 }
2442 if (F.LastFrame) {
2443 for (auto &Obj : F.LastFrame->CalleeByValArgs) {
2444 assert(Obj->isInaccessible() != Inaccessible &&
2445 "Unexpected byval object accessibility state.");
2446 Obj->setIsInaccessible(Inaccessible);
2447 }
2448 }
2449 }
2450
2452 Function *Callee = CB.getCalledFunction();
2453 // TODO: handle initializes
2454 auto &CalleeArgs = CurrentFrame->CalleeArgs;
2455 assert(CalleeArgs.empty() &&
2456 "Forgot to call returnFromCallee before entering a new call.");
2457 for (Value *Arg : CB.args())
2458 CalleeArgs.push_back(getValue(Arg));
2459
2460 if (!Callee) {
2461 Value *CalledOperand = CB.getCalledOperand();
2462 if (isNoopInlineAsm(CalledOperand, CB.getType())) {
2463 CurrentFrame->ResolvedCallee = nullptr;
2464 CurrentFrame->CalleeRetVal = AnyValue();
2466 return;
2467 }
2468
2469 if (isa<InlineAsm>(CalledOperand)) {
2470 Handler.onUnrecognizedInstruction(CB);
2471 setFailed();
2472 return;
2473 }
2474
2475 auto &CalleeVal = getValue(CalledOperand);
2476 if (CalleeVal.isPoison()) {
2477 reportImmediateUB() << "Indirect call through poison function pointer.";
2478 return;
2479 }
2480 Callee = Ctx.getTargetFunction(CalleeVal.asPointer());
2481 if (!Callee) {
2483 << "Indirect call through invalid function pointer.";
2484 return;
2485 }
2486 if (Callee->getFunctionType() != CB.getFunctionType()) {
2487 reportImmediateUB() << "Indirect call through a function pointer with "
2488 "mismatched signature. Expected: "
2489 << *CB.getFunctionType()
2490 << ", Actual: " << *Callee->getFunctionType();
2491 return;
2492 }
2493 }
2494
2495 assert(Callee && "Expected a resolved callee function.");
2496 assert(
2497 Callee->getFunctionType() == CB.getFunctionType() &&
2498 "Expected the callee function type to match the call site signature.");
2499 if (!Callee->isIntrinsic() &&
2500 Callee->getCallingConv() != CB.getCallingConv()) {
2502 << "Mismatched calling convention between callee and callsite.";
2503 return;
2504 }
2505
2506 // Copy byval arguments before marking caller stack objects inaccessible on
2507 // tail calls.
2508 for (auto [I, Arg] : enumerate(CB.args())) {
2509 Type *ArgTy = Arg->getType();
2510 AnyValue &ArgVal = CalleeArgs[I];
2511
2512 // CallBase::paramHasAttr also checks parameter attributes at known
2513 // callee. We do it explicitly to avoid duplication.
2514 AttributeSet AttrsAtCallSite = CB.getParamAttributes(I);
2515 AttributeSet AttrsAtCallee = Callee->getAttributes().getParamAttrs(I);
2516
2517 if (ArgTy->isPointerTy()) {
2518 auto *ByValTy = AttrsAtCallSite.getByValType();
2519 auto *ByValTyFromCallee = AttrsAtCallee.getByValType();
2520 if (ByValTy != ByValTyFromCallee) {
2522 << "Mismatched byval attribute between callee and callsite.";
2523 return;
2524 }
2525 if (ByValTy) {
2526 if (ArgVal.isPoison()) {
2527 reportImmediateUB() << "Invalid poison byval pointer argument.";
2528 return;
2529 }
2530
2531 uint64_t Size = Ctx.getEffectiveTypeAllocSize(ByValTy);
2532 MaybeAlign AllocAlign = AttrsAtCallSite.getAlignment();
2533 // Ignore the alignment at the callsite when it is set on the callee.
2534 if (MaybeAlign CalleeAlign = AttrsAtCallee.getAlignment())
2535 AllocAlign = CalleeAlign;
2536 if (!AllocAlign.has_value()) {
2537 // If the alignment is not specified, we use the default ABI
2538 // alignment. This is the default behavior of
2539 // TargetLoweringBase::getByValTypeAlignment.
2540 AllocAlign = DL.getABITypeAlign(ByValTy);
2541 }
2542 assert(I < Callee->arg_size() &&
2543 "Byval pointers cannot be passed via variadic arguments.");
2544 if (Ctx.exceedsMaxObjectSize(Size, ArgTy->getPointerAddressSpace())) {
2546 << "Byval argument with size that exceeds the maximum object "
2547 "size. Size: "
2548 << Size;
2549 return;
2550 }
2551 auto Obj = Ctx.allocate(
2552 Size, AllocAlign->value(), Callee->getArg(I)->getName(),
2555 if (!Obj) {
2556 reportError()
2557 << "Insufficient stack space for byval pointer argument.";
2558 return;
2559 }
2560 if (auto [MO, Offset] = verifyMemAccess(
2561 ArgVal.asPointer(), Size,
2562 std::max(AllocAlign.value(),
2563 AttrsAtCallSite.getAlignment().valueOrOne()),
2564 /*IsStore=*/false);
2565 MO)
2566 copy(MO->getBytes().slice(Offset, Size), Obj->getBytes().begin());
2567 else
2568 return;
2569 CurrentFrame->CalleeByValArgs.push_back(Obj);
2570 ArgVal = Ctx.deriveFromMemoryObject(std::move(Obj));
2571 }
2572 }
2573 }
2574
2575 if (CB.isTailCall()) {
2577 CurrentFrame->HasInaccessibleStackObjects = true;
2578 }
2579
2580 // Handle parameter attributes (Attributes from resolved callee should be
2581 // applied if available).
2582 for (auto [I, Arg] : enumerate(CB.args())) {
2583 Type *ArgTy = Arg->getType();
2584 AnyValue &ArgVal = CalleeArgs[I];
2585 AttributeSet AttrsAtCallSite = CB.getParamAttributes(I);
2586 AttributeSet AttrsAtCallee = Callee->getAttributes().getParamAttrs(I);
2587 handleAttributes(ArgTy, ArgVal, AttrsAtCallSite, AttrsAtCallee);
2588 }
2589 if (hasProgramExited())
2590 return;
2591
2592 CurrentFrame->ResolvedCallee = Callee;
2593 ArrayRef<AnyValue> Args = CalleeArgs;
2594 if (Function *Oracle = getSpeculativeLoadOracle(CB)) {
2595 Args = Args.drop_front(3);
2596 for (auto [Arg, ArgVal] :
2597 zip_equal(Oracle->args(), MutableArrayRef(CalleeArgs).drop_front(3)))
2598 handleAttributes(Arg.getType(), ArgVal, AttributeSet(),
2599 Arg.getAttributes());
2600 Callee = Oracle;
2601 }
2602 if (Callee->isIntrinsic()) {
2603 CurrentFrame->CalleeRetVal = callIntrinsic(CB, CalleeArgs);
2605 return;
2606 } else if (Callee->isDeclaration()) {
2607 CurrentFrame->CalleeRetVal = callLibFunc(CB, Callee, CalleeArgs);
2609 return;
2610 } else {
2611 uint32_t MaxStackDepth = Ctx.getMaxStackDepth();
2612 if (MaxStackDepth && CallStack.size() >= MaxStackDepth) {
2613 reportError() << "Maximum stack depth exceeded.";
2614 return;
2615 }
2616 assert(!Callee->empty() && "Expected a defined function.");
2617 // Suspend the current frame and push the callee frame onto the stack.
2618 AnyValue &RetVal = CurrentFrame->CalleeRetVal;
2620 CallStack.emplace_back(*Callee, &CB, CurrentFrame, Args, RetVal,
2621 Ctx.getTLIImpl());
2622 }
2623 }
2624
2626
2628 // TODO: handle exceptions
2629 enterCall(II);
2630 }
2631
2633 visitIntBinOp(I, [&](const APInt &LHS, const APInt &RHS) {
2634 return addNoWrap(LHS, RHS, I.hasNoSignedWrap(), I.hasNoUnsignedWrap());
2635 });
2636 }
2637
2639 visitIntBinOp(I, [&](const APInt &LHS, const APInt &RHS) {
2640 return subNoWrap(LHS, RHS, I.hasNoSignedWrap(), I.hasNoUnsignedWrap());
2641 });
2642 }
2643
2645 visitIntBinOp(I, [&](const APInt &LHS, const APInt &RHS) {
2646 return mulNoWrap(LHS, RHS, I.hasNoSignedWrap(), I.hasNoUnsignedWrap());
2647 });
2648 }
2649
2651 visitBinOp(I, [&](const AnyValue &LHS, const AnyValue &RHS) {
2652 return computeDivRem(I.getOpcode(), LHS, RHS, I.isExact());
2653 });
2654 }
2655
2657 visitBinOp(I, [&](const AnyValue &LHS, const AnyValue &RHS) {
2658 return computeDivRem(I.getOpcode(), LHS, RHS);
2659 });
2660 }
2661
2663 visitBinOp(I, [&](const AnyValue &LHS, const AnyValue &RHS) {
2664 return computeDivRem(I.getOpcode(), LHS, RHS, I.isExact());
2665 });
2666 }
2667
2669 visitBinOp(I, [&](const AnyValue &LHS, const AnyValue &RHS) {
2670 return computeDivRem(I.getOpcode(), LHS, RHS);
2671 });
2672 }
2673
2675 visitFPBinOp(I, [](const APFloat &LHS, const APFloat &RHS) -> APFloat {
2676 APFloat Res = LHS;
2678 return Res;
2679 });
2680 }
2681
2683 visitFPBinOp(I, [](const APFloat &LHS, const APFloat &RHS) -> APFloat {
2684 APFloat Res = LHS;
2686 return Res;
2687 });
2688 }
2689
2691 visitFPBinOp(I, [](const APFloat &LHS, const APFloat &RHS) -> APFloat {
2692 APFloat Res = LHS;
2694 return Res;
2695 });
2696 }
2697
2699 visitFPBinOp(I, [](const APFloat &LHS, const APFloat &RHS) -> APFloat {
2700 APFloat Res = LHS;
2702 return Res;
2703 });
2704 }
2705
2707 visitFPBinOp(I, [](const APFloat &LHS, const APFloat &RHS) -> APFloat {
2708 APFloat Res = LHS;
2709 Res.mod(RHS);
2710 return Res;
2711 });
2712 }
2713
2715 visitBitwiseFPUnOp(
2716 I, [](const APFloat &Operand) -> APFloat { return -Operand; });
2717 }
2718
2720 visitIntUnOp(Trunc, [&](const APInt &Operand) -> AnyValue {
2721 unsigned DestBW = Trunc.getType()->getScalarSizeInBits();
2722 if (Trunc.hasNoSignedWrap() && Operand.getSignificantBits() > DestBW)
2723 return AnyValue::poison();
2724 if (Trunc.hasNoUnsignedWrap() && Operand.getActiveBits() > DestBW)
2725 return AnyValue::poison();
2726 return Operand.trunc(DestBW);
2727 });
2728 }
2729
2731 visitIntUnOp(ZExt, [&](const APInt &Operand) -> AnyValue {
2732 uint32_t DestBW = ZExt.getDestTy()->getScalarSizeInBits();
2733 if (ZExt.hasNonNeg() && Operand.isNegative())
2734 return AnyValue::poison();
2735 return Operand.zext(DestBW);
2736 });
2737 }
2738
2740 visitIntUnOp(SExt, [&](const APInt &Operand) -> AnyValue {
2741 uint32_t DestBW = SExt.getDestTy()->getScalarSizeInBits();
2742 return Operand.sext(DestBW);
2743 });
2744 }
2745
2747
2748 void visitFPTruncInst(FPTruncInst &FPTrunc) { visitFPConvInst(FPTrunc); }
2749
2751 if (!Ctx.isDefaultFPEnv())
2752 reportImmediateUB() << "Non-constrained floating-point operation assumes "
2753 "default floating-point environment";
2754
2755 const fltSemantics &DstSem =
2756 I.getType()->getScalarType()->getFltSemantics();
2757
2758 visitUnOp(I, [&](const AnyValue &Operand) -> AnyValue {
2759 if (Operand.isPoison())
2760 return AnyValue::poison();
2761
2762 FastMathFlags FMF = cast<FPMathOperator>(I).getFastMathFlags();
2763 DenormalMode DenormMode =
2764 getCurrentDenormalMode(I.getOperand(0)->getType());
2765
2766 auto ValidatedOperand = handleFMFFlags(Operand, FMF, /*IsInput=*/true);
2767 if (ValidatedOperand.isPoison())
2768 return ValidatedOperand;
2769
2770 APFloat FOperand = handleDenormal(ValidatedOperand.asFloat(),
2771 DenormMode.Input, /*IsInput=*/true);
2772 APFloat SourceNaN = FOperand;
2773
2774 bool LosesInfo;
2775 FOperand.convert(DstSem, Ctx.getCurrentRoundingMode(), &LosesInfo);
2776
2777 if (auto ValidateRes = handleFMFFlags(FOperand, FMF, /*IsInput=*/false);
2778 ValidateRes.isPoison())
2779 return ValidateRes;
2780
2781 FOperand = handleDenormal(std::move(FOperand), DenormMode.Output, true);
2782
2783 return AnyValue(applyNaNPropagation(FOperand, {&SourceNaN}));
2784 });
2785 }
2786
2788 visitFPToIntInst(FPToSI, /*IsUnsigned=*/false);
2789 }
2790
2792 visitFPToIntInst(FPToUI, /*IsUnsigned=*/true);
2793 }
2794
2795 void visitFPToIntInst(Instruction &I, bool IsUnsigned) {
2796 // Note: We DO NOT use CurrentRoundingMode here.
2797 // Language specs require truncation towards zero for FP-to-Int conversions.
2798 visitUnOp(I, [&](const AnyValue &Operand) -> AnyValue {
2799 if (Operand.isPoison())
2800 return AnyValue::poison();
2801
2802 APSInt Res(I.getType()->getScalarSizeInBits(), /*isUnsigned=*/IsUnsigned);
2803 bool IsExact;
2805 Res, APFloat::rmTowardZero, &IsExact);
2806
2808 return AnyValue::poison();
2809
2810 return AnyValue(Res);
2811 });
2812 }
2813
2815 visitIntToFPInst(SIToFP, /*IsSigned=*/true);
2816 }
2817
2819 visitIntToFPInst(UIToFP, /*IsSigned=*/false);
2820 }
2821
2822 void visitIntToFPInst(Instruction &I, bool IsSigned) {
2823 const fltSemantics &DstSem =
2824 I.getType()->getScalarType()->getFltSemantics();
2825 FastMathFlags FMF = cast<FPMathOperator>(I).getFastMathFlags();
2826
2827 visitUnOp(I, [&](const AnyValue &Operand) -> AnyValue {
2828 if (Operand.isPoison())
2829 return AnyValue::poison();
2830
2831 APInt IOperand = Operand.asInteger();
2832
2833 if (isa<UIToFPInst>(I) && I.hasNonNeg() && IOperand.isNegative())
2834 return AnyValue::poison();
2835
2836 APFloat Res(DstSem);
2837
2838 Res.convertFromAPInt(Operand.asInteger(), /*IsSigned=*/IsSigned,
2839 Ctx.getCurrentRoundingMode());
2840
2841 // We need IsInput=true here because the nsz flag applies to the output.
2842 return handleFMFFlags(Res, FMF, /*IsInput=*/true);
2843 });
2844 }
2845
2847 visitIntBinOp(I, [](const APInt &LHS, const APInt &RHS) -> AnyValue {
2848 return LHS & RHS;
2849 });
2850 }
2851
2853 visitIntBinOp(I, [](const APInt &LHS, const APInt &RHS) -> AnyValue {
2854 return LHS ^ RHS;
2855 });
2856 }
2857
2859 visitIntBinOp(I, [&](const APInt &LHS, const APInt &RHS) -> AnyValue {
2860 if (cast<PossiblyDisjointInst>(I).isDisjoint() && LHS.intersects(RHS))
2861 return AnyValue::poison();
2862 return LHS | RHS;
2863 });
2864 }
2865
2867 visitIntBinOp(I, [&](const APInt &LHS, const APInt &RHS) -> AnyValue {
2868 if (RHS.uge(LHS.getBitWidth()))
2869 return AnyValue::poison();
2870 if (I.hasNoSignedWrap() && RHS.uge(LHS.getNumSignBits()))
2871 return AnyValue::poison();
2872 if (I.hasNoUnsignedWrap() && RHS.ugt(LHS.countl_zero()))
2873 return AnyValue::poison();
2874 return LHS.shl(RHS);
2875 });
2876 }
2877
2879 visitIntBinOp(I, [&](const APInt &LHS, const APInt &RHS) -> AnyValue {
2880 if (RHS.uge(LHS.getBitWidth()) ||
2881 (cast<PossiblyExactOperator>(I).isExact() &&
2882 RHS.ugt(LHS.countr_zero())))
2883 return AnyValue::poison();
2884 return LHS.lshr(RHS);
2885 });
2886 }
2887
2889 visitIntBinOp(I, [&](const APInt &LHS, const APInt &RHS) -> AnyValue {
2890 if (RHS.uge(LHS.getBitWidth()) ||
2891 (cast<PossiblyExactOperator>(I).isExact() &&
2892 RHS.ugt(LHS.countr_zero())))
2893 return AnyValue::poison();
2894 return LHS.ashr(RHS);
2895 });
2896 }
2897
2899 Type *OpTy = I.getOperand(0)->getType();
2900 unsigned AddrWidth =
2901 OpTy->isPtrOrPtrVectorTy() ? DL.getAddressSizeInBits(OpTy) : 0;
2902 visitBinOp(I, [&](const AnyValue &LHS, const AnyValue &RHS) -> AnyValue {
2903 if (LHS.isPoison() || RHS.isPoison())
2904 return AnyValue::poison();
2905 const APInt &LHSVal = LHS.isPointer()
2906 ? LHS.asPointer().address().trunc(AddrWidth)
2907 : LHS.asInteger();
2908 const APInt &RHSVal = RHS.isPointer()
2909 ? RHS.asPointer().address().trunc(AddrWidth)
2910 : RHS.asInteger();
2911 if (I.hasSameSign() && LHSVal.isNonNegative() != RHSVal.isNonNegative())
2912 return AnyValue::poison();
2913 return AnyValue::boolean(
2914 ICmpInst::compare(LHSVal, RHSVal, I.getPredicate()));
2915 });
2916 }
2917
2919 DenormalMode DenormMode =
2920 getCurrentDenormalMode(I.getOperand(0)->getType());
2921 FastMathFlags FMF = I.getFastMathFlags();
2922
2923 visitBinOp(I, [&](const AnyValue &LHS, const AnyValue &RHS) -> AnyValue {
2924 if (LHS.isPoison() || RHS.isPoison())
2925 return AnyValue::poison();
2926
2927 if (auto ValidateRes = handleFMFFlags(LHS, FMF, /*IsInput=*/true);
2928 ValidateRes.isPoison())
2929 return ValidateRes;
2930 if (auto ValidateRes = handleFMFFlags(RHS, FMF, /*IsInput=*/true);
2931 ValidateRes.isPoison())
2932 return ValidateRes;
2933
2934 APFloat FLHS =
2935 handleDenormal(LHS.asFloat(), DenormMode.Input, /*IsInput=*/true);
2936 APFloat FRHS =
2937 handleDenormal(RHS.asFloat(), DenormMode.Input, /*IsInput=*/true);
2938
2939 return AnyValue::boolean(FCmpInst::compare(FLHS, FRHS, I.getPredicate()));
2940 });
2941 }
2942
2943 /// Computes `select CondVal, TVVal, FVVal` of type \p Ty with fast-math flags
2944 /// \p FMF. \p CondVal is either an i1 or a vector of i1.
2945 AnyValue computeSelect(const AnyValue &CondVal, const AnyValue &TVVal,
2946 const AnyValue &FVVal, Type *Ty, FastMathFlags FMF) {
2947 AnyValue Res;
2948
2949 if (!CondVal.isAggregate()) {
2950 switch (CondVal.asBoolean()) {
2951 case BooleanKind::True:
2952 Res = TVVal;
2953 break;
2954 case BooleanKind::False:
2955 Res = FVVal;
2956 break;
2958 Res = AnyValue::getPoisonValue(Ctx, Ty);
2959 break;
2960 }
2961 } else {
2962 auto &Cond = CondVal.asAggregate();
2963 auto &TV = TVVal.asAggregate();
2964 auto &FV = FVVal.asAggregate();
2965 std::vector<AnyValue> ResVec;
2966 size_t Len = Cond.size();
2967 ResVec.reserve(Len);
2968 for (uint32_t I = 0; I != Len; ++I) {
2969 switch (Cond[I].asBoolean()) {
2970 case BooleanKind::True:
2971 ResVec.push_back(TV[I]);
2972 break;
2973 case BooleanKind::False:
2974 ResVec.push_back(FV[I]);
2975 break;
2977 ResVec.push_back(AnyValue::getPoisonValue(Ctx, Ty->getScalarType()));
2978 break;
2979 }
2980 }
2981 Res = AnyValue(std::move(ResVec));
2982 }
2983
2984 // Handle fast-math flags
2985 if (FMF.any())
2986 Res = handleFMFFlags(std::move(Res), FMF, /*IsInput=*/true);
2987 return Res;
2988 }
2989
2991 setResult(SI, computeSelect(getValue(SI.getCondition()),
2992 getValue(SI.getTrueValue()),
2993 getValue(SI.getFalseValue()), SI.getType(),
2994 SI.getFastMathFlagsOrNone()));
2995 }
2996
2998 uint64_t AllocSize = Ctx.getEffectiveTypeSize(AI.getAllocationBaseSize(DL));
2999 if (AI.isArrayAllocation()) {
3000 auto &Size = getValue(AI.getArraySize());
3001 if (Size.isPoison()) {
3002 reportImmediateUB() << "Alloca with poison array size.";
3003 return;
3004 }
3005 if (Size.asInteger().getActiveBits() > 64) {
3007 << "Alloca with large array size that overflows uint64_t. Size: "
3008 << Size.asInteger();
3009 return;
3010 }
3011 bool Overflowed = false;
3012 AllocSize = SaturatingMultiply(AllocSize, Size.asInteger().getZExtValue(),
3013 &Overflowed);
3014 if (Overflowed) {
3016 << "Alloca with allocation size that overflows uint64_t. Size: "
3017 << Size.asInteger();
3018 return;
3019 }
3020 }
3021 if (Ctx.exceedsMaxObjectSize(AllocSize, AI.getAddressSpace())) {
3023 << "Alloca with allocation size that exceeds the maximum object "
3024 "size. Size: "
3025 << AllocSize;
3026 return;
3027 }
3028 // If it is used by llvm.lifetime.start, it should be initially dead.
3029 bool IsInitiallyDead = any_of(AI.users(), [](User *U) {
3030 return match(U, m_Intrinsic<Intrinsic::lifetime_start>());
3031 });
3032 auto Obj = Ctx.allocate(AllocSize, AI.getPointerAlignment(DL).value(),
3033 AI.getName(), AI.getAddressSpace(),
3034 IsInitiallyDead ? MemInitKind::Poisoned
3037 if (!Obj) {
3038 reportError() << "Insufficient stack space.";
3039 return;
3040 }
3041 CurrentFrame->Allocas.push_back(Obj);
3042 setResult(AI, Ctx.deriveFromMemoryObject(Obj));
3043 }
3044
3046 setResult(GEP, Ctx.computeGEP(cast<GEPOperator>(GEP),
3047 [this](Value *V) -> const AnyValue & {
3048 return getValue(V);
3049 }));
3050 }
3051
3053 unsigned BitWidth = I.getType()->getScalarSizeInBits();
3054 return visitUnOp(I, [this, BitWidth](const AnyValue &V) -> AnyValue {
3055 if (V.isPoison())
3056 return AnyValue::poison();
3057 Ctx.exposeProvenance(V.asPointer().provenance());
3058 return V.asPointer().address().zextOrTrunc(BitWidth);
3059 });
3060 }
3061
3063 return visitUnOp(I, [&](const AnyValue &V) -> AnyValue {
3064 if (V.isPoison())
3065 return AnyValue::poison();
3066 auto Prov = Ctx.getWildcardProvenance();
3067 // TODO: check metadata
3068 return Pointer(std::move(Prov),
3069 V.asInteger().zextOrTrunc(DL.getPointerSizeInBits(
3070 I.getType()->getPointerAddressSpace())));
3071 });
3072 }
3073
3075 unsigned BitWidth = I.getType()->getScalarSizeInBits();
3076 return visitUnOp(I, [&](const AnyValue &V) -> AnyValue {
3077 if (V.isPoison())
3078 return AnyValue::poison();
3079 return V.asPointer().address().trunc(BitWidth);
3080 });
3081 }
3082
3084 auto RetVal = load(getValue(LI.getPointerOperand()), LI.getAlign(),
3085 LI.getType(), LI.hasMetadata(LLVMContext::MD_noundef));
3086 // TODO: track volatile loads
3087 handleMetadata(LI.getType(), RetVal, LI);
3088 setResult(LI, std::move(RetVal));
3089 }
3090
3092 auto &Ptr = getValue(SI.getPointerOperand());
3093 auto &Val = getValue(SI.getValueOperand());
3094 // TODO: track volatile stores
3095 // TODO: handle metadata
3096 store(Ptr, SI.getAlign(), Val, SI.getValueOperand()->getType());
3097 if (!hasProgramExited() && !Handler.onInstructionExecuted(SI, AnyValue()))
3098 setFailed();
3099 }
3100
3102 Handler.onUnrecognizedInstruction(I);
3103 setFailed();
3104 }
3105
3107 auto &Res = getValue(EVI.getAggregateOperand());
3108 const AnyValue *Pos = &Res;
3109 for (unsigned Idx : EVI.indices())
3110 Pos = &Pos->asAggregate()[Idx];
3111 setResult(EVI, *Pos);
3112 }
3113
3115 AnyValue Res = getValue(IVI.getAggregateOperand());
3116 AnyValue *Pos = &Res;
3117 for (unsigned Idx : IVI.indices())
3118 Pos = &Pos->asAggregate()[Idx];
3119 *Pos = getValue(IVI.getInsertedValueOperand());
3120 setResult(IVI, std::move(Res));
3121 }
3122
3124 auto Res = getValue(IEI.getOperand(0));
3125 auto &ResVec = Res.asAggregate();
3126 auto &Idx = getValue(IEI.getOperand(2));
3127 if (Idx.isPoison() || Idx.asInteger().uge(ResVec.size())) {
3128 setResult(IEI, AnyValue::getPoisonValue(Ctx, IEI.getType()));
3129 return;
3130 }
3131 ResVec[Idx.asInteger().getZExtValue()] = getValue(IEI.getOperand(1));
3132 setResult(IEI, std::move(Res));
3133 }
3134
3136 auto &SrcVec = getValue(EEI.getOperand(0)).asAggregate();
3137 auto &Idx = getValue(EEI.getOperand(1));
3138 if (Idx.isPoison() || Idx.asInteger().uge(SrcVec.size())) {
3139 setResult(EEI, AnyValue::getPoisonValue(Ctx, EEI.getType()));
3140 return;
3141 }
3142 setResult(EEI, SrcVec[Idx.asInteger().getZExtValue()]);
3143 }
3144
3146 auto &LHSVec = getValue(SVI.getOperand(0)).asAggregate();
3147 auto &RHSVec = getValue(SVI.getOperand(1)).asAggregate();
3149 ->getElementCount()
3150 .getKnownMinValue();
3151 std::vector<AnyValue> Res;
3152 uint32_t DstLen = Ctx.getEVL(SVI.getType()->getElementCount());
3153 Res.reserve(DstLen);
3154 uint32_t Stride = SVI.getShuffleMask().size();
3155 // For scalable vectors, we need to repeat the shuffle mask until we fill
3156 // the destination vector.
3157 for (uint32_t Off = 0; Off != DstLen; Off += Stride) {
3158 for (int Idx : SVI.getShuffleMask()) {
3159 if (Idx == PoisonMaskElem)
3160 Res.push_back(
3162 else if (Idx < static_cast<int>(Size))
3163 Res.push_back(LHSVec[Idx]);
3164 else
3165 Res.push_back(RHSVec[Idx - Size]);
3166 }
3167 }
3168 setResult(SVI, std::move(Res));
3169 }
3170
3172 // The conversion is done as if the value had been stored to memory and read
3173 // back as the target type.
3174 SmallVector<Byte> Bytes;
3175 Bytes.resize(Ctx.getEffectiveTypeStoreSize(BCI.getType()),
3176 Byte::concrete(0));
3177 Ctx.toBytes(getValue(BCI.getOperand(0)), BCI.getOperand(0)->getType(),
3178 Bytes);
3179 setResult(BCI, Ctx.fromBytes(Bytes, BCI.getType()));
3180 }
3181
3183 Type *BaseTy = BII.getType()->getScalarType();
3184 Type *ValTy = BII.getOperand(1)->getType()->getScalarType();
3185 uint64_t NumBits = DL.getTypeSizeInBits(ValTy).getFixedValue();
3186 visitTriOp(BII,
3187 [&](const AnyValue &Base, const AnyValue &Val,
3188 const AnyValue &Offset) -> AnyValue {
3189 if (Offset.isPoison())
3190 return AnyValue::getPoisonValue(Ctx, BaseTy);
3191 ByteValue Res = Base.asByte();
3192 uint64_t OffsetInBits = Offset.asInteger().getZExtValue();
3193 if (OffsetInBits + NumBits > Res.getBitWidth())
3194 return AnyValue::getPoisonValue(Ctx, BaseTy);
3195 Ctx.insertBits(Res, OffsetInBits, Val, ValTy);
3196 return Res;
3197 });
3198 }
3199
3201 Type *Ty = BEI.getType()->getScalarType();
3202 uint64_t NumBits = DL.getTypeSizeInBits(Ty).getFixedValue();
3203 visitBinOp(BEI,
3204 [&](const AnyValue &Src, const AnyValue &Offset) -> AnyValue {
3205 if (Offset.isPoison())
3206 return AnyValue::getPoisonValue(Ctx, Ty);
3207 const ByteValue &Bytes = Src.asByte();
3208 uint64_t OffsetInBits = Offset.asInteger().getZExtValue();
3209 if (OffsetInBits + NumBits > Bytes.getBitWidth())
3210 return AnyValue::getPoisonValue(Ctx, Ty);
3211 return Ctx.extractBits(Bytes, OffsetInBits, Ty);
3212 });
3213 }
3214
3216 AnyValue Val = getValue(FI.getOperand(0));
3217 Ctx.freeze(Val, FI.getType());
3218 setResult(FI, std::move(Val));
3219 }
3220
3221 /// This function implements the main interpreter loop.
3222 /// It handles function calls in a non-recursive manner to avoid stack
3223 /// overflows.
3225 uint32_t MaxSteps = Ctx.getMaxSteps();
3226 uint32_t Steps = 0;
3227 while (!hasProgramExited() && !CallStack.empty()) {
3228 Frame &Top = CallStack.back();
3229 CurrentFrame = &Top;
3230 if (Top.State == FrameState::Entry) {
3231 Handler.onFunctionEntry(Top.Func, Top.Args, Top.CallSite);
3232 } else {
3234 "Expected to return from a callee.");
3236 }
3237
3239 // Interpreter loop inside a function
3240 while (!hasProgramExited()) {
3242 "Expected to be in running state.");
3243 if (MaxSteps != 0 && Steps >= MaxSteps) {
3244 reportError() << "Exceeded maximum number of execution steps.";
3245 break;
3246 }
3247 ++Steps;
3248
3249 Instruction &I = *Top.PC;
3250 visit(&I);
3251 Ctx.resetNoncacheableConstantBuffer();
3252 if (hasProgramExited())
3253 break;
3254
3255 // A function call or return has occurred.
3256 // We need to exit the inner loop and switch to a different frame.
3257 if (Top.State != FrameState::Running)
3258 break;
3259
3260 // Otherwise, move to the next instruction if it is not a terminator.
3261 // For terminators, the PC is updated in the visit* method.
3262 if (!I.isTerminator())
3263 ++Top.PC;
3264 }
3265
3266 if (hasProgramExited())
3267 break;
3268
3269 if (Top.State == FrameState::Exit) {
3270 assert((Top.Func.getReturnType()->isVoidTy() || !Top.RetVal.isNone()) &&
3271 "Expected return value to be set on function exit.");
3272 Handler.onFunctionExit(Top.Func, Top.RetVal);
3273 // Free stack objects allocated in this frame.
3274 for (auto &Obj : Top.Allocas)
3275 Ctx.free(*Obj);
3276 CallStack.pop_back();
3277 } else {
3279 "Expected to enter a callee.");
3280 }
3281 }
3282 if (!hasProgramExited())
3284 return *getExitInfo();
3285 }
3286};
3287
3289 AnyValue &RetVal, EventHandler &Handler) {
3290 InstExecutor Executor(*this, Handler, F, Args, RetVal);
3291 return Executor.runMainLoop();
3292}
3293
3294} // namespace llvm::ubi
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
uint64_t uint64_t
AMDGPU Mark last scratch load
Rewrite undef for PHI
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
static GCRegistry::Add< ShadowStackGC > C("shadow-stack", "Very portable GC for uncooperative code generators")
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
Hexagon Common GEP
static bool isZero(Value *V, const DataLayout &DL, DominatorTree *DT, AssumptionCache *AC)
Definition Lint.cpp:550
#define F(x, y, z)
Definition MD5.cpp:54
#define I(x, y, z)
Definition MD5.cpp:57
#define H(x, y, z)
Definition MD5.cpp:56
ConstantRange Range(APInt(BitWidth, Low), APInt(BitWidth, High))
uint64_t IntrinsicInst * II
SmallVector< MachineOperand, 4 > Cond
static cl::opt< RegAllocEvictionAdvisorAnalysisLegacy::AdvisorMode > Mode("regalloc-enable-advisor", cl::Hidden, cl::init(RegAllocEvictionAdvisorAnalysisLegacy::AdvisorMode::Default), cl::desc("Enable regalloc advisor mode"), cl::values(clEnumValN(RegAllocEvictionAdvisorAnalysisLegacy::AdvisorMode::Default, "default", "Default"), clEnumValN(RegAllocEvictionAdvisorAnalysisLegacy::AdvisorMode::Release, "release", "precompiled"), clEnumValN(RegAllocEvictionAdvisorAnalysisLegacy::AdvisorMode::Development, "development", "for training")))
This file contains some templates that are useful if you are working with the STL at all.
This file defines the SmallVector class.
static SymbolRef::Type getType(const Symbol *Sym)
Definition TapiFile.cpp:39
Value * RHS
Value * LHS
The Input class is used to parse a yaml document into in-memory structs and vectors.
static constexpr roundingMode rmTowardZero
Definition APFloat.h:383
static constexpr roundingMode rmNearestTiesToEven
Definition APFloat.h:379
opStatus
IEEE-754R 7: Default exception handling.
Definition APFloat.h:395
static APFloat getQNaN(const fltSemantics &Sem, bool Negative=false, const APInt *payload=nullptr)
Factory for QNaN values.
Definition APFloat.h:1252
opStatus divide(const APFloat &RHS, roundingMode RM)
Definition APFloat.h:1340
void copySign(const APFloat &RHS)
Definition APFloat.h:1434
LLVM_ABI opStatus convert(const fltSemantics &ToSemantics, roundingMode RM, bool *losesInfo)
Definition APFloat.cpp:6106
opStatus subtract(const APFloat &RHS, roundingMode RM)
Definition APFloat.h:1322
bool bitwiseIsEqual(const APFloat &RHS) const
Definition APFloat.h:1576
bool isNegative() const
Definition APFloat.h:1611
bool isDenormal() const
Definition APFloat.h:1612
opStatus add(const APFloat &RHS, roundingMode RM)
Definition APFloat.h:1313
const fltSemantics & getSemantics() const
Definition APFloat.h:1619
APFloat makeQuiet() const
Assuming this is an IEEE-754 NaN value, quiet its signaling bit.
Definition APFloat.h:1448
bool isNaN() const
Definition APFloat.h:1609
opStatus convertFromAPInt(const APInt &Input, bool IsSigned, roundingMode RM)
Definition APFloat.h:1479
opStatus multiply(const APFloat &RHS, roundingMode RM)
Definition APFloat.h:1331
bool isSignaling() const
Definition APFloat.h:1613
opStatus fusedMultiplyAdd(const APFloat &Multiplicand, const APFloat &Addend, roundingMode RM)
Definition APFloat.h:1367
bool isZero() const
Definition APFloat.h:1607
opStatus convertToInteger(MutableArrayRef< integerPart > Input, unsigned int Width, bool IsSigned, roundingMode RM, bool *IsExact) const
Definition APFloat.h:1464
opStatus mod(const APFloat &RHS)
Definition APFloat.h:1358
void changeSign()
Definition APFloat.h:1429
static APFloat getZero(const fltSemantics &Sem, bool Negative=false)
Factory for Positive and Negative Zero.
Definition APFloat.h:1211
bool isInfinity() const
Definition APFloat.h:1608
Class for arbitrary precision integers.
Definition APInt.h:78
static APInt getAllOnes(unsigned numBits)
Return an APInt of a specified width with all bits set.
Definition APInt.h:230
static LLVM_ABI void udivrem(const APInt &LHS, const APInt &RHS, APInt &Quotient, APInt &Remainder)
Dual division/remainder interface.
Definition APInt.cpp:1796
LLVM_ABI APInt zext(unsigned width) const
Zero extend to a new width.
Definition APInt.cpp:1057
bool isMinSignedValue() const
Determine if this is the smallest signed value.
Definition APInt.h:419
uint64_t getZExtValue() const
Get zero extended value.
Definition APInt.h:1560
static LLVM_ABI void sdivrem(const APInt &LHS, const APInt &RHS, APInt &Quotient, APInt &Remainder)
Definition APInt.cpp:1928
unsigned popcount() const
Count the number of bits set.
Definition APInt.h:1690
LLVM_ABI APInt zextOrTrunc(unsigned width) const
Zero extend or truncate to width.
Definition APInt.cpp:1078
unsigned getActiveBits() const
Compute the number of active bits in the value.
Definition APInt.h:1532
LLVM_ABI APInt trunc(unsigned width) const
Truncate to new width.
Definition APInt.cpp:970
APInt abs() const
Get the absolute value.
Definition APInt.h:1815
bool isAllOnes() const
Determine if all bits are set. This is true for zero-width values.
Definition APInt.h:367
bool ugt(const APInt &RHS) const
Unsigned greater than comparison.
Definition APInt.h:1186
bool isZero() const
Determine if this value is zero, i.e. all bits are clear.
Definition APInt.h:376
LLVM_ABI APInt urem(const APInt &RHS) const
Unsigned remainder operation.
Definition APInt.cpp:1695
unsigned getBitWidth() const
Return the number of bits in the APInt.
Definition APInt.h:1508
bool ult(const APInt &RHS) const
Unsigned less than comparison.
Definition APInt.h:1115
unsigned getNumWords() const
Get the number of words.
Definition APInt.h:1515
bool isNegative() const
Determine sign of this APInt.
Definition APInt.h:325
LLVM_ABI APInt reverseBits() const
Definition APInt.cpp:786
unsigned countr_zero() const
Count the number of trailing zero bits.
Definition APInt.h:1659
unsigned countl_zero() const
The APInt version of std::countl_zero.
Definition APInt.h:1618
unsigned getSignificantBits() const
Get the minimum bit size for this signed APInt.
Definition APInt.h:1551
uint64_t getLimitedValue(uint64_t Limit=UINT64_MAX) const
If this value is smaller than the specified limit, return it, otherwise return the limit value.
Definition APInt.h:471
LLVM_ABI APInt uadd_sat(const APInt &RHS) const
Definition APInt.cpp:2083
bool isNonNegative() const
Determine if this APInt Value is non-negative (>= 0)
Definition APInt.h:330
LLVM_ABI APInt sext(unsigned width) const
Sign extend to a new width.
Definition APInt.cpp:1030
APInt shl(unsigned shiftAmt) const
Left-shift function.
Definition APInt.h:875
LLVM_ABI APInt byteSwap() const
Definition APInt.cpp:764
static APInt getZero(unsigned numBits)
Get the '0' value for the specified bit-width.
Definition APInt.h:196
bool isIntN(unsigned N) const
Check if this APInt has an N-bits unsigned integer value.
Definition APInt.h:428
APInt lshr(unsigned shiftAmt) const
Logical right-shift function.
Definition APInt.h:853
An arbitrary precision integer that knows its signedness.
Definition APSInt.h:24
an instruction to allocate memory on the stack
LLVM_ABI TypeSize getAllocationBaseSize(const DataLayout &DL) const
Get the size of the allocated type.
unsigned getAddressSpace() const
Return the address space for the allocation.
LLVM_ABI bool isArrayAllocation() const
Return true if there is an allocation size parameter to the allocation instruction that is not 1.
const Value * getArraySize() const
Get the number of elements allocated.
Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:40
ArrayRef< T > take_front(size_t N=1) const
Return a copy of *this with only the first N elements.
Definition ArrayRef.h:218
size_t size() const
Get the array size.
Definition ArrayRef.h:141
bool empty() const
Check if the array is empty.
Definition ArrayRef.h:136
ArrayRef< T > slice(size_t N, size_t M) const
slice(n, m) - Chop off the first N elements of the array, and keep M elements in the array.
Definition ArrayRef.h:185
This class holds the attributes for a particular argument, parameter, function, or return value.
Definition Attributes.h:448
LLVM_ABI Type * getByValType() const
bool hasAttribute(Attribute::AttrKind Kind) const
Return true if the attribute exists in this set.
Definition Attributes.h:532
LLVM_ABI Attribute getAttribute(Attribute::AttrKind Kind) const
Return the attribute object.
LLVM_ABI uint64_t getDereferenceableBytes() const
LLVM_ABI MaybeAlign getAlignment() const
LLVM_ABI uint64_t getDereferenceableOrNullBytes() const
bool isValid() const
Return true if the attribute is any kind of attribute.
Definition Attributes.h:263
LLVM Basic Block Representation.
Definition BasicBlock.h:62
iterator begin()
Instruction iterator methods.
Definition BasicBlock.h:440
This class represents a no-op cast from one type to another.
Base class for all callable instructions (InvokeInst and CallInst) Holds everything related to callin...
OperandBundleUse getOperandBundleAt(unsigned Index) const
Return the operand bundle at a specific index.
bool isNoBuiltin() const
Return true if the call should not be treated as a call to a builtin.
Function * getCalledFunction() const
Returns the function called, or null if this is an indirect function invocation or the function signa...
AttributeSet getParamAttributes(unsigned ArgNo) const
Return the param attributes for this call.
unsigned getNumOperandBundles() const
Return the number of operand bundles associated with this User.
CallingConv::ID getCallingConv() const
AttributeSet getRetAttributes() const
Return the return attributes for this call.
Value * getCalledOperand() const
Value * getArgOperand(unsigned i) const
FunctionType * getFunctionType() const
LLVM_ABI Intrinsic::ID getIntrinsicID() const
Returns the intrinsic ID of the intrinsic called or Intrinsic::not_intrinsic if the called function i...
iterator_range< User::op_iterator > args()
Iteration adapter for range-for loops.
bool doesNotReturn() const
Determine if the call cannot return.
LLVM_ABI bool isTailCall() const
Tests if this call site is marked as a tail call.
CallBr instruction, tracking function calls that may not return control but instead transfer it to a ...
BasicBlock * getDefaultDest() const
This class represents a function call, abstracting a target machine's calling convention.
Type * getDestTy() const
Return the destination type, as a convenience.
Definition InstrTypes.h:681
Conditional Branch instruction.
Value * getCondition() const
BasicBlock * getSuccessor(unsigned i) const
This class represents a range of values.
LLVM_ABI bool contains(const APInt &Val) const
Return true if the specified value is in the set.
A parsed version of the target data layout string in and methods for querying it.
Definition DataLayout.h:64
This instruction extracts a single (scalar) element from a VectorType value.
This instruction extracts a struct member or array element value from an aggregate value.
iterator_range< idx_iterator > indices() const
This instruction compares its operands according to the predicate given to the constructor.
static LLVM_ABI bool compare(const APFloat &LHS, const APFloat &RHS, FCmpInst::Predicate Pred)
Return result of LHS Pred RHS comparison.
This class represents an extension of floating point types.
This class represents a cast from floating point to signed integer.
This class represents a cast from floating point to unsigned integer.
This class represents a truncation of floating point types.
Convenience struct for specifying and reasoning about fast-math flags.
Definition FMF.h:23
bool any() const
Definition FMF.h:56
bool noSignedZeros() const
Definition FMF.h:67
bool noInfs() const
Definition FMF.h:66
void setNoSignedZeros(bool B=true)
Definition FMF.h:84
bool noNaNs() const
Definition FMF.h:65
static LLVM_ABI FixedVectorType * get(Type *ElementType, unsigned NumElts)
Definition Type.cpp:838
This class represents a freeze function that returns random concrete value if an operand is either a ...
Type * getReturnType() const
Returns the type of the ret val.
Definition Function.h:217
Represents flags for the getelementptr instruction/expression.
static GEPNoWrapFlags inBounds()
static GEPNoWrapFlags all()
static GEPNoWrapFlags none()
an instruction for type-safe pointer arithmetic to access elements of arrays and structs
This instruction compares its operands according to the predicate given to the constructor.
static LLVM_ABI bool compare(const APInt &LHS, const APInt &RHS, ICmpInst::Predicate Pred)
Return result of LHS Pred RHS comparison.
Indirect Branch Instruction.
iterator_range< succ_iterator > successors()
This instruction inserts a single (scalar) element into a VectorType value.
VectorType * getType() const
Overload to return most specific vector type.
This instruction inserts a struct field of array element value into an aggregate value.
Value * getInsertedValueOperand()
iterator_range< idx_iterator > indices() const
Base class for instruction visitors.
Definition InstVisitor.h:78
void visit(Iterator Start, Iterator End)
Definition InstVisitor.h:87
LLVM_ABI FastMathFlags getFastMathFlagsOrNone() const LLVM_READONLY
Convenience function for getting fast-math flags, or default-constructed FastMathFlags when not a FPM...
bool hasMetadata() const
Return true if this instruction has any metadata attached to it.
LLVM_ABI bool hasNonNeg() const LLVM_READONLY
Determine whether the the nneg flag is set.
iterator_range< user_iterator > users()
This class represents a cast from an integer to a pointer.
Invoke instruction.
An instruction for reading from memory.
Value * getPointerOperand()
Align getAlign() const
Return the alignment of the access that is being performed.
Metadata node.
Definition Metadata.h:1087
Represent a mutable reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:294
This class represents a cast from a pointer to an address (non-capturing ptrtoint).
This class represents a cast from a pointer to an integer.
Return a value (possibly void), from a function.
Value * getReturnValue() const
Convenience accessor. Returns null if there is no return value.
This class represents a sign extension of integer types.
This class represents a cast from signed integer to floating point.
This class represents the LLVM 'select' instruction.
This instruction constructs a fixed permutation of two input vectors.
VectorType * getType() const
Overload to return most specific vector type.
static LLVM_ABI void getShuffleMask(const Constant *Mask, SmallVectorImpl< int > &Result)
Convert the input shuffle mask operand to a vector of integers.
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
reference emplace_back(ArgTypes &&... Args)
void reserve(size_type N)
iterator erase(const_iterator CI)
void resize(size_type N)
void push_back(const T &Elt)
LLVM_NO_SANITIZE_CFI_UNRELATED_CAST iterator begin()
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
An instruction for storing to memory.
Represent a constant reference to a string, i.e.
Definition StringRef.h:56
Multiway switch.
Target - Wrapper for Target specific information.
Triple - Helper class for working with autoconf configuration names.
Definition Triple.h:48
This class represents a truncation of integer types.
The instances of the Type class are immutable: once they are created, they are never changed.
Definition Type.h:46
LLVM_ABI unsigned getIntegerBitWidth() const
bool isPointerTy() const
True if this is an instance of PointerType.
Definition Type.h:277
LLVM_ABI unsigned getPointerAddressSpace() const
Get the address space of this pointer or pointer vector type.
unsigned getScalarSizeInBits() const LLVM_READONLY
If this is a vector type, return the getPrimitiveSizeInBits value for the element type.
Definition Type.h:354
Type * getScalarType() const
If this is a vector type, return the element type, otherwise return 'this'.
Definition Type.h:370
bool isVoidTy() const
Return true if this is 'void'.
Definition Type.h:141
This class represents a cast unsigned integer to floating point.
Unconditional Branch instruction.
BasicBlock * getSuccessor(unsigned i=0) const
This function has undefined behavior.
Value * getOperand(unsigned i) const
Definition User.h:207
LLVM Value Representation.
Definition Value.h:75
Type * getType() const
All values are typed, get the type of this value.
Definition Value.h:257
LLVM_ABI Align getPointerAlignment(const DataLayout &DL) const
Returns an alignment of the pointer value.
Definition Value.cpp:985
LLVM_ABI StringRef getName() const
Return a constant reference to the value's name.
Definition Value.cpp:314
ElementCount getElementCount() const
Return an ElementCount instance to represent the (possibly scalable) number of elements in the vector...
This class represents zero extension of integer types.
An efficient, type-erasing, non-owning reference to a callable.
bool isAggregate() const
Definition Value.h:379
static LLVM_ABI AnyValue getPoisonValue(Context &Ctx, Type *Ty)
Definition Value.cpp:270
static AnyValue poison()
Use getPoisonValue unless you know the scalar type is integer/fp/ptr!
Definition Value.h:366
static AnyValue boolean(bool Val)
Definition Value.h:367
const Pointer & asPointer() const
Definition Value.h:412
BooleanKind asBoolean() const
Definition Value.h:447
bool isNone() const
Definition Value.h:373
const APInt & asInteger() const
Definition Value.h:402
const APFloat & asFloat() const
Definition Value.h:407
bool isPoison() const
Definition Value.h:374
const std::vector< AnyValue > & asAggregate() const
Definition Value.h:427
Represents a scalar byte value.
Definition Value.h:257
uint32_t getBitWidth() const
Definition Value.h:297
The global context for the interpreter.
Definition Context.h:227
LLVM_ABI ProgramExitInfo runFunction(Function &F, ArrayRef< AnyValue > Args, AnyValue &RetVal, EventHandler &Handler)
Execute the function F with arguments Args, and store the return value in RetVal if the function is n...
static LLVM_ABI AnyValue canonicalizeIndex(const AnyValue &Idx, unsigned IndexBitWidth, GEPNoWrapFlags Flags)
Sign extends or truncates the GEP index Idx to IndexBitWidth bits.
Definition Context.cpp:1023
An interface for handling events and managing outputs during interpretation.
Definition Context.h:166
EventHandler & Handler
DiagnosticReporter reportError()
std::pair< MemoryObject *, uint64_t > verifyMemAccess(const Pointer &Ptr, uint64_t AccessSize, Align Alignment, bool IsStore)
Check if the upcoming memory access is valid.
void executeMemSet(const AnyValue &Dest, const AnyValue &Val, const AnyValue &Length)
Fill Length bytes at Dest with Val.
ExecutorBase(Context &C, EventHandler &H)
std::optional< ProgramExitInfo > ExitInfo
std::optional< ProgramExitInfo > getExitInfo() const
void requestProgramExit(ProgramExitInfo::ProgramExitKind Kind, uint64_t ExitCode=0)
DiagnosticReporter reportImmediateUB()
void store(const AnyValue &Ptr, Align Alignment, const AnyValue &Val, Type *ValTy)
void executeMemTransfer(const AnyValue &Dest, const AnyValue &Src, const AnyValue &Length, Intrinsic::ID IID, bool IsLibCall)
Copy Length bytes from Src to Dest according to the intrinsic IID.
Instruction executor using the visitor pattern.
void visitAShr(BinaryOperator &I)
void visitCallInst(CallInst &CI)
void visitLoadInst(LoadInst &LI)
void visitFAdd(BinaryOperator &I)
void visitZExtInst(ZExtInst &ZExt)
void visitReturnInst(ReturnInst &RI)
void visitFPToSIInst(FPToSIInst &FPToSI)
void visitSub(BinaryOperator &I)
void visitBitInsertInst(BitInsertInst &BII)
AnyValue callIntrinsic(CallBase &CB, ArrayRef< AnyValue > Args)
AnyValue computeSelect(const AnyValue &CondVal, const AnyValue &TVVal, const AnyValue &FVVal, Type *Ty, FastMathFlags FMF)
Computes select CondVal, TVVal, FVVal of type Ty with fast-math flags FMF.
void visitURem(BinaryOperator &I)
void visitSRem(BinaryOperator &I)
void visitFPToIntInst(Instruction &I, bool IsUnsigned)
void visitFPConvInst(Instruction &I)
AnyValue countTrailingZeroElements(Type *RetTy, ArrayRef< AnyValue > Vec, bool IsZeroPoison, size_t Length)
void visitIndirectBrInst(IndirectBrInst &IBI)
void visitOr(BinaryOperator &I)
void visitShuffleVectorInst(ShuffleVectorInst &SVI)
void visitPtrToInt(PtrToIntInst &I)
void visitUncondBrInst(UncondBrInst &BI)
void visitInsertValueInst(InsertValueInst &IVI)
void setFrameStackInaccessible(Frame &F, bool Inaccessible)
void visitSExtInst(SExtInst &SExt)
void visitStoreInst(StoreInst &SI)
void visitShl(BinaryOperator &I)
AnyValue computeDivRem(unsigned Opcode, const AnyValue &LHS, const AnyValue &RHS, bool IsExact=false)
void visitTruncInst(TruncInst &Trunc)
void visitUDiv(BinaryOperator &I)
void visitInvokeInst(InvokeInst &II)
void visitPtrToAddr(PtrToAddrInst &I)
void visitAllocaInst(AllocaInst &AI)
InstExecutor(Context &C, EventHandler &H, Function &F, ArrayRef< AnyValue > Args, AnyValue &RetVal)
void visitIntToPtr(IntToPtrInst &I)
void visitFDiv(BinaryOperator &I)
void visitXor(BinaryOperator &I)
void visitUIToFPInst(UIToFPInst &UIToFP)
void visitBitCastInst(BitCastInst &BCI)
AnyValue callLibFunc(CallBase &CB, Function *ResolvedCallee, ArrayRef< AnyValue > CalleeArgs)
void visitCondBrInst(CondBrInst &BI)
void visitGetElementPtrInst(GetElementPtrInst &GEP)
void handleMetadata(Type *Ty, AnyValue &V, Instruction &I)
Handle both poison-generating and UB-implying metadata on instructions.
void visitFreezeInst(FreezeInst &FI)
void visitBitExtractInst(BitExtractInst &BEI)
void visitSIToFPInst(SIToFPInst &SIToFP)
void visitSelect(SelectInst &SI)
void visitFCmpInst(FCmpInst &I)
void visitAnd(BinaryOperator &I)
void visitFPExtInst(FPExtInst &FPExt)
void visitLShr(BinaryOperator &I)
void visitAdd(BinaryOperator &I)
void visitExtractValueInst(ExtractValueInst &EVI)
void visitIntToFPInst(Instruction &I, bool IsSigned)
void visitFRem(BinaryOperator &I)
void visitCallBrInst(CallBrInst &CI)
void visitFSub(BinaryOperator &I)
void visitSDiv(BinaryOperator &I)
void handleAttributes(Type *Ty, AnyValue &V, AttributeSet AttrsAtCallSite, AttributeSet AttrsAtCallee)
Handle both poison-generating and UB-implying attributes for parameters and return values.
void visitFPTruncInst(FPTruncInst &FPTrunc)
void visitInstruction(Instruction &I)
void visitFPToUIInst(FPToUIInst &FPToUI)
void enterCall(CallBase &CB)
void visitInsertElementInst(InsertElementInst &IEI)
void visitMul(BinaryOperator &I)
void visitSwitchInst(SwitchInst &SI)
ProgramExitInfo runMainLoop()
This function implements the main interpreter loop.
void visitFMul(BinaryOperator &I)
AnyValue callVectorReduction(Type *RetTy, FastMathFlags FMF, Intrinsic::ID IID, ArrayRef< AnyValue > Args)
void visitICmpInst(ICmpInst &I)
void visitExtractElementInst(ExtractElementInst &EEI)
void visitUnreachableInst(UnreachableInst &)
void visitFNeg(UnaryOperator &I)
const APInt & address() const
Definition Value.h:247
Pointer getWithNewAddr(const APInt &NewAddr) const
Definition Value.h:238
LLVM_ABI bool isNullPtr(unsigned AS, const DataLayout &DL) const
Definition Value.cpp:60
Components of a pointer excluding address.
Definition Value.h:188
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
LLVM_ABI APInt mulhu(const APInt &C1, const APInt &C2)
Performs (2*N)-bit multiplication on zero-extended operands.
Definition APInt.cpp:3184
LLVM_ABI APInt RoundingUDiv(const APInt &A, const APInt &B, APInt::Rounding RM)
Return A unsign-divided by B, rounded by the given rounding mode.
Definition APInt.cpp:2810
LLVM_ABI APInt pext(const APInt &Val, const APInt &Mask)
Perform a "compress" operation, also known as pext or bext.
Definition APInt.cpp:3264
LLVM_ABI APInt mulhs(const APInt &C1, const APInt &C2)
Performs (2*N)-bit multiplication on sign-extended operands.
Definition APInt.cpp:3176
const APInt & smin(const APInt &A, const APInt &B)
Determine the smaller of two APInts considered to be signed.
Definition APInt.h:2274
const APInt & smax(const APInt &A, const APInt &B)
Determine the larger of two APInts considered to be signed.
Definition APInt.h:2279
LLVM_ABI APInt clmul(const APInt &LHS, const APInt &RHS)
Perform a carry-less multiply, also known as XOR multiplication, and return low-bits.
Definition APInt.cpp:3244
const APInt & umin(const APInt &A, const APInt &B)
Determine the smaller of two APInts considered to be unsigned.
Definition APInt.h:2284
LLVM_ABI APInt pdep(const APInt &Val, const APInt &Mask)
Perform an "expand" operation, also known as pdep or bdep.
Definition APInt.cpp:3274
const APInt & umax(const APInt &A, const APInt &B)
Determine the larger of two APInts considered to be unsigned.
Definition APInt.h:2289
LLVM_ABI StringRef getBaseName(ID id)
Return the LLVM name for an intrinsic, without encoded types for overloading, such as "llvm....
std::enable_if_t< detail::IsValidPointer< X, Y >::value, X * > extract(Y &&MD)
Extract a Value from Metadata.
Definition Metadata.h:680
static void applyNoFPClassAttr(AnyValue &V, FPClassTest NoFPClass)
BooleanKind
Tri-state boolean value.
Definition Value.h:142
static void applyAlignAttr(AnyValue &V, Align Alignment)
static bool violatesDereferenceableBytesAttr(const AnyValue &V, uint64_t Bytes, bool OrNull, unsigned AS, Context &Ctx)
Assumes V is either a poison or a pointer.
static void applyNonNullAttr(AnyValue &V, unsigned AS, const DataLayout &DL)
AnyValue addNoWrap(const APInt &LHS, const APInt &RHS, bool HasNSW, bool HasNUW)
Definition Value.h:476
AnyValue subNoWrap(const APInt &LHS, const APInt &RHS, bool HasNSW, bool HasNUW)
Definition Value.h:487
static void forEachScalarValue(AnyValue &V, function_ref< void(AnyValue &)> Visit)
Visit the scalar values recursively.
NaNPropagationBehavior
Definition Context.h:65
static void applyRangeAttr(AnyValue &V, const ConstantRange &CR)
static bool violatesNoUndefAttr(const AnyValue &V)
AnyValue mulNoWrap(const APInt &LHS, const APInt &RHS, bool HasNSW, bool HasNUW)
Definition Value.h:498
auto drop_begin(T &&RangeOrContainer, size_t N=1)
Return a range covering RangeOrContainer with the first N elements excluded.
Definition STLExtras.h:316
@ Offset
Definition DWP.cpp:577
@ Length
Definition DWP.cpp:577
detail::zippy< detail::zip_shortest, T, U, Args... > zip(T &&t, U &&u, Args &&...args)
zip iterator for two or more iteratable types.
Definition STLExtras.h:846
unsigned char Boolean
Definition ConvertUTF.h:132
void fill(R &&Range, T &&Value)
Provide wrappers to std::fill which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1775
auto size(R &&Range, std::enable_if_t< std::is_base_of< std::random_access_iterator_tag, typename std::iterator_traits< decltype(Range.begin())>::iterator_category >::value, void > *=nullptr)
Get the size of a range.
Definition STLExtras.h:1685
detail::zippy< detail::zip_first, T, U, Args... > zip_equal(T &&t, U &&u, Args &&...args)
zip iterator that assumes that all iteratees have the same length.
Definition STLExtras.h:856
BundleAttr getBundleAttrFromOBU(OperandBundleUse OBU)
auto enumerate(FirstRange &&First, RestRanges &&...Rest)
Given two or more input ranges, returns a new range whose values are tuples (A, B,...
Definition STLExtras.h:2575
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:643
APFloat abs(APFloat X)
Returns the absolute value of the argument.
Definition APFloat.h:1764
LLVM_READONLY APFloat maximum(const APFloat &A, const APFloat &B)
Implements IEEE 754-2019 maximum semantics.
Definition APFloat.h:1844
constexpr bool isUIntN(unsigned N, uint64_t x)
Checks if an unsigned integer fits into the given (dynamic) bit width.
Definition MathExtras.h:244
OutputIt transform(R &&Range, OutputIt d_first, UnaryFunction F)
Wrapper function around std::transform to apply a function to a range and store the result elsewhere.
Definition STLExtras.h:2042
bool any_of(R &&range, UnaryPredicate P)
Provide wrappers to std::any_of which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1762
LLVM_READONLY APFloat maxnum(const APFloat &A, const APFloat &B)
Implements IEEE-754 2008 maxNum semantics.
Definition APFloat.h:1799
LLVM_READONLY APFloat minimumnum(const APFloat &A, const APFloat &B)
Implements IEEE 754-2019 minimumNumber semantics.
Definition APFloat.h:1830
FPClassTest
Floating-point class tests, supported by 'is_fpclass' intrinsic.
LLVM_ABI unsigned getDeinterleaveIntrinsicFactor(Intrinsic::ID ID)
Returns the corresponding factor of llvm.vector.deinterleaveN intrinsics.
LLVM_ABI unsigned getInterleaveIntrinsicFactor(Intrinsic::ID ID)
Returns the corresponding factor of llvm.vector.interleaveN intrinsics.
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
constexpr int PoisonMaskElem
@ Other
Any other memory.
Definition ModRef.h:68
LLVM_READONLY APFloat minnum(const APFloat &A, const APFloat &B)
Implements IEEE-754 2008 minNum semantics.
Definition APFloat.h:1780
std::enable_if_t< std::is_unsigned_v< T >, T > SaturatingMultiply(T X, T Y, bool *ResultOverflowed=nullptr)
Multiply two unsigned integers, X and Y, of type T.
Definition MathExtras.h:638
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Count
Definition InstrProf.h:145
DWARFExpression::Operation Op
@ NearestTiesToEven
roundTiesToEven.
OutputIt copy(R &&Range, OutputIt Out)
Definition STLExtras.h:1901
constexpr unsigned BitWidth
auto count_if(R &&Range, UnaryPredicate P)
Wrapper function around std::count_if to count the number of times an element satisfying a given pred...
Definition STLExtras.h:2035
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:559
constexpr bool isIntN(unsigned N, int64_t x)
Checks if an signed integer fits into the given (dynamic) bit width.
Definition MathExtras.h:249
unsigned Log2(Align A)
Returns the log2 of the alignment.
Definition Alignment.h:202
LLVM_READONLY APFloat minimum(const APFloat &A, const APFloat &B)
Implements IEEE 754-2019 minimum semantics.
Definition APFloat.h:1817
LLVM_READONLY APFloat maximumnum(const APFloat &A, const APFloat &B)
Implements IEEE 754-2019 maximumNumber semantics.
Definition APFloat.h:1857
void swap(llvm::BitVector &LHS, llvm::BitVector &RHS)
Implement std::swap in terms of BitVector swap.
Definition BitVector.h:881
#define N
This struct is a compact representation of a valid (non-zero power of two) alignment.
Definition Alignment.h:39
constexpr uint64_t value() const
This is a hole in the type system and should not be abused.
Definition Alignment.h:82
Represent subnormal handling kind for floating point instruction inputs and outputs.
DenormalModeKind Input
Denormal treatment kind for floating point instruction inputs in the default floating-point environme...
DenormalModeKind
Represent handled modes for denormal (aka subnormal) modes in the floating point environment.
@ PreserveSign
The sign of a flushed-to-zero number is preserved in the sign of 0.
@ PositiveZero
Denormals are flushed to positive zero.
DenormalModeKind Output
Denormal flushing mode for floating point instruction results in the default floating point environme...
This struct is a compact representation of a valid (power of two) or undefined (0) alignment.
Definition Alignment.h:111
Align valueOrOne() const
For convenience, returns a valid alignment or 1 if undefined.
Definition Alignment.h:135
A lightweight accessor for an operand bundle meant to be passed around by value.
ArrayRef< Use > Inputs
unsigned int precision
Definition APFloat.h:1059
Representation of a byte in memory.
Definition Value.h:43
static Byte undef()
Definition Value.h:51
static Byte poison()
Definition Value.h:50
static Byte concrete(uint8_t Val)
Definition Value.h:52
Context for a function call.
BasicBlock::iterator PC
ArrayRef< AnyValue > Args
CallBase * CallSite
SmallVector< IntrusiveRefCntPtr< MemoryObject > > Allocas
FrameState State
Function & Func
AnyValue & RetVal