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