1 //===- ValueTrackingTest.cpp - ValueTracking tests ------------------------===//
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 #include "llvm/Analysis/ValueTracking.h"
10 #include "llvm/Analysis/AssumptionCache.h"
11 #include "llvm/AsmParser/Parser.h"
12 #include "llvm/IR/ConstantRange.h"
13 #include "llvm/IR/Dominators.h"
14 #include "llvm/IR/Function.h"
15 #include "llvm/IR/InstIterator.h"
16 #include "llvm/IR/Instructions.h"
17 #include "llvm/IR/LLVMContext.h"
18 #include "llvm/IR/Module.h"
19 #include "llvm/Support/ErrorHandling.h"
20 #include "llvm/Support/KnownBits.h"
21 #include "llvm/Support/SourceMgr.h"
22 #include "llvm/Transforms/Utils/Local.h"
23 #include "gtest/gtest.h"
24 
25 using namespace llvm;
26 
27 namespace {
28 
29 static Instruction *findInstructionByNameOrNull(Function *F, StringRef Name) {
30   for (Instruction &I : instructions(F))
31     if (I.getName() == Name)
32       return &I;
33 
34   return nullptr;
35 }
36 
37 static Instruction &findInstructionByName(Function *F, StringRef Name) {
38   auto *I = findInstructionByNameOrNull(F, Name);
39   if (I)
40     return *I;
41 
42   llvm_unreachable("Expected value not found");
43 }
44 
45 class ValueTrackingTest : public testing::Test {
46 protected:
47   std::unique_ptr<Module> parseModule(StringRef Assembly) {
48     SMDiagnostic Error;
49     std::unique_ptr<Module> M = parseAssemblyString(Assembly, Error, Context);
50 
51     std::string errMsg;
52     raw_string_ostream os(errMsg);
53     Error.print("", os);
54     EXPECT_TRUE(M) << os.str();
55 
56     return M;
57   }
58 
59   void parseAssembly(StringRef Assembly) {
60     M = parseModule(Assembly);
61     ASSERT_TRUE(M);
62 
63     F = M->getFunction("test");
64     ASSERT_TRUE(F) << "Test must have a function @test";
65     if (!F)
66       return;
67 
68     A = findInstructionByNameOrNull(F, "A");
69     ASSERT_TRUE(A) << "@test must have an instruction %A";
70     A2 = findInstructionByNameOrNull(F, "A2");
71     A3 = findInstructionByNameOrNull(F, "A3");
72     A4 = findInstructionByNameOrNull(F, "A4");
73 
74     CxtI = findInstructionByNameOrNull(F, "CxtI");
75     CxtI2 = findInstructionByNameOrNull(F, "CxtI2");
76     CxtI3 = findInstructionByNameOrNull(F, "CxtI3");
77   }
78 
79   LLVMContext Context;
80   std::unique_ptr<Module> M;
81   Function *F = nullptr;
82   Instruction *A = nullptr;
83   // Instructions (optional)
84   Instruction *A2 = nullptr, *A3 = nullptr, *A4 = nullptr;
85 
86   // Context instructions (optional)
87   Instruction *CxtI = nullptr, *CxtI2 = nullptr, *CxtI3 = nullptr;
88 };
89 
90 class MatchSelectPatternTest : public ValueTrackingTest {
91 protected:
92   void expectPattern(const SelectPatternResult &P) {
93     Value *LHS, *RHS;
94     Instruction::CastOps CastOp;
95     SelectPatternResult R = matchSelectPattern(A, LHS, RHS, &CastOp);
96     EXPECT_EQ(P.Flavor, R.Flavor);
97     EXPECT_EQ(P.NaNBehavior, R.NaNBehavior);
98     EXPECT_EQ(P.Ordered, R.Ordered);
99   }
100 };
101 
102 class ComputeKnownBitsTest : public ValueTrackingTest {
103 protected:
104   void expectKnownBits(uint64_t Zero, uint64_t One) {
105     auto Known = computeKnownBits(A, M->getDataLayout());
106     ASSERT_FALSE(Known.hasConflict());
107     EXPECT_EQ(Known.One.getZExtValue(), One);
108     EXPECT_EQ(Known.Zero.getZExtValue(), Zero);
109   }
110 };
111 
112 }
113 
114 TEST_F(MatchSelectPatternTest, SimpleFMin) {
115   parseAssembly(
116       "define float @test(float %a) {\n"
117       "  %1 = fcmp ult float %a, 5.0\n"
118       "  %A = select i1 %1, float %a, float 5.0\n"
119       "  ret float %A\n"
120       "}\n");
121   expectPattern({SPF_FMINNUM, SPNB_RETURNS_NAN, false});
122 }
123 
124 TEST_F(MatchSelectPatternTest, SimpleFMax) {
125   parseAssembly(
126       "define float @test(float %a) {\n"
127       "  %1 = fcmp ogt float %a, 5.0\n"
128       "  %A = select i1 %1, float %a, float 5.0\n"
129       "  ret float %A\n"
130       "}\n");
131   expectPattern({SPF_FMAXNUM, SPNB_RETURNS_OTHER, true});
132 }
133 
134 TEST_F(MatchSelectPatternTest, SwappedFMax) {
135   parseAssembly(
136       "define float @test(float %a) {\n"
137       "  %1 = fcmp olt float 5.0, %a\n"
138       "  %A = select i1 %1, float %a, float 5.0\n"
139       "  ret float %A\n"
140       "}\n");
141   expectPattern({SPF_FMAXNUM, SPNB_RETURNS_OTHER, false});
142 }
143 
144 TEST_F(MatchSelectPatternTest, SwappedFMax2) {
145   parseAssembly(
146       "define float @test(float %a) {\n"
147       "  %1 = fcmp olt float %a, 5.0\n"
148       "  %A = select i1 %1, float 5.0, float %a\n"
149       "  ret float %A\n"
150       "}\n");
151   expectPattern({SPF_FMAXNUM, SPNB_RETURNS_NAN, false});
152 }
153 
154 TEST_F(MatchSelectPatternTest, SwappedFMax3) {
155   parseAssembly(
156       "define float @test(float %a) {\n"
157       "  %1 = fcmp ult float %a, 5.0\n"
158       "  %A = select i1 %1, float 5.0, float %a\n"
159       "  ret float %A\n"
160       "}\n");
161   expectPattern({SPF_FMAXNUM, SPNB_RETURNS_OTHER, true});
162 }
163 
164 TEST_F(MatchSelectPatternTest, FastFMin) {
165   parseAssembly(
166       "define float @test(float %a) {\n"
167       "  %1 = fcmp nnan olt float %a, 5.0\n"
168       "  %A = select i1 %1, float %a, float 5.0\n"
169       "  ret float %A\n"
170       "}\n");
171   expectPattern({SPF_FMINNUM, SPNB_RETURNS_ANY, false});
172 }
173 
174 TEST_F(MatchSelectPatternTest, FMinConstantZero) {
175   parseAssembly(
176       "define float @test(float %a) {\n"
177       "  %1 = fcmp ole float %a, 0.0\n"
178       "  %A = select i1 %1, float %a, float 0.0\n"
179       "  ret float %A\n"
180       "}\n");
181   // This shouldn't be matched, as %a could be -0.0.
182   expectPattern({SPF_UNKNOWN, SPNB_NA, false});
183 }
184 
185 TEST_F(MatchSelectPatternTest, FMinConstantZeroNsz) {
186   parseAssembly(
187       "define float @test(float %a) {\n"
188       "  %1 = fcmp nsz ole float %a, 0.0\n"
189       "  %A = select i1 %1, float %a, float 0.0\n"
190       "  ret float %A\n"
191       "}\n");
192   // But this should be, because we've ignored signed zeroes.
193   expectPattern({SPF_FMINNUM, SPNB_RETURNS_OTHER, true});
194 }
195 
196 TEST_F(MatchSelectPatternTest, FMinMismatchConstantZero1) {
197   parseAssembly(
198       "define float @test(float %a) {\n"
199       "  %1 = fcmp olt float -0.0, %a\n"
200       "  %A = select i1 %1, float 0.0, float %a\n"
201       "  ret float %A\n"
202       "}\n");
203   // The sign of zero doesn't matter in fcmp.
204   expectPattern({SPF_FMINNUM, SPNB_RETURNS_NAN, true});
205 }
206 
207 TEST_F(MatchSelectPatternTest, FMinMismatchConstantZero2) {
208   parseAssembly(
209       "define float @test(float %a) {\n"
210       "  %1 = fcmp ogt float %a, -0.0\n"
211       "  %A = select i1 %1, float 0.0, float %a\n"
212       "  ret float %A\n"
213       "}\n");
214   // The sign of zero doesn't matter in fcmp.
215   expectPattern({SPF_FMINNUM, SPNB_RETURNS_NAN, false});
216 }
217 
218 TEST_F(MatchSelectPatternTest, FMinMismatchConstantZero3) {
219   parseAssembly(
220       "define float @test(float %a) {\n"
221       "  %1 = fcmp olt float 0.0, %a\n"
222       "  %A = select i1 %1, float -0.0, float %a\n"
223       "  ret float %A\n"
224       "}\n");
225   // The sign of zero doesn't matter in fcmp.
226   expectPattern({SPF_FMINNUM, SPNB_RETURNS_NAN, true});
227 }
228 
229 TEST_F(MatchSelectPatternTest, FMinMismatchConstantZero4) {
230   parseAssembly(
231       "define float @test(float %a) {\n"
232       "  %1 = fcmp ogt float %a, 0.0\n"
233       "  %A = select i1 %1, float -0.0, float %a\n"
234       "  ret float %A\n"
235       "}\n");
236   // The sign of zero doesn't matter in fcmp.
237   expectPattern({SPF_FMINNUM, SPNB_RETURNS_NAN, false});
238 }
239 
240 TEST_F(MatchSelectPatternTest, FMinMismatchConstantZero5) {
241   parseAssembly(
242       "define float @test(float %a) {\n"
243       "  %1 = fcmp ogt float -0.0, %a\n"
244       "  %A = select i1 %1, float %a, float 0.0\n"
245       "  ret float %A\n"
246       "}\n");
247   // The sign of zero doesn't matter in fcmp.
248   expectPattern({SPF_FMINNUM, SPNB_RETURNS_OTHER, false});
249 }
250 
251 TEST_F(MatchSelectPatternTest, FMinMismatchConstantZero6) {
252   parseAssembly(
253       "define float @test(float %a) {\n"
254       "  %1 = fcmp olt float %a, -0.0\n"
255       "  %A = select i1 %1, float %a, float 0.0\n"
256       "  ret float %A\n"
257       "}\n");
258   // The sign of zero doesn't matter in fcmp.
259   expectPattern({SPF_FMINNUM, SPNB_RETURNS_OTHER, true});
260 }
261 
262 TEST_F(MatchSelectPatternTest, FMinMismatchConstantZero7) {
263   parseAssembly(
264       "define float @test(float %a) {\n"
265       "  %1 = fcmp ogt float 0.0, %a\n"
266       "  %A = select i1 %1, float %a, float -0.0\n"
267       "  ret float %A\n"
268       "}\n");
269   // The sign of zero doesn't matter in fcmp.
270   expectPattern({SPF_FMINNUM, SPNB_RETURNS_OTHER, false});
271 }
272 
273 TEST_F(MatchSelectPatternTest, FMinMismatchConstantZero8) {
274   parseAssembly(
275       "define float @test(float %a) {\n"
276       "  %1 = fcmp olt float %a, 0.0\n"
277       "  %A = select i1 %1, float %a, float -0.0\n"
278       "  ret float %A\n"
279       "}\n");
280   // The sign of zero doesn't matter in fcmp.
281   expectPattern({SPF_FMINNUM, SPNB_RETURNS_OTHER, true});
282 }
283 
284 TEST_F(MatchSelectPatternTest, FMaxMismatchConstantZero1) {
285   parseAssembly(
286       "define float @test(float %a) {\n"
287       "  %1 = fcmp ogt float -0.0, %a\n"
288       "  %A = select i1 %1, float 0.0, float %a\n"
289       "  ret float %A\n"
290       "}\n");
291   // The sign of zero doesn't matter in fcmp.
292   expectPattern({SPF_FMAXNUM, SPNB_RETURNS_NAN, true});
293 }
294 
295 TEST_F(MatchSelectPatternTest, FMaxMismatchConstantZero2) {
296   parseAssembly(
297       "define float @test(float %a) {\n"
298       "  %1 = fcmp olt float %a, -0.0\n"
299       "  %A = select i1 %1, float 0.0, float %a\n"
300       "  ret float %A\n"
301       "}\n");
302   // The sign of zero doesn't matter in fcmp.
303   expectPattern({SPF_FMAXNUM, SPNB_RETURNS_NAN, false});
304 }
305 
306 TEST_F(MatchSelectPatternTest, FMaxMismatchConstantZero3) {
307   parseAssembly(
308       "define float @test(float %a) {\n"
309       "  %1 = fcmp ogt float 0.0, %a\n"
310       "  %A = select i1 %1, float -0.0, float %a\n"
311       "  ret float %A\n"
312       "}\n");
313   // The sign of zero doesn't matter in fcmp.
314   expectPattern({SPF_FMAXNUM, SPNB_RETURNS_NAN, true});
315 }
316 
317 TEST_F(MatchSelectPatternTest, FMaxMismatchConstantZero4) {
318   parseAssembly(
319       "define float @test(float %a) {\n"
320       "  %1 = fcmp olt float %a, 0.0\n"
321       "  %A = select i1 %1, float -0.0, float %a\n"
322       "  ret float %A\n"
323       "}\n");
324   // The sign of zero doesn't matter in fcmp.
325   expectPattern({SPF_FMAXNUM, SPNB_RETURNS_NAN, false});
326 }
327 
328 TEST_F(MatchSelectPatternTest, FMaxMismatchConstantZero5) {
329   parseAssembly(
330       "define float @test(float %a) {\n"
331       "  %1 = fcmp olt float -0.0, %a\n"
332       "  %A = select i1 %1, float %a, float 0.0\n"
333       "  ret float %A\n"
334       "}\n");
335   // The sign of zero doesn't matter in fcmp.
336   expectPattern({SPF_FMAXNUM, SPNB_RETURNS_OTHER, false});
337 }
338 
339 TEST_F(MatchSelectPatternTest, FMaxMismatchConstantZero6) {
340   parseAssembly(
341       "define float @test(float %a) {\n"
342       "  %1 = fcmp ogt float %a, -0.0\n"
343       "  %A = select i1 %1, float %a, float 0.0\n"
344       "  ret float %A\n"
345       "}\n");
346   // The sign of zero doesn't matter in fcmp.
347   expectPattern({SPF_FMAXNUM, SPNB_RETURNS_OTHER, true});
348 }
349 
350 TEST_F(MatchSelectPatternTest, FMaxMismatchConstantZero7) {
351   parseAssembly(
352       "define float @test(float %a) {\n"
353       "  %1 = fcmp olt float 0.0, %a\n"
354       "  %A = select i1 %1, float %a, float -0.0\n"
355       "  ret float %A\n"
356       "}\n");
357   // The sign of zero doesn't matter in fcmp.
358   expectPattern({SPF_FMAXNUM, SPNB_RETURNS_OTHER, false});
359 }
360 
361 TEST_F(MatchSelectPatternTest, FMaxMismatchConstantZero8) {
362   parseAssembly(
363       "define float @test(float %a) {\n"
364       "  %1 = fcmp ogt float %a, 0.0\n"
365       "  %A = select i1 %1, float %a, float -0.0\n"
366       "  ret float %A\n"
367       "}\n");
368   // The sign of zero doesn't matter in fcmp.
369   expectPattern({SPF_FMAXNUM, SPNB_RETURNS_OTHER, true});
370 }
371 
372 TEST_F(MatchSelectPatternTest, FMinMismatchConstantZeroVecUndef) {
373   parseAssembly(
374       "define <2 x float> @test(<2 x float> %a) {\n"
375       "  %1 = fcmp ogt <2 x float> %a, <float -0.0, float -0.0>\n"
376       "  %A = select <2 x i1> %1, <2 x float> <float undef, float 0.0>, <2 x float> %a\n"
377       "  ret <2 x float> %A\n"
378       "}\n");
379   // An undef in a vector constant can not be back-propagated for this analysis.
380   expectPattern({SPF_UNKNOWN, SPNB_NA, false});
381 }
382 
383 TEST_F(MatchSelectPatternTest, FMaxMismatchConstantZeroVecUndef) {
384   parseAssembly(
385       "define <2 x float> @test(<2 x float> %a) {\n"
386       "  %1 = fcmp ogt <2 x float> %a, zeroinitializer\n"
387       "  %A = select <2 x i1> %1, <2 x float> %a, <2 x float> <float -0.0, float undef>\n"
388       "  ret <2 x float> %A\n"
389       "}\n");
390   // An undef in a vector constant can not be back-propagated for this analysis.
391   expectPattern({SPF_UNKNOWN, SPNB_NA, false});
392 }
393 
394 TEST_F(MatchSelectPatternTest, VectorFMinimum) {
395   parseAssembly(
396       "define <4 x float> @test(<4 x float> %a) {\n"
397       "  %1 = fcmp ule <4 x float> %a, \n"
398       "    <float 5.0, float 5.0, float 5.0, float 5.0>\n"
399       "  %A = select <4 x i1> %1, <4 x float> %a,\n"
400       "     <4 x float> <float 5.0, float 5.0, float 5.0, float 5.0>\n"
401       "  ret <4 x float> %A\n"
402       "}\n");
403   // Check that pattern matching works on vectors where each lane has the same
404   // unordered pattern.
405   expectPattern({SPF_FMINNUM, SPNB_RETURNS_NAN, false});
406 }
407 
408 TEST_F(MatchSelectPatternTest, VectorFMinOtherOrdered) {
409   parseAssembly(
410       "define <4 x float> @test(<4 x float> %a) {\n"
411       "  %1 = fcmp ole <4 x float> %a, \n"
412       "    <float 5.0, float 5.0, float 5.0, float 5.0>\n"
413       "  %A = select <4 x i1> %1, <4 x float> %a,\n"
414       "     <4 x float> <float 5.0, float 5.0, float 5.0, float 5.0>\n"
415       "  ret <4 x float> %A\n"
416       "}\n");
417   // Check that pattern matching works on vectors where each lane has the same
418   // ordered pattern.
419   expectPattern({SPF_FMINNUM, SPNB_RETURNS_OTHER, true});
420 }
421 
422 TEST_F(MatchSelectPatternTest, VectorNotFMinimum) {
423   parseAssembly(
424       "define <4 x float> @test(<4 x float> %a) {\n"
425       "  %1 = fcmp ule <4 x float> %a, \n"
426       "    <float 5.0, float 0x7ff8000000000000, float 5.0, float 5.0>\n"
427       "  %A = select <4 x i1> %1, <4 x float> %a,\n"
428       "     <4 x float> <float 5.0, float 0x7ff8000000000000, float 5.0, float "
429       "5.0>\n"
430       "  ret <4 x float> %A\n"
431       "}\n");
432   // The lane that contains a NaN (0x7ff80...) behaves like a
433   // non-NaN-propagating min and the other lines behave like a NaN-propagating
434   // min, so check that neither is returned.
435   expectPattern({SPF_UNKNOWN, SPNB_NA, false});
436 }
437 
438 TEST_F(MatchSelectPatternTest, VectorNotFMinZero) {
439   parseAssembly(
440       "define <4 x float> @test(<4 x float> %a) {\n"
441       "  %1 = fcmp ule <4 x float> %a, \n"
442       "    <float 5.0, float -0.0, float 5.0, float 5.0>\n"
443       "  %A = select <4 x i1> %1, <4 x float> %a,\n"
444       "     <4 x float> <float 5.0, float 0.0, float 5.0, float 5.0>\n"
445       "  ret <4 x float> %A\n"
446       "}\n");
447   // Always selects the second lane of %a if it is positive or negative zero, so
448   // this is stricter than a min.
449   expectPattern({SPF_UNKNOWN, SPNB_NA, false});
450 }
451 
452 TEST_F(MatchSelectPatternTest, DoubleCastU) {
453   parseAssembly(
454       "define i32 @test(i8 %a, i8 %b) {\n"
455       "  %1 = icmp ult i8 %a, %b\n"
456       "  %2 = zext i8 %a to i32\n"
457       "  %3 = zext i8 %b to i32\n"
458       "  %A = select i1 %1, i32 %2, i32 %3\n"
459       "  ret i32 %A\n"
460       "}\n");
461   // We should be able to look through the situation where we cast both operands
462   // to the select.
463   expectPattern({SPF_UMIN, SPNB_NA, false});
464 }
465 
466 TEST_F(MatchSelectPatternTest, DoubleCastS) {
467   parseAssembly(
468       "define i32 @test(i8 %a, i8 %b) {\n"
469       "  %1 = icmp slt i8 %a, %b\n"
470       "  %2 = sext i8 %a to i32\n"
471       "  %3 = sext i8 %b to i32\n"
472       "  %A = select i1 %1, i32 %2, i32 %3\n"
473       "  ret i32 %A\n"
474       "}\n");
475   // We should be able to look through the situation where we cast both operands
476   // to the select.
477   expectPattern({SPF_SMIN, SPNB_NA, false});
478 }
479 
480 TEST_F(MatchSelectPatternTest, DoubleCastBad) {
481   parseAssembly(
482       "define i32 @test(i8 %a, i8 %b) {\n"
483       "  %1 = icmp ult i8 %a, %b\n"
484       "  %2 = zext i8 %a to i32\n"
485       "  %3 = sext i8 %b to i32\n"
486       "  %A = select i1 %1, i32 %2, i32 %3\n"
487       "  ret i32 %A\n"
488       "}\n");
489   // The cast types here aren't the same, so we cannot match an UMIN.
490   expectPattern({SPF_UNKNOWN, SPNB_NA, false});
491 }
492 
493 TEST_F(MatchSelectPatternTest, NotNotSMin) {
494   parseAssembly(
495       "define i8 @test(i8 %a, i8 %b) {\n"
496       "  %cmp = icmp sgt i8 %a, %b\n"
497       "  %an = xor i8 %a, -1\n"
498       "  %bn = xor i8 %b, -1\n"
499       "  %A = select i1 %cmp, i8 %an, i8 %bn\n"
500       "  ret i8 %A\n"
501       "}\n");
502   expectPattern({SPF_SMIN, SPNB_NA, false});
503 }
504 
505 TEST_F(MatchSelectPatternTest, NotNotSMinSwap) {
506   parseAssembly(
507       "define <2 x i8> @test(<2 x i8> %a, <2 x i8> %b) {\n"
508       "  %cmp = icmp slt <2 x i8> %a, %b\n"
509       "  %an = xor <2 x i8> %a, <i8 -1, i8-1>\n"
510       "  %bn = xor <2 x i8> %b, <i8 -1, i8-1>\n"
511       "  %A = select <2 x i1> %cmp, <2 x i8> %bn, <2 x i8> %an\n"
512       "  ret <2 x i8> %A\n"
513       "}\n");
514   expectPattern({SPF_SMIN, SPNB_NA, false});
515 }
516 
517 TEST_F(MatchSelectPatternTest, NotNotSMax) {
518   parseAssembly(
519       "define i8 @test(i8 %a, i8 %b) {\n"
520       "  %cmp = icmp slt i8 %a, %b\n"
521       "  %an = xor i8 %a, -1\n"
522       "  %bn = xor i8 %b, -1\n"
523       "  %A = select i1 %cmp, i8 %an, i8 %bn\n"
524       "  ret i8 %A\n"
525       "}\n");
526   expectPattern({SPF_SMAX, SPNB_NA, false});
527 }
528 
529 TEST_F(MatchSelectPatternTest, NotNotSMaxSwap) {
530   parseAssembly(
531       "define <2 x i8> @test(<2 x i8> %a, <2 x i8> %b) {\n"
532       "  %cmp = icmp sgt <2 x i8> %a, %b\n"
533       "  %an = xor <2 x i8> %a, <i8 -1, i8-1>\n"
534       "  %bn = xor <2 x i8> %b, <i8 -1, i8-1>\n"
535       "  %A = select <2 x i1> %cmp, <2 x i8> %bn, <2 x i8> %an\n"
536       "  ret <2 x i8> %A\n"
537       "}\n");
538   expectPattern({SPF_SMAX, SPNB_NA, false});
539 }
540 
541 TEST_F(MatchSelectPatternTest, NotNotUMin) {
542   parseAssembly(
543       "define <2 x i8> @test(<2 x i8> %a, <2 x i8> %b) {\n"
544       "  %cmp = icmp ugt <2 x i8> %a, %b\n"
545       "  %an = xor <2 x i8> %a, <i8 -1, i8-1>\n"
546       "  %bn = xor <2 x i8> %b, <i8 -1, i8-1>\n"
547       "  %A = select <2 x i1> %cmp, <2 x i8> %an, <2 x i8> %bn\n"
548       "  ret <2 x i8> %A\n"
549       "}\n");
550   expectPattern({SPF_UMIN, SPNB_NA, false});
551 }
552 
553 TEST_F(MatchSelectPatternTest, NotNotUMinSwap) {
554   parseAssembly(
555       "define i8 @test(i8 %a, i8 %b) {\n"
556       "  %cmp = icmp ult i8 %a, %b\n"
557       "  %an = xor i8 %a, -1\n"
558       "  %bn = xor i8 %b, -1\n"
559       "  %A = select i1 %cmp, i8 %bn, i8 %an\n"
560       "  ret i8 %A\n"
561       "}\n");
562   expectPattern({SPF_UMIN, SPNB_NA, false});
563 }
564 
565 TEST_F(MatchSelectPatternTest, NotNotUMax) {
566   parseAssembly(
567       "define <2 x i8> @test(<2 x i8> %a, <2 x i8> %b) {\n"
568       "  %cmp = icmp ult <2 x i8> %a, %b\n"
569       "  %an = xor <2 x i8> %a, <i8 -1, i8-1>\n"
570       "  %bn = xor <2 x i8> %b, <i8 -1, i8-1>\n"
571       "  %A = select <2 x i1> %cmp, <2 x i8> %an, <2 x i8> %bn\n"
572       "  ret <2 x i8> %A\n"
573       "}\n");
574   expectPattern({SPF_UMAX, SPNB_NA, false});
575 }
576 
577 TEST_F(MatchSelectPatternTest, NotNotUMaxSwap) {
578   parseAssembly(
579       "define i8 @test(i8 %a, i8 %b) {\n"
580       "  %cmp = icmp ugt i8 %a, %b\n"
581       "  %an = xor i8 %a, -1\n"
582       "  %bn = xor i8 %b, -1\n"
583       "  %A = select i1 %cmp, i8 %bn, i8 %an\n"
584       "  ret i8 %A\n"
585       "}\n");
586   expectPattern({SPF_UMAX, SPNB_NA, false});
587 }
588 
589 TEST_F(MatchSelectPatternTest, NotNotEq) {
590   parseAssembly(
591       "define i8 @test(i8 %a, i8 %b) {\n"
592       "  %cmp = icmp eq i8 %a, %b\n"
593       "  %an = xor i8 %a, -1\n"
594       "  %bn = xor i8 %b, -1\n"
595       "  %A = select i1 %cmp, i8 %bn, i8 %an\n"
596       "  ret i8 %A\n"
597       "}\n");
598   expectPattern({SPF_UNKNOWN, SPNB_NA, false});
599 }
600 
601 TEST_F(MatchSelectPatternTest, NotNotNe) {
602   parseAssembly(
603       "define i8 @test(i8 %a, i8 %b) {\n"
604       "  %cmp = icmp ne i8 %a, %b\n"
605       "  %an = xor i8 %a, -1\n"
606       "  %bn = xor i8 %b, -1\n"
607       "  %A = select i1 %cmp, i8 %bn, i8 %an\n"
608       "  ret i8 %A\n"
609       "}\n");
610   expectPattern({SPF_UNKNOWN, SPNB_NA, false});
611 }
612 
613 TEST(ValueTracking, GuaranteedToTransferExecutionToSuccessor) {
614   StringRef Assembly =
615       "declare void @nounwind_readonly(i32*) nounwind readonly "
616       "declare void @nounwind_argmemonly(i32*) nounwind argmemonly "
617       "declare void @throws_but_readonly(i32*) readonly "
618       "declare void @throws_but_argmemonly(i32*) argmemonly "
619       "declare void @nounwind_willreturn(i32*) nounwind willreturn"
620       " "
621       "declare void @unknown(i32*) "
622       " "
623       "define void @f(i32* %p) { "
624       "  call void @nounwind_readonly(i32* %p) "
625       "  call void @nounwind_argmemonly(i32* %p) "
626       "  call void @throws_but_readonly(i32* %p) "
627       "  call void @throws_but_argmemonly(i32* %p) "
628       "  call void @unknown(i32* %p) nounwind readonly "
629       "  call void @unknown(i32* %p) nounwind argmemonly "
630       "  call void @unknown(i32* %p) readonly "
631       "  call void @unknown(i32* %p) argmemonly "
632       "  call void @nounwind_willreturn(i32* %p)"
633       "  ret void "
634       "} ";
635 
636   LLVMContext Context;
637   SMDiagnostic Error;
638   auto M = parseAssemblyString(Assembly, Error, Context);
639   assert(M && "Bad assembly?");
640 
641   auto *F = M->getFunction("f");
642   assert(F && "Bad assembly?");
643 
644   auto &BB = F->getEntryBlock();
645   bool ExpectedAnswers[] = {
646       true,  // call void @nounwind_readonly(i32* %p)
647       true,  // call void @nounwind_argmemonly(i32* %p)
648       false, // call void @throws_but_readonly(i32* %p)
649       false, // call void @throws_but_argmemonly(i32* %p)
650       true,  // call void @unknown(i32* %p) nounwind readonly
651       true,  // call void @unknown(i32* %p) nounwind argmemonly
652       false, // call void @unknown(i32* %p) readonly
653       false, // call void @unknown(i32* %p) argmemonly
654       true,  // call void @nounwind_willreturn(i32* %p)
655       false, // ret void
656   };
657 
658   int Index = 0;
659   for (auto &I : BB) {
660     EXPECT_EQ(isGuaranteedToTransferExecutionToSuccessor(&I),
661               ExpectedAnswers[Index])
662         << "Incorrect answer at instruction " << Index << " = " << I;
663     Index++;
664   }
665 }
666 
667 TEST_F(ValueTrackingTest, ComputeNumSignBits_PR32045) {
668   parseAssembly(
669       "define i32 @test(i32 %a) {\n"
670       "  %A = ashr i32 %a, -1\n"
671       "  ret i32 %A\n"
672       "}\n");
673   EXPECT_EQ(ComputeNumSignBits(A, M->getDataLayout()), 1u);
674 }
675 
676 // No guarantees for canonical IR in this analysis, so this just bails out.
677 TEST_F(ValueTrackingTest, ComputeNumSignBits_Shuffle) {
678   parseAssembly(
679       "define <2 x i32> @test() {\n"
680       "  %A = shufflevector <2 x i32> undef, <2 x i32> undef, <2 x i32> <i32 0, i32 0>\n"
681       "  ret <2 x i32> %A\n"
682       "}\n");
683   EXPECT_EQ(ComputeNumSignBits(A, M->getDataLayout()), 1u);
684 }
685 
686 // No guarantees for canonical IR in this analysis, so a shuffle element that
687 // references an undef value means this can't return any extra information.
688 TEST_F(ValueTrackingTest, ComputeNumSignBits_Shuffle2) {
689   parseAssembly(
690       "define <2 x i32> @test(<2 x i1> %x) {\n"
691       "  %sext = sext <2 x i1> %x to <2 x i32>\n"
692       "  %A = shufflevector <2 x i32> %sext, <2 x i32> undef, <2 x i32> <i32 0, i32 2>\n"
693       "  ret <2 x i32> %A\n"
694       "}\n");
695   EXPECT_EQ(ComputeNumSignBits(A, M->getDataLayout()), 1u);
696 }
697 
698 TEST_F(ValueTrackingTest, impliesPoisonTest_Identity) {
699   parseAssembly("define void @test(i32 %x, i32 %y) {\n"
700                 "  %A = add i32 %x, %y\n"
701                 "  ret void\n"
702                 "}");
703   EXPECT_TRUE(impliesPoison(A, A));
704 }
705 
706 TEST_F(ValueTrackingTest, impliesPoisonTest_ICmp) {
707   parseAssembly("define void @test(i32 %x) {\n"
708                 "  %A2 = icmp eq i32 %x, 0\n"
709                 "  %A = icmp eq i32 %x, 1\n"
710                 "  ret void\n"
711                 "}");
712   EXPECT_TRUE(impliesPoison(A2, A));
713 }
714 
715 TEST_F(ValueTrackingTest, impliesPoisonTest_ICmpUnknown) {
716   parseAssembly("define void @test(i32 %x, i32 %y) {\n"
717                 "  %A2 = icmp eq i32 %x, %y\n"
718                 "  %A = icmp eq i32 %x, 1\n"
719                 "  ret void\n"
720                 "}");
721   EXPECT_FALSE(impliesPoison(A2, A));
722 }
723 
724 TEST_F(ValueTrackingTest, impliesPoisonTest_AddNswOkay) {
725   parseAssembly("define void @test(i32 %x) {\n"
726                 "  %A2 = add nsw i32 %x, 1\n"
727                 "  %A = add i32 %A2, 1\n"
728                 "  ret void\n"
729                 "}");
730   EXPECT_TRUE(impliesPoison(A2, A));
731 }
732 
733 TEST_F(ValueTrackingTest, impliesPoisonTest_AddNswOkay2) {
734   parseAssembly("define void @test(i32 %x) {\n"
735                 "  %A2 = add i32 %x, 1\n"
736                 "  %A = add nsw i32 %A2, 1\n"
737                 "  ret void\n"
738                 "}");
739   EXPECT_TRUE(impliesPoison(A2, A));
740 }
741 
742 TEST_F(ValueTrackingTest, impliesPoisonTest_AddNsw) {
743   parseAssembly("define void @test(i32 %x) {\n"
744                 "  %A2 = add nsw i32 %x, 1\n"
745                 "  %A = add i32 %x, 1\n"
746                 "  ret void\n"
747                 "}");
748   EXPECT_FALSE(impliesPoison(A2, A));
749 }
750 
751 TEST_F(ValueTrackingTest, ComputeNumSignBits_Shuffle_Pointers) {
752   parseAssembly(
753       "define <2 x i32*> @test(<2 x i32*> %x) {\n"
754       "  %A = shufflevector <2 x i32*> zeroinitializer, <2 x i32*> undef, <2 x i32> zeroinitializer\n"
755       "  ret <2 x i32*> %A\n"
756       "}\n");
757   EXPECT_EQ(ComputeNumSignBits(A, M->getDataLayout()), 64u);
758 }
759 
760 TEST(ValueTracking, propagatesPoison) {
761   std::string AsmHead = "declare i32 @g(i32)\n"
762                         "define void @f(i32 %x, i32 %y, float %fx, float %fy, "
763                         "i1 %cond, i8* %p) {\n";
764   std::string AsmTail = "  ret void\n}";
765   // (propagates poison?, IR instruction)
766   SmallVector<std::pair<bool, std::string>, 32> Data = {
767       {true, "add i32 %x, %y"},
768       {true, "add nsw nuw i32 %x, %y"},
769       {true, "ashr i32 %x, %y"},
770       {true, "lshr exact i32 %x, 31"},
771       {true, "fcmp oeq float %fx, %fy"},
772       {true, "icmp eq i32 %x, %y"},
773       {true, "getelementptr i8, i8* %p, i32 %x"},
774       {true, "getelementptr inbounds i8, i8* %p, i32 %x"},
775       {true, "bitcast float %fx to i32"},
776       {false, "select i1 %cond, i32 %x, i32 %y"},
777       {false, "freeze i32 %x"},
778       {true, "udiv i32 %x, %y"},
779       {true, "urem i32 %x, %y"},
780       {true, "sdiv exact i32 %x, %y"},
781       {true, "srem i32 %x, %y"},
782       {false, "call i32 @g(i32 %x)"}};
783 
784   std::string AssemblyStr = AsmHead;
785   for (auto &Itm : Data)
786     AssemblyStr += Itm.second + "\n";
787   AssemblyStr += AsmTail;
788 
789   LLVMContext Context;
790   SMDiagnostic Error;
791   auto M = parseAssemblyString(AssemblyStr, Error, Context);
792   assert(M && "Bad assembly?");
793 
794   auto *F = M->getFunction("f");
795   assert(F && "Bad assembly?");
796 
797   auto &BB = F->getEntryBlock();
798 
799   int Index = 0;
800   for (auto &I : BB) {
801     if (isa<ReturnInst>(&I))
802       break;
803     EXPECT_EQ(propagatesPoison(cast<Operator>(&I)), Data[Index].first)
804         << "Incorrect answer at instruction " << Index << " = " << I;
805     Index++;
806   }
807 }
808 
809 TEST_F(ValueTrackingTest, programUndefinedIfPoison) {
810   parseAssembly("declare i32 @any_num()"
811                 "define void @test(i32 %mask) {\n"
812                 "  %A = call i32 @any_num()\n"
813                 "  %B = or i32 %A, %mask\n"
814                 "  udiv i32 1, %B"
815                 "  ret void\n"
816                 "}\n");
817   // If %A was poison, udiv raises UB regardless of %mask's value
818   EXPECT_EQ(programUndefinedIfPoison(A), true);
819 }
820 
821 TEST_F(ValueTrackingTest, programUndefinedIfUndefOrPoison) {
822   parseAssembly("declare i32 @any_num()"
823                 "define void @test(i32 %mask) {\n"
824                 "  %A = call i32 @any_num()\n"
825                 "  %B = or i32 %A, %mask\n"
826                 "  udiv i32 1, %B"
827                 "  ret void\n"
828                 "}\n");
829   // If %A was undef and %mask was 1, udiv does not raise UB
830   EXPECT_EQ(programUndefinedIfUndefOrPoison(A), false);
831 }
832 
833 TEST_F(ValueTrackingTest, isGuaranteedNotToBePoison_exploitBranchCond) {
834   parseAssembly("declare i1 @any_bool()"
835                 "define void @test(i1 %y) {\n"
836                 "  %A = call i1 @any_bool()\n"
837                 "  %cond = and i1 %A, %y\n"
838                 "  br i1 %cond, label %BB1, label %BB2\n"
839                 "BB1:\n"
840                 "  ret void\n"
841                 "BB2:\n"
842                 "  ret void\n"
843                 "}\n");
844   DominatorTree DT(*F);
845   for (auto &BB : *F) {
846     if (&BB == &F->getEntryBlock())
847       continue;
848 
849     EXPECT_EQ(isGuaranteedNotToBePoison(A, nullptr, BB.getTerminator(), &DT),
850               true)
851         << "isGuaranteedNotToBePoison does not hold at " << *BB.getTerminator();
852   }
853 }
854 
855 TEST_F(ValueTrackingTest, isGuaranteedNotToBePoison_phi) {
856   parseAssembly("declare i32 @any_i32(i32)"
857                 "define void @test() {\n"
858                 "ENTRY:\n"
859                 "  br label %LOOP\n"
860                 "LOOP:\n"
861                 "  %A = phi i32 [0, %ENTRY], [%A.next, %NEXT]\n"
862                 "  %A.next = call i32 @any_i32(i32 %A)\n"
863                 "  %cond = icmp eq i32 %A.next, 0\n"
864                 "  br i1 %cond, label %NEXT, label %EXIT\n"
865                 "NEXT:\n"
866                 "  br label %LOOP\n"
867                 "EXIT:\n"
868                 "  ret void\n"
869                 "}\n");
870   DominatorTree DT(*F);
871   for (auto &BB : *F) {
872     if (BB.getName() == "LOOP") {
873       EXPECT_EQ(isGuaranteedNotToBePoison(A, nullptr, A, &DT), true)
874           << "isGuaranteedNotToBePoison does not hold";
875     }
876   }
877 }
878 
879 TEST_F(ValueTrackingTest, isGuaranteedNotToBeUndefOrPoison) {
880   parseAssembly("declare void @f(i32 noundef)"
881                 "define void @test(i32 %x) {\n"
882                 "  %A = bitcast i32 %x to i32\n"
883                 "  call void @f(i32 noundef %x)\n"
884                 "  ret void\n"
885                 "}\n");
886   EXPECT_EQ(isGuaranteedNotToBeUndefOrPoison(A), true);
887   EXPECT_EQ(isGuaranteedNotToBeUndefOrPoison(UndefValue::get(IntegerType::get(Context, 8))), false);
888   EXPECT_EQ(isGuaranteedNotToBeUndefOrPoison(PoisonValue::get(IntegerType::get(Context, 8))), false);
889   EXPECT_EQ(isGuaranteedNotToBePoison(UndefValue::get(IntegerType::get(Context, 8))), true);
890   EXPECT_EQ(isGuaranteedNotToBePoison(PoisonValue::get(IntegerType::get(Context, 8))), false);
891 
892   Type *Int32Ty = Type::getInt32Ty(Context);
893   Constant *CU = UndefValue::get(Int32Ty);
894   Constant *CP = PoisonValue::get(Int32Ty);
895   Constant *C1 = ConstantInt::get(Int32Ty, 1);
896   Constant *C2 = ConstantInt::get(Int32Ty, 2);
897 
898   {
899     Constant *V1 = ConstantVector::get({C1, C2});
900     EXPECT_TRUE(isGuaranteedNotToBeUndefOrPoison(V1));
901     EXPECT_TRUE(isGuaranteedNotToBePoison(V1));
902   }
903 
904   {
905     Constant *V2 = ConstantVector::get({C1, CU});
906     EXPECT_FALSE(isGuaranteedNotToBeUndefOrPoison(V2));
907     EXPECT_TRUE(isGuaranteedNotToBePoison(V2));
908   }
909 
910   {
911     Constant *V3 = ConstantVector::get({C1, CP});
912     EXPECT_FALSE(isGuaranteedNotToBeUndefOrPoison(V3));
913     EXPECT_FALSE(isGuaranteedNotToBePoison(V3));
914   }
915 }
916 
917 TEST_F(ValueTrackingTest, isGuaranteedNotToBeUndefOrPoison_assume) {
918   parseAssembly("declare i1 @f_i1()\n"
919                 "declare i32 @f_i32()\n"
920                 "declare void @llvm.assume(i1)\n"
921                 "define void @test() {\n"
922                 "  %A = call i32 @f_i32()\n"
923                 "  %cond = call i1 @f_i1()\n"
924                 "  %CxtI = add i32 0, 0\n"
925                 "  br i1 %cond, label %BB1, label %EXIT\n"
926                 "BB1:\n"
927                 "  %CxtI2 = add i32 0, 0\n"
928                 "  %cond2 = call i1 @f_i1()\n"
929                 "  call void @llvm.assume(i1 true) [ \"noundef\"(i32 %A) ]\n"
930                 "  br i1 %cond2, label %BB2, label %EXIT\n"
931                 "BB2:\n"
932                 "  %CxtI3 = add i32 0, 0\n"
933                 "  ret void\n"
934                 "EXIT:\n"
935                 "  ret void\n"
936                 "}");
937   AssumptionCache AC(*F);
938   DominatorTree DT(*F);
939   EXPECT_FALSE(isGuaranteedNotToBeUndefOrPoison(A, &AC, CxtI, &DT));
940   EXPECT_FALSE(isGuaranteedNotToBeUndefOrPoison(A, &AC, CxtI2, &DT));
941   EXPECT_TRUE(isGuaranteedNotToBeUndefOrPoison(A, &AC, CxtI3, &DT));
942 }
943 
944 TEST(ValueTracking, canCreatePoisonOrUndef) {
945   std::string AsmHead =
946       "declare i32 @g(i32)\n"
947       "define void @f(i32 %x, i32 %y, float %fx, float %fy, i1 %cond, "
948       "<4 x i32> %vx, <4 x i32> %vx2, <vscale x 4 x i32> %svx, i8* %p) {\n";
949   std::string AsmTail = "  ret void\n}";
950   // (can create poison?, can create undef?, IR instruction)
951   SmallVector<std::pair<std::pair<bool, bool>, std::string>, 32> Data = {
952       {{false, false}, "add i32 %x, %y"},
953       {{true, false}, "add nsw nuw i32 %x, %y"},
954       {{true, false}, "shl i32 %x, %y"},
955       {{true, false}, "shl <4 x i32> %vx, %vx2"},
956       {{true, false}, "shl nsw i32 %x, %y"},
957       {{true, false}, "shl nsw <4 x i32> %vx, <i32 0, i32 1, i32 2, i32 3>"},
958       {{false, false}, "shl i32 %x, 31"},
959       {{true, false}, "shl i32 %x, 32"},
960       {{false, false}, "shl <4 x i32> %vx, <i32 0, i32 1, i32 2, i32 3>"},
961       {{true, false}, "shl <4 x i32> %vx, <i32 0, i32 1, i32 2, i32 32>"},
962       {{true, false}, "ashr i32 %x, %y"},
963       {{true, false}, "ashr exact i32 %x, %y"},
964       {{false, false}, "ashr i32 %x, 31"},
965       {{true, false}, "ashr exact i32 %x, 31"},
966       {{false, false}, "ashr <4 x i32> %vx, <i32 0, i32 1, i32 2, i32 3>"},
967       {{true, false}, "ashr <4 x i32> %vx, <i32 0, i32 1, i32 2, i32 32>"},
968       {{true, false}, "ashr exact <4 x i32> %vx, <i32 0, i32 1, i32 2, i32 3>"},
969       {{true, false}, "lshr i32 %x, %y"},
970       {{true, false}, "lshr exact i32 %x, 31"},
971       {{false, false}, "udiv i32 %x, %y"},
972       {{true, false}, "udiv exact i32 %x, %y"},
973       {{false, false}, "getelementptr i8, i8* %p, i32 %x"},
974       {{true, false}, "getelementptr inbounds i8, i8* %p, i32 %x"},
975       {{true, false}, "fneg nnan float %fx"},
976       {{false, false}, "fneg float %fx"},
977       {{false, false}, "fadd float %fx, %fy"},
978       {{true, false}, "fadd nnan float %fx, %fy"},
979       {{false, false}, "urem i32 %x, %y"},
980       {{true, false}, "fptoui float %fx to i32"},
981       {{true, false}, "fptosi float %fx to i32"},
982       {{false, false}, "bitcast float %fx to i32"},
983       {{false, false}, "select i1 %cond, i32 %x, i32 %y"},
984       {{true, false}, "select nnan i1 %cond, float %fx, float %fy"},
985       {{true, false}, "extractelement <4 x i32> %vx, i32 %x"},
986       {{false, false}, "extractelement <4 x i32> %vx, i32 3"},
987       {{true, false}, "extractelement <vscale x 4 x i32> %svx, i32 4"},
988       {{true, false}, "insertelement <4 x i32> %vx, i32 %x, i32 %y"},
989       {{false, false}, "insertelement <4 x i32> %vx, i32 %x, i32 3"},
990       {{true, false}, "insertelement <vscale x 4 x i32> %svx, i32 %x, i32 4"},
991       {{false, false}, "freeze i32 %x"},
992       {{false, false},
993        "shufflevector <4 x i32> %vx, <4 x i32> %vx2, "
994        "<4 x i32> <i32 0, i32 1, i32 2, i32 3>"},
995       {{false, true},
996        "shufflevector <4 x i32> %vx, <4 x i32> %vx2, "
997        "<4 x i32> <i32 0, i32 1, i32 2, i32 undef>"},
998       {{false, true},
999        "shufflevector <vscale x 4 x i32> %svx, "
1000        "<vscale x 4 x i32> %svx, <vscale x 4 x i32> undef"},
1001       {{true, false}, "call i32 @g(i32 %x)"},
1002       {{false, false}, "call noundef i32 @g(i32 %x)"},
1003       {{true, false}, "fcmp nnan oeq float %fx, %fy"},
1004       {{false, false}, "fcmp oeq float %fx, %fy"}};
1005 
1006   std::string AssemblyStr = AsmHead;
1007   for (auto &Itm : Data)
1008     AssemblyStr += Itm.second + "\n";
1009   AssemblyStr += AsmTail;
1010 
1011   LLVMContext Context;
1012   SMDiagnostic Error;
1013   auto M = parseAssemblyString(AssemblyStr, Error, Context);
1014   assert(M && "Bad assembly?");
1015 
1016   auto *F = M->getFunction("f");
1017   assert(F && "Bad assembly?");
1018 
1019   auto &BB = F->getEntryBlock();
1020 
1021   int Index = 0;
1022   for (auto &I : BB) {
1023     if (isa<ReturnInst>(&I))
1024       break;
1025     bool Poison = Data[Index].first.first;
1026     bool Undef = Data[Index].first.second;
1027     EXPECT_EQ(canCreatePoison(cast<Operator>(&I)), Poison)
1028         << "Incorrect answer of canCreatePoison at instruction " << Index
1029         << " = " << I;
1030     EXPECT_EQ(canCreateUndefOrPoison(cast<Operator>(&I)), Undef || Poison)
1031         << "Incorrect answer of canCreateUndef at instruction " << Index
1032         << " = " << I;
1033     Index++;
1034   }
1035 }
1036 
1037 TEST_F(ValueTrackingTest, computePtrAlignment) {
1038   parseAssembly("declare i1 @f_i1()\n"
1039                 "declare i8* @f_i8p()\n"
1040                 "declare void @llvm.assume(i1)\n"
1041                 "define void @test() {\n"
1042                 "  %A = call i8* @f_i8p()\n"
1043                 "  %cond = call i1 @f_i1()\n"
1044                 "  %CxtI = add i32 0, 0\n"
1045                 "  br i1 %cond, label %BB1, label %EXIT\n"
1046                 "BB1:\n"
1047                 "  %CxtI2 = add i32 0, 0\n"
1048                 "  %cond2 = call i1 @f_i1()\n"
1049                 "  call void @llvm.assume(i1 true) [ \"align\"(i8* %A, i64 16) ]\n"
1050                 "  br i1 %cond2, label %BB2, label %EXIT\n"
1051                 "BB2:\n"
1052                 "  %CxtI3 = add i32 0, 0\n"
1053                 "  ret void\n"
1054                 "EXIT:\n"
1055                 "  ret void\n"
1056                 "}");
1057   AssumptionCache AC(*F);
1058   DominatorTree DT(*F);
1059   DataLayout DL = M->getDataLayout();
1060   EXPECT_EQ(getKnownAlignment(A, DL, CxtI, &AC, &DT), Align(1));
1061   EXPECT_EQ(getKnownAlignment(A, DL, CxtI2, &AC, &DT), Align(1));
1062   EXPECT_EQ(getKnownAlignment(A, DL, CxtI3, &AC, &DT), Align(16));
1063 }
1064 
1065 TEST_F(ComputeKnownBitsTest, ComputeKnownBits) {
1066   parseAssembly(
1067       "define i32 @test(i32 %a, i32 %b) {\n"
1068       "  %ash = mul i32 %a, 8\n"
1069       "  %aad = add i32 %ash, 7\n"
1070       "  %aan = and i32 %aad, 4095\n"
1071       "  %bsh = shl i32 %b, 4\n"
1072       "  %bad = or i32 %bsh, 6\n"
1073       "  %ban = and i32 %bad, 4095\n"
1074       "  %A = mul i32 %aan, %ban\n"
1075       "  ret i32 %A\n"
1076       "}\n");
1077   expectKnownBits(/*zero*/ 4278190085u, /*one*/ 10u);
1078 }
1079 
1080 TEST_F(ComputeKnownBitsTest, ComputeKnownMulBits) {
1081   parseAssembly(
1082       "define i32 @test(i32 %a, i32 %b) {\n"
1083       "  %aa = shl i32 %a, 5\n"
1084       "  %bb = shl i32 %b, 5\n"
1085       "  %aaa = or i32 %aa, 24\n"
1086       "  %bbb = or i32 %bb, 28\n"
1087       "  %A = mul i32 %aaa, %bbb\n"
1088       "  ret i32 %A\n"
1089       "}\n");
1090   expectKnownBits(/*zero*/ 95u, /*one*/ 32u);
1091 }
1092 
1093 TEST_F(ValueTrackingTest, KnownNonZeroFromDomCond) {
1094   parseAssembly(R"(
1095     declare i8* @f_i8()
1096     define void @test(i1 %c) {
1097       %A = call i8* @f_i8()
1098       %B = call i8* @f_i8()
1099       %c1 = icmp ne i8* %A, null
1100       %cond = and i1 %c1, %c
1101       br i1 %cond, label %T, label %Q
1102     T:
1103       %CxtI = add i32 0, 0
1104       ret void
1105     Q:
1106       %CxtI2 = add i32 0, 0
1107       ret void
1108     }
1109   )");
1110   AssumptionCache AC(*F);
1111   DominatorTree DT(*F);
1112   DataLayout DL = M->getDataLayout();
1113   EXPECT_EQ(isKnownNonZero(A, DL, 0, &AC, CxtI, &DT), true);
1114   EXPECT_EQ(isKnownNonZero(A, DL, 0, &AC, CxtI2, &DT), false);
1115 }
1116 
1117 TEST_F(ValueTrackingTest, KnownNonZeroFromDomCond2) {
1118   parseAssembly(R"(
1119     declare i8* @f_i8()
1120     define void @test(i1 %c) {
1121       %A = call i8* @f_i8()
1122       %B = call i8* @f_i8()
1123       %c1 = icmp ne i8* %A, null
1124       %cond = select i1 %c, i1 %c1, i1 false
1125       br i1 %cond, label %T, label %Q
1126     T:
1127       %CxtI = add i32 0, 0
1128       ret void
1129     Q:
1130       %CxtI2 = add i32 0, 0
1131       ret void
1132     }
1133   )");
1134   AssumptionCache AC(*F);
1135   DominatorTree DT(*F);
1136   DataLayout DL = M->getDataLayout();
1137   EXPECT_EQ(isKnownNonZero(A, DL, 0, &AC, CxtI, &DT), true);
1138   EXPECT_EQ(isKnownNonZero(A, DL, 0, &AC, CxtI2, &DT), false);
1139 }
1140 
1141 TEST_F(ValueTrackingTest, IsImpliedConditionAnd) {
1142   parseAssembly(R"(
1143     define void @test(i32 %x, i32 %y) {
1144       %c1 = icmp ult i32 %x, 10
1145       %c2 = icmp ult i32 %y, 15
1146       %A = and i1 %c1, %c2
1147       ; x < 10 /\ y < 15
1148       %A2 = icmp ult i32 %x, 20
1149       %A3 = icmp uge i32 %y, 20
1150       %A4 = icmp ult i32 %x, 5
1151       ret void
1152     }
1153   )");
1154   DataLayout DL = M->getDataLayout();
1155   EXPECT_EQ(isImpliedCondition(A, A2, DL), true);
1156   EXPECT_EQ(isImpliedCondition(A, A3, DL), false);
1157   EXPECT_EQ(isImpliedCondition(A, A4, DL), None);
1158 }
1159 
1160 TEST_F(ValueTrackingTest, IsImpliedConditionAnd2) {
1161   parseAssembly(R"(
1162     define void @test(i32 %x, i32 %y) {
1163       %c1 = icmp ult i32 %x, 10
1164       %c2 = icmp ult i32 %y, 15
1165       %A = select i1 %c1, i1 %c2, i1 false
1166       ; x < 10 /\ y < 15
1167       %A2 = icmp ult i32 %x, 20
1168       %A3 = icmp uge i32 %y, 20
1169       %A4 = icmp ult i32 %x, 5
1170       ret void
1171     }
1172   )");
1173   DataLayout DL = M->getDataLayout();
1174   EXPECT_EQ(isImpliedCondition(A, A2, DL), true);
1175   EXPECT_EQ(isImpliedCondition(A, A3, DL), false);
1176   EXPECT_EQ(isImpliedCondition(A, A4, DL), None);
1177 }
1178 
1179 TEST_F(ValueTrackingTest, IsImpliedConditionOr) {
1180   parseAssembly(R"(
1181     define void @test(i32 %x, i32 %y) {
1182       %c1 = icmp ult i32 %x, 10
1183       %c2 = icmp ult i32 %y, 15
1184       %A = or i1 %c1, %c2 ; negated
1185       ; x >= 10 /\ y >= 15
1186       %A2 = icmp ult i32 %x, 5
1187       %A3 = icmp uge i32 %y, 10
1188       %A4 = icmp ult i32 %x, 15
1189       ret void
1190     }
1191   )");
1192   DataLayout DL = M->getDataLayout();
1193   EXPECT_EQ(isImpliedCondition(A, A2, DL, false), false);
1194   EXPECT_EQ(isImpliedCondition(A, A3, DL, false), true);
1195   EXPECT_EQ(isImpliedCondition(A, A4, DL, false), None);
1196 }
1197 
1198 TEST_F(ValueTrackingTest, IsImpliedConditionOr2) {
1199   parseAssembly(R"(
1200     define void @test(i32 %x, i32 %y) {
1201       %c1 = icmp ult i32 %x, 10
1202       %c2 = icmp ult i32 %y, 15
1203       %A = select i1 %c1, i1 true, i1 %c2 ; negated
1204       ; x >= 10 /\ y >= 15
1205       %A2 = icmp ult i32 %x, 5
1206       %A3 = icmp uge i32 %y, 10
1207       %A4 = icmp ult i32 %x, 15
1208       ret void
1209     }
1210   )");
1211   DataLayout DL = M->getDataLayout();
1212   EXPECT_EQ(isImpliedCondition(A, A2, DL, false), false);
1213   EXPECT_EQ(isImpliedCondition(A, A3, DL, false), true);
1214   EXPECT_EQ(isImpliedCondition(A, A4, DL, false), None);
1215 }
1216 
1217 TEST_F(ComputeKnownBitsTest, KnownNonZeroShift) {
1218   // %q is known nonzero without known bits.
1219   // Because %q is nonzero, %A[0] is known to be zero.
1220   parseAssembly(
1221       "define i8 @test(i8 %p, i8* %pq) {\n"
1222       "  %q = load i8, i8* %pq, !range !0\n"
1223       "  %A = shl i8 %p, %q\n"
1224       "  ret i8 %A\n"
1225       "}\n"
1226       "!0 = !{ i8 1, i8 5 }\n");
1227   expectKnownBits(/*zero*/ 1u, /*one*/ 0u);
1228 }
1229 
1230 TEST_F(ComputeKnownBitsTest, ComputeKnownFshl) {
1231   // fshl(....1111....0000, 00..1111........, 6)
1232   // = 11....000000..11
1233   parseAssembly(
1234       "define i16 @test(i16 %a, i16 %b) {\n"
1235       "  %aa = shl i16 %a, 4\n"
1236       "  %bb = lshr i16 %b, 2\n"
1237       "  %aaa = or i16 %aa, 3840\n"
1238       "  %bbb = or i16 %bb, 3840\n"
1239       "  %A = call i16 @llvm.fshl.i16(i16 %aaa, i16 %bbb, i16 6)\n"
1240       "  ret i16 %A\n"
1241       "}\n"
1242       "declare i16 @llvm.fshl.i16(i16, i16, i16)\n");
1243   expectKnownBits(/*zero*/ 1008u, /*one*/ 49155u);
1244 }
1245 
1246 TEST_F(ComputeKnownBitsTest, ComputeKnownFshr) {
1247   // fshr(....1111....0000, 00..1111........, 26)
1248   // = 11....000000..11
1249   parseAssembly(
1250       "define i16 @test(i16 %a, i16 %b) {\n"
1251       "  %aa = shl i16 %a, 4\n"
1252       "  %bb = lshr i16 %b, 2\n"
1253       "  %aaa = or i16 %aa, 3840\n"
1254       "  %bbb = or i16 %bb, 3840\n"
1255       "  %A = call i16 @llvm.fshr.i16(i16 %aaa, i16 %bbb, i16 26)\n"
1256       "  ret i16 %A\n"
1257       "}\n"
1258       "declare i16 @llvm.fshr.i16(i16, i16, i16)\n");
1259   expectKnownBits(/*zero*/ 1008u, /*one*/ 49155u);
1260 }
1261 
1262 TEST_F(ComputeKnownBitsTest, ComputeKnownFshlZero) {
1263   // fshl(....1111....0000, 00..1111........, 0)
1264   // = ....1111....0000
1265   parseAssembly(
1266       "define i16 @test(i16 %a, i16 %b) {\n"
1267       "  %aa = shl i16 %a, 4\n"
1268       "  %bb = lshr i16 %b, 2\n"
1269       "  %aaa = or i16 %aa, 3840\n"
1270       "  %bbb = or i16 %bb, 3840\n"
1271       "  %A = call i16 @llvm.fshl.i16(i16 %aaa, i16 %bbb, i16 0)\n"
1272       "  ret i16 %A\n"
1273       "}\n"
1274       "declare i16 @llvm.fshl.i16(i16, i16, i16)\n");
1275   expectKnownBits(/*zero*/ 15u, /*one*/ 3840u);
1276 }
1277 
1278 TEST_F(ComputeKnownBitsTest, ComputeKnownUAddSatLeadingOnes) {
1279   // uadd.sat(1111...1, ........)
1280   // = 1111....
1281   parseAssembly(
1282       "define i8 @test(i8 %a, i8 %b) {\n"
1283       "  %aa = or i8 %a, 241\n"
1284       "  %A = call i8 @llvm.uadd.sat.i8(i8 %aa, i8 %b)\n"
1285       "  ret i8 %A\n"
1286       "}\n"
1287       "declare i8 @llvm.uadd.sat.i8(i8, i8)\n");
1288   expectKnownBits(/*zero*/ 0u, /*one*/ 240u);
1289 }
1290 
1291 TEST_F(ComputeKnownBitsTest, ComputeKnownUAddSatOnesPreserved) {
1292   // uadd.sat(00...011, .1...110)
1293   // = .......1
1294   parseAssembly(
1295       "define i8 @test(i8 %a, i8 %b) {\n"
1296       "  %aa = or i8 %a, 3\n"
1297       "  %aaa = and i8 %aa, 59\n"
1298       "  %bb = or i8 %b, 70\n"
1299       "  %bbb = and i8 %bb, 254\n"
1300       "  %A = call i8 @llvm.uadd.sat.i8(i8 %aaa, i8 %bbb)\n"
1301       "  ret i8 %A\n"
1302       "}\n"
1303       "declare i8 @llvm.uadd.sat.i8(i8, i8)\n");
1304   expectKnownBits(/*zero*/ 0u, /*one*/ 1u);
1305 }
1306 
1307 TEST_F(ComputeKnownBitsTest, ComputeKnownUSubSatLHSLeadingZeros) {
1308   // usub.sat(0000...0, ........)
1309   // = 0000....
1310   parseAssembly(
1311       "define i8 @test(i8 %a, i8 %b) {\n"
1312       "  %aa = and i8 %a, 14\n"
1313       "  %A = call i8 @llvm.usub.sat.i8(i8 %aa, i8 %b)\n"
1314       "  ret i8 %A\n"
1315       "}\n"
1316       "declare i8 @llvm.usub.sat.i8(i8, i8)\n");
1317   expectKnownBits(/*zero*/ 240u, /*one*/ 0u);
1318 }
1319 
1320 TEST_F(ComputeKnownBitsTest, ComputeKnownUSubSatRHSLeadingOnes) {
1321   // usub.sat(........, 1111...1)
1322   // = 0000....
1323   parseAssembly(
1324       "define i8 @test(i8 %a, i8 %b) {\n"
1325       "  %bb = or i8 %a, 241\n"
1326       "  %A = call i8 @llvm.usub.sat.i8(i8 %a, i8 %bb)\n"
1327       "  ret i8 %A\n"
1328       "}\n"
1329       "declare i8 @llvm.usub.sat.i8(i8, i8)\n");
1330   expectKnownBits(/*zero*/ 240u, /*one*/ 0u);
1331 }
1332 
1333 TEST_F(ComputeKnownBitsTest, ComputeKnownUSubSatZerosPreserved) {
1334   // usub.sat(11...011, .1...110)
1335   // = ......0.
1336   parseAssembly(
1337       "define i8 @test(i8 %a, i8 %b) {\n"
1338       "  %aa = or i8 %a, 195\n"
1339       "  %aaa = and i8 %aa, 251\n"
1340       "  %bb = or i8 %b, 70\n"
1341       "  %bbb = and i8 %bb, 254\n"
1342       "  %A = call i8 @llvm.usub.sat.i8(i8 %aaa, i8 %bbb)\n"
1343       "  ret i8 %A\n"
1344       "}\n"
1345       "declare i8 @llvm.usub.sat.i8(i8, i8)\n");
1346   expectKnownBits(/*zero*/ 2u, /*one*/ 0u);
1347 }
1348 
1349 TEST_F(ComputeKnownBitsTest, ComputeKnownBitsPtrToIntTrunc) {
1350   // ptrtoint truncates the pointer type.
1351   parseAssembly(
1352       "define void @test(i8** %p) {\n"
1353       "  %A = load i8*, i8** %p\n"
1354       "  %i = ptrtoint i8* %A to i32\n"
1355       "  %m = and i32 %i, 31\n"
1356       "  %c = icmp eq i32 %m, 0\n"
1357       "  call void @llvm.assume(i1 %c)\n"
1358       "  ret void\n"
1359       "}\n"
1360       "declare void @llvm.assume(i1)\n");
1361   AssumptionCache AC(*F);
1362   KnownBits Known = computeKnownBits(
1363       A, M->getDataLayout(), /* Depth */ 0, &AC, F->front().getTerminator());
1364   EXPECT_EQ(Known.Zero.getZExtValue(), 31u);
1365   EXPECT_EQ(Known.One.getZExtValue(), 0u);
1366 }
1367 
1368 TEST_F(ComputeKnownBitsTest, ComputeKnownBitsPtrToIntZext) {
1369   // ptrtoint zero extends the pointer type.
1370   parseAssembly(
1371       "define void @test(i8** %p) {\n"
1372       "  %A = load i8*, i8** %p\n"
1373       "  %i = ptrtoint i8* %A to i128\n"
1374       "  %m = and i128 %i, 31\n"
1375       "  %c = icmp eq i128 %m, 0\n"
1376       "  call void @llvm.assume(i1 %c)\n"
1377       "  ret void\n"
1378       "}\n"
1379       "declare void @llvm.assume(i1)\n");
1380   AssumptionCache AC(*F);
1381   KnownBits Known = computeKnownBits(
1382       A, M->getDataLayout(), /* Depth */ 0, &AC, F->front().getTerminator());
1383   EXPECT_EQ(Known.Zero.getZExtValue(), 31u);
1384   EXPECT_EQ(Known.One.getZExtValue(), 0u);
1385 }
1386 
1387 TEST_F(ComputeKnownBitsTest, ComputeKnownBitsFreeze) {
1388   parseAssembly("define void @test() {\n"
1389                 "  %m = call i32 @any_num()\n"
1390                 "  %A = freeze i32 %m\n"
1391                 "  %n = and i32 %m, 31\n"
1392                 "  %c = icmp eq i32 %n, 0\n"
1393                 "  call void @llvm.assume(i1 %c)\n"
1394                 "  ret void\n"
1395                 "}\n"
1396                 "declare void @llvm.assume(i1)\n"
1397                 "declare i32 @any_num()\n");
1398   AssumptionCache AC(*F);
1399   KnownBits Known = computeKnownBits(A, M->getDataLayout(), /* Depth */ 0, &AC,
1400                                      F->front().getTerminator());
1401   EXPECT_EQ(Known.Zero.getZExtValue(), 31u);
1402   EXPECT_EQ(Known.One.getZExtValue(), 0u);
1403 }
1404 
1405 TEST_F(ComputeKnownBitsTest, ComputeKnownBitsAddWithRange) {
1406   parseAssembly("define void @test(i64* %p) {\n"
1407                 "  %A = load i64, i64* %p, !range !{i64 64, i64 65536}\n"
1408                 "  %APlus512 = add i64 %A, 512\n"
1409                 "  %c = icmp ugt i64 %APlus512, 523\n"
1410                 "  call void @llvm.assume(i1 %c)\n"
1411                 "  ret void\n"
1412                 "}\n"
1413                 "declare void @llvm.assume(i1)\n");
1414   AssumptionCache AC(*F);
1415   KnownBits Known = computeKnownBits(A, M->getDataLayout(), /* Depth */ 0, &AC,
1416                                      F->front().getTerminator());
1417   EXPECT_EQ(Known.Zero.getZExtValue(), ~(65536llu - 1));
1418   EXPECT_EQ(Known.One.getZExtValue(), 0u);
1419   Instruction &APlus512 = findInstructionByName(F, "APlus512");
1420   Known = computeKnownBits(&APlus512, M->getDataLayout(), /* Depth */ 0, &AC,
1421                            F->front().getTerminator());
1422   // We know of one less zero because 512 may have produced a 1 that
1423   // got carried all the way to the first trailing zero.
1424   EXPECT_EQ(Known.Zero.getZExtValue(), (~(65536llu - 1)) << 1);
1425   EXPECT_EQ(Known.One.getZExtValue(), 0u);
1426   // The known range is not precise given computeKnownBits works
1427   // with the masks of zeros and ones, not the ranges.
1428   EXPECT_EQ(Known.getMinValue(), 0u);
1429   EXPECT_EQ(Known.getMaxValue(), 131071);
1430 }
1431 
1432 // 512 + [32, 64) doesn't produce overlapping bits.
1433 // Make sure we get all the individual bits properly.
1434 TEST_F(ComputeKnownBitsTest, ComputeKnownBitsAddWithRangeNoOverlap) {
1435   parseAssembly("define void @test(i64* %p) {\n"
1436                 "  %A = load i64, i64* %p, !range !{i64 32, i64 64}\n"
1437                 "  %APlus512 = add i64 %A, 512\n"
1438                 "  %c = icmp ugt i64 %APlus512, 523\n"
1439                 "  call void @llvm.assume(i1 %c)\n"
1440                 "  ret void\n"
1441                 "}\n"
1442                 "declare void @llvm.assume(i1)\n");
1443   AssumptionCache AC(*F);
1444   KnownBits Known = computeKnownBits(A, M->getDataLayout(), /* Depth */ 0, &AC,
1445                                      F->front().getTerminator());
1446   EXPECT_EQ(Known.Zero.getZExtValue(), ~(64llu - 1));
1447   EXPECT_EQ(Known.One.getZExtValue(), 32u);
1448   Instruction &APlus512 = findInstructionByName(F, "APlus512");
1449   Known = computeKnownBits(&APlus512, M->getDataLayout(), /* Depth */ 0, &AC,
1450                            F->front().getTerminator());
1451   EXPECT_EQ(Known.Zero.getZExtValue(), ~512llu & ~(64llu - 1));
1452   EXPECT_EQ(Known.One.getZExtValue(), 512u | 32u);
1453   // The known range is not precise given computeKnownBits works
1454   // with the masks of zeros and ones, not the ranges.
1455   EXPECT_EQ(Known.getMinValue(), 544);
1456   EXPECT_EQ(Known.getMaxValue(), 575);
1457 }
1458 
1459 TEST_F(ComputeKnownBitsTest, ComputeKnownBitsGEPWithRange) {
1460   parseAssembly(
1461       "define void @test(i64* %p) {\n"
1462       "  %A = load i64, i64* %p, !range !{i64 64, i64 65536}\n"
1463       "  %APtr = inttoptr i64 %A to float*"
1464       "  %APtrPlus512 = getelementptr float, float* %APtr, i32 128\n"
1465       "  %c = icmp ugt float* %APtrPlus512, inttoptr (i32 523 to float*)\n"
1466       "  call void @llvm.assume(i1 %c)\n"
1467       "  ret void\n"
1468       "}\n"
1469       "declare void @llvm.assume(i1)\n");
1470   AssumptionCache AC(*F);
1471   KnownBits Known = computeKnownBits(A, M->getDataLayout(), /* Depth */ 0, &AC,
1472                                      F->front().getTerminator());
1473   EXPECT_EQ(Known.Zero.getZExtValue(), ~(65536llu - 1));
1474   EXPECT_EQ(Known.One.getZExtValue(), 0u);
1475   Instruction &APtrPlus512 = findInstructionByName(F, "APtrPlus512");
1476   Known = computeKnownBits(&APtrPlus512, M->getDataLayout(), /* Depth */ 0, &AC,
1477                            F->front().getTerminator());
1478   // We know of one less zero because 512 may have produced a 1 that
1479   // got carried all the way to the first trailing zero.
1480   EXPECT_EQ(Known.Zero.getZExtValue(), ~(65536llu - 1) << 1);
1481   EXPECT_EQ(Known.One.getZExtValue(), 0u);
1482   // The known range is not precise given computeKnownBits works
1483   // with the masks of zeros and ones, not the ranges.
1484   EXPECT_EQ(Known.getMinValue(), 0u);
1485   EXPECT_EQ(Known.getMaxValue(), 131071);
1486 }
1487 
1488 // 4*128 + [32, 64) doesn't produce overlapping bits.
1489 // Make sure we get all the individual bits properly.
1490 // This test is useful to check that we account for the scaling factor
1491 // in the gep. Indeed, gep float, [32,64), 128 is not 128 + [32,64).
1492 TEST_F(ComputeKnownBitsTest, ComputeKnownBitsGEPWithRangeNoOverlap) {
1493   parseAssembly(
1494       "define void @test(i64* %p) {\n"
1495       "  %A = load i64, i64* %p, !range !{i64 32, i64 64}\n"
1496       "  %APtr = inttoptr i64 %A to float*"
1497       "  %APtrPlus512 = getelementptr float, float* %APtr, i32 128\n"
1498       "  %c = icmp ugt float* %APtrPlus512, inttoptr (i32 523 to float*)\n"
1499       "  call void @llvm.assume(i1 %c)\n"
1500       "  ret void\n"
1501       "}\n"
1502       "declare void @llvm.assume(i1)\n");
1503   AssumptionCache AC(*F);
1504   KnownBits Known = computeKnownBits(A, M->getDataLayout(), /* Depth */ 0, &AC,
1505                                      F->front().getTerminator());
1506   EXPECT_EQ(Known.Zero.getZExtValue(), ~(64llu - 1));
1507   EXPECT_EQ(Known.One.getZExtValue(), 32u);
1508   Instruction &APtrPlus512 = findInstructionByName(F, "APtrPlus512");
1509   Known = computeKnownBits(&APtrPlus512, M->getDataLayout(), /* Depth */ 0, &AC,
1510                            F->front().getTerminator());
1511   EXPECT_EQ(Known.Zero.getZExtValue(), ~512llu & ~(64llu - 1));
1512   EXPECT_EQ(Known.One.getZExtValue(), 512u | 32u);
1513   // The known range is not precise given computeKnownBits works
1514   // with the masks of zeros and ones, not the ranges.
1515   EXPECT_EQ(Known.getMinValue(), 544);
1516   EXPECT_EQ(Known.getMaxValue(), 575);
1517 }
1518 
1519 class IsBytewiseValueTest : public ValueTrackingTest,
1520                             public ::testing::WithParamInterface<
1521                                 std::pair<const char *, const char *>> {
1522 protected:
1523 };
1524 
1525 const std::pair<const char *, const char *> IsBytewiseValueTests[] = {
1526     {
1527         "i8 0",
1528         "i48* null",
1529     },
1530     {
1531         "i8 undef",
1532         "i48* undef",
1533     },
1534     {
1535         "i8 0",
1536         "i8 zeroinitializer",
1537     },
1538     {
1539         "i8 0",
1540         "i8 0",
1541     },
1542     {
1543         "i8 -86",
1544         "i8 -86",
1545     },
1546     {
1547         "i8 -1",
1548         "i8 -1",
1549     },
1550     {
1551         "i8 undef",
1552         "i16 undef",
1553     },
1554     {
1555         "i8 0",
1556         "i16 0",
1557     },
1558     {
1559         "",
1560         "i16 7",
1561     },
1562     {
1563         "i8 -86",
1564         "i16 -21846",
1565     },
1566     {
1567         "i8 -1",
1568         "i16 -1",
1569     },
1570     {
1571         "i8 0",
1572         "i48 0",
1573     },
1574     {
1575         "i8 -1",
1576         "i48 -1",
1577     },
1578     {
1579         "i8 0",
1580         "i49 0",
1581     },
1582     {
1583         "",
1584         "i49 -1",
1585     },
1586     {
1587         "i8 0",
1588         "half 0xH0000",
1589     },
1590     {
1591         "i8 -85",
1592         "half 0xHABAB",
1593     },
1594     {
1595         "i8 0",
1596         "float 0.0",
1597     },
1598     {
1599         "i8 -1",
1600         "float 0xFFFFFFFFE0000000",
1601     },
1602     {
1603         "i8 0",
1604         "double 0.0",
1605     },
1606     {
1607         "i8 -15",
1608         "double 0xF1F1F1F1F1F1F1F1",
1609     },
1610     {
1611         "i8 undef",
1612         "i16* undef",
1613     },
1614     {
1615         "i8 0",
1616         "i16* inttoptr (i64 0 to i16*)",
1617     },
1618     {
1619         "i8 -1",
1620         "i16* inttoptr (i64 -1 to i16*)",
1621     },
1622     {
1623         "i8 -86",
1624         "i16* inttoptr (i64 -6148914691236517206 to i16*)",
1625     },
1626     {
1627         "",
1628         "i16* inttoptr (i48 -1 to i16*)",
1629     },
1630     {
1631         "i8 -1",
1632         "i16* inttoptr (i96 -1 to i16*)",
1633     },
1634     {
1635         "i8 undef",
1636         "[0 x i8] zeroinitializer",
1637     },
1638     {
1639         "i8 undef",
1640         "[0 x i8] undef",
1641     },
1642     {
1643         "i8 undef",
1644         "[5 x [0 x i8]] zeroinitializer",
1645     },
1646     {
1647         "i8 undef",
1648         "[5 x [0 x i8]] undef",
1649     },
1650     {
1651         "i8 0",
1652         "[6 x i8] zeroinitializer",
1653     },
1654     {
1655         "i8 undef",
1656         "[6 x i8] undef",
1657     },
1658     {
1659         "i8 1",
1660         "[5 x i8] [i8 1, i8 1, i8 1, i8 1, i8 1]",
1661     },
1662     {
1663         "",
1664         "[5 x i64] [i64 1, i64 1, i64 1, i64 1, i64 1]",
1665     },
1666     {
1667         "i8 -1",
1668         "[5 x i64] [i64 -1, i64 -1, i64 -1, i64 -1, i64 -1]",
1669     },
1670     {
1671         "",
1672         "[4 x i8] [i8 1, i8 2, i8 1, i8 1]",
1673     },
1674     {
1675         "i8 1",
1676         "[4 x i8] [i8 1, i8 undef, i8 1, i8 1]",
1677     },
1678     {
1679         "i8 0",
1680         "<6 x i8> zeroinitializer",
1681     },
1682     {
1683         "i8 undef",
1684         "<6 x i8> undef",
1685     },
1686     {
1687         "i8 1",
1688         "<5 x i8> <i8 1, i8 1, i8 1, i8 1, i8 1>",
1689     },
1690     {
1691         "",
1692         "<5 x i64> <i64 1, i64 1, i64 1, i64 1, i64 1>",
1693     },
1694     {
1695         "i8 -1",
1696         "<5 x i64> <i64 -1, i64 -1, i64 -1, i64 -1, i64 -1>",
1697     },
1698     {
1699         "",
1700         "<4 x i8> <i8 1, i8 1, i8 2, i8 1>",
1701     },
1702     {
1703         "i8 5",
1704         "<2 x i8> < i8 5, i8 undef >",
1705     },
1706     {
1707         "i8 0",
1708         "[2 x [2 x i16]] zeroinitializer",
1709     },
1710     {
1711         "i8 undef",
1712         "[2 x [2 x i16]] undef",
1713     },
1714     {
1715         "i8 -86",
1716         "[2 x [2 x i16]] [[2 x i16] [i16 -21846, i16 -21846], "
1717         "[2 x i16] [i16 -21846, i16 -21846]]",
1718     },
1719     {
1720         "",
1721         "[2 x [2 x i16]] [[2 x i16] [i16 -21846, i16 -21846], "
1722         "[2 x i16] [i16 -21836, i16 -21846]]",
1723     },
1724     {
1725         "i8 undef",
1726         "{ } zeroinitializer",
1727     },
1728     {
1729         "i8 undef",
1730         "{ } undef",
1731     },
1732     {
1733         "i8 undef",
1734         "{ {}, {} } zeroinitializer",
1735     },
1736     {
1737         "i8 undef",
1738         "{ {}, {} } undef",
1739     },
1740     {
1741         "i8 0",
1742         "{i8, i64, i16*} zeroinitializer",
1743     },
1744     {
1745         "i8 undef",
1746         "{i8, i64, i16*} undef",
1747     },
1748     {
1749         "i8 -86",
1750         "{i8, i64, i16*} {i8 -86, i64 -6148914691236517206, i16* undef}",
1751     },
1752     {
1753         "",
1754         "{i8, i64, i16*} {i8 86, i64 -6148914691236517206, i16* undef}",
1755     },
1756 };
1757 
1758 INSTANTIATE_TEST_CASE_P(IsBytewiseValueParamTests, IsBytewiseValueTest,
1759                         ::testing::ValuesIn(IsBytewiseValueTests),);
1760 
1761 TEST_P(IsBytewiseValueTest, IsBytewiseValue) {
1762   auto M = parseModule(std::string("@test = global ") + GetParam().second);
1763   GlobalVariable *GV = dyn_cast<GlobalVariable>(M->getNamedValue("test"));
1764   Value *Actual = isBytewiseValue(GV->getInitializer(), M->getDataLayout());
1765   std::string Buff;
1766   raw_string_ostream S(Buff);
1767   if (Actual)
1768     S << *Actual;
1769   EXPECT_EQ(GetParam().first, S.str());
1770 }
1771 
1772 TEST_F(ValueTrackingTest, ComputeConstantRange) {
1773   {
1774     // Assumptions:
1775     //  * stride >= 5
1776     //  * stride < 10
1777     //
1778     // stride = [5, 10)
1779     auto M = parseModule(R"(
1780   declare void @llvm.assume(i1)
1781 
1782   define i32 @test(i32 %stride) {
1783     %gt = icmp uge i32 %stride, 5
1784     call void @llvm.assume(i1 %gt)
1785     %lt = icmp ult i32 %stride, 10
1786     call void @llvm.assume(i1 %lt)
1787     %stride.plus.one = add nsw nuw i32 %stride, 1
1788     ret i32 %stride.plus.one
1789   })");
1790     Function *F = M->getFunction("test");
1791 
1792     AssumptionCache AC(*F);
1793     Value *Stride = &*F->arg_begin();
1794     ConstantRange CR1 = computeConstantRange(Stride, true, &AC, nullptr);
1795     EXPECT_TRUE(CR1.isFullSet());
1796 
1797     Instruction *I = &findInstructionByName(F, "stride.plus.one");
1798     ConstantRange CR2 = computeConstantRange(Stride, true, &AC, I);
1799     EXPECT_EQ(5, CR2.getLower());
1800     EXPECT_EQ(10, CR2.getUpper());
1801   }
1802 
1803   {
1804     // Assumptions:
1805     //  * stride >= 5
1806     //  * stride < 200
1807     //  * stride == 99
1808     //
1809     // stride = [99, 100)
1810     auto M = parseModule(R"(
1811   declare void @llvm.assume(i1)
1812 
1813   define i32 @test(i32 %stride) {
1814     %gt = icmp uge i32 %stride, 5
1815     call void @llvm.assume(i1 %gt)
1816     %lt = icmp ult i32 %stride, 200
1817     call void @llvm.assume(i1 %lt)
1818     %eq = icmp eq i32 %stride, 99
1819     call void @llvm.assume(i1 %eq)
1820     %stride.plus.one = add nsw nuw i32 %stride, 1
1821     ret i32 %stride.plus.one
1822   })");
1823     Function *F = M->getFunction("test");
1824 
1825     AssumptionCache AC(*F);
1826     Value *Stride = &*F->arg_begin();
1827     Instruction *I = &findInstructionByName(F, "stride.plus.one");
1828     ConstantRange CR = computeConstantRange(Stride, true, &AC, I);
1829     EXPECT_EQ(99, *CR.getSingleElement());
1830   }
1831 
1832   {
1833     // Assumptions:
1834     //  * stride >= 5
1835     //  * stride >= 50
1836     //  * stride < 100
1837     //  * stride < 200
1838     //
1839     // stride = [50, 100)
1840     auto M = parseModule(R"(
1841   declare void @llvm.assume(i1)
1842 
1843   define i32 @test(i32 %stride, i1 %cond) {
1844     %gt = icmp uge i32 %stride, 5
1845     call void @llvm.assume(i1 %gt)
1846     %gt.2 = icmp uge i32 %stride, 50
1847     call void @llvm.assume(i1 %gt.2)
1848     br i1 %cond, label %bb1, label %bb2
1849 
1850   bb1:
1851     %lt = icmp ult i32 %stride, 200
1852     call void @llvm.assume(i1 %lt)
1853     %lt.2 = icmp ult i32 %stride, 100
1854     call void @llvm.assume(i1 %lt.2)
1855     %stride.plus.one = add nsw nuw i32 %stride, 1
1856     ret i32 %stride.plus.one
1857 
1858   bb2:
1859     ret i32 0
1860   })");
1861     Function *F = M->getFunction("test");
1862 
1863     AssumptionCache AC(*F);
1864     Value *Stride = &*F->arg_begin();
1865     Instruction *GT2 = &findInstructionByName(F, "gt.2");
1866     ConstantRange CR = computeConstantRange(Stride, true, &AC, GT2);
1867     EXPECT_EQ(5, CR.getLower());
1868     EXPECT_EQ(0, CR.getUpper());
1869 
1870     Instruction *I = &findInstructionByName(F, "stride.plus.one");
1871     ConstantRange CR2 = computeConstantRange(Stride, true, &AC, I);
1872     EXPECT_EQ(50, CR2.getLower());
1873     EXPECT_EQ(100, CR2.getUpper());
1874   }
1875 
1876   {
1877     // Assumptions:
1878     //  * stride > 5
1879     //  * stride < 5
1880     //
1881     // stride = empty range, as the assumptions contradict each other.
1882     auto M = parseModule(R"(
1883   declare void @llvm.assume(i1)
1884 
1885   define i32 @test(i32 %stride, i1 %cond) {
1886     %gt = icmp ugt i32 %stride, 5
1887     call void @llvm.assume(i1 %gt)
1888     %lt = icmp ult i32 %stride, 5
1889     call void @llvm.assume(i1 %lt)
1890     %stride.plus.one = add nsw nuw i32 %stride, 1
1891     ret i32 %stride.plus.one
1892   })");
1893     Function *F = M->getFunction("test");
1894 
1895     AssumptionCache AC(*F);
1896     Value *Stride = &*F->arg_begin();
1897 
1898     Instruction *I = &findInstructionByName(F, "stride.plus.one");
1899     ConstantRange CR = computeConstantRange(Stride, true, &AC, I);
1900     EXPECT_TRUE(CR.isEmptySet());
1901   }
1902 
1903   {
1904     // Assumptions:
1905     //  * x.1 >= 5
1906     //  * x.2 < x.1
1907     //
1908     // stride = [0, 5)
1909     auto M = parseModule(R"(
1910   declare void @llvm.assume(i1)
1911 
1912   define i32 @test(i32 %x.1, i32 %x.2) {
1913     %gt = icmp uge i32 %x.1, 5
1914     call void @llvm.assume(i1 %gt)
1915     %lt = icmp ult i32 %x.2, %x.1
1916     call void @llvm.assume(i1 %lt)
1917     %stride.plus.one = add nsw nuw i32 %x.1, 1
1918     ret i32 %stride.plus.one
1919   })");
1920     Function *F = M->getFunction("test");
1921 
1922     AssumptionCache AC(*F);
1923     Value *X2 = &*std::next(F->arg_begin());
1924 
1925     Instruction *I = &findInstructionByName(F, "stride.plus.one");
1926     ConstantRange CR1 = computeConstantRange(X2, true, &AC, I);
1927     EXPECT_EQ(0, CR1.getLower());
1928     EXPECT_EQ(5, CR1.getUpper());
1929 
1930     // Check the depth cutoff results in a conservative result (full set) by
1931     // passing Depth == MaxDepth == 6.
1932     ConstantRange CR2 = computeConstantRange(X2, true, &AC, I, 6);
1933     EXPECT_TRUE(CR2.isFullSet());
1934   }
1935 }
1936 
1937 struct FindAllocaForValueTestParams {
1938   const char *IR;
1939   bool AnyOffsetResult;
1940   bool ZeroOffsetResult;
1941 };
1942 
1943 class FindAllocaForValueTest
1944     : public ValueTrackingTest,
1945       public ::testing::WithParamInterface<FindAllocaForValueTestParams> {
1946 protected:
1947 };
1948 
1949 const FindAllocaForValueTestParams FindAllocaForValueTests[] = {
1950     {R"(
1951       define void @test() {
1952         %a = alloca i64
1953         %r = bitcast i64* %a to i32*
1954         ret void
1955       })",
1956      true, true},
1957 
1958     {R"(
1959       define void @test() {
1960         %a = alloca i32
1961         %r = getelementptr i32, i32* %a, i32 1
1962         ret void
1963       })",
1964      true, false},
1965 
1966     {R"(
1967       define void @test() {
1968         %a = alloca i32
1969         %r = getelementptr i32, i32* %a, i32 0
1970         ret void
1971       })",
1972      true, true},
1973 
1974     {R"(
1975       define void @test(i1 %cond) {
1976       entry:
1977         %a = alloca i32
1978         br label %bb1
1979 
1980       bb1:
1981         %r = phi i32* [ %a, %entry ], [ %r, %bb1 ]
1982         br i1 %cond, label %bb1, label %exit
1983 
1984       exit:
1985         ret void
1986       })",
1987      true, true},
1988 
1989     {R"(
1990       define void @test(i1 %cond) {
1991         %a = alloca i32
1992         %r = select i1 %cond, i32* %a, i32* %a
1993         ret void
1994       })",
1995      true, true},
1996 
1997     {R"(
1998       define void @test(i1 %cond) {
1999         %a = alloca i32
2000         %b = alloca i32
2001         %r = select i1 %cond, i32* %a, i32* %b
2002         ret void
2003       })",
2004      false, false},
2005 
2006     {R"(
2007       define void @test(i1 %cond) {
2008       entry:
2009         %a = alloca i64
2010         %a32 = bitcast i64* %a to i32*
2011         br label %bb1
2012 
2013       bb1:
2014         %x = phi i32* [ %a32, %entry ], [ %x, %bb1 ]
2015         %r = getelementptr i32, i32* %x, i32 1
2016         br i1 %cond, label %bb1, label %exit
2017 
2018       exit:
2019         ret void
2020       })",
2021      true, false},
2022 
2023     {R"(
2024       define void @test(i1 %cond) {
2025       entry:
2026         %a = alloca i64
2027         %a32 = bitcast i64* %a to i32*
2028         br label %bb1
2029 
2030       bb1:
2031         %x = phi i32* [ %a32, %entry ], [ %r, %bb1 ]
2032         %r = getelementptr i32, i32* %x, i32 1
2033         br i1 %cond, label %bb1, label %exit
2034 
2035       exit:
2036         ret void
2037       })",
2038      true, false},
2039 
2040     {R"(
2041       define void @test(i1 %cond, i64* %a) {
2042       entry:
2043         %r = bitcast i64* %a to i32*
2044         ret void
2045       })",
2046      false, false},
2047 
2048     {R"(
2049       define void @test(i1 %cond) {
2050       entry:
2051         %a = alloca i32
2052         %b = alloca i32
2053         br label %bb1
2054 
2055       bb1:
2056         %r = phi i32* [ %a, %entry ], [ %b, %bb1 ]
2057         br i1 %cond, label %bb1, label %exit
2058 
2059       exit:
2060         ret void
2061       })",
2062      false, false},
2063 };
2064 
2065 TEST_P(FindAllocaForValueTest, findAllocaForValue) {
2066   auto M = parseModule(GetParam().IR);
2067   Function *F = M->getFunction("test");
2068   Instruction *I = &findInstructionByName(F, "r");
2069   const AllocaInst *AI = findAllocaForValue(I);
2070   EXPECT_EQ(!!AI, GetParam().AnyOffsetResult);
2071 }
2072 
2073 TEST_P(FindAllocaForValueTest, findAllocaForValueZeroOffset) {
2074   auto M = parseModule(GetParam().IR);
2075   Function *F = M->getFunction("test");
2076   Instruction *I = &findInstructionByName(F, "r");
2077   const AllocaInst *AI = findAllocaForValue(I, true);
2078   EXPECT_EQ(!!AI, GetParam().ZeroOffsetResult);
2079 }
2080 
2081 INSTANTIATE_TEST_CASE_P(FindAllocaForValueTest, FindAllocaForValueTest,
2082                         ::testing::ValuesIn(FindAllocaForValueTests), );
2083