1 //===- InstCombineCalls.cpp -----------------------------------------------===// 2 // 3 // The LLVM Compiler Infrastructure 4 // 5 // This file is distributed under the University of Illinois Open Source 6 // License. See LICENSE.TXT for details. 7 // 8 //===----------------------------------------------------------------------===// 9 // 10 // This file implements the visitCall and visitInvoke functions. 11 // 12 //===----------------------------------------------------------------------===// 13 14 #include "InstCombineInternal.h" 15 #include "llvm/ADT/Statistic.h" 16 #include "llvm/Analysis/InstructionSimplify.h" 17 #include "llvm/Analysis/Loads.h" 18 #include "llvm/Analysis/MemoryBuiltins.h" 19 #include "llvm/IR/CallSite.h" 20 #include "llvm/IR/Dominators.h" 21 #include "llvm/IR/PatternMatch.h" 22 #include "llvm/IR/Statepoint.h" 23 #include "llvm/Transforms/Utils/BuildLibCalls.h" 24 #include "llvm/Transforms/Utils/Local.h" 25 #include "llvm/Transforms/Utils/SimplifyLibCalls.h" 26 using namespace llvm; 27 using namespace PatternMatch; 28 29 #define DEBUG_TYPE "instcombine" 30 31 STATISTIC(NumSimplified, "Number of library calls simplified"); 32 33 /// Return the specified type promoted as it would be to pass though a va_arg 34 /// area. 35 static Type *getPromotedType(Type *Ty) { 36 if (IntegerType* ITy = dyn_cast<IntegerType>(Ty)) { 37 if (ITy->getBitWidth() < 32) 38 return Type::getInt32Ty(Ty->getContext()); 39 } 40 return Ty; 41 } 42 43 /// Given an aggregate type which ultimately holds a single scalar element, 44 /// like {{{type}}} or [1 x type], return type. 45 static Type *reduceToSingleValueType(Type *T) { 46 while (!T->isSingleValueType()) { 47 if (StructType *STy = dyn_cast<StructType>(T)) { 48 if (STy->getNumElements() == 1) 49 T = STy->getElementType(0); 50 else 51 break; 52 } else if (ArrayType *ATy = dyn_cast<ArrayType>(T)) { 53 if (ATy->getNumElements() == 1) 54 T = ATy->getElementType(); 55 else 56 break; 57 } else 58 break; 59 } 60 61 return T; 62 } 63 64 /// Return a constant boolean vector that has true elements in all positions 65 /// where the input constant data vector has an element with the sign bit set. 66 static Constant *getNegativeIsTrueBoolVec(ConstantDataVector *V) { 67 SmallVector<Constant *, 32> BoolVec; 68 IntegerType *BoolTy = Type::getInt1Ty(V->getContext()); 69 for (unsigned I = 0, E = V->getNumElements(); I != E; ++I) { 70 Constant *Elt = V->getElementAsConstant(I); 71 assert((isa<ConstantInt>(Elt) || isa<ConstantFP>(Elt)) && 72 "Unexpected constant data vector element type"); 73 bool Sign = V->getElementType()->isIntegerTy() 74 ? cast<ConstantInt>(Elt)->isNegative() 75 : cast<ConstantFP>(Elt)->isNegative(); 76 BoolVec.push_back(ConstantInt::get(BoolTy, Sign)); 77 } 78 return ConstantVector::get(BoolVec); 79 } 80 81 Instruction *InstCombiner::SimplifyMemTransfer(MemIntrinsic *MI) { 82 unsigned DstAlign = getKnownAlignment(MI->getArgOperand(0), DL, MI, AC, DT); 83 unsigned SrcAlign = getKnownAlignment(MI->getArgOperand(1), DL, MI, AC, DT); 84 unsigned MinAlign = std::min(DstAlign, SrcAlign); 85 unsigned CopyAlign = MI->getAlignment(); 86 87 if (CopyAlign < MinAlign) { 88 MI->setAlignment(ConstantInt::get(MI->getAlignmentType(), MinAlign, false)); 89 return MI; 90 } 91 92 // If MemCpyInst length is 1/2/4/8 bytes then replace memcpy with 93 // load/store. 94 ConstantInt *MemOpLength = dyn_cast<ConstantInt>(MI->getArgOperand(2)); 95 if (!MemOpLength) return nullptr; 96 97 // Source and destination pointer types are always "i8*" for intrinsic. See 98 // if the size is something we can handle with a single primitive load/store. 99 // A single load+store correctly handles overlapping memory in the memmove 100 // case. 101 uint64_t Size = MemOpLength->getLimitedValue(); 102 assert(Size && "0-sized memory transferring should be removed already."); 103 104 if (Size > 8 || (Size&(Size-1))) 105 return nullptr; // If not 1/2/4/8 bytes, exit. 106 107 // Use an integer load+store unless we can find something better. 108 unsigned SrcAddrSp = 109 cast<PointerType>(MI->getArgOperand(1)->getType())->getAddressSpace(); 110 unsigned DstAddrSp = 111 cast<PointerType>(MI->getArgOperand(0)->getType())->getAddressSpace(); 112 113 IntegerType* IntType = IntegerType::get(MI->getContext(), Size<<3); 114 Type *NewSrcPtrTy = PointerType::get(IntType, SrcAddrSp); 115 Type *NewDstPtrTy = PointerType::get(IntType, DstAddrSp); 116 117 // Memcpy forces the use of i8* for the source and destination. That means 118 // that if you're using memcpy to move one double around, you'll get a cast 119 // from double* to i8*. We'd much rather use a double load+store rather than 120 // an i64 load+store, here because this improves the odds that the source or 121 // dest address will be promotable. See if we can find a better type than the 122 // integer datatype. 123 Value *StrippedDest = MI->getArgOperand(0)->stripPointerCasts(); 124 MDNode *CopyMD = nullptr; 125 if (StrippedDest != MI->getArgOperand(0)) { 126 Type *SrcETy = cast<PointerType>(StrippedDest->getType()) 127 ->getElementType(); 128 if (SrcETy->isSized() && DL.getTypeStoreSize(SrcETy) == Size) { 129 // The SrcETy might be something like {{{double}}} or [1 x double]. Rip 130 // down through these levels if so. 131 SrcETy = reduceToSingleValueType(SrcETy); 132 133 if (SrcETy->isSingleValueType()) { 134 NewSrcPtrTy = PointerType::get(SrcETy, SrcAddrSp); 135 NewDstPtrTy = PointerType::get(SrcETy, DstAddrSp); 136 137 // If the memcpy has metadata describing the members, see if we can 138 // get the TBAA tag describing our copy. 139 if (MDNode *M = MI->getMetadata(LLVMContext::MD_tbaa_struct)) { 140 if (M->getNumOperands() == 3 && M->getOperand(0) && 141 mdconst::hasa<ConstantInt>(M->getOperand(0)) && 142 mdconst::extract<ConstantInt>(M->getOperand(0))->isNullValue() && 143 M->getOperand(1) && 144 mdconst::hasa<ConstantInt>(M->getOperand(1)) && 145 mdconst::extract<ConstantInt>(M->getOperand(1))->getValue() == 146 Size && 147 M->getOperand(2) && isa<MDNode>(M->getOperand(2))) 148 CopyMD = cast<MDNode>(M->getOperand(2)); 149 } 150 } 151 } 152 } 153 154 // If the memcpy/memmove provides better alignment info than we can 155 // infer, use it. 156 SrcAlign = std::max(SrcAlign, CopyAlign); 157 DstAlign = std::max(DstAlign, CopyAlign); 158 159 Value *Src = Builder->CreateBitCast(MI->getArgOperand(1), NewSrcPtrTy); 160 Value *Dest = Builder->CreateBitCast(MI->getArgOperand(0), NewDstPtrTy); 161 LoadInst *L = Builder->CreateLoad(Src, MI->isVolatile()); 162 L->setAlignment(SrcAlign); 163 if (CopyMD) 164 L->setMetadata(LLVMContext::MD_tbaa, CopyMD); 165 StoreInst *S = Builder->CreateStore(L, Dest, MI->isVolatile()); 166 S->setAlignment(DstAlign); 167 if (CopyMD) 168 S->setMetadata(LLVMContext::MD_tbaa, CopyMD); 169 170 // Set the size of the copy to 0, it will be deleted on the next iteration. 171 MI->setArgOperand(2, Constant::getNullValue(MemOpLength->getType())); 172 return MI; 173 } 174 175 Instruction *InstCombiner::SimplifyMemSet(MemSetInst *MI) { 176 unsigned Alignment = getKnownAlignment(MI->getDest(), DL, MI, AC, DT); 177 if (MI->getAlignment() < Alignment) { 178 MI->setAlignment(ConstantInt::get(MI->getAlignmentType(), 179 Alignment, false)); 180 return MI; 181 } 182 183 // Extract the length and alignment and fill if they are constant. 184 ConstantInt *LenC = dyn_cast<ConstantInt>(MI->getLength()); 185 ConstantInt *FillC = dyn_cast<ConstantInt>(MI->getValue()); 186 if (!LenC || !FillC || !FillC->getType()->isIntegerTy(8)) 187 return nullptr; 188 uint64_t Len = LenC->getLimitedValue(); 189 Alignment = MI->getAlignment(); 190 assert(Len && "0-sized memory setting should be removed already."); 191 192 // memset(s,c,n) -> store s, c (for n=1,2,4,8) 193 if (Len <= 8 && isPowerOf2_32((uint32_t)Len)) { 194 Type *ITy = IntegerType::get(MI->getContext(), Len*8); // n=1 -> i8. 195 196 Value *Dest = MI->getDest(); 197 unsigned DstAddrSp = cast<PointerType>(Dest->getType())->getAddressSpace(); 198 Type *NewDstPtrTy = PointerType::get(ITy, DstAddrSp); 199 Dest = Builder->CreateBitCast(Dest, NewDstPtrTy); 200 201 // Alignment 0 is identity for alignment 1 for memset, but not store. 202 if (Alignment == 0) Alignment = 1; 203 204 // Extract the fill value and store. 205 uint64_t Fill = FillC->getZExtValue()*0x0101010101010101ULL; 206 StoreInst *S = Builder->CreateStore(ConstantInt::get(ITy, Fill), Dest, 207 MI->isVolatile()); 208 S->setAlignment(Alignment); 209 210 // Set the size of the copy to 0, it will be deleted on the next iteration. 211 MI->setLength(Constant::getNullValue(LenC->getType())); 212 return MI; 213 } 214 215 return nullptr; 216 } 217 218 static Value *simplifyX86immShift(const IntrinsicInst &II, 219 InstCombiner::BuilderTy &Builder) { 220 bool LogicalShift = false; 221 bool ShiftLeft = false; 222 223 switch (II.getIntrinsicID()) { 224 default: 225 return nullptr; 226 case Intrinsic::x86_sse2_psra_d: 227 case Intrinsic::x86_sse2_psra_w: 228 case Intrinsic::x86_sse2_psrai_d: 229 case Intrinsic::x86_sse2_psrai_w: 230 case Intrinsic::x86_avx2_psra_d: 231 case Intrinsic::x86_avx2_psra_w: 232 case Intrinsic::x86_avx2_psrai_d: 233 case Intrinsic::x86_avx2_psrai_w: 234 LogicalShift = false; ShiftLeft = false; 235 break; 236 case Intrinsic::x86_sse2_psrl_d: 237 case Intrinsic::x86_sse2_psrl_q: 238 case Intrinsic::x86_sse2_psrl_w: 239 case Intrinsic::x86_sse2_psrli_d: 240 case Intrinsic::x86_sse2_psrli_q: 241 case Intrinsic::x86_sse2_psrli_w: 242 case Intrinsic::x86_avx2_psrl_d: 243 case Intrinsic::x86_avx2_psrl_q: 244 case Intrinsic::x86_avx2_psrl_w: 245 case Intrinsic::x86_avx2_psrli_d: 246 case Intrinsic::x86_avx2_psrli_q: 247 case Intrinsic::x86_avx2_psrli_w: 248 LogicalShift = true; ShiftLeft = false; 249 break; 250 case Intrinsic::x86_sse2_psll_d: 251 case Intrinsic::x86_sse2_psll_q: 252 case Intrinsic::x86_sse2_psll_w: 253 case Intrinsic::x86_sse2_pslli_d: 254 case Intrinsic::x86_sse2_pslli_q: 255 case Intrinsic::x86_sse2_pslli_w: 256 case Intrinsic::x86_avx2_psll_d: 257 case Intrinsic::x86_avx2_psll_q: 258 case Intrinsic::x86_avx2_psll_w: 259 case Intrinsic::x86_avx2_pslli_d: 260 case Intrinsic::x86_avx2_pslli_q: 261 case Intrinsic::x86_avx2_pslli_w: 262 LogicalShift = true; ShiftLeft = true; 263 break; 264 } 265 assert((LogicalShift || !ShiftLeft) && "Only logical shifts can shift left"); 266 267 // Simplify if count is constant. 268 auto Arg1 = II.getArgOperand(1); 269 auto CAZ = dyn_cast<ConstantAggregateZero>(Arg1); 270 auto CDV = dyn_cast<ConstantDataVector>(Arg1); 271 auto CInt = dyn_cast<ConstantInt>(Arg1); 272 if (!CAZ && !CDV && !CInt) 273 return nullptr; 274 275 APInt Count(64, 0); 276 if (CDV) { 277 // SSE2/AVX2 uses all the first 64-bits of the 128-bit vector 278 // operand to compute the shift amount. 279 auto VT = cast<VectorType>(CDV->getType()); 280 unsigned BitWidth = VT->getElementType()->getPrimitiveSizeInBits(); 281 assert((64 % BitWidth) == 0 && "Unexpected packed shift size"); 282 unsigned NumSubElts = 64 / BitWidth; 283 284 // Concatenate the sub-elements to create the 64-bit value. 285 for (unsigned i = 0; i != NumSubElts; ++i) { 286 unsigned SubEltIdx = (NumSubElts - 1) - i; 287 auto SubElt = cast<ConstantInt>(CDV->getElementAsConstant(SubEltIdx)); 288 Count = Count.shl(BitWidth); 289 Count |= SubElt->getValue().zextOrTrunc(64); 290 } 291 } 292 else if (CInt) 293 Count = CInt->getValue(); 294 295 auto Vec = II.getArgOperand(0); 296 auto VT = cast<VectorType>(Vec->getType()); 297 auto SVT = VT->getElementType(); 298 unsigned VWidth = VT->getNumElements(); 299 unsigned BitWidth = SVT->getPrimitiveSizeInBits(); 300 301 // If shift-by-zero then just return the original value. 302 if (Count == 0) 303 return Vec; 304 305 // Handle cases when Shift >= BitWidth. 306 if (Count.uge(BitWidth)) { 307 // If LogicalShift - just return zero. 308 if (LogicalShift) 309 return ConstantAggregateZero::get(VT); 310 311 // If ArithmeticShift - clamp Shift to (BitWidth - 1). 312 Count = APInt(64, BitWidth - 1); 313 } 314 315 // Get a constant vector of the same type as the first operand. 316 auto ShiftAmt = ConstantInt::get(SVT, Count.zextOrTrunc(BitWidth)); 317 auto ShiftVec = Builder.CreateVectorSplat(VWidth, ShiftAmt); 318 319 if (ShiftLeft) 320 return Builder.CreateShl(Vec, ShiftVec); 321 322 if (LogicalShift) 323 return Builder.CreateLShr(Vec, ShiftVec); 324 325 return Builder.CreateAShr(Vec, ShiftVec); 326 } 327 328 static Value *simplifyX86insertps(const IntrinsicInst &II, 329 InstCombiner::BuilderTy &Builder) { 330 auto *CInt = dyn_cast<ConstantInt>(II.getArgOperand(2)); 331 if (!CInt) 332 return nullptr; 333 334 VectorType *VecTy = cast<VectorType>(II.getType()); 335 assert(VecTy->getNumElements() == 4 && "insertps with wrong vector type"); 336 337 // The immediate permute control byte looks like this: 338 // [3:0] - zero mask for each 32-bit lane 339 // [5:4] - select one 32-bit destination lane 340 // [7:6] - select one 32-bit source lane 341 342 uint8_t Imm = CInt->getZExtValue(); 343 uint8_t ZMask = Imm & 0xf; 344 uint8_t DestLane = (Imm >> 4) & 0x3; 345 uint8_t SourceLane = (Imm >> 6) & 0x3; 346 347 ConstantAggregateZero *ZeroVector = ConstantAggregateZero::get(VecTy); 348 349 // If all zero mask bits are set, this was just a weird way to 350 // generate a zero vector. 351 if (ZMask == 0xf) 352 return ZeroVector; 353 354 // Initialize by passing all of the first source bits through. 355 int ShuffleMask[4] = { 0, 1, 2, 3 }; 356 357 // We may replace the second operand with the zero vector. 358 Value *V1 = II.getArgOperand(1); 359 360 if (ZMask) { 361 // If the zero mask is being used with a single input or the zero mask 362 // overrides the destination lane, this is a shuffle with the zero vector. 363 if ((II.getArgOperand(0) == II.getArgOperand(1)) || 364 (ZMask & (1 << DestLane))) { 365 V1 = ZeroVector; 366 // We may still move 32-bits of the first source vector from one lane 367 // to another. 368 ShuffleMask[DestLane] = SourceLane; 369 // The zero mask may override the previous insert operation. 370 for (unsigned i = 0; i < 4; ++i) 371 if ((ZMask >> i) & 0x1) 372 ShuffleMask[i] = i + 4; 373 } else { 374 // TODO: Model this case as 2 shuffles or a 'logical and' plus shuffle? 375 return nullptr; 376 } 377 } else { 378 // Replace the selected destination lane with the selected source lane. 379 ShuffleMask[DestLane] = SourceLane + 4; 380 } 381 382 return Builder.CreateShuffleVector(II.getArgOperand(0), V1, ShuffleMask); 383 } 384 385 /// Attempt to simplify SSE4A EXTRQ/EXTRQI instructions using constant folding 386 /// or conversion to a shuffle vector. 387 static Value *simplifyX86extrq(IntrinsicInst &II, Value *Op0, 388 ConstantInt *CILength, ConstantInt *CIIndex, 389 InstCombiner::BuilderTy &Builder) { 390 auto LowConstantHighUndef = [&](uint64_t Val) { 391 Type *IntTy64 = Type::getInt64Ty(II.getContext()); 392 Constant *Args[] = {ConstantInt::get(IntTy64, Val), 393 UndefValue::get(IntTy64)}; 394 return ConstantVector::get(Args); 395 }; 396 397 // See if we're dealing with constant values. 398 Constant *C0 = dyn_cast<Constant>(Op0); 399 ConstantInt *CI0 = 400 C0 ? dyn_cast<ConstantInt>(C0->getAggregateElement((unsigned)0)) 401 : nullptr; 402 403 // Attempt to constant fold. 404 if (CILength && CIIndex) { 405 // From AMD documentation: "The bit index and field length are each six 406 // bits in length other bits of the field are ignored." 407 APInt APIndex = CIIndex->getValue().zextOrTrunc(6); 408 APInt APLength = CILength->getValue().zextOrTrunc(6); 409 410 unsigned Index = APIndex.getZExtValue(); 411 412 // From AMD documentation: "a value of zero in the field length is 413 // defined as length of 64". 414 unsigned Length = APLength == 0 ? 64 : APLength.getZExtValue(); 415 416 // From AMD documentation: "If the sum of the bit index + length field 417 // is greater than 64, the results are undefined". 418 unsigned End = Index + Length; 419 420 // Note that both field index and field length are 8-bit quantities. 421 // Since variables 'Index' and 'Length' are unsigned values 422 // obtained from zero-extending field index and field length 423 // respectively, their sum should never wrap around. 424 if (End > 64) 425 return UndefValue::get(II.getType()); 426 427 // If we are inserting whole bytes, we can convert this to a shuffle. 428 // Lowering can recognize EXTRQI shuffle masks. 429 if ((Length % 8) == 0 && (Index % 8) == 0) { 430 // Convert bit indices to byte indices. 431 Length /= 8; 432 Index /= 8; 433 434 Type *IntTy8 = Type::getInt8Ty(II.getContext()); 435 Type *IntTy32 = Type::getInt32Ty(II.getContext()); 436 VectorType *ShufTy = VectorType::get(IntTy8, 16); 437 438 SmallVector<Constant *, 16> ShuffleMask; 439 for (int i = 0; i != (int)Length; ++i) 440 ShuffleMask.push_back( 441 Constant::getIntegerValue(IntTy32, APInt(32, i + Index))); 442 for (int i = Length; i != 8; ++i) 443 ShuffleMask.push_back( 444 Constant::getIntegerValue(IntTy32, APInt(32, i + 16))); 445 for (int i = 8; i != 16; ++i) 446 ShuffleMask.push_back(UndefValue::get(IntTy32)); 447 448 Value *SV = Builder.CreateShuffleVector( 449 Builder.CreateBitCast(Op0, ShufTy), 450 ConstantAggregateZero::get(ShufTy), ConstantVector::get(ShuffleMask)); 451 return Builder.CreateBitCast(SV, II.getType()); 452 } 453 454 // Constant Fold - shift Index'th bit to lowest position and mask off 455 // Length bits. 456 if (CI0) { 457 APInt Elt = CI0->getValue(); 458 Elt = Elt.lshr(Index).zextOrTrunc(Length); 459 return LowConstantHighUndef(Elt.getZExtValue()); 460 } 461 462 // If we were an EXTRQ call, we'll save registers if we convert to EXTRQI. 463 if (II.getIntrinsicID() == Intrinsic::x86_sse4a_extrq) { 464 Value *Args[] = {Op0, CILength, CIIndex}; 465 Module *M = II.getModule(); 466 Value *F = Intrinsic::getDeclaration(M, Intrinsic::x86_sse4a_extrqi); 467 return Builder.CreateCall(F, Args); 468 } 469 } 470 471 // Constant Fold - extraction from zero is always {zero, undef}. 472 if (CI0 && CI0->equalsInt(0)) 473 return LowConstantHighUndef(0); 474 475 return nullptr; 476 } 477 478 /// Attempt to simplify SSE4A INSERTQ/INSERTQI instructions using constant 479 /// folding or conversion to a shuffle vector. 480 static Value *simplifyX86insertq(IntrinsicInst &II, Value *Op0, Value *Op1, 481 APInt APLength, APInt APIndex, 482 InstCombiner::BuilderTy &Builder) { 483 484 // From AMD documentation: "The bit index and field length are each six bits 485 // in length other bits of the field are ignored." 486 APIndex = APIndex.zextOrTrunc(6); 487 APLength = APLength.zextOrTrunc(6); 488 489 // Attempt to constant fold. 490 unsigned Index = APIndex.getZExtValue(); 491 492 // From AMD documentation: "a value of zero in the field length is 493 // defined as length of 64". 494 unsigned Length = APLength == 0 ? 64 : APLength.getZExtValue(); 495 496 // From AMD documentation: "If the sum of the bit index + length field 497 // is greater than 64, the results are undefined". 498 unsigned End = Index + Length; 499 500 // Note that both field index and field length are 8-bit quantities. 501 // Since variables 'Index' and 'Length' are unsigned values 502 // obtained from zero-extending field index and field length 503 // respectively, their sum should never wrap around. 504 if (End > 64) 505 return UndefValue::get(II.getType()); 506 507 // If we are inserting whole bytes, we can convert this to a shuffle. 508 // Lowering can recognize INSERTQI shuffle masks. 509 if ((Length % 8) == 0 && (Index % 8) == 0) { 510 // Convert bit indices to byte indices. 511 Length /= 8; 512 Index /= 8; 513 514 Type *IntTy8 = Type::getInt8Ty(II.getContext()); 515 Type *IntTy32 = Type::getInt32Ty(II.getContext()); 516 VectorType *ShufTy = VectorType::get(IntTy8, 16); 517 518 SmallVector<Constant *, 16> ShuffleMask; 519 for (int i = 0; i != (int)Index; ++i) 520 ShuffleMask.push_back(Constant::getIntegerValue(IntTy32, APInt(32, i))); 521 for (int i = 0; i != (int)Length; ++i) 522 ShuffleMask.push_back( 523 Constant::getIntegerValue(IntTy32, APInt(32, i + 16))); 524 for (int i = Index + Length; i != 8; ++i) 525 ShuffleMask.push_back(Constant::getIntegerValue(IntTy32, APInt(32, i))); 526 for (int i = 8; i != 16; ++i) 527 ShuffleMask.push_back(UndefValue::get(IntTy32)); 528 529 Value *SV = Builder.CreateShuffleVector(Builder.CreateBitCast(Op0, ShufTy), 530 Builder.CreateBitCast(Op1, ShufTy), 531 ConstantVector::get(ShuffleMask)); 532 return Builder.CreateBitCast(SV, II.getType()); 533 } 534 535 // See if we're dealing with constant values. 536 Constant *C0 = dyn_cast<Constant>(Op0); 537 Constant *C1 = dyn_cast<Constant>(Op1); 538 ConstantInt *CI00 = 539 C0 ? dyn_cast<ConstantInt>(C0->getAggregateElement((unsigned)0)) 540 : nullptr; 541 ConstantInt *CI10 = 542 C1 ? dyn_cast<ConstantInt>(C1->getAggregateElement((unsigned)0)) 543 : nullptr; 544 545 // Constant Fold - insert bottom Length bits starting at the Index'th bit. 546 if (CI00 && CI10) { 547 APInt V00 = CI00->getValue(); 548 APInt V10 = CI10->getValue(); 549 APInt Mask = APInt::getLowBitsSet(64, Length).shl(Index); 550 V00 = V00 & ~Mask; 551 V10 = V10.zextOrTrunc(Length).zextOrTrunc(64).shl(Index); 552 APInt Val = V00 | V10; 553 Type *IntTy64 = Type::getInt64Ty(II.getContext()); 554 Constant *Args[] = {ConstantInt::get(IntTy64, Val.getZExtValue()), 555 UndefValue::get(IntTy64)}; 556 return ConstantVector::get(Args); 557 } 558 559 // If we were an INSERTQ call, we'll save demanded elements if we convert to 560 // INSERTQI. 561 if (II.getIntrinsicID() == Intrinsic::x86_sse4a_insertq) { 562 Type *IntTy8 = Type::getInt8Ty(II.getContext()); 563 Constant *CILength = ConstantInt::get(IntTy8, Length, false); 564 Constant *CIIndex = ConstantInt::get(IntTy8, Index, false); 565 566 Value *Args[] = {Op0, Op1, CILength, CIIndex}; 567 Module *M = II.getModule(); 568 Value *F = Intrinsic::getDeclaration(M, Intrinsic::x86_sse4a_insertqi); 569 return Builder.CreateCall(F, Args); 570 } 571 572 return nullptr; 573 } 574 575 /// Attempt to convert pshufb* to shufflevector if the mask is constant. 576 static Value *simplifyX86pshufb(const IntrinsicInst &II, 577 InstCombiner::BuilderTy &Builder) { 578 Constant *V = dyn_cast<Constant>(II.getArgOperand(1)); 579 if (!V) 580 return nullptr; 581 582 auto *VecTy = cast<VectorType>(II.getType()); 583 auto *MaskEltTy = Type::getInt32Ty(II.getContext()); 584 unsigned NumElts = VecTy->getNumElements(); 585 assert((NumElts == 16 || NumElts == 32) && 586 "Unexpected number of elements in shuffle mask!"); 587 588 // Construct a shuffle mask from constant integers or UNDEFs. 589 Constant *Indexes[32] = {NULL}; 590 591 // Each byte in the shuffle control mask forms an index to permute the 592 // corresponding byte in the destination operand. 593 for (unsigned I = 0; I < NumElts; ++I) { 594 Constant *COp = V->getAggregateElement(I); 595 if (!COp || (!isa<UndefValue>(COp) && !isa<ConstantInt>(COp))) 596 return nullptr; 597 598 if (isa<UndefValue>(COp)) { 599 Indexes[I] = UndefValue::get(MaskEltTy); 600 continue; 601 } 602 603 int8_t Index = cast<ConstantInt>(COp)->getValue().getZExtValue(); 604 605 // If the most significant bit (bit[7]) of each byte of the shuffle 606 // control mask is set, then zero is written in the result byte. 607 // The zero vector is in the right-hand side of the resulting 608 // shufflevector. 609 610 // The value of each index for the high 128-bit lane is the least 611 // significant 4 bits of the respective shuffle control byte. 612 Index = ((Index < 0) ? NumElts : Index & 0x0F) + (I & 0xF0); 613 Indexes[I] = ConstantInt::get(MaskEltTy, Index); 614 } 615 616 auto ShuffleMask = ConstantVector::get(makeArrayRef(Indexes, NumElts)); 617 auto V1 = II.getArgOperand(0); 618 auto V2 = Constant::getNullValue(VecTy); 619 return Builder.CreateShuffleVector(V1, V2, ShuffleMask); 620 } 621 622 /// Attempt to convert vpermilvar* to shufflevector if the mask is constant. 623 static Value *simplifyX86vpermilvar(const IntrinsicInst &II, 624 InstCombiner::BuilderTy &Builder) { 625 Constant *V = dyn_cast<Constant>(II.getArgOperand(1)); 626 if (!V) 627 return nullptr; 628 629 auto *MaskEltTy = Type::getInt32Ty(II.getContext()); 630 unsigned NumElts = cast<VectorType>(V->getType())->getNumElements(); 631 assert(NumElts == 8 || NumElts == 4 || NumElts == 2); 632 633 // Construct a shuffle mask from constant integers or UNDEFs. 634 Constant *Indexes[8] = {NULL}; 635 636 // The intrinsics only read one or two bits, clear the rest. 637 for (unsigned I = 0; I < NumElts; ++I) { 638 Constant *COp = V->getAggregateElement(I); 639 if (!COp || (!isa<UndefValue>(COp) && !isa<ConstantInt>(COp))) 640 return nullptr; 641 642 if (isa<UndefValue>(COp)) { 643 Indexes[I] = UndefValue::get(MaskEltTy); 644 continue; 645 } 646 647 APInt Index = cast<ConstantInt>(COp)->getValue(); 648 Index = Index.zextOrTrunc(32).getLoBits(2); 649 650 // The PD variants uses bit 1 to select per-lane element index, so 651 // shift down to convert to generic shuffle mask index. 652 if (II.getIntrinsicID() == Intrinsic::x86_avx_vpermilvar_pd || 653 II.getIntrinsicID() == Intrinsic::x86_avx_vpermilvar_pd_256) 654 Index = Index.lshr(1); 655 656 // The _256 variants are a bit trickier since the mask bits always index 657 // into the corresponding 128 half. In order to convert to a generic 658 // shuffle, we have to make that explicit. 659 if ((II.getIntrinsicID() == Intrinsic::x86_avx_vpermilvar_ps_256 || 660 II.getIntrinsicID() == Intrinsic::x86_avx_vpermilvar_pd_256) && 661 ((NumElts / 2) <= I)) { 662 Index += APInt(32, NumElts / 2); 663 } 664 665 Indexes[I] = ConstantInt::get(MaskEltTy, Index); 666 } 667 668 auto ShuffleMask = ConstantVector::get(makeArrayRef(Indexes, NumElts)); 669 auto V1 = II.getArgOperand(0); 670 auto V2 = UndefValue::get(V1->getType()); 671 return Builder.CreateShuffleVector(V1, V2, ShuffleMask); 672 } 673 674 /// Attempt to convert vpermd/vpermps to shufflevector if the mask is constant. 675 static Value *simplifyX86vpermv(const IntrinsicInst &II, 676 InstCombiner::BuilderTy &Builder) { 677 auto *V = dyn_cast<Constant>(II.getArgOperand(1)); 678 if (!V) 679 return nullptr; 680 681 auto *VecTy = cast<VectorType>(II.getType()); 682 auto *MaskEltTy = Type::getInt32Ty(II.getContext()); 683 unsigned Size = VecTy->getNumElements(); 684 assert(Size == 8 && "Unexpected shuffle mask size"); 685 686 // Construct a shuffle mask from constant integers or UNDEFs. 687 Constant *Indexes[8] = {NULL}; 688 689 for (unsigned I = 0; I < Size; ++I) { 690 Constant *COp = V->getAggregateElement(I); 691 if (!COp || (!isa<UndefValue>(COp) && !isa<ConstantInt>(COp))) 692 return nullptr; 693 694 if (isa<UndefValue>(COp)) { 695 Indexes[I] = UndefValue::get(MaskEltTy); 696 continue; 697 } 698 699 APInt Index = cast<ConstantInt>(COp)->getValue(); 700 Index = Index.zextOrTrunc(32).getLoBits(3); 701 Indexes[I] = ConstantInt::get(MaskEltTy, Index); 702 } 703 704 auto ShuffleMask = ConstantVector::get(makeArrayRef(Indexes, Size)); 705 auto V1 = II.getArgOperand(0); 706 auto V2 = UndefValue::get(VecTy); 707 return Builder.CreateShuffleVector(V1, V2, ShuffleMask); 708 } 709 710 /// The shuffle mask for a perm2*128 selects any two halves of two 256-bit 711 /// source vectors, unless a zero bit is set. If a zero bit is set, 712 /// then ignore that half of the mask and clear that half of the vector. 713 static Value *simplifyX86vperm2(const IntrinsicInst &II, 714 InstCombiner::BuilderTy &Builder) { 715 auto *CInt = dyn_cast<ConstantInt>(II.getArgOperand(2)); 716 if (!CInt) 717 return nullptr; 718 719 VectorType *VecTy = cast<VectorType>(II.getType()); 720 ConstantAggregateZero *ZeroVector = ConstantAggregateZero::get(VecTy); 721 722 // The immediate permute control byte looks like this: 723 // [1:0] - select 128 bits from sources for low half of destination 724 // [2] - ignore 725 // [3] - zero low half of destination 726 // [5:4] - select 128 bits from sources for high half of destination 727 // [6] - ignore 728 // [7] - zero high half of destination 729 730 uint8_t Imm = CInt->getZExtValue(); 731 732 bool LowHalfZero = Imm & 0x08; 733 bool HighHalfZero = Imm & 0x80; 734 735 // If both zero mask bits are set, this was just a weird way to 736 // generate a zero vector. 737 if (LowHalfZero && HighHalfZero) 738 return ZeroVector; 739 740 // If 0 or 1 zero mask bits are set, this is a simple shuffle. 741 unsigned NumElts = VecTy->getNumElements(); 742 unsigned HalfSize = NumElts / 2; 743 SmallVector<int, 8> ShuffleMask(NumElts); 744 745 // The high bit of the selection field chooses the 1st or 2nd operand. 746 bool LowInputSelect = Imm & 0x02; 747 bool HighInputSelect = Imm & 0x20; 748 749 // The low bit of the selection field chooses the low or high half 750 // of the selected operand. 751 bool LowHalfSelect = Imm & 0x01; 752 bool HighHalfSelect = Imm & 0x10; 753 754 // Determine which operand(s) are actually in use for this instruction. 755 Value *V0 = LowInputSelect ? II.getArgOperand(1) : II.getArgOperand(0); 756 Value *V1 = HighInputSelect ? II.getArgOperand(1) : II.getArgOperand(0); 757 758 // If needed, replace operands based on zero mask. 759 V0 = LowHalfZero ? ZeroVector : V0; 760 V1 = HighHalfZero ? ZeroVector : V1; 761 762 // Permute low half of result. 763 unsigned StartIndex = LowHalfSelect ? HalfSize : 0; 764 for (unsigned i = 0; i < HalfSize; ++i) 765 ShuffleMask[i] = StartIndex + i; 766 767 // Permute high half of result. 768 StartIndex = HighHalfSelect ? HalfSize : 0; 769 StartIndex += NumElts; 770 for (unsigned i = 0; i < HalfSize; ++i) 771 ShuffleMask[i + HalfSize] = StartIndex + i; 772 773 return Builder.CreateShuffleVector(V0, V1, ShuffleMask); 774 } 775 776 /// Decode XOP integer vector comparison intrinsics. 777 static Value *simplifyX86vpcom(const IntrinsicInst &II, 778 InstCombiner::BuilderTy &Builder, 779 bool IsSigned) { 780 if (auto *CInt = dyn_cast<ConstantInt>(II.getArgOperand(2))) { 781 uint64_t Imm = CInt->getZExtValue() & 0x7; 782 VectorType *VecTy = cast<VectorType>(II.getType()); 783 CmpInst::Predicate Pred = ICmpInst::BAD_ICMP_PREDICATE; 784 785 switch (Imm) { 786 case 0x0: 787 Pred = IsSigned ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT; 788 break; 789 case 0x1: 790 Pred = IsSigned ? ICmpInst::ICMP_SLE : ICmpInst::ICMP_ULE; 791 break; 792 case 0x2: 793 Pred = IsSigned ? ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT; 794 break; 795 case 0x3: 796 Pred = IsSigned ? ICmpInst::ICMP_SGE : ICmpInst::ICMP_UGE; 797 break; 798 case 0x4: 799 Pred = ICmpInst::ICMP_EQ; break; 800 case 0x5: 801 Pred = ICmpInst::ICMP_NE; break; 802 case 0x6: 803 return ConstantInt::getSigned(VecTy, 0); // FALSE 804 case 0x7: 805 return ConstantInt::getSigned(VecTy, -1); // TRUE 806 } 807 808 if (Value *Cmp = Builder.CreateICmp(Pred, II.getArgOperand(0), 809 II.getArgOperand(1))) 810 return Builder.CreateSExtOrTrunc(Cmp, VecTy); 811 } 812 return nullptr; 813 } 814 815 static Value *simplifyMinnumMaxnum(const IntrinsicInst &II) { 816 Value *Arg0 = II.getArgOperand(0); 817 Value *Arg1 = II.getArgOperand(1); 818 819 // fmin(x, x) -> x 820 if (Arg0 == Arg1) 821 return Arg0; 822 823 const auto *C1 = dyn_cast<ConstantFP>(Arg1); 824 825 // fmin(x, nan) -> x 826 if (C1 && C1->isNaN()) 827 return Arg0; 828 829 // This is the value because if undef were NaN, we would return the other 830 // value and cannot return a NaN unless both operands are. 831 // 832 // fmin(undef, x) -> x 833 if (isa<UndefValue>(Arg0)) 834 return Arg1; 835 836 // fmin(x, undef) -> x 837 if (isa<UndefValue>(Arg1)) 838 return Arg0; 839 840 Value *X = nullptr; 841 Value *Y = nullptr; 842 if (II.getIntrinsicID() == Intrinsic::minnum) { 843 // fmin(x, fmin(x, y)) -> fmin(x, y) 844 // fmin(y, fmin(x, y)) -> fmin(x, y) 845 if (match(Arg1, m_FMin(m_Value(X), m_Value(Y)))) { 846 if (Arg0 == X || Arg0 == Y) 847 return Arg1; 848 } 849 850 // fmin(fmin(x, y), x) -> fmin(x, y) 851 // fmin(fmin(x, y), y) -> fmin(x, y) 852 if (match(Arg0, m_FMin(m_Value(X), m_Value(Y)))) { 853 if (Arg1 == X || Arg1 == Y) 854 return Arg0; 855 } 856 857 // TODO: fmin(nnan x, inf) -> x 858 // TODO: fmin(nnan ninf x, flt_max) -> x 859 if (C1 && C1->isInfinity()) { 860 // fmin(x, -inf) -> -inf 861 if (C1->isNegative()) 862 return Arg1; 863 } 864 } else { 865 assert(II.getIntrinsicID() == Intrinsic::maxnum); 866 // fmax(x, fmax(x, y)) -> fmax(x, y) 867 // fmax(y, fmax(x, y)) -> fmax(x, y) 868 if (match(Arg1, m_FMax(m_Value(X), m_Value(Y)))) { 869 if (Arg0 == X || Arg0 == Y) 870 return Arg1; 871 } 872 873 // fmax(fmax(x, y), x) -> fmax(x, y) 874 // fmax(fmax(x, y), y) -> fmax(x, y) 875 if (match(Arg0, m_FMax(m_Value(X), m_Value(Y)))) { 876 if (Arg1 == X || Arg1 == Y) 877 return Arg0; 878 } 879 880 // TODO: fmax(nnan x, -inf) -> x 881 // TODO: fmax(nnan ninf x, -flt_max) -> x 882 if (C1 && C1->isInfinity()) { 883 // fmax(x, inf) -> inf 884 if (!C1->isNegative()) 885 return Arg1; 886 } 887 } 888 return nullptr; 889 } 890 891 static Value *simplifyMaskedLoad(const IntrinsicInst &II, 892 InstCombiner::BuilderTy &Builder) { 893 auto *ConstMask = dyn_cast<Constant>(II.getArgOperand(2)); 894 if (!ConstMask) 895 return nullptr; 896 897 // If the mask is all zeros, the "passthru" argument is the result. 898 if (ConstMask->isNullValue()) 899 return II.getArgOperand(3); 900 901 // If the mask is all ones, this is a plain vector load of the 1st argument. 902 if (ConstMask->isAllOnesValue()) { 903 Value *LoadPtr = II.getArgOperand(0); 904 unsigned Alignment = cast<ConstantInt>(II.getArgOperand(1))->getZExtValue(); 905 return Builder.CreateAlignedLoad(LoadPtr, Alignment, "unmaskedload"); 906 } 907 908 return nullptr; 909 } 910 911 static Instruction *simplifyMaskedStore(IntrinsicInst &II, InstCombiner &IC) { 912 auto *ConstMask = dyn_cast<Constant>(II.getArgOperand(3)); 913 if (!ConstMask) 914 return nullptr; 915 916 // If the mask is all zeros, this instruction does nothing. 917 if (ConstMask->isNullValue()) 918 return IC.eraseInstFromFunction(II); 919 920 // If the mask is all ones, this is a plain vector store of the 1st argument. 921 if (ConstMask->isAllOnesValue()) { 922 Value *StorePtr = II.getArgOperand(1); 923 unsigned Alignment = cast<ConstantInt>(II.getArgOperand(2))->getZExtValue(); 924 return new StoreInst(II.getArgOperand(0), StorePtr, false, Alignment); 925 } 926 927 return nullptr; 928 } 929 930 static Instruction *simplifyMaskedGather(IntrinsicInst &II, InstCombiner &IC) { 931 // If the mask is all zeros, return the "passthru" argument of the gather. 932 auto *ConstMask = dyn_cast<Constant>(II.getArgOperand(2)); 933 if (ConstMask && ConstMask->isNullValue()) 934 return IC.replaceInstUsesWith(II, II.getArgOperand(3)); 935 936 return nullptr; 937 } 938 939 static Instruction *simplifyMaskedScatter(IntrinsicInst &II, InstCombiner &IC) { 940 // If the mask is all zeros, a scatter does nothing. 941 auto *ConstMask = dyn_cast<Constant>(II.getArgOperand(3)); 942 if (ConstMask && ConstMask->isNullValue()) 943 return IC.eraseInstFromFunction(II); 944 945 return nullptr; 946 } 947 948 // TODO: If the x86 backend knew how to convert a bool vector mask back to an 949 // XMM register mask efficiently, we could transform all x86 masked intrinsics 950 // to LLVM masked intrinsics and remove the x86 masked intrinsic defs. 951 static Instruction *simplifyX86MaskedLoad(IntrinsicInst &II, InstCombiner &IC) { 952 Value *Ptr = II.getOperand(0); 953 Value *Mask = II.getOperand(1); 954 Constant *ZeroVec = Constant::getNullValue(II.getType()); 955 956 // Special case a zero mask since that's not a ConstantDataVector. 957 // This masked load instruction creates a zero vector. 958 if (isa<ConstantAggregateZero>(Mask)) 959 return IC.replaceInstUsesWith(II, ZeroVec); 960 961 auto *ConstMask = dyn_cast<ConstantDataVector>(Mask); 962 if (!ConstMask) 963 return nullptr; 964 965 // The mask is constant. Convert this x86 intrinsic to the LLVM instrinsic 966 // to allow target-independent optimizations. 967 968 // First, cast the x86 intrinsic scalar pointer to a vector pointer to match 969 // the LLVM intrinsic definition for the pointer argument. 970 unsigned AddrSpace = cast<PointerType>(Ptr->getType())->getAddressSpace(); 971 PointerType *VecPtrTy = PointerType::get(II.getType(), AddrSpace); 972 Value *PtrCast = IC.Builder->CreateBitCast(Ptr, VecPtrTy, "castvec"); 973 974 // Second, convert the x86 XMM integer vector mask to a vector of bools based 975 // on each element's most significant bit (the sign bit). 976 Constant *BoolMask = getNegativeIsTrueBoolVec(ConstMask); 977 978 // The pass-through vector for an x86 masked load is a zero vector. 979 CallInst *NewMaskedLoad = 980 IC.Builder->CreateMaskedLoad(PtrCast, 1, BoolMask, ZeroVec); 981 return IC.replaceInstUsesWith(II, NewMaskedLoad); 982 } 983 984 // TODO: If the x86 backend knew how to convert a bool vector mask back to an 985 // XMM register mask efficiently, we could transform all x86 masked intrinsics 986 // to LLVM masked intrinsics and remove the x86 masked intrinsic defs. 987 static bool simplifyX86MaskedStore(IntrinsicInst &II, InstCombiner &IC) { 988 Value *Ptr = II.getOperand(0); 989 Value *Mask = II.getOperand(1); 990 Value *Vec = II.getOperand(2); 991 992 // Special case a zero mask since that's not a ConstantDataVector: 993 // this masked store instruction does nothing. 994 if (isa<ConstantAggregateZero>(Mask)) { 995 IC.eraseInstFromFunction(II); 996 return true; 997 } 998 999 // The SSE2 version is too weird (eg, unaligned but non-temporal) to do 1000 // anything else at this level. 1001 if (II.getIntrinsicID() == Intrinsic::x86_sse2_maskmov_dqu) 1002 return false; 1003 1004 auto *ConstMask = dyn_cast<ConstantDataVector>(Mask); 1005 if (!ConstMask) 1006 return false; 1007 1008 // The mask is constant. Convert this x86 intrinsic to the LLVM instrinsic 1009 // to allow target-independent optimizations. 1010 1011 // First, cast the x86 intrinsic scalar pointer to a vector pointer to match 1012 // the LLVM intrinsic definition for the pointer argument. 1013 unsigned AddrSpace = cast<PointerType>(Ptr->getType())->getAddressSpace(); 1014 PointerType *VecPtrTy = PointerType::get(Vec->getType(), AddrSpace); 1015 Value *PtrCast = IC.Builder->CreateBitCast(Ptr, VecPtrTy, "castvec"); 1016 1017 // Second, convert the x86 XMM integer vector mask to a vector of bools based 1018 // on each element's most significant bit (the sign bit). 1019 Constant *BoolMask = getNegativeIsTrueBoolVec(ConstMask); 1020 1021 IC.Builder->CreateMaskedStore(Vec, PtrCast, 1, BoolMask); 1022 1023 // 'Replace uses' doesn't work for stores. Erase the original masked store. 1024 IC.eraseInstFromFunction(II); 1025 return true; 1026 } 1027 1028 // Returns true iff the 2 intrinsics have the same operands, limiting the 1029 // comparison to the first NumOperands. 1030 static bool haveSameOperands(const IntrinsicInst &I, const IntrinsicInst &E, 1031 unsigned NumOperands) { 1032 assert(I.getNumArgOperands() >= NumOperands && "Not enough operands"); 1033 assert(E.getNumArgOperands() >= NumOperands && "Not enough operands"); 1034 for (unsigned i = 0; i < NumOperands; i++) 1035 if (I.getArgOperand(i) != E.getArgOperand(i)) 1036 return false; 1037 return true; 1038 } 1039 1040 // Remove trivially empty start/end intrinsic ranges, i.e. a start 1041 // immediately followed by an end (ignoring debuginfo or other 1042 // start/end intrinsics in between). As this handles only the most trivial 1043 // cases, tracking the nesting level is not needed: 1044 // 1045 // call @llvm.foo.start(i1 0) ; &I 1046 // call @llvm.foo.start(i1 0) 1047 // call @llvm.foo.end(i1 0) ; This one will not be skipped: it will be removed 1048 // call @llvm.foo.end(i1 0) 1049 static bool removeTriviallyEmptyRange(IntrinsicInst &I, unsigned StartID, 1050 unsigned EndID, InstCombiner &IC) { 1051 assert(I.getIntrinsicID() == StartID && 1052 "Start intrinsic does not have expected ID"); 1053 BasicBlock::iterator BI(I), BE(I.getParent()->end()); 1054 for (++BI; BI != BE; ++BI) { 1055 if (auto *E = dyn_cast<IntrinsicInst>(BI)) { 1056 if (isa<DbgInfoIntrinsic>(E) || E->getIntrinsicID() == StartID) 1057 continue; 1058 if (E->getIntrinsicID() == EndID && 1059 haveSameOperands(I, *E, E->getNumArgOperands())) { 1060 IC.eraseInstFromFunction(*E); 1061 IC.eraseInstFromFunction(I); 1062 return true; 1063 } 1064 } 1065 break; 1066 } 1067 1068 return false; 1069 } 1070 1071 Instruction *InstCombiner::visitVAStartInst(VAStartInst &I) { 1072 removeTriviallyEmptyRange(I, Intrinsic::vastart, Intrinsic::vaend, *this); 1073 return nullptr; 1074 } 1075 1076 Instruction *InstCombiner::visitVACopyInst(VACopyInst &I) { 1077 removeTriviallyEmptyRange(I, Intrinsic::vacopy, Intrinsic::vaend, *this); 1078 return nullptr; 1079 } 1080 1081 /// CallInst simplification. This mostly only handles folding of intrinsic 1082 /// instructions. For normal calls, it allows visitCallSite to do the heavy 1083 /// lifting. 1084 Instruction *InstCombiner::visitCallInst(CallInst &CI) { 1085 auto Args = CI.arg_operands(); 1086 if (Value *V = SimplifyCall(CI.getCalledValue(), Args.begin(), Args.end(), DL, 1087 TLI, DT, AC)) 1088 return replaceInstUsesWith(CI, V); 1089 1090 if (isFreeCall(&CI, TLI)) 1091 return visitFree(CI); 1092 1093 // If the caller function is nounwind, mark the call as nounwind, even if the 1094 // callee isn't. 1095 if (CI.getParent()->getParent()->doesNotThrow() && 1096 !CI.doesNotThrow()) { 1097 CI.setDoesNotThrow(); 1098 return &CI; 1099 } 1100 1101 IntrinsicInst *II = dyn_cast<IntrinsicInst>(&CI); 1102 if (!II) return visitCallSite(&CI); 1103 1104 // Intrinsics cannot occur in an invoke, so handle them here instead of in 1105 // visitCallSite. 1106 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(II)) { 1107 bool Changed = false; 1108 1109 // memmove/cpy/set of zero bytes is a noop. 1110 if (Constant *NumBytes = dyn_cast<Constant>(MI->getLength())) { 1111 if (NumBytes->isNullValue()) 1112 return eraseInstFromFunction(CI); 1113 1114 if (ConstantInt *CI = dyn_cast<ConstantInt>(NumBytes)) 1115 if (CI->getZExtValue() == 1) { 1116 // Replace the instruction with just byte operations. We would 1117 // transform other cases to loads/stores, but we don't know if 1118 // alignment is sufficient. 1119 } 1120 } 1121 1122 // No other transformations apply to volatile transfers. 1123 if (MI->isVolatile()) 1124 return nullptr; 1125 1126 // If we have a memmove and the source operation is a constant global, 1127 // then the source and dest pointers can't alias, so we can change this 1128 // into a call to memcpy. 1129 if (MemMoveInst *MMI = dyn_cast<MemMoveInst>(MI)) { 1130 if (GlobalVariable *GVSrc = dyn_cast<GlobalVariable>(MMI->getSource())) 1131 if (GVSrc->isConstant()) { 1132 Module *M = CI.getModule(); 1133 Intrinsic::ID MemCpyID = Intrinsic::memcpy; 1134 Type *Tys[3] = { CI.getArgOperand(0)->getType(), 1135 CI.getArgOperand(1)->getType(), 1136 CI.getArgOperand(2)->getType() }; 1137 CI.setCalledFunction(Intrinsic::getDeclaration(M, MemCpyID, Tys)); 1138 Changed = true; 1139 } 1140 } 1141 1142 if (MemTransferInst *MTI = dyn_cast<MemTransferInst>(MI)) { 1143 // memmove(x,x,size) -> noop. 1144 if (MTI->getSource() == MTI->getDest()) 1145 return eraseInstFromFunction(CI); 1146 } 1147 1148 // If we can determine a pointer alignment that is bigger than currently 1149 // set, update the alignment. 1150 if (isa<MemTransferInst>(MI)) { 1151 if (Instruction *I = SimplifyMemTransfer(MI)) 1152 return I; 1153 } else if (MemSetInst *MSI = dyn_cast<MemSetInst>(MI)) { 1154 if (Instruction *I = SimplifyMemSet(MSI)) 1155 return I; 1156 } 1157 1158 if (Changed) return II; 1159 } 1160 1161 auto SimplifyDemandedVectorEltsLow = [this](Value *Op, unsigned Width, 1162 unsigned DemandedWidth) { 1163 APInt UndefElts(Width, 0); 1164 APInt DemandedElts = APInt::getLowBitsSet(Width, DemandedWidth); 1165 return SimplifyDemandedVectorElts(Op, DemandedElts, UndefElts); 1166 }; 1167 auto SimplifyDemandedVectorEltsHigh = [this](Value *Op, unsigned Width, 1168 unsigned DemandedWidth) { 1169 APInt UndefElts(Width, 0); 1170 APInt DemandedElts = APInt::getHighBitsSet(Width, DemandedWidth); 1171 return SimplifyDemandedVectorElts(Op, DemandedElts, UndefElts); 1172 }; 1173 1174 switch (II->getIntrinsicID()) { 1175 default: break; 1176 case Intrinsic::objectsize: { 1177 uint64_t Size; 1178 if (getObjectSize(II->getArgOperand(0), Size, DL, TLI)) { 1179 APInt APSize(II->getType()->getIntegerBitWidth(), Size); 1180 // Equality check to be sure that `Size` can fit in a value of type 1181 // `II->getType()` 1182 if (APSize == Size) 1183 return replaceInstUsesWith(CI, ConstantInt::get(II->getType(), APSize)); 1184 } 1185 return nullptr; 1186 } 1187 case Intrinsic::bswap: { 1188 Value *IIOperand = II->getArgOperand(0); 1189 Value *X = nullptr; 1190 1191 // bswap(bswap(x)) -> x 1192 if (match(IIOperand, m_BSwap(m_Value(X)))) 1193 return replaceInstUsesWith(CI, X); 1194 1195 // bswap(trunc(bswap(x))) -> trunc(lshr(x, c)) 1196 if (match(IIOperand, m_Trunc(m_BSwap(m_Value(X))))) { 1197 unsigned C = X->getType()->getPrimitiveSizeInBits() - 1198 IIOperand->getType()->getPrimitiveSizeInBits(); 1199 Value *CV = ConstantInt::get(X->getType(), C); 1200 Value *V = Builder->CreateLShr(X, CV); 1201 return new TruncInst(V, IIOperand->getType()); 1202 } 1203 break; 1204 } 1205 1206 case Intrinsic::bitreverse: { 1207 Value *IIOperand = II->getArgOperand(0); 1208 Value *X = nullptr; 1209 1210 // bitreverse(bitreverse(x)) -> x 1211 if (match(IIOperand, m_Intrinsic<Intrinsic::bitreverse>(m_Value(X)))) 1212 return replaceInstUsesWith(CI, X); 1213 break; 1214 } 1215 1216 case Intrinsic::masked_load: 1217 if (Value *SimplifiedMaskedOp = simplifyMaskedLoad(*II, *Builder)) 1218 return replaceInstUsesWith(CI, SimplifiedMaskedOp); 1219 break; 1220 case Intrinsic::masked_store: 1221 return simplifyMaskedStore(*II, *this); 1222 case Intrinsic::masked_gather: 1223 return simplifyMaskedGather(*II, *this); 1224 case Intrinsic::masked_scatter: 1225 return simplifyMaskedScatter(*II, *this); 1226 1227 case Intrinsic::powi: 1228 if (ConstantInt *Power = dyn_cast<ConstantInt>(II->getArgOperand(1))) { 1229 // powi(x, 0) -> 1.0 1230 if (Power->isZero()) 1231 return replaceInstUsesWith(CI, ConstantFP::get(CI.getType(), 1.0)); 1232 // powi(x, 1) -> x 1233 if (Power->isOne()) 1234 return replaceInstUsesWith(CI, II->getArgOperand(0)); 1235 // powi(x, -1) -> 1/x 1236 if (Power->isAllOnesValue()) 1237 return BinaryOperator::CreateFDiv(ConstantFP::get(CI.getType(), 1.0), 1238 II->getArgOperand(0)); 1239 } 1240 break; 1241 case Intrinsic::cttz: { 1242 // If all bits below the first known one are known zero, 1243 // this value is constant. 1244 IntegerType *IT = dyn_cast<IntegerType>(II->getArgOperand(0)->getType()); 1245 // FIXME: Try to simplify vectors of integers. 1246 if (!IT) break; 1247 uint32_t BitWidth = IT->getBitWidth(); 1248 APInt KnownZero(BitWidth, 0); 1249 APInt KnownOne(BitWidth, 0); 1250 computeKnownBits(II->getArgOperand(0), KnownZero, KnownOne, 0, II); 1251 unsigned TrailingZeros = KnownOne.countTrailingZeros(); 1252 APInt Mask(APInt::getLowBitsSet(BitWidth, TrailingZeros)); 1253 if ((Mask & KnownZero) == Mask) 1254 return replaceInstUsesWith(CI, ConstantInt::get(IT, 1255 APInt(BitWidth, TrailingZeros))); 1256 1257 } 1258 break; 1259 case Intrinsic::ctlz: { 1260 // If all bits above the first known one are known zero, 1261 // this value is constant. 1262 IntegerType *IT = dyn_cast<IntegerType>(II->getArgOperand(0)->getType()); 1263 // FIXME: Try to simplify vectors of integers. 1264 if (!IT) break; 1265 uint32_t BitWidth = IT->getBitWidth(); 1266 APInt KnownZero(BitWidth, 0); 1267 APInt KnownOne(BitWidth, 0); 1268 computeKnownBits(II->getArgOperand(0), KnownZero, KnownOne, 0, II); 1269 unsigned LeadingZeros = KnownOne.countLeadingZeros(); 1270 APInt Mask(APInt::getHighBitsSet(BitWidth, LeadingZeros)); 1271 if ((Mask & KnownZero) == Mask) 1272 return replaceInstUsesWith(CI, ConstantInt::get(IT, 1273 APInt(BitWidth, LeadingZeros))); 1274 1275 } 1276 break; 1277 1278 case Intrinsic::uadd_with_overflow: 1279 case Intrinsic::sadd_with_overflow: 1280 case Intrinsic::umul_with_overflow: 1281 case Intrinsic::smul_with_overflow: 1282 if (isa<Constant>(II->getArgOperand(0)) && 1283 !isa<Constant>(II->getArgOperand(1))) { 1284 // Canonicalize constants into the RHS. 1285 Value *LHS = II->getArgOperand(0); 1286 II->setArgOperand(0, II->getArgOperand(1)); 1287 II->setArgOperand(1, LHS); 1288 return II; 1289 } 1290 // fall through 1291 1292 case Intrinsic::usub_with_overflow: 1293 case Intrinsic::ssub_with_overflow: { 1294 OverflowCheckFlavor OCF = 1295 IntrinsicIDToOverflowCheckFlavor(II->getIntrinsicID()); 1296 assert(OCF != OCF_INVALID && "unexpected!"); 1297 1298 Value *OperationResult = nullptr; 1299 Constant *OverflowResult = nullptr; 1300 if (OptimizeOverflowCheck(OCF, II->getArgOperand(0), II->getArgOperand(1), 1301 *II, OperationResult, OverflowResult)) 1302 return CreateOverflowTuple(II, OperationResult, OverflowResult); 1303 1304 break; 1305 } 1306 1307 case Intrinsic::minnum: 1308 case Intrinsic::maxnum: { 1309 Value *Arg0 = II->getArgOperand(0); 1310 Value *Arg1 = II->getArgOperand(1); 1311 // Canonicalize constants to the RHS. 1312 if (isa<ConstantFP>(Arg0) && !isa<ConstantFP>(Arg1)) { 1313 II->setArgOperand(0, Arg1); 1314 II->setArgOperand(1, Arg0); 1315 return II; 1316 } 1317 if (Value *V = simplifyMinnumMaxnum(*II)) 1318 return replaceInstUsesWith(*II, V); 1319 break; 1320 } 1321 case Intrinsic::ppc_altivec_lvx: 1322 case Intrinsic::ppc_altivec_lvxl: 1323 // Turn PPC lvx -> load if the pointer is known aligned. 1324 if (getOrEnforceKnownAlignment(II->getArgOperand(0), 16, DL, II, AC, DT) >= 1325 16) { 1326 Value *Ptr = Builder->CreateBitCast(II->getArgOperand(0), 1327 PointerType::getUnqual(II->getType())); 1328 return new LoadInst(Ptr); 1329 } 1330 break; 1331 case Intrinsic::ppc_vsx_lxvw4x: 1332 case Intrinsic::ppc_vsx_lxvd2x: { 1333 // Turn PPC VSX loads into normal loads. 1334 Value *Ptr = Builder->CreateBitCast(II->getArgOperand(0), 1335 PointerType::getUnqual(II->getType())); 1336 return new LoadInst(Ptr, Twine(""), false, 1); 1337 } 1338 case Intrinsic::ppc_altivec_stvx: 1339 case Intrinsic::ppc_altivec_stvxl: 1340 // Turn stvx -> store if the pointer is known aligned. 1341 if (getOrEnforceKnownAlignment(II->getArgOperand(1), 16, DL, II, AC, DT) >= 1342 16) { 1343 Type *OpPtrTy = 1344 PointerType::getUnqual(II->getArgOperand(0)->getType()); 1345 Value *Ptr = Builder->CreateBitCast(II->getArgOperand(1), OpPtrTy); 1346 return new StoreInst(II->getArgOperand(0), Ptr); 1347 } 1348 break; 1349 case Intrinsic::ppc_vsx_stxvw4x: 1350 case Intrinsic::ppc_vsx_stxvd2x: { 1351 // Turn PPC VSX stores into normal stores. 1352 Type *OpPtrTy = PointerType::getUnqual(II->getArgOperand(0)->getType()); 1353 Value *Ptr = Builder->CreateBitCast(II->getArgOperand(1), OpPtrTy); 1354 return new StoreInst(II->getArgOperand(0), Ptr, false, 1); 1355 } 1356 case Intrinsic::ppc_qpx_qvlfs: 1357 // Turn PPC QPX qvlfs -> load if the pointer is known aligned. 1358 if (getOrEnforceKnownAlignment(II->getArgOperand(0), 16, DL, II, AC, DT) >= 1359 16) { 1360 Type *VTy = VectorType::get(Builder->getFloatTy(), 1361 II->getType()->getVectorNumElements()); 1362 Value *Ptr = Builder->CreateBitCast(II->getArgOperand(0), 1363 PointerType::getUnqual(VTy)); 1364 Value *Load = Builder->CreateLoad(Ptr); 1365 return new FPExtInst(Load, II->getType()); 1366 } 1367 break; 1368 case Intrinsic::ppc_qpx_qvlfd: 1369 // Turn PPC QPX qvlfd -> load if the pointer is known aligned. 1370 if (getOrEnforceKnownAlignment(II->getArgOperand(0), 32, DL, II, AC, DT) >= 1371 32) { 1372 Value *Ptr = Builder->CreateBitCast(II->getArgOperand(0), 1373 PointerType::getUnqual(II->getType())); 1374 return new LoadInst(Ptr); 1375 } 1376 break; 1377 case Intrinsic::ppc_qpx_qvstfs: 1378 // Turn PPC QPX qvstfs -> store if the pointer is known aligned. 1379 if (getOrEnforceKnownAlignment(II->getArgOperand(1), 16, DL, II, AC, DT) >= 1380 16) { 1381 Type *VTy = VectorType::get(Builder->getFloatTy(), 1382 II->getArgOperand(0)->getType()->getVectorNumElements()); 1383 Value *TOp = Builder->CreateFPTrunc(II->getArgOperand(0), VTy); 1384 Type *OpPtrTy = PointerType::getUnqual(VTy); 1385 Value *Ptr = Builder->CreateBitCast(II->getArgOperand(1), OpPtrTy); 1386 return new StoreInst(TOp, Ptr); 1387 } 1388 break; 1389 case Intrinsic::ppc_qpx_qvstfd: 1390 // Turn PPC QPX qvstfd -> store if the pointer is known aligned. 1391 if (getOrEnforceKnownAlignment(II->getArgOperand(1), 32, DL, II, AC, DT) >= 1392 32) { 1393 Type *OpPtrTy = 1394 PointerType::getUnqual(II->getArgOperand(0)->getType()); 1395 Value *Ptr = Builder->CreateBitCast(II->getArgOperand(1), OpPtrTy); 1396 return new StoreInst(II->getArgOperand(0), Ptr); 1397 } 1398 break; 1399 1400 case Intrinsic::x86_vcvtph2ps_128: 1401 case Intrinsic::x86_vcvtph2ps_256: { 1402 auto Arg = II->getArgOperand(0); 1403 auto ArgType = cast<VectorType>(Arg->getType()); 1404 auto RetType = cast<VectorType>(II->getType()); 1405 unsigned ArgWidth = ArgType->getNumElements(); 1406 unsigned RetWidth = RetType->getNumElements(); 1407 assert(RetWidth <= ArgWidth && "Unexpected input/return vector widths"); 1408 assert(ArgType->isIntOrIntVectorTy() && 1409 ArgType->getScalarSizeInBits() == 16 && 1410 "CVTPH2PS input type should be 16-bit integer vector"); 1411 assert(RetType->getScalarType()->isFloatTy() && 1412 "CVTPH2PS output type should be 32-bit float vector"); 1413 1414 // Constant folding: Convert to generic half to single conversion. 1415 if (isa<ConstantAggregateZero>(Arg)) 1416 return replaceInstUsesWith(*II, ConstantAggregateZero::get(RetType)); 1417 1418 if (isa<ConstantDataVector>(Arg)) { 1419 auto VectorHalfAsShorts = Arg; 1420 if (RetWidth < ArgWidth) { 1421 SmallVector<int, 8> SubVecMask; 1422 for (unsigned i = 0; i != RetWidth; ++i) 1423 SubVecMask.push_back((int)i); 1424 VectorHalfAsShorts = Builder->CreateShuffleVector( 1425 Arg, UndefValue::get(ArgType), SubVecMask); 1426 } 1427 1428 auto VectorHalfType = 1429 VectorType::get(Type::getHalfTy(II->getContext()), RetWidth); 1430 auto VectorHalfs = 1431 Builder->CreateBitCast(VectorHalfAsShorts, VectorHalfType); 1432 auto VectorFloats = Builder->CreateFPExt(VectorHalfs, RetType); 1433 return replaceInstUsesWith(*II, VectorFloats); 1434 } 1435 1436 // We only use the lowest lanes of the argument. 1437 if (Value *V = SimplifyDemandedVectorEltsLow(Arg, ArgWidth, RetWidth)) { 1438 II->setArgOperand(0, V); 1439 return II; 1440 } 1441 break; 1442 } 1443 1444 case Intrinsic::x86_sse_cvtss2si: 1445 case Intrinsic::x86_sse_cvtss2si64: 1446 case Intrinsic::x86_sse_cvttss2si: 1447 case Intrinsic::x86_sse_cvttss2si64: 1448 case Intrinsic::x86_sse2_cvtsd2si: 1449 case Intrinsic::x86_sse2_cvtsd2si64: 1450 case Intrinsic::x86_sse2_cvttsd2si: 1451 case Intrinsic::x86_sse2_cvttsd2si64: { 1452 // These intrinsics only demand the 0th element of their input vectors. If 1453 // we can simplify the input based on that, do so now. 1454 Value *Arg = II->getArgOperand(0); 1455 unsigned VWidth = Arg->getType()->getVectorNumElements(); 1456 if (Value *V = SimplifyDemandedVectorEltsLow(Arg, VWidth, 1)) { 1457 II->setArgOperand(0, V); 1458 return II; 1459 } 1460 break; 1461 } 1462 1463 case Intrinsic::x86_sse_comieq_ss: 1464 case Intrinsic::x86_sse_comige_ss: 1465 case Intrinsic::x86_sse_comigt_ss: 1466 case Intrinsic::x86_sse_comile_ss: 1467 case Intrinsic::x86_sse_comilt_ss: 1468 case Intrinsic::x86_sse_comineq_ss: 1469 case Intrinsic::x86_sse_ucomieq_ss: 1470 case Intrinsic::x86_sse_ucomige_ss: 1471 case Intrinsic::x86_sse_ucomigt_ss: 1472 case Intrinsic::x86_sse_ucomile_ss: 1473 case Intrinsic::x86_sse_ucomilt_ss: 1474 case Intrinsic::x86_sse_ucomineq_ss: 1475 case Intrinsic::x86_sse2_comieq_sd: 1476 case Intrinsic::x86_sse2_comige_sd: 1477 case Intrinsic::x86_sse2_comigt_sd: 1478 case Intrinsic::x86_sse2_comile_sd: 1479 case Intrinsic::x86_sse2_comilt_sd: 1480 case Intrinsic::x86_sse2_comineq_sd: 1481 case Intrinsic::x86_sse2_ucomieq_sd: 1482 case Intrinsic::x86_sse2_ucomige_sd: 1483 case Intrinsic::x86_sse2_ucomigt_sd: 1484 case Intrinsic::x86_sse2_ucomile_sd: 1485 case Intrinsic::x86_sse2_ucomilt_sd: 1486 case Intrinsic::x86_sse2_ucomineq_sd: { 1487 // These intrinsics only demand the 0th element of their input vectors. If 1488 // we can simplify the input based on that, do so now. 1489 bool MadeChange = false; 1490 Value *Arg0 = II->getArgOperand(0); 1491 Value *Arg1 = II->getArgOperand(1); 1492 unsigned VWidth = Arg0->getType()->getVectorNumElements(); 1493 if (Value *V = SimplifyDemandedVectorEltsLow(Arg0, VWidth, 1)) { 1494 II->setArgOperand(0, V); 1495 MadeChange = true; 1496 } 1497 if (Value *V = SimplifyDemandedVectorEltsLow(Arg1, VWidth, 1)) { 1498 II->setArgOperand(1, V); 1499 MadeChange = true; 1500 } 1501 if (MadeChange) 1502 return II; 1503 break; 1504 } 1505 1506 case Intrinsic::x86_sse_add_ss: 1507 case Intrinsic::x86_sse_sub_ss: 1508 case Intrinsic::x86_sse_mul_ss: 1509 case Intrinsic::x86_sse_div_ss: 1510 case Intrinsic::x86_sse_min_ss: 1511 case Intrinsic::x86_sse_max_ss: 1512 case Intrinsic::x86_sse_cmp_ss: 1513 case Intrinsic::x86_sse2_add_sd: 1514 case Intrinsic::x86_sse2_sub_sd: 1515 case Intrinsic::x86_sse2_mul_sd: 1516 case Intrinsic::x86_sse2_div_sd: 1517 case Intrinsic::x86_sse2_min_sd: 1518 case Intrinsic::x86_sse2_max_sd: 1519 case Intrinsic::x86_sse2_cmp_sd: { 1520 // These intrinsics only demand the lowest element of the second input 1521 // vector. 1522 Value *Arg1 = II->getArgOperand(1); 1523 unsigned VWidth = Arg1->getType()->getVectorNumElements(); 1524 if (Value *V = SimplifyDemandedVectorEltsLow(Arg1, VWidth, 1)) { 1525 II->setArgOperand(1, V); 1526 return II; 1527 } 1528 break; 1529 } 1530 1531 case Intrinsic::x86_sse41_round_ss: 1532 case Intrinsic::x86_sse41_round_sd: { 1533 // These intrinsics demand the upper elements of the first input vector and 1534 // the lowest element of the second input vector. 1535 bool MadeChange = false; 1536 Value *Arg0 = II->getArgOperand(0); 1537 Value *Arg1 = II->getArgOperand(1); 1538 unsigned VWidth = Arg0->getType()->getVectorNumElements(); 1539 if (Value *V = SimplifyDemandedVectorEltsHigh(Arg0, VWidth, VWidth - 1)) { 1540 II->setArgOperand(0, V); 1541 MadeChange = true; 1542 } 1543 if (Value *V = SimplifyDemandedVectorEltsLow(Arg1, VWidth, 1)) { 1544 II->setArgOperand(1, V); 1545 MadeChange = true; 1546 } 1547 if (MadeChange) 1548 return II; 1549 break; 1550 } 1551 1552 // Constant fold ashr( <A x Bi>, Ci ). 1553 // Constant fold lshr( <A x Bi>, Ci ). 1554 // Constant fold shl( <A x Bi>, Ci ). 1555 case Intrinsic::x86_sse2_psrai_d: 1556 case Intrinsic::x86_sse2_psrai_w: 1557 case Intrinsic::x86_avx2_psrai_d: 1558 case Intrinsic::x86_avx2_psrai_w: 1559 case Intrinsic::x86_sse2_psrli_d: 1560 case Intrinsic::x86_sse2_psrli_q: 1561 case Intrinsic::x86_sse2_psrli_w: 1562 case Intrinsic::x86_avx2_psrli_d: 1563 case Intrinsic::x86_avx2_psrli_q: 1564 case Intrinsic::x86_avx2_psrli_w: 1565 case Intrinsic::x86_sse2_pslli_d: 1566 case Intrinsic::x86_sse2_pslli_q: 1567 case Intrinsic::x86_sse2_pslli_w: 1568 case Intrinsic::x86_avx2_pslli_d: 1569 case Intrinsic::x86_avx2_pslli_q: 1570 case Intrinsic::x86_avx2_pslli_w: 1571 if (Value *V = simplifyX86immShift(*II, *Builder)) 1572 return replaceInstUsesWith(*II, V); 1573 break; 1574 1575 case Intrinsic::x86_sse2_psra_d: 1576 case Intrinsic::x86_sse2_psra_w: 1577 case Intrinsic::x86_avx2_psra_d: 1578 case Intrinsic::x86_avx2_psra_w: 1579 case Intrinsic::x86_sse2_psrl_d: 1580 case Intrinsic::x86_sse2_psrl_q: 1581 case Intrinsic::x86_sse2_psrl_w: 1582 case Intrinsic::x86_avx2_psrl_d: 1583 case Intrinsic::x86_avx2_psrl_q: 1584 case Intrinsic::x86_avx2_psrl_w: 1585 case Intrinsic::x86_sse2_psll_d: 1586 case Intrinsic::x86_sse2_psll_q: 1587 case Intrinsic::x86_sse2_psll_w: 1588 case Intrinsic::x86_avx2_psll_d: 1589 case Intrinsic::x86_avx2_psll_q: 1590 case Intrinsic::x86_avx2_psll_w: { 1591 if (Value *V = simplifyX86immShift(*II, *Builder)) 1592 return replaceInstUsesWith(*II, V); 1593 1594 // SSE2/AVX2 uses only the first 64-bits of the 128-bit vector 1595 // operand to compute the shift amount. 1596 Value *Arg1 = II->getArgOperand(1); 1597 assert(Arg1->getType()->getPrimitiveSizeInBits() == 128 && 1598 "Unexpected packed shift size"); 1599 unsigned VWidth = Arg1->getType()->getVectorNumElements(); 1600 1601 if (Value *V = SimplifyDemandedVectorEltsLow(Arg1, VWidth, VWidth / 2)) { 1602 II->setArgOperand(1, V); 1603 return II; 1604 } 1605 break; 1606 } 1607 1608 case Intrinsic::x86_sse41_insertps: 1609 if (Value *V = simplifyX86insertps(*II, *Builder)) 1610 return replaceInstUsesWith(*II, V); 1611 break; 1612 1613 case Intrinsic::x86_sse4a_extrq: { 1614 Value *Op0 = II->getArgOperand(0); 1615 Value *Op1 = II->getArgOperand(1); 1616 unsigned VWidth0 = Op0->getType()->getVectorNumElements(); 1617 unsigned VWidth1 = Op1->getType()->getVectorNumElements(); 1618 assert(Op0->getType()->getPrimitiveSizeInBits() == 128 && 1619 Op1->getType()->getPrimitiveSizeInBits() == 128 && VWidth0 == 2 && 1620 VWidth1 == 16 && "Unexpected operand sizes"); 1621 1622 // See if we're dealing with constant values. 1623 Constant *C1 = dyn_cast<Constant>(Op1); 1624 ConstantInt *CILength = 1625 C1 ? dyn_cast<ConstantInt>(C1->getAggregateElement((unsigned)0)) 1626 : nullptr; 1627 ConstantInt *CIIndex = 1628 C1 ? dyn_cast<ConstantInt>(C1->getAggregateElement((unsigned)1)) 1629 : nullptr; 1630 1631 // Attempt to simplify to a constant, shuffle vector or EXTRQI call. 1632 if (Value *V = simplifyX86extrq(*II, Op0, CILength, CIIndex, *Builder)) 1633 return replaceInstUsesWith(*II, V); 1634 1635 // EXTRQ only uses the lowest 64-bits of the first 128-bit vector 1636 // operands and the lowest 16-bits of the second. 1637 bool MadeChange = false; 1638 if (Value *V = SimplifyDemandedVectorEltsLow(Op0, VWidth0, 1)) { 1639 II->setArgOperand(0, V); 1640 MadeChange = true; 1641 } 1642 if (Value *V = SimplifyDemandedVectorEltsLow(Op1, VWidth1, 2)) { 1643 II->setArgOperand(1, V); 1644 MadeChange = true; 1645 } 1646 if (MadeChange) 1647 return II; 1648 break; 1649 } 1650 1651 case Intrinsic::x86_sse4a_extrqi: { 1652 // EXTRQI: Extract Length bits starting from Index. Zero pad the remaining 1653 // bits of the lower 64-bits. The upper 64-bits are undefined. 1654 Value *Op0 = II->getArgOperand(0); 1655 unsigned VWidth = Op0->getType()->getVectorNumElements(); 1656 assert(Op0->getType()->getPrimitiveSizeInBits() == 128 && VWidth == 2 && 1657 "Unexpected operand size"); 1658 1659 // See if we're dealing with constant values. 1660 ConstantInt *CILength = dyn_cast<ConstantInt>(II->getArgOperand(1)); 1661 ConstantInt *CIIndex = dyn_cast<ConstantInt>(II->getArgOperand(2)); 1662 1663 // Attempt to simplify to a constant or shuffle vector. 1664 if (Value *V = simplifyX86extrq(*II, Op0, CILength, CIIndex, *Builder)) 1665 return replaceInstUsesWith(*II, V); 1666 1667 // EXTRQI only uses the lowest 64-bits of the first 128-bit vector 1668 // operand. 1669 if (Value *V = SimplifyDemandedVectorEltsLow(Op0, VWidth, 1)) { 1670 II->setArgOperand(0, V); 1671 return II; 1672 } 1673 break; 1674 } 1675 1676 case Intrinsic::x86_sse4a_insertq: { 1677 Value *Op0 = II->getArgOperand(0); 1678 Value *Op1 = II->getArgOperand(1); 1679 unsigned VWidth = Op0->getType()->getVectorNumElements(); 1680 assert(Op0->getType()->getPrimitiveSizeInBits() == 128 && 1681 Op1->getType()->getPrimitiveSizeInBits() == 128 && VWidth == 2 && 1682 Op1->getType()->getVectorNumElements() == 2 && 1683 "Unexpected operand size"); 1684 1685 // See if we're dealing with constant values. 1686 Constant *C1 = dyn_cast<Constant>(Op1); 1687 ConstantInt *CI11 = 1688 C1 ? dyn_cast<ConstantInt>(C1->getAggregateElement((unsigned)1)) 1689 : nullptr; 1690 1691 // Attempt to simplify to a constant, shuffle vector or INSERTQI call. 1692 if (CI11) { 1693 APInt V11 = CI11->getValue(); 1694 APInt Len = V11.zextOrTrunc(6); 1695 APInt Idx = V11.lshr(8).zextOrTrunc(6); 1696 if (Value *V = simplifyX86insertq(*II, Op0, Op1, Len, Idx, *Builder)) 1697 return replaceInstUsesWith(*II, V); 1698 } 1699 1700 // INSERTQ only uses the lowest 64-bits of the first 128-bit vector 1701 // operand. 1702 if (Value *V = SimplifyDemandedVectorEltsLow(Op0, VWidth, 1)) { 1703 II->setArgOperand(0, V); 1704 return II; 1705 } 1706 break; 1707 } 1708 1709 case Intrinsic::x86_sse4a_insertqi: { 1710 // INSERTQI: Extract lowest Length bits from lower half of second source and 1711 // insert over first source starting at Index bit. The upper 64-bits are 1712 // undefined. 1713 Value *Op0 = II->getArgOperand(0); 1714 Value *Op1 = II->getArgOperand(1); 1715 unsigned VWidth0 = Op0->getType()->getVectorNumElements(); 1716 unsigned VWidth1 = Op1->getType()->getVectorNumElements(); 1717 assert(Op0->getType()->getPrimitiveSizeInBits() == 128 && 1718 Op1->getType()->getPrimitiveSizeInBits() == 128 && VWidth0 == 2 && 1719 VWidth1 == 2 && "Unexpected operand sizes"); 1720 1721 // See if we're dealing with constant values. 1722 ConstantInt *CILength = dyn_cast<ConstantInt>(II->getArgOperand(2)); 1723 ConstantInt *CIIndex = dyn_cast<ConstantInt>(II->getArgOperand(3)); 1724 1725 // Attempt to simplify to a constant or shuffle vector. 1726 if (CILength && CIIndex) { 1727 APInt Len = CILength->getValue().zextOrTrunc(6); 1728 APInt Idx = CIIndex->getValue().zextOrTrunc(6); 1729 if (Value *V = simplifyX86insertq(*II, Op0, Op1, Len, Idx, *Builder)) 1730 return replaceInstUsesWith(*II, V); 1731 } 1732 1733 // INSERTQI only uses the lowest 64-bits of the first two 128-bit vector 1734 // operands. 1735 bool MadeChange = false; 1736 if (Value *V = SimplifyDemandedVectorEltsLow(Op0, VWidth0, 1)) { 1737 II->setArgOperand(0, V); 1738 MadeChange = true; 1739 } 1740 if (Value *V = SimplifyDemandedVectorEltsLow(Op1, VWidth1, 1)) { 1741 II->setArgOperand(1, V); 1742 MadeChange = true; 1743 } 1744 if (MadeChange) 1745 return II; 1746 break; 1747 } 1748 1749 case Intrinsic::x86_sse41_pblendvb: 1750 case Intrinsic::x86_sse41_blendvps: 1751 case Intrinsic::x86_sse41_blendvpd: 1752 case Intrinsic::x86_avx_blendv_ps_256: 1753 case Intrinsic::x86_avx_blendv_pd_256: 1754 case Intrinsic::x86_avx2_pblendvb: { 1755 // Convert blendv* to vector selects if the mask is constant. 1756 // This optimization is convoluted because the intrinsic is defined as 1757 // getting a vector of floats or doubles for the ps and pd versions. 1758 // FIXME: That should be changed. 1759 1760 Value *Op0 = II->getArgOperand(0); 1761 Value *Op1 = II->getArgOperand(1); 1762 Value *Mask = II->getArgOperand(2); 1763 1764 // fold (blend A, A, Mask) -> A 1765 if (Op0 == Op1) 1766 return replaceInstUsesWith(CI, Op0); 1767 1768 // Zero Mask - select 1st argument. 1769 if (isa<ConstantAggregateZero>(Mask)) 1770 return replaceInstUsesWith(CI, Op0); 1771 1772 // Constant Mask - select 1st/2nd argument lane based on top bit of mask. 1773 if (auto *ConstantMask = dyn_cast<ConstantDataVector>(Mask)) { 1774 Constant *NewSelector = getNegativeIsTrueBoolVec(ConstantMask); 1775 return SelectInst::Create(NewSelector, Op1, Op0, "blendv"); 1776 } 1777 break; 1778 } 1779 1780 case Intrinsic::x86_ssse3_pshuf_b_128: 1781 case Intrinsic::x86_avx2_pshuf_b: 1782 if (Value *V = simplifyX86pshufb(*II, *Builder)) 1783 return replaceInstUsesWith(*II, V); 1784 break; 1785 1786 case Intrinsic::x86_avx_vpermilvar_ps: 1787 case Intrinsic::x86_avx_vpermilvar_ps_256: 1788 case Intrinsic::x86_avx_vpermilvar_pd: 1789 case Intrinsic::x86_avx_vpermilvar_pd_256: 1790 if (Value *V = simplifyX86vpermilvar(*II, *Builder)) 1791 return replaceInstUsesWith(*II, V); 1792 break; 1793 1794 case Intrinsic::x86_avx2_permd: 1795 case Intrinsic::x86_avx2_permps: 1796 if (Value *V = simplifyX86vpermv(*II, *Builder)) 1797 return replaceInstUsesWith(*II, V); 1798 break; 1799 1800 case Intrinsic::x86_avx_vperm2f128_pd_256: 1801 case Intrinsic::x86_avx_vperm2f128_ps_256: 1802 case Intrinsic::x86_avx_vperm2f128_si_256: 1803 case Intrinsic::x86_avx2_vperm2i128: 1804 if (Value *V = simplifyX86vperm2(*II, *Builder)) 1805 return replaceInstUsesWith(*II, V); 1806 break; 1807 1808 case Intrinsic::x86_avx_maskload_ps: 1809 case Intrinsic::x86_avx_maskload_pd: 1810 case Intrinsic::x86_avx_maskload_ps_256: 1811 case Intrinsic::x86_avx_maskload_pd_256: 1812 case Intrinsic::x86_avx2_maskload_d: 1813 case Intrinsic::x86_avx2_maskload_q: 1814 case Intrinsic::x86_avx2_maskload_d_256: 1815 case Intrinsic::x86_avx2_maskload_q_256: 1816 if (Instruction *I = simplifyX86MaskedLoad(*II, *this)) 1817 return I; 1818 break; 1819 1820 case Intrinsic::x86_sse2_maskmov_dqu: 1821 case Intrinsic::x86_avx_maskstore_ps: 1822 case Intrinsic::x86_avx_maskstore_pd: 1823 case Intrinsic::x86_avx_maskstore_ps_256: 1824 case Intrinsic::x86_avx_maskstore_pd_256: 1825 case Intrinsic::x86_avx2_maskstore_d: 1826 case Intrinsic::x86_avx2_maskstore_q: 1827 case Intrinsic::x86_avx2_maskstore_d_256: 1828 case Intrinsic::x86_avx2_maskstore_q_256: 1829 if (simplifyX86MaskedStore(*II, *this)) 1830 return nullptr; 1831 break; 1832 1833 case Intrinsic::x86_xop_vpcomb: 1834 case Intrinsic::x86_xop_vpcomd: 1835 case Intrinsic::x86_xop_vpcomq: 1836 case Intrinsic::x86_xop_vpcomw: 1837 if (Value *V = simplifyX86vpcom(*II, *Builder, true)) 1838 return replaceInstUsesWith(*II, V); 1839 break; 1840 1841 case Intrinsic::x86_xop_vpcomub: 1842 case Intrinsic::x86_xop_vpcomud: 1843 case Intrinsic::x86_xop_vpcomuq: 1844 case Intrinsic::x86_xop_vpcomuw: 1845 if (Value *V = simplifyX86vpcom(*II, *Builder, false)) 1846 return replaceInstUsesWith(*II, V); 1847 break; 1848 1849 case Intrinsic::ppc_altivec_vperm: 1850 // Turn vperm(V1,V2,mask) -> shuffle(V1,V2,mask) if mask is a constant. 1851 // Note that ppc_altivec_vperm has a big-endian bias, so when creating 1852 // a vectorshuffle for little endian, we must undo the transformation 1853 // performed on vec_perm in altivec.h. That is, we must complement 1854 // the permutation mask with respect to 31 and reverse the order of 1855 // V1 and V2. 1856 if (Constant *Mask = dyn_cast<Constant>(II->getArgOperand(2))) { 1857 assert(Mask->getType()->getVectorNumElements() == 16 && 1858 "Bad type for intrinsic!"); 1859 1860 // Check that all of the elements are integer constants or undefs. 1861 bool AllEltsOk = true; 1862 for (unsigned i = 0; i != 16; ++i) { 1863 Constant *Elt = Mask->getAggregateElement(i); 1864 if (!Elt || !(isa<ConstantInt>(Elt) || isa<UndefValue>(Elt))) { 1865 AllEltsOk = false; 1866 break; 1867 } 1868 } 1869 1870 if (AllEltsOk) { 1871 // Cast the input vectors to byte vectors. 1872 Value *Op0 = Builder->CreateBitCast(II->getArgOperand(0), 1873 Mask->getType()); 1874 Value *Op1 = Builder->CreateBitCast(II->getArgOperand(1), 1875 Mask->getType()); 1876 Value *Result = UndefValue::get(Op0->getType()); 1877 1878 // Only extract each element once. 1879 Value *ExtractedElts[32]; 1880 memset(ExtractedElts, 0, sizeof(ExtractedElts)); 1881 1882 for (unsigned i = 0; i != 16; ++i) { 1883 if (isa<UndefValue>(Mask->getAggregateElement(i))) 1884 continue; 1885 unsigned Idx = 1886 cast<ConstantInt>(Mask->getAggregateElement(i))->getZExtValue(); 1887 Idx &= 31; // Match the hardware behavior. 1888 if (DL.isLittleEndian()) 1889 Idx = 31 - Idx; 1890 1891 if (!ExtractedElts[Idx]) { 1892 Value *Op0ToUse = (DL.isLittleEndian()) ? Op1 : Op0; 1893 Value *Op1ToUse = (DL.isLittleEndian()) ? Op0 : Op1; 1894 ExtractedElts[Idx] = 1895 Builder->CreateExtractElement(Idx < 16 ? Op0ToUse : Op1ToUse, 1896 Builder->getInt32(Idx&15)); 1897 } 1898 1899 // Insert this value into the result vector. 1900 Result = Builder->CreateInsertElement(Result, ExtractedElts[Idx], 1901 Builder->getInt32(i)); 1902 } 1903 return CastInst::Create(Instruction::BitCast, Result, CI.getType()); 1904 } 1905 } 1906 break; 1907 1908 case Intrinsic::arm_neon_vld1: 1909 case Intrinsic::arm_neon_vld2: 1910 case Intrinsic::arm_neon_vld3: 1911 case Intrinsic::arm_neon_vld4: 1912 case Intrinsic::arm_neon_vld2lane: 1913 case Intrinsic::arm_neon_vld3lane: 1914 case Intrinsic::arm_neon_vld4lane: 1915 case Intrinsic::arm_neon_vst1: 1916 case Intrinsic::arm_neon_vst2: 1917 case Intrinsic::arm_neon_vst3: 1918 case Intrinsic::arm_neon_vst4: 1919 case Intrinsic::arm_neon_vst2lane: 1920 case Intrinsic::arm_neon_vst3lane: 1921 case Intrinsic::arm_neon_vst4lane: { 1922 unsigned MemAlign = getKnownAlignment(II->getArgOperand(0), DL, II, AC, DT); 1923 unsigned AlignArg = II->getNumArgOperands() - 1; 1924 ConstantInt *IntrAlign = dyn_cast<ConstantInt>(II->getArgOperand(AlignArg)); 1925 if (IntrAlign && IntrAlign->getZExtValue() < MemAlign) { 1926 II->setArgOperand(AlignArg, 1927 ConstantInt::get(Type::getInt32Ty(II->getContext()), 1928 MemAlign, false)); 1929 return II; 1930 } 1931 break; 1932 } 1933 1934 case Intrinsic::arm_neon_vmulls: 1935 case Intrinsic::arm_neon_vmullu: 1936 case Intrinsic::aarch64_neon_smull: 1937 case Intrinsic::aarch64_neon_umull: { 1938 Value *Arg0 = II->getArgOperand(0); 1939 Value *Arg1 = II->getArgOperand(1); 1940 1941 // Handle mul by zero first: 1942 if (isa<ConstantAggregateZero>(Arg0) || isa<ConstantAggregateZero>(Arg1)) { 1943 return replaceInstUsesWith(CI, ConstantAggregateZero::get(II->getType())); 1944 } 1945 1946 // Check for constant LHS & RHS - in this case we just simplify. 1947 bool Zext = (II->getIntrinsicID() == Intrinsic::arm_neon_vmullu || 1948 II->getIntrinsicID() == Intrinsic::aarch64_neon_umull); 1949 VectorType *NewVT = cast<VectorType>(II->getType()); 1950 if (Constant *CV0 = dyn_cast<Constant>(Arg0)) { 1951 if (Constant *CV1 = dyn_cast<Constant>(Arg1)) { 1952 CV0 = ConstantExpr::getIntegerCast(CV0, NewVT, /*isSigned=*/!Zext); 1953 CV1 = ConstantExpr::getIntegerCast(CV1, NewVT, /*isSigned=*/!Zext); 1954 1955 return replaceInstUsesWith(CI, ConstantExpr::getMul(CV0, CV1)); 1956 } 1957 1958 // Couldn't simplify - canonicalize constant to the RHS. 1959 std::swap(Arg0, Arg1); 1960 } 1961 1962 // Handle mul by one: 1963 if (Constant *CV1 = dyn_cast<Constant>(Arg1)) 1964 if (ConstantInt *Splat = 1965 dyn_cast_or_null<ConstantInt>(CV1->getSplatValue())) 1966 if (Splat->isOne()) 1967 return CastInst::CreateIntegerCast(Arg0, II->getType(), 1968 /*isSigned=*/!Zext); 1969 1970 break; 1971 } 1972 1973 case Intrinsic::amdgcn_rcp: { 1974 if (const ConstantFP *C = dyn_cast<ConstantFP>(II->getArgOperand(0))) { 1975 const APFloat &ArgVal = C->getValueAPF(); 1976 APFloat Val(ArgVal.getSemantics(), 1.0); 1977 APFloat::opStatus Status = Val.divide(ArgVal, 1978 APFloat::rmNearestTiesToEven); 1979 // Only do this if it was exact and therefore not dependent on the 1980 // rounding mode. 1981 if (Status == APFloat::opOK) 1982 return replaceInstUsesWith(CI, ConstantFP::get(II->getContext(), Val)); 1983 } 1984 1985 break; 1986 } 1987 case Intrinsic::amdgcn_frexp_mant: 1988 case Intrinsic::amdgcn_frexp_exp: { 1989 Value *Src = II->getArgOperand(0); 1990 if (const ConstantFP *C = dyn_cast<ConstantFP>(Src)) { 1991 int Exp; 1992 APFloat Significand = frexp(C->getValueAPF(), Exp, 1993 APFloat::rmNearestTiesToEven); 1994 1995 if (II->getIntrinsicID() == Intrinsic::amdgcn_frexp_mant) { 1996 return replaceInstUsesWith(CI, ConstantFP::get(II->getContext(), 1997 Significand)); 1998 } 1999 2000 // Match instruction special case behavior. 2001 if (Exp == APFloat::IEK_NaN || Exp == APFloat::IEK_Inf) 2002 Exp = 0; 2003 2004 return replaceInstUsesWith(CI, ConstantInt::get(II->getType(), Exp)); 2005 } 2006 2007 if (isa<UndefValue>(Src)) 2008 return replaceInstUsesWith(CI, UndefValue::get(II->getType())); 2009 2010 break; 2011 } 2012 case Intrinsic::stackrestore: { 2013 // If the save is right next to the restore, remove the restore. This can 2014 // happen when variable allocas are DCE'd. 2015 if (IntrinsicInst *SS = dyn_cast<IntrinsicInst>(II->getArgOperand(0))) { 2016 if (SS->getIntrinsicID() == Intrinsic::stacksave) { 2017 if (&*++SS->getIterator() == II) 2018 return eraseInstFromFunction(CI); 2019 } 2020 } 2021 2022 // Scan down this block to see if there is another stack restore in the 2023 // same block without an intervening call/alloca. 2024 BasicBlock::iterator BI(II); 2025 TerminatorInst *TI = II->getParent()->getTerminator(); 2026 bool CannotRemove = false; 2027 for (++BI; &*BI != TI; ++BI) { 2028 if (isa<AllocaInst>(BI)) { 2029 CannotRemove = true; 2030 break; 2031 } 2032 if (CallInst *BCI = dyn_cast<CallInst>(BI)) { 2033 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(BCI)) { 2034 // If there is a stackrestore below this one, remove this one. 2035 if (II->getIntrinsicID() == Intrinsic::stackrestore) 2036 return eraseInstFromFunction(CI); 2037 2038 // Bail if we cross over an intrinsic with side effects, such as 2039 // llvm.stacksave, llvm.read_register, or llvm.setjmp. 2040 if (II->mayHaveSideEffects()) { 2041 CannotRemove = true; 2042 break; 2043 } 2044 } else { 2045 // If we found a non-intrinsic call, we can't remove the stack 2046 // restore. 2047 CannotRemove = true; 2048 break; 2049 } 2050 } 2051 } 2052 2053 // If the stack restore is in a return, resume, or unwind block and if there 2054 // are no allocas or calls between the restore and the return, nuke the 2055 // restore. 2056 if (!CannotRemove && (isa<ReturnInst>(TI) || isa<ResumeInst>(TI))) 2057 return eraseInstFromFunction(CI); 2058 break; 2059 } 2060 case Intrinsic::lifetime_start: 2061 if (removeTriviallyEmptyRange(*II, Intrinsic::lifetime_start, 2062 Intrinsic::lifetime_end, *this)) 2063 return nullptr; 2064 break; 2065 case Intrinsic::assume: { 2066 Value *IIOperand = II->getArgOperand(0); 2067 // Remove an assume if it is immediately followed by an identical assume. 2068 if (match(II->getNextNode(), 2069 m_Intrinsic<Intrinsic::assume>(m_Specific(IIOperand)))) 2070 return eraseInstFromFunction(CI); 2071 2072 // Canonicalize assume(a && b) -> assume(a); assume(b); 2073 // Note: New assumption intrinsics created here are registered by 2074 // the InstCombineIRInserter object. 2075 Value *AssumeIntrinsic = II->getCalledValue(), *A, *B; 2076 if (match(IIOperand, m_And(m_Value(A), m_Value(B)))) { 2077 Builder->CreateCall(AssumeIntrinsic, A, II->getName()); 2078 Builder->CreateCall(AssumeIntrinsic, B, II->getName()); 2079 return eraseInstFromFunction(*II); 2080 } 2081 // assume(!(a || b)) -> assume(!a); assume(!b); 2082 if (match(IIOperand, m_Not(m_Or(m_Value(A), m_Value(B))))) { 2083 Builder->CreateCall(AssumeIntrinsic, Builder->CreateNot(A), 2084 II->getName()); 2085 Builder->CreateCall(AssumeIntrinsic, Builder->CreateNot(B), 2086 II->getName()); 2087 return eraseInstFromFunction(*II); 2088 } 2089 2090 // assume( (load addr) != null ) -> add 'nonnull' metadata to load 2091 // (if assume is valid at the load) 2092 if (ICmpInst* ICmp = dyn_cast<ICmpInst>(IIOperand)) { 2093 Value *LHS = ICmp->getOperand(0); 2094 Value *RHS = ICmp->getOperand(1); 2095 if (ICmpInst::ICMP_NE == ICmp->getPredicate() && 2096 isa<LoadInst>(LHS) && 2097 isa<Constant>(RHS) && 2098 RHS->getType()->isPointerTy() && 2099 cast<Constant>(RHS)->isNullValue()) { 2100 LoadInst* LI = cast<LoadInst>(LHS); 2101 if (isValidAssumeForContext(II, LI, DT)) { 2102 MDNode *MD = MDNode::get(II->getContext(), None); 2103 LI->setMetadata(LLVMContext::MD_nonnull, MD); 2104 return eraseInstFromFunction(*II); 2105 } 2106 } 2107 // TODO: apply nonnull return attributes to calls and invokes 2108 // TODO: apply range metadata for range check patterns? 2109 } 2110 // If there is a dominating assume with the same condition as this one, 2111 // then this one is redundant, and should be removed. 2112 APInt KnownZero(1, 0), KnownOne(1, 0); 2113 computeKnownBits(IIOperand, KnownZero, KnownOne, 0, II); 2114 if (KnownOne.isAllOnesValue()) 2115 return eraseInstFromFunction(*II); 2116 2117 break; 2118 } 2119 case Intrinsic::experimental_gc_relocate: { 2120 // Translate facts known about a pointer before relocating into 2121 // facts about the relocate value, while being careful to 2122 // preserve relocation semantics. 2123 Value *DerivedPtr = cast<GCRelocateInst>(II)->getDerivedPtr(); 2124 2125 // Remove the relocation if unused, note that this check is required 2126 // to prevent the cases below from looping forever. 2127 if (II->use_empty()) 2128 return eraseInstFromFunction(*II); 2129 2130 // Undef is undef, even after relocation. 2131 // TODO: provide a hook for this in GCStrategy. This is clearly legal for 2132 // most practical collectors, but there was discussion in the review thread 2133 // about whether it was legal for all possible collectors. 2134 if (isa<UndefValue>(DerivedPtr)) 2135 // Use undef of gc_relocate's type to replace it. 2136 return replaceInstUsesWith(*II, UndefValue::get(II->getType())); 2137 2138 if (auto *PT = dyn_cast<PointerType>(II->getType())) { 2139 // The relocation of null will be null for most any collector. 2140 // TODO: provide a hook for this in GCStrategy. There might be some 2141 // weird collector this property does not hold for. 2142 if (isa<ConstantPointerNull>(DerivedPtr)) 2143 // Use null-pointer of gc_relocate's type to replace it. 2144 return replaceInstUsesWith(*II, ConstantPointerNull::get(PT)); 2145 2146 // isKnownNonNull -> nonnull attribute 2147 if (isKnownNonNullAt(DerivedPtr, II, DT, TLI)) 2148 II->addAttribute(AttributeSet::ReturnIndex, Attribute::NonNull); 2149 } 2150 2151 // TODO: bitcast(relocate(p)) -> relocate(bitcast(p)) 2152 // Canonicalize on the type from the uses to the defs 2153 2154 // TODO: relocate((gep p, C, C2, ...)) -> gep(relocate(p), C, C2, ...) 2155 break; 2156 } 2157 } 2158 2159 return visitCallSite(II); 2160 } 2161 2162 // InvokeInst simplification 2163 // 2164 Instruction *InstCombiner::visitInvokeInst(InvokeInst &II) { 2165 return visitCallSite(&II); 2166 } 2167 2168 /// If this cast does not affect the value passed through the varargs area, we 2169 /// can eliminate the use of the cast. 2170 static bool isSafeToEliminateVarargsCast(const CallSite CS, 2171 const DataLayout &DL, 2172 const CastInst *const CI, 2173 const int ix) { 2174 if (!CI->isLosslessCast()) 2175 return false; 2176 2177 // If this is a GC intrinsic, avoid munging types. We need types for 2178 // statepoint reconstruction in SelectionDAG. 2179 // TODO: This is probably something which should be expanded to all 2180 // intrinsics since the entire point of intrinsics is that 2181 // they are understandable by the optimizer. 2182 if (isStatepoint(CS) || isGCRelocate(CS) || isGCResult(CS)) 2183 return false; 2184 2185 // The size of ByVal or InAlloca arguments is derived from the type, so we 2186 // can't change to a type with a different size. If the size were 2187 // passed explicitly we could avoid this check. 2188 if (!CS.isByValOrInAllocaArgument(ix)) 2189 return true; 2190 2191 Type* SrcTy = 2192 cast<PointerType>(CI->getOperand(0)->getType())->getElementType(); 2193 Type* DstTy = cast<PointerType>(CI->getType())->getElementType(); 2194 if (!SrcTy->isSized() || !DstTy->isSized()) 2195 return false; 2196 if (DL.getTypeAllocSize(SrcTy) != DL.getTypeAllocSize(DstTy)) 2197 return false; 2198 return true; 2199 } 2200 2201 Instruction *InstCombiner::tryOptimizeCall(CallInst *CI) { 2202 if (!CI->getCalledFunction()) return nullptr; 2203 2204 auto InstCombineRAUW = [this](Instruction *From, Value *With) { 2205 replaceInstUsesWith(*From, With); 2206 }; 2207 LibCallSimplifier Simplifier(DL, TLI, InstCombineRAUW); 2208 if (Value *With = Simplifier.optimizeCall(CI)) { 2209 ++NumSimplified; 2210 return CI->use_empty() ? CI : replaceInstUsesWith(*CI, With); 2211 } 2212 2213 return nullptr; 2214 } 2215 2216 static IntrinsicInst *findInitTrampolineFromAlloca(Value *TrampMem) { 2217 // Strip off at most one level of pointer casts, looking for an alloca. This 2218 // is good enough in practice and simpler than handling any number of casts. 2219 Value *Underlying = TrampMem->stripPointerCasts(); 2220 if (Underlying != TrampMem && 2221 (!Underlying->hasOneUse() || Underlying->user_back() != TrampMem)) 2222 return nullptr; 2223 if (!isa<AllocaInst>(Underlying)) 2224 return nullptr; 2225 2226 IntrinsicInst *InitTrampoline = nullptr; 2227 for (User *U : TrampMem->users()) { 2228 IntrinsicInst *II = dyn_cast<IntrinsicInst>(U); 2229 if (!II) 2230 return nullptr; 2231 if (II->getIntrinsicID() == Intrinsic::init_trampoline) { 2232 if (InitTrampoline) 2233 // More than one init_trampoline writes to this value. Give up. 2234 return nullptr; 2235 InitTrampoline = II; 2236 continue; 2237 } 2238 if (II->getIntrinsicID() == Intrinsic::adjust_trampoline) 2239 // Allow any number of calls to adjust.trampoline. 2240 continue; 2241 return nullptr; 2242 } 2243 2244 // No call to init.trampoline found. 2245 if (!InitTrampoline) 2246 return nullptr; 2247 2248 // Check that the alloca is being used in the expected way. 2249 if (InitTrampoline->getOperand(0) != TrampMem) 2250 return nullptr; 2251 2252 return InitTrampoline; 2253 } 2254 2255 static IntrinsicInst *findInitTrampolineFromBB(IntrinsicInst *AdjustTramp, 2256 Value *TrampMem) { 2257 // Visit all the previous instructions in the basic block, and try to find a 2258 // init.trampoline which has a direct path to the adjust.trampoline. 2259 for (BasicBlock::iterator I = AdjustTramp->getIterator(), 2260 E = AdjustTramp->getParent()->begin(); 2261 I != E;) { 2262 Instruction *Inst = &*--I; 2263 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) 2264 if (II->getIntrinsicID() == Intrinsic::init_trampoline && 2265 II->getOperand(0) == TrampMem) 2266 return II; 2267 if (Inst->mayWriteToMemory()) 2268 return nullptr; 2269 } 2270 return nullptr; 2271 } 2272 2273 // Given a call to llvm.adjust.trampoline, find and return the corresponding 2274 // call to llvm.init.trampoline if the call to the trampoline can be optimized 2275 // to a direct call to a function. Otherwise return NULL. 2276 // 2277 static IntrinsicInst *findInitTrampoline(Value *Callee) { 2278 Callee = Callee->stripPointerCasts(); 2279 IntrinsicInst *AdjustTramp = dyn_cast<IntrinsicInst>(Callee); 2280 if (!AdjustTramp || 2281 AdjustTramp->getIntrinsicID() != Intrinsic::adjust_trampoline) 2282 return nullptr; 2283 2284 Value *TrampMem = AdjustTramp->getOperand(0); 2285 2286 if (IntrinsicInst *IT = findInitTrampolineFromAlloca(TrampMem)) 2287 return IT; 2288 if (IntrinsicInst *IT = findInitTrampolineFromBB(AdjustTramp, TrampMem)) 2289 return IT; 2290 return nullptr; 2291 } 2292 2293 /// Improvements for call and invoke instructions. 2294 Instruction *InstCombiner::visitCallSite(CallSite CS) { 2295 2296 if (isAllocLikeFn(CS.getInstruction(), TLI)) 2297 return visitAllocSite(*CS.getInstruction()); 2298 2299 bool Changed = false; 2300 2301 // Mark any parameters that are known to be non-null with the nonnull 2302 // attribute. This is helpful for inlining calls to functions with null 2303 // checks on their arguments. 2304 SmallVector<unsigned, 4> Indices; 2305 unsigned ArgNo = 0; 2306 2307 for (Value *V : CS.args()) { 2308 if (V->getType()->isPointerTy() && 2309 !CS.paramHasAttr(ArgNo + 1, Attribute::NonNull) && 2310 isKnownNonNullAt(V, CS.getInstruction(), DT, TLI)) 2311 Indices.push_back(ArgNo + 1); 2312 ArgNo++; 2313 } 2314 2315 assert(ArgNo == CS.arg_size() && "sanity check"); 2316 2317 if (!Indices.empty()) { 2318 AttributeSet AS = CS.getAttributes(); 2319 LLVMContext &Ctx = CS.getInstruction()->getContext(); 2320 AS = AS.addAttribute(Ctx, Indices, 2321 Attribute::get(Ctx, Attribute::NonNull)); 2322 CS.setAttributes(AS); 2323 Changed = true; 2324 } 2325 2326 // If the callee is a pointer to a function, attempt to move any casts to the 2327 // arguments of the call/invoke. 2328 Value *Callee = CS.getCalledValue(); 2329 if (!isa<Function>(Callee) && transformConstExprCastCall(CS)) 2330 return nullptr; 2331 2332 if (Function *CalleeF = dyn_cast<Function>(Callee)) { 2333 // Remove the convergent attr on calls when the callee is not convergent. 2334 if (CS.isConvergent() && !CalleeF->isConvergent()) { 2335 DEBUG(dbgs() << "Removing convergent attr from instr " 2336 << CS.getInstruction() << "\n"); 2337 CS.setNotConvergent(); 2338 return CS.getInstruction(); 2339 } 2340 2341 // If the call and callee calling conventions don't match, this call must 2342 // be unreachable, as the call is undefined. 2343 if (CalleeF->getCallingConv() != CS.getCallingConv() && 2344 // Only do this for calls to a function with a body. A prototype may 2345 // not actually end up matching the implementation's calling conv for a 2346 // variety of reasons (e.g. it may be written in assembly). 2347 !CalleeF->isDeclaration()) { 2348 Instruction *OldCall = CS.getInstruction(); 2349 new StoreInst(ConstantInt::getTrue(Callee->getContext()), 2350 UndefValue::get(Type::getInt1PtrTy(Callee->getContext())), 2351 OldCall); 2352 // If OldCall does not return void then replaceAllUsesWith undef. 2353 // This allows ValueHandlers and custom metadata to adjust itself. 2354 if (!OldCall->getType()->isVoidTy()) 2355 replaceInstUsesWith(*OldCall, UndefValue::get(OldCall->getType())); 2356 if (isa<CallInst>(OldCall)) 2357 return eraseInstFromFunction(*OldCall); 2358 2359 // We cannot remove an invoke, because it would change the CFG, just 2360 // change the callee to a null pointer. 2361 cast<InvokeInst>(OldCall)->setCalledFunction( 2362 Constant::getNullValue(CalleeF->getType())); 2363 return nullptr; 2364 } 2365 } 2366 2367 if (isa<ConstantPointerNull>(Callee) || isa<UndefValue>(Callee)) { 2368 // If CS does not return void then replaceAllUsesWith undef. 2369 // This allows ValueHandlers and custom metadata to adjust itself. 2370 if (!CS.getInstruction()->getType()->isVoidTy()) 2371 replaceInstUsesWith(*CS.getInstruction(), 2372 UndefValue::get(CS.getInstruction()->getType())); 2373 2374 if (isa<InvokeInst>(CS.getInstruction())) { 2375 // Can't remove an invoke because we cannot change the CFG. 2376 return nullptr; 2377 } 2378 2379 // This instruction is not reachable, just remove it. We insert a store to 2380 // undef so that we know that this code is not reachable, despite the fact 2381 // that we can't modify the CFG here. 2382 new StoreInst(ConstantInt::getTrue(Callee->getContext()), 2383 UndefValue::get(Type::getInt1PtrTy(Callee->getContext())), 2384 CS.getInstruction()); 2385 2386 return eraseInstFromFunction(*CS.getInstruction()); 2387 } 2388 2389 if (IntrinsicInst *II = findInitTrampoline(Callee)) 2390 return transformCallThroughTrampoline(CS, II); 2391 2392 PointerType *PTy = cast<PointerType>(Callee->getType()); 2393 FunctionType *FTy = cast<FunctionType>(PTy->getElementType()); 2394 if (FTy->isVarArg()) { 2395 int ix = FTy->getNumParams(); 2396 // See if we can optimize any arguments passed through the varargs area of 2397 // the call. 2398 for (CallSite::arg_iterator I = CS.arg_begin() + FTy->getNumParams(), 2399 E = CS.arg_end(); I != E; ++I, ++ix) { 2400 CastInst *CI = dyn_cast<CastInst>(*I); 2401 if (CI && isSafeToEliminateVarargsCast(CS, DL, CI, ix)) { 2402 *I = CI->getOperand(0); 2403 Changed = true; 2404 } 2405 } 2406 } 2407 2408 if (isa<InlineAsm>(Callee) && !CS.doesNotThrow()) { 2409 // Inline asm calls cannot throw - mark them 'nounwind'. 2410 CS.setDoesNotThrow(); 2411 Changed = true; 2412 } 2413 2414 // Try to optimize the call if possible, we require DataLayout for most of 2415 // this. None of these calls are seen as possibly dead so go ahead and 2416 // delete the instruction now. 2417 if (CallInst *CI = dyn_cast<CallInst>(CS.getInstruction())) { 2418 Instruction *I = tryOptimizeCall(CI); 2419 // If we changed something return the result, etc. Otherwise let 2420 // the fallthrough check. 2421 if (I) return eraseInstFromFunction(*I); 2422 } 2423 2424 return Changed ? CS.getInstruction() : nullptr; 2425 } 2426 2427 /// If the callee is a constexpr cast of a function, attempt to move the cast to 2428 /// the arguments of the call/invoke. 2429 bool InstCombiner::transformConstExprCastCall(CallSite CS) { 2430 Function *Callee = 2431 dyn_cast<Function>(CS.getCalledValue()->stripPointerCasts()); 2432 if (!Callee) 2433 return false; 2434 // The prototype of thunks are a lie, don't try to directly call such 2435 // functions. 2436 if (Callee->hasFnAttribute("thunk")) 2437 return false; 2438 Instruction *Caller = CS.getInstruction(); 2439 const AttributeSet &CallerPAL = CS.getAttributes(); 2440 2441 // Okay, this is a cast from a function to a different type. Unless doing so 2442 // would cause a type conversion of one of our arguments, change this call to 2443 // be a direct call with arguments casted to the appropriate types. 2444 // 2445 FunctionType *FT = Callee->getFunctionType(); 2446 Type *OldRetTy = Caller->getType(); 2447 Type *NewRetTy = FT->getReturnType(); 2448 2449 // Check to see if we are changing the return type... 2450 if (OldRetTy != NewRetTy) { 2451 2452 if (NewRetTy->isStructTy()) 2453 return false; // TODO: Handle multiple return values. 2454 2455 if (!CastInst::isBitOrNoopPointerCastable(NewRetTy, OldRetTy, DL)) { 2456 if (Callee->isDeclaration()) 2457 return false; // Cannot transform this return value. 2458 2459 if (!Caller->use_empty() && 2460 // void -> non-void is handled specially 2461 !NewRetTy->isVoidTy()) 2462 return false; // Cannot transform this return value. 2463 } 2464 2465 if (!CallerPAL.isEmpty() && !Caller->use_empty()) { 2466 AttrBuilder RAttrs(CallerPAL, AttributeSet::ReturnIndex); 2467 if (RAttrs.overlaps(AttributeFuncs::typeIncompatible(NewRetTy))) 2468 return false; // Attribute not compatible with transformed value. 2469 } 2470 2471 // If the callsite is an invoke instruction, and the return value is used by 2472 // a PHI node in a successor, we cannot change the return type of the call 2473 // because there is no place to put the cast instruction (without breaking 2474 // the critical edge). Bail out in this case. 2475 if (!Caller->use_empty()) 2476 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) 2477 for (User *U : II->users()) 2478 if (PHINode *PN = dyn_cast<PHINode>(U)) 2479 if (PN->getParent() == II->getNormalDest() || 2480 PN->getParent() == II->getUnwindDest()) 2481 return false; 2482 } 2483 2484 unsigned NumActualArgs = CS.arg_size(); 2485 unsigned NumCommonArgs = std::min(FT->getNumParams(), NumActualArgs); 2486 2487 // Prevent us turning: 2488 // declare void @takes_i32_inalloca(i32* inalloca) 2489 // call void bitcast (void (i32*)* @takes_i32_inalloca to void (i32)*)(i32 0) 2490 // 2491 // into: 2492 // call void @takes_i32_inalloca(i32* null) 2493 // 2494 // Similarly, avoid folding away bitcasts of byval calls. 2495 if (Callee->getAttributes().hasAttrSomewhere(Attribute::InAlloca) || 2496 Callee->getAttributes().hasAttrSomewhere(Attribute::ByVal)) 2497 return false; 2498 2499 CallSite::arg_iterator AI = CS.arg_begin(); 2500 for (unsigned i = 0, e = NumCommonArgs; i != e; ++i, ++AI) { 2501 Type *ParamTy = FT->getParamType(i); 2502 Type *ActTy = (*AI)->getType(); 2503 2504 if (!CastInst::isBitOrNoopPointerCastable(ActTy, ParamTy, DL)) 2505 return false; // Cannot transform this parameter value. 2506 2507 if (AttrBuilder(CallerPAL.getParamAttributes(i + 1), i + 1). 2508 overlaps(AttributeFuncs::typeIncompatible(ParamTy))) 2509 return false; // Attribute not compatible with transformed value. 2510 2511 if (CS.isInAllocaArgument(i)) 2512 return false; // Cannot transform to and from inalloca. 2513 2514 // If the parameter is passed as a byval argument, then we have to have a 2515 // sized type and the sized type has to have the same size as the old type. 2516 if (ParamTy != ActTy && 2517 CallerPAL.getParamAttributes(i + 1).hasAttribute(i + 1, 2518 Attribute::ByVal)) { 2519 PointerType *ParamPTy = dyn_cast<PointerType>(ParamTy); 2520 if (!ParamPTy || !ParamPTy->getElementType()->isSized()) 2521 return false; 2522 2523 Type *CurElTy = ActTy->getPointerElementType(); 2524 if (DL.getTypeAllocSize(CurElTy) != 2525 DL.getTypeAllocSize(ParamPTy->getElementType())) 2526 return false; 2527 } 2528 } 2529 2530 if (Callee->isDeclaration()) { 2531 // Do not delete arguments unless we have a function body. 2532 if (FT->getNumParams() < NumActualArgs && !FT->isVarArg()) 2533 return false; 2534 2535 // If the callee is just a declaration, don't change the varargsness of the 2536 // call. We don't want to introduce a varargs call where one doesn't 2537 // already exist. 2538 PointerType *APTy = cast<PointerType>(CS.getCalledValue()->getType()); 2539 if (FT->isVarArg()!=cast<FunctionType>(APTy->getElementType())->isVarArg()) 2540 return false; 2541 2542 // If both the callee and the cast type are varargs, we still have to make 2543 // sure the number of fixed parameters are the same or we have the same 2544 // ABI issues as if we introduce a varargs call. 2545 if (FT->isVarArg() && 2546 cast<FunctionType>(APTy->getElementType())->isVarArg() && 2547 FT->getNumParams() != 2548 cast<FunctionType>(APTy->getElementType())->getNumParams()) 2549 return false; 2550 } 2551 2552 if (FT->getNumParams() < NumActualArgs && FT->isVarArg() && 2553 !CallerPAL.isEmpty()) 2554 // In this case we have more arguments than the new function type, but we 2555 // won't be dropping them. Check that these extra arguments have attributes 2556 // that are compatible with being a vararg call argument. 2557 for (unsigned i = CallerPAL.getNumSlots(); i; --i) { 2558 unsigned Index = CallerPAL.getSlotIndex(i - 1); 2559 if (Index <= FT->getNumParams()) 2560 break; 2561 2562 // Check if it has an attribute that's incompatible with varargs. 2563 AttributeSet PAttrs = CallerPAL.getSlotAttributes(i - 1); 2564 if (PAttrs.hasAttribute(Index, Attribute::StructRet)) 2565 return false; 2566 } 2567 2568 2569 // Okay, we decided that this is a safe thing to do: go ahead and start 2570 // inserting cast instructions as necessary. 2571 std::vector<Value*> Args; 2572 Args.reserve(NumActualArgs); 2573 SmallVector<AttributeSet, 8> attrVec; 2574 attrVec.reserve(NumCommonArgs); 2575 2576 // Get any return attributes. 2577 AttrBuilder RAttrs(CallerPAL, AttributeSet::ReturnIndex); 2578 2579 // If the return value is not being used, the type may not be compatible 2580 // with the existing attributes. Wipe out any problematic attributes. 2581 RAttrs.remove(AttributeFuncs::typeIncompatible(NewRetTy)); 2582 2583 // Add the new return attributes. 2584 if (RAttrs.hasAttributes()) 2585 attrVec.push_back(AttributeSet::get(Caller->getContext(), 2586 AttributeSet::ReturnIndex, RAttrs)); 2587 2588 AI = CS.arg_begin(); 2589 for (unsigned i = 0; i != NumCommonArgs; ++i, ++AI) { 2590 Type *ParamTy = FT->getParamType(i); 2591 2592 if ((*AI)->getType() == ParamTy) { 2593 Args.push_back(*AI); 2594 } else { 2595 Args.push_back(Builder->CreateBitOrPointerCast(*AI, ParamTy)); 2596 } 2597 2598 // Add any parameter attributes. 2599 AttrBuilder PAttrs(CallerPAL.getParamAttributes(i + 1), i + 1); 2600 if (PAttrs.hasAttributes()) 2601 attrVec.push_back(AttributeSet::get(Caller->getContext(), i + 1, 2602 PAttrs)); 2603 } 2604 2605 // If the function takes more arguments than the call was taking, add them 2606 // now. 2607 for (unsigned i = NumCommonArgs; i != FT->getNumParams(); ++i) 2608 Args.push_back(Constant::getNullValue(FT->getParamType(i))); 2609 2610 // If we are removing arguments to the function, emit an obnoxious warning. 2611 if (FT->getNumParams() < NumActualArgs) { 2612 // TODO: if (!FT->isVarArg()) this call may be unreachable. PR14722 2613 if (FT->isVarArg()) { 2614 // Add all of the arguments in their promoted form to the arg list. 2615 for (unsigned i = FT->getNumParams(); i != NumActualArgs; ++i, ++AI) { 2616 Type *PTy = getPromotedType((*AI)->getType()); 2617 if (PTy != (*AI)->getType()) { 2618 // Must promote to pass through va_arg area! 2619 Instruction::CastOps opcode = 2620 CastInst::getCastOpcode(*AI, false, PTy, false); 2621 Args.push_back(Builder->CreateCast(opcode, *AI, PTy)); 2622 } else { 2623 Args.push_back(*AI); 2624 } 2625 2626 // Add any parameter attributes. 2627 AttrBuilder PAttrs(CallerPAL.getParamAttributes(i + 1), i + 1); 2628 if (PAttrs.hasAttributes()) 2629 attrVec.push_back(AttributeSet::get(FT->getContext(), i + 1, 2630 PAttrs)); 2631 } 2632 } 2633 } 2634 2635 AttributeSet FnAttrs = CallerPAL.getFnAttributes(); 2636 if (CallerPAL.hasAttributes(AttributeSet::FunctionIndex)) 2637 attrVec.push_back(AttributeSet::get(Callee->getContext(), FnAttrs)); 2638 2639 if (NewRetTy->isVoidTy()) 2640 Caller->setName(""); // Void type should not have a name. 2641 2642 const AttributeSet &NewCallerPAL = AttributeSet::get(Callee->getContext(), 2643 attrVec); 2644 2645 SmallVector<OperandBundleDef, 1> OpBundles; 2646 CS.getOperandBundlesAsDefs(OpBundles); 2647 2648 Instruction *NC; 2649 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) { 2650 NC = Builder->CreateInvoke(Callee, II->getNormalDest(), II->getUnwindDest(), 2651 Args, OpBundles); 2652 NC->takeName(II); 2653 cast<InvokeInst>(NC)->setCallingConv(II->getCallingConv()); 2654 cast<InvokeInst>(NC)->setAttributes(NewCallerPAL); 2655 } else { 2656 CallInst *CI = cast<CallInst>(Caller); 2657 NC = Builder->CreateCall(Callee, Args, OpBundles); 2658 NC->takeName(CI); 2659 if (CI->isTailCall()) 2660 cast<CallInst>(NC)->setTailCall(); 2661 cast<CallInst>(NC)->setCallingConv(CI->getCallingConv()); 2662 cast<CallInst>(NC)->setAttributes(NewCallerPAL); 2663 } 2664 2665 // Insert a cast of the return type as necessary. 2666 Value *NV = NC; 2667 if (OldRetTy != NV->getType() && !Caller->use_empty()) { 2668 if (!NV->getType()->isVoidTy()) { 2669 NV = NC = CastInst::CreateBitOrPointerCast(NC, OldRetTy); 2670 NC->setDebugLoc(Caller->getDebugLoc()); 2671 2672 // If this is an invoke instruction, we should insert it after the first 2673 // non-phi, instruction in the normal successor block. 2674 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) { 2675 BasicBlock::iterator I = II->getNormalDest()->getFirstInsertionPt(); 2676 InsertNewInstBefore(NC, *I); 2677 } else { 2678 // Otherwise, it's a call, just insert cast right after the call. 2679 InsertNewInstBefore(NC, *Caller); 2680 } 2681 Worklist.AddUsersToWorkList(*Caller); 2682 } else { 2683 NV = UndefValue::get(Caller->getType()); 2684 } 2685 } 2686 2687 if (!Caller->use_empty()) 2688 replaceInstUsesWith(*Caller, NV); 2689 else if (Caller->hasValueHandle()) { 2690 if (OldRetTy == NV->getType()) 2691 ValueHandleBase::ValueIsRAUWd(Caller, NV); 2692 else 2693 // We cannot call ValueIsRAUWd with a different type, and the 2694 // actual tracked value will disappear. 2695 ValueHandleBase::ValueIsDeleted(Caller); 2696 } 2697 2698 eraseInstFromFunction(*Caller); 2699 return true; 2700 } 2701 2702 /// Turn a call to a function created by init_trampoline / adjust_trampoline 2703 /// intrinsic pair into a direct call to the underlying function. 2704 Instruction * 2705 InstCombiner::transformCallThroughTrampoline(CallSite CS, 2706 IntrinsicInst *Tramp) { 2707 Value *Callee = CS.getCalledValue(); 2708 PointerType *PTy = cast<PointerType>(Callee->getType()); 2709 FunctionType *FTy = cast<FunctionType>(PTy->getElementType()); 2710 const AttributeSet &Attrs = CS.getAttributes(); 2711 2712 // If the call already has the 'nest' attribute somewhere then give up - 2713 // otherwise 'nest' would occur twice after splicing in the chain. 2714 if (Attrs.hasAttrSomewhere(Attribute::Nest)) 2715 return nullptr; 2716 2717 assert(Tramp && 2718 "transformCallThroughTrampoline called with incorrect CallSite."); 2719 2720 Function *NestF =cast<Function>(Tramp->getArgOperand(1)->stripPointerCasts()); 2721 FunctionType *NestFTy = cast<FunctionType>(NestF->getValueType()); 2722 2723 const AttributeSet &NestAttrs = NestF->getAttributes(); 2724 if (!NestAttrs.isEmpty()) { 2725 unsigned NestIdx = 1; 2726 Type *NestTy = nullptr; 2727 AttributeSet NestAttr; 2728 2729 // Look for a parameter marked with the 'nest' attribute. 2730 for (FunctionType::param_iterator I = NestFTy->param_begin(), 2731 E = NestFTy->param_end(); I != E; ++NestIdx, ++I) 2732 if (NestAttrs.hasAttribute(NestIdx, Attribute::Nest)) { 2733 // Record the parameter type and any other attributes. 2734 NestTy = *I; 2735 NestAttr = NestAttrs.getParamAttributes(NestIdx); 2736 break; 2737 } 2738 2739 if (NestTy) { 2740 Instruction *Caller = CS.getInstruction(); 2741 std::vector<Value*> NewArgs; 2742 NewArgs.reserve(CS.arg_size() + 1); 2743 2744 SmallVector<AttributeSet, 8> NewAttrs; 2745 NewAttrs.reserve(Attrs.getNumSlots() + 1); 2746 2747 // Insert the nest argument into the call argument list, which may 2748 // mean appending it. Likewise for attributes. 2749 2750 // Add any result attributes. 2751 if (Attrs.hasAttributes(AttributeSet::ReturnIndex)) 2752 NewAttrs.push_back(AttributeSet::get(Caller->getContext(), 2753 Attrs.getRetAttributes())); 2754 2755 { 2756 unsigned Idx = 1; 2757 CallSite::arg_iterator I = CS.arg_begin(), E = CS.arg_end(); 2758 do { 2759 if (Idx == NestIdx) { 2760 // Add the chain argument and attributes. 2761 Value *NestVal = Tramp->getArgOperand(2); 2762 if (NestVal->getType() != NestTy) 2763 NestVal = Builder->CreateBitCast(NestVal, NestTy, "nest"); 2764 NewArgs.push_back(NestVal); 2765 NewAttrs.push_back(AttributeSet::get(Caller->getContext(), 2766 NestAttr)); 2767 } 2768 2769 if (I == E) 2770 break; 2771 2772 // Add the original argument and attributes. 2773 NewArgs.push_back(*I); 2774 AttributeSet Attr = Attrs.getParamAttributes(Idx); 2775 if (Attr.hasAttributes(Idx)) { 2776 AttrBuilder B(Attr, Idx); 2777 NewAttrs.push_back(AttributeSet::get(Caller->getContext(), 2778 Idx + (Idx >= NestIdx), B)); 2779 } 2780 2781 ++Idx; 2782 ++I; 2783 } while (1); 2784 } 2785 2786 // Add any function attributes. 2787 if (Attrs.hasAttributes(AttributeSet::FunctionIndex)) 2788 NewAttrs.push_back(AttributeSet::get(FTy->getContext(), 2789 Attrs.getFnAttributes())); 2790 2791 // The trampoline may have been bitcast to a bogus type (FTy). 2792 // Handle this by synthesizing a new function type, equal to FTy 2793 // with the chain parameter inserted. 2794 2795 std::vector<Type*> NewTypes; 2796 NewTypes.reserve(FTy->getNumParams()+1); 2797 2798 // Insert the chain's type into the list of parameter types, which may 2799 // mean appending it. 2800 { 2801 unsigned Idx = 1; 2802 FunctionType::param_iterator I = FTy->param_begin(), 2803 E = FTy->param_end(); 2804 2805 do { 2806 if (Idx == NestIdx) 2807 // Add the chain's type. 2808 NewTypes.push_back(NestTy); 2809 2810 if (I == E) 2811 break; 2812 2813 // Add the original type. 2814 NewTypes.push_back(*I); 2815 2816 ++Idx; 2817 ++I; 2818 } while (1); 2819 } 2820 2821 // Replace the trampoline call with a direct call. Let the generic 2822 // code sort out any function type mismatches. 2823 FunctionType *NewFTy = FunctionType::get(FTy->getReturnType(), NewTypes, 2824 FTy->isVarArg()); 2825 Constant *NewCallee = 2826 NestF->getType() == PointerType::getUnqual(NewFTy) ? 2827 NestF : ConstantExpr::getBitCast(NestF, 2828 PointerType::getUnqual(NewFTy)); 2829 const AttributeSet &NewPAL = 2830 AttributeSet::get(FTy->getContext(), NewAttrs); 2831 2832 SmallVector<OperandBundleDef, 1> OpBundles; 2833 CS.getOperandBundlesAsDefs(OpBundles); 2834 2835 Instruction *NewCaller; 2836 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) { 2837 NewCaller = InvokeInst::Create(NewCallee, 2838 II->getNormalDest(), II->getUnwindDest(), 2839 NewArgs, OpBundles); 2840 cast<InvokeInst>(NewCaller)->setCallingConv(II->getCallingConv()); 2841 cast<InvokeInst>(NewCaller)->setAttributes(NewPAL); 2842 } else { 2843 NewCaller = CallInst::Create(NewCallee, NewArgs, OpBundles); 2844 if (cast<CallInst>(Caller)->isTailCall()) 2845 cast<CallInst>(NewCaller)->setTailCall(); 2846 cast<CallInst>(NewCaller)-> 2847 setCallingConv(cast<CallInst>(Caller)->getCallingConv()); 2848 cast<CallInst>(NewCaller)->setAttributes(NewPAL); 2849 } 2850 2851 return NewCaller; 2852 } 2853 } 2854 2855 // Replace the trampoline call with a direct call. Since there is no 'nest' 2856 // parameter, there is no need to adjust the argument list. Let the generic 2857 // code sort out any function type mismatches. 2858 Constant *NewCallee = 2859 NestF->getType() == PTy ? NestF : 2860 ConstantExpr::getBitCast(NestF, PTy); 2861 CS.setCalledFunction(NewCallee); 2862 return CS.getInstruction(); 2863 } 2864