xref: /llvm-project/llvm/unittests/IR/InstructionsTest.cpp (revision 6292a808b3524d9ba6f4ce55bc5b9e547b088dd8)
1 //===- llvm/unittest/IR/InstructionsTest.cpp - Instructions unit 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/IR/Instructions.h"
10 #include "llvm/ADT/CombinationGenerator.h"
11 #include "llvm/ADT/STLExtras.h"
12 #include "llvm/Analysis/ValueTracking.h"
13 #include "llvm/Analysis/VectorUtils.h"
14 #include "llvm/AsmParser/Parser.h"
15 #include "llvm/IR/BasicBlock.h"
16 #include "llvm/IR/Constants.h"
17 #include "llvm/IR/DataLayout.h"
18 #include "llvm/IR/DebugInfoMetadata.h"
19 #include "llvm/IR/DerivedTypes.h"
20 #include "llvm/IR/FPEnv.h"
21 #include "llvm/IR/Function.h"
22 #include "llvm/IR/IRBuilder.h"
23 #include "llvm/IR/LLVMContext.h"
24 #include "llvm/IR/MDBuilder.h"
25 #include "llvm/IR/Module.h"
26 #include "llvm/IR/NoFolder.h"
27 #include "llvm/IR/Operator.h"
28 #include "llvm/Support/CommandLine.h"
29 #include "llvm/Support/SourceMgr.h"
30 #include "llvm-c/Core.h"
31 #include "gmock/gmock-matchers.h"
32 #include "gtest/gtest.h"
33 #include <memory>
34 
35 extern llvm::cl::opt<bool> UseNewDbgInfoFormat;
36 
37 namespace llvm {
38 namespace {
39 
40 static std::unique_ptr<Module> parseIR(LLVMContext &C, const char *IR) {
41   SMDiagnostic Err;
42   std::unique_ptr<Module> Mod = parseAssemblyString(IR, Err, C);
43   if (!Mod)
44     Err.print("InstructionsTests", errs());
45   return Mod;
46 }
47 
48 TEST(InstructionsTest, ReturnInst) {
49   LLVMContext C;
50 
51   // test for PR6589
52   const ReturnInst* r0 = ReturnInst::Create(C);
53   EXPECT_EQ(r0->getNumOperands(), 0U);
54   EXPECT_EQ(r0->op_begin(), r0->op_end());
55 
56   IntegerType* Int1 = IntegerType::get(C, 1);
57   Constant* One = ConstantInt::get(Int1, 1, true);
58   const ReturnInst* r1 = ReturnInst::Create(C, One);
59   EXPECT_EQ(1U, r1->getNumOperands());
60   User::const_op_iterator b(r1->op_begin());
61   EXPECT_NE(r1->op_end(), b);
62   EXPECT_EQ(One, *b);
63   EXPECT_EQ(One, r1->getOperand(0));
64   ++b;
65   EXPECT_EQ(r1->op_end(), b);
66 
67   // clean up
68   delete r0;
69   delete r1;
70 }
71 
72 // Test fixture that provides a module and a single function within it. Useful
73 // for tests that need to refer to the function in some way.
74 class ModuleWithFunctionTest : public testing::Test {
75 protected:
76   ModuleWithFunctionTest() : M(new Module("MyModule", Ctx)) {
77     FArgTypes.push_back(Type::getInt8Ty(Ctx));
78     FArgTypes.push_back(Type::getInt32Ty(Ctx));
79     FArgTypes.push_back(Type::getInt64Ty(Ctx));
80     FunctionType *FTy =
81         FunctionType::get(Type::getVoidTy(Ctx), FArgTypes, false);
82     F = Function::Create(FTy, Function::ExternalLinkage, "", M.get());
83   }
84 
85   LLVMContext Ctx;
86   std::unique_ptr<Module> M;
87   SmallVector<Type *, 3> FArgTypes;
88   Function *F;
89 };
90 
91 TEST_F(ModuleWithFunctionTest, CallInst) {
92   Value *Args[] = {ConstantInt::get(Type::getInt8Ty(Ctx), 20),
93                    ConstantInt::get(Type::getInt32Ty(Ctx), 9999),
94                    ConstantInt::get(Type::getInt64Ty(Ctx), 42)};
95   std::unique_ptr<CallInst> Call(CallInst::Create(F, Args));
96 
97   // Make sure iteration over a call's arguments works as expected.
98   unsigned Idx = 0;
99   for (Value *Arg : Call->args()) {
100     EXPECT_EQ(FArgTypes[Idx], Arg->getType());
101     EXPECT_EQ(Call->getArgOperand(Idx)->getType(), Arg->getType());
102     Idx++;
103   }
104 
105   Call->addRetAttr(Attribute::get(Call->getContext(), "test-str-attr"));
106   EXPECT_TRUE(Call->hasRetAttr("test-str-attr"));
107   EXPECT_FALSE(Call->hasRetAttr("not-on-call"));
108 
109   Call->addFnAttr(Attribute::get(Call->getContext(), "test-str-fn-attr"));
110   ASSERT_TRUE(Call->hasFnAttr("test-str-fn-attr"));
111   Call->removeFnAttr("test-str-fn-attr");
112   EXPECT_FALSE(Call->hasFnAttr("test-str-fn-attr"));
113 }
114 
115 TEST_F(ModuleWithFunctionTest, InvokeInst) {
116   BasicBlock *BB1 = BasicBlock::Create(Ctx, "", F);
117   BasicBlock *BB2 = BasicBlock::Create(Ctx, "", F);
118 
119   Value *Args[] = {ConstantInt::get(Type::getInt8Ty(Ctx), 20),
120                    ConstantInt::get(Type::getInt32Ty(Ctx), 9999),
121                    ConstantInt::get(Type::getInt64Ty(Ctx), 42)};
122   std::unique_ptr<InvokeInst> Invoke(InvokeInst::Create(F, BB1, BB2, Args));
123 
124   // Make sure iteration over invoke's arguments works as expected.
125   unsigned Idx = 0;
126   for (Value *Arg : Invoke->args()) {
127     EXPECT_EQ(FArgTypes[Idx], Arg->getType());
128     EXPECT_EQ(Invoke->getArgOperand(Idx)->getType(), Arg->getType());
129     Idx++;
130   }
131 }
132 
133 TEST(InstructionsTest, BranchInst) {
134   LLVMContext C;
135 
136   // Make a BasicBlocks
137   BasicBlock* bb0 = BasicBlock::Create(C);
138   BasicBlock* bb1 = BasicBlock::Create(C);
139 
140   // Mandatory BranchInst
141   const BranchInst* b0 = BranchInst::Create(bb0);
142 
143   EXPECT_TRUE(b0->isUnconditional());
144   EXPECT_FALSE(b0->isConditional());
145   EXPECT_EQ(1U, b0->getNumSuccessors());
146 
147   // check num operands
148   EXPECT_EQ(1U, b0->getNumOperands());
149 
150   EXPECT_NE(b0->op_begin(), b0->op_end());
151   EXPECT_EQ(b0->op_end(), std::next(b0->op_begin()));
152 
153   EXPECT_EQ(b0->op_end(), std::next(b0->op_begin()));
154 
155   IntegerType* Int1 = IntegerType::get(C, 1);
156   Constant* One = ConstantInt::get(Int1, 1, true);
157 
158   // Conditional BranchInst
159   BranchInst* b1 = BranchInst::Create(bb0, bb1, One);
160 
161   EXPECT_FALSE(b1->isUnconditional());
162   EXPECT_TRUE(b1->isConditional());
163   EXPECT_EQ(2U, b1->getNumSuccessors());
164 
165   // check num operands
166   EXPECT_EQ(3U, b1->getNumOperands());
167 
168   User::const_op_iterator b(b1->op_begin());
169 
170   // check COND
171   EXPECT_NE(b, b1->op_end());
172   EXPECT_EQ(One, *b);
173   EXPECT_EQ(One, b1->getOperand(0));
174   EXPECT_EQ(One, b1->getCondition());
175   ++b;
176 
177   // check ELSE
178   EXPECT_EQ(bb1, *b);
179   EXPECT_EQ(bb1, b1->getOperand(1));
180   EXPECT_EQ(bb1, b1->getSuccessor(1));
181   ++b;
182 
183   // check THEN
184   EXPECT_EQ(bb0, *b);
185   EXPECT_EQ(bb0, b1->getOperand(2));
186   EXPECT_EQ(bb0, b1->getSuccessor(0));
187   ++b;
188 
189   EXPECT_EQ(b1->op_end(), b);
190 
191   // clean up
192   delete b0;
193   delete b1;
194 
195   delete bb0;
196   delete bb1;
197 }
198 
199 TEST(InstructionsTest, CastInst) {
200   LLVMContext C;
201 
202   Type *Int8Ty = Type::getInt8Ty(C);
203   Type *Int16Ty = Type::getInt16Ty(C);
204   Type *Int32Ty = Type::getInt32Ty(C);
205   Type *Int64Ty = Type::getInt64Ty(C);
206   Type *V8x8Ty = FixedVectorType::get(Int8Ty, 8);
207   Type *V8x64Ty = FixedVectorType::get(Int64Ty, 8);
208 
209   Type *HalfTy = Type::getHalfTy(C);
210   Type *FloatTy = Type::getFloatTy(C);
211   Type *DoubleTy = Type::getDoubleTy(C);
212 
213   Type *V2Int32Ty = FixedVectorType::get(Int32Ty, 2);
214   Type *V2Int64Ty = FixedVectorType::get(Int64Ty, 2);
215   Type *V4Int16Ty = FixedVectorType::get(Int16Ty, 4);
216   Type *V1Int16Ty = FixedVectorType::get(Int16Ty, 1);
217 
218   Type *VScaleV2Int32Ty = ScalableVectorType::get(Int32Ty, 2);
219   Type *VScaleV2Int64Ty = ScalableVectorType::get(Int64Ty, 2);
220   Type *VScaleV4Int16Ty = ScalableVectorType::get(Int16Ty, 4);
221   Type *VScaleV1Int16Ty = ScalableVectorType::get(Int16Ty, 1);
222 
223   Type *PtrTy = PointerType::get(C, 0);
224   Type *PtrAS1Ty = PointerType::get(C, 1);
225 
226   Type *V2PtrAS1Ty = FixedVectorType::get(PtrAS1Ty, 2);
227   Type *V4PtrAS1Ty = FixedVectorType::get(PtrAS1Ty, 4);
228   Type *VScaleV4PtrAS1Ty = ScalableVectorType::get(PtrAS1Ty, 4);
229 
230   Type *V2PtrTy = FixedVectorType::get(PtrTy, 2);
231   Type *V4PtrTy = FixedVectorType::get(PtrTy, 4);
232   Type *VScaleV2PtrTy = ScalableVectorType::get(PtrTy, 2);
233   Type *VScaleV4PtrTy = ScalableVectorType::get(PtrTy, 4);
234 
235   const Constant* c8 = Constant::getNullValue(V8x8Ty);
236   const Constant* c64 = Constant::getNullValue(V8x64Ty);
237 
238   const Constant *v2ptr32 = Constant::getNullValue(V2PtrTy);
239 
240   EXPECT_EQ(CastInst::Trunc, CastInst::getCastOpcode(c64, true, V8x8Ty, true));
241   EXPECT_EQ(CastInst::SExt, CastInst::getCastOpcode(c8, true, V8x64Ty, true));
242 
243   EXPECT_FALSE(CastInst::isBitCastable(V8x64Ty, V8x8Ty));
244   EXPECT_FALSE(CastInst::isBitCastable(V8x8Ty, V8x64Ty));
245 
246   // Check address space casts are rejected since we don't know the sizes here
247   EXPECT_FALSE(CastInst::isBitCastable(PtrTy, PtrAS1Ty));
248   EXPECT_FALSE(CastInst::isBitCastable(PtrAS1Ty, PtrTy));
249   EXPECT_FALSE(CastInst::isBitCastable(V2PtrTy, V2PtrAS1Ty));
250   EXPECT_FALSE(CastInst::isBitCastable(V2PtrAS1Ty, V2PtrTy));
251   EXPECT_TRUE(CastInst::isBitCastable(V2PtrAS1Ty, V2PtrAS1Ty));
252   EXPECT_EQ(CastInst::AddrSpaceCast,
253             CastInst::getCastOpcode(v2ptr32, true, V2PtrAS1Ty, true));
254 
255   // Test mismatched number of elements for pointers
256   EXPECT_FALSE(CastInst::isBitCastable(V2PtrAS1Ty, V4PtrAS1Ty));
257   EXPECT_FALSE(CastInst::isBitCastable(V4PtrAS1Ty, V2PtrAS1Ty));
258   EXPECT_FALSE(CastInst::isBitCastable(PtrTy, V2PtrTy));
259   EXPECT_FALSE(CastInst::isBitCastable(V2PtrTy, PtrTy));
260 
261   EXPECT_TRUE(CastInst::isBitCastable(PtrTy, PtrTy));
262   EXPECT_FALSE(CastInst::isBitCastable(DoubleTy, FloatTy));
263   EXPECT_FALSE(CastInst::isBitCastable(FloatTy, DoubleTy));
264   EXPECT_TRUE(CastInst::isBitCastable(FloatTy, FloatTy));
265   EXPECT_TRUE(CastInst::isBitCastable(FloatTy, FloatTy));
266   EXPECT_TRUE(CastInst::isBitCastable(FloatTy, Int32Ty));
267   EXPECT_TRUE(CastInst::isBitCastable(Int16Ty, HalfTy));
268   EXPECT_TRUE(CastInst::isBitCastable(Int32Ty, FloatTy));
269   EXPECT_TRUE(CastInst::isBitCastable(V2Int32Ty, Int64Ty));
270 
271   EXPECT_TRUE(CastInst::isBitCastable(V2Int32Ty, V4Int16Ty));
272   EXPECT_FALSE(CastInst::isBitCastable(Int32Ty, Int64Ty));
273   EXPECT_FALSE(CastInst::isBitCastable(Int64Ty, Int32Ty));
274 
275   EXPECT_FALSE(CastInst::isBitCastable(V2PtrTy, Int64Ty));
276   EXPECT_FALSE(CastInst::isBitCastable(Int64Ty, V2PtrTy));
277   EXPECT_FALSE(CastInst::isBitCastable(V2Int32Ty, V2Int64Ty));
278   EXPECT_FALSE(CastInst::isBitCastable(V2Int64Ty, V2Int32Ty));
279 
280   EXPECT_FALSE(CastInst::castIsValid(Instruction::BitCast,
281                                      Constant::getNullValue(V4PtrTy), V2PtrTy));
282   EXPECT_FALSE(CastInst::castIsValid(Instruction::BitCast,
283                                      Constant::getNullValue(V2PtrTy), V4PtrTy));
284 
285   EXPECT_FALSE(CastInst::castIsValid(
286       Instruction::AddrSpaceCast, Constant::getNullValue(V4PtrAS1Ty), V2PtrTy));
287   EXPECT_FALSE(CastInst::castIsValid(
288       Instruction::AddrSpaceCast, Constant::getNullValue(V2PtrTy), V4PtrAS1Ty));
289 
290   // Address space cast of fixed/scalable vectors of pointers to scalable/fixed
291   // vector of pointers.
292   EXPECT_FALSE(CastInst::castIsValid(Instruction::AddrSpaceCast,
293                                      Constant::getNullValue(VScaleV4PtrAS1Ty),
294                                      V4PtrTy));
295   EXPECT_FALSE(CastInst::castIsValid(Instruction::AddrSpaceCast,
296                                      Constant::getNullValue(V4PtrTy),
297                                      VScaleV4PtrAS1Ty));
298   // Address space cast of scalable vectors of pointers to scalable vector of
299   // pointers.
300   EXPECT_FALSE(CastInst::castIsValid(Instruction::AddrSpaceCast,
301                                      Constant::getNullValue(VScaleV4PtrAS1Ty),
302                                      VScaleV2PtrTy));
303   EXPECT_FALSE(CastInst::castIsValid(Instruction::AddrSpaceCast,
304                                      Constant::getNullValue(VScaleV2PtrTy),
305                                      VScaleV4PtrAS1Ty));
306   EXPECT_TRUE(CastInst::castIsValid(Instruction::AddrSpaceCast,
307                                     Constant::getNullValue(VScaleV4PtrTy),
308                                     VScaleV4PtrAS1Ty));
309   // Same number of lanes, different address space.
310   EXPECT_TRUE(CastInst::castIsValid(Instruction::AddrSpaceCast,
311                                     Constant::getNullValue(VScaleV4PtrAS1Ty),
312                                     VScaleV4PtrTy));
313   // Same number of lanes, same address space.
314   EXPECT_FALSE(CastInst::castIsValid(Instruction::AddrSpaceCast,
315                                      Constant::getNullValue(VScaleV4PtrTy),
316                                      VScaleV4PtrTy));
317 
318   // Bit casting fixed/scalable vector to scalable/fixed vectors.
319   EXPECT_FALSE(CastInst::castIsValid(Instruction::BitCast,
320                                      Constant::getNullValue(V2Int32Ty),
321                                      VScaleV2Int32Ty));
322   EXPECT_FALSE(CastInst::castIsValid(Instruction::BitCast,
323                                      Constant::getNullValue(V2Int64Ty),
324                                      VScaleV2Int64Ty));
325   EXPECT_FALSE(CastInst::castIsValid(Instruction::BitCast,
326                                      Constant::getNullValue(V4Int16Ty),
327                                      VScaleV4Int16Ty));
328   EXPECT_FALSE(CastInst::castIsValid(Instruction::BitCast,
329                                      Constant::getNullValue(VScaleV2Int32Ty),
330                                      V2Int32Ty));
331   EXPECT_FALSE(CastInst::castIsValid(Instruction::BitCast,
332                                      Constant::getNullValue(VScaleV2Int64Ty),
333                                      V2Int64Ty));
334   EXPECT_FALSE(CastInst::castIsValid(Instruction::BitCast,
335                                      Constant::getNullValue(VScaleV4Int16Ty),
336                                      V4Int16Ty));
337 
338   // Bit casting scalable vectors to scalable vectors.
339   EXPECT_TRUE(CastInst::castIsValid(Instruction::BitCast,
340                                     Constant::getNullValue(VScaleV4Int16Ty),
341                                     VScaleV2Int32Ty));
342   EXPECT_TRUE(CastInst::castIsValid(Instruction::BitCast,
343                                     Constant::getNullValue(VScaleV2Int32Ty),
344                                     VScaleV4Int16Ty));
345   EXPECT_FALSE(CastInst::castIsValid(Instruction::BitCast,
346                                      Constant::getNullValue(VScaleV2Int64Ty),
347                                      VScaleV2Int32Ty));
348   EXPECT_FALSE(CastInst::castIsValid(Instruction::BitCast,
349                                      Constant::getNullValue(VScaleV2Int32Ty),
350                                      VScaleV2Int64Ty));
351 
352   // Bitcasting to/from <vscale x 1 x Ty>
353   EXPECT_FALSE(CastInst::castIsValid(Instruction::BitCast,
354                                      Constant::getNullValue(VScaleV1Int16Ty),
355                                      V1Int16Ty));
356   EXPECT_FALSE(CastInst::castIsValid(Instruction::BitCast,
357                                      Constant::getNullValue(V1Int16Ty),
358                                      VScaleV1Int16Ty));
359 
360   // Check that assertion is not hit when creating a cast with a vector of
361   // pointers
362   // First form
363   BasicBlock *BB = BasicBlock::Create(C);
364   Constant *NullV2I32Ptr = Constant::getNullValue(V2PtrTy);
365   auto Inst1 = CastInst::CreatePointerCast(NullV2I32Ptr, V2Int32Ty, "foo", BB);
366 
367   Constant *NullVScaleV2I32Ptr = Constant::getNullValue(VScaleV2PtrTy);
368   auto Inst1VScale = CastInst::CreatePointerCast(
369       NullVScaleV2I32Ptr, VScaleV2Int32Ty, "foo.vscale", BB);
370 
371   // Second form
372   auto Inst2 = CastInst::CreatePointerCast(NullV2I32Ptr, V2Int32Ty);
373   auto Inst2VScale =
374       CastInst::CreatePointerCast(NullVScaleV2I32Ptr, VScaleV2Int32Ty);
375 
376   delete Inst2;
377   delete Inst2VScale;
378   Inst1->eraseFromParent();
379   Inst1VScale->eraseFromParent();
380   delete BB;
381 }
382 
383 TEST(InstructionsTest, CastCAPI) {
384   LLVMContext C;
385 
386   Type *Int8Ty = Type::getInt8Ty(C);
387   Type *Int64Ty = Type::getInt64Ty(C);
388 
389   Type *FloatTy = Type::getFloatTy(C);
390   Type *DoubleTy = Type::getDoubleTy(C);
391 
392   Type *PtrTy = PointerType::get(C, 0);
393 
394   const Constant *C8 = Constant::getNullValue(Int8Ty);
395   const Constant *C64 = Constant::getNullValue(Int64Ty);
396 
397   EXPECT_EQ(LLVMBitCast,
398             LLVMGetCastOpcode(wrap(C64), true, wrap(Int64Ty), true));
399   EXPECT_EQ(LLVMTrunc, LLVMGetCastOpcode(wrap(C64), true, wrap(Int8Ty), true));
400   EXPECT_EQ(LLVMSExt, LLVMGetCastOpcode(wrap(C8), true, wrap(Int64Ty), true));
401   EXPECT_EQ(LLVMZExt, LLVMGetCastOpcode(wrap(C8), false, wrap(Int64Ty), true));
402 
403   const Constant *CF32 = Constant::getNullValue(FloatTy);
404   const Constant *CF64 = Constant::getNullValue(DoubleTy);
405 
406   EXPECT_EQ(LLVMFPToUI,
407             LLVMGetCastOpcode(wrap(CF32), true, wrap(Int8Ty), false));
408   EXPECT_EQ(LLVMFPToSI,
409             LLVMGetCastOpcode(wrap(CF32), true, wrap(Int8Ty), true));
410   EXPECT_EQ(LLVMUIToFP,
411             LLVMGetCastOpcode(wrap(C8), false, wrap(FloatTy), true));
412   EXPECT_EQ(LLVMSIToFP, LLVMGetCastOpcode(wrap(C8), true, wrap(FloatTy), true));
413   EXPECT_EQ(LLVMFPTrunc,
414             LLVMGetCastOpcode(wrap(CF64), true, wrap(FloatTy), true));
415   EXPECT_EQ(LLVMFPExt,
416             LLVMGetCastOpcode(wrap(CF32), true, wrap(DoubleTy), true));
417 
418   const Constant *CPtr8 = Constant::getNullValue(PtrTy);
419 
420   EXPECT_EQ(LLVMPtrToInt,
421             LLVMGetCastOpcode(wrap(CPtr8), true, wrap(Int8Ty), true));
422   EXPECT_EQ(LLVMIntToPtr, LLVMGetCastOpcode(wrap(C8), true, wrap(PtrTy), true));
423 
424   Type *V8x8Ty = FixedVectorType::get(Int8Ty, 8);
425   Type *V8x64Ty = FixedVectorType::get(Int64Ty, 8);
426   const Constant *CV8 = Constant::getNullValue(V8x8Ty);
427   const Constant *CV64 = Constant::getNullValue(V8x64Ty);
428 
429   EXPECT_EQ(LLVMTrunc, LLVMGetCastOpcode(wrap(CV64), true, wrap(V8x8Ty), true));
430   EXPECT_EQ(LLVMSExt, LLVMGetCastOpcode(wrap(CV8), true, wrap(V8x64Ty), true));
431 
432   Type *PtrAS1Ty = PointerType::get(C, 1);
433   Type *V2PtrAS1Ty = FixedVectorType::get(PtrAS1Ty, 2);
434   Type *V2PtrTy = FixedVectorType::get(PtrTy, 2);
435   const Constant *CV2Ptr = Constant::getNullValue(V2PtrTy);
436 
437   EXPECT_EQ(LLVMAddrSpaceCast,
438             LLVMGetCastOpcode(wrap(CV2Ptr), true, wrap(V2PtrAS1Ty), true));
439 }
440 
441 TEST(InstructionsTest, VectorGep) {
442   LLVMContext C;
443 
444   // Type Definitions
445   Type *I32Ty = IntegerType::get(C, 32);
446   PointerType *PtrTy = PointerType::get(C, 0);
447   VectorType *V2xPTy = FixedVectorType::get(PtrTy, 2);
448 
449   // Test different aspects of the vector-of-pointers type
450   // and GEPs which use this type.
451   ConstantInt *Ci32a = ConstantInt::get(C, APInt(32, 1492));
452   ConstantInt *Ci32b = ConstantInt::get(C, APInt(32, 1948));
453   std::vector<Constant*> ConstVa(2, Ci32a);
454   std::vector<Constant*> ConstVb(2, Ci32b);
455   Constant *C2xi32a = ConstantVector::get(ConstVa);
456   Constant *C2xi32b = ConstantVector::get(ConstVb);
457 
458   CastInst *PtrVecA = new IntToPtrInst(C2xi32a, V2xPTy);
459   CastInst *PtrVecB = new IntToPtrInst(C2xi32b, V2xPTy);
460 
461   ICmpInst *ICmp0 = new ICmpInst(ICmpInst::ICMP_SGT, PtrVecA, PtrVecB);
462   ICmpInst *ICmp1 = new ICmpInst(ICmpInst::ICMP_ULT, PtrVecA, PtrVecB);
463   EXPECT_NE(ICmp0, ICmp1); // suppress warning.
464 
465   BasicBlock* BB0 = BasicBlock::Create(C);
466   // Test InsertAtEnd ICmpInst constructor.
467   ICmpInst *ICmp2 = new ICmpInst(BB0, ICmpInst::ICMP_SGE, PtrVecA, PtrVecB);
468   EXPECT_NE(ICmp0, ICmp2); // suppress warning.
469 
470   GetElementPtrInst *Gep0 = GetElementPtrInst::Create(I32Ty, PtrVecA, C2xi32a);
471   GetElementPtrInst *Gep1 = GetElementPtrInst::Create(I32Ty, PtrVecA, C2xi32b);
472   GetElementPtrInst *Gep2 = GetElementPtrInst::Create(I32Ty, PtrVecB, C2xi32a);
473   GetElementPtrInst *Gep3 = GetElementPtrInst::Create(I32Ty, PtrVecB, C2xi32b);
474 
475   CastInst *BTC0 = new BitCastInst(Gep0, V2xPTy);
476   CastInst *BTC1 = new BitCastInst(Gep1, V2xPTy);
477   CastInst *BTC2 = new BitCastInst(Gep2, V2xPTy);
478   CastInst *BTC3 = new BitCastInst(Gep3, V2xPTy);
479 
480   Value *S0 = BTC0->stripPointerCasts();
481   Value *S1 = BTC1->stripPointerCasts();
482   Value *S2 = BTC2->stripPointerCasts();
483   Value *S3 = BTC3->stripPointerCasts();
484 
485   EXPECT_NE(S0, Gep0);
486   EXPECT_NE(S1, Gep1);
487   EXPECT_NE(S2, Gep2);
488   EXPECT_NE(S3, Gep3);
489 
490   int64_t Offset;
491   DataLayout TD("e-p:64:64:64-i1:8:8-i8:8:8-i16:16:16-i32:32:32-i64:64:64-f3"
492                 "2:32:32-f64:64:64-v64:64:64-v128:128:128-a:0:64-s:64:64-f80"
493                 ":128:128-n8:16:32:64-S128");
494   // Make sure we don't crash
495   GetPointerBaseWithConstantOffset(Gep0, Offset, TD);
496   GetPointerBaseWithConstantOffset(Gep1, Offset, TD);
497   GetPointerBaseWithConstantOffset(Gep2, Offset, TD);
498   GetPointerBaseWithConstantOffset(Gep3, Offset, TD);
499 
500   // Gep of Geps
501   GetElementPtrInst *GepII0 = GetElementPtrInst::Create(I32Ty, Gep0, C2xi32b);
502   GetElementPtrInst *GepII1 = GetElementPtrInst::Create(I32Ty, Gep1, C2xi32a);
503   GetElementPtrInst *GepII2 = GetElementPtrInst::Create(I32Ty, Gep2, C2xi32b);
504   GetElementPtrInst *GepII3 = GetElementPtrInst::Create(I32Ty, Gep3, C2xi32a);
505 
506   EXPECT_EQ(GepII0->getNumIndices(), 1u);
507   EXPECT_EQ(GepII1->getNumIndices(), 1u);
508   EXPECT_EQ(GepII2->getNumIndices(), 1u);
509   EXPECT_EQ(GepII3->getNumIndices(), 1u);
510 
511   EXPECT_FALSE(GepII0->hasAllZeroIndices());
512   EXPECT_FALSE(GepII1->hasAllZeroIndices());
513   EXPECT_FALSE(GepII2->hasAllZeroIndices());
514   EXPECT_FALSE(GepII3->hasAllZeroIndices());
515 
516   delete GepII0;
517   delete GepII1;
518   delete GepII2;
519   delete GepII3;
520 
521   delete BTC0;
522   delete BTC1;
523   delete BTC2;
524   delete BTC3;
525 
526   delete Gep0;
527   delete Gep1;
528   delete Gep2;
529   delete Gep3;
530 
531   ICmp2->eraseFromParent();
532   delete BB0;
533 
534   delete ICmp0;
535   delete ICmp1;
536   delete PtrVecA;
537   delete PtrVecB;
538 }
539 
540 TEST(InstructionsTest, FPMathOperator) {
541   LLVMContext Context;
542   IRBuilder<> Builder(Context);
543   MDBuilder MDHelper(Context);
544   Instruction *I = Builder.CreatePHI(Builder.getDoubleTy(), 0);
545   MDNode *MD1 = MDHelper.createFPMath(1.0);
546   Value *V1 = Builder.CreateFAdd(I, I, "", MD1);
547   EXPECT_TRUE(isa<FPMathOperator>(V1));
548   FPMathOperator *O1 = cast<FPMathOperator>(V1);
549   EXPECT_EQ(O1->getFPAccuracy(), 1.0);
550   V1->deleteValue();
551   I->deleteValue();
552 }
553 
554 TEST(InstructionTest, ConstrainedTrans) {
555   LLVMContext Context;
556   std::unique_ptr<Module> M(new Module("MyModule", Context));
557   FunctionType *FTy =
558       FunctionType::get(Type::getVoidTy(Context),
559                         {Type::getFloatTy(Context), Type::getFloatTy(Context),
560                          Type::getInt32Ty(Context)},
561                         false);
562   auto *F = Function::Create(FTy, Function::ExternalLinkage, "", M.get());
563   auto *BB = BasicBlock::Create(Context, "bb", F);
564   IRBuilder<> Builder(Context);
565   Builder.SetInsertPoint(BB);
566   auto *Arg0 = F->arg_begin();
567   auto *Arg1 = F->arg_begin() + 1;
568 
569   {
570     auto *I = cast<Instruction>(Builder.CreateFAdd(Arg0, Arg1));
571     EXPECT_EQ(Intrinsic::experimental_constrained_fadd,
572               getConstrainedIntrinsicID(*I));
573   }
574 
575   {
576     auto *I = cast<Instruction>(
577         Builder.CreateFPToSI(Arg0, Type::getInt32Ty(Context)));
578     EXPECT_EQ(Intrinsic::experimental_constrained_fptosi,
579               getConstrainedIntrinsicID(*I));
580   }
581 
582   {
583     auto *I = cast<Instruction>(Builder.CreateIntrinsic(
584         Intrinsic::ceil, {Type::getFloatTy(Context)}, {Arg0}));
585     EXPECT_EQ(Intrinsic::experimental_constrained_ceil,
586               getConstrainedIntrinsicID(*I));
587   }
588 
589   {
590     auto *I = cast<Instruction>(Builder.CreateFCmpOEQ(Arg0, Arg1));
591     EXPECT_EQ(Intrinsic::experimental_constrained_fcmp,
592               getConstrainedIntrinsicID(*I));
593   }
594 
595   {
596     auto *Arg2 = F->arg_begin() + 2;
597     auto *I = cast<Instruction>(Builder.CreateAdd(Arg2, Arg2));
598     EXPECT_EQ(Intrinsic::not_intrinsic, getConstrainedIntrinsicID(*I));
599   }
600 
601   {
602     auto *I = cast<Instruction>(Builder.CreateConstrainedFPBinOp(
603         Intrinsic::experimental_constrained_fadd, Arg0, Arg0));
604     EXPECT_EQ(Intrinsic::not_intrinsic, getConstrainedIntrinsicID(*I));
605   }
606 }
607 
608 TEST(InstructionsTest, isEliminableCastPair) {
609   LLVMContext C;
610 
611   Type* Int16Ty = Type::getInt16Ty(C);
612   Type* Int32Ty = Type::getInt32Ty(C);
613   Type* Int64Ty = Type::getInt64Ty(C);
614   Type *Int64PtrTy = PointerType::get(C, 0);
615 
616   // Source and destination pointers have same size -> bitcast.
617   EXPECT_EQ(CastInst::isEliminableCastPair(CastInst::PtrToInt,
618                                            CastInst::IntToPtr,
619                                            Int64PtrTy, Int64Ty, Int64PtrTy,
620                                            Int32Ty, nullptr, Int32Ty),
621             CastInst::BitCast);
622 
623   // Source and destination have unknown sizes, but the same address space and
624   // the intermediate int is the maximum pointer size -> bitcast
625   EXPECT_EQ(CastInst::isEliminableCastPair(CastInst::PtrToInt,
626                                            CastInst::IntToPtr,
627                                            Int64PtrTy, Int64Ty, Int64PtrTy,
628                                            nullptr, nullptr, nullptr),
629             CastInst::BitCast);
630 
631   // Source and destination have unknown sizes, but the same address space and
632   // the intermediate int is not the maximum pointer size -> nothing
633   EXPECT_EQ(CastInst::isEliminableCastPair(CastInst::PtrToInt,
634                                            CastInst::IntToPtr,
635                                            Int64PtrTy, Int32Ty, Int64PtrTy,
636                                            nullptr, nullptr, nullptr),
637             0U);
638 
639   // Middle pointer big enough -> bitcast.
640   EXPECT_EQ(CastInst::isEliminableCastPair(CastInst::IntToPtr,
641                                            CastInst::PtrToInt,
642                                            Int64Ty, Int64PtrTy, Int64Ty,
643                                            nullptr, Int64Ty, nullptr),
644             CastInst::BitCast);
645 
646   // Middle pointer too small -> fail.
647   EXPECT_EQ(CastInst::isEliminableCastPair(CastInst::IntToPtr,
648                                            CastInst::PtrToInt,
649                                            Int64Ty, Int64PtrTy, Int64Ty,
650                                            nullptr, Int32Ty, nullptr),
651             0U);
652 
653   // Test that we don't eliminate bitcasts between different address spaces,
654   // or if we don't have available pointer size information.
655   DataLayout DL("e-p:32:32:32-p1:16:16:16-p2:64:64:64-i1:8:8-i8:8:8-i16:16:16"
656                 "-i32:32:32-i64:64:64-f32:32:32-f64:64:64-v64:64:64"
657                 "-v128:128:128-a:0:64-s:64:64-f80:128:128-n8:16:32:64-S128");
658 
659   Type *Int64PtrTyAS1 = PointerType::get(C, 1);
660   Type *Int64PtrTyAS2 = PointerType::get(C, 2);
661 
662   IntegerType *Int16SizePtr = DL.getIntPtrType(C, 1);
663   IntegerType *Int64SizePtr = DL.getIntPtrType(C, 2);
664 
665   // Cannot simplify inttoptr, addrspacecast
666   EXPECT_EQ(CastInst::isEliminableCastPair(CastInst::IntToPtr,
667                                            CastInst::AddrSpaceCast,
668                                            Int16Ty, Int64PtrTyAS1, Int64PtrTyAS2,
669                                            nullptr, Int16SizePtr, Int64SizePtr),
670             0U);
671 
672   // Cannot simplify addrspacecast, ptrtoint
673   EXPECT_EQ(CastInst::isEliminableCastPair(CastInst::AddrSpaceCast,
674                                            CastInst::PtrToInt,
675                                            Int64PtrTyAS1, Int64PtrTyAS2, Int16Ty,
676                                            Int64SizePtr, Int16SizePtr, nullptr),
677             0U);
678 
679   // Pass since the bitcast address spaces are the same
680   EXPECT_EQ(CastInst::isEliminableCastPair(CastInst::IntToPtr,
681                                            CastInst::BitCast,
682                                            Int16Ty, Int64PtrTyAS1, Int64PtrTyAS1,
683                                            nullptr, nullptr, nullptr),
684             CastInst::IntToPtr);
685 
686 }
687 
688 TEST(InstructionsTest, CloneCall) {
689   LLVMContext C;
690   Type *Int32Ty = Type::getInt32Ty(C);
691   Type *ArgTys[] = {Int32Ty, Int32Ty, Int32Ty};
692   FunctionType *FnTy = FunctionType::get(Int32Ty, ArgTys, /*isVarArg=*/false);
693   Value *Callee = Constant::getNullValue(PointerType::getUnqual(C));
694   Value *Args[] = {
695     ConstantInt::get(Int32Ty, 1),
696     ConstantInt::get(Int32Ty, 2),
697     ConstantInt::get(Int32Ty, 3)
698   };
699   std::unique_ptr<CallInst> Call(
700       CallInst::Create(FnTy, Callee, Args, "result"));
701 
702   // Test cloning the tail call kind.
703   CallInst::TailCallKind Kinds[] = {CallInst::TCK_None, CallInst::TCK_Tail,
704                                     CallInst::TCK_MustTail};
705   for (CallInst::TailCallKind TCK : Kinds) {
706     Call->setTailCallKind(TCK);
707     std::unique_ptr<CallInst> Clone(cast<CallInst>(Call->clone()));
708     EXPECT_EQ(Call->getTailCallKind(), Clone->getTailCallKind());
709   }
710   Call->setTailCallKind(CallInst::TCK_None);
711 
712   // Test cloning an attribute.
713   {
714     AttrBuilder AB(C);
715     AB.addAttribute(Attribute::NoUnwind);
716     Call->setAttributes(
717         AttributeList::get(C, AttributeList::FunctionIndex, AB));
718     std::unique_ptr<CallInst> Clone(cast<CallInst>(Call->clone()));
719     EXPECT_TRUE(Clone->doesNotThrow());
720   }
721 }
722 
723 TEST(InstructionsTest, AlterCallBundles) {
724   LLVMContext C;
725   Type *Int32Ty = Type::getInt32Ty(C);
726   FunctionType *FnTy = FunctionType::get(Int32Ty, Int32Ty, /*isVarArg=*/false);
727   Value *Callee = Constant::getNullValue(PointerType::getUnqual(C));
728   Value *Args[] = {ConstantInt::get(Int32Ty, 42)};
729   OperandBundleDef OldBundle("before", UndefValue::get(Int32Ty));
730   std::unique_ptr<CallInst> Call(
731       CallInst::Create(FnTy, Callee, Args, OldBundle, "result"));
732   Call->setTailCallKind(CallInst::TailCallKind::TCK_NoTail);
733   AttrBuilder AB(C);
734   AB.addAttribute(Attribute::Cold);
735   Call->setAttributes(AttributeList::get(C, AttributeList::FunctionIndex, AB));
736   Call->setDebugLoc(DebugLoc(MDNode::get(C, {})));
737 
738   OperandBundleDef NewBundle("after", ConstantInt::get(Int32Ty, 7));
739   std::unique_ptr<CallInst> Clone(CallInst::Create(Call.get(), NewBundle));
740   EXPECT_EQ(Call->arg_size(), Clone->arg_size());
741   EXPECT_EQ(Call->getArgOperand(0), Clone->getArgOperand(0));
742   EXPECT_EQ(Call->getCallingConv(), Clone->getCallingConv());
743   EXPECT_EQ(Call->getTailCallKind(), Clone->getTailCallKind());
744   EXPECT_TRUE(Clone->hasFnAttr(Attribute::AttrKind::Cold));
745   EXPECT_EQ(Call->getDebugLoc(), Clone->getDebugLoc());
746   EXPECT_EQ(Clone->getNumOperandBundles(), 1U);
747   EXPECT_TRUE(Clone->getOperandBundle("after"));
748 }
749 
750 TEST(InstructionsTest, AlterInvokeBundles) {
751   LLVMContext C;
752   Type *Int32Ty = Type::getInt32Ty(C);
753   FunctionType *FnTy = FunctionType::get(Int32Ty, Int32Ty, /*isVarArg=*/false);
754   Value *Callee = Constant::getNullValue(PointerType::getUnqual(C));
755   Value *Args[] = {ConstantInt::get(Int32Ty, 42)};
756   std::unique_ptr<BasicBlock> NormalDest(BasicBlock::Create(C));
757   std::unique_ptr<BasicBlock> UnwindDest(BasicBlock::Create(C));
758   OperandBundleDef OldBundle("before", UndefValue::get(Int32Ty));
759   std::unique_ptr<InvokeInst> Invoke(
760       InvokeInst::Create(FnTy, Callee, NormalDest.get(), UnwindDest.get(), Args,
761                          OldBundle, "result"));
762   AttrBuilder AB(C);
763   AB.addAttribute(Attribute::Cold);
764   Invoke->setAttributes(
765       AttributeList::get(C, AttributeList::FunctionIndex, AB));
766   Invoke->setDebugLoc(DebugLoc(MDNode::get(C, {})));
767 
768   OperandBundleDef NewBundle("after", ConstantInt::get(Int32Ty, 7));
769   std::unique_ptr<InvokeInst> Clone(
770       InvokeInst::Create(Invoke.get(), NewBundle));
771   EXPECT_EQ(Invoke->getNormalDest(), Clone->getNormalDest());
772   EXPECT_EQ(Invoke->getUnwindDest(), Clone->getUnwindDest());
773   EXPECT_EQ(Invoke->arg_size(), Clone->arg_size());
774   EXPECT_EQ(Invoke->getArgOperand(0), Clone->getArgOperand(0));
775   EXPECT_EQ(Invoke->getCallingConv(), Clone->getCallingConv());
776   EXPECT_TRUE(Clone->hasFnAttr(Attribute::AttrKind::Cold));
777   EXPECT_EQ(Invoke->getDebugLoc(), Clone->getDebugLoc());
778   EXPECT_EQ(Clone->getNumOperandBundles(), 1U);
779   EXPECT_TRUE(Clone->getOperandBundle("after"));
780 }
781 
782 TEST_F(ModuleWithFunctionTest, DropPoisonGeneratingFlags) {
783   auto *OnlyBB = BasicBlock::Create(Ctx, "bb", F);
784   auto *Arg0 = &*F->arg_begin();
785 
786   IRBuilder<NoFolder> B(Ctx);
787   B.SetInsertPoint(OnlyBB);
788 
789   {
790     auto *UI =
791         cast<Instruction>(B.CreateUDiv(Arg0, Arg0, "", /*isExact*/ true));
792     ASSERT_TRUE(UI->isExact());
793     UI->dropPoisonGeneratingFlags();
794     ASSERT_FALSE(UI->isExact());
795   }
796 
797   {
798     auto *ShrI =
799         cast<Instruction>(B.CreateLShr(Arg0, Arg0, "", /*isExact*/ true));
800     ASSERT_TRUE(ShrI->isExact());
801     ShrI->dropPoisonGeneratingFlags();
802     ASSERT_FALSE(ShrI->isExact());
803   }
804 
805   {
806     auto *AI = cast<Instruction>(
807         B.CreateAdd(Arg0, Arg0, "", /*HasNUW*/ true, /*HasNSW*/ false));
808     ASSERT_TRUE(AI->hasNoUnsignedWrap());
809     AI->dropPoisonGeneratingFlags();
810     ASSERT_FALSE(AI->hasNoUnsignedWrap());
811     ASSERT_FALSE(AI->hasNoSignedWrap());
812   }
813 
814   {
815     auto *SI = cast<Instruction>(
816         B.CreateAdd(Arg0, Arg0, "", /*HasNUW*/ false, /*HasNSW*/ true));
817     ASSERT_TRUE(SI->hasNoSignedWrap());
818     SI->dropPoisonGeneratingFlags();
819     ASSERT_FALSE(SI->hasNoUnsignedWrap());
820     ASSERT_FALSE(SI->hasNoSignedWrap());
821   }
822 
823   {
824     auto *ShlI = cast<Instruction>(
825         B.CreateShl(Arg0, Arg0, "", /*HasNUW*/ true, /*HasNSW*/ true));
826     ASSERT_TRUE(ShlI->hasNoSignedWrap());
827     ASSERT_TRUE(ShlI->hasNoUnsignedWrap());
828     ShlI->dropPoisonGeneratingFlags();
829     ASSERT_FALSE(ShlI->hasNoUnsignedWrap());
830     ASSERT_FALSE(ShlI->hasNoSignedWrap());
831   }
832 
833   {
834     Value *GEPBase = Constant::getNullValue(B.getPtrTy());
835     auto *GI = cast<GetElementPtrInst>(
836         B.CreateInBoundsGEP(B.getInt8Ty(), GEPBase, Arg0));
837     ASSERT_TRUE(GI->isInBounds());
838     GI->dropPoisonGeneratingFlags();
839     ASSERT_FALSE(GI->isInBounds());
840   }
841 }
842 
843 TEST(InstructionsTest, GEPIndices) {
844   LLVMContext Context;
845   IRBuilder<NoFolder> Builder(Context);
846   Type *ElementTy = Builder.getInt8Ty();
847   Type *ArrTy = ArrayType::get(ArrayType::get(ElementTy, 64), 64);
848   Value *Indices[] = {
849     Builder.getInt32(0),
850     Builder.getInt32(13),
851     Builder.getInt32(42) };
852 
853   Value *V = Builder.CreateGEP(
854       ArrTy, UndefValue::get(PointerType::getUnqual(Context)), Indices);
855   ASSERT_TRUE(isa<GetElementPtrInst>(V));
856 
857   auto *GEPI = cast<GetElementPtrInst>(V);
858   ASSERT_NE(GEPI->idx_begin(), GEPI->idx_end());
859   ASSERT_EQ(GEPI->idx_end(), std::next(GEPI->idx_begin(), 3));
860   EXPECT_EQ(Indices[0], GEPI->idx_begin()[0]);
861   EXPECT_EQ(Indices[1], GEPI->idx_begin()[1]);
862   EXPECT_EQ(Indices[2], GEPI->idx_begin()[2]);
863   EXPECT_EQ(GEPI->idx_begin(), GEPI->indices().begin());
864   EXPECT_EQ(GEPI->idx_end(), GEPI->indices().end());
865 
866   const auto *CGEPI = GEPI;
867   ASSERT_NE(CGEPI->idx_begin(), CGEPI->idx_end());
868   ASSERT_EQ(CGEPI->idx_end(), std::next(CGEPI->idx_begin(), 3));
869   EXPECT_EQ(Indices[0], CGEPI->idx_begin()[0]);
870   EXPECT_EQ(Indices[1], CGEPI->idx_begin()[1]);
871   EXPECT_EQ(Indices[2], CGEPI->idx_begin()[2]);
872   EXPECT_EQ(CGEPI->idx_begin(), CGEPI->indices().begin());
873   EXPECT_EQ(CGEPI->idx_end(), CGEPI->indices().end());
874 
875   delete GEPI;
876 }
877 
878 TEST(InstructionsTest, ZeroIndexGEP) {
879   LLVMContext Context;
880   DataLayout DL;
881   Type *PtrTy = PointerType::getUnqual(Context);
882   auto *GEP = GetElementPtrInst::Create(Type::getInt8Ty(Context),
883                                         PoisonValue::get(PtrTy), {});
884 
885   APInt Offset(DL.getIndexTypeSizeInBits(PtrTy), 0);
886   EXPECT_TRUE(GEP->accumulateConstantOffset(DL, Offset));
887   EXPECT_TRUE(Offset.isZero());
888 
889   delete GEP;
890 }
891 
892 TEST(InstructionsTest, SwitchInst) {
893   LLVMContext C;
894 
895   std::unique_ptr<BasicBlock> BB1, BB2, BB3;
896   BB1.reset(BasicBlock::Create(C));
897   BB2.reset(BasicBlock::Create(C));
898   BB3.reset(BasicBlock::Create(C));
899 
900   // We create block 0 after the others so that it gets destroyed first and
901   // clears the uses of the other basic blocks.
902   std::unique_ptr<BasicBlock> BB0(BasicBlock::Create(C));
903 
904   auto *Int32Ty = Type::getInt32Ty(C);
905 
906   SwitchInst *SI =
907       SwitchInst::Create(UndefValue::get(Int32Ty), BB0.get(), 3, BB0.get());
908   SI->addCase(ConstantInt::get(Int32Ty, 1), BB1.get());
909   SI->addCase(ConstantInt::get(Int32Ty, 2), BB2.get());
910   SI->addCase(ConstantInt::get(Int32Ty, 3), BB3.get());
911 
912   auto CI = SI->case_begin();
913   ASSERT_NE(CI, SI->case_end());
914   EXPECT_EQ(1, CI->getCaseValue()->getSExtValue());
915   EXPECT_EQ(BB1.get(), CI->getCaseSuccessor());
916   EXPECT_EQ(2, (CI + 1)->getCaseValue()->getSExtValue());
917   EXPECT_EQ(BB2.get(), (CI + 1)->getCaseSuccessor());
918   EXPECT_EQ(3, (CI + 2)->getCaseValue()->getSExtValue());
919   EXPECT_EQ(BB3.get(), (CI + 2)->getCaseSuccessor());
920   EXPECT_EQ(CI + 1, std::next(CI));
921   EXPECT_EQ(CI + 2, std::next(CI, 2));
922   EXPECT_EQ(CI + 3, std::next(CI, 3));
923   EXPECT_EQ(SI->case_end(), CI + 3);
924   EXPECT_EQ(0, CI - CI);
925   EXPECT_EQ(1, (CI + 1) - CI);
926   EXPECT_EQ(2, (CI + 2) - CI);
927   EXPECT_EQ(3, SI->case_end() - CI);
928   EXPECT_EQ(3, std::distance(CI, SI->case_end()));
929 
930   auto CCI = const_cast<const SwitchInst *>(SI)->case_begin();
931   SwitchInst::ConstCaseIt CCE = SI->case_end();
932   ASSERT_NE(CCI, SI->case_end());
933   EXPECT_EQ(1, CCI->getCaseValue()->getSExtValue());
934   EXPECT_EQ(BB1.get(), CCI->getCaseSuccessor());
935   EXPECT_EQ(2, (CCI + 1)->getCaseValue()->getSExtValue());
936   EXPECT_EQ(BB2.get(), (CCI + 1)->getCaseSuccessor());
937   EXPECT_EQ(3, (CCI + 2)->getCaseValue()->getSExtValue());
938   EXPECT_EQ(BB3.get(), (CCI + 2)->getCaseSuccessor());
939   EXPECT_EQ(CCI + 1, std::next(CCI));
940   EXPECT_EQ(CCI + 2, std::next(CCI, 2));
941   EXPECT_EQ(CCI + 3, std::next(CCI, 3));
942   EXPECT_EQ(CCE, CCI + 3);
943   EXPECT_EQ(0, CCI - CCI);
944   EXPECT_EQ(1, (CCI + 1) - CCI);
945   EXPECT_EQ(2, (CCI + 2) - CCI);
946   EXPECT_EQ(3, CCE - CCI);
947   EXPECT_EQ(3, std::distance(CCI, CCE));
948 
949   // Make sure that the const iterator is compatible with a const auto ref.
950   const auto &Handle = *CCI;
951   EXPECT_EQ(1, Handle.getCaseValue()->getSExtValue());
952   EXPECT_EQ(BB1.get(), Handle.getCaseSuccessor());
953 }
954 
955 TEST(InstructionsTest, SwitchInstProfUpdateWrapper) {
956   LLVMContext C;
957 
958   std::unique_ptr<BasicBlock> BB1, BB2, BB3;
959   BB1.reset(BasicBlock::Create(C));
960   BB2.reset(BasicBlock::Create(C));
961   BB3.reset(BasicBlock::Create(C));
962 
963   // We create block 0 after the others so that it gets destroyed first and
964   // clears the uses of the other basic blocks.
965   std::unique_ptr<BasicBlock> BB0(BasicBlock::Create(C));
966 
967   auto *Int32Ty = Type::getInt32Ty(C);
968 
969   SwitchInst *SI =
970       SwitchInst::Create(UndefValue::get(Int32Ty), BB0.get(), 4, BB0.get());
971   SI->addCase(ConstantInt::get(Int32Ty, 1), BB1.get());
972   SI->addCase(ConstantInt::get(Int32Ty, 2), BB2.get());
973   SI->setMetadata(LLVMContext::MD_prof,
974                   MDBuilder(C).createBranchWeights({ 9, 1, 22 }));
975 
976   {
977     SwitchInstProfUpdateWrapper SIW(*SI);
978     EXPECT_EQ(*SIW.getSuccessorWeight(0), 9u);
979     EXPECT_EQ(*SIW.getSuccessorWeight(1), 1u);
980     EXPECT_EQ(*SIW.getSuccessorWeight(2), 22u);
981     SIW.setSuccessorWeight(0, 99u);
982     SIW.setSuccessorWeight(1, 11u);
983     EXPECT_EQ(*SIW.getSuccessorWeight(0), 99u);
984     EXPECT_EQ(*SIW.getSuccessorWeight(1), 11u);
985     EXPECT_EQ(*SIW.getSuccessorWeight(2), 22u);
986   }
987 
988   { // Create another wrapper and check that the data persist.
989     SwitchInstProfUpdateWrapper SIW(*SI);
990     EXPECT_EQ(*SIW.getSuccessorWeight(0), 99u);
991     EXPECT_EQ(*SIW.getSuccessorWeight(1), 11u);
992     EXPECT_EQ(*SIW.getSuccessorWeight(2), 22u);
993   }
994 }
995 
996 TEST(InstructionsTest, CommuteShuffleMask) {
997   SmallVector<int, 16> Indices({-1, 0, 7});
998   ShuffleVectorInst::commuteShuffleMask(Indices, 4);
999   EXPECT_THAT(Indices, testing::ContainerEq(ArrayRef<int>({-1, 4, 3})));
1000 }
1001 
1002 TEST(InstructionsTest, ShuffleMaskQueries) {
1003   // Create the elements for various constant vectors.
1004   LLVMContext Ctx;
1005   Type *Int32Ty = Type::getInt32Ty(Ctx);
1006   Constant *CU = UndefValue::get(Int32Ty);
1007   Constant *C0 = ConstantInt::get(Int32Ty, 0);
1008   Constant *C1 = ConstantInt::get(Int32Ty, 1);
1009   Constant *C2 = ConstantInt::get(Int32Ty, 2);
1010   Constant *C3 = ConstantInt::get(Int32Ty, 3);
1011   Constant *C4 = ConstantInt::get(Int32Ty, 4);
1012   Constant *C5 = ConstantInt::get(Int32Ty, 5);
1013   Constant *C6 = ConstantInt::get(Int32Ty, 6);
1014   Constant *C7 = ConstantInt::get(Int32Ty, 7);
1015 
1016   Constant *Identity = ConstantVector::get({C0, CU, C2, C3, C4});
1017   EXPECT_TRUE(ShuffleVectorInst::isIdentityMask(
1018       Identity, cast<FixedVectorType>(Identity->getType())->getNumElements()));
1019   EXPECT_FALSE(ShuffleVectorInst::isSelectMask(
1020       Identity,
1021       cast<FixedVectorType>(Identity->getType())
1022           ->getNumElements())); // identity is distinguished from select
1023   EXPECT_FALSE(ShuffleVectorInst::isReverseMask(
1024       Identity, cast<FixedVectorType>(Identity->getType())->getNumElements()));
1025   EXPECT_TRUE(ShuffleVectorInst::isSingleSourceMask(
1026       Identity, cast<FixedVectorType>(Identity->getType())
1027                     ->getNumElements())); // identity is always single source
1028   EXPECT_FALSE(ShuffleVectorInst::isZeroEltSplatMask(
1029       Identity, cast<FixedVectorType>(Identity->getType())->getNumElements()));
1030   EXPECT_FALSE(ShuffleVectorInst::isTransposeMask(
1031       Identity, cast<FixedVectorType>(Identity->getType())->getNumElements()));
1032 
1033   Constant *Select = ConstantVector::get({CU, C1, C5});
1034   EXPECT_FALSE(ShuffleVectorInst::isIdentityMask(
1035       Select, cast<FixedVectorType>(Select->getType())->getNumElements()));
1036   EXPECT_TRUE(ShuffleVectorInst::isSelectMask(
1037       Select, cast<FixedVectorType>(Select->getType())->getNumElements()));
1038   EXPECT_FALSE(ShuffleVectorInst::isReverseMask(
1039       Select, cast<FixedVectorType>(Select->getType())->getNumElements()));
1040   EXPECT_FALSE(ShuffleVectorInst::isSingleSourceMask(
1041       Select, cast<FixedVectorType>(Select->getType())->getNumElements()));
1042   EXPECT_FALSE(ShuffleVectorInst::isZeroEltSplatMask(
1043       Select, cast<FixedVectorType>(Select->getType())->getNumElements()));
1044   EXPECT_FALSE(ShuffleVectorInst::isTransposeMask(
1045       Select, cast<FixedVectorType>(Select->getType())->getNumElements()));
1046 
1047   Constant *Reverse = ConstantVector::get({C3, C2, C1, CU});
1048   EXPECT_FALSE(ShuffleVectorInst::isIdentityMask(
1049       Reverse, cast<FixedVectorType>(Reverse->getType())->getNumElements()));
1050   EXPECT_FALSE(ShuffleVectorInst::isSelectMask(
1051       Reverse, cast<FixedVectorType>(Reverse->getType())->getNumElements()));
1052   EXPECT_TRUE(ShuffleVectorInst::isReverseMask(
1053       Reverse, cast<FixedVectorType>(Reverse->getType())->getNumElements()));
1054   EXPECT_TRUE(ShuffleVectorInst::isSingleSourceMask(
1055       Reverse, cast<FixedVectorType>(Reverse->getType())
1056                    ->getNumElements())); // reverse is always single source
1057   EXPECT_FALSE(ShuffleVectorInst::isZeroEltSplatMask(
1058       Reverse, cast<FixedVectorType>(Reverse->getType())->getNumElements()));
1059   EXPECT_FALSE(ShuffleVectorInst::isTransposeMask(
1060       Reverse, cast<FixedVectorType>(Reverse->getType())->getNumElements()));
1061 
1062   Constant *SingleSource = ConstantVector::get({C2, C2, C0, CU});
1063   EXPECT_FALSE(ShuffleVectorInst::isIdentityMask(
1064       SingleSource,
1065       cast<FixedVectorType>(SingleSource->getType())->getNumElements()));
1066   EXPECT_FALSE(ShuffleVectorInst::isSelectMask(
1067       SingleSource,
1068       cast<FixedVectorType>(SingleSource->getType())->getNumElements()));
1069   EXPECT_FALSE(ShuffleVectorInst::isReverseMask(
1070       SingleSource,
1071       cast<FixedVectorType>(SingleSource->getType())->getNumElements()));
1072   EXPECT_TRUE(ShuffleVectorInst::isSingleSourceMask(
1073       SingleSource,
1074       cast<FixedVectorType>(SingleSource->getType())->getNumElements()));
1075   EXPECT_FALSE(ShuffleVectorInst::isZeroEltSplatMask(
1076       SingleSource,
1077       cast<FixedVectorType>(SingleSource->getType())->getNumElements()));
1078   EXPECT_FALSE(ShuffleVectorInst::isTransposeMask(
1079       SingleSource,
1080       cast<FixedVectorType>(SingleSource->getType())->getNumElements()));
1081 
1082   Constant *ZeroEltSplat = ConstantVector::get({C0, C0, CU, C0});
1083   EXPECT_FALSE(ShuffleVectorInst::isIdentityMask(
1084       ZeroEltSplat,
1085       cast<FixedVectorType>(ZeroEltSplat->getType())->getNumElements()));
1086   EXPECT_FALSE(ShuffleVectorInst::isSelectMask(
1087       ZeroEltSplat,
1088       cast<FixedVectorType>(ZeroEltSplat->getType())->getNumElements()));
1089   EXPECT_FALSE(ShuffleVectorInst::isReverseMask(
1090       ZeroEltSplat,
1091       cast<FixedVectorType>(ZeroEltSplat->getType())->getNumElements()));
1092   EXPECT_TRUE(ShuffleVectorInst::isSingleSourceMask(
1093       ZeroEltSplat, cast<FixedVectorType>(ZeroEltSplat->getType())
1094                         ->getNumElements())); // 0-splat is always single source
1095   EXPECT_TRUE(ShuffleVectorInst::isZeroEltSplatMask(
1096       ZeroEltSplat,
1097       cast<FixedVectorType>(ZeroEltSplat->getType())->getNumElements()));
1098   EXPECT_FALSE(ShuffleVectorInst::isTransposeMask(
1099       ZeroEltSplat,
1100       cast<FixedVectorType>(ZeroEltSplat->getType())->getNumElements()));
1101 
1102   Constant *Transpose = ConstantVector::get({C0, C4, C2, C6});
1103   EXPECT_FALSE(ShuffleVectorInst::isIdentityMask(
1104       Transpose,
1105       cast<FixedVectorType>(Transpose->getType())->getNumElements()));
1106   EXPECT_FALSE(ShuffleVectorInst::isSelectMask(
1107       Transpose,
1108       cast<FixedVectorType>(Transpose->getType())->getNumElements()));
1109   EXPECT_FALSE(ShuffleVectorInst::isReverseMask(
1110       Transpose,
1111       cast<FixedVectorType>(Transpose->getType())->getNumElements()));
1112   EXPECT_FALSE(ShuffleVectorInst::isSingleSourceMask(
1113       Transpose,
1114       cast<FixedVectorType>(Transpose->getType())->getNumElements()));
1115   EXPECT_FALSE(ShuffleVectorInst::isZeroEltSplatMask(
1116       Transpose,
1117       cast<FixedVectorType>(Transpose->getType())->getNumElements()));
1118   EXPECT_TRUE(ShuffleVectorInst::isTransposeMask(
1119       Transpose,
1120       cast<FixedVectorType>(Transpose->getType())->getNumElements()));
1121 
1122   // More tests to make sure the logic is/stays correct...
1123   EXPECT_TRUE(ShuffleVectorInst::isIdentityMask(
1124       ConstantVector::get({CU, C1, CU, C3}), 4));
1125   EXPECT_TRUE(ShuffleVectorInst::isIdentityMask(
1126       ConstantVector::get({C4, CU, C6, CU}), 4));
1127 
1128   EXPECT_TRUE(ShuffleVectorInst::isSelectMask(
1129       ConstantVector::get({C4, C1, C6, CU}), 4));
1130   EXPECT_TRUE(ShuffleVectorInst::isSelectMask(
1131       ConstantVector::get({CU, C1, C6, C3}), 4));
1132 
1133   EXPECT_TRUE(ShuffleVectorInst::isReverseMask(
1134       ConstantVector::get({C7, C6, CU, C4}), 4));
1135   EXPECT_TRUE(ShuffleVectorInst::isReverseMask(
1136       ConstantVector::get({C3, CU, C1, CU}), 4));
1137 
1138   EXPECT_TRUE(ShuffleVectorInst::isSingleSourceMask(
1139       ConstantVector::get({C7, C5, CU, C7}), 4));
1140   EXPECT_TRUE(ShuffleVectorInst::isSingleSourceMask(
1141       ConstantVector::get({C3, C0, CU, C3}), 4));
1142 
1143   EXPECT_TRUE(ShuffleVectorInst::isZeroEltSplatMask(
1144       ConstantVector::get({C4, CU, CU, C4}), 4));
1145   EXPECT_TRUE(ShuffleVectorInst::isZeroEltSplatMask(
1146       ConstantVector::get({CU, C0, CU, C0}), 4));
1147 
1148   EXPECT_TRUE(ShuffleVectorInst::isTransposeMask(
1149       ConstantVector::get({C1, C5, C3, C7}), 4));
1150   EXPECT_TRUE(
1151       ShuffleVectorInst::isTransposeMask(ConstantVector::get({C1, C3}), 2));
1152 
1153   // Nothing special about the values here - just re-using inputs to reduce
1154   // code.
1155   Constant *V0 = ConstantVector::get({C0, C1, C2, C3});
1156   Constant *V1 = ConstantVector::get({C3, C2, C1, C0});
1157 
1158   // Identity with undef elts.
1159   ShuffleVectorInst *Id1 = new ShuffleVectorInst(V0, V1,
1160                                                  ConstantVector::get({C0, C1, CU, CU}));
1161   EXPECT_TRUE(Id1->isIdentity());
1162   EXPECT_FALSE(Id1->isIdentityWithPadding());
1163   EXPECT_FALSE(Id1->isIdentityWithExtract());
1164   EXPECT_FALSE(Id1->isConcat());
1165   delete Id1;
1166 
1167   // Result has less elements than operands.
1168   ShuffleVectorInst *Id2 = new ShuffleVectorInst(V0, V1,
1169                                                  ConstantVector::get({C0, C1, C2}));
1170   EXPECT_FALSE(Id2->isIdentity());
1171   EXPECT_FALSE(Id2->isIdentityWithPadding());
1172   EXPECT_TRUE(Id2->isIdentityWithExtract());
1173   EXPECT_FALSE(Id2->isConcat());
1174   delete Id2;
1175 
1176   // Result has less elements than operands; choose from Op1.
1177   ShuffleVectorInst *Id3 = new ShuffleVectorInst(V0, V1,
1178                                                  ConstantVector::get({C4, CU, C6}));
1179   EXPECT_FALSE(Id3->isIdentity());
1180   EXPECT_FALSE(Id3->isIdentityWithPadding());
1181   EXPECT_TRUE(Id3->isIdentityWithExtract());
1182   EXPECT_FALSE(Id3->isConcat());
1183   delete Id3;
1184 
1185   // Result has less elements than operands; choose from Op0 and Op1 is not identity.
1186   ShuffleVectorInst *Id4 = new ShuffleVectorInst(V0, V1,
1187                                                  ConstantVector::get({C4, C1, C6}));
1188   EXPECT_FALSE(Id4->isIdentity());
1189   EXPECT_FALSE(Id4->isIdentityWithPadding());
1190   EXPECT_FALSE(Id4->isIdentityWithExtract());
1191   EXPECT_FALSE(Id4->isConcat());
1192   delete Id4;
1193 
1194   // Result has more elements than operands, and extra elements are undef.
1195   ShuffleVectorInst *Id5 = new ShuffleVectorInst(V0, V1,
1196                                                  ConstantVector::get({CU, C1, C2, C3, CU, CU}));
1197   EXPECT_FALSE(Id5->isIdentity());
1198   EXPECT_TRUE(Id5->isIdentityWithPadding());
1199   EXPECT_FALSE(Id5->isIdentityWithExtract());
1200   EXPECT_FALSE(Id5->isConcat());
1201   delete Id5;
1202 
1203   // Result has more elements than operands, and extra elements are undef; choose from Op1.
1204   ShuffleVectorInst *Id6 = new ShuffleVectorInst(V0, V1,
1205                                                  ConstantVector::get({C4, C5, C6, CU, CU, CU}));
1206   EXPECT_FALSE(Id6->isIdentity());
1207   EXPECT_TRUE(Id6->isIdentityWithPadding());
1208   EXPECT_FALSE(Id6->isIdentityWithExtract());
1209   EXPECT_FALSE(Id6->isConcat());
1210   delete Id6;
1211 
1212   // Result has more elements than operands, but extra elements are not undef.
1213   ShuffleVectorInst *Id7 = new ShuffleVectorInst(V0, V1,
1214                                                  ConstantVector::get({C0, C1, C2, C3, CU, C1}));
1215   EXPECT_FALSE(Id7->isIdentity());
1216   EXPECT_FALSE(Id7->isIdentityWithPadding());
1217   EXPECT_FALSE(Id7->isIdentityWithExtract());
1218   EXPECT_FALSE(Id7->isConcat());
1219   delete Id7;
1220 
1221   // Result has more elements than operands; choose from Op0 and Op1 is not identity.
1222   ShuffleVectorInst *Id8 = new ShuffleVectorInst(V0, V1,
1223                                                  ConstantVector::get({C4, CU, C2, C3, CU, CU}));
1224   EXPECT_FALSE(Id8->isIdentity());
1225   EXPECT_FALSE(Id8->isIdentityWithPadding());
1226   EXPECT_FALSE(Id8->isIdentityWithExtract());
1227   EXPECT_FALSE(Id8->isConcat());
1228   delete Id8;
1229 
1230   // Result has twice as many elements as operands; choose consecutively from Op0 and Op1 is concat.
1231   ShuffleVectorInst *Id9 = new ShuffleVectorInst(V0, V1,
1232                                                  ConstantVector::get({C0, CU, C2, C3, CU, CU, C6, C7}));
1233   EXPECT_FALSE(Id9->isIdentity());
1234   EXPECT_FALSE(Id9->isIdentityWithPadding());
1235   EXPECT_FALSE(Id9->isIdentityWithExtract());
1236   EXPECT_TRUE(Id9->isConcat());
1237   delete Id9;
1238 
1239   // Result has less than twice as many elements as operands, so not a concat.
1240   ShuffleVectorInst *Id10 = new ShuffleVectorInst(V0, V1,
1241                                                   ConstantVector::get({C0, CU, C2, C3, CU, CU, C6}));
1242   EXPECT_FALSE(Id10->isIdentity());
1243   EXPECT_FALSE(Id10->isIdentityWithPadding());
1244   EXPECT_FALSE(Id10->isIdentityWithExtract());
1245   EXPECT_FALSE(Id10->isConcat());
1246   delete Id10;
1247 
1248   // Result has more than twice as many elements as operands, so not a concat.
1249   ShuffleVectorInst *Id11 = new ShuffleVectorInst(V0, V1,
1250                                                   ConstantVector::get({C0, CU, C2, C3, CU, CU, C6, C7, CU}));
1251   EXPECT_FALSE(Id11->isIdentity());
1252   EXPECT_FALSE(Id11->isIdentityWithPadding());
1253   EXPECT_FALSE(Id11->isIdentityWithExtract());
1254   EXPECT_FALSE(Id11->isConcat());
1255   delete Id11;
1256 
1257   // If an input is undef, it's not a concat.
1258   // TODO: IdentityWithPadding should be true here even though the high mask values are not undef.
1259   ShuffleVectorInst *Id12 = new ShuffleVectorInst(V0, ConstantVector::get({CU, CU, CU, CU}),
1260                                                   ConstantVector::get({C0, CU, C2, C3, CU, CU, C6, C7}));
1261   EXPECT_FALSE(Id12->isIdentity());
1262   EXPECT_FALSE(Id12->isIdentityWithPadding());
1263   EXPECT_FALSE(Id12->isIdentityWithExtract());
1264   EXPECT_FALSE(Id12->isConcat());
1265   delete Id12;
1266 
1267   // Not possible to express shuffle mask for scalable vector for extract
1268   // subvector.
1269   Type *VScaleV4Int32Ty = ScalableVectorType::get(Int32Ty, 4);
1270   ShuffleVectorInst *Id13 =
1271       new ShuffleVectorInst(Constant::getAllOnesValue(VScaleV4Int32Ty),
1272                             UndefValue::get(VScaleV4Int32Ty),
1273                             Constant::getNullValue(VScaleV4Int32Ty));
1274   int Index = 0;
1275   EXPECT_FALSE(Id13->isExtractSubvectorMask(Index));
1276   EXPECT_FALSE(Id13->changesLength());
1277   EXPECT_FALSE(Id13->increasesLength());
1278   delete Id13;
1279 
1280   // Result has twice as many operands.
1281   Type *VScaleV2Int32Ty = ScalableVectorType::get(Int32Ty, 2);
1282   ShuffleVectorInst *Id14 =
1283       new ShuffleVectorInst(Constant::getAllOnesValue(VScaleV2Int32Ty),
1284                             UndefValue::get(VScaleV2Int32Ty),
1285                             Constant::getNullValue(VScaleV4Int32Ty));
1286   EXPECT_TRUE(Id14->changesLength());
1287   EXPECT_TRUE(Id14->increasesLength());
1288   delete Id14;
1289 
1290   // Not possible to express these masks for scalable vectors, make sure we
1291   // don't crash.
1292   ShuffleVectorInst *Id15 =
1293       new ShuffleVectorInst(Constant::getAllOnesValue(VScaleV2Int32Ty),
1294                             Constant::getNullValue(VScaleV2Int32Ty),
1295                             Constant::getNullValue(VScaleV2Int32Ty));
1296   EXPECT_FALSE(Id15->isIdentityWithPadding());
1297   EXPECT_FALSE(Id15->isIdentityWithExtract());
1298   EXPECT_FALSE(Id15->isConcat());
1299   delete Id15;
1300 }
1301 
1302 TEST(InstructionsTest, ShuffleMaskIsReplicationMask) {
1303   for (int ReplicationFactor : seq_inclusive(1, 8)) {
1304     for (int VF : seq_inclusive(1, 8)) {
1305       const auto ReplicatedMask = createReplicatedMask(ReplicationFactor, VF);
1306       int GuessedReplicationFactor = -1, GuessedVF = -1;
1307       EXPECT_TRUE(ShuffleVectorInst::isReplicationMask(
1308           ReplicatedMask, GuessedReplicationFactor, GuessedVF));
1309       EXPECT_EQ(GuessedReplicationFactor, ReplicationFactor);
1310       EXPECT_EQ(GuessedVF, VF);
1311 
1312       for (int OpVF : seq_inclusive(VF, 2 * VF + 1)) {
1313         LLVMContext Ctx;
1314         Type *OpVFTy = FixedVectorType::get(IntegerType::getInt1Ty(Ctx), OpVF);
1315         Value *Op = ConstantVector::getNullValue(OpVFTy);
1316         ShuffleVectorInst *SVI = new ShuffleVectorInst(Op, Op, ReplicatedMask);
1317         EXPECT_EQ(SVI->isReplicationMask(GuessedReplicationFactor, GuessedVF),
1318                   OpVF == VF);
1319         delete SVI;
1320       }
1321     }
1322   }
1323 }
1324 
1325 TEST(InstructionsTest, ShuffleMaskIsReplicationMask_undef) {
1326   for (int ReplicationFactor : seq_inclusive(1, 4)) {
1327     for (int VF : seq_inclusive(1, 4)) {
1328       const auto ReplicatedMask = createReplicatedMask(ReplicationFactor, VF);
1329       int GuessedReplicationFactor = -1, GuessedVF = -1;
1330 
1331       // If we change some mask elements to undef, we should still match.
1332 
1333       SmallVector<SmallVector<bool>> ElementChoices(ReplicatedMask.size(),
1334                                                     {false, true});
1335 
1336       CombinationGenerator<bool, decltype(ElementChoices)::value_type,
1337                            /*variable_smallsize=*/4>
1338           G(ElementChoices);
1339 
1340       G.generate([&](ArrayRef<bool> UndefOverrides) -> bool {
1341         SmallVector<int> AdjustedMask;
1342         AdjustedMask.reserve(ReplicatedMask.size());
1343         for (auto I : zip(ReplicatedMask, UndefOverrides))
1344           AdjustedMask.emplace_back(std::get<1>(I) ? -1 : std::get<0>(I));
1345         assert(AdjustedMask.size() == ReplicatedMask.size() &&
1346                "Size misprediction");
1347 
1348         EXPECT_TRUE(ShuffleVectorInst::isReplicationMask(
1349             AdjustedMask, GuessedReplicationFactor, GuessedVF));
1350         // Do not check GuessedReplicationFactor and GuessedVF,
1351         // with enough undef's we may deduce a different tuple.
1352 
1353         return /*Abort=*/false;
1354       });
1355     }
1356   }
1357 }
1358 
1359 TEST(InstructionsTest, ShuffleMaskIsReplicationMask_Exhaustive_Correctness) {
1360   for (int ShufMaskNumElts : seq_inclusive(1, 6)) {
1361     SmallVector<int> PossibleShufMaskElts;
1362     PossibleShufMaskElts.reserve(ShufMaskNumElts + 2);
1363     for (int PossibleShufMaskElt : seq_inclusive(-1, ShufMaskNumElts))
1364       PossibleShufMaskElts.emplace_back(PossibleShufMaskElt);
1365     assert(PossibleShufMaskElts.size() == ShufMaskNumElts + 2U &&
1366            "Size misprediction");
1367 
1368     SmallVector<SmallVector<int>> ElementChoices(ShufMaskNumElts,
1369                                                  PossibleShufMaskElts);
1370 
1371     CombinationGenerator<int, decltype(ElementChoices)::value_type,
1372                          /*variable_smallsize=*/4>
1373         G(ElementChoices);
1374 
1375     G.generate([&](ArrayRef<int> Mask) -> bool {
1376       int GuessedReplicationFactor = -1, GuessedVF = -1;
1377       bool Match = ShuffleVectorInst::isReplicationMask(
1378           Mask, GuessedReplicationFactor, GuessedVF);
1379       if (!Match)
1380         return /*Abort=*/false;
1381 
1382       const auto ActualMask =
1383           createReplicatedMask(GuessedReplicationFactor, GuessedVF);
1384       EXPECT_EQ(Mask.size(), ActualMask.size());
1385       for (auto I : zip(Mask, ActualMask)) {
1386         int Elt = std::get<0>(I);
1387         int ActualElt = std::get<0>(I);
1388 
1389         if (Elt != -1) {
1390           EXPECT_EQ(Elt, ActualElt);
1391         }
1392       }
1393 
1394       return /*Abort=*/false;
1395     });
1396   }
1397 }
1398 
1399 TEST(InstructionsTest, GetSplat) {
1400   // Create the elements for various constant vectors.
1401   LLVMContext Ctx;
1402   Type *Int32Ty = Type::getInt32Ty(Ctx);
1403   Constant *CU = UndefValue::get(Int32Ty);
1404   Constant *CP = PoisonValue::get(Int32Ty);
1405   Constant *C0 = ConstantInt::get(Int32Ty, 0);
1406   Constant *C1 = ConstantInt::get(Int32Ty, 1);
1407 
1408   Constant *Splat0 = ConstantVector::get({C0, C0, C0, C0});
1409   Constant *Splat1 = ConstantVector::get({C1, C1, C1, C1 ,C1});
1410   Constant *Splat0Undef = ConstantVector::get({C0, CU, C0, CU});
1411   Constant *Splat1Undef = ConstantVector::get({CU, CU, C1, CU});
1412   Constant *NotSplat = ConstantVector::get({C1, C1, C0, C1 ,C1});
1413   Constant *NotSplatUndef = ConstantVector::get({CU, C1, CU, CU ,C0});
1414   Constant *Splat0Poison = ConstantVector::get({C0, CP, C0, CP});
1415   Constant *Splat1Poison = ConstantVector::get({CP, CP, C1, CP});
1416   Constant *NotSplatPoison = ConstantVector::get({CP, C1, CP, CP, C0});
1417 
1418   // Default - undef/poison is not allowed.
1419   EXPECT_EQ(Splat0->getSplatValue(), C0);
1420   EXPECT_EQ(Splat1->getSplatValue(), C1);
1421   EXPECT_EQ(Splat0Undef->getSplatValue(), nullptr);
1422   EXPECT_EQ(Splat1Undef->getSplatValue(), nullptr);
1423   EXPECT_EQ(Splat0Poison->getSplatValue(), nullptr);
1424   EXPECT_EQ(Splat1Poison->getSplatValue(), nullptr);
1425   EXPECT_EQ(NotSplat->getSplatValue(), nullptr);
1426   EXPECT_EQ(NotSplatUndef->getSplatValue(), nullptr);
1427   EXPECT_EQ(NotSplatPoison->getSplatValue(), nullptr);
1428 
1429   // Disallow poison explicitly.
1430   EXPECT_EQ(Splat0->getSplatValue(false), C0);
1431   EXPECT_EQ(Splat1->getSplatValue(false), C1);
1432   EXPECT_EQ(Splat0Undef->getSplatValue(false), nullptr);
1433   EXPECT_EQ(Splat1Undef->getSplatValue(false), nullptr);
1434   EXPECT_EQ(Splat0Poison->getSplatValue(false), nullptr);
1435   EXPECT_EQ(Splat1Poison->getSplatValue(false), nullptr);
1436   EXPECT_EQ(NotSplat->getSplatValue(false), nullptr);
1437   EXPECT_EQ(NotSplatUndef->getSplatValue(false), nullptr);
1438   EXPECT_EQ(NotSplatPoison->getSplatValue(false), nullptr);
1439 
1440   // Allow poison but not undef.
1441   EXPECT_EQ(Splat0->getSplatValue(true), C0);
1442   EXPECT_EQ(Splat1->getSplatValue(true), C1);
1443   EXPECT_EQ(Splat0Undef->getSplatValue(true), nullptr);
1444   EXPECT_EQ(Splat1Undef->getSplatValue(true), nullptr);
1445   EXPECT_EQ(Splat0Poison->getSplatValue(true), C0);
1446   EXPECT_EQ(Splat1Poison->getSplatValue(true), C1);
1447   EXPECT_EQ(NotSplat->getSplatValue(true), nullptr);
1448   EXPECT_EQ(NotSplatUndef->getSplatValue(true), nullptr);
1449   EXPECT_EQ(NotSplatPoison->getSplatValue(true), nullptr);
1450 }
1451 
1452 TEST(InstructionsTest, SkipDebug) {
1453   LLVMContext C;
1454   bool OldDbgValueMode = UseNewDbgInfoFormat;
1455   UseNewDbgInfoFormat = false;
1456   std::unique_ptr<Module> M = parseIR(C,
1457                                       R"(
1458       declare void @llvm.dbg.value(metadata, metadata, metadata)
1459 
1460       define void @f() {
1461       entry:
1462         call void @llvm.dbg.value(metadata i32 0, metadata !11, metadata !DIExpression()), !dbg !13
1463         ret void
1464       }
1465 
1466       !llvm.dbg.cu = !{!0}
1467       !llvm.module.flags = !{!3, !4}
1468       !0 = distinct !DICompileUnit(language: DW_LANG_C99, file: !1, producer: "clang version 6.0.0", isOptimized: false, runtimeVersion: 0, emissionKind: FullDebug, enums: !2)
1469       !1 = !DIFile(filename: "t2.c", directory: "foo")
1470       !2 = !{}
1471       !3 = !{i32 2, !"Dwarf Version", i32 4}
1472       !4 = !{i32 2, !"Debug Info Version", i32 3}
1473       !8 = distinct !DISubprogram(name: "f", scope: !1, file: !1, line: 1, type: !9, isLocal: false, isDefinition: true, scopeLine: 1, isOptimized: false, unit: !0, retainedNodes: !2)
1474       !9 = !DISubroutineType(types: !10)
1475       !10 = !{null}
1476       !11 = !DILocalVariable(name: "x", scope: !8, file: !1, line: 2, type: !12)
1477       !12 = !DIBasicType(name: "int", size: 32, encoding: DW_ATE_signed)
1478       !13 = !DILocation(line: 2, column: 7, scope: !8)
1479   )");
1480   ASSERT_TRUE(M);
1481   Function *F = cast<Function>(M->getNamedValue("f"));
1482   BasicBlock &BB = F->front();
1483 
1484   // The first non-debug instruction is the terminator.
1485   auto *Term = BB.getTerminator();
1486   EXPECT_EQ(Term, BB.begin()->getNextNonDebugInstruction());
1487   EXPECT_EQ(Term->getIterator(), skipDebugIntrinsics(BB.begin()));
1488 
1489   // After the terminator, there are no non-debug instructions.
1490   EXPECT_EQ(nullptr, Term->getNextNonDebugInstruction());
1491   UseNewDbgInfoFormat = OldDbgValueMode;
1492 }
1493 
1494 TEST(InstructionsTest, PhiMightNotBeFPMathOperator) {
1495   LLVMContext Context;
1496   IRBuilder<> Builder(Context);
1497   MDBuilder MDHelper(Context);
1498   Instruction *I = Builder.CreatePHI(Builder.getInt32Ty(), 0);
1499   EXPECT_FALSE(isa<FPMathOperator>(I));
1500   I->deleteValue();
1501   Instruction *FP = Builder.CreatePHI(Builder.getDoubleTy(), 0);
1502   EXPECT_TRUE(isa<FPMathOperator>(FP));
1503   FP->deleteValue();
1504 }
1505 
1506 TEST(InstructionsTest, FPCallIsFPMathOperator) {
1507   LLVMContext C;
1508 
1509   Type *ITy = Type::getInt32Ty(C);
1510   FunctionType *IFnTy = FunctionType::get(ITy, {});
1511   PointerType *PtrTy = PointerType::getUnqual(C);
1512   Value *ICallee = Constant::getNullValue(PtrTy);
1513   std::unique_ptr<CallInst> ICall(CallInst::Create(IFnTy, ICallee, {}, ""));
1514   EXPECT_FALSE(isa<FPMathOperator>(ICall));
1515 
1516   Type *VITy = FixedVectorType::get(ITy, 2);
1517   FunctionType *VIFnTy = FunctionType::get(VITy, {});
1518   Value *VICallee = Constant::getNullValue(PtrTy);
1519   std::unique_ptr<CallInst> VICall(CallInst::Create(VIFnTy, VICallee, {}, ""));
1520   EXPECT_FALSE(isa<FPMathOperator>(VICall));
1521 
1522   Type *AITy = ArrayType::get(ITy, 2);
1523   FunctionType *AIFnTy = FunctionType::get(AITy, {});
1524   Value *AICallee = Constant::getNullValue(PtrTy);
1525   std::unique_ptr<CallInst> AICall(CallInst::Create(AIFnTy, AICallee, {}, ""));
1526   EXPECT_FALSE(isa<FPMathOperator>(AICall));
1527 
1528   Type *FTy = Type::getFloatTy(C);
1529   FunctionType *FFnTy = FunctionType::get(FTy, {});
1530   Value *FCallee = Constant::getNullValue(PtrTy);
1531   std::unique_ptr<CallInst> FCall(CallInst::Create(FFnTy, FCallee, {}, ""));
1532   EXPECT_TRUE(isa<FPMathOperator>(FCall));
1533 
1534   Type *VFTy = FixedVectorType::get(FTy, 2);
1535   FunctionType *VFFnTy = FunctionType::get(VFTy, {});
1536   Value *VFCallee = Constant::getNullValue(PtrTy);
1537   std::unique_ptr<CallInst> VFCall(CallInst::Create(VFFnTy, VFCallee, {}, ""));
1538   EXPECT_TRUE(isa<FPMathOperator>(VFCall));
1539 
1540   Type *AFTy = ArrayType::get(FTy, 2);
1541   FunctionType *AFFnTy = FunctionType::get(AFTy, {});
1542   Value *AFCallee = Constant::getNullValue(PtrTy);
1543   std::unique_ptr<CallInst> AFCall(CallInst::Create(AFFnTy, AFCallee, {}, ""));
1544   EXPECT_TRUE(isa<FPMathOperator>(AFCall));
1545 
1546   Type *AVFTy = ArrayType::get(VFTy, 2);
1547   FunctionType *AVFFnTy = FunctionType::get(AVFTy, {});
1548   Value *AVFCallee = Constant::getNullValue(PtrTy);
1549   std::unique_ptr<CallInst> AVFCall(
1550       CallInst::Create(AVFFnTy, AVFCallee, {}, ""));
1551   EXPECT_TRUE(isa<FPMathOperator>(AVFCall));
1552 
1553   Type *StructITy = StructType::get(ITy, ITy);
1554   FunctionType *StructIFnTy = FunctionType::get(StructITy, {});
1555   Value *StructICallee = Constant::getNullValue(PtrTy);
1556   std::unique_ptr<CallInst> StructICall(
1557       CallInst::Create(StructIFnTy, StructICallee, {}, ""));
1558   EXPECT_FALSE(isa<FPMathOperator>(StructICall));
1559 
1560   Type *EmptyStructTy = StructType::get(C);
1561   FunctionType *EmptyStructFnTy = FunctionType::get(EmptyStructTy, {});
1562   Value *EmptyStructCallee = Constant::getNullValue(PtrTy);
1563   std::unique_ptr<CallInst> EmptyStructCall(
1564       CallInst::Create(EmptyStructFnTy, EmptyStructCallee, {}, ""));
1565   EXPECT_FALSE(isa<FPMathOperator>(EmptyStructCall));
1566 
1567   Type *NamedStructFTy = StructType::create({FTy, FTy}, "AStruct");
1568   FunctionType *NamedStructFFnTy = FunctionType::get(NamedStructFTy, {});
1569   Value *NamedStructFCallee = Constant::getNullValue(PtrTy);
1570   std::unique_ptr<CallInst> NamedStructFCall(
1571       CallInst::Create(NamedStructFFnTy, NamedStructFCallee, {}, ""));
1572   EXPECT_FALSE(isa<FPMathOperator>(NamedStructFCall));
1573 
1574   Type *MixedStructTy = StructType::get(FTy, ITy);
1575   FunctionType *MixedStructFnTy = FunctionType::get(MixedStructTy, {});
1576   Value *MixedStructCallee = Constant::getNullValue(PtrTy);
1577   std::unique_ptr<CallInst> MixedStructCall(
1578       CallInst::Create(MixedStructFnTy, MixedStructCallee, {}, ""));
1579   EXPECT_FALSE(isa<FPMathOperator>(MixedStructCall));
1580 
1581   Type *StructFTy = StructType::get(FTy, FTy, FTy);
1582   FunctionType *StructFFnTy = FunctionType::get(StructFTy, {});
1583   Value *StructFCallee = Constant::getNullValue(PtrTy);
1584   std::unique_ptr<CallInst> StructFCall(
1585       CallInst::Create(StructFFnTy, StructFCallee, {}, ""));
1586   EXPECT_TRUE(isa<FPMathOperator>(StructFCall));
1587 
1588   Type *StructVFTy = StructType::get(VFTy, VFTy, VFTy, VFTy);
1589   FunctionType *StructVFFnTy = FunctionType::get(StructVFTy, {});
1590   Value *StructVFCallee = Constant::getNullValue(PtrTy);
1591   std::unique_ptr<CallInst> StructVFCall(
1592       CallInst::Create(StructVFFnTy, StructVFCallee, {}, ""));
1593   EXPECT_TRUE(isa<FPMathOperator>(StructVFCall));
1594 
1595   Type *NestedStructFTy = StructType::get(StructFTy, StructFTy, StructFTy);
1596   FunctionType *NestedStructFFnTy = FunctionType::get(NestedStructFTy, {});
1597   Value *NestedStructFCallee = Constant::getNullValue(PtrTy);
1598   std::unique_ptr<CallInst> NestedStructFCall(
1599       CallInst::Create(NestedStructFFnTy, NestedStructFCallee, {}, ""));
1600   EXPECT_FALSE(isa<FPMathOperator>(NestedStructFCall));
1601 
1602   Type *AStructFTy = ArrayType::get(StructFTy, 5);
1603   FunctionType *AStructFFnTy = FunctionType::get(AStructFTy, {});
1604   Value *AStructFCallee = Constant::getNullValue(PtrTy);
1605   std::unique_ptr<CallInst> AStructFCall(
1606       CallInst::Create(AStructFFnTy, AStructFCallee, {}, ""));
1607   EXPECT_FALSE(isa<FPMathOperator>(AStructFCall));
1608 }
1609 
1610 TEST(InstructionsTest, FNegInstruction) {
1611   LLVMContext Context;
1612   Type *FltTy = Type::getFloatTy(Context);
1613   Constant *One = ConstantFP::get(FltTy, 1.0);
1614   BinaryOperator *FAdd = BinaryOperator::CreateFAdd(One, One);
1615   FAdd->setHasNoNaNs(true);
1616   UnaryOperator *FNeg = UnaryOperator::CreateFNegFMF(One, FAdd);
1617   EXPECT_TRUE(FNeg->hasNoNaNs());
1618   EXPECT_FALSE(FNeg->hasNoInfs());
1619   EXPECT_FALSE(FNeg->hasNoSignedZeros());
1620   EXPECT_FALSE(FNeg->hasAllowReciprocal());
1621   EXPECT_FALSE(FNeg->hasAllowContract());
1622   EXPECT_FALSE(FNeg->hasAllowReassoc());
1623   EXPECT_FALSE(FNeg->hasApproxFunc());
1624   FAdd->deleteValue();
1625   FNeg->deleteValue();
1626 }
1627 
1628 TEST(InstructionsTest, CallBrInstruction) {
1629   LLVMContext Context;
1630   std::unique_ptr<Module> M = parseIR(Context, R"(
1631 define void @foo() {
1632 entry:
1633   callbr void asm sideeffect "// XXX: ${0:l}", "!i"()
1634           to label %land.rhs.i [label %branch_test.exit]
1635 
1636 land.rhs.i:
1637   br label %branch_test.exit
1638 
1639 branch_test.exit:
1640   %0 = phi i1 [ true, %entry ], [ false, %land.rhs.i ]
1641   br i1 %0, label %if.end, label %if.then
1642 
1643 if.then:
1644   ret void
1645 
1646 if.end:
1647   ret void
1648 }
1649 )");
1650   Function *Foo = M->getFunction("foo");
1651   auto BBs = Foo->begin();
1652   CallBrInst &CBI = cast<CallBrInst>(BBs->front());
1653   ++BBs;
1654   ++BBs;
1655   BasicBlock &BranchTestExit = *BBs;
1656   ++BBs;
1657   BasicBlock &IfThen = *BBs;
1658 
1659   // Test that setting the first indirect destination of callbr updates the dest
1660   EXPECT_EQ(&BranchTestExit, CBI.getIndirectDest(0));
1661   CBI.setIndirectDest(0, &IfThen);
1662   EXPECT_EQ(&IfThen, CBI.getIndirectDest(0));
1663 }
1664 
1665 TEST(InstructionsTest, UnaryOperator) {
1666   LLVMContext Context;
1667   IRBuilder<> Builder(Context);
1668   Instruction *I = Builder.CreatePHI(Builder.getDoubleTy(), 0);
1669   Value *F = Builder.CreateFNeg(I);
1670 
1671   EXPECT_TRUE(isa<Value>(F));
1672   EXPECT_TRUE(isa<Instruction>(F));
1673   EXPECT_TRUE(isa<UnaryInstruction>(F));
1674   EXPECT_TRUE(isa<UnaryOperator>(F));
1675   EXPECT_FALSE(isa<BinaryOperator>(F));
1676 
1677   F->deleteValue();
1678   I->deleteValue();
1679 }
1680 
1681 TEST(InstructionsTest, DropLocation) {
1682   LLVMContext C;
1683   std::unique_ptr<Module> M = parseIR(C,
1684                                       R"(
1685       declare void @callee()
1686 
1687       define void @no_parent_scope() {
1688         call void @callee()           ; I1: Call with no location.
1689         call void @callee(), !dbg !11 ; I2: Call with location.
1690         ret void, !dbg !11            ; I3: Non-call with location.
1691       }
1692 
1693       define void @with_parent_scope() !dbg !8 {
1694         call void @callee()           ; I1: Call with no location.
1695         call void @callee(), !dbg !11 ; I2: Call with location.
1696         ret void, !dbg !11            ; I3: Non-call with location.
1697       }
1698 
1699       !llvm.dbg.cu = !{!0}
1700       !llvm.module.flags = !{!3, !4}
1701       !0 = distinct !DICompileUnit(language: DW_LANG_C99, file: !1, producer: "", isOptimized: false, runtimeVersion: 0, emissionKind: FullDebug, enums: !2)
1702       !1 = !DIFile(filename: "t2.c", directory: "foo")
1703       !2 = !{}
1704       !3 = !{i32 2, !"Dwarf Version", i32 4}
1705       !4 = !{i32 2, !"Debug Info Version", i32 3}
1706       !8 = distinct !DISubprogram(name: "f", scope: !1, file: !1, line: 1, type: !9, isLocal: false, isDefinition: true, scopeLine: 1, isOptimized: false, unit: !0, retainedNodes: !2)
1707       !9 = !DISubroutineType(types: !10)
1708       !10 = !{null}
1709       !11 = !DILocation(line: 2, column: 7, scope: !8, inlinedAt: !12)
1710       !12 = !DILocation(line: 3, column: 8, scope: !8)
1711   )");
1712   ASSERT_TRUE(M);
1713 
1714   {
1715     Function *NoParentScopeF =
1716         cast<Function>(M->getNamedValue("no_parent_scope"));
1717     BasicBlock &BB = NoParentScopeF->front();
1718 
1719     auto *I1 = &*BB.getFirstNonPHIIt();
1720     auto *I2 = I1->getNextNode();
1721     auto *I3 = BB.getTerminator();
1722 
1723     EXPECT_EQ(I1->getDebugLoc(), DebugLoc());
1724     I1->dropLocation();
1725     EXPECT_EQ(I1->getDebugLoc(), DebugLoc());
1726 
1727     EXPECT_EQ(I2->getDebugLoc().getLine(), 2U);
1728     I2->dropLocation();
1729     EXPECT_EQ(I1->getDebugLoc(), DebugLoc());
1730 
1731     EXPECT_EQ(I3->getDebugLoc().getLine(), 2U);
1732     I3->dropLocation();
1733     EXPECT_EQ(I3->getDebugLoc(), DebugLoc());
1734   }
1735 
1736   {
1737     Function *WithParentScopeF =
1738         cast<Function>(M->getNamedValue("with_parent_scope"));
1739     BasicBlock &BB = WithParentScopeF->front();
1740 
1741     auto *I2 = BB.getFirstNonPHIIt()->getNextNode();
1742 
1743     MDNode *Scope = cast<MDNode>(WithParentScopeF->getSubprogram());
1744     EXPECT_EQ(I2->getDebugLoc().getLine(), 2U);
1745     I2->dropLocation();
1746     EXPECT_EQ(I2->getDebugLoc().getLine(), 0U);
1747     EXPECT_EQ(I2->getDebugLoc().getScope(), Scope);
1748     EXPECT_EQ(I2->getDebugLoc().getInlinedAt(), nullptr);
1749   }
1750 }
1751 
1752 TEST(InstructionsTest, BranchWeightOverflow) {
1753   LLVMContext C;
1754   std::unique_ptr<Module> M = parseIR(C,
1755                                       R"(
1756       declare void @callee()
1757 
1758       define void @caller() {
1759         call void @callee(), !prof !1
1760         ret void
1761       }
1762 
1763       !1 = !{!"branch_weights", i32 20000}
1764   )");
1765   ASSERT_TRUE(M);
1766   CallInst *CI =
1767       cast<CallInst>(&M->getFunction("caller")->getEntryBlock().front());
1768   uint64_t ProfWeight;
1769   CI->extractProfTotalWeight(ProfWeight);
1770   ASSERT_EQ(ProfWeight, 20000U);
1771   CI->updateProfWeight(10000000, 1);
1772   CI->extractProfTotalWeight(ProfWeight);
1773   ASSERT_EQ(ProfWeight, UINT32_MAX);
1774 }
1775 
1776 TEST(InstructionsTest, FreezeInst) {
1777   LLVMContext C;
1778   std::unique_ptr<Module> M = parseIR(C,
1779                                       R"(
1780       define void @foo(i8 %arg) {
1781         freeze i8 %arg
1782         ret void
1783   }
1784   )");
1785   ASSERT_TRUE(M);
1786   Value *FI = &M->getFunction("foo")->getEntryBlock().front();
1787   EXPECT_TRUE(isa<UnaryInstruction>(FI));
1788 }
1789 
1790 TEST(InstructionsTest, AllocaInst) {
1791   LLVMContext Ctx;
1792   std::unique_ptr<Module> M = parseIR(Ctx, R"(
1793       %T = type { i64, [3 x i32]}
1794       define void @f(i32 %n) {
1795       entry:
1796         %A = alloca i32, i32 1
1797         %B = alloca i32, i32 4
1798         %C = alloca i32, i32 %n
1799         %D = alloca double
1800         %E = alloca <vscale x 8 x double>
1801         %F = alloca [2 x half]
1802         %G = alloca [2 x [3 x i128]]
1803         %H = alloca %T
1804         %I = alloca i32, i64 9223372036854775807
1805         ret void
1806       }
1807     )");
1808   const DataLayout &DL = M->getDataLayout();
1809   ASSERT_TRUE(M);
1810   Function *Fun = cast<Function>(M->getNamedValue("f"));
1811   BasicBlock &BB = Fun->front();
1812   auto It = BB.begin();
1813   AllocaInst &A = cast<AllocaInst>(*It++);
1814   AllocaInst &B = cast<AllocaInst>(*It++);
1815   AllocaInst &C = cast<AllocaInst>(*It++);
1816   AllocaInst &D = cast<AllocaInst>(*It++);
1817   AllocaInst &E = cast<AllocaInst>(*It++);
1818   AllocaInst &F = cast<AllocaInst>(*It++);
1819   AllocaInst &G = cast<AllocaInst>(*It++);
1820   AllocaInst &H = cast<AllocaInst>(*It++);
1821   AllocaInst &I = cast<AllocaInst>(*It++);
1822   EXPECT_EQ(A.getAllocationSizeInBits(DL), TypeSize::getFixed(32));
1823   EXPECT_EQ(B.getAllocationSizeInBits(DL), TypeSize::getFixed(128));
1824   EXPECT_FALSE(C.getAllocationSizeInBits(DL));
1825   EXPECT_EQ(DL.getTypeSizeInBits(D.getAllocatedType()), TypeSize::getFixed(64));
1826   EXPECT_EQ(D.getAllocationSizeInBits(DL), TypeSize::getFixed(64));
1827   EXPECT_EQ(E.getAllocationSizeInBits(DL), TypeSize::getScalable(512));
1828   EXPECT_EQ(F.getAllocationSizeInBits(DL), TypeSize::getFixed(32));
1829   EXPECT_EQ(G.getAllocationSizeInBits(DL), TypeSize::getFixed(768));
1830   EXPECT_EQ(H.getAllocationSizeInBits(DL), TypeSize::getFixed(160));
1831   EXPECT_FALSE(I.getAllocationSizeInBits(DL));
1832 }
1833 
1834 TEST(InstructionsTest, InsertAtBegin) {
1835   LLVMContext Ctx;
1836   std::unique_ptr<Module> M = parseIR(Ctx, R"(
1837     define void @f(i32 %a, i32 %b) {
1838      entry:
1839        ret void
1840     }
1841 )");
1842   Function *F = &*M->begin();
1843   Argument *ArgA = F->getArg(0);
1844   Argument *ArgB = F->getArg(1);
1845   BasicBlock *BB = &*F->begin();
1846   Instruction *Ret = &*BB->begin();
1847   Instruction *I = BinaryOperator::CreateAdd(ArgA, ArgB);
1848   auto It = I->insertInto(BB, BB->begin());
1849   EXPECT_EQ(&*It, I);
1850   EXPECT_EQ(I->getNextNode(), Ret);
1851 }
1852 
1853 TEST(InstructionsTest, InsertAtEnd) {
1854   LLVMContext Ctx;
1855   std::unique_ptr<Module> M = parseIR(Ctx, R"(
1856     define void @f(i32 %a, i32 %b) {
1857      entry:
1858        ret void
1859     }
1860 )");
1861   Function *F = &*M->begin();
1862   Argument *ArgA = F->getArg(0);
1863   Argument *ArgB = F->getArg(1);
1864   BasicBlock *BB = &*F->begin();
1865   Instruction *Ret = &*BB->begin();
1866   Instruction *I = BinaryOperator::CreateAdd(ArgA, ArgB);
1867   auto It = I->insertInto(BB, BB->end());
1868   EXPECT_EQ(&*It, I);
1869   EXPECT_EQ(Ret->getNextNode(), I);
1870 }
1871 
1872 TEST(InstructionsTest, AtomicSyncscope) {
1873   LLVMContext Ctx;
1874 
1875   Module M("Mod", Ctx);
1876   FunctionType *FT = FunctionType::get(Type::getVoidTy(Ctx), {}, false);
1877   Function *F = Function::Create(FT, Function::ExternalLinkage, "Fun", M);
1878   BasicBlock *BB = BasicBlock::Create(Ctx, "Entry", F);
1879   IRBuilder<> Builder(BB);
1880 
1881   // SyncScope-variants of LLVM C IRBuilder APIs are tested by llvm-c-test,
1882   // so cover the old versions (with a SingleThreaded argument) here.
1883   Value *Ptr = ConstantPointerNull::get(Builder.getPtrTy());
1884   Value *Val = ConstantInt::get(Type::getInt32Ty(Ctx), 0);
1885 
1886   // fence
1887   LLVMValueRef Fence = LLVMBuildFence(
1888       wrap(&Builder), LLVMAtomicOrderingSequentiallyConsistent, 0, "");
1889   EXPECT_FALSE(LLVMIsAtomicSingleThread(Fence));
1890   Fence = LLVMBuildFence(wrap(&Builder),
1891                          LLVMAtomicOrderingSequentiallyConsistent, 1, "");
1892   EXPECT_TRUE(LLVMIsAtomicSingleThread(Fence));
1893 
1894   // atomicrmw
1895   LLVMValueRef AtomicRMW = LLVMBuildAtomicRMW(
1896       wrap(&Builder), LLVMAtomicRMWBinOpXchg, wrap(Ptr), wrap(Val),
1897       LLVMAtomicOrderingSequentiallyConsistent, 0);
1898   EXPECT_FALSE(LLVMIsAtomicSingleThread(AtomicRMW));
1899   AtomicRMW = LLVMBuildAtomicRMW(wrap(&Builder), LLVMAtomicRMWBinOpXchg,
1900                                  wrap(Ptr), wrap(Val),
1901                                  LLVMAtomicOrderingSequentiallyConsistent, 1);
1902   EXPECT_TRUE(LLVMIsAtomicSingleThread(AtomicRMW));
1903 
1904   // cmpxchg
1905   LLVMValueRef CmpXchg =
1906       LLVMBuildAtomicCmpXchg(wrap(&Builder), wrap(Ptr), wrap(Val), wrap(Val),
1907                              LLVMAtomicOrderingSequentiallyConsistent,
1908                              LLVMAtomicOrderingSequentiallyConsistent, 0);
1909   EXPECT_FALSE(LLVMIsAtomicSingleThread(CmpXchg));
1910   CmpXchg =
1911       LLVMBuildAtomicCmpXchg(wrap(&Builder), wrap(Ptr), wrap(Val), wrap(Val),
1912                              LLVMAtomicOrderingSequentiallyConsistent,
1913                              LLVMAtomicOrderingSequentiallyConsistent, 1);
1914   EXPECT_TRUE(LLVMIsAtomicSingleThread(CmpXchg));
1915 }
1916 
1917 TEST(InstructionsTest, CmpPredicate) {
1918   CmpPredicate P0(CmpInst::ICMP_ULE, false), P1(CmpInst::ICMP_ULE, true),
1919       P2(CmpInst::ICMP_SLE, false), P3(CmpInst::ICMP_SLT, false);
1920   CmpPredicate Q0 = P0, Q1 = P1, Q2 = P2;
1921   CmpInst::Predicate R0 = P0, R1 = P1, R2 = P2;
1922 
1923   EXPECT_EQ(*CmpPredicate::getMatching(P0, P1), CmpInst::ICMP_ULE);
1924   EXPECT_EQ(CmpPredicate::getMatching(P0, P1)->hasSameSign(), false);
1925   EXPECT_EQ(*CmpPredicate::getMatching(P1, P1), CmpInst::ICMP_ULE);
1926   EXPECT_EQ(CmpPredicate::getMatching(P1, P1)->hasSameSign(), true);
1927   EXPECT_EQ(CmpPredicate::getMatching(P0, P2), std::nullopt);
1928   EXPECT_EQ(*CmpPredicate::getMatching(P1, P2), CmpInst::ICMP_SLE);
1929   EXPECT_EQ(CmpPredicate::getMatching(P1, P2)->hasSameSign(), false);
1930   EXPECT_EQ(CmpPredicate::getMatching(P1, P3), std::nullopt);
1931   EXPECT_EQ(CmpPredicate::getMatching(P1, CmpInst::FCMP_ULE), std::nullopt);
1932   EXPECT_FALSE(Q0.hasSameSign());
1933   EXPECT_TRUE(Q1.hasSameSign());
1934   EXPECT_FALSE(Q2.hasSameSign());
1935   EXPECT_EQ(P0, R0);
1936   EXPECT_EQ(P1, R1);
1937   EXPECT_EQ(P2, R2);
1938 }
1939 
1940 } // end anonymous namespace
1941 } // end namespace llvm
1942