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