Debian Codegraph @

llvm/unittests/IR/InstructionsTest.cpp

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