1 //===- InstCombineCalls.cpp -----------------------------------------------===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 // 9 // This file implements the visitCall, visitInvoke, and visitCallBr functions. 10 // 11 //===----------------------------------------------------------------------===// 12 13 #include "InstCombineInternal.h" 14 #include "llvm/ADT/APFloat.h" 15 #include "llvm/ADT/APInt.h" 16 #include "llvm/ADT/ArrayRef.h" 17 #include "llvm/ADT/None.h" 18 #include "llvm/ADT/Optional.h" 19 #include "llvm/ADT/STLExtras.h" 20 #include "llvm/ADT/SmallVector.h" 21 #include "llvm/ADT/Statistic.h" 22 #include "llvm/ADT/Twine.h" 23 #include "llvm/Analysis/AssumptionCache.h" 24 #include "llvm/Analysis/InstructionSimplify.h" 25 #include "llvm/Analysis/Loads.h" 26 #include "llvm/Analysis/MemoryBuiltins.h" 27 #include "llvm/Analysis/ValueTracking.h" 28 #include "llvm/Analysis/VectorUtils.h" 29 #include "llvm/IR/Attributes.h" 30 #include "llvm/IR/BasicBlock.h" 31 #include "llvm/IR/Constant.h" 32 #include "llvm/IR/Constants.h" 33 #include "llvm/IR/DataLayout.h" 34 #include "llvm/IR/DerivedTypes.h" 35 #include "llvm/IR/Function.h" 36 #include "llvm/IR/GlobalVariable.h" 37 #include "llvm/IR/InstrTypes.h" 38 #include "llvm/IR/Instruction.h" 39 #include "llvm/IR/Instructions.h" 40 #include "llvm/IR/IntrinsicInst.h" 41 #include "llvm/IR/Intrinsics.h" 42 #include "llvm/IR/LLVMContext.h" 43 #include "llvm/IR/Metadata.h" 44 #include "llvm/IR/PatternMatch.h" 45 #include "llvm/IR/Statepoint.h" 46 #include "llvm/IR/Type.h" 47 #include "llvm/IR/User.h" 48 #include "llvm/IR/Value.h" 49 #include "llvm/IR/ValueHandle.h" 50 #include "llvm/Support/AtomicOrdering.h" 51 #include "llvm/Support/Casting.h" 52 #include "llvm/Support/CommandLine.h" 53 #include "llvm/Support/Compiler.h" 54 #include "llvm/Support/Debug.h" 55 #include "llvm/Support/ErrorHandling.h" 56 #include "llvm/Support/KnownBits.h" 57 #include "llvm/Support/MathExtras.h" 58 #include "llvm/Support/raw_ostream.h" 59 #include "llvm/Transforms/InstCombine/InstCombineWorklist.h" 60 #include "llvm/Transforms/Utils/Local.h" 61 #include "llvm/Transforms/Utils/SimplifyLibCalls.h" 62 #include <algorithm> 63 #include <cassert> 64 #include <cstdint> 65 #include <cstring> 66 #include <utility> 67 #include <vector> 68 69 using namespace llvm; 70 using namespace PatternMatch; 71 72 #define DEBUG_TYPE "instcombine" 73 74 STATISTIC(NumSimplified, "Number of library calls simplified"); 75 76 static cl::opt<unsigned> GuardWideningWindow( 77 "instcombine-guard-widening-window", 78 cl::init(3), 79 cl::desc("How wide an instruction window to bypass looking for " 80 "another guard")); 81 82 /// Return the specified type promoted as it would be to pass though a va_arg 83 /// area. 84 static Type *getPromotedType(Type *Ty) { 85 if (IntegerType* ITy = dyn_cast<IntegerType>(Ty)) { 86 if (ITy->getBitWidth() < 32) 87 return Type::getInt32Ty(Ty->getContext()); 88 } 89 return Ty; 90 } 91 92 /// Return a constant boolean vector that has true elements in all positions 93 /// where the input constant data vector has an element with the sign bit set. 94 static Constant *getNegativeIsTrueBoolVec(ConstantDataVector *V) { 95 SmallVector<Constant *, 32> BoolVec; 96 IntegerType *BoolTy = Type::getInt1Ty(V->getContext()); 97 for (unsigned I = 0, E = V->getNumElements(); I != E; ++I) { 98 Constant *Elt = V->getElementAsConstant(I); 99 assert((isa<ConstantInt>(Elt) || isa<ConstantFP>(Elt)) && 100 "Unexpected constant data vector element type"); 101 bool Sign = V->getElementType()->isIntegerTy() 102 ? cast<ConstantInt>(Elt)->isNegative() 103 : cast<ConstantFP>(Elt)->isNegative(); 104 BoolVec.push_back(ConstantInt::get(BoolTy, Sign)); 105 } 106 return ConstantVector::get(BoolVec); 107 } 108 109 Instruction *InstCombiner::SimplifyAnyMemTransfer(AnyMemTransferInst *MI) { 110 unsigned DstAlign = getKnownAlignment(MI->getRawDest(), DL, MI, &AC, &DT); 111 unsigned CopyDstAlign = MI->getDestAlignment(); 112 if (CopyDstAlign < DstAlign){ 113 MI->setDestAlignment(DstAlign); 114 return MI; 115 } 116 117 unsigned SrcAlign = getKnownAlignment(MI->getRawSource(), DL, MI, &AC, &DT); 118 unsigned CopySrcAlign = MI->getSourceAlignment(); 119 if (CopySrcAlign < SrcAlign) { 120 MI->setSourceAlignment(SrcAlign); 121 return MI; 122 } 123 124 // If we have a store to a location which is known constant, we can conclude 125 // that the store must be storing the constant value (else the memory 126 // wouldn't be constant), and this must be a noop. 127 if (AA->pointsToConstantMemory(MI->getDest())) { 128 // Set the size of the copy to 0, it will be deleted on the next iteration. 129 MI->setLength(Constant::getNullValue(MI->getLength()->getType())); 130 return MI; 131 } 132 133 // If MemCpyInst length is 1/2/4/8 bytes then replace memcpy with 134 // load/store. 135 ConstantInt *MemOpLength = dyn_cast<ConstantInt>(MI->getLength()); 136 if (!MemOpLength) return nullptr; 137 138 // Source and destination pointer types are always "i8*" for intrinsic. See 139 // if the size is something we can handle with a single primitive load/store. 140 // A single load+store correctly handles overlapping memory in the memmove 141 // case. 142 uint64_t Size = MemOpLength->getLimitedValue(); 143 assert(Size && "0-sized memory transferring should be removed already."); 144 145 if (Size > 8 || (Size&(Size-1))) 146 return nullptr; // If not 1/2/4/8 bytes, exit. 147 148 // If it is an atomic and alignment is less than the size then we will 149 // introduce the unaligned memory access which will be later transformed 150 // into libcall in CodeGen. This is not evident performance gain so disable 151 // it now. 152 if (isa<AtomicMemTransferInst>(MI)) 153 if (CopyDstAlign < Size || CopySrcAlign < Size) 154 return nullptr; 155 156 // Use an integer load+store unless we can find something better. 157 unsigned SrcAddrSp = 158 cast<PointerType>(MI->getArgOperand(1)->getType())->getAddressSpace(); 159 unsigned DstAddrSp = 160 cast<PointerType>(MI->getArgOperand(0)->getType())->getAddressSpace(); 161 162 IntegerType* IntType = IntegerType::get(MI->getContext(), Size<<3); 163 Type *NewSrcPtrTy = PointerType::get(IntType, SrcAddrSp); 164 Type *NewDstPtrTy = PointerType::get(IntType, DstAddrSp); 165 166 // If the memcpy has metadata describing the members, see if we can get the 167 // TBAA tag describing our copy. 168 MDNode *CopyMD = nullptr; 169 if (MDNode *M = MI->getMetadata(LLVMContext::MD_tbaa)) { 170 CopyMD = M; 171 } else if (MDNode *M = MI->getMetadata(LLVMContext::MD_tbaa_struct)) { 172 if (M->getNumOperands() == 3 && M->getOperand(0) && 173 mdconst::hasa<ConstantInt>(M->getOperand(0)) && 174 mdconst::extract<ConstantInt>(M->getOperand(0))->isZero() && 175 M->getOperand(1) && 176 mdconst::hasa<ConstantInt>(M->getOperand(1)) && 177 mdconst::extract<ConstantInt>(M->getOperand(1))->getValue() == 178 Size && 179 M->getOperand(2) && isa<MDNode>(M->getOperand(2))) 180 CopyMD = cast<MDNode>(M->getOperand(2)); 181 } 182 183 Value *Src = Builder.CreateBitCast(MI->getArgOperand(1), NewSrcPtrTy); 184 Value *Dest = Builder.CreateBitCast(MI->getArgOperand(0), NewDstPtrTy); 185 LoadInst *L = Builder.CreateLoad(IntType, Src); 186 // Alignment from the mem intrinsic will be better, so use it. 187 L->setAlignment(CopySrcAlign); 188 if (CopyMD) 189 L->setMetadata(LLVMContext::MD_tbaa, CopyMD); 190 MDNode *LoopMemParallelMD = 191 MI->getMetadata(LLVMContext::MD_mem_parallel_loop_access); 192 if (LoopMemParallelMD) 193 L->setMetadata(LLVMContext::MD_mem_parallel_loop_access, LoopMemParallelMD); 194 MDNode *AccessGroupMD = MI->getMetadata(LLVMContext::MD_access_group); 195 if (AccessGroupMD) 196 L->setMetadata(LLVMContext::MD_access_group, AccessGroupMD); 197 198 StoreInst *S = Builder.CreateStore(L, Dest); 199 // Alignment from the mem intrinsic will be better, so use it. 200 S->setAlignment(CopyDstAlign); 201 if (CopyMD) 202 S->setMetadata(LLVMContext::MD_tbaa, CopyMD); 203 if (LoopMemParallelMD) 204 S->setMetadata(LLVMContext::MD_mem_parallel_loop_access, LoopMemParallelMD); 205 if (AccessGroupMD) 206 S->setMetadata(LLVMContext::MD_access_group, AccessGroupMD); 207 208 if (auto *MT = dyn_cast<MemTransferInst>(MI)) { 209 // non-atomics can be volatile 210 L->setVolatile(MT->isVolatile()); 211 S->setVolatile(MT->isVolatile()); 212 } 213 if (isa<AtomicMemTransferInst>(MI)) { 214 // atomics have to be unordered 215 L->setOrdering(AtomicOrdering::Unordered); 216 S->setOrdering(AtomicOrdering::Unordered); 217 } 218 219 // Set the size of the copy to 0, it will be deleted on the next iteration. 220 MI->setLength(Constant::getNullValue(MemOpLength->getType())); 221 return MI; 222 } 223 224 Instruction *InstCombiner::SimplifyAnyMemSet(AnyMemSetInst *MI) { 225 unsigned Alignment = getKnownAlignment(MI->getDest(), DL, MI, &AC, &DT); 226 if (MI->getDestAlignment() < Alignment) { 227 MI->setDestAlignment(Alignment); 228 return MI; 229 } 230 231 // If we have a store to a location which is known constant, we can conclude 232 // that the store must be storing the constant value (else the memory 233 // wouldn't be constant), and this must be a noop. 234 if (AA->pointsToConstantMemory(MI->getDest())) { 235 // Set the size of the copy to 0, it will be deleted on the next iteration. 236 MI->setLength(Constant::getNullValue(MI->getLength()->getType())); 237 return MI; 238 } 239 240 // Extract the length and alignment and fill if they are constant. 241 ConstantInt *LenC = dyn_cast<ConstantInt>(MI->getLength()); 242 ConstantInt *FillC = dyn_cast<ConstantInt>(MI->getValue()); 243 if (!LenC || !FillC || !FillC->getType()->isIntegerTy(8)) 244 return nullptr; 245 uint64_t Len = LenC->getLimitedValue(); 246 Alignment = MI->getDestAlignment(); 247 assert(Len && "0-sized memory setting should be removed already."); 248 249 // Alignment 0 is identity for alignment 1 for memset, but not store. 250 if (Alignment == 0) 251 Alignment = 1; 252 253 // If it is an atomic and alignment is less than the size then we will 254 // introduce the unaligned memory access which will be later transformed 255 // into libcall in CodeGen. This is not evident performance gain so disable 256 // it now. 257 if (isa<AtomicMemSetInst>(MI)) 258 if (Alignment < Len) 259 return nullptr; 260 261 // memset(s,c,n) -> store s, c (for n=1,2,4,8) 262 if (Len <= 8 && isPowerOf2_32((uint32_t)Len)) { 263 Type *ITy = IntegerType::get(MI->getContext(), Len*8); // n=1 -> i8. 264 265 Value *Dest = MI->getDest(); 266 unsigned DstAddrSp = cast<PointerType>(Dest->getType())->getAddressSpace(); 267 Type *NewDstPtrTy = PointerType::get(ITy, DstAddrSp); 268 Dest = Builder.CreateBitCast(Dest, NewDstPtrTy); 269 270 // Extract the fill value and store. 271 uint64_t Fill = FillC->getZExtValue()*0x0101010101010101ULL; 272 StoreInst *S = Builder.CreateStore(ConstantInt::get(ITy, Fill), Dest, 273 MI->isVolatile()); 274 S->setAlignment(Alignment); 275 if (isa<AtomicMemSetInst>(MI)) 276 S->setOrdering(AtomicOrdering::Unordered); 277 278 // Set the size of the copy to 0, it will be deleted on the next iteration. 279 MI->setLength(Constant::getNullValue(LenC->getType())); 280 return MI; 281 } 282 283 return nullptr; 284 } 285 286 static Value *simplifyX86immShift(const IntrinsicInst &II, 287 InstCombiner::BuilderTy &Builder) { 288 bool LogicalShift = false; 289 bool ShiftLeft = false; 290 291 switch (II.getIntrinsicID()) { 292 default: llvm_unreachable("Unexpected intrinsic!"); 293 case Intrinsic::x86_sse2_psra_d: 294 case Intrinsic::x86_sse2_psra_w: 295 case Intrinsic::x86_sse2_psrai_d: 296 case Intrinsic::x86_sse2_psrai_w: 297 case Intrinsic::x86_avx2_psra_d: 298 case Intrinsic::x86_avx2_psra_w: 299 case Intrinsic::x86_avx2_psrai_d: 300 case Intrinsic::x86_avx2_psrai_w: 301 case Intrinsic::x86_avx512_psra_q_128: 302 case Intrinsic::x86_avx512_psrai_q_128: 303 case Intrinsic::x86_avx512_psra_q_256: 304 case Intrinsic::x86_avx512_psrai_q_256: 305 case Intrinsic::x86_avx512_psra_d_512: 306 case Intrinsic::x86_avx512_psra_q_512: 307 case Intrinsic::x86_avx512_psra_w_512: 308 case Intrinsic::x86_avx512_psrai_d_512: 309 case Intrinsic::x86_avx512_psrai_q_512: 310 case Intrinsic::x86_avx512_psrai_w_512: 311 LogicalShift = false; ShiftLeft = false; 312 break; 313 case Intrinsic::x86_sse2_psrl_d: 314 case Intrinsic::x86_sse2_psrl_q: 315 case Intrinsic::x86_sse2_psrl_w: 316 case Intrinsic::x86_sse2_psrli_d: 317 case Intrinsic::x86_sse2_psrli_q: 318 case Intrinsic::x86_sse2_psrli_w: 319 case Intrinsic::x86_avx2_psrl_d: 320 case Intrinsic::x86_avx2_psrl_q: 321 case Intrinsic::x86_avx2_psrl_w: 322 case Intrinsic::x86_avx2_psrli_d: 323 case Intrinsic::x86_avx2_psrli_q: 324 case Intrinsic::x86_avx2_psrli_w: 325 case Intrinsic::x86_avx512_psrl_d_512: 326 case Intrinsic::x86_avx512_psrl_q_512: 327 case Intrinsic::x86_avx512_psrl_w_512: 328 case Intrinsic::x86_avx512_psrli_d_512: 329 case Intrinsic::x86_avx512_psrli_q_512: 330 case Intrinsic::x86_avx512_psrli_w_512: 331 LogicalShift = true; ShiftLeft = false; 332 break; 333 case Intrinsic::x86_sse2_psll_d: 334 case Intrinsic::x86_sse2_psll_q: 335 case Intrinsic::x86_sse2_psll_w: 336 case Intrinsic::x86_sse2_pslli_d: 337 case Intrinsic::x86_sse2_pslli_q: 338 case Intrinsic::x86_sse2_pslli_w: 339 case Intrinsic::x86_avx2_psll_d: 340 case Intrinsic::x86_avx2_psll_q: 341 case Intrinsic::x86_avx2_psll_w: 342 case Intrinsic::x86_avx2_pslli_d: 343 case Intrinsic::x86_avx2_pslli_q: 344 case Intrinsic::x86_avx2_pslli_w: 345 case Intrinsic::x86_avx512_psll_d_512: 346 case Intrinsic::x86_avx512_psll_q_512: 347 case Intrinsic::x86_avx512_psll_w_512: 348 case Intrinsic::x86_avx512_pslli_d_512: 349 case Intrinsic::x86_avx512_pslli_q_512: 350 case Intrinsic::x86_avx512_pslli_w_512: 351 LogicalShift = true; ShiftLeft = true; 352 break; 353 } 354 assert((LogicalShift || !ShiftLeft) && "Only logical shifts can shift left"); 355 356 // Simplify if count is constant. 357 auto Arg1 = II.getArgOperand(1); 358 auto CAZ = dyn_cast<ConstantAggregateZero>(Arg1); 359 auto CDV = dyn_cast<ConstantDataVector>(Arg1); 360 auto CInt = dyn_cast<ConstantInt>(Arg1); 361 if (!CAZ && !CDV && !CInt) 362 return nullptr; 363 364 APInt Count(64, 0); 365 if (CDV) { 366 // SSE2/AVX2 uses all the first 64-bits of the 128-bit vector 367 // operand to compute the shift amount. 368 auto VT = cast<VectorType>(CDV->getType()); 369 unsigned BitWidth = VT->getElementType()->getPrimitiveSizeInBits(); 370 assert((64 % BitWidth) == 0 && "Unexpected packed shift size"); 371 unsigned NumSubElts = 64 / BitWidth; 372 373 // Concatenate the sub-elements to create the 64-bit value. 374 for (unsigned i = 0; i != NumSubElts; ++i) { 375 unsigned SubEltIdx = (NumSubElts - 1) - i; 376 auto SubElt = cast<ConstantInt>(CDV->getElementAsConstant(SubEltIdx)); 377 Count <<= BitWidth; 378 Count |= SubElt->getValue().zextOrTrunc(64); 379 } 380 } 381 else if (CInt) 382 Count = CInt->getValue(); 383 384 auto Vec = II.getArgOperand(0); 385 auto VT = cast<VectorType>(Vec->getType()); 386 auto SVT = VT->getElementType(); 387 unsigned VWidth = VT->getNumElements(); 388 unsigned BitWidth = SVT->getPrimitiveSizeInBits(); 389 390 // If shift-by-zero then just return the original value. 391 if (Count.isNullValue()) 392 return Vec; 393 394 // Handle cases when Shift >= BitWidth. 395 if (Count.uge(BitWidth)) { 396 // If LogicalShift - just return zero. 397 if (LogicalShift) 398 return ConstantAggregateZero::get(VT); 399 400 // If ArithmeticShift - clamp Shift to (BitWidth - 1). 401 Count = APInt(64, BitWidth - 1); 402 } 403 404 // Get a constant vector of the same type as the first operand. 405 auto ShiftAmt = ConstantInt::get(SVT, Count.zextOrTrunc(BitWidth)); 406 auto ShiftVec = Builder.CreateVectorSplat(VWidth, ShiftAmt); 407 408 if (ShiftLeft) 409 return Builder.CreateShl(Vec, ShiftVec); 410 411 if (LogicalShift) 412 return Builder.CreateLShr(Vec, ShiftVec); 413 414 return Builder.CreateAShr(Vec, ShiftVec); 415 } 416 417 // Attempt to simplify AVX2 per-element shift intrinsics to a generic IR shift. 418 // Unlike the generic IR shifts, the intrinsics have defined behaviour for out 419 // of range shift amounts (logical - set to zero, arithmetic - splat sign bit). 420 static Value *simplifyX86varShift(const IntrinsicInst &II, 421 InstCombiner::BuilderTy &Builder) { 422 bool LogicalShift = false; 423 bool ShiftLeft = false; 424 425 switch (II.getIntrinsicID()) { 426 default: llvm_unreachable("Unexpected intrinsic!"); 427 case Intrinsic::x86_avx2_psrav_d: 428 case Intrinsic::x86_avx2_psrav_d_256: 429 case Intrinsic::x86_avx512_psrav_q_128: 430 case Intrinsic::x86_avx512_psrav_q_256: 431 case Intrinsic::x86_avx512_psrav_d_512: 432 case Intrinsic::x86_avx512_psrav_q_512: 433 case Intrinsic::x86_avx512_psrav_w_128: 434 case Intrinsic::x86_avx512_psrav_w_256: 435 case Intrinsic::x86_avx512_psrav_w_512: 436 LogicalShift = false; 437 ShiftLeft = false; 438 break; 439 case Intrinsic::x86_avx2_psrlv_d: 440 case Intrinsic::x86_avx2_psrlv_d_256: 441 case Intrinsic::x86_avx2_psrlv_q: 442 case Intrinsic::x86_avx2_psrlv_q_256: 443 case Intrinsic::x86_avx512_psrlv_d_512: 444 case Intrinsic::x86_avx512_psrlv_q_512: 445 case Intrinsic::x86_avx512_psrlv_w_128: 446 case Intrinsic::x86_avx512_psrlv_w_256: 447 case Intrinsic::x86_avx512_psrlv_w_512: 448 LogicalShift = true; 449 ShiftLeft = false; 450 break; 451 case Intrinsic::x86_avx2_psllv_d: 452 case Intrinsic::x86_avx2_psllv_d_256: 453 case Intrinsic::x86_avx2_psllv_q: 454 case Intrinsic::x86_avx2_psllv_q_256: 455 case Intrinsic::x86_avx512_psllv_d_512: 456 case Intrinsic::x86_avx512_psllv_q_512: 457 case Intrinsic::x86_avx512_psllv_w_128: 458 case Intrinsic::x86_avx512_psllv_w_256: 459 case Intrinsic::x86_avx512_psllv_w_512: 460 LogicalShift = true; 461 ShiftLeft = true; 462 break; 463 } 464 assert((LogicalShift || !ShiftLeft) && "Only logical shifts can shift left"); 465 466 // Simplify if all shift amounts are constant/undef. 467 auto *CShift = dyn_cast<Constant>(II.getArgOperand(1)); 468 if (!CShift) 469 return nullptr; 470 471 auto Vec = II.getArgOperand(0); 472 auto VT = cast<VectorType>(II.getType()); 473 auto SVT = VT->getVectorElementType(); 474 int NumElts = VT->getNumElements(); 475 int BitWidth = SVT->getIntegerBitWidth(); 476 477 // Collect each element's shift amount. 478 // We also collect special cases: UNDEF = -1, OUT-OF-RANGE = BitWidth. 479 bool AnyOutOfRange = false; 480 SmallVector<int, 8> ShiftAmts; 481 for (int I = 0; I < NumElts; ++I) { 482 auto *CElt = CShift->getAggregateElement(I); 483 if (CElt && isa<UndefValue>(CElt)) { 484 ShiftAmts.push_back(-1); 485 continue; 486 } 487 488 auto *COp = dyn_cast_or_null<ConstantInt>(CElt); 489 if (!COp) 490 return nullptr; 491 492 // Handle out of range shifts. 493 // If LogicalShift - set to BitWidth (special case). 494 // If ArithmeticShift - set to (BitWidth - 1) (sign splat). 495 APInt ShiftVal = COp->getValue(); 496 if (ShiftVal.uge(BitWidth)) { 497 AnyOutOfRange = LogicalShift; 498 ShiftAmts.push_back(LogicalShift ? BitWidth : BitWidth - 1); 499 continue; 500 } 501 502 ShiftAmts.push_back((int)ShiftVal.getZExtValue()); 503 } 504 505 // If all elements out of range or UNDEF, return vector of zeros/undefs. 506 // ArithmeticShift should only hit this if they are all UNDEF. 507 auto OutOfRange = [&](int Idx) { return (Idx < 0) || (BitWidth <= Idx); }; 508 if (llvm::all_of(ShiftAmts, OutOfRange)) { 509 SmallVector<Constant *, 8> ConstantVec; 510 for (int Idx : ShiftAmts) { 511 if (Idx < 0) { 512 ConstantVec.push_back(UndefValue::get(SVT)); 513 } else { 514 assert(LogicalShift && "Logical shift expected"); 515 ConstantVec.push_back(ConstantInt::getNullValue(SVT)); 516 } 517 } 518 return ConstantVector::get(ConstantVec); 519 } 520 521 // We can't handle only some out of range values with generic logical shifts. 522 if (AnyOutOfRange) 523 return nullptr; 524 525 // Build the shift amount constant vector. 526 SmallVector<Constant *, 8> ShiftVecAmts; 527 for (int Idx : ShiftAmts) { 528 if (Idx < 0) 529 ShiftVecAmts.push_back(UndefValue::get(SVT)); 530 else 531 ShiftVecAmts.push_back(ConstantInt::get(SVT, Idx)); 532 } 533 auto ShiftVec = ConstantVector::get(ShiftVecAmts); 534 535 if (ShiftLeft) 536 return Builder.CreateShl(Vec, ShiftVec); 537 538 if (LogicalShift) 539 return Builder.CreateLShr(Vec, ShiftVec); 540 541 return Builder.CreateAShr(Vec, ShiftVec); 542 } 543 544 static Value *simplifyX86pack(IntrinsicInst &II, 545 InstCombiner::BuilderTy &Builder, bool IsSigned) { 546 Value *Arg0 = II.getArgOperand(0); 547 Value *Arg1 = II.getArgOperand(1); 548 Type *ResTy = II.getType(); 549 550 // Fast all undef handling. 551 if (isa<UndefValue>(Arg0) && isa<UndefValue>(Arg1)) 552 return UndefValue::get(ResTy); 553 554 Type *ArgTy = Arg0->getType(); 555 unsigned NumLanes = ResTy->getPrimitiveSizeInBits() / 128; 556 unsigned NumSrcElts = ArgTy->getVectorNumElements(); 557 assert(ResTy->getVectorNumElements() == (2 * NumSrcElts) && 558 "Unexpected packing types"); 559 560 unsigned NumSrcEltsPerLane = NumSrcElts / NumLanes; 561 unsigned DstScalarSizeInBits = ResTy->getScalarSizeInBits(); 562 unsigned SrcScalarSizeInBits = ArgTy->getScalarSizeInBits(); 563 assert(SrcScalarSizeInBits == (2 * DstScalarSizeInBits) && 564 "Unexpected packing types"); 565 566 // Constant folding. 567 if (!isa<Constant>(Arg0) || !isa<Constant>(Arg1)) 568 return nullptr; 569 570 // Clamp Values - signed/unsigned both use signed clamp values, but they 571 // differ on the min/max values. 572 APInt MinValue, MaxValue; 573 if (IsSigned) { 574 // PACKSS: Truncate signed value with signed saturation. 575 // Source values less than dst minint are saturated to minint. 576 // Source values greater than dst maxint are saturated to maxint. 577 MinValue = 578 APInt::getSignedMinValue(DstScalarSizeInBits).sext(SrcScalarSizeInBits); 579 MaxValue = 580 APInt::getSignedMaxValue(DstScalarSizeInBits).sext(SrcScalarSizeInBits); 581 } else { 582 // PACKUS: Truncate signed value with unsigned saturation. 583 // Source values less than zero are saturated to zero. 584 // Source values greater than dst maxuint are saturated to maxuint. 585 MinValue = APInt::getNullValue(SrcScalarSizeInBits); 586 MaxValue = APInt::getLowBitsSet(SrcScalarSizeInBits, DstScalarSizeInBits); 587 } 588 589 auto *MinC = Constant::getIntegerValue(ArgTy, MinValue); 590 auto *MaxC = Constant::getIntegerValue(ArgTy, MaxValue); 591 Arg0 = Builder.CreateSelect(Builder.CreateICmpSLT(Arg0, MinC), MinC, Arg0); 592 Arg1 = Builder.CreateSelect(Builder.CreateICmpSLT(Arg1, MinC), MinC, Arg1); 593 Arg0 = Builder.CreateSelect(Builder.CreateICmpSGT(Arg0, MaxC), MaxC, Arg0); 594 Arg1 = Builder.CreateSelect(Builder.CreateICmpSGT(Arg1, MaxC), MaxC, Arg1); 595 596 // Shuffle clamped args together at the lane level. 597 SmallVector<unsigned, 32> PackMask; 598 for (unsigned Lane = 0; Lane != NumLanes; ++Lane) { 599 for (unsigned Elt = 0; Elt != NumSrcEltsPerLane; ++Elt) 600 PackMask.push_back(Elt + (Lane * NumSrcEltsPerLane)); 601 for (unsigned Elt = 0; Elt != NumSrcEltsPerLane; ++Elt) 602 PackMask.push_back(Elt + (Lane * NumSrcEltsPerLane) + NumSrcElts); 603 } 604 auto *Shuffle = Builder.CreateShuffleVector(Arg0, Arg1, PackMask); 605 606 // Truncate to dst size. 607 return Builder.CreateTrunc(Shuffle, ResTy); 608 } 609 610 // Replace X86-specific intrinsics with generic floor-ceil where applicable. 611 static Value *simplifyX86round(IntrinsicInst &II, 612 InstCombiner::BuilderTy &Builder) { 613 ConstantInt *Arg = nullptr; 614 Intrinsic::ID IntrinsicID = II.getIntrinsicID(); 615 616 if (IntrinsicID == Intrinsic::x86_sse41_round_ss || 617 IntrinsicID == Intrinsic::x86_sse41_round_sd) 618 Arg = dyn_cast<ConstantInt>(II.getArgOperand(2)); 619 else if (IntrinsicID == Intrinsic::x86_avx512_mask_rndscale_ss || 620 IntrinsicID == Intrinsic::x86_avx512_mask_rndscale_sd) 621 Arg = dyn_cast<ConstantInt>(II.getArgOperand(4)); 622 else 623 Arg = dyn_cast<ConstantInt>(II.getArgOperand(1)); 624 if (!Arg) 625 return nullptr; 626 unsigned RoundControl = Arg->getZExtValue(); 627 628 Arg = nullptr; 629 unsigned SAE = 0; 630 if (IntrinsicID == Intrinsic::x86_avx512_mask_rndscale_ps_512 || 631 IntrinsicID == Intrinsic::x86_avx512_mask_rndscale_pd_512) 632 Arg = dyn_cast<ConstantInt>(II.getArgOperand(4)); 633 else if (IntrinsicID == Intrinsic::x86_avx512_mask_rndscale_ss || 634 IntrinsicID == Intrinsic::x86_avx512_mask_rndscale_sd) 635 Arg = dyn_cast<ConstantInt>(II.getArgOperand(5)); 636 else 637 SAE = 4; 638 if (!SAE) { 639 if (!Arg) 640 return nullptr; 641 SAE = Arg->getZExtValue(); 642 } 643 644 if (SAE != 4 || (RoundControl != 2 /*ceil*/ && RoundControl != 1 /*floor*/)) 645 return nullptr; 646 647 Value *Src, *Dst, *Mask; 648 bool IsScalar = false; 649 if (IntrinsicID == Intrinsic::x86_sse41_round_ss || 650 IntrinsicID == Intrinsic::x86_sse41_round_sd || 651 IntrinsicID == Intrinsic::x86_avx512_mask_rndscale_ss || 652 IntrinsicID == Intrinsic::x86_avx512_mask_rndscale_sd) { 653 IsScalar = true; 654 if (IntrinsicID == Intrinsic::x86_avx512_mask_rndscale_ss || 655 IntrinsicID == Intrinsic::x86_avx512_mask_rndscale_sd) { 656 Mask = II.getArgOperand(3); 657 Value *Zero = Constant::getNullValue(Mask->getType()); 658 Mask = Builder.CreateAnd(Mask, 1); 659 Mask = Builder.CreateICmp(ICmpInst::ICMP_NE, Mask, Zero); 660 Dst = II.getArgOperand(2); 661 } else 662 Dst = II.getArgOperand(0); 663 Src = Builder.CreateExtractElement(II.getArgOperand(1), (uint64_t)0); 664 } else { 665 Src = II.getArgOperand(0); 666 if (IntrinsicID == Intrinsic::x86_avx512_mask_rndscale_ps_128 || 667 IntrinsicID == Intrinsic::x86_avx512_mask_rndscale_ps_256 || 668 IntrinsicID == Intrinsic::x86_avx512_mask_rndscale_ps_512 || 669 IntrinsicID == Intrinsic::x86_avx512_mask_rndscale_pd_128 || 670 IntrinsicID == Intrinsic::x86_avx512_mask_rndscale_pd_256 || 671 IntrinsicID == Intrinsic::x86_avx512_mask_rndscale_pd_512) { 672 Dst = II.getArgOperand(2); 673 Mask = II.getArgOperand(3); 674 } else { 675 Dst = Src; 676 Mask = ConstantInt::getAllOnesValue( 677 Builder.getIntNTy(Src->getType()->getVectorNumElements())); 678 } 679 } 680 681 Intrinsic::ID ID = (RoundControl == 2) ? Intrinsic::ceil : Intrinsic::floor; 682 Value *Res = Builder.CreateUnaryIntrinsic(ID, Src, &II); 683 if (!IsScalar) { 684 if (auto *C = dyn_cast<Constant>(Mask)) 685 if (C->isAllOnesValue()) 686 return Res; 687 auto *MaskTy = VectorType::get( 688 Builder.getInt1Ty(), cast<IntegerType>(Mask->getType())->getBitWidth()); 689 Mask = Builder.CreateBitCast(Mask, MaskTy); 690 unsigned Width = Src->getType()->getVectorNumElements(); 691 if (MaskTy->getVectorNumElements() > Width) { 692 uint32_t Indices[4]; 693 for (unsigned i = 0; i != Width; ++i) 694 Indices[i] = i; 695 Mask = Builder.CreateShuffleVector(Mask, Mask, 696 makeArrayRef(Indices, Width)); 697 } 698 return Builder.CreateSelect(Mask, Res, Dst); 699 } 700 if (IntrinsicID == Intrinsic::x86_avx512_mask_rndscale_ss || 701 IntrinsicID == Intrinsic::x86_avx512_mask_rndscale_sd) { 702 Dst = Builder.CreateExtractElement(Dst, (uint64_t)0); 703 Res = Builder.CreateSelect(Mask, Res, Dst); 704 Dst = II.getArgOperand(0); 705 } 706 return Builder.CreateInsertElement(Dst, Res, (uint64_t)0); 707 } 708 709 static Value *simplifyX86movmsk(const IntrinsicInst &II, 710 InstCombiner::BuilderTy &Builder) { 711 Value *Arg = II.getArgOperand(0); 712 Type *ResTy = II.getType(); 713 Type *ArgTy = Arg->getType(); 714 715 // movmsk(undef) -> zero as we must ensure the upper bits are zero. 716 if (isa<UndefValue>(Arg)) 717 return Constant::getNullValue(ResTy); 718 719 // We can't easily peek through x86_mmx types. 720 if (!ArgTy->isVectorTy()) 721 return nullptr; 722 723 // Expand MOVMSK to compare/bitcast/zext: 724 // e.g. PMOVMSKB(v16i8 x): 725 // %cmp = icmp slt <16 x i8> %x, zeroinitializer 726 // %int = bitcast <16 x i1> %cmp to i16 727 // %res = zext i16 %int to i32 728 unsigned NumElts = ArgTy->getVectorNumElements(); 729 Type *IntegerVecTy = VectorType::getInteger(cast<VectorType>(ArgTy)); 730 Type *IntegerTy = Builder.getIntNTy(NumElts); 731 732 Value *Res = Builder.CreateBitCast(Arg, IntegerVecTy); 733 Res = Builder.CreateICmpSLT(Res, Constant::getNullValue(IntegerVecTy)); 734 Res = Builder.CreateBitCast(Res, IntegerTy); 735 Res = Builder.CreateZExtOrTrunc(Res, ResTy); 736 return Res; 737 } 738 739 static Value *simplifyX86addcarry(const IntrinsicInst &II, 740 InstCombiner::BuilderTy &Builder) { 741 Value *CarryIn = II.getArgOperand(0); 742 Value *Op1 = II.getArgOperand(1); 743 Value *Op2 = II.getArgOperand(2); 744 Type *RetTy = II.getType(); 745 Type *OpTy = Op1->getType(); 746 assert(RetTy->getStructElementType(0)->isIntegerTy(8) && 747 RetTy->getStructElementType(1) == OpTy && OpTy == Op2->getType() && 748 "Unexpected types for x86 addcarry"); 749 750 // If carry-in is zero, this is just an unsigned add with overflow. 751 if (match(CarryIn, m_ZeroInt())) { 752 Value *UAdd = Builder.CreateIntrinsic(Intrinsic::uadd_with_overflow, OpTy, 753 { Op1, Op2 }); 754 // The types have to be adjusted to match the x86 call types. 755 Value *UAddResult = Builder.CreateExtractValue(UAdd, 0); 756 Value *UAddOV = Builder.CreateZExt(Builder.CreateExtractValue(UAdd, 1), 757 Builder.getInt8Ty()); 758 Value *Res = UndefValue::get(RetTy); 759 Res = Builder.CreateInsertValue(Res, UAddOV, 0); 760 return Builder.CreateInsertValue(Res, UAddResult, 1); 761 } 762 763 return nullptr; 764 } 765 766 static Value *simplifyX86insertps(const IntrinsicInst &II, 767 InstCombiner::BuilderTy &Builder) { 768 auto *CInt = dyn_cast<ConstantInt>(II.getArgOperand(2)); 769 if (!CInt) 770 return nullptr; 771 772 VectorType *VecTy = cast<VectorType>(II.getType()); 773 assert(VecTy->getNumElements() == 4 && "insertps with wrong vector type"); 774 775 // The immediate permute control byte looks like this: 776 // [3:0] - zero mask for each 32-bit lane 777 // [5:4] - select one 32-bit destination lane 778 // [7:6] - select one 32-bit source lane 779 780 uint8_t Imm = CInt->getZExtValue(); 781 uint8_t ZMask = Imm & 0xf; 782 uint8_t DestLane = (Imm >> 4) & 0x3; 783 uint8_t SourceLane = (Imm >> 6) & 0x3; 784 785 ConstantAggregateZero *ZeroVector = ConstantAggregateZero::get(VecTy); 786 787 // If all zero mask bits are set, this was just a weird way to 788 // generate a zero vector. 789 if (ZMask == 0xf) 790 return ZeroVector; 791 792 // Initialize by passing all of the first source bits through. 793 uint32_t ShuffleMask[4] = { 0, 1, 2, 3 }; 794 795 // We may replace the second operand with the zero vector. 796 Value *V1 = II.getArgOperand(1); 797 798 if (ZMask) { 799 // If the zero mask is being used with a single input or the zero mask 800 // overrides the destination lane, this is a shuffle with the zero vector. 801 if ((II.getArgOperand(0) == II.getArgOperand(1)) || 802 (ZMask & (1 << DestLane))) { 803 V1 = ZeroVector; 804 // We may still move 32-bits of the first source vector from one lane 805 // to another. 806 ShuffleMask[DestLane] = SourceLane; 807 // The zero mask may override the previous insert operation. 808 for (unsigned i = 0; i < 4; ++i) 809 if ((ZMask >> i) & 0x1) 810 ShuffleMask[i] = i + 4; 811 } else { 812 // TODO: Model this case as 2 shuffles or a 'logical and' plus shuffle? 813 return nullptr; 814 } 815 } else { 816 // Replace the selected destination lane with the selected source lane. 817 ShuffleMask[DestLane] = SourceLane + 4; 818 } 819 820 return Builder.CreateShuffleVector(II.getArgOperand(0), V1, ShuffleMask); 821 } 822 823 /// Attempt to simplify SSE4A EXTRQ/EXTRQI instructions using constant folding 824 /// or conversion to a shuffle vector. 825 static Value *simplifyX86extrq(IntrinsicInst &II, Value *Op0, 826 ConstantInt *CILength, ConstantInt *CIIndex, 827 InstCombiner::BuilderTy &Builder) { 828 auto LowConstantHighUndef = [&](uint64_t Val) { 829 Type *IntTy64 = Type::getInt64Ty(II.getContext()); 830 Constant *Args[] = {ConstantInt::get(IntTy64, Val), 831 UndefValue::get(IntTy64)}; 832 return ConstantVector::get(Args); 833 }; 834 835 // See if we're dealing with constant values. 836 Constant *C0 = dyn_cast<Constant>(Op0); 837 ConstantInt *CI0 = 838 C0 ? dyn_cast_or_null<ConstantInt>(C0->getAggregateElement((unsigned)0)) 839 : nullptr; 840 841 // Attempt to constant fold. 842 if (CILength && CIIndex) { 843 // From AMD documentation: "The bit index and field length are each six 844 // bits in length other bits of the field are ignored." 845 APInt APIndex = CIIndex->getValue().zextOrTrunc(6); 846 APInt APLength = CILength->getValue().zextOrTrunc(6); 847 848 unsigned Index = APIndex.getZExtValue(); 849 850 // From AMD documentation: "a value of zero in the field length is 851 // defined as length of 64". 852 unsigned Length = APLength == 0 ? 64 : APLength.getZExtValue(); 853 854 // From AMD documentation: "If the sum of the bit index + length field 855 // is greater than 64, the results are undefined". 856 unsigned End = Index + Length; 857 858 // Note that both field index and field length are 8-bit quantities. 859 // Since variables 'Index' and 'Length' are unsigned values 860 // obtained from zero-extending field index and field length 861 // respectively, their sum should never wrap around. 862 if (End > 64) 863 return UndefValue::get(II.getType()); 864 865 // If we are inserting whole bytes, we can convert this to a shuffle. 866 // Lowering can recognize EXTRQI shuffle masks. 867 if ((Length % 8) == 0 && (Index % 8) == 0) { 868 // Convert bit indices to byte indices. 869 Length /= 8; 870 Index /= 8; 871 872 Type *IntTy8 = Type::getInt8Ty(II.getContext()); 873 Type *IntTy32 = Type::getInt32Ty(II.getContext()); 874 VectorType *ShufTy = VectorType::get(IntTy8, 16); 875 876 SmallVector<Constant *, 16> ShuffleMask; 877 for (int i = 0; i != (int)Length; ++i) 878 ShuffleMask.push_back( 879 Constant::getIntegerValue(IntTy32, APInt(32, i + Index))); 880 for (int i = Length; i != 8; ++i) 881 ShuffleMask.push_back( 882 Constant::getIntegerValue(IntTy32, APInt(32, i + 16))); 883 for (int i = 8; i != 16; ++i) 884 ShuffleMask.push_back(UndefValue::get(IntTy32)); 885 886 Value *SV = Builder.CreateShuffleVector( 887 Builder.CreateBitCast(Op0, ShufTy), 888 ConstantAggregateZero::get(ShufTy), ConstantVector::get(ShuffleMask)); 889 return Builder.CreateBitCast(SV, II.getType()); 890 } 891 892 // Constant Fold - shift Index'th bit to lowest position and mask off 893 // Length bits. 894 if (CI0) { 895 APInt Elt = CI0->getValue(); 896 Elt.lshrInPlace(Index); 897 Elt = Elt.zextOrTrunc(Length); 898 return LowConstantHighUndef(Elt.getZExtValue()); 899 } 900 901 // If we were an EXTRQ call, we'll save registers if we convert to EXTRQI. 902 if (II.getIntrinsicID() == Intrinsic::x86_sse4a_extrq) { 903 Value *Args[] = {Op0, CILength, CIIndex}; 904 Module *M = II.getModule(); 905 Function *F = Intrinsic::getDeclaration(M, Intrinsic::x86_sse4a_extrqi); 906 return Builder.CreateCall(F, Args); 907 } 908 } 909 910 // Constant Fold - extraction from zero is always {zero, undef}. 911 if (CI0 && CI0->isZero()) 912 return LowConstantHighUndef(0); 913 914 return nullptr; 915 } 916 917 /// Attempt to simplify SSE4A INSERTQ/INSERTQI instructions using constant 918 /// folding or conversion to a shuffle vector. 919 static Value *simplifyX86insertq(IntrinsicInst &II, Value *Op0, Value *Op1, 920 APInt APLength, APInt APIndex, 921 InstCombiner::BuilderTy &Builder) { 922 // From AMD documentation: "The bit index and field length are each six bits 923 // in length other bits of the field are ignored." 924 APIndex = APIndex.zextOrTrunc(6); 925 APLength = APLength.zextOrTrunc(6); 926 927 // Attempt to constant fold. 928 unsigned Index = APIndex.getZExtValue(); 929 930 // From AMD documentation: "a value of zero in the field length is 931 // defined as length of 64". 932 unsigned Length = APLength == 0 ? 64 : APLength.getZExtValue(); 933 934 // From AMD documentation: "If the sum of the bit index + length field 935 // is greater than 64, the results are undefined". 936 unsigned End = Index + Length; 937 938 // Note that both field index and field length are 8-bit quantities. 939 // Since variables 'Index' and 'Length' are unsigned values 940 // obtained from zero-extending field index and field length 941 // respectively, their sum should never wrap around. 942 if (End > 64) 943 return UndefValue::get(II.getType()); 944 945 // If we are inserting whole bytes, we can convert this to a shuffle. 946 // Lowering can recognize INSERTQI shuffle masks. 947 if ((Length % 8) == 0 && (Index % 8) == 0) { 948 // Convert bit indices to byte indices. 949 Length /= 8; 950 Index /= 8; 951 952 Type *IntTy8 = Type::getInt8Ty(II.getContext()); 953 Type *IntTy32 = Type::getInt32Ty(II.getContext()); 954 VectorType *ShufTy = VectorType::get(IntTy8, 16); 955 956 SmallVector<Constant *, 16> ShuffleMask; 957 for (int i = 0; i != (int)Index; ++i) 958 ShuffleMask.push_back(Constant::getIntegerValue(IntTy32, APInt(32, i))); 959 for (int i = 0; i != (int)Length; ++i) 960 ShuffleMask.push_back( 961 Constant::getIntegerValue(IntTy32, APInt(32, i + 16))); 962 for (int i = Index + Length; i != 8; ++i) 963 ShuffleMask.push_back(Constant::getIntegerValue(IntTy32, APInt(32, i))); 964 for (int i = 8; i != 16; ++i) 965 ShuffleMask.push_back(UndefValue::get(IntTy32)); 966 967 Value *SV = Builder.CreateShuffleVector(Builder.CreateBitCast(Op0, ShufTy), 968 Builder.CreateBitCast(Op1, ShufTy), 969 ConstantVector::get(ShuffleMask)); 970 return Builder.CreateBitCast(SV, II.getType()); 971 } 972 973 // See if we're dealing with constant values. 974 Constant *C0 = dyn_cast<Constant>(Op0); 975 Constant *C1 = dyn_cast<Constant>(Op1); 976 ConstantInt *CI00 = 977 C0 ? dyn_cast_or_null<ConstantInt>(C0->getAggregateElement((unsigned)0)) 978 : nullptr; 979 ConstantInt *CI10 = 980 C1 ? dyn_cast_or_null<ConstantInt>(C1->getAggregateElement((unsigned)0)) 981 : nullptr; 982 983 // Constant Fold - insert bottom Length bits starting at the Index'th bit. 984 if (CI00 && CI10) { 985 APInt V00 = CI00->getValue(); 986 APInt V10 = CI10->getValue(); 987 APInt Mask = APInt::getLowBitsSet(64, Length).shl(Index); 988 V00 = V00 & ~Mask; 989 V10 = V10.zextOrTrunc(Length).zextOrTrunc(64).shl(Index); 990 APInt Val = V00 | V10; 991 Type *IntTy64 = Type::getInt64Ty(II.getContext()); 992 Constant *Args[] = {ConstantInt::get(IntTy64, Val.getZExtValue()), 993 UndefValue::get(IntTy64)}; 994 return ConstantVector::get(Args); 995 } 996 997 // If we were an INSERTQ call, we'll save demanded elements if we convert to 998 // INSERTQI. 999 if (II.getIntrinsicID() == Intrinsic::x86_sse4a_insertq) { 1000 Type *IntTy8 = Type::getInt8Ty(II.getContext()); 1001 Constant *CILength = ConstantInt::get(IntTy8, Length, false); 1002 Constant *CIIndex = ConstantInt::get(IntTy8, Index, false); 1003 1004 Value *Args[] = {Op0, Op1, CILength, CIIndex}; 1005 Module *M = II.getModule(); 1006 Function *F = Intrinsic::getDeclaration(M, Intrinsic::x86_sse4a_insertqi); 1007 return Builder.CreateCall(F, Args); 1008 } 1009 1010 return nullptr; 1011 } 1012 1013 /// Attempt to convert pshufb* to shufflevector if the mask is constant. 1014 static Value *simplifyX86pshufb(const IntrinsicInst &II, 1015 InstCombiner::BuilderTy &Builder) { 1016 Constant *V = dyn_cast<Constant>(II.getArgOperand(1)); 1017 if (!V) 1018 return nullptr; 1019 1020 auto *VecTy = cast<VectorType>(II.getType()); 1021 auto *MaskEltTy = Type::getInt32Ty(II.getContext()); 1022 unsigned NumElts = VecTy->getNumElements(); 1023 assert((NumElts == 16 || NumElts == 32 || NumElts == 64) && 1024 "Unexpected number of elements in shuffle mask!"); 1025 1026 // Construct a shuffle mask from constant integers or UNDEFs. 1027 Constant *Indexes[64] = {nullptr}; 1028 1029 // Each byte in the shuffle control mask forms an index to permute the 1030 // corresponding byte in the destination operand. 1031 for (unsigned I = 0; I < NumElts; ++I) { 1032 Constant *COp = V->getAggregateElement(I); 1033 if (!COp || (!isa<UndefValue>(COp) && !isa<ConstantInt>(COp))) 1034 return nullptr; 1035 1036 if (isa<UndefValue>(COp)) { 1037 Indexes[I] = UndefValue::get(MaskEltTy); 1038 continue; 1039 } 1040 1041 int8_t Index = cast<ConstantInt>(COp)->getValue().getZExtValue(); 1042 1043 // If the most significant bit (bit[7]) of each byte of the shuffle 1044 // control mask is set, then zero is written in the result byte. 1045 // The zero vector is in the right-hand side of the resulting 1046 // shufflevector. 1047 1048 // The value of each index for the high 128-bit lane is the least 1049 // significant 4 bits of the respective shuffle control byte. 1050 Index = ((Index < 0) ? NumElts : Index & 0x0F) + (I & 0xF0); 1051 Indexes[I] = ConstantInt::get(MaskEltTy, Index); 1052 } 1053 1054 auto ShuffleMask = ConstantVector::get(makeArrayRef(Indexes, NumElts)); 1055 auto V1 = II.getArgOperand(0); 1056 auto V2 = Constant::getNullValue(VecTy); 1057 return Builder.CreateShuffleVector(V1, V2, ShuffleMask); 1058 } 1059 1060 /// Attempt to convert vpermilvar* to shufflevector if the mask is constant. 1061 static Value *simplifyX86vpermilvar(const IntrinsicInst &II, 1062 InstCombiner::BuilderTy &Builder) { 1063 Constant *V = dyn_cast<Constant>(II.getArgOperand(1)); 1064 if (!V) 1065 return nullptr; 1066 1067 auto *VecTy = cast<VectorType>(II.getType()); 1068 auto *MaskEltTy = Type::getInt32Ty(II.getContext()); 1069 unsigned NumElts = VecTy->getVectorNumElements(); 1070 bool IsPD = VecTy->getScalarType()->isDoubleTy(); 1071 unsigned NumLaneElts = IsPD ? 2 : 4; 1072 assert(NumElts == 16 || NumElts == 8 || NumElts == 4 || NumElts == 2); 1073 1074 // Construct a shuffle mask from constant integers or UNDEFs. 1075 Constant *Indexes[16] = {nullptr}; 1076 1077 // The intrinsics only read one or two bits, clear the rest. 1078 for (unsigned I = 0; I < NumElts; ++I) { 1079 Constant *COp = V->getAggregateElement(I); 1080 if (!COp || (!isa<UndefValue>(COp) && !isa<ConstantInt>(COp))) 1081 return nullptr; 1082 1083 if (isa<UndefValue>(COp)) { 1084 Indexes[I] = UndefValue::get(MaskEltTy); 1085 continue; 1086 } 1087 1088 APInt Index = cast<ConstantInt>(COp)->getValue(); 1089 Index = Index.zextOrTrunc(32).getLoBits(2); 1090 1091 // The PD variants uses bit 1 to select per-lane element index, so 1092 // shift down to convert to generic shuffle mask index. 1093 if (IsPD) 1094 Index.lshrInPlace(1); 1095 1096 // The _256 variants are a bit trickier since the mask bits always index 1097 // into the corresponding 128 half. In order to convert to a generic 1098 // shuffle, we have to make that explicit. 1099 Index += APInt(32, (I / NumLaneElts) * NumLaneElts); 1100 1101 Indexes[I] = ConstantInt::get(MaskEltTy, Index); 1102 } 1103 1104 auto ShuffleMask = ConstantVector::get(makeArrayRef(Indexes, NumElts)); 1105 auto V1 = II.getArgOperand(0); 1106 auto V2 = UndefValue::get(V1->getType()); 1107 return Builder.CreateShuffleVector(V1, V2, ShuffleMask); 1108 } 1109 1110 /// Attempt to convert vpermd/vpermps to shufflevector if the mask is constant. 1111 static Value *simplifyX86vpermv(const IntrinsicInst &II, 1112 InstCombiner::BuilderTy &Builder) { 1113 auto *V = dyn_cast<Constant>(II.getArgOperand(1)); 1114 if (!V) 1115 return nullptr; 1116 1117 auto *VecTy = cast<VectorType>(II.getType()); 1118 auto *MaskEltTy = Type::getInt32Ty(II.getContext()); 1119 unsigned Size = VecTy->getNumElements(); 1120 assert((Size == 4 || Size == 8 || Size == 16 || Size == 32 || Size == 64) && 1121 "Unexpected shuffle mask size"); 1122 1123 // Construct a shuffle mask from constant integers or UNDEFs. 1124 Constant *Indexes[64] = {nullptr}; 1125 1126 for (unsigned I = 0; I < Size; ++I) { 1127 Constant *COp = V->getAggregateElement(I); 1128 if (!COp || (!isa<UndefValue>(COp) && !isa<ConstantInt>(COp))) 1129 return nullptr; 1130 1131 if (isa<UndefValue>(COp)) { 1132 Indexes[I] = UndefValue::get(MaskEltTy); 1133 continue; 1134 } 1135 1136 uint32_t Index = cast<ConstantInt>(COp)->getZExtValue(); 1137 Index &= Size - 1; 1138 Indexes[I] = ConstantInt::get(MaskEltTy, Index); 1139 } 1140 1141 auto ShuffleMask = ConstantVector::get(makeArrayRef(Indexes, Size)); 1142 auto V1 = II.getArgOperand(0); 1143 auto V2 = UndefValue::get(VecTy); 1144 return Builder.CreateShuffleVector(V1, V2, ShuffleMask); 1145 } 1146 1147 // TODO, Obvious Missing Transforms: 1148 // * Narrow width by halfs excluding zero/undef lanes 1149 Value *InstCombiner::simplifyMaskedLoad(IntrinsicInst &II) { 1150 Value *LoadPtr = II.getArgOperand(0); 1151 unsigned Alignment = cast<ConstantInt>(II.getArgOperand(1))->getZExtValue(); 1152 1153 // If the mask is all ones or undefs, this is a plain vector load of the 1st 1154 // argument. 1155 if (maskIsAllOneOrUndef(II.getArgOperand(2))) 1156 return Builder.CreateAlignedLoad(II.getType(), LoadPtr, Alignment, 1157 "unmaskedload"); 1158 1159 // If we can unconditionally load from this address, replace with a 1160 // load/select idiom. TODO: use DT for context sensitive query 1161 if (isDereferenceableAndAlignedPointer(LoadPtr, Alignment, 1162 II.getModule()->getDataLayout(), 1163 &II, nullptr)) { 1164 Value *LI = Builder.CreateAlignedLoad(II.getType(), LoadPtr, Alignment, 1165 "unmaskedload"); 1166 return Builder.CreateSelect(II.getArgOperand(2), LI, II.getArgOperand(3)); 1167 } 1168 1169 return nullptr; 1170 } 1171 1172 // TODO, Obvious Missing Transforms: 1173 // * Single constant active lane -> store 1174 // * Narrow width by halfs excluding zero/undef lanes 1175 Instruction *InstCombiner::simplifyMaskedStore(IntrinsicInst &II) { 1176 auto *ConstMask = dyn_cast<Constant>(II.getArgOperand(3)); 1177 if (!ConstMask) 1178 return nullptr; 1179 1180 // If the mask is all zeros, this instruction does nothing. 1181 if (ConstMask->isNullValue()) 1182 return eraseInstFromFunction(II); 1183 1184 // If the mask is all ones, this is a plain vector store of the 1st argument. 1185 if (ConstMask->isAllOnesValue()) { 1186 Value *StorePtr = II.getArgOperand(1); 1187 unsigned Alignment = cast<ConstantInt>(II.getArgOperand(2))->getZExtValue(); 1188 return new StoreInst(II.getArgOperand(0), StorePtr, false, Alignment); 1189 } 1190 1191 // Use masked off lanes to simplify operands via SimplifyDemandedVectorElts 1192 APInt DemandedElts = possiblyDemandedEltsInMask(ConstMask); 1193 APInt UndefElts(DemandedElts.getBitWidth(), 0); 1194 if (Value *V = SimplifyDemandedVectorElts(II.getOperand(0), 1195 DemandedElts, UndefElts)) { 1196 II.setOperand(0, V); 1197 return &II; 1198 } 1199 1200 return nullptr; 1201 } 1202 1203 // TODO, Obvious Missing Transforms: 1204 // * Single constant active lane load -> load 1205 // * Dereferenceable address & few lanes -> scalarize speculative load/selects 1206 // * Adjacent vector addresses -> masked.load 1207 // * Narrow width by halfs excluding zero/undef lanes 1208 // * Vector splat address w/known mask -> scalar load 1209 // * Vector incrementing address -> vector masked load 1210 Instruction *InstCombiner::simplifyMaskedGather(IntrinsicInst &II) { 1211 return nullptr; 1212 } 1213 1214 // TODO, Obvious Missing Transforms: 1215 // * Single constant active lane -> store 1216 // * Adjacent vector addresses -> masked.store 1217 // * Narrow store width by halfs excluding zero/undef lanes 1218 // * Vector splat address w/known mask -> scalar store 1219 // * Vector incrementing address -> vector masked store 1220 Instruction *InstCombiner::simplifyMaskedScatter(IntrinsicInst &II) { 1221 auto *ConstMask = dyn_cast<Constant>(II.getArgOperand(3)); 1222 if (!ConstMask) 1223 return nullptr; 1224 1225 // If the mask is all zeros, a scatter does nothing. 1226 if (ConstMask->isNullValue()) 1227 return eraseInstFromFunction(II); 1228 1229 // Use masked off lanes to simplify operands via SimplifyDemandedVectorElts 1230 APInt DemandedElts = possiblyDemandedEltsInMask(ConstMask); 1231 APInt UndefElts(DemandedElts.getBitWidth(), 0); 1232 if (Value *V = SimplifyDemandedVectorElts(II.getOperand(0), 1233 DemandedElts, UndefElts)) { 1234 II.setOperand(0, V); 1235 return &II; 1236 } 1237 if (Value *V = SimplifyDemandedVectorElts(II.getOperand(1), 1238 DemandedElts, UndefElts)) { 1239 II.setOperand(1, V); 1240 return &II; 1241 } 1242 1243 return nullptr; 1244 } 1245 1246 /// This function transforms launder.invariant.group and strip.invariant.group 1247 /// like: 1248 /// launder(launder(%x)) -> launder(%x) (the result is not the argument) 1249 /// launder(strip(%x)) -> launder(%x) 1250 /// strip(strip(%x)) -> strip(%x) (the result is not the argument) 1251 /// strip(launder(%x)) -> strip(%x) 1252 /// This is legal because it preserves the most recent information about 1253 /// the presence or absence of invariant.group. 1254 static Instruction *simplifyInvariantGroupIntrinsic(IntrinsicInst &II, 1255 InstCombiner &IC) { 1256 auto *Arg = II.getArgOperand(0); 1257 auto *StrippedArg = Arg->stripPointerCasts(); 1258 auto *StrippedInvariantGroupsArg = Arg->stripPointerCastsAndInvariantGroups(); 1259 if (StrippedArg == StrippedInvariantGroupsArg) 1260 return nullptr; // No launders/strips to remove. 1261 1262 Value *Result = nullptr; 1263 1264 if (II.getIntrinsicID() == Intrinsic::launder_invariant_group) 1265 Result = IC.Builder.CreateLaunderInvariantGroup(StrippedInvariantGroupsArg); 1266 else if (II.getIntrinsicID() == Intrinsic::strip_invariant_group) 1267 Result = IC.Builder.CreateStripInvariantGroup(StrippedInvariantGroupsArg); 1268 else 1269 llvm_unreachable( 1270 "simplifyInvariantGroupIntrinsic only handles launder and strip"); 1271 if (Result->getType()->getPointerAddressSpace() != 1272 II.getType()->getPointerAddressSpace()) 1273 Result = IC.Builder.CreateAddrSpaceCast(Result, II.getType()); 1274 if (Result->getType() != II.getType()) 1275 Result = IC.Builder.CreateBitCast(Result, II.getType()); 1276 1277 return cast<Instruction>(Result); 1278 } 1279 1280 static Instruction *foldCttzCtlz(IntrinsicInst &II, InstCombiner &IC) { 1281 assert((II.getIntrinsicID() == Intrinsic::cttz || 1282 II.getIntrinsicID() == Intrinsic::ctlz) && 1283 "Expected cttz or ctlz intrinsic"); 1284 bool IsTZ = II.getIntrinsicID() == Intrinsic::cttz; 1285 Value *Op0 = II.getArgOperand(0); 1286 Value *X; 1287 // ctlz(bitreverse(x)) -> cttz(x) 1288 // cttz(bitreverse(x)) -> ctlz(x) 1289 if (match(Op0, m_BitReverse(m_Value(X)))) { 1290 Intrinsic::ID ID = IsTZ ? Intrinsic::ctlz : Intrinsic::cttz; 1291 Function *F = Intrinsic::getDeclaration(II.getModule(), ID, II.getType()); 1292 return CallInst::Create(F, {X, II.getArgOperand(1)}); 1293 } 1294 1295 KnownBits Known = IC.computeKnownBits(Op0, 0, &II); 1296 1297 // Create a mask for bits above (ctlz) or below (cttz) the first known one. 1298 unsigned PossibleZeros = IsTZ ? Known.countMaxTrailingZeros() 1299 : Known.countMaxLeadingZeros(); 1300 unsigned DefiniteZeros = IsTZ ? Known.countMinTrailingZeros() 1301 : Known.countMinLeadingZeros(); 1302 1303 // If all bits above (ctlz) or below (cttz) the first known one are known 1304 // zero, this value is constant. 1305 // FIXME: This should be in InstSimplify because we're replacing an 1306 // instruction with a constant. 1307 if (PossibleZeros == DefiniteZeros) { 1308 auto *C = ConstantInt::get(Op0->getType(), DefiniteZeros); 1309 return IC.replaceInstUsesWith(II, C); 1310 } 1311 1312 // If the input to cttz/ctlz is known to be non-zero, 1313 // then change the 'ZeroIsUndef' parameter to 'true' 1314 // because we know the zero behavior can't affect the result. 1315 if (!Known.One.isNullValue() || 1316 isKnownNonZero(Op0, IC.getDataLayout(), 0, &IC.getAssumptionCache(), &II, 1317 &IC.getDominatorTree())) { 1318 if (!match(II.getArgOperand(1), m_One())) { 1319 II.setOperand(1, IC.Builder.getTrue()); 1320 return &II; 1321 } 1322 } 1323 1324 // Add range metadata since known bits can't completely reflect what we know. 1325 // TODO: Handle splat vectors. 1326 auto *IT = dyn_cast<IntegerType>(Op0->getType()); 1327 if (IT && IT->getBitWidth() != 1 && !II.getMetadata(LLVMContext::MD_range)) { 1328 Metadata *LowAndHigh[] = { 1329 ConstantAsMetadata::get(ConstantInt::get(IT, DefiniteZeros)), 1330 ConstantAsMetadata::get(ConstantInt::get(IT, PossibleZeros + 1))}; 1331 II.setMetadata(LLVMContext::MD_range, 1332 MDNode::get(II.getContext(), LowAndHigh)); 1333 return &II; 1334 } 1335 1336 return nullptr; 1337 } 1338 1339 static Instruction *foldCtpop(IntrinsicInst &II, InstCombiner &IC) { 1340 assert(II.getIntrinsicID() == Intrinsic::ctpop && 1341 "Expected ctpop intrinsic"); 1342 Value *Op0 = II.getArgOperand(0); 1343 Value *X; 1344 // ctpop(bitreverse(x)) -> ctpop(x) 1345 // ctpop(bswap(x)) -> ctpop(x) 1346 if (match(Op0, m_BitReverse(m_Value(X))) || match(Op0, m_BSwap(m_Value(X)))) { 1347 II.setOperand(0, X); 1348 return &II; 1349 } 1350 1351 // FIXME: Try to simplify vectors of integers. 1352 auto *IT = dyn_cast<IntegerType>(Op0->getType()); 1353 if (!IT) 1354 return nullptr; 1355 1356 unsigned BitWidth = IT->getBitWidth(); 1357 KnownBits Known(BitWidth); 1358 IC.computeKnownBits(Op0, Known, 0, &II); 1359 1360 unsigned MinCount = Known.countMinPopulation(); 1361 unsigned MaxCount = Known.countMaxPopulation(); 1362 1363 // Add range metadata since known bits can't completely reflect what we know. 1364 if (IT->getBitWidth() != 1 && !II.getMetadata(LLVMContext::MD_range)) { 1365 Metadata *LowAndHigh[] = { 1366 ConstantAsMetadata::get(ConstantInt::get(IT, MinCount)), 1367 ConstantAsMetadata::get(ConstantInt::get(IT, MaxCount + 1))}; 1368 II.setMetadata(LLVMContext::MD_range, 1369 MDNode::get(II.getContext(), LowAndHigh)); 1370 return &II; 1371 } 1372 1373 return nullptr; 1374 } 1375 1376 // TODO: If the x86 backend knew how to convert a bool vector mask back to an 1377 // XMM register mask efficiently, we could transform all x86 masked intrinsics 1378 // to LLVM masked intrinsics and remove the x86 masked intrinsic defs. 1379 static Instruction *simplifyX86MaskedLoad(IntrinsicInst &II, InstCombiner &IC) { 1380 Value *Ptr = II.getOperand(0); 1381 Value *Mask = II.getOperand(1); 1382 Constant *ZeroVec = Constant::getNullValue(II.getType()); 1383 1384 // Special case a zero mask since that's not a ConstantDataVector. 1385 // This masked load instruction creates a zero vector. 1386 if (isa<ConstantAggregateZero>(Mask)) 1387 return IC.replaceInstUsesWith(II, ZeroVec); 1388 1389 auto *ConstMask = dyn_cast<ConstantDataVector>(Mask); 1390 if (!ConstMask) 1391 return nullptr; 1392 1393 // The mask is constant. Convert this x86 intrinsic to the LLVM instrinsic 1394 // to allow target-independent optimizations. 1395 1396 // First, cast the x86 intrinsic scalar pointer to a vector pointer to match 1397 // the LLVM intrinsic definition for the pointer argument. 1398 unsigned AddrSpace = cast<PointerType>(Ptr->getType())->getAddressSpace(); 1399 PointerType *VecPtrTy = PointerType::get(II.getType(), AddrSpace); 1400 Value *PtrCast = IC.Builder.CreateBitCast(Ptr, VecPtrTy, "castvec"); 1401 1402 // Second, convert the x86 XMM integer vector mask to a vector of bools based 1403 // on each element's most significant bit (the sign bit). 1404 Constant *BoolMask = getNegativeIsTrueBoolVec(ConstMask); 1405 1406 // The pass-through vector for an x86 masked load is a zero vector. 1407 CallInst *NewMaskedLoad = 1408 IC.Builder.CreateMaskedLoad(PtrCast, 1, BoolMask, ZeroVec); 1409 return IC.replaceInstUsesWith(II, NewMaskedLoad); 1410 } 1411 1412 // TODO: If the x86 backend knew how to convert a bool vector mask back to an 1413 // XMM register mask efficiently, we could transform all x86 masked intrinsics 1414 // to LLVM masked intrinsics and remove the x86 masked intrinsic defs. 1415 static bool simplifyX86MaskedStore(IntrinsicInst &II, InstCombiner &IC) { 1416 Value *Ptr = II.getOperand(0); 1417 Value *Mask = II.getOperand(1); 1418 Value *Vec = II.getOperand(2); 1419 1420 // Special case a zero mask since that's not a ConstantDataVector: 1421 // this masked store instruction does nothing. 1422 if (isa<ConstantAggregateZero>(Mask)) { 1423 IC.eraseInstFromFunction(II); 1424 return true; 1425 } 1426 1427 // The SSE2 version is too weird (eg, unaligned but non-temporal) to do 1428 // anything else at this level. 1429 if (II.getIntrinsicID() == Intrinsic::x86_sse2_maskmov_dqu) 1430 return false; 1431 1432 auto *ConstMask = dyn_cast<ConstantDataVector>(Mask); 1433 if (!ConstMask) 1434 return false; 1435 1436 // The mask is constant. Convert this x86 intrinsic to the LLVM instrinsic 1437 // to allow target-independent optimizations. 1438 1439 // First, cast the x86 intrinsic scalar pointer to a vector pointer to match 1440 // the LLVM intrinsic definition for the pointer argument. 1441 unsigned AddrSpace = cast<PointerType>(Ptr->getType())->getAddressSpace(); 1442 PointerType *VecPtrTy = PointerType::get(Vec->getType(), AddrSpace); 1443 Value *PtrCast = IC.Builder.CreateBitCast(Ptr, VecPtrTy, "castvec"); 1444 1445 // Second, convert the x86 XMM integer vector mask to a vector of bools based 1446 // on each element's most significant bit (the sign bit). 1447 Constant *BoolMask = getNegativeIsTrueBoolVec(ConstMask); 1448 1449 IC.Builder.CreateMaskedStore(Vec, PtrCast, 1, BoolMask); 1450 1451 // 'Replace uses' doesn't work for stores. Erase the original masked store. 1452 IC.eraseInstFromFunction(II); 1453 return true; 1454 } 1455 1456 // Constant fold llvm.amdgcn.fmed3 intrinsics for standard inputs. 1457 // 1458 // A single NaN input is folded to minnum, so we rely on that folding for 1459 // handling NaNs. 1460 static APFloat fmed3AMDGCN(const APFloat &Src0, const APFloat &Src1, 1461 const APFloat &Src2) { 1462 APFloat Max3 = maxnum(maxnum(Src0, Src1), Src2); 1463 1464 APFloat::cmpResult Cmp0 = Max3.compare(Src0); 1465 assert(Cmp0 != APFloat::cmpUnordered && "nans handled separately"); 1466 if (Cmp0 == APFloat::cmpEqual) 1467 return maxnum(Src1, Src2); 1468 1469 APFloat::cmpResult Cmp1 = Max3.compare(Src1); 1470 assert(Cmp1 != APFloat::cmpUnordered && "nans handled separately"); 1471 if (Cmp1 == APFloat::cmpEqual) 1472 return maxnum(Src0, Src2); 1473 1474 return maxnum(Src0, Src1); 1475 } 1476 1477 /// Convert a table lookup to shufflevector if the mask is constant. 1478 /// This could benefit tbl1 if the mask is { 7,6,5,4,3,2,1,0 }, in 1479 /// which case we could lower the shufflevector with rev64 instructions 1480 /// as it's actually a byte reverse. 1481 static Value *simplifyNeonTbl1(const IntrinsicInst &II, 1482 InstCombiner::BuilderTy &Builder) { 1483 // Bail out if the mask is not a constant. 1484 auto *C = dyn_cast<Constant>(II.getArgOperand(1)); 1485 if (!C) 1486 return nullptr; 1487 1488 auto *VecTy = cast<VectorType>(II.getType()); 1489 unsigned NumElts = VecTy->getNumElements(); 1490 1491 // Only perform this transformation for <8 x i8> vector types. 1492 if (!VecTy->getElementType()->isIntegerTy(8) || NumElts != 8) 1493 return nullptr; 1494 1495 uint32_t Indexes[8]; 1496 1497 for (unsigned I = 0; I < NumElts; ++I) { 1498 Constant *COp = C->getAggregateElement(I); 1499 1500 if (!COp || !isa<ConstantInt>(COp)) 1501 return nullptr; 1502 1503 Indexes[I] = cast<ConstantInt>(COp)->getLimitedValue(); 1504 1505 // Make sure the mask indices are in range. 1506 if (Indexes[I] >= NumElts) 1507 return nullptr; 1508 } 1509 1510 auto *ShuffleMask = ConstantDataVector::get(II.getContext(), 1511 makeArrayRef(Indexes)); 1512 auto *V1 = II.getArgOperand(0); 1513 auto *V2 = Constant::getNullValue(V1->getType()); 1514 return Builder.CreateShuffleVector(V1, V2, ShuffleMask); 1515 } 1516 1517 /// Convert a vector load intrinsic into a simple llvm load instruction. 1518 /// This is beneficial when the underlying object being addressed comes 1519 /// from a constant, since we get constant-folding for free. 1520 static Value *simplifyNeonVld1(const IntrinsicInst &II, 1521 unsigned MemAlign, 1522 InstCombiner::BuilderTy &Builder) { 1523 auto *IntrAlign = dyn_cast<ConstantInt>(II.getArgOperand(1)); 1524 1525 if (!IntrAlign) 1526 return nullptr; 1527 1528 unsigned Alignment = IntrAlign->getLimitedValue() < MemAlign ? 1529 MemAlign : IntrAlign->getLimitedValue(); 1530 1531 if (!isPowerOf2_32(Alignment)) 1532 return nullptr; 1533 1534 auto *BCastInst = Builder.CreateBitCast(II.getArgOperand(0), 1535 PointerType::get(II.getType(), 0)); 1536 return Builder.CreateAlignedLoad(II.getType(), BCastInst, Alignment); 1537 } 1538 1539 // Returns true iff the 2 intrinsics have the same operands, limiting the 1540 // comparison to the first NumOperands. 1541 static bool haveSameOperands(const IntrinsicInst &I, const IntrinsicInst &E, 1542 unsigned NumOperands) { 1543 assert(I.getNumArgOperands() >= NumOperands && "Not enough operands"); 1544 assert(E.getNumArgOperands() >= NumOperands && "Not enough operands"); 1545 for (unsigned i = 0; i < NumOperands; i++) 1546 if (I.getArgOperand(i) != E.getArgOperand(i)) 1547 return false; 1548 return true; 1549 } 1550 1551 // Remove trivially empty start/end intrinsic ranges, i.e. a start 1552 // immediately followed by an end (ignoring debuginfo or other 1553 // start/end intrinsics in between). As this handles only the most trivial 1554 // cases, tracking the nesting level is not needed: 1555 // 1556 // call @llvm.foo.start(i1 0) ; &I 1557 // call @llvm.foo.start(i1 0) 1558 // call @llvm.foo.end(i1 0) ; This one will not be skipped: it will be removed 1559 // call @llvm.foo.end(i1 0) 1560 static bool removeTriviallyEmptyRange(IntrinsicInst &I, unsigned StartID, 1561 unsigned EndID, InstCombiner &IC) { 1562 assert(I.getIntrinsicID() == StartID && 1563 "Start intrinsic does not have expected ID"); 1564 BasicBlock::iterator BI(I), BE(I.getParent()->end()); 1565 for (++BI; BI != BE; ++BI) { 1566 if (auto *E = dyn_cast<IntrinsicInst>(BI)) { 1567 if (isa<DbgInfoIntrinsic>(E) || E->getIntrinsicID() == StartID) 1568 continue; 1569 if (E->getIntrinsicID() == EndID && 1570 haveSameOperands(I, *E, E->getNumArgOperands())) { 1571 IC.eraseInstFromFunction(*E); 1572 IC.eraseInstFromFunction(I); 1573 return true; 1574 } 1575 } 1576 break; 1577 } 1578 1579 return false; 1580 } 1581 1582 // Convert NVVM intrinsics to target-generic LLVM code where possible. 1583 static Instruction *SimplifyNVVMIntrinsic(IntrinsicInst *II, InstCombiner &IC) { 1584 // Each NVVM intrinsic we can simplify can be replaced with one of: 1585 // 1586 // * an LLVM intrinsic, 1587 // * an LLVM cast operation, 1588 // * an LLVM binary operation, or 1589 // * ad-hoc LLVM IR for the particular operation. 1590 1591 // Some transformations are only valid when the module's 1592 // flush-denormals-to-zero (ftz) setting is true/false, whereas other 1593 // transformations are valid regardless of the module's ftz setting. 1594 enum FtzRequirementTy { 1595 FTZ_Any, // Any ftz setting is ok. 1596 FTZ_MustBeOn, // Transformation is valid only if ftz is on. 1597 FTZ_MustBeOff, // Transformation is valid only if ftz is off. 1598 }; 1599 // Classes of NVVM intrinsics that can't be replaced one-to-one with a 1600 // target-generic intrinsic, cast op, or binary op but that we can nonetheless 1601 // simplify. 1602 enum SpecialCase { 1603 SPC_Reciprocal, 1604 }; 1605 1606 // SimplifyAction is a poor-man's variant (plus an additional flag) that 1607 // represents how to replace an NVVM intrinsic with target-generic LLVM IR. 1608 struct SimplifyAction { 1609 // Invariant: At most one of these Optionals has a value. 1610 Optional<Intrinsic::ID> IID; 1611 Optional<Instruction::CastOps> CastOp; 1612 Optional<Instruction::BinaryOps> BinaryOp; 1613 Optional<SpecialCase> Special; 1614 1615 FtzRequirementTy FtzRequirement = FTZ_Any; 1616 1617 SimplifyAction() = default; 1618 1619 SimplifyAction(Intrinsic::ID IID, FtzRequirementTy FtzReq) 1620 : IID(IID), FtzRequirement(FtzReq) {} 1621 1622 // Cast operations don't have anything to do with FTZ, so we skip that 1623 // argument. 1624 SimplifyAction(Instruction::CastOps CastOp) : CastOp(CastOp) {} 1625 1626 SimplifyAction(Instruction::BinaryOps BinaryOp, FtzRequirementTy FtzReq) 1627 : BinaryOp(BinaryOp), FtzRequirement(FtzReq) {} 1628 1629 SimplifyAction(SpecialCase Special, FtzRequirementTy FtzReq) 1630 : Special(Special), FtzRequirement(FtzReq) {} 1631 }; 1632 1633 // Try to generate a SimplifyAction describing how to replace our 1634 // IntrinsicInstr with target-generic LLVM IR. 1635 const SimplifyAction Action = [II]() -> SimplifyAction { 1636 switch (II->getIntrinsicID()) { 1637 // NVVM intrinsics that map directly to LLVM intrinsics. 1638 case Intrinsic::nvvm_ceil_d: 1639 return {Intrinsic::ceil, FTZ_Any}; 1640 case Intrinsic::nvvm_ceil_f: 1641 return {Intrinsic::ceil, FTZ_MustBeOff}; 1642 case Intrinsic::nvvm_ceil_ftz_f: 1643 return {Intrinsic::ceil, FTZ_MustBeOn}; 1644 case Intrinsic::nvvm_fabs_d: 1645 return {Intrinsic::fabs, FTZ_Any}; 1646 case Intrinsic::nvvm_fabs_f: 1647 return {Intrinsic::fabs, FTZ_MustBeOff}; 1648 case Intrinsic::nvvm_fabs_ftz_f: 1649 return {Intrinsic::fabs, FTZ_MustBeOn}; 1650 case Intrinsic::nvvm_floor_d: 1651 return {Intrinsic::floor, FTZ_Any}; 1652 case Intrinsic::nvvm_floor_f: 1653 return {Intrinsic::floor, FTZ_MustBeOff}; 1654 case Intrinsic::nvvm_floor_ftz_f: 1655 return {Intrinsic::floor, FTZ_MustBeOn}; 1656 case Intrinsic::nvvm_fma_rn_d: 1657 return {Intrinsic::fma, FTZ_Any}; 1658 case Intrinsic::nvvm_fma_rn_f: 1659 return {Intrinsic::fma, FTZ_MustBeOff}; 1660 case Intrinsic::nvvm_fma_rn_ftz_f: 1661 return {Intrinsic::fma, FTZ_MustBeOn}; 1662 case Intrinsic::nvvm_fmax_d: 1663 return {Intrinsic::maxnum, FTZ_Any}; 1664 case Intrinsic::nvvm_fmax_f: 1665 return {Intrinsic::maxnum, FTZ_MustBeOff}; 1666 case Intrinsic::nvvm_fmax_ftz_f: 1667 return {Intrinsic::maxnum, FTZ_MustBeOn}; 1668 case Intrinsic::nvvm_fmin_d: 1669 return {Intrinsic::minnum, FTZ_Any}; 1670 case Intrinsic::nvvm_fmin_f: 1671 return {Intrinsic::minnum, FTZ_MustBeOff}; 1672 case Intrinsic::nvvm_fmin_ftz_f: 1673 return {Intrinsic::minnum, FTZ_MustBeOn}; 1674 case Intrinsic::nvvm_round_d: 1675 return {Intrinsic::round, FTZ_Any}; 1676 case Intrinsic::nvvm_round_f: 1677 return {Intrinsic::round, FTZ_MustBeOff}; 1678 case Intrinsic::nvvm_round_ftz_f: 1679 return {Intrinsic::round, FTZ_MustBeOn}; 1680 case Intrinsic::nvvm_sqrt_rn_d: 1681 return {Intrinsic::sqrt, FTZ_Any}; 1682 case Intrinsic::nvvm_sqrt_f: 1683 // nvvm_sqrt_f is a special case. For most intrinsics, foo_ftz_f is the 1684 // ftz version, and foo_f is the non-ftz version. But nvvm_sqrt_f adopts 1685 // the ftz-ness of the surrounding code. sqrt_rn_f and sqrt_rn_ftz_f are 1686 // the versions with explicit ftz-ness. 1687 return {Intrinsic::sqrt, FTZ_Any}; 1688 case Intrinsic::nvvm_sqrt_rn_f: 1689 return {Intrinsic::sqrt, FTZ_MustBeOff}; 1690 case Intrinsic::nvvm_sqrt_rn_ftz_f: 1691 return {Intrinsic::sqrt, FTZ_MustBeOn}; 1692 case Intrinsic::nvvm_trunc_d: 1693 return {Intrinsic::trunc, FTZ_Any}; 1694 case Intrinsic::nvvm_trunc_f: 1695 return {Intrinsic::trunc, FTZ_MustBeOff}; 1696 case Intrinsic::nvvm_trunc_ftz_f: 1697 return {Intrinsic::trunc, FTZ_MustBeOn}; 1698 1699 // NVVM intrinsics that map to LLVM cast operations. 1700 // 1701 // Note that llvm's target-generic conversion operators correspond to the rz 1702 // (round to zero) versions of the nvvm conversion intrinsics, even though 1703 // most everything else here uses the rn (round to nearest even) nvvm ops. 1704 case Intrinsic::nvvm_d2i_rz: 1705 case Intrinsic::nvvm_f2i_rz: 1706 case Intrinsic::nvvm_d2ll_rz: 1707 case Intrinsic::nvvm_f2ll_rz: 1708 return {Instruction::FPToSI}; 1709 case Intrinsic::nvvm_d2ui_rz: 1710 case Intrinsic::nvvm_f2ui_rz: 1711 case Intrinsic::nvvm_d2ull_rz: 1712 case Intrinsic::nvvm_f2ull_rz: 1713 return {Instruction::FPToUI}; 1714 case Intrinsic::nvvm_i2d_rz: 1715 case Intrinsic::nvvm_i2f_rz: 1716 case Intrinsic::nvvm_ll2d_rz: 1717 case Intrinsic::nvvm_ll2f_rz: 1718 return {Instruction::SIToFP}; 1719 case Intrinsic::nvvm_ui2d_rz: 1720 case Intrinsic::nvvm_ui2f_rz: 1721 case Intrinsic::nvvm_ull2d_rz: 1722 case Intrinsic::nvvm_ull2f_rz: 1723 return {Instruction::UIToFP}; 1724 1725 // NVVM intrinsics that map to LLVM binary ops. 1726 case Intrinsic::nvvm_add_rn_d: 1727 return {Instruction::FAdd, FTZ_Any}; 1728 case Intrinsic::nvvm_add_rn_f: 1729 return {Instruction::FAdd, FTZ_MustBeOff}; 1730 case Intrinsic::nvvm_add_rn_ftz_f: 1731 return {Instruction::FAdd, FTZ_MustBeOn}; 1732 case Intrinsic::nvvm_mul_rn_d: 1733 return {Instruction::FMul, FTZ_Any}; 1734 case Intrinsic::nvvm_mul_rn_f: 1735 return {Instruction::FMul, FTZ_MustBeOff}; 1736 case Intrinsic::nvvm_mul_rn_ftz_f: 1737 return {Instruction::FMul, FTZ_MustBeOn}; 1738 case Intrinsic::nvvm_div_rn_d: 1739 return {Instruction::FDiv, FTZ_Any}; 1740 case Intrinsic::nvvm_div_rn_f: 1741 return {Instruction::FDiv, FTZ_MustBeOff}; 1742 case Intrinsic::nvvm_div_rn_ftz_f: 1743 return {Instruction::FDiv, FTZ_MustBeOn}; 1744 1745 // The remainder of cases are NVVM intrinsics that map to LLVM idioms, but 1746 // need special handling. 1747 // 1748 // We seem to be missing intrinsics for rcp.approx.{ftz.}f32, which is just 1749 // as well. 1750 case Intrinsic::nvvm_rcp_rn_d: 1751 return {SPC_Reciprocal, FTZ_Any}; 1752 case Intrinsic::nvvm_rcp_rn_f: 1753 return {SPC_Reciprocal, FTZ_MustBeOff}; 1754 case Intrinsic::nvvm_rcp_rn_ftz_f: 1755 return {SPC_Reciprocal, FTZ_MustBeOn}; 1756 1757 // We do not currently simplify intrinsics that give an approximate answer. 1758 // These include: 1759 // 1760 // - nvvm_cos_approx_{f,ftz_f} 1761 // - nvvm_ex2_approx_{d,f,ftz_f} 1762 // - nvvm_lg2_approx_{d,f,ftz_f} 1763 // - nvvm_sin_approx_{f,ftz_f} 1764 // - nvvm_sqrt_approx_{f,ftz_f} 1765 // - nvvm_rsqrt_approx_{d,f,ftz_f} 1766 // - nvvm_div_approx_{ftz_d,ftz_f,f} 1767 // - nvvm_rcp_approx_ftz_d 1768 // 1769 // Ideally we'd encode them as e.g. "fast call @llvm.cos", where "fast" 1770 // means that fastmath is enabled in the intrinsic. Unfortunately only 1771 // binary operators (currently) have a fastmath bit in SelectionDAG, so this 1772 // information gets lost and we can't select on it. 1773 // 1774 // TODO: div and rcp are lowered to a binary op, so these we could in theory 1775 // lower them to "fast fdiv". 1776 1777 default: 1778 return {}; 1779 } 1780 }(); 1781 1782 // If Action.FtzRequirementTy is not satisfied by the module's ftz state, we 1783 // can bail out now. (Notice that in the case that IID is not an NVVM 1784 // intrinsic, we don't have to look up any module metadata, as 1785 // FtzRequirementTy will be FTZ_Any.) 1786 if (Action.FtzRequirement != FTZ_Any) { 1787 bool FtzEnabled = 1788 II->getFunction()->getFnAttribute("nvptx-f32ftz").getValueAsString() == 1789 "true"; 1790 1791 if (FtzEnabled != (Action.FtzRequirement == FTZ_MustBeOn)) 1792 return nullptr; 1793 } 1794 1795 // Simplify to target-generic intrinsic. 1796 if (Action.IID) { 1797 SmallVector<Value *, 4> Args(II->arg_operands()); 1798 // All the target-generic intrinsics currently of interest to us have one 1799 // type argument, equal to that of the nvvm intrinsic's argument. 1800 Type *Tys[] = {II->getArgOperand(0)->getType()}; 1801 return CallInst::Create( 1802 Intrinsic::getDeclaration(II->getModule(), *Action.IID, Tys), Args); 1803 } 1804 1805 // Simplify to target-generic binary op. 1806 if (Action.BinaryOp) 1807 return BinaryOperator::Create(*Action.BinaryOp, II->getArgOperand(0), 1808 II->getArgOperand(1), II->getName()); 1809 1810 // Simplify to target-generic cast op. 1811 if (Action.CastOp) 1812 return CastInst::Create(*Action.CastOp, II->getArgOperand(0), II->getType(), 1813 II->getName()); 1814 1815 // All that's left are the special cases. 1816 if (!Action.Special) 1817 return nullptr; 1818 1819 switch (*Action.Special) { 1820 case SPC_Reciprocal: 1821 // Simplify reciprocal. 1822 return BinaryOperator::Create( 1823 Instruction::FDiv, ConstantFP::get(II->getArgOperand(0)->getType(), 1), 1824 II->getArgOperand(0), II->getName()); 1825 } 1826 llvm_unreachable("All SpecialCase enumerators should be handled in switch."); 1827 } 1828 1829 Instruction *InstCombiner::visitVAStartInst(VAStartInst &I) { 1830 removeTriviallyEmptyRange(I, Intrinsic::vastart, Intrinsic::vaend, *this); 1831 return nullptr; 1832 } 1833 1834 Instruction *InstCombiner::visitVACopyInst(VACopyInst &I) { 1835 removeTriviallyEmptyRange(I, Intrinsic::vacopy, Intrinsic::vaend, *this); 1836 return nullptr; 1837 } 1838 1839 static Instruction *canonicalizeConstantArg0ToArg1(CallInst &Call) { 1840 assert(Call.getNumArgOperands() > 1 && "Need at least 2 args to swap"); 1841 Value *Arg0 = Call.getArgOperand(0), *Arg1 = Call.getArgOperand(1); 1842 if (isa<Constant>(Arg0) && !isa<Constant>(Arg1)) { 1843 Call.setArgOperand(0, Arg1); 1844 Call.setArgOperand(1, Arg0); 1845 return &Call; 1846 } 1847 return nullptr; 1848 } 1849 1850 Instruction *InstCombiner::foldIntrinsicWithOverflowCommon(IntrinsicInst *II) { 1851 OverflowCheckFlavor OCF = 1852 IntrinsicIDToOverflowCheckFlavor(II->getIntrinsicID()); 1853 assert(OCF != OCF_INVALID && "unexpected!"); 1854 1855 Value *OperationResult = nullptr; 1856 Constant *OverflowResult = nullptr; 1857 if (OptimizeOverflowCheck(OCF, II->getArgOperand(0), II->getArgOperand(1), 1858 *II, OperationResult, OverflowResult)) 1859 return CreateOverflowTuple(II, OperationResult, OverflowResult); 1860 return nullptr; 1861 } 1862 1863 /// CallInst simplification. This mostly only handles folding of intrinsic 1864 /// instructions. For normal calls, it allows visitCallBase to do the heavy 1865 /// lifting. 1866 Instruction *InstCombiner::visitCallInst(CallInst &CI) { 1867 if (Value *V = SimplifyCall(&CI, SQ.getWithInstruction(&CI))) 1868 return replaceInstUsesWith(CI, V); 1869 1870 if (isFreeCall(&CI, &TLI)) 1871 return visitFree(CI); 1872 1873 // If the caller function is nounwind, mark the call as nounwind, even if the 1874 // callee isn't. 1875 if (CI.getFunction()->doesNotThrow() && !CI.doesNotThrow()) { 1876 CI.setDoesNotThrow(); 1877 return &CI; 1878 } 1879 1880 IntrinsicInst *II = dyn_cast<IntrinsicInst>(&CI); 1881 if (!II) return visitCallBase(CI); 1882 1883 // Intrinsics cannot occur in an invoke or a callbr, so handle them here 1884 // instead of in visitCallBase. 1885 if (auto *MI = dyn_cast<AnyMemIntrinsic>(II)) { 1886 bool Changed = false; 1887 1888 // memmove/cpy/set of zero bytes is a noop. 1889 if (Constant *NumBytes = dyn_cast<Constant>(MI->getLength())) { 1890 if (NumBytes->isNullValue()) 1891 return eraseInstFromFunction(CI); 1892 1893 if (ConstantInt *CI = dyn_cast<ConstantInt>(NumBytes)) 1894 if (CI->getZExtValue() == 1) { 1895 // Replace the instruction with just byte operations. We would 1896 // transform other cases to loads/stores, but we don't know if 1897 // alignment is sufficient. 1898 } 1899 } 1900 1901 // No other transformations apply to volatile transfers. 1902 if (auto *M = dyn_cast<MemIntrinsic>(MI)) 1903 if (M->isVolatile()) 1904 return nullptr; 1905 1906 // If we have a memmove and the source operation is a constant global, 1907 // then the source and dest pointers can't alias, so we can change this 1908 // into a call to memcpy. 1909 if (auto *MMI = dyn_cast<AnyMemMoveInst>(MI)) { 1910 if (GlobalVariable *GVSrc = dyn_cast<GlobalVariable>(MMI->getSource())) 1911 if (GVSrc->isConstant()) { 1912 Module *M = CI.getModule(); 1913 Intrinsic::ID MemCpyID = 1914 isa<AtomicMemMoveInst>(MMI) 1915 ? Intrinsic::memcpy_element_unordered_atomic 1916 : Intrinsic::memcpy; 1917 Type *Tys[3] = { CI.getArgOperand(0)->getType(), 1918 CI.getArgOperand(1)->getType(), 1919 CI.getArgOperand(2)->getType() }; 1920 CI.setCalledFunction(Intrinsic::getDeclaration(M, MemCpyID, Tys)); 1921 Changed = true; 1922 } 1923 } 1924 1925 if (AnyMemTransferInst *MTI = dyn_cast<AnyMemTransferInst>(MI)) { 1926 // memmove(x,x,size) -> noop. 1927 if (MTI->getSource() == MTI->getDest()) 1928 return eraseInstFromFunction(CI); 1929 } 1930 1931 // If we can determine a pointer alignment that is bigger than currently 1932 // set, update the alignment. 1933 if (auto *MTI = dyn_cast<AnyMemTransferInst>(MI)) { 1934 if (Instruction *I = SimplifyAnyMemTransfer(MTI)) 1935 return I; 1936 } else if (auto *MSI = dyn_cast<AnyMemSetInst>(MI)) { 1937 if (Instruction *I = SimplifyAnyMemSet(MSI)) 1938 return I; 1939 } 1940 1941 if (Changed) return II; 1942 } 1943 1944 // For vector result intrinsics, use the generic demanded vector support. 1945 if (II->getType()->isVectorTy()) { 1946 auto VWidth = II->getType()->getVectorNumElements(); 1947 APInt UndefElts(VWidth, 0); 1948 APInt AllOnesEltMask(APInt::getAllOnesValue(VWidth)); 1949 if (Value *V = SimplifyDemandedVectorElts(II, AllOnesEltMask, UndefElts)) { 1950 if (V != II) 1951 return replaceInstUsesWith(*II, V); 1952 return II; 1953 } 1954 } 1955 1956 if (Instruction *I = SimplifyNVVMIntrinsic(II, *this)) 1957 return I; 1958 1959 auto SimplifyDemandedVectorEltsLow = [this](Value *Op, unsigned Width, 1960 unsigned DemandedWidth) { 1961 APInt UndefElts(Width, 0); 1962 APInt DemandedElts = APInt::getLowBitsSet(Width, DemandedWidth); 1963 return SimplifyDemandedVectorElts(Op, DemandedElts, UndefElts); 1964 }; 1965 1966 switch (II->getIntrinsicID()) { 1967 default: break; 1968 case Intrinsic::objectsize: 1969 if (Value *V = lowerObjectSizeCall(II, DL, &TLI, /*MustSucceed=*/false)) 1970 return replaceInstUsesWith(CI, V); 1971 return nullptr; 1972 case Intrinsic::bswap: { 1973 Value *IIOperand = II->getArgOperand(0); 1974 Value *X = nullptr; 1975 1976 // bswap(trunc(bswap(x))) -> trunc(lshr(x, c)) 1977 if (match(IIOperand, m_Trunc(m_BSwap(m_Value(X))))) { 1978 unsigned C = X->getType()->getPrimitiveSizeInBits() - 1979 IIOperand->getType()->getPrimitiveSizeInBits(); 1980 Value *CV = ConstantInt::get(X->getType(), C); 1981 Value *V = Builder.CreateLShr(X, CV); 1982 return new TruncInst(V, IIOperand->getType()); 1983 } 1984 break; 1985 } 1986 case Intrinsic::masked_load: 1987 if (Value *SimplifiedMaskedOp = simplifyMaskedLoad(*II)) 1988 return replaceInstUsesWith(CI, SimplifiedMaskedOp); 1989 break; 1990 case Intrinsic::masked_store: 1991 return simplifyMaskedStore(*II); 1992 case Intrinsic::masked_gather: 1993 return simplifyMaskedGather(*II); 1994 case Intrinsic::masked_scatter: 1995 return simplifyMaskedScatter(*II); 1996 case Intrinsic::launder_invariant_group: 1997 case Intrinsic::strip_invariant_group: 1998 if (auto *SkippedBarrier = simplifyInvariantGroupIntrinsic(*II, *this)) 1999 return replaceInstUsesWith(*II, SkippedBarrier); 2000 break; 2001 case Intrinsic::powi: 2002 if (ConstantInt *Power = dyn_cast<ConstantInt>(II->getArgOperand(1))) { 2003 // 0 and 1 are handled in instsimplify 2004 2005 // powi(x, -1) -> 1/x 2006 if (Power->isMinusOne()) 2007 return BinaryOperator::CreateFDiv(ConstantFP::get(CI.getType(), 1.0), 2008 II->getArgOperand(0)); 2009 // powi(x, 2) -> x*x 2010 if (Power->equalsInt(2)) 2011 return BinaryOperator::CreateFMul(II->getArgOperand(0), 2012 II->getArgOperand(0)); 2013 } 2014 break; 2015 2016 case Intrinsic::cttz: 2017 case Intrinsic::ctlz: 2018 if (auto *I = foldCttzCtlz(*II, *this)) 2019 return I; 2020 break; 2021 2022 case Intrinsic::ctpop: 2023 if (auto *I = foldCtpop(*II, *this)) 2024 return I; 2025 break; 2026 2027 case Intrinsic::fshl: 2028 case Intrinsic::fshr: { 2029 Value *Op0 = II->getArgOperand(0), *Op1 = II->getArgOperand(1); 2030 Type *Ty = II->getType(); 2031 unsigned BitWidth = Ty->getScalarSizeInBits(); 2032 Constant *ShAmtC; 2033 if (match(II->getArgOperand(2), m_Constant(ShAmtC)) && 2034 !isa<ConstantExpr>(ShAmtC) && !ShAmtC->containsConstantExpression()) { 2035 // Canonicalize a shift amount constant operand to modulo the bit-width. 2036 Constant *WidthC = ConstantInt::get(Ty, BitWidth); 2037 Constant *ModuloC = ConstantExpr::getURem(ShAmtC, WidthC); 2038 if (ModuloC != ShAmtC) { 2039 II->setArgOperand(2, ModuloC); 2040 return II; 2041 } 2042 assert(ConstantExpr::getICmp(ICmpInst::ICMP_UGT, WidthC, ShAmtC) == 2043 ConstantInt::getTrue(CmpInst::makeCmpResultType(Ty)) && 2044 "Shift amount expected to be modulo bitwidth"); 2045 2046 // Canonicalize funnel shift right by constant to funnel shift left. This 2047 // is not entirely arbitrary. For historical reasons, the backend may 2048 // recognize rotate left patterns but miss rotate right patterns. 2049 if (II->getIntrinsicID() == Intrinsic::fshr) { 2050 // fshr X, Y, C --> fshl X, Y, (BitWidth - C) 2051 Constant *LeftShiftC = ConstantExpr::getSub(WidthC, ShAmtC); 2052 Module *Mod = II->getModule(); 2053 Function *Fshl = Intrinsic::getDeclaration(Mod, Intrinsic::fshl, Ty); 2054 return CallInst::Create(Fshl, { Op0, Op1, LeftShiftC }); 2055 } 2056 assert(II->getIntrinsicID() == Intrinsic::fshl && 2057 "All funnel shifts by simple constants should go left"); 2058 2059 // fshl(X, 0, C) --> shl X, C 2060 // fshl(X, undef, C) --> shl X, C 2061 if (match(Op1, m_ZeroInt()) || match(Op1, m_Undef())) 2062 return BinaryOperator::CreateShl(Op0, ShAmtC); 2063 2064 // fshl(0, X, C) --> lshr X, (BW-C) 2065 // fshl(undef, X, C) --> lshr X, (BW-C) 2066 if (match(Op0, m_ZeroInt()) || match(Op0, m_Undef())) 2067 return BinaryOperator::CreateLShr(Op1, 2068 ConstantExpr::getSub(WidthC, ShAmtC)); 2069 } 2070 2071 // Left or right might be masked. 2072 if (SimplifyDemandedInstructionBits(*II)) 2073 return &CI; 2074 2075 // The shift amount (operand 2) of a funnel shift is modulo the bitwidth, 2076 // so only the low bits of the shift amount are demanded if the bitwidth is 2077 // a power-of-2. 2078 if (!isPowerOf2_32(BitWidth)) 2079 break; 2080 APInt Op2Demanded = APInt::getLowBitsSet(BitWidth, Log2_32_Ceil(BitWidth)); 2081 KnownBits Op2Known(BitWidth); 2082 if (SimplifyDemandedBits(II, 2, Op2Demanded, Op2Known)) 2083 return &CI; 2084 break; 2085 } 2086 case Intrinsic::uadd_with_overflow: 2087 case Intrinsic::sadd_with_overflow: { 2088 if (Instruction *I = canonicalizeConstantArg0ToArg1(CI)) 2089 return I; 2090 if (Instruction *I = foldIntrinsicWithOverflowCommon(II)) 2091 return I; 2092 2093 // Given 2 constant operands whose sum does not overflow: 2094 // uaddo (X +nuw C0), C1 -> uaddo X, C0 + C1 2095 // saddo (X +nsw C0), C1 -> saddo X, C0 + C1 2096 Value *X; 2097 const APInt *C0, *C1; 2098 Value *Arg0 = II->getArgOperand(0); 2099 Value *Arg1 = II->getArgOperand(1); 2100 bool IsSigned = II->getIntrinsicID() == Intrinsic::sadd_with_overflow; 2101 bool HasNWAdd = IsSigned ? match(Arg0, m_NSWAdd(m_Value(X), m_APInt(C0))) 2102 : match(Arg0, m_NUWAdd(m_Value(X), m_APInt(C0))); 2103 if (HasNWAdd && match(Arg1, m_APInt(C1))) { 2104 bool Overflow; 2105 APInt NewC = 2106 IsSigned ? C1->sadd_ov(*C0, Overflow) : C1->uadd_ov(*C0, Overflow); 2107 if (!Overflow) 2108 return replaceInstUsesWith( 2109 *II, Builder.CreateBinaryIntrinsic( 2110 II->getIntrinsicID(), X, 2111 ConstantInt::get(Arg1->getType(), NewC))); 2112 } 2113 break; 2114 } 2115 2116 case Intrinsic::umul_with_overflow: 2117 case Intrinsic::smul_with_overflow: 2118 if (Instruction *I = canonicalizeConstantArg0ToArg1(CI)) 2119 return I; 2120 LLVM_FALLTHROUGH; 2121 2122 case Intrinsic::usub_with_overflow: 2123 if (Instruction *I = foldIntrinsicWithOverflowCommon(II)) 2124 return I; 2125 break; 2126 2127 case Intrinsic::ssub_with_overflow: { 2128 if (Instruction *I = foldIntrinsicWithOverflowCommon(II)) 2129 return I; 2130 2131 Constant *C; 2132 Value *Arg0 = II->getArgOperand(0); 2133 Value *Arg1 = II->getArgOperand(1); 2134 // Given a constant C that is not the minimum signed value 2135 // for an integer of a given bit width: 2136 // 2137 // ssubo X, C -> saddo X, -C 2138 if (match(Arg1, m_Constant(C)) && C->isNotMinSignedValue()) { 2139 Value *NegVal = ConstantExpr::getNeg(C); 2140 // Build a saddo call that is equivalent to the discovered 2141 // ssubo call. 2142 return replaceInstUsesWith( 2143 *II, Builder.CreateBinaryIntrinsic(Intrinsic::sadd_with_overflow, 2144 Arg0, NegVal)); 2145 } 2146 2147 break; 2148 } 2149 2150 case Intrinsic::uadd_sat: 2151 case Intrinsic::sadd_sat: 2152 if (Instruction *I = canonicalizeConstantArg0ToArg1(CI)) 2153 return I; 2154 LLVM_FALLTHROUGH; 2155 case Intrinsic::usub_sat: 2156 case Intrinsic::ssub_sat: { 2157 Value *Arg0 = II->getArgOperand(0); 2158 Value *Arg1 = II->getArgOperand(1); 2159 Intrinsic::ID IID = II->getIntrinsicID(); 2160 2161 // Make use of known overflow information. 2162 OverflowResult OR; 2163 switch (IID) { 2164 default: 2165 llvm_unreachable("Unexpected intrinsic!"); 2166 case Intrinsic::uadd_sat: 2167 OR = computeOverflowForUnsignedAdd(Arg0, Arg1, II); 2168 if (OR == OverflowResult::NeverOverflows) 2169 return BinaryOperator::CreateNUWAdd(Arg0, Arg1); 2170 if (OR == OverflowResult::AlwaysOverflows) 2171 return replaceInstUsesWith(*II, 2172 ConstantInt::getAllOnesValue(II->getType())); 2173 break; 2174 case Intrinsic::usub_sat: 2175 OR = computeOverflowForUnsignedSub(Arg0, Arg1, II); 2176 if (OR == OverflowResult::NeverOverflows) 2177 return BinaryOperator::CreateNUWSub(Arg0, Arg1); 2178 if (OR == OverflowResult::AlwaysOverflows) 2179 return replaceInstUsesWith(*II, 2180 ConstantInt::getNullValue(II->getType())); 2181 break; 2182 case Intrinsic::sadd_sat: 2183 if (willNotOverflowSignedAdd(Arg0, Arg1, *II)) 2184 return BinaryOperator::CreateNSWAdd(Arg0, Arg1); 2185 break; 2186 case Intrinsic::ssub_sat: 2187 if (willNotOverflowSignedSub(Arg0, Arg1, *II)) 2188 return BinaryOperator::CreateNSWSub(Arg0, Arg1); 2189 break; 2190 } 2191 2192 // ssub.sat(X, C) -> sadd.sat(X, -C) if C != MIN 2193 Constant *C; 2194 if (IID == Intrinsic::ssub_sat && match(Arg1, m_Constant(C)) && 2195 C->isNotMinSignedValue()) { 2196 Value *NegVal = ConstantExpr::getNeg(C); 2197 return replaceInstUsesWith( 2198 *II, Builder.CreateBinaryIntrinsic( 2199 Intrinsic::sadd_sat, Arg0, NegVal)); 2200 } 2201 2202 // sat(sat(X + Val2) + Val) -> sat(X + (Val+Val2)) 2203 // sat(sat(X - Val2) - Val) -> sat(X - (Val+Val2)) 2204 // if Val and Val2 have the same sign 2205 if (auto *Other = dyn_cast<IntrinsicInst>(Arg0)) { 2206 Value *X; 2207 const APInt *Val, *Val2; 2208 APInt NewVal; 2209 bool IsUnsigned = 2210 IID == Intrinsic::uadd_sat || IID == Intrinsic::usub_sat; 2211 if (Other->getIntrinsicID() == II->getIntrinsicID() && 2212 match(Arg1, m_APInt(Val)) && 2213 match(Other->getArgOperand(0), m_Value(X)) && 2214 match(Other->getArgOperand(1), m_APInt(Val2))) { 2215 if (IsUnsigned) 2216 NewVal = Val->uadd_sat(*Val2); 2217 else if (Val->isNonNegative() == Val2->isNonNegative()) { 2218 bool Overflow; 2219 NewVal = Val->sadd_ov(*Val2, Overflow); 2220 if (Overflow) { 2221 // Both adds together may add more than SignedMaxValue 2222 // without saturating the final result. 2223 break; 2224 } 2225 } else { 2226 // Cannot fold saturated addition with different signs. 2227 break; 2228 } 2229 2230 return replaceInstUsesWith( 2231 *II, Builder.CreateBinaryIntrinsic( 2232 IID, X, ConstantInt::get(II->getType(), NewVal))); 2233 } 2234 } 2235 break; 2236 } 2237 2238 case Intrinsic::minnum: 2239 case Intrinsic::maxnum: 2240 case Intrinsic::minimum: 2241 case Intrinsic::maximum: { 2242 if (Instruction *I = canonicalizeConstantArg0ToArg1(CI)) 2243 return I; 2244 Value *Arg0 = II->getArgOperand(0); 2245 Value *Arg1 = II->getArgOperand(1); 2246 Intrinsic::ID IID = II->getIntrinsicID(); 2247 Value *X, *Y; 2248 if (match(Arg0, m_FNeg(m_Value(X))) && match(Arg1, m_FNeg(m_Value(Y))) && 2249 (Arg0->hasOneUse() || Arg1->hasOneUse())) { 2250 // If both operands are negated, invert the call and negate the result: 2251 // min(-X, -Y) --> -(max(X, Y)) 2252 // max(-X, -Y) --> -(min(X, Y)) 2253 Intrinsic::ID NewIID; 2254 switch (IID) { 2255 case Intrinsic::maxnum: 2256 NewIID = Intrinsic::minnum; 2257 break; 2258 case Intrinsic::minnum: 2259 NewIID = Intrinsic::maxnum; 2260 break; 2261 case Intrinsic::maximum: 2262 NewIID = Intrinsic::minimum; 2263 break; 2264 case Intrinsic::minimum: 2265 NewIID = Intrinsic::maximum; 2266 break; 2267 default: 2268 llvm_unreachable("unexpected intrinsic ID"); 2269 } 2270 Value *NewCall = Builder.CreateBinaryIntrinsic(NewIID, X, Y, II); 2271 Instruction *FNeg = BinaryOperator::CreateFNeg(NewCall); 2272 FNeg->copyIRFlags(II); 2273 return FNeg; 2274 } 2275 2276 // m(m(X, C2), C1) -> m(X, C) 2277 const APFloat *C1, *C2; 2278 if (auto *M = dyn_cast<IntrinsicInst>(Arg0)) { 2279 if (M->getIntrinsicID() == IID && match(Arg1, m_APFloat(C1)) && 2280 ((match(M->getArgOperand(0), m_Value(X)) && 2281 match(M->getArgOperand(1), m_APFloat(C2))) || 2282 (match(M->getArgOperand(1), m_Value(X)) && 2283 match(M->getArgOperand(0), m_APFloat(C2))))) { 2284 APFloat Res(0.0); 2285 switch (IID) { 2286 case Intrinsic::maxnum: 2287 Res = maxnum(*C1, *C2); 2288 break; 2289 case Intrinsic::minnum: 2290 Res = minnum(*C1, *C2); 2291 break; 2292 case Intrinsic::maximum: 2293 Res = maximum(*C1, *C2); 2294 break; 2295 case Intrinsic::minimum: 2296 Res = minimum(*C1, *C2); 2297 break; 2298 default: 2299 llvm_unreachable("unexpected intrinsic ID"); 2300 } 2301 Instruction *NewCall = Builder.CreateBinaryIntrinsic( 2302 IID, X, ConstantFP::get(Arg0->getType(), Res)); 2303 NewCall->copyIRFlags(II); 2304 return replaceInstUsesWith(*II, NewCall); 2305 } 2306 } 2307 2308 break; 2309 } 2310 case Intrinsic::fmuladd: { 2311 // Canonicalize fast fmuladd to the separate fmul + fadd. 2312 if (II->isFast()) { 2313 BuilderTy::FastMathFlagGuard Guard(Builder); 2314 Builder.setFastMathFlags(II->getFastMathFlags()); 2315 Value *Mul = Builder.CreateFMul(II->getArgOperand(0), 2316 II->getArgOperand(1)); 2317 Value *Add = Builder.CreateFAdd(Mul, II->getArgOperand(2)); 2318 Add->takeName(II); 2319 return replaceInstUsesWith(*II, Add); 2320 } 2321 2322 LLVM_FALLTHROUGH; 2323 } 2324 case Intrinsic::fma: { 2325 if (Instruction *I = canonicalizeConstantArg0ToArg1(CI)) 2326 return I; 2327 2328 // fma fneg(x), fneg(y), z -> fma x, y, z 2329 Value *Src0 = II->getArgOperand(0); 2330 Value *Src1 = II->getArgOperand(1); 2331 Value *X, *Y; 2332 if (match(Src0, m_FNeg(m_Value(X))) && match(Src1, m_FNeg(m_Value(Y)))) { 2333 II->setArgOperand(0, X); 2334 II->setArgOperand(1, Y); 2335 return II; 2336 } 2337 2338 // fma fabs(x), fabs(x), z -> fma x, x, z 2339 if (match(Src0, m_FAbs(m_Value(X))) && 2340 match(Src1, m_FAbs(m_Specific(X)))) { 2341 II->setArgOperand(0, X); 2342 II->setArgOperand(1, X); 2343 return II; 2344 } 2345 2346 // fma x, 1, z -> fadd x, z 2347 if (match(Src1, m_FPOne())) { 2348 auto *FAdd = BinaryOperator::CreateFAdd(Src0, II->getArgOperand(2)); 2349 FAdd->copyFastMathFlags(II); 2350 return FAdd; 2351 } 2352 2353 break; 2354 } 2355 case Intrinsic::fabs: { 2356 Value *Cond; 2357 Constant *LHS, *RHS; 2358 if (match(II->getArgOperand(0), 2359 m_Select(m_Value(Cond), m_Constant(LHS), m_Constant(RHS)))) { 2360 CallInst *Call0 = Builder.CreateCall(II->getCalledFunction(), {LHS}); 2361 CallInst *Call1 = Builder.CreateCall(II->getCalledFunction(), {RHS}); 2362 return SelectInst::Create(Cond, Call0, Call1); 2363 } 2364 2365 LLVM_FALLTHROUGH; 2366 } 2367 case Intrinsic::ceil: 2368 case Intrinsic::floor: 2369 case Intrinsic::round: 2370 case Intrinsic::nearbyint: 2371 case Intrinsic::rint: 2372 case Intrinsic::trunc: { 2373 Value *ExtSrc; 2374 if (match(II->getArgOperand(0), m_OneUse(m_FPExt(m_Value(ExtSrc))))) { 2375 // Narrow the call: intrinsic (fpext x) -> fpext (intrinsic x) 2376 Value *NarrowII = 2377 Builder.CreateUnaryIntrinsic(II->getIntrinsicID(), ExtSrc, II); 2378 return new FPExtInst(NarrowII, II->getType()); 2379 } 2380 break; 2381 } 2382 case Intrinsic::cos: 2383 case Intrinsic::amdgcn_cos: { 2384 Value *X; 2385 Value *Src = II->getArgOperand(0); 2386 if (match(Src, m_FNeg(m_Value(X))) || match(Src, m_FAbs(m_Value(X)))) { 2387 // cos(-x) -> cos(x) 2388 // cos(fabs(x)) -> cos(x) 2389 II->setArgOperand(0, X); 2390 return II; 2391 } 2392 break; 2393 } 2394 case Intrinsic::sin: { 2395 Value *X; 2396 if (match(II->getArgOperand(0), m_OneUse(m_FNeg(m_Value(X))))) { 2397 // sin(-x) --> -sin(x) 2398 Value *NewSin = Builder.CreateUnaryIntrinsic(Intrinsic::sin, X, II); 2399 Instruction *FNeg = BinaryOperator::CreateFNeg(NewSin); 2400 FNeg->copyFastMathFlags(II); 2401 return FNeg; 2402 } 2403 break; 2404 } 2405 case Intrinsic::ppc_altivec_lvx: 2406 case Intrinsic::ppc_altivec_lvxl: 2407 // Turn PPC lvx -> load if the pointer is known aligned. 2408 if (getOrEnforceKnownAlignment(II->getArgOperand(0), 16, DL, II, &AC, 2409 &DT) >= 16) { 2410 Value *Ptr = Builder.CreateBitCast(II->getArgOperand(0), 2411 PointerType::getUnqual(II->getType())); 2412 return new LoadInst(II->getType(), Ptr); 2413 } 2414 break; 2415 case Intrinsic::ppc_vsx_lxvw4x: 2416 case Intrinsic::ppc_vsx_lxvd2x: { 2417 // Turn PPC VSX loads into normal loads. 2418 Value *Ptr = Builder.CreateBitCast(II->getArgOperand(0), 2419 PointerType::getUnqual(II->getType())); 2420 return new LoadInst(II->getType(), Ptr, Twine(""), false, 1); 2421 } 2422 case Intrinsic::ppc_altivec_stvx: 2423 case Intrinsic::ppc_altivec_stvxl: 2424 // Turn stvx -> store if the pointer is known aligned. 2425 if (getOrEnforceKnownAlignment(II->getArgOperand(1), 16, DL, II, &AC, 2426 &DT) >= 16) { 2427 Type *OpPtrTy = 2428 PointerType::getUnqual(II->getArgOperand(0)->getType()); 2429 Value *Ptr = Builder.CreateBitCast(II->getArgOperand(1), OpPtrTy); 2430 return new StoreInst(II->getArgOperand(0), Ptr); 2431 } 2432 break; 2433 case Intrinsic::ppc_vsx_stxvw4x: 2434 case Intrinsic::ppc_vsx_stxvd2x: { 2435 // Turn PPC VSX stores into normal stores. 2436 Type *OpPtrTy = PointerType::getUnqual(II->getArgOperand(0)->getType()); 2437 Value *Ptr = Builder.CreateBitCast(II->getArgOperand(1), OpPtrTy); 2438 return new StoreInst(II->getArgOperand(0), Ptr, false, 1); 2439 } 2440 case Intrinsic::ppc_qpx_qvlfs: 2441 // Turn PPC QPX qvlfs -> load if the pointer is known aligned. 2442 if (getOrEnforceKnownAlignment(II->getArgOperand(0), 16, DL, II, &AC, 2443 &DT) >= 16) { 2444 Type *VTy = VectorType::get(Builder.getFloatTy(), 2445 II->getType()->getVectorNumElements()); 2446 Value *Ptr = Builder.CreateBitCast(II->getArgOperand(0), 2447 PointerType::getUnqual(VTy)); 2448 Value *Load = Builder.CreateLoad(VTy, Ptr); 2449 return new FPExtInst(Load, II->getType()); 2450 } 2451 break; 2452 case Intrinsic::ppc_qpx_qvlfd: 2453 // Turn PPC QPX qvlfd -> load if the pointer is known aligned. 2454 if (getOrEnforceKnownAlignment(II->getArgOperand(0), 32, DL, II, &AC, 2455 &DT) >= 32) { 2456 Value *Ptr = Builder.CreateBitCast(II->getArgOperand(0), 2457 PointerType::getUnqual(II->getType())); 2458 return new LoadInst(II->getType(), Ptr); 2459 } 2460 break; 2461 case Intrinsic::ppc_qpx_qvstfs: 2462 // Turn PPC QPX qvstfs -> store if the pointer is known aligned. 2463 if (getOrEnforceKnownAlignment(II->getArgOperand(1), 16, DL, II, &AC, 2464 &DT) >= 16) { 2465 Type *VTy = VectorType::get(Builder.getFloatTy(), 2466 II->getArgOperand(0)->getType()->getVectorNumElements()); 2467 Value *TOp = Builder.CreateFPTrunc(II->getArgOperand(0), VTy); 2468 Type *OpPtrTy = PointerType::getUnqual(VTy); 2469 Value *Ptr = Builder.CreateBitCast(II->getArgOperand(1), OpPtrTy); 2470 return new StoreInst(TOp, Ptr); 2471 } 2472 break; 2473 case Intrinsic::ppc_qpx_qvstfd: 2474 // Turn PPC QPX qvstfd -> store if the pointer is known aligned. 2475 if (getOrEnforceKnownAlignment(II->getArgOperand(1), 32, DL, II, &AC, 2476 &DT) >= 32) { 2477 Type *OpPtrTy = 2478 PointerType::getUnqual(II->getArgOperand(0)->getType()); 2479 Value *Ptr = Builder.CreateBitCast(II->getArgOperand(1), OpPtrTy); 2480 return new StoreInst(II->getArgOperand(0), Ptr); 2481 } 2482 break; 2483 2484 case Intrinsic::x86_bmi_bextr_32: 2485 case Intrinsic::x86_bmi_bextr_64: 2486 case Intrinsic::x86_tbm_bextri_u32: 2487 case Intrinsic::x86_tbm_bextri_u64: 2488 // If the RHS is a constant we can try some simplifications. 2489 if (auto *C = dyn_cast<ConstantInt>(II->getArgOperand(1))) { 2490 uint64_t Shift = C->getZExtValue(); 2491 uint64_t Length = (Shift >> 8) & 0xff; 2492 Shift &= 0xff; 2493 unsigned BitWidth = II->getType()->getIntegerBitWidth(); 2494 // If the length is 0 or the shift is out of range, replace with zero. 2495 if (Length == 0 || Shift >= BitWidth) 2496 return replaceInstUsesWith(CI, ConstantInt::get(II->getType(), 0)); 2497 // If the LHS is also a constant, we can completely constant fold this. 2498 if (auto *InC = dyn_cast<ConstantInt>(II->getArgOperand(0))) { 2499 uint64_t Result = InC->getZExtValue() >> Shift; 2500 if (Length > BitWidth) 2501 Length = BitWidth; 2502 Result &= maskTrailingOnes<uint64_t>(Length); 2503 return replaceInstUsesWith(CI, ConstantInt::get(II->getType(), Result)); 2504 } 2505 // TODO should we turn this into 'and' if shift is 0? Or 'shl' if we 2506 // are only masking bits that a shift already cleared? 2507 } 2508 break; 2509 2510 case Intrinsic::x86_bmi_bzhi_32: 2511 case Intrinsic::x86_bmi_bzhi_64: 2512 // If the RHS is a constant we can try some simplifications. 2513 if (auto *C = dyn_cast<ConstantInt>(II->getArgOperand(1))) { 2514 uint64_t Index = C->getZExtValue() & 0xff; 2515 unsigned BitWidth = II->getType()->getIntegerBitWidth(); 2516 if (Index >= BitWidth) 2517 return replaceInstUsesWith(CI, II->getArgOperand(0)); 2518 if (Index == 0) 2519 return replaceInstUsesWith(CI, ConstantInt::get(II->getType(), 0)); 2520 // If the LHS is also a constant, we can completely constant fold this. 2521 if (auto *InC = dyn_cast<ConstantInt>(II->getArgOperand(0))) { 2522 uint64_t Result = InC->getZExtValue(); 2523 Result &= maskTrailingOnes<uint64_t>(Index); 2524 return replaceInstUsesWith(CI, ConstantInt::get(II->getType(), Result)); 2525 } 2526 // TODO should we convert this to an AND if the RHS is constant? 2527 } 2528 break; 2529 2530 case Intrinsic::x86_vcvtph2ps_128: 2531 case Intrinsic::x86_vcvtph2ps_256: { 2532 auto Arg = II->getArgOperand(0); 2533 auto ArgType = cast<VectorType>(Arg->getType()); 2534 auto RetType = cast<VectorType>(II->getType()); 2535 unsigned ArgWidth = ArgType->getNumElements(); 2536 unsigned RetWidth = RetType->getNumElements(); 2537 assert(RetWidth <= ArgWidth && "Unexpected input/return vector widths"); 2538 assert(ArgType->isIntOrIntVectorTy() && 2539 ArgType->getScalarSizeInBits() == 16 && 2540 "CVTPH2PS input type should be 16-bit integer vector"); 2541 assert(RetType->getScalarType()->isFloatTy() && 2542 "CVTPH2PS output type should be 32-bit float vector"); 2543 2544 // Constant folding: Convert to generic half to single conversion. 2545 if (isa<ConstantAggregateZero>(Arg)) 2546 return replaceInstUsesWith(*II, ConstantAggregateZero::get(RetType)); 2547 2548 if (isa<ConstantDataVector>(Arg)) { 2549 auto VectorHalfAsShorts = Arg; 2550 if (RetWidth < ArgWidth) { 2551 SmallVector<uint32_t, 8> SubVecMask; 2552 for (unsigned i = 0; i != RetWidth; ++i) 2553 SubVecMask.push_back((int)i); 2554 VectorHalfAsShorts = Builder.CreateShuffleVector( 2555 Arg, UndefValue::get(ArgType), SubVecMask); 2556 } 2557 2558 auto VectorHalfType = 2559 VectorType::get(Type::getHalfTy(II->getContext()), RetWidth); 2560 auto VectorHalfs = 2561 Builder.CreateBitCast(VectorHalfAsShorts, VectorHalfType); 2562 auto VectorFloats = Builder.CreateFPExt(VectorHalfs, RetType); 2563 return replaceInstUsesWith(*II, VectorFloats); 2564 } 2565 2566 // We only use the lowest lanes of the argument. 2567 if (Value *V = SimplifyDemandedVectorEltsLow(Arg, ArgWidth, RetWidth)) { 2568 II->setArgOperand(0, V); 2569 return II; 2570 } 2571 break; 2572 } 2573 2574 case Intrinsic::x86_sse_cvtss2si: 2575 case Intrinsic::x86_sse_cvtss2si64: 2576 case Intrinsic::x86_sse_cvttss2si: 2577 case Intrinsic::x86_sse_cvttss2si64: 2578 case Intrinsic::x86_sse2_cvtsd2si: 2579 case Intrinsic::x86_sse2_cvtsd2si64: 2580 case Intrinsic::x86_sse2_cvttsd2si: 2581 case Intrinsic::x86_sse2_cvttsd2si64: 2582 case Intrinsic::x86_avx512_vcvtss2si32: 2583 case Intrinsic::x86_avx512_vcvtss2si64: 2584 case Intrinsic::x86_avx512_vcvtss2usi32: 2585 case Intrinsic::x86_avx512_vcvtss2usi64: 2586 case Intrinsic::x86_avx512_vcvtsd2si32: 2587 case Intrinsic::x86_avx512_vcvtsd2si64: 2588 case Intrinsic::x86_avx512_vcvtsd2usi32: 2589 case Intrinsic::x86_avx512_vcvtsd2usi64: 2590 case Intrinsic::x86_avx512_cvttss2si: 2591 case Intrinsic::x86_avx512_cvttss2si64: 2592 case Intrinsic::x86_avx512_cvttss2usi: 2593 case Intrinsic::x86_avx512_cvttss2usi64: 2594 case Intrinsic::x86_avx512_cvttsd2si: 2595 case Intrinsic::x86_avx512_cvttsd2si64: 2596 case Intrinsic::x86_avx512_cvttsd2usi: 2597 case Intrinsic::x86_avx512_cvttsd2usi64: { 2598 // These intrinsics only demand the 0th element of their input vectors. If 2599 // we can simplify the input based on that, do so now. 2600 Value *Arg = II->getArgOperand(0); 2601 unsigned VWidth = Arg->getType()->getVectorNumElements(); 2602 if (Value *V = SimplifyDemandedVectorEltsLow(Arg, VWidth, 1)) { 2603 II->setArgOperand(0, V); 2604 return II; 2605 } 2606 break; 2607 } 2608 2609 case Intrinsic::x86_sse41_round_ps: 2610 case Intrinsic::x86_sse41_round_pd: 2611 case Intrinsic::x86_avx_round_ps_256: 2612 case Intrinsic::x86_avx_round_pd_256: 2613 case Intrinsic::x86_avx512_mask_rndscale_ps_128: 2614 case Intrinsic::x86_avx512_mask_rndscale_ps_256: 2615 case Intrinsic::x86_avx512_mask_rndscale_ps_512: 2616 case Intrinsic::x86_avx512_mask_rndscale_pd_128: 2617 case Intrinsic::x86_avx512_mask_rndscale_pd_256: 2618 case Intrinsic::x86_avx512_mask_rndscale_pd_512: 2619 case Intrinsic::x86_avx512_mask_rndscale_ss: 2620 case Intrinsic::x86_avx512_mask_rndscale_sd: 2621 if (Value *V = simplifyX86round(*II, Builder)) 2622 return replaceInstUsesWith(*II, V); 2623 break; 2624 2625 case Intrinsic::x86_mmx_pmovmskb: 2626 case Intrinsic::x86_sse_movmsk_ps: 2627 case Intrinsic::x86_sse2_movmsk_pd: 2628 case Intrinsic::x86_sse2_pmovmskb_128: 2629 case Intrinsic::x86_avx_movmsk_pd_256: 2630 case Intrinsic::x86_avx_movmsk_ps_256: 2631 case Intrinsic::x86_avx2_pmovmskb: 2632 if (Value *V = simplifyX86movmsk(*II, Builder)) 2633 return replaceInstUsesWith(*II, V); 2634 break; 2635 2636 case Intrinsic::x86_sse_comieq_ss: 2637 case Intrinsic::x86_sse_comige_ss: 2638 case Intrinsic::x86_sse_comigt_ss: 2639 case Intrinsic::x86_sse_comile_ss: 2640 case Intrinsic::x86_sse_comilt_ss: 2641 case Intrinsic::x86_sse_comineq_ss: 2642 case Intrinsic::x86_sse_ucomieq_ss: 2643 case Intrinsic::x86_sse_ucomige_ss: 2644 case Intrinsic::x86_sse_ucomigt_ss: 2645 case Intrinsic::x86_sse_ucomile_ss: 2646 case Intrinsic::x86_sse_ucomilt_ss: 2647 case Intrinsic::x86_sse_ucomineq_ss: 2648 case Intrinsic::x86_sse2_comieq_sd: 2649 case Intrinsic::x86_sse2_comige_sd: 2650 case Intrinsic::x86_sse2_comigt_sd: 2651 case Intrinsic::x86_sse2_comile_sd: 2652 case Intrinsic::x86_sse2_comilt_sd: 2653 case Intrinsic::x86_sse2_comineq_sd: 2654 case Intrinsic::x86_sse2_ucomieq_sd: 2655 case Intrinsic::x86_sse2_ucomige_sd: 2656 case Intrinsic::x86_sse2_ucomigt_sd: 2657 case Intrinsic::x86_sse2_ucomile_sd: 2658 case Intrinsic::x86_sse2_ucomilt_sd: 2659 case Intrinsic::x86_sse2_ucomineq_sd: 2660 case Intrinsic::x86_avx512_vcomi_ss: 2661 case Intrinsic::x86_avx512_vcomi_sd: 2662 case Intrinsic::x86_avx512_mask_cmp_ss: 2663 case Intrinsic::x86_avx512_mask_cmp_sd: { 2664 // These intrinsics only demand the 0th element of their input vectors. If 2665 // we can simplify the input based on that, do so now. 2666 bool MadeChange = false; 2667 Value *Arg0 = II->getArgOperand(0); 2668 Value *Arg1 = II->getArgOperand(1); 2669 unsigned VWidth = Arg0->getType()->getVectorNumElements(); 2670 if (Value *V = SimplifyDemandedVectorEltsLow(Arg0, VWidth, 1)) { 2671 II->setArgOperand(0, V); 2672 MadeChange = true; 2673 } 2674 if (Value *V = SimplifyDemandedVectorEltsLow(Arg1, VWidth, 1)) { 2675 II->setArgOperand(1, V); 2676 MadeChange = true; 2677 } 2678 if (MadeChange) 2679 return II; 2680 break; 2681 } 2682 case Intrinsic::x86_avx512_cmp_pd_128: 2683 case Intrinsic::x86_avx512_cmp_pd_256: 2684 case Intrinsic::x86_avx512_cmp_pd_512: 2685 case Intrinsic::x86_avx512_cmp_ps_128: 2686 case Intrinsic::x86_avx512_cmp_ps_256: 2687 case Intrinsic::x86_avx512_cmp_ps_512: { 2688 // Folding cmp(sub(a,b),0) -> cmp(a,b) and cmp(0,sub(a,b)) -> cmp(b,a) 2689 Value *Arg0 = II->getArgOperand(0); 2690 Value *Arg1 = II->getArgOperand(1); 2691 bool Arg0IsZero = match(Arg0, m_PosZeroFP()); 2692 if (Arg0IsZero) 2693 std::swap(Arg0, Arg1); 2694 Value *A, *B; 2695 // This fold requires only the NINF(not +/- inf) since inf minus 2696 // inf is nan. 2697 // NSZ(No Signed Zeros) is not needed because zeros of any sign are 2698 // equal for both compares. 2699 // NNAN is not needed because nans compare the same for both compares. 2700 // The compare intrinsic uses the above assumptions and therefore 2701 // doesn't require additional flags. 2702 if ((match(Arg0, m_OneUse(m_FSub(m_Value(A), m_Value(B)))) && 2703 match(Arg1, m_PosZeroFP()) && isa<Instruction>(Arg0) && 2704 cast<Instruction>(Arg0)->getFastMathFlags().noInfs())) { 2705 if (Arg0IsZero) 2706 std::swap(A, B); 2707 II->setArgOperand(0, A); 2708 II->setArgOperand(1, B); 2709 return II; 2710 } 2711 break; 2712 } 2713 2714 case Intrinsic::x86_avx512_add_ps_512: 2715 case Intrinsic::x86_avx512_div_ps_512: 2716 case Intrinsic::x86_avx512_mul_ps_512: 2717 case Intrinsic::x86_avx512_sub_ps_512: 2718 case Intrinsic::x86_avx512_add_pd_512: 2719 case Intrinsic::x86_avx512_div_pd_512: 2720 case Intrinsic::x86_avx512_mul_pd_512: 2721 case Intrinsic::x86_avx512_sub_pd_512: 2722 // If the rounding mode is CUR_DIRECTION(4) we can turn these into regular 2723 // IR operations. 2724 if (auto *R = dyn_cast<ConstantInt>(II->getArgOperand(2))) { 2725 if (R->getValue() == 4) { 2726 Value *Arg0 = II->getArgOperand(0); 2727 Value *Arg1 = II->getArgOperand(1); 2728 2729 Value *V; 2730 switch (II->getIntrinsicID()) { 2731 default: llvm_unreachable("Case stmts out of sync!"); 2732 case Intrinsic::x86_avx512_add_ps_512: 2733 case Intrinsic::x86_avx512_add_pd_512: 2734 V = Builder.CreateFAdd(Arg0, Arg1); 2735 break; 2736 case Intrinsic::x86_avx512_sub_ps_512: 2737 case Intrinsic::x86_avx512_sub_pd_512: 2738 V = Builder.CreateFSub(Arg0, Arg1); 2739 break; 2740 case Intrinsic::x86_avx512_mul_ps_512: 2741 case Intrinsic::x86_avx512_mul_pd_512: 2742 V = Builder.CreateFMul(Arg0, Arg1); 2743 break; 2744 case Intrinsic::x86_avx512_div_ps_512: 2745 case Intrinsic::x86_avx512_div_pd_512: 2746 V = Builder.CreateFDiv(Arg0, Arg1); 2747 break; 2748 } 2749 2750 return replaceInstUsesWith(*II, V); 2751 } 2752 } 2753 break; 2754 2755 case Intrinsic::x86_avx512_mask_add_ss_round: 2756 case Intrinsic::x86_avx512_mask_div_ss_round: 2757 case Intrinsic::x86_avx512_mask_mul_ss_round: 2758 case Intrinsic::x86_avx512_mask_sub_ss_round: 2759 case Intrinsic::x86_avx512_mask_add_sd_round: 2760 case Intrinsic::x86_avx512_mask_div_sd_round: 2761 case Intrinsic::x86_avx512_mask_mul_sd_round: 2762 case Intrinsic::x86_avx512_mask_sub_sd_round: 2763 // If the rounding mode is CUR_DIRECTION(4) we can turn these into regular 2764 // IR operations. 2765 if (auto *R = dyn_cast<ConstantInt>(II->getArgOperand(4))) { 2766 if (R->getValue() == 4) { 2767 // Extract the element as scalars. 2768 Value *Arg0 = II->getArgOperand(0); 2769 Value *Arg1 = II->getArgOperand(1); 2770 Value *LHS = Builder.CreateExtractElement(Arg0, (uint64_t)0); 2771 Value *RHS = Builder.CreateExtractElement(Arg1, (uint64_t)0); 2772 2773 Value *V; 2774 switch (II->getIntrinsicID()) { 2775 default: llvm_unreachable("Case stmts out of sync!"); 2776 case Intrinsic::x86_avx512_mask_add_ss_round: 2777 case Intrinsic::x86_avx512_mask_add_sd_round: 2778 V = Builder.CreateFAdd(LHS, RHS); 2779 break; 2780 case Intrinsic::x86_avx512_mask_sub_ss_round: 2781 case Intrinsic::x86_avx512_mask_sub_sd_round: 2782 V = Builder.CreateFSub(LHS, RHS); 2783 break; 2784 case Intrinsic::x86_avx512_mask_mul_ss_round: 2785 case Intrinsic::x86_avx512_mask_mul_sd_round: 2786 V = Builder.CreateFMul(LHS, RHS); 2787 break; 2788 case Intrinsic::x86_avx512_mask_div_ss_round: 2789 case Intrinsic::x86_avx512_mask_div_sd_round: 2790 V = Builder.CreateFDiv(LHS, RHS); 2791 break; 2792 } 2793 2794 // Handle the masking aspect of the intrinsic. 2795 Value *Mask = II->getArgOperand(3); 2796 auto *C = dyn_cast<ConstantInt>(Mask); 2797 // We don't need a select if we know the mask bit is a 1. 2798 if (!C || !C->getValue()[0]) { 2799 // Cast the mask to an i1 vector and then extract the lowest element. 2800 auto *MaskTy = VectorType::get(Builder.getInt1Ty(), 2801 cast<IntegerType>(Mask->getType())->getBitWidth()); 2802 Mask = Builder.CreateBitCast(Mask, MaskTy); 2803 Mask = Builder.CreateExtractElement(Mask, (uint64_t)0); 2804 // Extract the lowest element from the passthru operand. 2805 Value *Passthru = Builder.CreateExtractElement(II->getArgOperand(2), 2806 (uint64_t)0); 2807 V = Builder.CreateSelect(Mask, V, Passthru); 2808 } 2809 2810 // Insert the result back into the original argument 0. 2811 V = Builder.CreateInsertElement(Arg0, V, (uint64_t)0); 2812 2813 return replaceInstUsesWith(*II, V); 2814 } 2815 } 2816 break; 2817 2818 case Intrinsic::x86_sse41_round_ss: 2819 case Intrinsic::x86_sse41_round_sd: { 2820 if (Value *V = simplifyX86round(*II, Builder)) 2821 return replaceInstUsesWith(*II, V); 2822 break; 2823 } 2824 2825 // Constant fold ashr( <A x Bi>, Ci ). 2826 // Constant fold lshr( <A x Bi>, Ci ). 2827 // Constant fold shl( <A x Bi>, Ci ). 2828 case Intrinsic::x86_sse2_psrai_d: 2829 case Intrinsic::x86_sse2_psrai_w: 2830 case Intrinsic::x86_avx2_psrai_d: 2831 case Intrinsic::x86_avx2_psrai_w: 2832 case Intrinsic::x86_avx512_psrai_q_128: 2833 case Intrinsic::x86_avx512_psrai_q_256: 2834 case Intrinsic::x86_avx512_psrai_d_512: 2835 case Intrinsic::x86_avx512_psrai_q_512: 2836 case Intrinsic::x86_avx512_psrai_w_512: 2837 case Intrinsic::x86_sse2_psrli_d: 2838 case Intrinsic::x86_sse2_psrli_q: 2839 case Intrinsic::x86_sse2_psrli_w: 2840 case Intrinsic::x86_avx2_psrli_d: 2841 case Intrinsic::x86_avx2_psrli_q: 2842 case Intrinsic::x86_avx2_psrli_w: 2843 case Intrinsic::x86_avx512_psrli_d_512: 2844 case Intrinsic::x86_avx512_psrli_q_512: 2845 case Intrinsic::x86_avx512_psrli_w_512: 2846 case Intrinsic::x86_sse2_pslli_d: 2847 case Intrinsic::x86_sse2_pslli_q: 2848 case Intrinsic::x86_sse2_pslli_w: 2849 case Intrinsic::x86_avx2_pslli_d: 2850 case Intrinsic::x86_avx2_pslli_q: 2851 case Intrinsic::x86_avx2_pslli_w: 2852 case Intrinsic::x86_avx512_pslli_d_512: 2853 case Intrinsic::x86_avx512_pslli_q_512: 2854 case Intrinsic::x86_avx512_pslli_w_512: 2855 if (Value *V = simplifyX86immShift(*II, Builder)) 2856 return replaceInstUsesWith(*II, V); 2857 break; 2858 2859 case Intrinsic::x86_sse2_psra_d: 2860 case Intrinsic::x86_sse2_psra_w: 2861 case Intrinsic::x86_avx2_psra_d: 2862 case Intrinsic::x86_avx2_psra_w: 2863 case Intrinsic::x86_avx512_psra_q_128: 2864 case Intrinsic::x86_avx512_psra_q_256: 2865 case Intrinsic::x86_avx512_psra_d_512: 2866 case Intrinsic::x86_avx512_psra_q_512: 2867 case Intrinsic::x86_avx512_psra_w_512: 2868 case Intrinsic::x86_sse2_psrl_d: 2869 case Intrinsic::x86_sse2_psrl_q: 2870 case Intrinsic::x86_sse2_psrl_w: 2871 case Intrinsic::x86_avx2_psrl_d: 2872 case Intrinsic::x86_avx2_psrl_q: 2873 case Intrinsic::x86_avx2_psrl_w: 2874 case Intrinsic::x86_avx512_psrl_d_512: 2875 case Intrinsic::x86_avx512_psrl_q_512: 2876 case Intrinsic::x86_avx512_psrl_w_512: 2877 case Intrinsic::x86_sse2_psll_d: 2878 case Intrinsic::x86_sse2_psll_q: 2879 case Intrinsic::x86_sse2_psll_w: 2880 case Intrinsic::x86_avx2_psll_d: 2881 case Intrinsic::x86_avx2_psll_q: 2882 case Intrinsic::x86_avx2_psll_w: 2883 case Intrinsic::x86_avx512_psll_d_512: 2884 case Intrinsic::x86_avx512_psll_q_512: 2885 case Intrinsic::x86_avx512_psll_w_512: { 2886 if (Value *V = simplifyX86immShift(*II, Builder)) 2887 return replaceInstUsesWith(*II, V); 2888 2889 // SSE2/AVX2 uses only the first 64-bits of the 128-bit vector 2890 // operand to compute the shift amount. 2891 Value *Arg1 = II->getArgOperand(1); 2892 assert(Arg1->getType()->getPrimitiveSizeInBits() == 128 && 2893 "Unexpected packed shift size"); 2894 unsigned VWidth = Arg1->getType()->getVectorNumElements(); 2895 2896 if (Value *V = SimplifyDemandedVectorEltsLow(Arg1, VWidth, VWidth / 2)) { 2897 II->setArgOperand(1, V); 2898 return II; 2899 } 2900 break; 2901 } 2902 2903 case Intrinsic::x86_avx2_psllv_d: 2904 case Intrinsic::x86_avx2_psllv_d_256: 2905 case Intrinsic::x86_avx2_psllv_q: 2906 case Intrinsic::x86_avx2_psllv_q_256: 2907 case Intrinsic::x86_avx512_psllv_d_512: 2908 case Intrinsic::x86_avx512_psllv_q_512: 2909 case Intrinsic::x86_avx512_psllv_w_128: 2910 case Intrinsic::x86_avx512_psllv_w_256: 2911 case Intrinsic::x86_avx512_psllv_w_512: 2912 case Intrinsic::x86_avx2_psrav_d: 2913 case Intrinsic::x86_avx2_psrav_d_256: 2914 case Intrinsic::x86_avx512_psrav_q_128: 2915 case Intrinsic::x86_avx512_psrav_q_256: 2916 case Intrinsic::x86_avx512_psrav_d_512: 2917 case Intrinsic::x86_avx512_psrav_q_512: 2918 case Intrinsic::x86_avx512_psrav_w_128: 2919 case Intrinsic::x86_avx512_psrav_w_256: 2920 case Intrinsic::x86_avx512_psrav_w_512: 2921 case Intrinsic::x86_avx2_psrlv_d: 2922 case Intrinsic::x86_avx2_psrlv_d_256: 2923 case Intrinsic::x86_avx2_psrlv_q: 2924 case Intrinsic::x86_avx2_psrlv_q_256: 2925 case Intrinsic::x86_avx512_psrlv_d_512: 2926 case Intrinsic::x86_avx512_psrlv_q_512: 2927 case Intrinsic::x86_avx512_psrlv_w_128: 2928 case Intrinsic::x86_avx512_psrlv_w_256: 2929 case Intrinsic::x86_avx512_psrlv_w_512: 2930 if (Value *V = simplifyX86varShift(*II, Builder)) 2931 return replaceInstUsesWith(*II, V); 2932 break; 2933 2934 case Intrinsic::x86_sse2_packssdw_128: 2935 case Intrinsic::x86_sse2_packsswb_128: 2936 case Intrinsic::x86_avx2_packssdw: 2937 case Intrinsic::x86_avx2_packsswb: 2938 case Intrinsic::x86_avx512_packssdw_512: 2939 case Intrinsic::x86_avx512_packsswb_512: 2940 if (Value *V = simplifyX86pack(*II, Builder, true)) 2941 return replaceInstUsesWith(*II, V); 2942 break; 2943 2944 case Intrinsic::x86_sse2_packuswb_128: 2945 case Intrinsic::x86_sse41_packusdw: 2946 case Intrinsic::x86_avx2_packusdw: 2947 case Intrinsic::x86_avx2_packuswb: 2948 case Intrinsic::x86_avx512_packusdw_512: 2949 case Intrinsic::x86_avx512_packuswb_512: 2950 if (Value *V = simplifyX86pack(*II, Builder, false)) 2951 return replaceInstUsesWith(*II, V); 2952 break; 2953 2954 case Intrinsic::x86_pclmulqdq: 2955 case Intrinsic::x86_pclmulqdq_256: 2956 case Intrinsic::x86_pclmulqdq_512: { 2957 if (auto *C = dyn_cast<ConstantInt>(II->getArgOperand(2))) { 2958 unsigned Imm = C->getZExtValue(); 2959 2960 bool MadeChange = false; 2961 Value *Arg0 = II->getArgOperand(0); 2962 Value *Arg1 = II->getArgOperand(1); 2963 unsigned VWidth = Arg0->getType()->getVectorNumElements(); 2964 2965 APInt UndefElts1(VWidth, 0); 2966 APInt DemandedElts1 = APInt::getSplat(VWidth, 2967 APInt(2, (Imm & 0x01) ? 2 : 1)); 2968 if (Value *V = SimplifyDemandedVectorElts(Arg0, DemandedElts1, 2969 UndefElts1)) { 2970 II->setArgOperand(0, V); 2971 MadeChange = true; 2972 } 2973 2974 APInt UndefElts2(VWidth, 0); 2975 APInt DemandedElts2 = APInt::getSplat(VWidth, 2976 APInt(2, (Imm & 0x10) ? 2 : 1)); 2977 if (Value *V = SimplifyDemandedVectorElts(Arg1, DemandedElts2, 2978 UndefElts2)) { 2979 II->setArgOperand(1, V); 2980 MadeChange = true; 2981 } 2982 2983 // If either input elements are undef, the result is zero. 2984 if (DemandedElts1.isSubsetOf(UndefElts1) || 2985 DemandedElts2.isSubsetOf(UndefElts2)) 2986 return replaceInstUsesWith(*II, 2987 ConstantAggregateZero::get(II->getType())); 2988 2989 if (MadeChange) 2990 return II; 2991 } 2992 break; 2993 } 2994 2995 case Intrinsic::x86_sse41_insertps: 2996 if (Value *V = simplifyX86insertps(*II, Builder)) 2997 return replaceInstUsesWith(*II, V); 2998 break; 2999 3000 case Intrinsic::x86_sse4a_extrq: { 3001 Value *Op0 = II->getArgOperand(0); 3002 Value *Op1 = II->getArgOperand(1); 3003 unsigned VWidth0 = Op0->getType()->getVectorNumElements(); 3004 unsigned VWidth1 = Op1->getType()->getVectorNumElements(); 3005 assert(Op0->getType()->getPrimitiveSizeInBits() == 128 && 3006 Op1->getType()->getPrimitiveSizeInBits() == 128 && VWidth0 == 2 && 3007 VWidth1 == 16 && "Unexpected operand sizes"); 3008 3009 // See if we're dealing with constant values. 3010 Constant *C1 = dyn_cast<Constant>(Op1); 3011 ConstantInt *CILength = 3012 C1 ? dyn_cast_or_null<ConstantInt>(C1->getAggregateElement((unsigned)0)) 3013 : nullptr; 3014 ConstantInt *CIIndex = 3015 C1 ? dyn_cast_or_null<ConstantInt>(C1->getAggregateElement((unsigned)1)) 3016 : nullptr; 3017 3018 // Attempt to simplify to a constant, shuffle vector or EXTRQI call. 3019 if (Value *V = simplifyX86extrq(*II, Op0, CILength, CIIndex, Builder)) 3020 return replaceInstUsesWith(*II, V); 3021 3022 // EXTRQ only uses the lowest 64-bits of the first 128-bit vector 3023 // operands and the lowest 16-bits of the second. 3024 bool MadeChange = false; 3025 if (Value *V = SimplifyDemandedVectorEltsLow(Op0, VWidth0, 1)) { 3026 II->setArgOperand(0, V); 3027 MadeChange = true; 3028 } 3029 if (Value *V = SimplifyDemandedVectorEltsLow(Op1, VWidth1, 2)) { 3030 II->setArgOperand(1, V); 3031 MadeChange = true; 3032 } 3033 if (MadeChange) 3034 return II; 3035 break; 3036 } 3037 3038 case Intrinsic::x86_sse4a_extrqi: { 3039 // EXTRQI: Extract Length bits starting from Index. Zero pad the remaining 3040 // bits of the lower 64-bits. The upper 64-bits are undefined. 3041 Value *Op0 = II->getArgOperand(0); 3042 unsigned VWidth = Op0->getType()->getVectorNumElements(); 3043 assert(Op0->getType()->getPrimitiveSizeInBits() == 128 && VWidth == 2 && 3044 "Unexpected operand size"); 3045 3046 // See if we're dealing with constant values. 3047 ConstantInt *CILength = dyn_cast<ConstantInt>(II->getArgOperand(1)); 3048 ConstantInt *CIIndex = dyn_cast<ConstantInt>(II->getArgOperand(2)); 3049 3050 // Attempt to simplify to a constant or shuffle vector. 3051 if (Value *V = simplifyX86extrq(*II, Op0, CILength, CIIndex, Builder)) 3052 return replaceInstUsesWith(*II, V); 3053 3054 // EXTRQI only uses the lowest 64-bits of the first 128-bit vector 3055 // operand. 3056 if (Value *V = SimplifyDemandedVectorEltsLow(Op0, VWidth, 1)) { 3057 II->setArgOperand(0, V); 3058 return II; 3059 } 3060 break; 3061 } 3062 3063 case Intrinsic::x86_sse4a_insertq: { 3064 Value *Op0 = II->getArgOperand(0); 3065 Value *Op1 = II->getArgOperand(1); 3066 unsigned VWidth = Op0->getType()->getVectorNumElements(); 3067 assert(Op0->getType()->getPrimitiveSizeInBits() == 128 && 3068 Op1->getType()->getPrimitiveSizeInBits() == 128 && VWidth == 2 && 3069 Op1->getType()->getVectorNumElements() == 2 && 3070 "Unexpected operand size"); 3071 3072 // See if we're dealing with constant values. 3073 Constant *C1 = dyn_cast<Constant>(Op1); 3074 ConstantInt *CI11 = 3075 C1 ? dyn_cast_or_null<ConstantInt>(C1->getAggregateElement((unsigned)1)) 3076 : nullptr; 3077 3078 // Attempt to simplify to a constant, shuffle vector or INSERTQI call. 3079 if (CI11) { 3080 const APInt &V11 = CI11->getValue(); 3081 APInt Len = V11.zextOrTrunc(6); 3082 APInt Idx = V11.lshr(8).zextOrTrunc(6); 3083 if (Value *V = simplifyX86insertq(*II, Op0, Op1, Len, Idx, Builder)) 3084 return replaceInstUsesWith(*II, V); 3085 } 3086 3087 // INSERTQ only uses the lowest 64-bits of the first 128-bit vector 3088 // operand. 3089 if (Value *V = SimplifyDemandedVectorEltsLow(Op0, VWidth, 1)) { 3090 II->setArgOperand(0, V); 3091 return II; 3092 } 3093 break; 3094 } 3095 3096 case Intrinsic::x86_sse4a_insertqi: { 3097 // INSERTQI: Extract lowest Length bits from lower half of second source and 3098 // insert over first source starting at Index bit. The upper 64-bits are 3099 // undefined. 3100 Value *Op0 = II->getArgOperand(0); 3101 Value *Op1 = II->getArgOperand(1); 3102 unsigned VWidth0 = Op0->getType()->getVectorNumElements(); 3103 unsigned VWidth1 = Op1->getType()->getVectorNumElements(); 3104 assert(Op0->getType()->getPrimitiveSizeInBits() == 128 && 3105 Op1->getType()->getPrimitiveSizeInBits() == 128 && VWidth0 == 2 && 3106 VWidth1 == 2 && "Unexpected operand sizes"); 3107 3108 // See if we're dealing with constant values. 3109 ConstantInt *CILength = dyn_cast<ConstantInt>(II->getArgOperand(2)); 3110 ConstantInt *CIIndex = dyn_cast<ConstantInt>(II->getArgOperand(3)); 3111 3112 // Attempt to simplify to a constant or shuffle vector. 3113 if (CILength && CIIndex) { 3114 APInt Len = CILength->getValue().zextOrTrunc(6); 3115 APInt Idx = CIIndex->getValue().zextOrTrunc(6); 3116 if (Value *V = simplifyX86insertq(*II, Op0, Op1, Len, Idx, Builder)) 3117 return replaceInstUsesWith(*II, V); 3118 } 3119 3120 // INSERTQI only uses the lowest 64-bits of the first two 128-bit vector 3121 // operands. 3122 bool MadeChange = false; 3123 if (Value *V = SimplifyDemandedVectorEltsLow(Op0, VWidth0, 1)) { 3124 II->setArgOperand(0, V); 3125 MadeChange = true; 3126 } 3127 if (Value *V = SimplifyDemandedVectorEltsLow(Op1, VWidth1, 1)) { 3128 II->setArgOperand(1, V); 3129 MadeChange = true; 3130 } 3131 if (MadeChange) 3132 return II; 3133 break; 3134 } 3135 3136 case Intrinsic::x86_sse41_pblendvb: 3137 case Intrinsic::x86_sse41_blendvps: 3138 case Intrinsic::x86_sse41_blendvpd: 3139 case Intrinsic::x86_avx_blendv_ps_256: 3140 case Intrinsic::x86_avx_blendv_pd_256: 3141 case Intrinsic::x86_avx2_pblendvb: { 3142 // fold (blend A, A, Mask) -> A 3143 Value *Op0 = II->getArgOperand(0); 3144 Value *Op1 = II->getArgOperand(1); 3145 Value *Mask = II->getArgOperand(2); 3146 if (Op0 == Op1) 3147 return replaceInstUsesWith(CI, Op0); 3148 3149 // Zero Mask - select 1st argument. 3150 if (isa<ConstantAggregateZero>(Mask)) 3151 return replaceInstUsesWith(CI, Op0); 3152 3153 // Constant Mask - select 1st/2nd argument lane based on top bit of mask. 3154 if (auto *ConstantMask = dyn_cast<ConstantDataVector>(Mask)) { 3155 Constant *NewSelector = getNegativeIsTrueBoolVec(ConstantMask); 3156 return SelectInst::Create(NewSelector, Op1, Op0, "blendv"); 3157 } 3158 3159 // Convert to a vector select if we can bypass casts and find a boolean 3160 // vector condition value. 3161 Value *BoolVec; 3162 Mask = peekThroughBitcast(Mask); 3163 if (match(Mask, m_SExt(m_Value(BoolVec))) && 3164 BoolVec->getType()->isVectorTy() && 3165 BoolVec->getType()->getScalarSizeInBits() == 1) { 3166 assert(Mask->getType()->getPrimitiveSizeInBits() == 3167 II->getType()->getPrimitiveSizeInBits() && 3168 "Not expecting mask and operands with different sizes"); 3169 3170 unsigned NumMaskElts = Mask->getType()->getVectorNumElements(); 3171 unsigned NumOperandElts = II->getType()->getVectorNumElements(); 3172 if (NumMaskElts == NumOperandElts) 3173 return SelectInst::Create(BoolVec, Op1, Op0); 3174 3175 // If the mask has less elements than the operands, each mask bit maps to 3176 // multiple elements of the operands. Bitcast back and forth. 3177 if (NumMaskElts < NumOperandElts) { 3178 Value *CastOp0 = Builder.CreateBitCast(Op0, Mask->getType()); 3179 Value *CastOp1 = Builder.CreateBitCast(Op1, Mask->getType()); 3180 Value *Sel = Builder.CreateSelect(BoolVec, CastOp1, CastOp0); 3181 return new BitCastInst(Sel, II->getType()); 3182 } 3183 } 3184 3185 break; 3186 } 3187 3188 case Intrinsic::x86_ssse3_pshuf_b_128: 3189 case Intrinsic::x86_avx2_pshuf_b: 3190 case Intrinsic::x86_avx512_pshuf_b_512: 3191 if (Value *V = simplifyX86pshufb(*II, Builder)) 3192 return replaceInstUsesWith(*II, V); 3193 break; 3194 3195 case Intrinsic::x86_avx_vpermilvar_ps: 3196 case Intrinsic::x86_avx_vpermilvar_ps_256: 3197 case Intrinsic::x86_avx512_vpermilvar_ps_512: 3198 case Intrinsic::x86_avx_vpermilvar_pd: 3199 case Intrinsic::x86_avx_vpermilvar_pd_256: 3200 case Intrinsic::x86_avx512_vpermilvar_pd_512: 3201 if (Value *V = simplifyX86vpermilvar(*II, Builder)) 3202 return replaceInstUsesWith(*II, V); 3203 break; 3204 3205 case Intrinsic::x86_avx2_permd: 3206 case Intrinsic::x86_avx2_permps: 3207 case Intrinsic::x86_avx512_permvar_df_256: 3208 case Intrinsic::x86_avx512_permvar_df_512: 3209 case Intrinsic::x86_avx512_permvar_di_256: 3210 case Intrinsic::x86_avx512_permvar_di_512: 3211 case Intrinsic::x86_avx512_permvar_hi_128: 3212 case Intrinsic::x86_avx512_permvar_hi_256: 3213 case Intrinsic::x86_avx512_permvar_hi_512: 3214 case Intrinsic::x86_avx512_permvar_qi_128: 3215 case Intrinsic::x86_avx512_permvar_qi_256: 3216 case Intrinsic::x86_avx512_permvar_qi_512: 3217 case Intrinsic::x86_avx512_permvar_sf_512: 3218 case Intrinsic::x86_avx512_permvar_si_512: 3219 if (Value *V = simplifyX86vpermv(*II, Builder)) 3220 return replaceInstUsesWith(*II, V); 3221 break; 3222 3223 case Intrinsic::x86_avx_maskload_ps: 3224 case Intrinsic::x86_avx_maskload_pd: 3225 case Intrinsic::x86_avx_maskload_ps_256: 3226 case Intrinsic::x86_avx_maskload_pd_256: 3227 case Intrinsic::x86_avx2_maskload_d: 3228 case Intrinsic::x86_avx2_maskload_q: 3229 case Intrinsic::x86_avx2_maskload_d_256: 3230 case Intrinsic::x86_avx2_maskload_q_256: 3231 if (Instruction *I = simplifyX86MaskedLoad(*II, *this)) 3232 return I; 3233 break; 3234 3235 case Intrinsic::x86_sse2_maskmov_dqu: 3236 case Intrinsic::x86_avx_maskstore_ps: 3237 case Intrinsic::x86_avx_maskstore_pd: 3238 case Intrinsic::x86_avx_maskstore_ps_256: 3239 case Intrinsic::x86_avx_maskstore_pd_256: 3240 case Intrinsic::x86_avx2_maskstore_d: 3241 case Intrinsic::x86_avx2_maskstore_q: 3242 case Intrinsic::x86_avx2_maskstore_d_256: 3243 case Intrinsic::x86_avx2_maskstore_q_256: 3244 if (simplifyX86MaskedStore(*II, *this)) 3245 return nullptr; 3246 break; 3247 3248 case Intrinsic::x86_addcarry_32: 3249 case Intrinsic::x86_addcarry_64: 3250 if (Value *V = simplifyX86addcarry(*II, Builder)) 3251 return replaceInstUsesWith(*II, V); 3252 break; 3253 3254 case Intrinsic::ppc_altivec_vperm: 3255 // Turn vperm(V1,V2,mask) -> shuffle(V1,V2,mask) if mask is a constant. 3256 // Note that ppc_altivec_vperm has a big-endian bias, so when creating 3257 // a vectorshuffle for little endian, we must undo the transformation 3258 // performed on vec_perm in altivec.h. That is, we must complement 3259 // the permutation mask with respect to 31 and reverse the order of 3260 // V1 and V2. 3261 if (Constant *Mask = dyn_cast<Constant>(II->getArgOperand(2))) { 3262 assert(Mask->getType()->getVectorNumElements() == 16 && 3263 "Bad type for intrinsic!"); 3264 3265 // Check that all of the elements are integer constants or undefs. 3266 bool AllEltsOk = true; 3267 for (unsigned i = 0; i != 16; ++i) { 3268 Constant *Elt = Mask->getAggregateElement(i); 3269 if (!Elt || !(isa<ConstantInt>(Elt) || isa<UndefValue>(Elt))) { 3270 AllEltsOk = false; 3271 break; 3272 } 3273 } 3274 3275 if (AllEltsOk) { 3276 // Cast the input vectors to byte vectors. 3277 Value *Op0 = Builder.CreateBitCast(II->getArgOperand(0), 3278 Mask->getType()); 3279 Value *Op1 = Builder.CreateBitCast(II->getArgOperand(1), 3280 Mask->getType()); 3281 Value *Result = UndefValue::get(Op0->getType()); 3282 3283 // Only extract each element once. 3284 Value *ExtractedElts[32]; 3285 memset(ExtractedElts, 0, sizeof(ExtractedElts)); 3286 3287 for (unsigned i = 0; i != 16; ++i) { 3288 if (isa<UndefValue>(Mask->getAggregateElement(i))) 3289 continue; 3290 unsigned Idx = 3291 cast<ConstantInt>(Mask->getAggregateElement(i))->getZExtValue(); 3292 Idx &= 31; // Match the hardware behavior. 3293 if (DL.isLittleEndian()) 3294 Idx = 31 - Idx; 3295 3296 if (!ExtractedElts[Idx]) { 3297 Value *Op0ToUse = (DL.isLittleEndian()) ? Op1 : Op0; 3298 Value *Op1ToUse = (DL.isLittleEndian()) ? Op0 : Op1; 3299 ExtractedElts[Idx] = 3300 Builder.CreateExtractElement(Idx < 16 ? Op0ToUse : Op1ToUse, 3301 Builder.getInt32(Idx&15)); 3302 } 3303 3304 // Insert this value into the result vector. 3305 Result = Builder.CreateInsertElement(Result, ExtractedElts[Idx], 3306 Builder.getInt32(i)); 3307 } 3308 return CastInst::Create(Instruction::BitCast, Result, CI.getType()); 3309 } 3310 } 3311 break; 3312 3313 case Intrinsic::arm_neon_vld1: { 3314 unsigned MemAlign = getKnownAlignment(II->getArgOperand(0), 3315 DL, II, &AC, &DT); 3316 if (Value *V = simplifyNeonVld1(*II, MemAlign, Builder)) 3317 return replaceInstUsesWith(*II, V); 3318 break; 3319 } 3320 3321 case Intrinsic::arm_neon_vld2: 3322 case Intrinsic::arm_neon_vld3: 3323 case Intrinsic::arm_neon_vld4: 3324 case Intrinsic::arm_neon_vld2lane: 3325 case Intrinsic::arm_neon_vld3lane: 3326 case Intrinsic::arm_neon_vld4lane: 3327 case Intrinsic::arm_neon_vst1: 3328 case Intrinsic::arm_neon_vst2: 3329 case Intrinsic::arm_neon_vst3: 3330 case Intrinsic::arm_neon_vst4: 3331 case Intrinsic::arm_neon_vst2lane: 3332 case Intrinsic::arm_neon_vst3lane: 3333 case Intrinsic::arm_neon_vst4lane: { 3334 unsigned MemAlign = 3335 getKnownAlignment(II->getArgOperand(0), DL, II, &AC, &DT); 3336 unsigned AlignArg = II->getNumArgOperands() - 1; 3337 ConstantInt *IntrAlign = dyn_cast<ConstantInt>(II->getArgOperand(AlignArg)); 3338 if (IntrAlign && IntrAlign->getZExtValue() < MemAlign) { 3339 II->setArgOperand(AlignArg, 3340 ConstantInt::get(Type::getInt32Ty(II->getContext()), 3341 MemAlign, false)); 3342 return II; 3343 } 3344 break; 3345 } 3346 3347 case Intrinsic::arm_neon_vtbl1: 3348 case Intrinsic::aarch64_neon_tbl1: 3349 if (Value *V = simplifyNeonTbl1(*II, Builder)) 3350 return replaceInstUsesWith(*II, V); 3351 break; 3352 3353 case Intrinsic::arm_neon_vmulls: 3354 case Intrinsic::arm_neon_vmullu: 3355 case Intrinsic::aarch64_neon_smull: 3356 case Intrinsic::aarch64_neon_umull: { 3357 Value *Arg0 = II->getArgOperand(0); 3358 Value *Arg1 = II->getArgOperand(1); 3359 3360 // Handle mul by zero first: 3361 if (isa<ConstantAggregateZero>(Arg0) || isa<ConstantAggregateZero>(Arg1)) { 3362 return replaceInstUsesWith(CI, ConstantAggregateZero::get(II->getType())); 3363 } 3364 3365 // Check for constant LHS & RHS - in this case we just simplify. 3366 bool Zext = (II->getIntrinsicID() == Intrinsic::arm_neon_vmullu || 3367 II->getIntrinsicID() == Intrinsic::aarch64_neon_umull); 3368 VectorType *NewVT = cast<VectorType>(II->getType()); 3369 if (Constant *CV0 = dyn_cast<Constant>(Arg0)) { 3370 if (Constant *CV1 = dyn_cast<Constant>(Arg1)) { 3371 CV0 = ConstantExpr::getIntegerCast(CV0, NewVT, /*isSigned=*/!Zext); 3372 CV1 = ConstantExpr::getIntegerCast(CV1, NewVT, /*isSigned=*/!Zext); 3373 3374 return replaceInstUsesWith(CI, ConstantExpr::getMul(CV0, CV1)); 3375 } 3376 3377 // Couldn't simplify - canonicalize constant to the RHS. 3378 std::swap(Arg0, Arg1); 3379 } 3380 3381 // Handle mul by one: 3382 if (Constant *CV1 = dyn_cast<Constant>(Arg1)) 3383 if (ConstantInt *Splat = 3384 dyn_cast_or_null<ConstantInt>(CV1->getSplatValue())) 3385 if (Splat->isOne()) 3386 return CastInst::CreateIntegerCast(Arg0, II->getType(), 3387 /*isSigned=*/!Zext); 3388 3389 break; 3390 } 3391 case Intrinsic::arm_neon_aesd: 3392 case Intrinsic::arm_neon_aese: 3393 case Intrinsic::aarch64_crypto_aesd: 3394 case Intrinsic::aarch64_crypto_aese: { 3395 Value *DataArg = II->getArgOperand(0); 3396 Value *KeyArg = II->getArgOperand(1); 3397 3398 // Try to use the builtin XOR in AESE and AESD to eliminate a prior XOR 3399 Value *Data, *Key; 3400 if (match(KeyArg, m_ZeroInt()) && 3401 match(DataArg, m_Xor(m_Value(Data), m_Value(Key)))) { 3402 II->setArgOperand(0, Data); 3403 II->setArgOperand(1, Key); 3404 return II; 3405 } 3406 break; 3407 } 3408 case Intrinsic::amdgcn_rcp: { 3409 Value *Src = II->getArgOperand(0); 3410 3411 // TODO: Move to ConstantFolding/InstSimplify? 3412 if (isa<UndefValue>(Src)) 3413 return replaceInstUsesWith(CI, Src); 3414 3415 if (const ConstantFP *C = dyn_cast<ConstantFP>(Src)) { 3416 const APFloat &ArgVal = C->getValueAPF(); 3417 APFloat Val(ArgVal.getSemantics(), 1.0); 3418 APFloat::opStatus Status = Val.divide(ArgVal, 3419 APFloat::rmNearestTiesToEven); 3420 // Only do this if it was exact and therefore not dependent on the 3421 // rounding mode. 3422 if (Status == APFloat::opOK) 3423 return replaceInstUsesWith(CI, ConstantFP::get(II->getContext(), Val)); 3424 } 3425 3426 break; 3427 } 3428 case Intrinsic::amdgcn_rsq: { 3429 Value *Src = II->getArgOperand(0); 3430 3431 // TODO: Move to ConstantFolding/InstSimplify? 3432 if (isa<UndefValue>(Src)) 3433 return replaceInstUsesWith(CI, Src); 3434 break; 3435 } 3436 case Intrinsic::amdgcn_frexp_mant: 3437 case Intrinsic::amdgcn_frexp_exp: { 3438 Value *Src = II->getArgOperand(0); 3439 if (const ConstantFP *C = dyn_cast<ConstantFP>(Src)) { 3440 int Exp; 3441 APFloat Significand = frexp(C->getValueAPF(), Exp, 3442 APFloat::rmNearestTiesToEven); 3443 3444 if (II->getIntrinsicID() == Intrinsic::amdgcn_frexp_mant) { 3445 return replaceInstUsesWith(CI, ConstantFP::get(II->getContext(), 3446 Significand)); 3447 } 3448 3449 // Match instruction special case behavior. 3450 if (Exp == APFloat::IEK_NaN || Exp == APFloat::IEK_Inf) 3451 Exp = 0; 3452 3453 return replaceInstUsesWith(CI, ConstantInt::get(II->getType(), Exp)); 3454 } 3455 3456 if (isa<UndefValue>(Src)) 3457 return replaceInstUsesWith(CI, UndefValue::get(II->getType())); 3458 3459 break; 3460 } 3461 case Intrinsic::amdgcn_class: { 3462 enum { 3463 S_NAN = 1 << 0, // Signaling NaN 3464 Q_NAN = 1 << 1, // Quiet NaN 3465 N_INFINITY = 1 << 2, // Negative infinity 3466 N_NORMAL = 1 << 3, // Negative normal 3467 N_SUBNORMAL = 1 << 4, // Negative subnormal 3468 N_ZERO = 1 << 5, // Negative zero 3469 P_ZERO = 1 << 6, // Positive zero 3470 P_SUBNORMAL = 1 << 7, // Positive subnormal 3471 P_NORMAL = 1 << 8, // Positive normal 3472 P_INFINITY = 1 << 9 // Positive infinity 3473 }; 3474 3475 const uint32_t FullMask = S_NAN | Q_NAN | N_INFINITY | N_NORMAL | 3476 N_SUBNORMAL | N_ZERO | P_ZERO | P_SUBNORMAL | P_NORMAL | P_INFINITY; 3477 3478 Value *Src0 = II->getArgOperand(0); 3479 Value *Src1 = II->getArgOperand(1); 3480 const ConstantInt *CMask = dyn_cast<ConstantInt>(Src1); 3481 if (!CMask) { 3482 if (isa<UndefValue>(Src0)) 3483 return replaceInstUsesWith(*II, UndefValue::get(II->getType())); 3484 3485 if (isa<UndefValue>(Src1)) 3486 return replaceInstUsesWith(*II, ConstantInt::get(II->getType(), false)); 3487 break; 3488 } 3489 3490 uint32_t Mask = CMask->getZExtValue(); 3491 3492 // If all tests are made, it doesn't matter what the value is. 3493 if ((Mask & FullMask) == FullMask) 3494 return replaceInstUsesWith(*II, ConstantInt::get(II->getType(), true)); 3495 3496 if ((Mask & FullMask) == 0) 3497 return replaceInstUsesWith(*II, ConstantInt::get(II->getType(), false)); 3498 3499 if (Mask == (S_NAN | Q_NAN)) { 3500 // Equivalent of isnan. Replace with standard fcmp. 3501 Value *FCmp = Builder.CreateFCmpUNO(Src0, Src0); 3502 FCmp->takeName(II); 3503 return replaceInstUsesWith(*II, FCmp); 3504 } 3505 3506 if (Mask == (N_ZERO | P_ZERO)) { 3507 // Equivalent of == 0. 3508 Value *FCmp = Builder.CreateFCmpOEQ( 3509 Src0, ConstantFP::get(Src0->getType(), 0.0)); 3510 3511 FCmp->takeName(II); 3512 return replaceInstUsesWith(*II, FCmp); 3513 } 3514 3515 // fp_class (nnan x), qnan|snan|other -> fp_class (nnan x), other 3516 if (((Mask & S_NAN) || (Mask & Q_NAN)) && isKnownNeverNaN(Src0, &TLI)) { 3517 II->setArgOperand(1, ConstantInt::get(Src1->getType(), 3518 Mask & ~(S_NAN | Q_NAN))); 3519 return II; 3520 } 3521 3522 const ConstantFP *CVal = dyn_cast<ConstantFP>(Src0); 3523 if (!CVal) { 3524 if (isa<UndefValue>(Src0)) 3525 return replaceInstUsesWith(*II, UndefValue::get(II->getType())); 3526 3527 // Clamp mask to used bits 3528 if ((Mask & FullMask) != Mask) { 3529 CallInst *NewCall = Builder.CreateCall(II->getCalledFunction(), 3530 { Src0, ConstantInt::get(Src1->getType(), Mask & FullMask) } 3531 ); 3532 3533 NewCall->takeName(II); 3534 return replaceInstUsesWith(*II, NewCall); 3535 } 3536 3537 break; 3538 } 3539 3540 const APFloat &Val = CVal->getValueAPF(); 3541 3542 bool Result = 3543 ((Mask & S_NAN) && Val.isNaN() && Val.isSignaling()) || 3544 ((Mask & Q_NAN) && Val.isNaN() && !Val.isSignaling()) || 3545 ((Mask & N_INFINITY) && Val.isInfinity() && Val.isNegative()) || 3546 ((Mask & N_NORMAL) && Val.isNormal() && Val.isNegative()) || 3547 ((Mask & N_SUBNORMAL) && Val.isDenormal() && Val.isNegative()) || 3548 ((Mask & N_ZERO) && Val.isZero() && Val.isNegative()) || 3549 ((Mask & P_ZERO) && Val.isZero() && !Val.isNegative()) || 3550 ((Mask & P_SUBNORMAL) && Val.isDenormal() && !Val.isNegative()) || 3551 ((Mask & P_NORMAL) && Val.isNormal() && !Val.isNegative()) || 3552 ((Mask & P_INFINITY) && Val.isInfinity() && !Val.isNegative()); 3553 3554 return replaceInstUsesWith(*II, ConstantInt::get(II->getType(), Result)); 3555 } 3556 case Intrinsic::amdgcn_cvt_pkrtz: { 3557 Value *Src0 = II->getArgOperand(0); 3558 Value *Src1 = II->getArgOperand(1); 3559 if (const ConstantFP *C0 = dyn_cast<ConstantFP>(Src0)) { 3560 if (const ConstantFP *C1 = dyn_cast<ConstantFP>(Src1)) { 3561 const fltSemantics &HalfSem 3562 = II->getType()->getScalarType()->getFltSemantics(); 3563 bool LosesInfo; 3564 APFloat Val0 = C0->getValueAPF(); 3565 APFloat Val1 = C1->getValueAPF(); 3566 Val0.convert(HalfSem, APFloat::rmTowardZero, &LosesInfo); 3567 Val1.convert(HalfSem, APFloat::rmTowardZero, &LosesInfo); 3568 3569 Constant *Folded = ConstantVector::get({ 3570 ConstantFP::get(II->getContext(), Val0), 3571 ConstantFP::get(II->getContext(), Val1) }); 3572 return replaceInstUsesWith(*II, Folded); 3573 } 3574 } 3575 3576 if (isa<UndefValue>(Src0) && isa<UndefValue>(Src1)) 3577 return replaceInstUsesWith(*II, UndefValue::get(II->getType())); 3578 3579 break; 3580 } 3581 case Intrinsic::amdgcn_cvt_pknorm_i16: 3582 case Intrinsic::amdgcn_cvt_pknorm_u16: 3583 case Intrinsic::amdgcn_cvt_pk_i16: 3584 case Intrinsic::amdgcn_cvt_pk_u16: { 3585 Value *Src0 = II->getArgOperand(0); 3586 Value *Src1 = II->getArgOperand(1); 3587 3588 if (isa<UndefValue>(Src0) && isa<UndefValue>(Src1)) 3589 return replaceInstUsesWith(*II, UndefValue::get(II->getType())); 3590 3591 break; 3592 } 3593 case Intrinsic::amdgcn_ubfe: 3594 case Intrinsic::amdgcn_sbfe: { 3595 // Decompose simple cases into standard shifts. 3596 Value *Src = II->getArgOperand(0); 3597 if (isa<UndefValue>(Src)) 3598 return replaceInstUsesWith(*II, Src); 3599 3600 unsigned Width; 3601 Type *Ty = II->getType(); 3602 unsigned IntSize = Ty->getIntegerBitWidth(); 3603 3604 ConstantInt *CWidth = dyn_cast<ConstantInt>(II->getArgOperand(2)); 3605 if (CWidth) { 3606 Width = CWidth->getZExtValue(); 3607 if ((Width & (IntSize - 1)) == 0) 3608 return replaceInstUsesWith(*II, ConstantInt::getNullValue(Ty)); 3609 3610 if (Width >= IntSize) { 3611 // Hardware ignores high bits, so remove those. 3612 II->setArgOperand(2, ConstantInt::get(CWidth->getType(), 3613 Width & (IntSize - 1))); 3614 return II; 3615 } 3616 } 3617 3618 unsigned Offset; 3619 ConstantInt *COffset = dyn_cast<ConstantInt>(II->getArgOperand(1)); 3620 if (COffset) { 3621 Offset = COffset->getZExtValue(); 3622 if (Offset >= IntSize) { 3623 II->setArgOperand(1, ConstantInt::get(COffset->getType(), 3624 Offset & (IntSize - 1))); 3625 return II; 3626 } 3627 } 3628 3629 bool Signed = II->getIntrinsicID() == Intrinsic::amdgcn_sbfe; 3630 3631 if (!CWidth || !COffset) 3632 break; 3633 3634 // The case of Width == 0 is handled above, which makes this tranformation 3635 // safe. If Width == 0, then the ashr and lshr instructions become poison 3636 // value since the shift amount would be equal to the bit size. 3637 assert(Width != 0); 3638 3639 // TODO: This allows folding to undef when the hardware has specific 3640 // behavior? 3641 if (Offset + Width < IntSize) { 3642 Value *Shl = Builder.CreateShl(Src, IntSize - Offset - Width); 3643 Value *RightShift = Signed ? Builder.CreateAShr(Shl, IntSize - Width) 3644 : Builder.CreateLShr(Shl, IntSize - Width); 3645 RightShift->takeName(II); 3646 return replaceInstUsesWith(*II, RightShift); 3647 } 3648 3649 Value *RightShift = Signed ? Builder.CreateAShr(Src, Offset) 3650 : Builder.CreateLShr(Src, Offset); 3651 3652 RightShift->takeName(II); 3653 return replaceInstUsesWith(*II, RightShift); 3654 } 3655 case Intrinsic::amdgcn_exp: 3656 case Intrinsic::amdgcn_exp_compr: { 3657 ConstantInt *En = cast<ConstantInt>(II->getArgOperand(1)); 3658 unsigned EnBits = En->getZExtValue(); 3659 if (EnBits == 0xf) 3660 break; // All inputs enabled. 3661 3662 bool IsCompr = II->getIntrinsicID() == Intrinsic::amdgcn_exp_compr; 3663 bool Changed = false; 3664 for (int I = 0; I < (IsCompr ? 2 : 4); ++I) { 3665 if ((!IsCompr && (EnBits & (1 << I)) == 0) || 3666 (IsCompr && ((EnBits & (0x3 << (2 * I))) == 0))) { 3667 Value *Src = II->getArgOperand(I + 2); 3668 if (!isa<UndefValue>(Src)) { 3669 II->setArgOperand(I + 2, UndefValue::get(Src->getType())); 3670 Changed = true; 3671 } 3672 } 3673 } 3674 3675 if (Changed) 3676 return II; 3677 3678 break; 3679 } 3680 case Intrinsic::amdgcn_fmed3: { 3681 // Note this does not preserve proper sNaN behavior if IEEE-mode is enabled 3682 // for the shader. 3683 3684 Value *Src0 = II->getArgOperand(0); 3685 Value *Src1 = II->getArgOperand(1); 3686 Value *Src2 = II->getArgOperand(2); 3687 3688 // Checking for NaN before canonicalization provides better fidelity when 3689 // mapping other operations onto fmed3 since the order of operands is 3690 // unchanged. 3691 CallInst *NewCall = nullptr; 3692 if (match(Src0, m_NaN()) || isa<UndefValue>(Src0)) { 3693 NewCall = Builder.CreateMinNum(Src1, Src2); 3694 } else if (match(Src1, m_NaN()) || isa<UndefValue>(Src1)) { 3695 NewCall = Builder.CreateMinNum(Src0, Src2); 3696 } else if (match(Src2, m_NaN()) || isa<UndefValue>(Src2)) { 3697 NewCall = Builder.CreateMaxNum(Src0, Src1); 3698 } 3699 3700 if (NewCall) { 3701 NewCall->copyFastMathFlags(II); 3702 NewCall->takeName(II); 3703 return replaceInstUsesWith(*II, NewCall); 3704 } 3705 3706 bool Swap = false; 3707 // Canonicalize constants to RHS operands. 3708 // 3709 // fmed3(c0, x, c1) -> fmed3(x, c0, c1) 3710 if (isa<Constant>(Src0) && !isa<Constant>(Src1)) { 3711 std::swap(Src0, Src1); 3712 Swap = true; 3713 } 3714 3715 if (isa<Constant>(Src1) && !isa<Constant>(Src2)) { 3716 std::swap(Src1, Src2); 3717 Swap = true; 3718 } 3719 3720 if (isa<Constant>(Src0) && !isa<Constant>(Src1)) { 3721 std::swap(Src0, Src1); 3722 Swap = true; 3723 } 3724 3725 if (Swap) { 3726 II->setArgOperand(0, Src0); 3727 II->setArgOperand(1, Src1); 3728 II->setArgOperand(2, Src2); 3729 return II; 3730 } 3731 3732 if (const ConstantFP *C0 = dyn_cast<ConstantFP>(Src0)) { 3733 if (const ConstantFP *C1 = dyn_cast<ConstantFP>(Src1)) { 3734 if (const ConstantFP *C2 = dyn_cast<ConstantFP>(Src2)) { 3735 APFloat Result = fmed3AMDGCN(C0->getValueAPF(), C1->getValueAPF(), 3736 C2->getValueAPF()); 3737 return replaceInstUsesWith(*II, 3738 ConstantFP::get(Builder.getContext(), Result)); 3739 } 3740 } 3741 } 3742 3743 break; 3744 } 3745 case Intrinsic::amdgcn_icmp: 3746 case Intrinsic::amdgcn_fcmp: { 3747 const ConstantInt *CC = cast<ConstantInt>(II->getArgOperand(2)); 3748 // Guard against invalid arguments. 3749 int64_t CCVal = CC->getZExtValue(); 3750 bool IsInteger = II->getIntrinsicID() == Intrinsic::amdgcn_icmp; 3751 if ((IsInteger && (CCVal < CmpInst::FIRST_ICMP_PREDICATE || 3752 CCVal > CmpInst::LAST_ICMP_PREDICATE)) || 3753 (!IsInteger && (CCVal < CmpInst::FIRST_FCMP_PREDICATE || 3754 CCVal > CmpInst::LAST_FCMP_PREDICATE))) 3755 break; 3756 3757 Value *Src0 = II->getArgOperand(0); 3758 Value *Src1 = II->getArgOperand(1); 3759 3760 if (auto *CSrc0 = dyn_cast<Constant>(Src0)) { 3761 if (auto *CSrc1 = dyn_cast<Constant>(Src1)) { 3762 Constant *CCmp = ConstantExpr::getCompare(CCVal, CSrc0, CSrc1); 3763 if (CCmp->isNullValue()) { 3764 return replaceInstUsesWith( 3765 *II, ConstantExpr::getSExt(CCmp, II->getType())); 3766 } 3767 3768 // The result of V_ICMP/V_FCMP assembly instructions (which this 3769 // intrinsic exposes) is one bit per thread, masked with the EXEC 3770 // register (which contains the bitmask of live threads). So a 3771 // comparison that always returns true is the same as a read of the 3772 // EXEC register. 3773 Function *NewF = Intrinsic::getDeclaration( 3774 II->getModule(), Intrinsic::read_register, II->getType()); 3775 Metadata *MDArgs[] = {MDString::get(II->getContext(), "exec")}; 3776 MDNode *MD = MDNode::get(II->getContext(), MDArgs); 3777 Value *Args[] = {MetadataAsValue::get(II->getContext(), MD)}; 3778 CallInst *NewCall = Builder.CreateCall(NewF, Args); 3779 NewCall->addAttribute(AttributeList::FunctionIndex, 3780 Attribute::Convergent); 3781 NewCall->takeName(II); 3782 return replaceInstUsesWith(*II, NewCall); 3783 } 3784 3785 // Canonicalize constants to RHS. 3786 CmpInst::Predicate SwapPred 3787 = CmpInst::getSwappedPredicate(static_cast<CmpInst::Predicate>(CCVal)); 3788 II->setArgOperand(0, Src1); 3789 II->setArgOperand(1, Src0); 3790 II->setArgOperand(2, ConstantInt::get(CC->getType(), 3791 static_cast<int>(SwapPred))); 3792 return II; 3793 } 3794 3795 if (CCVal != CmpInst::ICMP_EQ && CCVal != CmpInst::ICMP_NE) 3796 break; 3797 3798 // Canonicalize compare eq with true value to compare != 0 3799 // llvm.amdgcn.icmp(zext (i1 x), 1, eq) 3800 // -> llvm.amdgcn.icmp(zext (i1 x), 0, ne) 3801 // llvm.amdgcn.icmp(sext (i1 x), -1, eq) 3802 // -> llvm.amdgcn.icmp(sext (i1 x), 0, ne) 3803 Value *ExtSrc; 3804 if (CCVal == CmpInst::ICMP_EQ && 3805 ((match(Src1, m_One()) && match(Src0, m_ZExt(m_Value(ExtSrc)))) || 3806 (match(Src1, m_AllOnes()) && match(Src0, m_SExt(m_Value(ExtSrc))))) && 3807 ExtSrc->getType()->isIntegerTy(1)) { 3808 II->setArgOperand(1, ConstantInt::getNullValue(Src1->getType())); 3809 II->setArgOperand(2, ConstantInt::get(CC->getType(), CmpInst::ICMP_NE)); 3810 return II; 3811 } 3812 3813 CmpInst::Predicate SrcPred; 3814 Value *SrcLHS; 3815 Value *SrcRHS; 3816 3817 // Fold compare eq/ne with 0 from a compare result as the predicate to the 3818 // intrinsic. The typical use is a wave vote function in the library, which 3819 // will be fed from a user code condition compared with 0. Fold in the 3820 // redundant compare. 3821 3822 // llvm.amdgcn.icmp([sz]ext ([if]cmp pred a, b), 0, ne) 3823 // -> llvm.amdgcn.[if]cmp(a, b, pred) 3824 // 3825 // llvm.amdgcn.icmp([sz]ext ([if]cmp pred a, b), 0, eq) 3826 // -> llvm.amdgcn.[if]cmp(a, b, inv pred) 3827 if (match(Src1, m_Zero()) && 3828 match(Src0, 3829 m_ZExtOrSExt(m_Cmp(SrcPred, m_Value(SrcLHS), m_Value(SrcRHS))))) { 3830 if (CCVal == CmpInst::ICMP_EQ) 3831 SrcPred = CmpInst::getInversePredicate(SrcPred); 3832 3833 Intrinsic::ID NewIID = CmpInst::isFPPredicate(SrcPred) ? 3834 Intrinsic::amdgcn_fcmp : Intrinsic::amdgcn_icmp; 3835 3836 Type *Ty = SrcLHS->getType(); 3837 if (auto *CmpType = dyn_cast<IntegerType>(Ty)) { 3838 // Promote to next legal integer type. 3839 unsigned Width = CmpType->getBitWidth(); 3840 unsigned NewWidth = Width; 3841 3842 // Don't do anything for i1 comparisons. 3843 if (Width == 1) 3844 break; 3845 3846 if (Width <= 16) 3847 NewWidth = 16; 3848 else if (Width <= 32) 3849 NewWidth = 32; 3850 else if (Width <= 64) 3851 NewWidth = 64; 3852 else if (Width > 64) 3853 break; // Can't handle this. 3854 3855 if (Width != NewWidth) { 3856 IntegerType *CmpTy = Builder.getIntNTy(NewWidth); 3857 if (CmpInst::isSigned(SrcPred)) { 3858 SrcLHS = Builder.CreateSExt(SrcLHS, CmpTy); 3859 SrcRHS = Builder.CreateSExt(SrcRHS, CmpTy); 3860 } else { 3861 SrcLHS = Builder.CreateZExt(SrcLHS, CmpTy); 3862 SrcRHS = Builder.CreateZExt(SrcRHS, CmpTy); 3863 } 3864 } 3865 } else if (!Ty->isFloatTy() && !Ty->isDoubleTy() && !Ty->isHalfTy()) 3866 break; 3867 3868 Function *NewF = 3869 Intrinsic::getDeclaration(II->getModule(), NewIID, SrcLHS->getType()); 3870 Value *Args[] = { SrcLHS, SrcRHS, 3871 ConstantInt::get(CC->getType(), SrcPred) }; 3872 CallInst *NewCall = Builder.CreateCall(NewF, Args); 3873 NewCall->takeName(II); 3874 return replaceInstUsesWith(*II, NewCall); 3875 } 3876 3877 break; 3878 } 3879 case Intrinsic::amdgcn_wqm_vote: { 3880 // wqm_vote is identity when the argument is constant. 3881 if (!isa<Constant>(II->getArgOperand(0))) 3882 break; 3883 3884 return replaceInstUsesWith(*II, II->getArgOperand(0)); 3885 } 3886 case Intrinsic::amdgcn_kill: { 3887 const ConstantInt *C = dyn_cast<ConstantInt>(II->getArgOperand(0)); 3888 if (!C || !C->getZExtValue()) 3889 break; 3890 3891 // amdgcn.kill(i1 1) is a no-op 3892 return eraseInstFromFunction(CI); 3893 } 3894 case Intrinsic::amdgcn_update_dpp: { 3895 Value *Old = II->getArgOperand(0); 3896 3897 auto BC = cast<ConstantInt>(II->getArgOperand(5)); 3898 auto RM = cast<ConstantInt>(II->getArgOperand(3)); 3899 auto BM = cast<ConstantInt>(II->getArgOperand(4)); 3900 if (BC->isZeroValue() || 3901 RM->getZExtValue() != 0xF || 3902 BM->getZExtValue() != 0xF || 3903 isa<UndefValue>(Old)) 3904 break; 3905 3906 // If bound_ctrl = 1, row mask = bank mask = 0xf we can omit old value. 3907 II->setOperand(0, UndefValue::get(Old->getType())); 3908 return II; 3909 } 3910 case Intrinsic::stackrestore: { 3911 // If the save is right next to the restore, remove the restore. This can 3912 // happen when variable allocas are DCE'd. 3913 if (IntrinsicInst *SS = dyn_cast<IntrinsicInst>(II->getArgOperand(0))) { 3914 if (SS->getIntrinsicID() == Intrinsic::stacksave) { 3915 // Skip over debug info. 3916 if (SS->getNextNonDebugInstruction() == II) { 3917 return eraseInstFromFunction(CI); 3918 } 3919 } 3920 } 3921 3922 // Scan down this block to see if there is another stack restore in the 3923 // same block without an intervening call/alloca. 3924 BasicBlock::iterator BI(II); 3925 Instruction *TI = II->getParent()->getTerminator(); 3926 bool CannotRemove = false; 3927 for (++BI; &*BI != TI; ++BI) { 3928 if (isa<AllocaInst>(BI)) { 3929 CannotRemove = true; 3930 break; 3931 } 3932 if (CallInst *BCI = dyn_cast<CallInst>(BI)) { 3933 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(BCI)) { 3934 // If there is a stackrestore below this one, remove this one. 3935 if (II->getIntrinsicID() == Intrinsic::stackrestore) 3936 return eraseInstFromFunction(CI); 3937 3938 // Bail if we cross over an intrinsic with side effects, such as 3939 // llvm.stacksave, llvm.read_register, or llvm.setjmp. 3940 if (II->mayHaveSideEffects()) { 3941 CannotRemove = true; 3942 break; 3943 } 3944 } else { 3945 // If we found a non-intrinsic call, we can't remove the stack 3946 // restore. 3947 CannotRemove = true; 3948 break; 3949 } 3950 } 3951 } 3952 3953 // If the stack restore is in a return, resume, or unwind block and if there 3954 // are no allocas or calls between the restore and the return, nuke the 3955 // restore. 3956 if (!CannotRemove && (isa<ReturnInst>(TI) || isa<ResumeInst>(TI))) 3957 return eraseInstFromFunction(CI); 3958 break; 3959 } 3960 case Intrinsic::lifetime_start: 3961 // Asan needs to poison memory to detect invalid access which is possible 3962 // even for empty lifetime range. 3963 if (II->getFunction()->hasFnAttribute(Attribute::SanitizeAddress) || 3964 II->getFunction()->hasFnAttribute(Attribute::SanitizeHWAddress)) 3965 break; 3966 3967 if (removeTriviallyEmptyRange(*II, Intrinsic::lifetime_start, 3968 Intrinsic::lifetime_end, *this)) 3969 return nullptr; 3970 break; 3971 case Intrinsic::assume: { 3972 Value *IIOperand = II->getArgOperand(0); 3973 // Remove an assume if it is followed by an identical assume. 3974 // TODO: Do we need this? Unless there are conflicting assumptions, the 3975 // computeKnownBits(IIOperand) below here eliminates redundant assumes. 3976 Instruction *Next = II->getNextNonDebugInstruction(); 3977 if (match(Next, m_Intrinsic<Intrinsic::assume>(m_Specific(IIOperand)))) 3978 return eraseInstFromFunction(CI); 3979 3980 // Canonicalize assume(a && b) -> assume(a); assume(b); 3981 // Note: New assumption intrinsics created here are registered by 3982 // the InstCombineIRInserter object. 3983 FunctionType *AssumeIntrinsicTy = II->getFunctionType(); 3984 Value *AssumeIntrinsic = II->getCalledValue(); 3985 Value *A, *B; 3986 if (match(IIOperand, m_And(m_Value(A), m_Value(B)))) { 3987 Builder.CreateCall(AssumeIntrinsicTy, AssumeIntrinsic, A, II->getName()); 3988 Builder.CreateCall(AssumeIntrinsicTy, AssumeIntrinsic, B, II->getName()); 3989 return eraseInstFromFunction(*II); 3990 } 3991 // assume(!(a || b)) -> assume(!a); assume(!b); 3992 if (match(IIOperand, m_Not(m_Or(m_Value(A), m_Value(B))))) { 3993 Builder.CreateCall(AssumeIntrinsicTy, AssumeIntrinsic, 3994 Builder.CreateNot(A), II->getName()); 3995 Builder.CreateCall(AssumeIntrinsicTy, AssumeIntrinsic, 3996 Builder.CreateNot(B), II->getName()); 3997 return eraseInstFromFunction(*II); 3998 } 3999 4000 // assume( (load addr) != null ) -> add 'nonnull' metadata to load 4001 // (if assume is valid at the load) 4002 CmpInst::Predicate Pred; 4003 Instruction *LHS; 4004 if (match(IIOperand, m_ICmp(Pred, m_Instruction(LHS), m_Zero())) && 4005 Pred == ICmpInst::ICMP_NE && LHS->getOpcode() == Instruction::Load && 4006 LHS->getType()->isPointerTy() && 4007 isValidAssumeForContext(II, LHS, &DT)) { 4008 MDNode *MD = MDNode::get(II->getContext(), None); 4009 LHS->setMetadata(LLVMContext::MD_nonnull, MD); 4010 return eraseInstFromFunction(*II); 4011 4012 // TODO: apply nonnull return attributes to calls and invokes 4013 // TODO: apply range metadata for range check patterns? 4014 } 4015 4016 // If there is a dominating assume with the same condition as this one, 4017 // then this one is redundant, and should be removed. 4018 KnownBits Known(1); 4019 computeKnownBits(IIOperand, Known, 0, II); 4020 if (Known.isAllOnes()) 4021 return eraseInstFromFunction(*II); 4022 4023 // Update the cache of affected values for this assumption (we might be 4024 // here because we just simplified the condition). 4025 AC.updateAffectedValues(II); 4026 break; 4027 } 4028 case Intrinsic::experimental_gc_relocate: { 4029 // Translate facts known about a pointer before relocating into 4030 // facts about the relocate value, while being careful to 4031 // preserve relocation semantics. 4032 Value *DerivedPtr = cast<GCRelocateInst>(II)->getDerivedPtr(); 4033 4034 // Remove the relocation if unused, note that this check is required 4035 // to prevent the cases below from looping forever. 4036 if (II->use_empty()) 4037 return eraseInstFromFunction(*II); 4038 4039 // Undef is undef, even after relocation. 4040 // TODO: provide a hook for this in GCStrategy. This is clearly legal for 4041 // most practical collectors, but there was discussion in the review thread 4042 // about whether it was legal for all possible collectors. 4043 if (isa<UndefValue>(DerivedPtr)) 4044 // Use undef of gc_relocate's type to replace it. 4045 return replaceInstUsesWith(*II, UndefValue::get(II->getType())); 4046 4047 if (auto *PT = dyn_cast<PointerType>(II->getType())) { 4048 // The relocation of null will be null for most any collector. 4049 // TODO: provide a hook for this in GCStrategy. There might be some 4050 // weird collector this property does not hold for. 4051 if (isa<ConstantPointerNull>(DerivedPtr)) 4052 // Use null-pointer of gc_relocate's type to replace it. 4053 return replaceInstUsesWith(*II, ConstantPointerNull::get(PT)); 4054 4055 // isKnownNonNull -> nonnull attribute 4056 if (!II->hasRetAttr(Attribute::NonNull) && 4057 isKnownNonZero(DerivedPtr, DL, 0, &AC, II, &DT)) { 4058 II->addAttribute(AttributeList::ReturnIndex, Attribute::NonNull); 4059 return II; 4060 } 4061 } 4062 4063 // TODO: bitcast(relocate(p)) -> relocate(bitcast(p)) 4064 // Canonicalize on the type from the uses to the defs 4065 4066 // TODO: relocate((gep p, C, C2, ...)) -> gep(relocate(p), C, C2, ...) 4067 break; 4068 } 4069 4070 case Intrinsic::experimental_guard: { 4071 // Is this guard followed by another guard? We scan forward over a small 4072 // fixed window of instructions to handle common cases with conditions 4073 // computed between guards. 4074 Instruction *NextInst = II->getNextNode(); 4075 for (unsigned i = 0; i < GuardWideningWindow; i++) { 4076 // Note: Using context-free form to avoid compile time blow up 4077 if (!isSafeToSpeculativelyExecute(NextInst)) 4078 break; 4079 NextInst = NextInst->getNextNode(); 4080 } 4081 Value *NextCond = nullptr; 4082 if (match(NextInst, 4083 m_Intrinsic<Intrinsic::experimental_guard>(m_Value(NextCond)))) { 4084 Value *CurrCond = II->getArgOperand(0); 4085 4086 // Remove a guard that it is immediately preceded by an identical guard. 4087 if (CurrCond == NextCond) 4088 return eraseInstFromFunction(*NextInst); 4089 4090 // Otherwise canonicalize guard(a); guard(b) -> guard(a & b). 4091 Instruction* MoveI = II->getNextNode(); 4092 while (MoveI != NextInst) { 4093 auto *Temp = MoveI; 4094 MoveI = MoveI->getNextNode(); 4095 Temp->moveBefore(II); 4096 } 4097 II->setArgOperand(0, Builder.CreateAnd(CurrCond, NextCond)); 4098 return eraseInstFromFunction(*NextInst); 4099 } 4100 break; 4101 } 4102 } 4103 return visitCallBase(*II); 4104 } 4105 4106 // Fence instruction simplification 4107 Instruction *InstCombiner::visitFenceInst(FenceInst &FI) { 4108 // Remove identical consecutive fences. 4109 Instruction *Next = FI.getNextNonDebugInstruction(); 4110 if (auto *NFI = dyn_cast<FenceInst>(Next)) 4111 if (FI.isIdenticalTo(NFI)) 4112 return eraseInstFromFunction(FI); 4113 return nullptr; 4114 } 4115 4116 // InvokeInst simplification 4117 Instruction *InstCombiner::visitInvokeInst(InvokeInst &II) { 4118 return visitCallBase(II); 4119 } 4120 4121 // CallBrInst simplification 4122 Instruction *InstCombiner::visitCallBrInst(CallBrInst &CBI) { 4123 return visitCallBase(CBI); 4124 } 4125 4126 /// If this cast does not affect the value passed through the varargs area, we 4127 /// can eliminate the use of the cast. 4128 static bool isSafeToEliminateVarargsCast(const CallBase &Call, 4129 const DataLayout &DL, 4130 const CastInst *const CI, 4131 const int ix) { 4132 if (!CI->isLosslessCast()) 4133 return false; 4134 4135 // If this is a GC intrinsic, avoid munging types. We need types for 4136 // statepoint reconstruction in SelectionDAG. 4137 // TODO: This is probably something which should be expanded to all 4138 // intrinsics since the entire point of intrinsics is that 4139 // they are understandable by the optimizer. 4140 if (isStatepoint(&Call) || isGCRelocate(&Call) || isGCResult(&Call)) 4141 return false; 4142 4143 // The size of ByVal or InAlloca arguments is derived from the type, so we 4144 // can't change to a type with a different size. If the size were 4145 // passed explicitly we could avoid this check. 4146 if (!Call.isByValOrInAllocaArgument(ix)) 4147 return true; 4148 4149 Type* SrcTy = 4150 cast<PointerType>(CI->getOperand(0)->getType())->getElementType(); 4151 Type* DstTy = cast<PointerType>(CI->getType())->getElementType(); 4152 if (!SrcTy->isSized() || !DstTy->isSized()) 4153 return false; 4154 if (DL.getTypeAllocSize(SrcTy) != DL.getTypeAllocSize(DstTy)) 4155 return false; 4156 return true; 4157 } 4158 4159 Instruction *InstCombiner::tryOptimizeCall(CallInst *CI) { 4160 if (!CI->getCalledFunction()) return nullptr; 4161 4162 auto InstCombineRAUW = [this](Instruction *From, Value *With) { 4163 replaceInstUsesWith(*From, With); 4164 }; 4165 auto InstCombineErase = [this](Instruction *I) { 4166 eraseInstFromFunction(*I); 4167 }; 4168 LibCallSimplifier Simplifier(DL, &TLI, ORE, BFI, PSI, InstCombineRAUW, 4169 InstCombineErase); 4170 if (Value *With = Simplifier.optimizeCall(CI)) { 4171 ++NumSimplified; 4172 return CI->use_empty() ? CI : replaceInstUsesWith(*CI, With); 4173 } 4174 4175 return nullptr; 4176 } 4177 4178 static IntrinsicInst *findInitTrampolineFromAlloca(Value *TrampMem) { 4179 // Strip off at most one level of pointer casts, looking for an alloca. This 4180 // is good enough in practice and simpler than handling any number of casts. 4181 Value *Underlying = TrampMem->stripPointerCasts(); 4182 if (Underlying != TrampMem && 4183 (!Underlying->hasOneUse() || Underlying->user_back() != TrampMem)) 4184 return nullptr; 4185 if (!isa<AllocaInst>(Underlying)) 4186 return nullptr; 4187 4188 IntrinsicInst *InitTrampoline = nullptr; 4189 for (User *U : TrampMem->users()) { 4190 IntrinsicInst *II = dyn_cast<IntrinsicInst>(U); 4191 if (!II) 4192 return nullptr; 4193 if (II->getIntrinsicID() == Intrinsic::init_trampoline) { 4194 if (InitTrampoline) 4195 // More than one init_trampoline writes to this value. Give up. 4196 return nullptr; 4197 InitTrampoline = II; 4198 continue; 4199 } 4200 if (II->getIntrinsicID() == Intrinsic::adjust_trampoline) 4201 // Allow any number of calls to adjust.trampoline. 4202 continue; 4203 return nullptr; 4204 } 4205 4206 // No call to init.trampoline found. 4207 if (!InitTrampoline) 4208 return nullptr; 4209 4210 // Check that the alloca is being used in the expected way. 4211 if (InitTrampoline->getOperand(0) != TrampMem) 4212 return nullptr; 4213 4214 return InitTrampoline; 4215 } 4216 4217 static IntrinsicInst *findInitTrampolineFromBB(IntrinsicInst *AdjustTramp, 4218 Value *TrampMem) { 4219 // Visit all the previous instructions in the basic block, and try to find a 4220 // init.trampoline which has a direct path to the adjust.trampoline. 4221 for (BasicBlock::iterator I = AdjustTramp->getIterator(), 4222 E = AdjustTramp->getParent()->begin(); 4223 I != E;) { 4224 Instruction *Inst = &*--I; 4225 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) 4226 if (II->getIntrinsicID() == Intrinsic::init_trampoline && 4227 II->getOperand(0) == TrampMem) 4228 return II; 4229 if (Inst->mayWriteToMemory()) 4230 return nullptr; 4231 } 4232 return nullptr; 4233 } 4234 4235 // Given a call to llvm.adjust.trampoline, find and return the corresponding 4236 // call to llvm.init.trampoline if the call to the trampoline can be optimized 4237 // to a direct call to a function. Otherwise return NULL. 4238 static IntrinsicInst *findInitTrampoline(Value *Callee) { 4239 Callee = Callee->stripPointerCasts(); 4240 IntrinsicInst *AdjustTramp = dyn_cast<IntrinsicInst>(Callee); 4241 if (!AdjustTramp || 4242 AdjustTramp->getIntrinsicID() != Intrinsic::adjust_trampoline) 4243 return nullptr; 4244 4245 Value *TrampMem = AdjustTramp->getOperand(0); 4246 4247 if (IntrinsicInst *IT = findInitTrampolineFromAlloca(TrampMem)) 4248 return IT; 4249 if (IntrinsicInst *IT = findInitTrampolineFromBB(AdjustTramp, TrampMem)) 4250 return IT; 4251 return nullptr; 4252 } 4253 4254 /// Improvements for call, callbr and invoke instructions. 4255 Instruction *InstCombiner::visitCallBase(CallBase &Call) { 4256 if (isAllocLikeFn(&Call, &TLI)) 4257 return visitAllocSite(Call); 4258 4259 bool Changed = false; 4260 4261 // Mark any parameters that are known to be non-null with the nonnull 4262 // attribute. This is helpful for inlining calls to functions with null 4263 // checks on their arguments. 4264 SmallVector<unsigned, 4> ArgNos; 4265 unsigned ArgNo = 0; 4266 4267 for (Value *V : Call.args()) { 4268 if (V->getType()->isPointerTy() && 4269 !Call.paramHasAttr(ArgNo, Attribute::NonNull) && 4270 isKnownNonZero(V, DL, 0, &AC, &Call, &DT)) 4271 ArgNos.push_back(ArgNo); 4272 ArgNo++; 4273 } 4274 4275 assert(ArgNo == Call.arg_size() && "sanity check"); 4276 4277 if (!ArgNos.empty()) { 4278 AttributeList AS = Call.getAttributes(); 4279 LLVMContext &Ctx = Call.getContext(); 4280 AS = AS.addParamAttribute(Ctx, ArgNos, 4281 Attribute::get(Ctx, Attribute::NonNull)); 4282 Call.setAttributes(AS); 4283 Changed = true; 4284 } 4285 4286 // If the callee is a pointer to a function, attempt to move any casts to the 4287 // arguments of the call/callbr/invoke. 4288 Value *Callee = Call.getCalledValue(); 4289 if (!isa<Function>(Callee) && transformConstExprCastCall(Call)) 4290 return nullptr; 4291 4292 if (Function *CalleeF = dyn_cast<Function>(Callee)) { 4293 // Remove the convergent attr on calls when the callee is not convergent. 4294 if (Call.isConvergent() && !CalleeF->isConvergent() && 4295 !CalleeF->isIntrinsic()) { 4296 LLVM_DEBUG(dbgs() << "Removing convergent attr from instr " << Call 4297 << "\n"); 4298 Call.setNotConvergent(); 4299 return &Call; 4300 } 4301 4302 // If the call and callee calling conventions don't match, this call must 4303 // be unreachable, as the call is undefined. 4304 if (CalleeF->getCallingConv() != Call.getCallingConv() && 4305 // Only do this for calls to a function with a body. A prototype may 4306 // not actually end up matching the implementation's calling conv for a 4307 // variety of reasons (e.g. it may be written in assembly). 4308 !CalleeF->isDeclaration()) { 4309 Instruction *OldCall = &Call; 4310 CreateNonTerminatorUnreachable(OldCall); 4311 // If OldCall does not return void then replaceAllUsesWith undef. 4312 // This allows ValueHandlers and custom metadata to adjust itself. 4313 if (!OldCall->getType()->isVoidTy()) 4314 replaceInstUsesWith(*OldCall, UndefValue::get(OldCall->getType())); 4315 if (isa<CallInst>(OldCall)) 4316 return eraseInstFromFunction(*OldCall); 4317 4318 // We cannot remove an invoke or a callbr, because it would change thexi 4319 // CFG, just change the callee to a null pointer. 4320 cast<CallBase>(OldCall)->setCalledFunction( 4321 CalleeF->getFunctionType(), 4322 Constant::getNullValue(CalleeF->getType())); 4323 return nullptr; 4324 } 4325 } 4326 4327 if ((isa<ConstantPointerNull>(Callee) && 4328 !NullPointerIsDefined(Call.getFunction())) || 4329 isa<UndefValue>(Callee)) { 4330 // If Call does not return void then replaceAllUsesWith undef. 4331 // This allows ValueHandlers and custom metadata to adjust itself. 4332 if (!Call.getType()->isVoidTy()) 4333 replaceInstUsesWith(Call, UndefValue::get(Call.getType())); 4334 4335 if (Call.isTerminator()) { 4336 // Can't remove an invoke or callbr because we cannot change the CFG. 4337 return nullptr; 4338 } 4339 4340 // This instruction is not reachable, just remove it. 4341 CreateNonTerminatorUnreachable(&Call); 4342 return eraseInstFromFunction(Call); 4343 } 4344 4345 if (IntrinsicInst *II = findInitTrampoline(Callee)) 4346 return transformCallThroughTrampoline(Call, *II); 4347 4348 PointerType *PTy = cast<PointerType>(Callee->getType()); 4349 FunctionType *FTy = cast<FunctionType>(PTy->getElementType()); 4350 if (FTy->isVarArg()) { 4351 int ix = FTy->getNumParams(); 4352 // See if we can optimize any arguments passed through the varargs area of 4353 // the call. 4354 for (auto I = Call.arg_begin() + FTy->getNumParams(), E = Call.arg_end(); 4355 I != E; ++I, ++ix) { 4356 CastInst *CI = dyn_cast<CastInst>(*I); 4357 if (CI && isSafeToEliminateVarargsCast(Call, DL, CI, ix)) { 4358 *I = CI->getOperand(0); 4359 Changed = true; 4360 } 4361 } 4362 } 4363 4364 if (isa<InlineAsm>(Callee) && !Call.doesNotThrow()) { 4365 // Inline asm calls cannot throw - mark them 'nounwind'. 4366 Call.setDoesNotThrow(); 4367 Changed = true; 4368 } 4369 4370 // Try to optimize the call if possible, we require DataLayout for most of 4371 // this. None of these calls are seen as possibly dead so go ahead and 4372 // delete the instruction now. 4373 if (CallInst *CI = dyn_cast<CallInst>(&Call)) { 4374 Instruction *I = tryOptimizeCall(CI); 4375 // If we changed something return the result, etc. Otherwise let 4376 // the fallthrough check. 4377 if (I) return eraseInstFromFunction(*I); 4378 } 4379 4380 return Changed ? &Call : nullptr; 4381 } 4382 4383 /// If the callee is a constexpr cast of a function, attempt to move the cast to 4384 /// the arguments of the call/callbr/invoke. 4385 bool InstCombiner::transformConstExprCastCall(CallBase &Call) { 4386 auto *Callee = dyn_cast<Function>(Call.getCalledValue()->stripPointerCasts()); 4387 if (!Callee) 4388 return false; 4389 4390 // If this is a call to a thunk function, don't remove the cast. Thunks are 4391 // used to transparently forward all incoming parameters and outgoing return 4392 // values, so it's important to leave the cast in place. 4393 if (Callee->hasFnAttribute("thunk")) 4394 return false; 4395 4396 // If this is a musttail call, the callee's prototype must match the caller's 4397 // prototype with the exception of pointee types. The code below doesn't 4398 // implement that, so we can't do this transform. 4399 // TODO: Do the transform if it only requires adding pointer casts. 4400 if (Call.isMustTailCall()) 4401 return false; 4402 4403 Instruction *Caller = &Call; 4404 const AttributeList &CallerPAL = Call.getAttributes(); 4405 4406 // Okay, this is a cast from a function to a different type. Unless doing so 4407 // would cause a type conversion of one of our arguments, change this call to 4408 // be a direct call with arguments casted to the appropriate types. 4409 FunctionType *FT = Callee->getFunctionType(); 4410 Type *OldRetTy = Caller->getType(); 4411 Type *NewRetTy = FT->getReturnType(); 4412 4413 // Check to see if we are changing the return type... 4414 if (OldRetTy != NewRetTy) { 4415 4416 if (NewRetTy->isStructTy()) 4417 return false; // TODO: Handle multiple return values. 4418 4419 if (!CastInst::isBitOrNoopPointerCastable(NewRetTy, OldRetTy, DL)) { 4420 if (Callee->isDeclaration()) 4421 return false; // Cannot transform this return value. 4422 4423 if (!Caller->use_empty() && 4424 // void -> non-void is handled specially 4425 !NewRetTy->isVoidTy()) 4426 return false; // Cannot transform this return value. 4427 } 4428 4429 if (!CallerPAL.isEmpty() && !Caller->use_empty()) { 4430 AttrBuilder RAttrs(CallerPAL, AttributeList::ReturnIndex); 4431 if (RAttrs.overlaps(AttributeFuncs::typeIncompatible(NewRetTy))) 4432 return false; // Attribute not compatible with transformed value. 4433 } 4434 4435 // If the callbase is an invoke/callbr instruction, and the return value is 4436 // used by a PHI node in a successor, we cannot change the return type of 4437 // the call because there is no place to put the cast instruction (without 4438 // breaking the critical edge). Bail out in this case. 4439 if (!Caller->use_empty()) { 4440 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) 4441 for (User *U : II->users()) 4442 if (PHINode *PN = dyn_cast<PHINode>(U)) 4443 if (PN->getParent() == II->getNormalDest() || 4444 PN->getParent() == II->getUnwindDest()) 4445 return false; 4446 // FIXME: Be conservative for callbr to avoid a quadratic search. 4447 if (isa<CallBrInst>(Caller)) 4448 return false; 4449 } 4450 } 4451 4452 unsigned NumActualArgs = Call.arg_size(); 4453 unsigned NumCommonArgs = std::min(FT->getNumParams(), NumActualArgs); 4454 4455 // Prevent us turning: 4456 // declare void @takes_i32_inalloca(i32* inalloca) 4457 // call void bitcast (void (i32*)* @takes_i32_inalloca to void (i32)*)(i32 0) 4458 // 4459 // into: 4460 // call void @takes_i32_inalloca(i32* null) 4461 // 4462 // Similarly, avoid folding away bitcasts of byval calls. 4463 if (Callee->getAttributes().hasAttrSomewhere(Attribute::InAlloca) || 4464 Callee->getAttributes().hasAttrSomewhere(Attribute::ByVal)) 4465 return false; 4466 4467 auto AI = Call.arg_begin(); 4468 for (unsigned i = 0, e = NumCommonArgs; i != e; ++i, ++AI) { 4469 Type *ParamTy = FT->getParamType(i); 4470 Type *ActTy = (*AI)->getType(); 4471 4472 if (!CastInst::isBitOrNoopPointerCastable(ActTy, ParamTy, DL)) 4473 return false; // Cannot transform this parameter value. 4474 4475 if (AttrBuilder(CallerPAL.getParamAttributes(i)) 4476 .overlaps(AttributeFuncs::typeIncompatible(ParamTy))) 4477 return false; // Attribute not compatible with transformed value. 4478 4479 if (Call.isInAllocaArgument(i)) 4480 return false; // Cannot transform to and from inalloca. 4481 4482 // If the parameter is passed as a byval argument, then we have to have a 4483 // sized type and the sized type has to have the same size as the old type. 4484 if (ParamTy != ActTy && CallerPAL.hasParamAttribute(i, Attribute::ByVal)) { 4485 PointerType *ParamPTy = dyn_cast<PointerType>(ParamTy); 4486 if (!ParamPTy || !ParamPTy->getElementType()->isSized()) 4487 return false; 4488 4489 Type *CurElTy = ActTy->getPointerElementType(); 4490 if (DL.getTypeAllocSize(CurElTy) != 4491 DL.getTypeAllocSize(ParamPTy->getElementType())) 4492 return false; 4493 } 4494 } 4495 4496 if (Callee->isDeclaration()) { 4497 // Do not delete arguments unless we have a function body. 4498 if (FT->getNumParams() < NumActualArgs && !FT->isVarArg()) 4499 return false; 4500 4501 // If the callee is just a declaration, don't change the varargsness of the 4502 // call. We don't want to introduce a varargs call where one doesn't 4503 // already exist. 4504 PointerType *APTy = cast<PointerType>(Call.getCalledValue()->getType()); 4505 if (FT->isVarArg()!=cast<FunctionType>(APTy->getElementType())->isVarArg()) 4506 return false; 4507 4508 // If both the callee and the cast type are varargs, we still have to make 4509 // sure the number of fixed parameters are the same or we have the same 4510 // ABI issues as if we introduce a varargs call. 4511 if (FT->isVarArg() && 4512 cast<FunctionType>(APTy->getElementType())->isVarArg() && 4513 FT->getNumParams() != 4514 cast<FunctionType>(APTy->getElementType())->getNumParams()) 4515 return false; 4516 } 4517 4518 if (FT->getNumParams() < NumActualArgs && FT->isVarArg() && 4519 !CallerPAL.isEmpty()) { 4520 // In this case we have more arguments than the new function type, but we 4521 // won't be dropping them. Check that these extra arguments have attributes 4522 // that are compatible with being a vararg call argument. 4523 unsigned SRetIdx; 4524 if (CallerPAL.hasAttrSomewhere(Attribute::StructRet, &SRetIdx) && 4525 SRetIdx > FT->getNumParams()) 4526 return false; 4527 } 4528 4529 // Okay, we decided that this is a safe thing to do: go ahead and start 4530 // inserting cast instructions as necessary. 4531 SmallVector<Value *, 8> Args; 4532 SmallVector<AttributeSet, 8> ArgAttrs; 4533 Args.reserve(NumActualArgs); 4534 ArgAttrs.reserve(NumActualArgs); 4535 4536 // Get any return attributes. 4537 AttrBuilder RAttrs(CallerPAL, AttributeList::ReturnIndex); 4538 4539 // If the return value is not being used, the type may not be compatible 4540 // with the existing attributes. Wipe out any problematic attributes. 4541 RAttrs.remove(AttributeFuncs::typeIncompatible(NewRetTy)); 4542 4543 AI = Call.arg_begin(); 4544 for (unsigned i = 0; i != NumCommonArgs; ++i, ++AI) { 4545 Type *ParamTy = FT->getParamType(i); 4546 4547 Value *NewArg = *AI; 4548 if ((*AI)->getType() != ParamTy) 4549 NewArg = Builder.CreateBitOrPointerCast(*AI, ParamTy); 4550 Args.push_back(NewArg); 4551 4552 // Add any parameter attributes. 4553 ArgAttrs.push_back(CallerPAL.getParamAttributes(i)); 4554 } 4555 4556 // If the function takes more arguments than the call was taking, add them 4557 // now. 4558 for (unsigned i = NumCommonArgs; i != FT->getNumParams(); ++i) { 4559 Args.push_back(Constant::getNullValue(FT->getParamType(i))); 4560 ArgAttrs.push_back(AttributeSet()); 4561 } 4562 4563 // If we are removing arguments to the function, emit an obnoxious warning. 4564 if (FT->getNumParams() < NumActualArgs) { 4565 // TODO: if (!FT->isVarArg()) this call may be unreachable. PR14722 4566 if (FT->isVarArg()) { 4567 // Add all of the arguments in their promoted form to the arg list. 4568 for (unsigned i = FT->getNumParams(); i != NumActualArgs; ++i, ++AI) { 4569 Type *PTy = getPromotedType((*AI)->getType()); 4570 Value *NewArg = *AI; 4571 if (PTy != (*AI)->getType()) { 4572 // Must promote to pass through va_arg area! 4573 Instruction::CastOps opcode = 4574 CastInst::getCastOpcode(*AI, false, PTy, false); 4575 NewArg = Builder.CreateCast(opcode, *AI, PTy); 4576 } 4577 Args.push_back(NewArg); 4578 4579 // Add any parameter attributes. 4580 ArgAttrs.push_back(CallerPAL.getParamAttributes(i)); 4581 } 4582 } 4583 } 4584 4585 AttributeSet FnAttrs = CallerPAL.getFnAttributes(); 4586 4587 if (NewRetTy->isVoidTy()) 4588 Caller->setName(""); // Void type should not have a name. 4589 4590 assert((ArgAttrs.size() == FT->getNumParams() || FT->isVarArg()) && 4591 "missing argument attributes"); 4592 LLVMContext &Ctx = Callee->getContext(); 4593 AttributeList NewCallerPAL = AttributeList::get( 4594 Ctx, FnAttrs, AttributeSet::get(Ctx, RAttrs), ArgAttrs); 4595 4596 SmallVector<OperandBundleDef, 1> OpBundles; 4597 Call.getOperandBundlesAsDefs(OpBundles); 4598 4599 CallBase *NewCall; 4600 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) { 4601 NewCall = Builder.CreateInvoke(Callee, II->getNormalDest(), 4602 II->getUnwindDest(), Args, OpBundles); 4603 } else if (CallBrInst *CBI = dyn_cast<CallBrInst>(Caller)) { 4604 NewCall = Builder.CreateCallBr(Callee, CBI->getDefaultDest(), 4605 CBI->getIndirectDests(), Args, OpBundles); 4606 } else { 4607 NewCall = Builder.CreateCall(Callee, Args, OpBundles); 4608 cast<CallInst>(NewCall)->setTailCallKind( 4609 cast<CallInst>(Caller)->getTailCallKind()); 4610 } 4611 NewCall->takeName(Caller); 4612 NewCall->setCallingConv(Call.getCallingConv()); 4613 NewCall->setAttributes(NewCallerPAL); 4614 4615 // Preserve the weight metadata for the new call instruction. The metadata 4616 // is used by SamplePGO to check callsite's hotness. 4617 uint64_t W; 4618 if (Caller->extractProfTotalWeight(W)) 4619 NewCall->setProfWeight(W); 4620 4621 // Insert a cast of the return type as necessary. 4622 Instruction *NC = NewCall; 4623 Value *NV = NC; 4624 if (OldRetTy != NV->getType() && !Caller->use_empty()) { 4625 if (!NV->getType()->isVoidTy()) { 4626 NV = NC = CastInst::CreateBitOrPointerCast(NC, OldRetTy); 4627 NC->setDebugLoc(Caller->getDebugLoc()); 4628 4629 // If this is an invoke/callbr instruction, we should insert it after the 4630 // first non-phi instruction in the normal successor block. 4631 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) { 4632 BasicBlock::iterator I = II->getNormalDest()->getFirstInsertionPt(); 4633 InsertNewInstBefore(NC, *I); 4634 } else if (CallBrInst *CBI = dyn_cast<CallBrInst>(Caller)) { 4635 BasicBlock::iterator I = CBI->getDefaultDest()->getFirstInsertionPt(); 4636 InsertNewInstBefore(NC, *I); 4637 } else { 4638 // Otherwise, it's a call, just insert cast right after the call. 4639 InsertNewInstBefore(NC, *Caller); 4640 } 4641 Worklist.AddUsersToWorkList(*Caller); 4642 } else { 4643 NV = UndefValue::get(Caller->getType()); 4644 } 4645 } 4646 4647 if (!Caller->use_empty()) 4648 replaceInstUsesWith(*Caller, NV); 4649 else if (Caller->hasValueHandle()) { 4650 if (OldRetTy == NV->getType()) 4651 ValueHandleBase::ValueIsRAUWd(Caller, NV); 4652 else 4653 // We cannot call ValueIsRAUWd with a different type, and the 4654 // actual tracked value will disappear. 4655 ValueHandleBase::ValueIsDeleted(Caller); 4656 } 4657 4658 eraseInstFromFunction(*Caller); 4659 return true; 4660 } 4661 4662 /// Turn a call to a function created by init_trampoline / adjust_trampoline 4663 /// intrinsic pair into a direct call to the underlying function. 4664 Instruction * 4665 InstCombiner::transformCallThroughTrampoline(CallBase &Call, 4666 IntrinsicInst &Tramp) { 4667 Value *Callee = Call.getCalledValue(); 4668 Type *CalleeTy = Callee->getType(); 4669 FunctionType *FTy = Call.getFunctionType(); 4670 AttributeList Attrs = Call.getAttributes(); 4671 4672 // If the call already has the 'nest' attribute somewhere then give up - 4673 // otherwise 'nest' would occur twice after splicing in the chain. 4674 if (Attrs.hasAttrSomewhere(Attribute::Nest)) 4675 return nullptr; 4676 4677 Function *NestF = cast<Function>(Tramp.getArgOperand(1)->stripPointerCasts()); 4678 FunctionType *NestFTy = NestF->getFunctionType(); 4679 4680 AttributeList NestAttrs = NestF->getAttributes(); 4681 if (!NestAttrs.isEmpty()) { 4682 unsigned NestArgNo = 0; 4683 Type *NestTy = nullptr; 4684 AttributeSet NestAttr; 4685 4686 // Look for a parameter marked with the 'nest' attribute. 4687 for (FunctionType::param_iterator I = NestFTy->param_begin(), 4688 E = NestFTy->param_end(); 4689 I != E; ++NestArgNo, ++I) { 4690 AttributeSet AS = NestAttrs.getParamAttributes(NestArgNo); 4691 if (AS.hasAttribute(Attribute::Nest)) { 4692 // Record the parameter type and any other attributes. 4693 NestTy = *I; 4694 NestAttr = AS; 4695 break; 4696 } 4697 } 4698 4699 if (NestTy) { 4700 std::vector<Value*> NewArgs; 4701 std::vector<AttributeSet> NewArgAttrs; 4702 NewArgs.reserve(Call.arg_size() + 1); 4703 NewArgAttrs.reserve(Call.arg_size()); 4704 4705 // Insert the nest argument into the call argument list, which may 4706 // mean appending it. Likewise for attributes. 4707 4708 { 4709 unsigned ArgNo = 0; 4710 auto I = Call.arg_begin(), E = Call.arg_end(); 4711 do { 4712 if (ArgNo == NestArgNo) { 4713 // Add the chain argument and attributes. 4714 Value *NestVal = Tramp.getArgOperand(2); 4715 if (NestVal->getType() != NestTy) 4716 NestVal = Builder.CreateBitCast(NestVal, NestTy, "nest"); 4717 NewArgs.push_back(NestVal); 4718 NewArgAttrs.push_back(NestAttr); 4719 } 4720 4721 if (I == E) 4722 break; 4723 4724 // Add the original argument and attributes. 4725 NewArgs.push_back(*I); 4726 NewArgAttrs.push_back(Attrs.getParamAttributes(ArgNo)); 4727 4728 ++ArgNo; 4729 ++I; 4730 } while (true); 4731 } 4732 4733 // The trampoline may have been bitcast to a bogus type (FTy). 4734 // Handle this by synthesizing a new function type, equal to FTy 4735 // with the chain parameter inserted. 4736 4737 std::vector<Type*> NewTypes; 4738 NewTypes.reserve(FTy->getNumParams()+1); 4739 4740 // Insert the chain's type into the list of parameter types, which may 4741 // mean appending it. 4742 { 4743 unsigned ArgNo = 0; 4744 FunctionType::param_iterator I = FTy->param_begin(), 4745 E = FTy->param_end(); 4746 4747 do { 4748 if (ArgNo == NestArgNo) 4749 // Add the chain's type. 4750 NewTypes.push_back(NestTy); 4751 4752 if (I == E) 4753 break; 4754 4755 // Add the original type. 4756 NewTypes.push_back(*I); 4757 4758 ++ArgNo; 4759 ++I; 4760 } while (true); 4761 } 4762 4763 // Replace the trampoline call with a direct call. Let the generic 4764 // code sort out any function type mismatches. 4765 FunctionType *NewFTy = FunctionType::get(FTy->getReturnType(), NewTypes, 4766 FTy->isVarArg()); 4767 Constant *NewCallee = 4768 NestF->getType() == PointerType::getUnqual(NewFTy) ? 4769 NestF : ConstantExpr::getBitCast(NestF, 4770 PointerType::getUnqual(NewFTy)); 4771 AttributeList NewPAL = 4772 AttributeList::get(FTy->getContext(), Attrs.getFnAttributes(), 4773 Attrs.getRetAttributes(), NewArgAttrs); 4774 4775 SmallVector<OperandBundleDef, 1> OpBundles; 4776 Call.getOperandBundlesAsDefs(OpBundles); 4777 4778 Instruction *NewCaller; 4779 if (InvokeInst *II = dyn_cast<InvokeInst>(&Call)) { 4780 NewCaller = InvokeInst::Create(NewFTy, NewCallee, 4781 II->getNormalDest(), II->getUnwindDest(), 4782 NewArgs, OpBundles); 4783 cast<InvokeInst>(NewCaller)->setCallingConv(II->getCallingConv()); 4784 cast<InvokeInst>(NewCaller)->setAttributes(NewPAL); 4785 } else if (CallBrInst *CBI = dyn_cast<CallBrInst>(&Call)) { 4786 NewCaller = 4787 CallBrInst::Create(NewFTy, NewCallee, CBI->getDefaultDest(), 4788 CBI->getIndirectDests(), NewArgs, OpBundles); 4789 cast<CallBrInst>(NewCaller)->setCallingConv(CBI->getCallingConv()); 4790 cast<CallBrInst>(NewCaller)->setAttributes(NewPAL); 4791 } else { 4792 NewCaller = CallInst::Create(NewFTy, NewCallee, NewArgs, OpBundles); 4793 cast<CallInst>(NewCaller)->setTailCallKind( 4794 cast<CallInst>(Call).getTailCallKind()); 4795 cast<CallInst>(NewCaller)->setCallingConv( 4796 cast<CallInst>(Call).getCallingConv()); 4797 cast<CallInst>(NewCaller)->setAttributes(NewPAL); 4798 } 4799 NewCaller->setDebugLoc(Call.getDebugLoc()); 4800 4801 return NewCaller; 4802 } 4803 } 4804 4805 // Replace the trampoline call with a direct call. Since there is no 'nest' 4806 // parameter, there is no need to adjust the argument list. Let the generic 4807 // code sort out any function type mismatches. 4808 Constant *NewCallee = ConstantExpr::getBitCast(NestF, CalleeTy); 4809 Call.setCalledFunction(FTy, NewCallee); 4810 return &Call; 4811 } 4812