1 //===- InstCombineCalls.cpp -----------------------------------------------===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 // 9 // This file implements the visitCall, visitInvoke, and visitCallBr functions. 10 // 11 //===----------------------------------------------------------------------===// 12 13 #include "InstCombineInternal.h" 14 #include "llvm/ADT/APFloat.h" 15 #include "llvm/ADT/APInt.h" 16 #include "llvm/ADT/APSInt.h" 17 #include "llvm/ADT/ArrayRef.h" 18 #include "llvm/ADT/FloatingPointMode.h" 19 #include "llvm/ADT/None.h" 20 #include "llvm/ADT/Optional.h" 21 #include "llvm/ADT/STLExtras.h" 22 #include "llvm/ADT/SmallVector.h" 23 #include "llvm/ADT/Statistic.h" 24 #include "llvm/ADT/Twine.h" 25 #include "llvm/Analysis/AliasAnalysis.h" 26 #include "llvm/Analysis/AssumeBundleQueries.h" 27 #include "llvm/Analysis/AssumptionCache.h" 28 #include "llvm/Analysis/InstructionSimplify.h" 29 #include "llvm/Analysis/Loads.h" 30 #include "llvm/Analysis/MemoryBuiltins.h" 31 #include "llvm/Analysis/TargetTransformInfo.h" 32 #include "llvm/Analysis/ValueTracking.h" 33 #include "llvm/Analysis/VectorUtils.h" 34 #include "llvm/IR/Attributes.h" 35 #include "llvm/IR/BasicBlock.h" 36 #include "llvm/IR/Constant.h" 37 #include "llvm/IR/Constants.h" 38 #include "llvm/IR/DataLayout.h" 39 #include "llvm/IR/DerivedTypes.h" 40 #include "llvm/IR/Function.h" 41 #include "llvm/IR/GlobalVariable.h" 42 #include "llvm/IR/InstrTypes.h" 43 #include "llvm/IR/Instruction.h" 44 #include "llvm/IR/Instructions.h" 45 #include "llvm/IR/IntrinsicInst.h" 46 #include "llvm/IR/Intrinsics.h" 47 #include "llvm/IR/IntrinsicsAArch64.h" 48 #include "llvm/IR/IntrinsicsAMDGPU.h" 49 #include "llvm/IR/IntrinsicsARM.h" 50 #include "llvm/IR/IntrinsicsHexagon.h" 51 #include "llvm/IR/LLVMContext.h" 52 #include "llvm/IR/Metadata.h" 53 #include "llvm/IR/PatternMatch.h" 54 #include "llvm/IR/Statepoint.h" 55 #include "llvm/IR/Type.h" 56 #include "llvm/IR/User.h" 57 #include "llvm/IR/Value.h" 58 #include "llvm/IR/ValueHandle.h" 59 #include "llvm/Support/AtomicOrdering.h" 60 #include "llvm/Support/Casting.h" 61 #include "llvm/Support/CommandLine.h" 62 #include "llvm/Support/Compiler.h" 63 #include "llvm/Support/Debug.h" 64 #include "llvm/Support/ErrorHandling.h" 65 #include "llvm/Support/KnownBits.h" 66 #include "llvm/Support/MathExtras.h" 67 #include "llvm/Support/raw_ostream.h" 68 #include "llvm/Transforms/InstCombine/InstCombineWorklist.h" 69 #include "llvm/Transforms/InstCombine/InstCombiner.h" 70 #include "llvm/Transforms/Utils/Local.h" 71 #include "llvm/Transforms/Utils/SimplifyLibCalls.h" 72 #include <algorithm> 73 #include <cassert> 74 #include <cstdint> 75 #include <cstring> 76 #include <utility> 77 #include <vector> 78 79 using namespace llvm; 80 using namespace PatternMatch; 81 82 #define DEBUG_TYPE "instcombine" 83 84 STATISTIC(NumSimplified, "Number of library calls simplified"); 85 86 static cl::opt<unsigned> GuardWideningWindow( 87 "instcombine-guard-widening-window", 88 cl::init(3), 89 cl::desc("How wide an instruction window to bypass looking for " 90 "another guard")); 91 92 /// Return the specified type promoted as it would be to pass though a va_arg 93 /// area. 94 static Type *getPromotedType(Type *Ty) { 95 if (IntegerType* ITy = dyn_cast<IntegerType>(Ty)) { 96 if (ITy->getBitWidth() < 32) 97 return Type::getInt32Ty(Ty->getContext()); 98 } 99 return Ty; 100 } 101 102 Instruction *InstCombinerImpl::SimplifyAnyMemTransfer(AnyMemTransferInst *MI) { 103 Align DstAlign = getKnownAlignment(MI->getRawDest(), DL, MI, &AC, &DT); 104 MaybeAlign CopyDstAlign = MI->getDestAlign(); 105 if (!CopyDstAlign || *CopyDstAlign < DstAlign) { 106 MI->setDestAlignment(DstAlign); 107 return MI; 108 } 109 110 Align SrcAlign = getKnownAlignment(MI->getRawSource(), DL, MI, &AC, &DT); 111 MaybeAlign CopySrcAlign = MI->getSourceAlign(); 112 if (!CopySrcAlign || *CopySrcAlign < SrcAlign) { 113 MI->setSourceAlignment(SrcAlign); 114 return MI; 115 } 116 117 // If we have a store to a location which is known constant, we can conclude 118 // that the store must be storing the constant value (else the memory 119 // wouldn't be constant), and this must be a noop. 120 if (AA->pointsToConstantMemory(MI->getDest())) { 121 // Set the size of the copy to 0, it will be deleted on the next iteration. 122 MI->setLength(Constant::getNullValue(MI->getLength()->getType())); 123 return MI; 124 } 125 126 // If MemCpyInst length is 1/2/4/8 bytes then replace memcpy with 127 // load/store. 128 ConstantInt *MemOpLength = dyn_cast<ConstantInt>(MI->getLength()); 129 if (!MemOpLength) return nullptr; 130 131 // Source and destination pointer types are always "i8*" for intrinsic. See 132 // if the size is something we can handle with a single primitive load/store. 133 // A single load+store correctly handles overlapping memory in the memmove 134 // case. 135 uint64_t Size = MemOpLength->getLimitedValue(); 136 assert(Size && "0-sized memory transferring should be removed already."); 137 138 if (Size > 8 || (Size&(Size-1))) 139 return nullptr; // If not 1/2/4/8 bytes, exit. 140 141 // If it is an atomic and alignment is less than the size then we will 142 // introduce the unaligned memory access which will be later transformed 143 // into libcall in CodeGen. This is not evident performance gain so disable 144 // it now. 145 if (isa<AtomicMemTransferInst>(MI)) 146 if (*CopyDstAlign < Size || *CopySrcAlign < Size) 147 return nullptr; 148 149 // Use an integer load+store unless we can find something better. 150 unsigned SrcAddrSp = 151 cast<PointerType>(MI->getArgOperand(1)->getType())->getAddressSpace(); 152 unsigned DstAddrSp = 153 cast<PointerType>(MI->getArgOperand(0)->getType())->getAddressSpace(); 154 155 IntegerType* IntType = IntegerType::get(MI->getContext(), Size<<3); 156 Type *NewSrcPtrTy = PointerType::get(IntType, SrcAddrSp); 157 Type *NewDstPtrTy = PointerType::get(IntType, DstAddrSp); 158 159 // If the memcpy has metadata describing the members, see if we can get the 160 // TBAA tag describing our copy. 161 MDNode *CopyMD = nullptr; 162 if (MDNode *M = MI->getMetadata(LLVMContext::MD_tbaa)) { 163 CopyMD = M; 164 } else if (MDNode *M = MI->getMetadata(LLVMContext::MD_tbaa_struct)) { 165 if (M->getNumOperands() == 3 && M->getOperand(0) && 166 mdconst::hasa<ConstantInt>(M->getOperand(0)) && 167 mdconst::extract<ConstantInt>(M->getOperand(0))->isZero() && 168 M->getOperand(1) && 169 mdconst::hasa<ConstantInt>(M->getOperand(1)) && 170 mdconst::extract<ConstantInt>(M->getOperand(1))->getValue() == 171 Size && 172 M->getOperand(2) && isa<MDNode>(M->getOperand(2))) 173 CopyMD = cast<MDNode>(M->getOperand(2)); 174 } 175 176 Value *Src = Builder.CreateBitCast(MI->getArgOperand(1), NewSrcPtrTy); 177 Value *Dest = Builder.CreateBitCast(MI->getArgOperand(0), NewDstPtrTy); 178 LoadInst *L = Builder.CreateLoad(IntType, Src); 179 // Alignment from the mem intrinsic will be better, so use it. 180 L->setAlignment(*CopySrcAlign); 181 if (CopyMD) 182 L->setMetadata(LLVMContext::MD_tbaa, CopyMD); 183 MDNode *LoopMemParallelMD = 184 MI->getMetadata(LLVMContext::MD_mem_parallel_loop_access); 185 if (LoopMemParallelMD) 186 L->setMetadata(LLVMContext::MD_mem_parallel_loop_access, LoopMemParallelMD); 187 MDNode *AccessGroupMD = MI->getMetadata(LLVMContext::MD_access_group); 188 if (AccessGroupMD) 189 L->setMetadata(LLVMContext::MD_access_group, AccessGroupMD); 190 191 StoreInst *S = Builder.CreateStore(L, Dest); 192 // Alignment from the mem intrinsic will be better, so use it. 193 S->setAlignment(*CopyDstAlign); 194 if (CopyMD) 195 S->setMetadata(LLVMContext::MD_tbaa, CopyMD); 196 if (LoopMemParallelMD) 197 S->setMetadata(LLVMContext::MD_mem_parallel_loop_access, LoopMemParallelMD); 198 if (AccessGroupMD) 199 S->setMetadata(LLVMContext::MD_access_group, AccessGroupMD); 200 201 if (auto *MT = dyn_cast<MemTransferInst>(MI)) { 202 // non-atomics can be volatile 203 L->setVolatile(MT->isVolatile()); 204 S->setVolatile(MT->isVolatile()); 205 } 206 if (isa<AtomicMemTransferInst>(MI)) { 207 // atomics have to be unordered 208 L->setOrdering(AtomicOrdering::Unordered); 209 S->setOrdering(AtomicOrdering::Unordered); 210 } 211 212 // Set the size of the copy to 0, it will be deleted on the next iteration. 213 MI->setLength(Constant::getNullValue(MemOpLength->getType())); 214 return MI; 215 } 216 217 Instruction *InstCombinerImpl::SimplifyAnyMemSet(AnyMemSetInst *MI) { 218 const Align KnownAlignment = 219 getKnownAlignment(MI->getDest(), DL, MI, &AC, &DT); 220 MaybeAlign MemSetAlign = MI->getDestAlign(); 221 if (!MemSetAlign || *MemSetAlign < KnownAlignment) { 222 MI->setDestAlignment(KnownAlignment); 223 return MI; 224 } 225 226 // If we have a store to a location which is known constant, we can conclude 227 // that the store must be storing the constant value (else the memory 228 // wouldn't be constant), and this must be a noop. 229 if (AA->pointsToConstantMemory(MI->getDest())) { 230 // Set the size of the copy to 0, it will be deleted on the next iteration. 231 MI->setLength(Constant::getNullValue(MI->getLength()->getType())); 232 return MI; 233 } 234 235 // Extract the length and alignment and fill if they are constant. 236 ConstantInt *LenC = dyn_cast<ConstantInt>(MI->getLength()); 237 ConstantInt *FillC = dyn_cast<ConstantInt>(MI->getValue()); 238 if (!LenC || !FillC || !FillC->getType()->isIntegerTy(8)) 239 return nullptr; 240 const uint64_t Len = LenC->getLimitedValue(); 241 assert(Len && "0-sized memory setting should be removed already."); 242 const Align Alignment = assumeAligned(MI->getDestAlignment()); 243 244 // If it is an atomic and alignment is less than the size then we will 245 // introduce the unaligned memory access which will be later transformed 246 // into libcall in CodeGen. This is not evident performance gain so disable 247 // it now. 248 if (isa<AtomicMemSetInst>(MI)) 249 if (Alignment < Len) 250 return nullptr; 251 252 // memset(s,c,n) -> store s, c (for n=1,2,4,8) 253 if (Len <= 8 && isPowerOf2_32((uint32_t)Len)) { 254 Type *ITy = IntegerType::get(MI->getContext(), Len*8); // n=1 -> i8. 255 256 Value *Dest = MI->getDest(); 257 unsigned DstAddrSp = cast<PointerType>(Dest->getType())->getAddressSpace(); 258 Type *NewDstPtrTy = PointerType::get(ITy, DstAddrSp); 259 Dest = Builder.CreateBitCast(Dest, NewDstPtrTy); 260 261 // Extract the fill value and store. 262 uint64_t Fill = FillC->getZExtValue()*0x0101010101010101ULL; 263 StoreInst *S = Builder.CreateStore(ConstantInt::get(ITy, Fill), Dest, 264 MI->isVolatile()); 265 S->setAlignment(Alignment); 266 if (isa<AtomicMemSetInst>(MI)) 267 S->setOrdering(AtomicOrdering::Unordered); 268 269 // Set the size of the copy to 0, it will be deleted on the next iteration. 270 MI->setLength(Constant::getNullValue(LenC->getType())); 271 return MI; 272 } 273 274 return nullptr; 275 } 276 277 // TODO, Obvious Missing Transforms: 278 // * Narrow width by halfs excluding zero/undef lanes 279 Value *InstCombinerImpl::simplifyMaskedLoad(IntrinsicInst &II) { 280 Value *LoadPtr = II.getArgOperand(0); 281 const Align Alignment = 282 cast<ConstantInt>(II.getArgOperand(1))->getAlignValue(); 283 284 // If the mask is all ones or undefs, this is a plain vector load of the 1st 285 // argument. 286 if (maskIsAllOneOrUndef(II.getArgOperand(2))) 287 return Builder.CreateAlignedLoad(II.getType(), LoadPtr, Alignment, 288 "unmaskedload"); 289 290 // If we can unconditionally load from this address, replace with a 291 // load/select idiom. TODO: use DT for context sensitive query 292 if (isDereferenceablePointer(LoadPtr, II.getType(), 293 II.getModule()->getDataLayout(), &II, nullptr)) { 294 Value *LI = Builder.CreateAlignedLoad(II.getType(), LoadPtr, Alignment, 295 "unmaskedload"); 296 return Builder.CreateSelect(II.getArgOperand(2), LI, II.getArgOperand(3)); 297 } 298 299 return nullptr; 300 } 301 302 // TODO, Obvious Missing Transforms: 303 // * Single constant active lane -> store 304 // * Narrow width by halfs excluding zero/undef lanes 305 Instruction *InstCombinerImpl::simplifyMaskedStore(IntrinsicInst &II) { 306 auto *ConstMask = dyn_cast<Constant>(II.getArgOperand(3)); 307 if (!ConstMask) 308 return nullptr; 309 310 // If the mask is all zeros, this instruction does nothing. 311 if (ConstMask->isNullValue()) 312 return eraseInstFromFunction(II); 313 314 // If the mask is all ones, this is a plain vector store of the 1st argument. 315 if (ConstMask->isAllOnesValue()) { 316 Value *StorePtr = II.getArgOperand(1); 317 Align Alignment = cast<ConstantInt>(II.getArgOperand(2))->getAlignValue(); 318 return new StoreInst(II.getArgOperand(0), StorePtr, false, Alignment); 319 } 320 321 if (isa<ScalableVectorType>(ConstMask->getType())) 322 return nullptr; 323 324 // Use masked off lanes to simplify operands via SimplifyDemandedVectorElts 325 APInt DemandedElts = possiblyDemandedEltsInMask(ConstMask); 326 APInt UndefElts(DemandedElts.getBitWidth(), 0); 327 if (Value *V = 328 SimplifyDemandedVectorElts(II.getOperand(0), DemandedElts, UndefElts)) 329 return replaceOperand(II, 0, V); 330 331 return nullptr; 332 } 333 334 // TODO, Obvious Missing Transforms: 335 // * Single constant active lane load -> load 336 // * Dereferenceable address & few lanes -> scalarize speculative load/selects 337 // * Adjacent vector addresses -> masked.load 338 // * Narrow width by halfs excluding zero/undef lanes 339 // * Vector splat address w/known mask -> scalar load 340 // * Vector incrementing address -> vector masked load 341 Instruction *InstCombinerImpl::simplifyMaskedGather(IntrinsicInst &II) { 342 return nullptr; 343 } 344 345 // TODO, Obvious Missing Transforms: 346 // * Single constant active lane -> store 347 // * Adjacent vector addresses -> masked.store 348 // * Narrow store width by halfs excluding zero/undef lanes 349 // * Vector splat address w/known mask -> scalar store 350 // * Vector incrementing address -> vector masked store 351 Instruction *InstCombinerImpl::simplifyMaskedScatter(IntrinsicInst &II) { 352 auto *ConstMask = dyn_cast<Constant>(II.getArgOperand(3)); 353 if (!ConstMask) 354 return nullptr; 355 356 // If the mask is all zeros, a scatter does nothing. 357 if (ConstMask->isNullValue()) 358 return eraseInstFromFunction(II); 359 360 if (isa<ScalableVectorType>(ConstMask->getType())) 361 return nullptr; 362 363 // Use masked off lanes to simplify operands via SimplifyDemandedVectorElts 364 APInt DemandedElts = possiblyDemandedEltsInMask(ConstMask); 365 APInt UndefElts(DemandedElts.getBitWidth(), 0); 366 if (Value *V = 367 SimplifyDemandedVectorElts(II.getOperand(0), DemandedElts, UndefElts)) 368 return replaceOperand(II, 0, V); 369 if (Value *V = 370 SimplifyDemandedVectorElts(II.getOperand(1), DemandedElts, UndefElts)) 371 return replaceOperand(II, 1, V); 372 373 return nullptr; 374 } 375 376 /// This function transforms launder.invariant.group and strip.invariant.group 377 /// like: 378 /// launder(launder(%x)) -> launder(%x) (the result is not the argument) 379 /// launder(strip(%x)) -> launder(%x) 380 /// strip(strip(%x)) -> strip(%x) (the result is not the argument) 381 /// strip(launder(%x)) -> strip(%x) 382 /// This is legal because it preserves the most recent information about 383 /// the presence or absence of invariant.group. 384 static Instruction *simplifyInvariantGroupIntrinsic(IntrinsicInst &II, 385 InstCombinerImpl &IC) { 386 auto *Arg = II.getArgOperand(0); 387 auto *StrippedArg = Arg->stripPointerCasts(); 388 auto *StrippedInvariantGroupsArg = Arg->stripPointerCastsAndInvariantGroups(); 389 if (StrippedArg == StrippedInvariantGroupsArg) 390 return nullptr; // No launders/strips to remove. 391 392 Value *Result = nullptr; 393 394 if (II.getIntrinsicID() == Intrinsic::launder_invariant_group) 395 Result = IC.Builder.CreateLaunderInvariantGroup(StrippedInvariantGroupsArg); 396 else if (II.getIntrinsicID() == Intrinsic::strip_invariant_group) 397 Result = IC.Builder.CreateStripInvariantGroup(StrippedInvariantGroupsArg); 398 else 399 llvm_unreachable( 400 "simplifyInvariantGroupIntrinsic only handles launder and strip"); 401 if (Result->getType()->getPointerAddressSpace() != 402 II.getType()->getPointerAddressSpace()) 403 Result = IC.Builder.CreateAddrSpaceCast(Result, II.getType()); 404 if (Result->getType() != II.getType()) 405 Result = IC.Builder.CreateBitCast(Result, II.getType()); 406 407 return cast<Instruction>(Result); 408 } 409 410 static Instruction *foldCttzCtlz(IntrinsicInst &II, InstCombinerImpl &IC) { 411 assert((II.getIntrinsicID() == Intrinsic::cttz || 412 II.getIntrinsicID() == Intrinsic::ctlz) && 413 "Expected cttz or ctlz intrinsic"); 414 bool IsTZ = II.getIntrinsicID() == Intrinsic::cttz; 415 Value *Op0 = II.getArgOperand(0); 416 Value *X; 417 // ctlz(bitreverse(x)) -> cttz(x) 418 // cttz(bitreverse(x)) -> ctlz(x) 419 if (match(Op0, m_BitReverse(m_Value(X)))) { 420 Intrinsic::ID ID = IsTZ ? Intrinsic::ctlz : Intrinsic::cttz; 421 Function *F = Intrinsic::getDeclaration(II.getModule(), ID, II.getType()); 422 return CallInst::Create(F, {X, II.getArgOperand(1)}); 423 } 424 425 if (IsTZ) { 426 // cttz(-x) -> cttz(x) 427 if (match(Op0, m_Neg(m_Value(X)))) 428 return IC.replaceOperand(II, 0, X); 429 430 // cttz(abs(x)) -> cttz(x) 431 // cttz(nabs(x)) -> cttz(x) 432 Value *Y; 433 SelectPatternFlavor SPF = matchSelectPattern(Op0, X, Y).Flavor; 434 if (SPF == SPF_ABS || SPF == SPF_NABS) 435 return IC.replaceOperand(II, 0, X); 436 437 if (match(Op0, m_Intrinsic<Intrinsic::abs>(m_Value(X)))) 438 return IC.replaceOperand(II, 0, X); 439 } 440 441 KnownBits Known = IC.computeKnownBits(Op0, 0, &II); 442 443 // Create a mask for bits above (ctlz) or below (cttz) the first known one. 444 unsigned PossibleZeros = IsTZ ? Known.countMaxTrailingZeros() 445 : Known.countMaxLeadingZeros(); 446 unsigned DefiniteZeros = IsTZ ? Known.countMinTrailingZeros() 447 : Known.countMinLeadingZeros(); 448 449 // If all bits above (ctlz) or below (cttz) the first known one are known 450 // zero, this value is constant. 451 // FIXME: This should be in InstSimplify because we're replacing an 452 // instruction with a constant. 453 if (PossibleZeros == DefiniteZeros) { 454 auto *C = ConstantInt::get(Op0->getType(), DefiniteZeros); 455 return IC.replaceInstUsesWith(II, C); 456 } 457 458 // If the input to cttz/ctlz is known to be non-zero, 459 // then change the 'ZeroIsUndef' parameter to 'true' 460 // because we know the zero behavior can't affect the result. 461 if (!Known.One.isNullValue() || 462 isKnownNonZero(Op0, IC.getDataLayout(), 0, &IC.getAssumptionCache(), &II, 463 &IC.getDominatorTree())) { 464 if (!match(II.getArgOperand(1), m_One())) 465 return IC.replaceOperand(II, 1, IC.Builder.getTrue()); 466 } 467 468 // Add range metadata since known bits can't completely reflect what we know. 469 // TODO: Handle splat vectors. 470 auto *IT = dyn_cast<IntegerType>(Op0->getType()); 471 if (IT && IT->getBitWidth() != 1 && !II.getMetadata(LLVMContext::MD_range)) { 472 Metadata *LowAndHigh[] = { 473 ConstantAsMetadata::get(ConstantInt::get(IT, DefiniteZeros)), 474 ConstantAsMetadata::get(ConstantInt::get(IT, PossibleZeros + 1))}; 475 II.setMetadata(LLVMContext::MD_range, 476 MDNode::get(II.getContext(), LowAndHigh)); 477 return &II; 478 } 479 480 return nullptr; 481 } 482 483 static Instruction *foldCtpop(IntrinsicInst &II, InstCombinerImpl &IC) { 484 assert(II.getIntrinsicID() == Intrinsic::ctpop && 485 "Expected ctpop intrinsic"); 486 Type *Ty = II.getType(); 487 unsigned BitWidth = Ty->getScalarSizeInBits(); 488 Value *Op0 = II.getArgOperand(0); 489 Value *X; 490 491 // ctpop(bitreverse(x)) -> ctpop(x) 492 // ctpop(bswap(x)) -> ctpop(x) 493 if (match(Op0, m_BitReverse(m_Value(X))) || match(Op0, m_BSwap(m_Value(X)))) 494 return IC.replaceOperand(II, 0, X); 495 496 // ctpop(x | -x) -> bitwidth - cttz(x, false) 497 if (Op0->hasOneUse() && 498 match(Op0, m_c_Or(m_Value(X), m_Neg(m_Deferred(X))))) { 499 Function *F = 500 Intrinsic::getDeclaration(II.getModule(), Intrinsic::cttz, Ty); 501 auto *Cttz = IC.Builder.CreateCall(F, {X, IC.Builder.getFalse()}); 502 auto *Bw = ConstantInt::get(Ty, APInt(BitWidth, BitWidth)); 503 return IC.replaceInstUsesWith(II, IC.Builder.CreateSub(Bw, Cttz)); 504 } 505 506 // ctpop(~x & (x - 1)) -> cttz(x, false) 507 if (match(Op0, 508 m_c_And(m_Not(m_Value(X)), m_Add(m_Deferred(X), m_AllOnes())))) { 509 Function *F = 510 Intrinsic::getDeclaration(II.getModule(), Intrinsic::cttz, Ty); 511 return CallInst::Create(F, {X, IC.Builder.getFalse()}); 512 } 513 514 // FIXME: Try to simplify vectors of integers. 515 auto *IT = dyn_cast<IntegerType>(Ty); 516 if (!IT) 517 return nullptr; 518 519 KnownBits Known(BitWidth); 520 IC.computeKnownBits(Op0, Known, 0, &II); 521 522 unsigned MinCount = Known.countMinPopulation(); 523 unsigned MaxCount = Known.countMaxPopulation(); 524 525 // Add range metadata since known bits can't completely reflect what we know. 526 if (IT->getBitWidth() != 1 && !II.getMetadata(LLVMContext::MD_range)) { 527 Metadata *LowAndHigh[] = { 528 ConstantAsMetadata::get(ConstantInt::get(IT, MinCount)), 529 ConstantAsMetadata::get(ConstantInt::get(IT, MaxCount + 1))}; 530 II.setMetadata(LLVMContext::MD_range, 531 MDNode::get(II.getContext(), LowAndHigh)); 532 return &II; 533 } 534 535 return nullptr; 536 } 537 538 /// Convert a table lookup to shufflevector if the mask is constant. 539 /// This could benefit tbl1 if the mask is { 7,6,5,4,3,2,1,0 }, in 540 /// which case we could lower the shufflevector with rev64 instructions 541 /// as it's actually a byte reverse. 542 static Value *simplifyNeonTbl1(const IntrinsicInst &II, 543 InstCombiner::BuilderTy &Builder) { 544 // Bail out if the mask is not a constant. 545 auto *C = dyn_cast<Constant>(II.getArgOperand(1)); 546 if (!C) 547 return nullptr; 548 549 auto *VecTy = cast<FixedVectorType>(II.getType()); 550 unsigned NumElts = VecTy->getNumElements(); 551 552 // Only perform this transformation for <8 x i8> vector types. 553 if (!VecTy->getElementType()->isIntegerTy(8) || NumElts != 8) 554 return nullptr; 555 556 int Indexes[8]; 557 558 for (unsigned I = 0; I < NumElts; ++I) { 559 Constant *COp = C->getAggregateElement(I); 560 561 if (!COp || !isa<ConstantInt>(COp)) 562 return nullptr; 563 564 Indexes[I] = cast<ConstantInt>(COp)->getLimitedValue(); 565 566 // Make sure the mask indices are in range. 567 if ((unsigned)Indexes[I] >= NumElts) 568 return nullptr; 569 } 570 571 auto *V1 = II.getArgOperand(0); 572 auto *V2 = Constant::getNullValue(V1->getType()); 573 return Builder.CreateShuffleVector(V1, V2, makeArrayRef(Indexes)); 574 } 575 576 // Returns true iff the 2 intrinsics have the same operands, limiting the 577 // comparison to the first NumOperands. 578 static bool haveSameOperands(const IntrinsicInst &I, const IntrinsicInst &E, 579 unsigned NumOperands) { 580 assert(I.getNumArgOperands() >= NumOperands && "Not enough operands"); 581 assert(E.getNumArgOperands() >= NumOperands && "Not enough operands"); 582 for (unsigned i = 0; i < NumOperands; i++) 583 if (I.getArgOperand(i) != E.getArgOperand(i)) 584 return false; 585 return true; 586 } 587 588 // Remove trivially empty start/end intrinsic ranges, i.e. a start 589 // immediately followed by an end (ignoring debuginfo or other 590 // start/end intrinsics in between). As this handles only the most trivial 591 // cases, tracking the nesting level is not needed: 592 // 593 // call @llvm.foo.start(i1 0) 594 // call @llvm.foo.start(i1 0) ; This one won't be skipped: it will be removed 595 // call @llvm.foo.end(i1 0) 596 // call @llvm.foo.end(i1 0) ; &I 597 static bool 598 removeTriviallyEmptyRange(IntrinsicInst &EndI, InstCombinerImpl &IC, 599 std::function<bool(const IntrinsicInst &)> IsStart) { 600 // We start from the end intrinsic and scan backwards, so that InstCombine 601 // has already processed (and potentially removed) all the instructions 602 // before the end intrinsic. 603 BasicBlock::reverse_iterator BI(EndI), BE(EndI.getParent()->rend()); 604 for (; BI != BE; ++BI) { 605 if (auto *I = dyn_cast<IntrinsicInst>(&*BI)) { 606 if (isa<DbgInfoIntrinsic>(I) || 607 I->getIntrinsicID() == EndI.getIntrinsicID()) 608 continue; 609 if (IsStart(*I)) { 610 if (haveSameOperands(EndI, *I, EndI.getNumArgOperands())) { 611 IC.eraseInstFromFunction(*I); 612 IC.eraseInstFromFunction(EndI); 613 return true; 614 } 615 // Skip start intrinsics that don't pair with this end intrinsic. 616 continue; 617 } 618 } 619 break; 620 } 621 622 return false; 623 } 624 625 Instruction *InstCombinerImpl::visitVAEndInst(VAEndInst &I) { 626 removeTriviallyEmptyRange(I, *this, [](const IntrinsicInst &I) { 627 return I.getIntrinsicID() == Intrinsic::vastart || 628 I.getIntrinsicID() == Intrinsic::vacopy; 629 }); 630 return nullptr; 631 } 632 633 static CallInst *canonicalizeConstantArg0ToArg1(CallInst &Call) { 634 assert(Call.getNumArgOperands() > 1 && "Need at least 2 args to swap"); 635 Value *Arg0 = Call.getArgOperand(0), *Arg1 = Call.getArgOperand(1); 636 if (isa<Constant>(Arg0) && !isa<Constant>(Arg1)) { 637 Call.setArgOperand(0, Arg1); 638 Call.setArgOperand(1, Arg0); 639 return &Call; 640 } 641 return nullptr; 642 } 643 644 /// Creates a result tuple for an overflow intrinsic \p II with a given 645 /// \p Result and a constant \p Overflow value. 646 static Instruction *createOverflowTuple(IntrinsicInst *II, Value *Result, 647 Constant *Overflow) { 648 Constant *V[] = {UndefValue::get(Result->getType()), Overflow}; 649 StructType *ST = cast<StructType>(II->getType()); 650 Constant *Struct = ConstantStruct::get(ST, V); 651 return InsertValueInst::Create(Struct, Result, 0); 652 } 653 654 Instruction * 655 InstCombinerImpl::foldIntrinsicWithOverflowCommon(IntrinsicInst *II) { 656 WithOverflowInst *WO = cast<WithOverflowInst>(II); 657 Value *OperationResult = nullptr; 658 Constant *OverflowResult = nullptr; 659 if (OptimizeOverflowCheck(WO->getBinaryOp(), WO->isSigned(), WO->getLHS(), 660 WO->getRHS(), *WO, OperationResult, OverflowResult)) 661 return createOverflowTuple(WO, OperationResult, OverflowResult); 662 return nullptr; 663 } 664 665 static Optional<bool> getKnownSign(Value *Op, Instruction *CxtI, 666 const DataLayout &DL, AssumptionCache *AC, 667 DominatorTree *DT) { 668 KnownBits Known = computeKnownBits(Op, DL, 0, AC, CxtI, DT); 669 if (Known.isNonNegative()) 670 return false; 671 if (Known.isNegative()) 672 return true; 673 674 return isImpliedByDomCondition( 675 ICmpInst::ICMP_SLT, Op, Constant::getNullValue(Op->getType()), CxtI, DL); 676 } 677 678 /// CallInst simplification. This mostly only handles folding of intrinsic 679 /// instructions. For normal calls, it allows visitCallBase to do the heavy 680 /// lifting. 681 Instruction *InstCombinerImpl::visitCallInst(CallInst &CI) { 682 // Don't try to simplify calls without uses. It will not do anything useful, 683 // but will result in the following folds being skipped. 684 if (!CI.use_empty()) 685 if (Value *V = SimplifyCall(&CI, SQ.getWithInstruction(&CI))) 686 return replaceInstUsesWith(CI, V); 687 688 if (isFreeCall(&CI, &TLI)) 689 return visitFree(CI); 690 691 // If the caller function is nounwind, mark the call as nounwind, even if the 692 // callee isn't. 693 if (CI.getFunction()->doesNotThrow() && !CI.doesNotThrow()) { 694 CI.setDoesNotThrow(); 695 return &CI; 696 } 697 698 IntrinsicInst *II = dyn_cast<IntrinsicInst>(&CI); 699 if (!II) return visitCallBase(CI); 700 701 // For atomic unordered mem intrinsics if len is not a positive or 702 // not a multiple of element size then behavior is undefined. 703 if (auto *AMI = dyn_cast<AtomicMemIntrinsic>(II)) 704 if (ConstantInt *NumBytes = dyn_cast<ConstantInt>(AMI->getLength())) 705 if (NumBytes->getSExtValue() < 0 || 706 (NumBytes->getZExtValue() % AMI->getElementSizeInBytes() != 0)) { 707 CreateNonTerminatorUnreachable(AMI); 708 assert(AMI->getType()->isVoidTy() && 709 "non void atomic unordered mem intrinsic"); 710 return eraseInstFromFunction(*AMI); 711 } 712 713 // Intrinsics cannot occur in an invoke or a callbr, so handle them here 714 // instead of in visitCallBase. 715 if (auto *MI = dyn_cast<AnyMemIntrinsic>(II)) { 716 bool Changed = false; 717 718 // memmove/cpy/set of zero bytes is a noop. 719 if (Constant *NumBytes = dyn_cast<Constant>(MI->getLength())) { 720 if (NumBytes->isNullValue()) 721 return eraseInstFromFunction(CI); 722 723 if (ConstantInt *CI = dyn_cast<ConstantInt>(NumBytes)) 724 if (CI->getZExtValue() == 1) { 725 // Replace the instruction with just byte operations. We would 726 // transform other cases to loads/stores, but we don't know if 727 // alignment is sufficient. 728 } 729 } 730 731 // No other transformations apply to volatile transfers. 732 if (auto *M = dyn_cast<MemIntrinsic>(MI)) 733 if (M->isVolatile()) 734 return nullptr; 735 736 // If we have a memmove and the source operation is a constant global, 737 // then the source and dest pointers can't alias, so we can change this 738 // into a call to memcpy. 739 if (auto *MMI = dyn_cast<AnyMemMoveInst>(MI)) { 740 if (GlobalVariable *GVSrc = dyn_cast<GlobalVariable>(MMI->getSource())) 741 if (GVSrc->isConstant()) { 742 Module *M = CI.getModule(); 743 Intrinsic::ID MemCpyID = 744 isa<AtomicMemMoveInst>(MMI) 745 ? Intrinsic::memcpy_element_unordered_atomic 746 : Intrinsic::memcpy; 747 Type *Tys[3] = { CI.getArgOperand(0)->getType(), 748 CI.getArgOperand(1)->getType(), 749 CI.getArgOperand(2)->getType() }; 750 CI.setCalledFunction(Intrinsic::getDeclaration(M, MemCpyID, Tys)); 751 Changed = true; 752 } 753 } 754 755 if (AnyMemTransferInst *MTI = dyn_cast<AnyMemTransferInst>(MI)) { 756 // memmove(x,x,size) -> noop. 757 if (MTI->getSource() == MTI->getDest()) 758 return eraseInstFromFunction(CI); 759 } 760 761 // If we can determine a pointer alignment that is bigger than currently 762 // set, update the alignment. 763 if (auto *MTI = dyn_cast<AnyMemTransferInst>(MI)) { 764 if (Instruction *I = SimplifyAnyMemTransfer(MTI)) 765 return I; 766 } else if (auto *MSI = dyn_cast<AnyMemSetInst>(MI)) { 767 if (Instruction *I = SimplifyAnyMemSet(MSI)) 768 return I; 769 } 770 771 if (Changed) return II; 772 } 773 774 // For fixed width vector result intrinsics, use the generic demanded vector 775 // support. 776 if (auto *IIFVTy = dyn_cast<FixedVectorType>(II->getType())) { 777 auto VWidth = IIFVTy->getNumElements(); 778 APInt UndefElts(VWidth, 0); 779 APInt AllOnesEltMask(APInt::getAllOnesValue(VWidth)); 780 if (Value *V = SimplifyDemandedVectorElts(II, AllOnesEltMask, UndefElts)) { 781 if (V != II) 782 return replaceInstUsesWith(*II, V); 783 return II; 784 } 785 } 786 787 if (II->isCommutative()) { 788 if (CallInst *NewCall = canonicalizeConstantArg0ToArg1(CI)) 789 return NewCall; 790 } 791 792 Intrinsic::ID IID = II->getIntrinsicID(); 793 switch (IID) { 794 case Intrinsic::objectsize: 795 if (Value *V = lowerObjectSizeCall(II, DL, &TLI, /*MustSucceed=*/false)) 796 return replaceInstUsesWith(CI, V); 797 return nullptr; 798 case Intrinsic::abs: { 799 Value *IIOperand = II->getArgOperand(0); 800 bool IntMinIsPoison = cast<Constant>(II->getArgOperand(1))->isOneValue(); 801 802 // abs(-x) -> abs(x) 803 // TODO: Copy nsw if it was present on the neg? 804 Value *X; 805 if (match(IIOperand, m_Neg(m_Value(X)))) 806 return replaceOperand(*II, 0, X); 807 if (match(IIOperand, m_Select(m_Value(), m_Value(X), m_Neg(m_Deferred(X))))) 808 return replaceOperand(*II, 0, X); 809 if (match(IIOperand, m_Select(m_Value(), m_Neg(m_Value(X)), m_Deferred(X)))) 810 return replaceOperand(*II, 0, X); 811 812 if (Optional<bool> Sign = getKnownSign(IIOperand, II, DL, &AC, &DT)) { 813 // abs(x) -> x if x >= 0 814 if (!*Sign) 815 return replaceInstUsesWith(*II, IIOperand); 816 817 // abs(x) -> -x if x < 0 818 if (IntMinIsPoison) 819 return BinaryOperator::CreateNSWNeg(IIOperand); 820 return BinaryOperator::CreateNeg(IIOperand); 821 } 822 823 // abs (sext X) --> zext (abs X*) 824 // Clear the IsIntMin (nsw) bit on the abs to allow narrowing. 825 if (match(IIOperand, m_OneUse(m_SExt(m_Value(X))))) { 826 Value *NarrowAbs = 827 Builder.CreateBinaryIntrinsic(Intrinsic::abs, X, Builder.getFalse()); 828 return CastInst::Create(Instruction::ZExt, NarrowAbs, II->getType()); 829 } 830 831 break; 832 } 833 case Intrinsic::umax: 834 case Intrinsic::umin: { 835 Value *I0 = II->getArgOperand(0), *I1 = II->getArgOperand(1); 836 Value *X, *Y; 837 if (match(I0, m_ZExt(m_Value(X))) && match(I1, m_ZExt(m_Value(Y))) && 838 (I0->hasOneUse() || I1->hasOneUse()) && X->getType() == Y->getType()) { 839 Value *NarrowMaxMin = Builder.CreateBinaryIntrinsic(IID, X, Y); 840 return CastInst::Create(Instruction::ZExt, NarrowMaxMin, II->getType()); 841 } 842 // If both operands of unsigned min/max are sign-extended, it is still ok 843 // to narrow the operation. 844 LLVM_FALLTHROUGH; 845 } 846 case Intrinsic::smax: 847 case Intrinsic::smin: { 848 Value *I0 = II->getArgOperand(0), *I1 = II->getArgOperand(1); 849 Value *X, *Y; 850 if (match(I0, m_SExt(m_Value(X))) && match(I1, m_SExt(m_Value(Y))) && 851 (I0->hasOneUse() || I1->hasOneUse()) && X->getType() == Y->getType()) { 852 Value *NarrowMaxMin = Builder.CreateBinaryIntrinsic(IID, X, Y); 853 return CastInst::Create(Instruction::SExt, NarrowMaxMin, II->getType()); 854 } 855 break; 856 } 857 case Intrinsic::bswap: { 858 Value *IIOperand = II->getArgOperand(0); 859 Value *X = nullptr; 860 861 // bswap(trunc(bswap(x))) -> trunc(lshr(x, c)) 862 if (match(IIOperand, m_Trunc(m_BSwap(m_Value(X))))) { 863 unsigned C = X->getType()->getScalarSizeInBits() - 864 IIOperand->getType()->getScalarSizeInBits(); 865 Value *CV = ConstantInt::get(X->getType(), C); 866 Value *V = Builder.CreateLShr(X, CV); 867 return new TruncInst(V, IIOperand->getType()); 868 } 869 break; 870 } 871 case Intrinsic::masked_load: 872 if (Value *SimplifiedMaskedOp = simplifyMaskedLoad(*II)) 873 return replaceInstUsesWith(CI, SimplifiedMaskedOp); 874 break; 875 case Intrinsic::masked_store: 876 return simplifyMaskedStore(*II); 877 case Intrinsic::masked_gather: 878 return simplifyMaskedGather(*II); 879 case Intrinsic::masked_scatter: 880 return simplifyMaskedScatter(*II); 881 case Intrinsic::launder_invariant_group: 882 case Intrinsic::strip_invariant_group: 883 if (auto *SkippedBarrier = simplifyInvariantGroupIntrinsic(*II, *this)) 884 return replaceInstUsesWith(*II, SkippedBarrier); 885 break; 886 case Intrinsic::powi: 887 if (ConstantInt *Power = dyn_cast<ConstantInt>(II->getArgOperand(1))) { 888 // 0 and 1 are handled in instsimplify 889 890 // powi(x, -1) -> 1/x 891 if (Power->isMinusOne()) 892 return BinaryOperator::CreateFDiv(ConstantFP::get(CI.getType(), 1.0), 893 II->getArgOperand(0)); 894 // powi(x, 2) -> x*x 895 if (Power->equalsInt(2)) 896 return BinaryOperator::CreateFMul(II->getArgOperand(0), 897 II->getArgOperand(0)); 898 } 899 break; 900 901 case Intrinsic::cttz: 902 case Intrinsic::ctlz: 903 if (auto *I = foldCttzCtlz(*II, *this)) 904 return I; 905 break; 906 907 case Intrinsic::ctpop: 908 if (auto *I = foldCtpop(*II, *this)) 909 return I; 910 break; 911 912 case Intrinsic::fshl: 913 case Intrinsic::fshr: { 914 Value *Op0 = II->getArgOperand(0), *Op1 = II->getArgOperand(1); 915 Type *Ty = II->getType(); 916 unsigned BitWidth = Ty->getScalarSizeInBits(); 917 Constant *ShAmtC; 918 if (match(II->getArgOperand(2), m_ImmConstant(ShAmtC)) && 919 !ShAmtC->containsConstantExpression()) { 920 // Canonicalize a shift amount constant operand to modulo the bit-width. 921 Constant *WidthC = ConstantInt::get(Ty, BitWidth); 922 Constant *ModuloC = ConstantExpr::getURem(ShAmtC, WidthC); 923 if (ModuloC != ShAmtC) 924 return replaceOperand(*II, 2, ModuloC); 925 926 assert(ConstantExpr::getICmp(ICmpInst::ICMP_UGT, WidthC, ShAmtC) == 927 ConstantInt::getTrue(CmpInst::makeCmpResultType(Ty)) && 928 "Shift amount expected to be modulo bitwidth"); 929 930 // Canonicalize funnel shift right by constant to funnel shift left. This 931 // is not entirely arbitrary. For historical reasons, the backend may 932 // recognize rotate left patterns but miss rotate right patterns. 933 if (IID == Intrinsic::fshr) { 934 // fshr X, Y, C --> fshl X, Y, (BitWidth - C) 935 Constant *LeftShiftC = ConstantExpr::getSub(WidthC, ShAmtC); 936 Module *Mod = II->getModule(); 937 Function *Fshl = Intrinsic::getDeclaration(Mod, Intrinsic::fshl, Ty); 938 return CallInst::Create(Fshl, { Op0, Op1, LeftShiftC }); 939 } 940 assert(IID == Intrinsic::fshl && 941 "All funnel shifts by simple constants should go left"); 942 943 // fshl(X, 0, C) --> shl X, C 944 // fshl(X, undef, C) --> shl X, C 945 if (match(Op1, m_ZeroInt()) || match(Op1, m_Undef())) 946 return BinaryOperator::CreateShl(Op0, ShAmtC); 947 948 // fshl(0, X, C) --> lshr X, (BW-C) 949 // fshl(undef, X, C) --> lshr X, (BW-C) 950 if (match(Op0, m_ZeroInt()) || match(Op0, m_Undef())) 951 return BinaryOperator::CreateLShr(Op1, 952 ConstantExpr::getSub(WidthC, ShAmtC)); 953 954 // fshl i16 X, X, 8 --> bswap i16 X (reduce to more-specific form) 955 if (Op0 == Op1 && BitWidth == 16 && match(ShAmtC, m_SpecificInt(8))) { 956 Module *Mod = II->getModule(); 957 Function *Bswap = Intrinsic::getDeclaration(Mod, Intrinsic::bswap, Ty); 958 return CallInst::Create(Bswap, { Op0 }); 959 } 960 } 961 962 // Left or right might be masked. 963 if (SimplifyDemandedInstructionBits(*II)) 964 return &CI; 965 966 // The shift amount (operand 2) of a funnel shift is modulo the bitwidth, 967 // so only the low bits of the shift amount are demanded if the bitwidth is 968 // a power-of-2. 969 if (!isPowerOf2_32(BitWidth)) 970 break; 971 APInt Op2Demanded = APInt::getLowBitsSet(BitWidth, Log2_32_Ceil(BitWidth)); 972 KnownBits Op2Known(BitWidth); 973 if (SimplifyDemandedBits(II, 2, Op2Demanded, Op2Known)) 974 return &CI; 975 break; 976 } 977 case Intrinsic::uadd_with_overflow: 978 case Intrinsic::sadd_with_overflow: { 979 if (Instruction *I = foldIntrinsicWithOverflowCommon(II)) 980 return I; 981 982 // Given 2 constant operands whose sum does not overflow: 983 // uaddo (X +nuw C0), C1 -> uaddo X, C0 + C1 984 // saddo (X +nsw C0), C1 -> saddo X, C0 + C1 985 Value *X; 986 const APInt *C0, *C1; 987 Value *Arg0 = II->getArgOperand(0); 988 Value *Arg1 = II->getArgOperand(1); 989 bool IsSigned = IID == Intrinsic::sadd_with_overflow; 990 bool HasNWAdd = IsSigned ? match(Arg0, m_NSWAdd(m_Value(X), m_APInt(C0))) 991 : match(Arg0, m_NUWAdd(m_Value(X), m_APInt(C0))); 992 if (HasNWAdd && match(Arg1, m_APInt(C1))) { 993 bool Overflow; 994 APInt NewC = 995 IsSigned ? C1->sadd_ov(*C0, Overflow) : C1->uadd_ov(*C0, Overflow); 996 if (!Overflow) 997 return replaceInstUsesWith( 998 *II, Builder.CreateBinaryIntrinsic( 999 IID, X, ConstantInt::get(Arg1->getType(), NewC))); 1000 } 1001 break; 1002 } 1003 1004 case Intrinsic::umul_with_overflow: 1005 case Intrinsic::smul_with_overflow: 1006 case Intrinsic::usub_with_overflow: 1007 if (Instruction *I = foldIntrinsicWithOverflowCommon(II)) 1008 return I; 1009 break; 1010 1011 case Intrinsic::ssub_with_overflow: { 1012 if (Instruction *I = foldIntrinsicWithOverflowCommon(II)) 1013 return I; 1014 1015 Constant *C; 1016 Value *Arg0 = II->getArgOperand(0); 1017 Value *Arg1 = II->getArgOperand(1); 1018 // Given a constant C that is not the minimum signed value 1019 // for an integer of a given bit width: 1020 // 1021 // ssubo X, C -> saddo X, -C 1022 if (match(Arg1, m_Constant(C)) && C->isNotMinSignedValue()) { 1023 Value *NegVal = ConstantExpr::getNeg(C); 1024 // Build a saddo call that is equivalent to the discovered 1025 // ssubo call. 1026 return replaceInstUsesWith( 1027 *II, Builder.CreateBinaryIntrinsic(Intrinsic::sadd_with_overflow, 1028 Arg0, NegVal)); 1029 } 1030 1031 break; 1032 } 1033 1034 case Intrinsic::uadd_sat: 1035 case Intrinsic::sadd_sat: 1036 case Intrinsic::usub_sat: 1037 case Intrinsic::ssub_sat: { 1038 SaturatingInst *SI = cast<SaturatingInst>(II); 1039 Type *Ty = SI->getType(); 1040 Value *Arg0 = SI->getLHS(); 1041 Value *Arg1 = SI->getRHS(); 1042 1043 // Make use of known overflow information. 1044 OverflowResult OR = computeOverflow(SI->getBinaryOp(), SI->isSigned(), 1045 Arg0, Arg1, SI); 1046 switch (OR) { 1047 case OverflowResult::MayOverflow: 1048 break; 1049 case OverflowResult::NeverOverflows: 1050 if (SI->isSigned()) 1051 return BinaryOperator::CreateNSW(SI->getBinaryOp(), Arg0, Arg1); 1052 else 1053 return BinaryOperator::CreateNUW(SI->getBinaryOp(), Arg0, Arg1); 1054 case OverflowResult::AlwaysOverflowsLow: { 1055 unsigned BitWidth = Ty->getScalarSizeInBits(); 1056 APInt Min = APSInt::getMinValue(BitWidth, !SI->isSigned()); 1057 return replaceInstUsesWith(*SI, ConstantInt::get(Ty, Min)); 1058 } 1059 case OverflowResult::AlwaysOverflowsHigh: { 1060 unsigned BitWidth = Ty->getScalarSizeInBits(); 1061 APInt Max = APSInt::getMaxValue(BitWidth, !SI->isSigned()); 1062 return replaceInstUsesWith(*SI, ConstantInt::get(Ty, Max)); 1063 } 1064 } 1065 1066 // ssub.sat(X, C) -> sadd.sat(X, -C) if C != MIN 1067 Constant *C; 1068 if (IID == Intrinsic::ssub_sat && match(Arg1, m_Constant(C)) && 1069 C->isNotMinSignedValue()) { 1070 Value *NegVal = ConstantExpr::getNeg(C); 1071 return replaceInstUsesWith( 1072 *II, Builder.CreateBinaryIntrinsic( 1073 Intrinsic::sadd_sat, Arg0, NegVal)); 1074 } 1075 1076 // sat(sat(X + Val2) + Val) -> sat(X + (Val+Val2)) 1077 // sat(sat(X - Val2) - Val) -> sat(X - (Val+Val2)) 1078 // if Val and Val2 have the same sign 1079 if (auto *Other = dyn_cast<IntrinsicInst>(Arg0)) { 1080 Value *X; 1081 const APInt *Val, *Val2; 1082 APInt NewVal; 1083 bool IsUnsigned = 1084 IID == Intrinsic::uadd_sat || IID == Intrinsic::usub_sat; 1085 if (Other->getIntrinsicID() == IID && 1086 match(Arg1, m_APInt(Val)) && 1087 match(Other->getArgOperand(0), m_Value(X)) && 1088 match(Other->getArgOperand(1), m_APInt(Val2))) { 1089 if (IsUnsigned) 1090 NewVal = Val->uadd_sat(*Val2); 1091 else if (Val->isNonNegative() == Val2->isNonNegative()) { 1092 bool Overflow; 1093 NewVal = Val->sadd_ov(*Val2, Overflow); 1094 if (Overflow) { 1095 // Both adds together may add more than SignedMaxValue 1096 // without saturating the final result. 1097 break; 1098 } 1099 } else { 1100 // Cannot fold saturated addition with different signs. 1101 break; 1102 } 1103 1104 return replaceInstUsesWith( 1105 *II, Builder.CreateBinaryIntrinsic( 1106 IID, X, ConstantInt::get(II->getType(), NewVal))); 1107 } 1108 } 1109 break; 1110 } 1111 1112 case Intrinsic::minnum: 1113 case Intrinsic::maxnum: 1114 case Intrinsic::minimum: 1115 case Intrinsic::maximum: { 1116 Value *Arg0 = II->getArgOperand(0); 1117 Value *Arg1 = II->getArgOperand(1); 1118 Value *X, *Y; 1119 if (match(Arg0, m_FNeg(m_Value(X))) && match(Arg1, m_FNeg(m_Value(Y))) && 1120 (Arg0->hasOneUse() || Arg1->hasOneUse())) { 1121 // If both operands are negated, invert the call and negate the result: 1122 // min(-X, -Y) --> -(max(X, Y)) 1123 // max(-X, -Y) --> -(min(X, Y)) 1124 Intrinsic::ID NewIID; 1125 switch (IID) { 1126 case Intrinsic::maxnum: 1127 NewIID = Intrinsic::minnum; 1128 break; 1129 case Intrinsic::minnum: 1130 NewIID = Intrinsic::maxnum; 1131 break; 1132 case Intrinsic::maximum: 1133 NewIID = Intrinsic::minimum; 1134 break; 1135 case Intrinsic::minimum: 1136 NewIID = Intrinsic::maximum; 1137 break; 1138 default: 1139 llvm_unreachable("unexpected intrinsic ID"); 1140 } 1141 Value *NewCall = Builder.CreateBinaryIntrinsic(NewIID, X, Y, II); 1142 Instruction *FNeg = UnaryOperator::CreateFNeg(NewCall); 1143 FNeg->copyIRFlags(II); 1144 return FNeg; 1145 } 1146 1147 // m(m(X, C2), C1) -> m(X, C) 1148 const APFloat *C1, *C2; 1149 if (auto *M = dyn_cast<IntrinsicInst>(Arg0)) { 1150 if (M->getIntrinsicID() == IID && match(Arg1, m_APFloat(C1)) && 1151 ((match(M->getArgOperand(0), m_Value(X)) && 1152 match(M->getArgOperand(1), m_APFloat(C2))) || 1153 (match(M->getArgOperand(1), m_Value(X)) && 1154 match(M->getArgOperand(0), m_APFloat(C2))))) { 1155 APFloat Res(0.0); 1156 switch (IID) { 1157 case Intrinsic::maxnum: 1158 Res = maxnum(*C1, *C2); 1159 break; 1160 case Intrinsic::minnum: 1161 Res = minnum(*C1, *C2); 1162 break; 1163 case Intrinsic::maximum: 1164 Res = maximum(*C1, *C2); 1165 break; 1166 case Intrinsic::minimum: 1167 Res = minimum(*C1, *C2); 1168 break; 1169 default: 1170 llvm_unreachable("unexpected intrinsic ID"); 1171 } 1172 Instruction *NewCall = Builder.CreateBinaryIntrinsic( 1173 IID, X, ConstantFP::get(Arg0->getType(), Res), II); 1174 // TODO: Conservatively intersecting FMF. If Res == C2, the transform 1175 // was a simplification (so Arg0 and its original flags could 1176 // propagate?) 1177 NewCall->andIRFlags(M); 1178 return replaceInstUsesWith(*II, NewCall); 1179 } 1180 } 1181 1182 Value *ExtSrc0; 1183 Value *ExtSrc1; 1184 1185 // minnum (fpext x), (fpext y) -> minnum x, y 1186 // maxnum (fpext x), (fpext y) -> maxnum x, y 1187 if (match(II->getArgOperand(0), m_OneUse(m_FPExt(m_Value(ExtSrc0)))) && 1188 match(II->getArgOperand(1), m_OneUse(m_FPExt(m_Value(ExtSrc1)))) && 1189 ExtSrc0->getType() == ExtSrc1->getType()) { 1190 Function *F = Intrinsic::getDeclaration( 1191 II->getModule(), II->getIntrinsicID(), {ExtSrc0->getType()}); 1192 CallInst *NewCall = Builder.CreateCall(F, { ExtSrc0, ExtSrc1 }); 1193 NewCall->copyFastMathFlags(II); 1194 NewCall->takeName(II); 1195 return new FPExtInst(NewCall, II->getType()); 1196 } 1197 1198 break; 1199 } 1200 case Intrinsic::fmuladd: { 1201 // Canonicalize fast fmuladd to the separate fmul + fadd. 1202 if (II->isFast()) { 1203 BuilderTy::FastMathFlagGuard Guard(Builder); 1204 Builder.setFastMathFlags(II->getFastMathFlags()); 1205 Value *Mul = Builder.CreateFMul(II->getArgOperand(0), 1206 II->getArgOperand(1)); 1207 Value *Add = Builder.CreateFAdd(Mul, II->getArgOperand(2)); 1208 Add->takeName(II); 1209 return replaceInstUsesWith(*II, Add); 1210 } 1211 1212 // Try to simplify the underlying FMul. 1213 if (Value *V = SimplifyFMulInst(II->getArgOperand(0), II->getArgOperand(1), 1214 II->getFastMathFlags(), 1215 SQ.getWithInstruction(II))) { 1216 auto *FAdd = BinaryOperator::CreateFAdd(V, II->getArgOperand(2)); 1217 FAdd->copyFastMathFlags(II); 1218 return FAdd; 1219 } 1220 1221 LLVM_FALLTHROUGH; 1222 } 1223 case Intrinsic::fma: { 1224 // fma fneg(x), fneg(y), z -> fma x, y, z 1225 Value *Src0 = II->getArgOperand(0); 1226 Value *Src1 = II->getArgOperand(1); 1227 Value *X, *Y; 1228 if (match(Src0, m_FNeg(m_Value(X))) && match(Src1, m_FNeg(m_Value(Y)))) { 1229 replaceOperand(*II, 0, X); 1230 replaceOperand(*II, 1, Y); 1231 return II; 1232 } 1233 1234 // fma fabs(x), fabs(x), z -> fma x, x, z 1235 if (match(Src0, m_FAbs(m_Value(X))) && 1236 match(Src1, m_FAbs(m_Specific(X)))) { 1237 replaceOperand(*II, 0, X); 1238 replaceOperand(*II, 1, X); 1239 return II; 1240 } 1241 1242 // Try to simplify the underlying FMul. We can only apply simplifications 1243 // that do not require rounding. 1244 if (Value *V = SimplifyFMAFMul(II->getArgOperand(0), II->getArgOperand(1), 1245 II->getFastMathFlags(), 1246 SQ.getWithInstruction(II))) { 1247 auto *FAdd = BinaryOperator::CreateFAdd(V, II->getArgOperand(2)); 1248 FAdd->copyFastMathFlags(II); 1249 return FAdd; 1250 } 1251 1252 // fma x, y, 0 -> fmul x, y 1253 // This is always valid for -0.0, but requires nsz for +0.0 as 1254 // -0.0 + 0.0 = 0.0, which would not be the same as the fmul on its own. 1255 if (match(II->getArgOperand(2), m_NegZeroFP()) || 1256 (match(II->getArgOperand(2), m_PosZeroFP()) && 1257 II->getFastMathFlags().noSignedZeros())) 1258 return BinaryOperator::CreateFMulFMF(Src0, Src1, II); 1259 1260 break; 1261 } 1262 case Intrinsic::copysign: { 1263 Value *Mag = II->getArgOperand(0), *Sign = II->getArgOperand(1); 1264 if (SignBitMustBeZero(Sign, &TLI)) { 1265 // If we know that the sign argument is positive, reduce to FABS: 1266 // copysign Mag, +Sign --> fabs Mag 1267 Value *Fabs = Builder.CreateUnaryIntrinsic(Intrinsic::fabs, Mag, II); 1268 return replaceInstUsesWith(*II, Fabs); 1269 } 1270 // TODO: There should be a ValueTracking sibling like SignBitMustBeOne. 1271 const APFloat *C; 1272 if (match(Sign, m_APFloat(C)) && C->isNegative()) { 1273 // If we know that the sign argument is negative, reduce to FNABS: 1274 // copysign Mag, -Sign --> fneg (fabs Mag) 1275 Value *Fabs = Builder.CreateUnaryIntrinsic(Intrinsic::fabs, Mag, II); 1276 return replaceInstUsesWith(*II, Builder.CreateFNegFMF(Fabs, II)); 1277 } 1278 1279 // Propagate sign argument through nested calls: 1280 // copysign Mag, (copysign ?, X) --> copysign Mag, X 1281 Value *X; 1282 if (match(Sign, m_Intrinsic<Intrinsic::copysign>(m_Value(), m_Value(X)))) 1283 return replaceOperand(*II, 1, X); 1284 1285 // Peek through changes of magnitude's sign-bit. This call rewrites those: 1286 // copysign (fabs X), Sign --> copysign X, Sign 1287 // copysign (fneg X), Sign --> copysign X, Sign 1288 if (match(Mag, m_FAbs(m_Value(X))) || match(Mag, m_FNeg(m_Value(X)))) 1289 return replaceOperand(*II, 0, X); 1290 1291 break; 1292 } 1293 case Intrinsic::fabs: { 1294 Value *Cond, *TVal, *FVal; 1295 if (match(II->getArgOperand(0), 1296 m_Select(m_Value(Cond), m_Value(TVal), m_Value(FVal)))) { 1297 // fabs (select Cond, TrueC, FalseC) --> select Cond, AbsT, AbsF 1298 if (isa<Constant>(TVal) && isa<Constant>(FVal)) { 1299 CallInst *AbsT = Builder.CreateCall(II->getCalledFunction(), {TVal}); 1300 CallInst *AbsF = Builder.CreateCall(II->getCalledFunction(), {FVal}); 1301 return SelectInst::Create(Cond, AbsT, AbsF); 1302 } 1303 // fabs (select Cond, -FVal, FVal) --> fabs FVal 1304 if (match(TVal, m_FNeg(m_Specific(FVal)))) 1305 return replaceOperand(*II, 0, FVal); 1306 // fabs (select Cond, TVal, -TVal) --> fabs TVal 1307 if (match(FVal, m_FNeg(m_Specific(TVal)))) 1308 return replaceOperand(*II, 0, TVal); 1309 } 1310 1311 LLVM_FALLTHROUGH; 1312 } 1313 case Intrinsic::ceil: 1314 case Intrinsic::floor: 1315 case Intrinsic::round: 1316 case Intrinsic::roundeven: 1317 case Intrinsic::nearbyint: 1318 case Intrinsic::rint: 1319 case Intrinsic::trunc: { 1320 Value *ExtSrc; 1321 if (match(II->getArgOperand(0), m_OneUse(m_FPExt(m_Value(ExtSrc))))) { 1322 // Narrow the call: intrinsic (fpext x) -> fpext (intrinsic x) 1323 Value *NarrowII = Builder.CreateUnaryIntrinsic(IID, ExtSrc, II); 1324 return new FPExtInst(NarrowII, II->getType()); 1325 } 1326 break; 1327 } 1328 case Intrinsic::cos: 1329 case Intrinsic::amdgcn_cos: { 1330 Value *X; 1331 Value *Src = II->getArgOperand(0); 1332 if (match(Src, m_FNeg(m_Value(X))) || match(Src, m_FAbs(m_Value(X)))) { 1333 // cos(-x) -> cos(x) 1334 // cos(fabs(x)) -> cos(x) 1335 return replaceOperand(*II, 0, X); 1336 } 1337 break; 1338 } 1339 case Intrinsic::sin: { 1340 Value *X; 1341 if (match(II->getArgOperand(0), m_OneUse(m_FNeg(m_Value(X))))) { 1342 // sin(-x) --> -sin(x) 1343 Value *NewSin = Builder.CreateUnaryIntrinsic(Intrinsic::sin, X, II); 1344 Instruction *FNeg = UnaryOperator::CreateFNeg(NewSin); 1345 FNeg->copyFastMathFlags(II); 1346 return FNeg; 1347 } 1348 break; 1349 } 1350 1351 case Intrinsic::arm_neon_vtbl1: 1352 case Intrinsic::aarch64_neon_tbl1: 1353 if (Value *V = simplifyNeonTbl1(*II, Builder)) 1354 return replaceInstUsesWith(*II, V); 1355 break; 1356 1357 case Intrinsic::arm_neon_vmulls: 1358 case Intrinsic::arm_neon_vmullu: 1359 case Intrinsic::aarch64_neon_smull: 1360 case Intrinsic::aarch64_neon_umull: { 1361 Value *Arg0 = II->getArgOperand(0); 1362 Value *Arg1 = II->getArgOperand(1); 1363 1364 // Handle mul by zero first: 1365 if (isa<ConstantAggregateZero>(Arg0) || isa<ConstantAggregateZero>(Arg1)) { 1366 return replaceInstUsesWith(CI, ConstantAggregateZero::get(II->getType())); 1367 } 1368 1369 // Check for constant LHS & RHS - in this case we just simplify. 1370 bool Zext = (IID == Intrinsic::arm_neon_vmullu || 1371 IID == Intrinsic::aarch64_neon_umull); 1372 VectorType *NewVT = cast<VectorType>(II->getType()); 1373 if (Constant *CV0 = dyn_cast<Constant>(Arg0)) { 1374 if (Constant *CV1 = dyn_cast<Constant>(Arg1)) { 1375 CV0 = ConstantExpr::getIntegerCast(CV0, NewVT, /*isSigned=*/!Zext); 1376 CV1 = ConstantExpr::getIntegerCast(CV1, NewVT, /*isSigned=*/!Zext); 1377 1378 return replaceInstUsesWith(CI, ConstantExpr::getMul(CV0, CV1)); 1379 } 1380 1381 // Couldn't simplify - canonicalize constant to the RHS. 1382 std::swap(Arg0, Arg1); 1383 } 1384 1385 // Handle mul by one: 1386 if (Constant *CV1 = dyn_cast<Constant>(Arg1)) 1387 if (ConstantInt *Splat = 1388 dyn_cast_or_null<ConstantInt>(CV1->getSplatValue())) 1389 if (Splat->isOne()) 1390 return CastInst::CreateIntegerCast(Arg0, II->getType(), 1391 /*isSigned=*/!Zext); 1392 1393 break; 1394 } 1395 case Intrinsic::arm_neon_aesd: 1396 case Intrinsic::arm_neon_aese: 1397 case Intrinsic::aarch64_crypto_aesd: 1398 case Intrinsic::aarch64_crypto_aese: { 1399 Value *DataArg = II->getArgOperand(0); 1400 Value *KeyArg = II->getArgOperand(1); 1401 1402 // Try to use the builtin XOR in AESE and AESD to eliminate a prior XOR 1403 Value *Data, *Key; 1404 if (match(KeyArg, m_ZeroInt()) && 1405 match(DataArg, m_Xor(m_Value(Data), m_Value(Key)))) { 1406 replaceOperand(*II, 0, Data); 1407 replaceOperand(*II, 1, Key); 1408 return II; 1409 } 1410 break; 1411 } 1412 case Intrinsic::hexagon_V6_vandvrt: 1413 case Intrinsic::hexagon_V6_vandvrt_128B: { 1414 // Simplify Q -> V -> Q conversion. 1415 if (auto Op0 = dyn_cast<IntrinsicInst>(II->getArgOperand(0))) { 1416 Intrinsic::ID ID0 = Op0->getIntrinsicID(); 1417 if (ID0 != Intrinsic::hexagon_V6_vandqrt && 1418 ID0 != Intrinsic::hexagon_V6_vandqrt_128B) 1419 break; 1420 Value *Bytes = Op0->getArgOperand(1), *Mask = II->getArgOperand(1); 1421 uint64_t Bytes1 = computeKnownBits(Bytes, 0, Op0).One.getZExtValue(); 1422 uint64_t Mask1 = computeKnownBits(Mask, 0, II).One.getZExtValue(); 1423 // Check if every byte has common bits in Bytes and Mask. 1424 uint64_t C = Bytes1 & Mask1; 1425 if ((C & 0xFF) && (C & 0xFF00) && (C & 0xFF0000) && (C & 0xFF000000)) 1426 return replaceInstUsesWith(*II, Op0->getArgOperand(0)); 1427 } 1428 break; 1429 } 1430 case Intrinsic::stackrestore: { 1431 // If the save is right next to the restore, remove the restore. This can 1432 // happen when variable allocas are DCE'd. 1433 if (IntrinsicInst *SS = dyn_cast<IntrinsicInst>(II->getArgOperand(0))) { 1434 if (SS->getIntrinsicID() == Intrinsic::stacksave) { 1435 // Skip over debug info. 1436 if (SS->getNextNonDebugInstruction() == II) { 1437 return eraseInstFromFunction(CI); 1438 } 1439 } 1440 } 1441 1442 // Scan down this block to see if there is another stack restore in the 1443 // same block without an intervening call/alloca. 1444 BasicBlock::iterator BI(II); 1445 Instruction *TI = II->getParent()->getTerminator(); 1446 bool CannotRemove = false; 1447 for (++BI; &*BI != TI; ++BI) { 1448 if (isa<AllocaInst>(BI)) { 1449 CannotRemove = true; 1450 break; 1451 } 1452 if (CallInst *BCI = dyn_cast<CallInst>(BI)) { 1453 if (auto *II2 = dyn_cast<IntrinsicInst>(BCI)) { 1454 // If there is a stackrestore below this one, remove this one. 1455 if (II2->getIntrinsicID() == Intrinsic::stackrestore) 1456 return eraseInstFromFunction(CI); 1457 1458 // Bail if we cross over an intrinsic with side effects, such as 1459 // llvm.stacksave, or llvm.read_register. 1460 if (II2->mayHaveSideEffects()) { 1461 CannotRemove = true; 1462 break; 1463 } 1464 } else { 1465 // If we found a non-intrinsic call, we can't remove the stack 1466 // restore. 1467 CannotRemove = true; 1468 break; 1469 } 1470 } 1471 } 1472 1473 // If the stack restore is in a return, resume, or unwind block and if there 1474 // are no allocas or calls between the restore and the return, nuke the 1475 // restore. 1476 if (!CannotRemove && (isa<ReturnInst>(TI) || isa<ResumeInst>(TI))) 1477 return eraseInstFromFunction(CI); 1478 break; 1479 } 1480 case Intrinsic::lifetime_end: 1481 // Asan needs to poison memory to detect invalid access which is possible 1482 // even for empty lifetime range. 1483 if (II->getFunction()->hasFnAttribute(Attribute::SanitizeAddress) || 1484 II->getFunction()->hasFnAttribute(Attribute::SanitizeMemory) || 1485 II->getFunction()->hasFnAttribute(Attribute::SanitizeHWAddress)) 1486 break; 1487 1488 if (removeTriviallyEmptyRange(*II, *this, [](const IntrinsicInst &I) { 1489 return I.getIntrinsicID() == Intrinsic::lifetime_start; 1490 })) 1491 return nullptr; 1492 break; 1493 case Intrinsic::assume: { 1494 Value *IIOperand = II->getArgOperand(0); 1495 SmallVector<OperandBundleDef, 4> OpBundles; 1496 II->getOperandBundlesAsDefs(OpBundles); 1497 bool HasOpBundles = !OpBundles.empty(); 1498 // Remove an assume if it is followed by an identical assume. 1499 // TODO: Do we need this? Unless there are conflicting assumptions, the 1500 // computeKnownBits(IIOperand) below here eliminates redundant assumes. 1501 Instruction *Next = II->getNextNonDebugInstruction(); 1502 if (HasOpBundles && 1503 match(Next, m_Intrinsic<Intrinsic::assume>(m_Specific(IIOperand))) && 1504 !cast<IntrinsicInst>(Next)->hasOperandBundles()) 1505 return eraseInstFromFunction(CI); 1506 1507 // Canonicalize assume(a && b) -> assume(a); assume(b); 1508 // Note: New assumption intrinsics created here are registered by 1509 // the InstCombineIRInserter object. 1510 FunctionType *AssumeIntrinsicTy = II->getFunctionType(); 1511 Value *AssumeIntrinsic = II->getCalledOperand(); 1512 Value *A, *B; 1513 if (match(IIOperand, m_LogicalAnd(m_Value(A), m_Value(B)))) { 1514 Builder.CreateCall(AssumeIntrinsicTy, AssumeIntrinsic, A, OpBundles, 1515 II->getName()); 1516 Builder.CreateCall(AssumeIntrinsicTy, AssumeIntrinsic, B, II->getName()); 1517 return eraseInstFromFunction(*II); 1518 } 1519 // assume(!(a || b)) -> assume(!a); assume(!b); 1520 if (match(IIOperand, m_Not(m_LogicalOr(m_Value(A), m_Value(B))))) { 1521 Builder.CreateCall(AssumeIntrinsicTy, AssumeIntrinsic, 1522 Builder.CreateNot(A), OpBundles, II->getName()); 1523 Builder.CreateCall(AssumeIntrinsicTy, AssumeIntrinsic, 1524 Builder.CreateNot(B), II->getName()); 1525 return eraseInstFromFunction(*II); 1526 } 1527 1528 // assume( (load addr) != null ) -> add 'nonnull' metadata to load 1529 // (if assume is valid at the load) 1530 CmpInst::Predicate Pred; 1531 Instruction *LHS; 1532 if (match(IIOperand, m_ICmp(Pred, m_Instruction(LHS), m_Zero())) && 1533 Pred == ICmpInst::ICMP_NE && LHS->getOpcode() == Instruction::Load && 1534 LHS->getType()->isPointerTy() && 1535 isValidAssumeForContext(II, LHS, &DT)) { 1536 MDNode *MD = MDNode::get(II->getContext(), None); 1537 LHS->setMetadata(LLVMContext::MD_nonnull, MD); 1538 if (!HasOpBundles) 1539 return eraseInstFromFunction(*II); 1540 1541 // TODO: apply nonnull return attributes to calls and invokes 1542 // TODO: apply range metadata for range check patterns? 1543 } 1544 1545 // If there is a dominating assume with the same condition as this one, 1546 // then this one is redundant, and should be removed. 1547 KnownBits Known(1); 1548 computeKnownBits(IIOperand, Known, 0, II); 1549 if (Known.isAllOnes() && isAssumeWithEmptyBundle(*II)) 1550 return eraseInstFromFunction(*II); 1551 1552 // Update the cache of affected values for this assumption (we might be 1553 // here because we just simplified the condition). 1554 AC.updateAffectedValues(II); 1555 break; 1556 } 1557 case Intrinsic::experimental_gc_statepoint: { 1558 GCStatepointInst &GCSP = *cast<GCStatepointInst>(II); 1559 SmallPtrSet<Value *, 32> LiveGcValues; 1560 for (const GCRelocateInst *Reloc : GCSP.getGCRelocates()) { 1561 GCRelocateInst &GCR = *const_cast<GCRelocateInst *>(Reloc); 1562 1563 // Remove the relocation if unused. 1564 if (GCR.use_empty()) { 1565 eraseInstFromFunction(GCR); 1566 continue; 1567 } 1568 1569 Value *DerivedPtr = GCR.getDerivedPtr(); 1570 Value *BasePtr = GCR.getBasePtr(); 1571 1572 // Undef is undef, even after relocation. 1573 if (isa<UndefValue>(DerivedPtr) || isa<UndefValue>(BasePtr)) { 1574 replaceInstUsesWith(GCR, UndefValue::get(GCR.getType())); 1575 eraseInstFromFunction(GCR); 1576 continue; 1577 } 1578 1579 if (auto *PT = dyn_cast<PointerType>(GCR.getType())) { 1580 // The relocation of null will be null for most any collector. 1581 // TODO: provide a hook for this in GCStrategy. There might be some 1582 // weird collector this property does not hold for. 1583 if (isa<ConstantPointerNull>(DerivedPtr)) { 1584 // Use null-pointer of gc_relocate's type to replace it. 1585 replaceInstUsesWith(GCR, ConstantPointerNull::get(PT)); 1586 eraseInstFromFunction(GCR); 1587 continue; 1588 } 1589 1590 // isKnownNonNull -> nonnull attribute 1591 if (!GCR.hasRetAttr(Attribute::NonNull) && 1592 isKnownNonZero(DerivedPtr, DL, 0, &AC, II, &DT)) { 1593 GCR.addAttribute(AttributeList::ReturnIndex, Attribute::NonNull); 1594 // We discovered new fact, re-check users. 1595 Worklist.pushUsersToWorkList(GCR); 1596 } 1597 } 1598 1599 // If we have two copies of the same pointer in the statepoint argument 1600 // list, canonicalize to one. This may let us common gc.relocates. 1601 if (GCR.getBasePtr() == GCR.getDerivedPtr() && 1602 GCR.getBasePtrIndex() != GCR.getDerivedPtrIndex()) { 1603 auto *OpIntTy = GCR.getOperand(2)->getType(); 1604 GCR.setOperand(2, ConstantInt::get(OpIntTy, GCR.getBasePtrIndex())); 1605 } 1606 1607 // TODO: bitcast(relocate(p)) -> relocate(bitcast(p)) 1608 // Canonicalize on the type from the uses to the defs 1609 1610 // TODO: relocate((gep p, C, C2, ...)) -> gep(relocate(p), C, C2, ...) 1611 LiveGcValues.insert(BasePtr); 1612 LiveGcValues.insert(DerivedPtr); 1613 } 1614 Optional<OperandBundleUse> Bundle = 1615 GCSP.getOperandBundle(LLVMContext::OB_gc_live); 1616 unsigned NumOfGCLives = LiveGcValues.size(); 1617 if (!Bundle.hasValue() || NumOfGCLives == Bundle->Inputs.size()) 1618 break; 1619 // We can reduce the size of gc live bundle. 1620 DenseMap<Value *, unsigned> Val2Idx; 1621 std::vector<Value *> NewLiveGc; 1622 for (unsigned I = 0, E = Bundle->Inputs.size(); I < E; ++I) { 1623 Value *V = Bundle->Inputs[I]; 1624 if (Val2Idx.count(V)) 1625 continue; 1626 if (LiveGcValues.count(V)) { 1627 Val2Idx[V] = NewLiveGc.size(); 1628 NewLiveGc.push_back(V); 1629 } else 1630 Val2Idx[V] = NumOfGCLives; 1631 } 1632 // Update all gc.relocates 1633 for (const GCRelocateInst *Reloc : GCSP.getGCRelocates()) { 1634 GCRelocateInst &GCR = *const_cast<GCRelocateInst *>(Reloc); 1635 Value *BasePtr = GCR.getBasePtr(); 1636 assert(Val2Idx.count(BasePtr) && Val2Idx[BasePtr] != NumOfGCLives && 1637 "Missed live gc for base pointer"); 1638 auto *OpIntTy1 = GCR.getOperand(1)->getType(); 1639 GCR.setOperand(1, ConstantInt::get(OpIntTy1, Val2Idx[BasePtr])); 1640 Value *DerivedPtr = GCR.getDerivedPtr(); 1641 assert(Val2Idx.count(DerivedPtr) && Val2Idx[DerivedPtr] != NumOfGCLives && 1642 "Missed live gc for derived pointer"); 1643 auto *OpIntTy2 = GCR.getOperand(2)->getType(); 1644 GCR.setOperand(2, ConstantInt::get(OpIntTy2, Val2Idx[DerivedPtr])); 1645 } 1646 // Create new statepoint instruction. 1647 OperandBundleDef NewBundle("gc-live", NewLiveGc); 1648 if (isa<CallInst>(II)) 1649 return CallInst::CreateWithReplacedBundle(cast<CallInst>(II), NewBundle); 1650 else 1651 return InvokeInst::CreateWithReplacedBundle(cast<InvokeInst>(II), 1652 NewBundle); 1653 break; 1654 } 1655 case Intrinsic::experimental_guard: { 1656 // Is this guard followed by another guard? We scan forward over a small 1657 // fixed window of instructions to handle common cases with conditions 1658 // computed between guards. 1659 Instruction *NextInst = II->getNextNonDebugInstruction(); 1660 for (unsigned i = 0; i < GuardWideningWindow; i++) { 1661 // Note: Using context-free form to avoid compile time blow up 1662 if (!isSafeToSpeculativelyExecute(NextInst)) 1663 break; 1664 NextInst = NextInst->getNextNonDebugInstruction(); 1665 } 1666 Value *NextCond = nullptr; 1667 if (match(NextInst, 1668 m_Intrinsic<Intrinsic::experimental_guard>(m_Value(NextCond)))) { 1669 Value *CurrCond = II->getArgOperand(0); 1670 1671 // Remove a guard that it is immediately preceded by an identical guard. 1672 // Otherwise canonicalize guard(a); guard(b) -> guard(a & b). 1673 if (CurrCond != NextCond) { 1674 Instruction *MoveI = II->getNextNonDebugInstruction(); 1675 while (MoveI != NextInst) { 1676 auto *Temp = MoveI; 1677 MoveI = MoveI->getNextNonDebugInstruction(); 1678 Temp->moveBefore(II); 1679 } 1680 replaceOperand(*II, 0, Builder.CreateAnd(CurrCond, NextCond)); 1681 } 1682 eraseInstFromFunction(*NextInst); 1683 return II; 1684 } 1685 break; 1686 } 1687 case Intrinsic::experimental_vector_insert: { 1688 Value *Vec = II->getArgOperand(0); 1689 Value *SubVec = II->getArgOperand(1); 1690 Value *Idx = II->getArgOperand(2); 1691 auto *DstTy = dyn_cast<FixedVectorType>(II->getType()); 1692 auto *VecTy = dyn_cast<FixedVectorType>(Vec->getType()); 1693 auto *SubVecTy = dyn_cast<FixedVectorType>(SubVec->getType()); 1694 1695 // Only canonicalize if the destination vector, Vec, and SubVec are all 1696 // fixed vectors. 1697 if (DstTy && VecTy && SubVecTy) { 1698 unsigned DstNumElts = DstTy->getNumElements(); 1699 unsigned VecNumElts = VecTy->getNumElements(); 1700 unsigned SubVecNumElts = SubVecTy->getNumElements(); 1701 unsigned IdxN = cast<ConstantInt>(Idx)->getZExtValue(); 1702 1703 // The result of this call is undefined if IdxN is not a constant multiple 1704 // of the SubVec's minimum vector length OR the insertion overruns Vec. 1705 if (IdxN % SubVecNumElts != 0 || IdxN + SubVecNumElts > VecNumElts) { 1706 replaceInstUsesWith(CI, UndefValue::get(CI.getType())); 1707 return eraseInstFromFunction(CI); 1708 } 1709 1710 // An insert that entirely overwrites Vec with SubVec is a nop. 1711 if (VecNumElts == SubVecNumElts) { 1712 replaceInstUsesWith(CI, SubVec); 1713 return eraseInstFromFunction(CI); 1714 } 1715 1716 // Widen SubVec into a vector of the same width as Vec, since 1717 // shufflevector requires the two input vectors to be the same width. 1718 // Elements beyond the bounds of SubVec within the widened vector are 1719 // undefined. 1720 SmallVector<int, 8> WidenMask; 1721 unsigned i; 1722 for (i = 0; i != SubVecNumElts; ++i) 1723 WidenMask.push_back(i); 1724 for (; i != VecNumElts; ++i) 1725 WidenMask.push_back(UndefMaskElem); 1726 1727 Value *WidenShuffle = Builder.CreateShuffleVector(SubVec, WidenMask); 1728 1729 SmallVector<int, 8> Mask; 1730 for (unsigned i = 0; i != IdxN; ++i) 1731 Mask.push_back(i); 1732 for (unsigned i = DstNumElts; i != DstNumElts + SubVecNumElts; ++i) 1733 Mask.push_back(i); 1734 for (unsigned i = IdxN + SubVecNumElts; i != DstNumElts; ++i) 1735 Mask.push_back(i); 1736 1737 Value *Shuffle = Builder.CreateShuffleVector(Vec, WidenShuffle, Mask); 1738 replaceInstUsesWith(CI, Shuffle); 1739 return eraseInstFromFunction(CI); 1740 } 1741 break; 1742 } 1743 case Intrinsic::experimental_vector_extract: { 1744 Value *Vec = II->getArgOperand(0); 1745 Value *Idx = II->getArgOperand(1); 1746 1747 auto *DstTy = dyn_cast<FixedVectorType>(II->getType()); 1748 auto *VecTy = dyn_cast<FixedVectorType>(Vec->getType()); 1749 1750 // Only canonicalize if the the destination vector and Vec are fixed 1751 // vectors. 1752 if (DstTy && VecTy) { 1753 unsigned DstNumElts = DstTy->getNumElements(); 1754 unsigned VecNumElts = VecTy->getNumElements(); 1755 unsigned IdxN = cast<ConstantInt>(Idx)->getZExtValue(); 1756 1757 // The result of this call is undefined if IdxN is not a constant multiple 1758 // of the result type's minimum vector length OR the extraction overruns 1759 // Vec. 1760 if (IdxN % DstNumElts != 0 || IdxN + DstNumElts > VecNumElts) { 1761 replaceInstUsesWith(CI, UndefValue::get(CI.getType())); 1762 return eraseInstFromFunction(CI); 1763 } 1764 1765 // Extracting the entirety of Vec is a nop. 1766 if (VecNumElts == DstNumElts) { 1767 replaceInstUsesWith(CI, Vec); 1768 return eraseInstFromFunction(CI); 1769 } 1770 1771 SmallVector<int, 8> Mask; 1772 for (unsigned i = 0; i != DstNumElts; ++i) 1773 Mask.push_back(IdxN + i); 1774 1775 Value *Shuffle = 1776 Builder.CreateShuffleVector(Vec, UndefValue::get(VecTy), Mask); 1777 replaceInstUsesWith(CI, Shuffle); 1778 return eraseInstFromFunction(CI); 1779 } 1780 break; 1781 } 1782 default: { 1783 // Handle target specific intrinsics 1784 Optional<Instruction *> V = targetInstCombineIntrinsic(*II); 1785 if (V.hasValue()) 1786 return V.getValue(); 1787 break; 1788 } 1789 } 1790 return visitCallBase(*II); 1791 } 1792 1793 // Fence instruction simplification 1794 Instruction *InstCombinerImpl::visitFenceInst(FenceInst &FI) { 1795 // Remove identical consecutive fences. 1796 Instruction *Next = FI.getNextNonDebugInstruction(); 1797 if (auto *NFI = dyn_cast<FenceInst>(Next)) 1798 if (FI.isIdenticalTo(NFI)) 1799 return eraseInstFromFunction(FI); 1800 return nullptr; 1801 } 1802 1803 // InvokeInst simplification 1804 Instruction *InstCombinerImpl::visitInvokeInst(InvokeInst &II) { 1805 return visitCallBase(II); 1806 } 1807 1808 // CallBrInst simplification 1809 Instruction *InstCombinerImpl::visitCallBrInst(CallBrInst &CBI) { 1810 return visitCallBase(CBI); 1811 } 1812 1813 /// If this cast does not affect the value passed through the varargs area, we 1814 /// can eliminate the use of the cast. 1815 static bool isSafeToEliminateVarargsCast(const CallBase &Call, 1816 const DataLayout &DL, 1817 const CastInst *const CI, 1818 const int ix) { 1819 if (!CI->isLosslessCast()) 1820 return false; 1821 1822 // If this is a GC intrinsic, avoid munging types. We need types for 1823 // statepoint reconstruction in SelectionDAG. 1824 // TODO: This is probably something which should be expanded to all 1825 // intrinsics since the entire point of intrinsics is that 1826 // they are understandable by the optimizer. 1827 if (isa<GCStatepointInst>(Call) || isa<GCRelocateInst>(Call) || 1828 isa<GCResultInst>(Call)) 1829 return false; 1830 1831 // The size of ByVal or InAlloca arguments is derived from the type, so we 1832 // can't change to a type with a different size. If the size were 1833 // passed explicitly we could avoid this check. 1834 if (!Call.isPassPointeeByValueArgument(ix)) 1835 return true; 1836 1837 Type* SrcTy = 1838 cast<PointerType>(CI->getOperand(0)->getType())->getElementType(); 1839 Type *DstTy = Call.isByValArgument(ix) 1840 ? Call.getParamByValType(ix) 1841 : cast<PointerType>(CI->getType())->getElementType(); 1842 if (!SrcTy->isSized() || !DstTy->isSized()) 1843 return false; 1844 if (DL.getTypeAllocSize(SrcTy) != DL.getTypeAllocSize(DstTy)) 1845 return false; 1846 return true; 1847 } 1848 1849 Instruction *InstCombinerImpl::tryOptimizeCall(CallInst *CI) { 1850 if (!CI->getCalledFunction()) return nullptr; 1851 1852 auto InstCombineRAUW = [this](Instruction *From, Value *With) { 1853 replaceInstUsesWith(*From, With); 1854 }; 1855 auto InstCombineErase = [this](Instruction *I) { 1856 eraseInstFromFunction(*I); 1857 }; 1858 LibCallSimplifier Simplifier(DL, &TLI, ORE, BFI, PSI, InstCombineRAUW, 1859 InstCombineErase); 1860 if (Value *With = Simplifier.optimizeCall(CI, Builder)) { 1861 ++NumSimplified; 1862 return CI->use_empty() ? CI : replaceInstUsesWith(*CI, With); 1863 } 1864 1865 return nullptr; 1866 } 1867 1868 static IntrinsicInst *findInitTrampolineFromAlloca(Value *TrampMem) { 1869 // Strip off at most one level of pointer casts, looking for an alloca. This 1870 // is good enough in practice and simpler than handling any number of casts. 1871 Value *Underlying = TrampMem->stripPointerCasts(); 1872 if (Underlying != TrampMem && 1873 (!Underlying->hasOneUse() || Underlying->user_back() != TrampMem)) 1874 return nullptr; 1875 if (!isa<AllocaInst>(Underlying)) 1876 return nullptr; 1877 1878 IntrinsicInst *InitTrampoline = nullptr; 1879 for (User *U : TrampMem->users()) { 1880 IntrinsicInst *II = dyn_cast<IntrinsicInst>(U); 1881 if (!II) 1882 return nullptr; 1883 if (II->getIntrinsicID() == Intrinsic::init_trampoline) { 1884 if (InitTrampoline) 1885 // More than one init_trampoline writes to this value. Give up. 1886 return nullptr; 1887 InitTrampoline = II; 1888 continue; 1889 } 1890 if (II->getIntrinsicID() == Intrinsic::adjust_trampoline) 1891 // Allow any number of calls to adjust.trampoline. 1892 continue; 1893 return nullptr; 1894 } 1895 1896 // No call to init.trampoline found. 1897 if (!InitTrampoline) 1898 return nullptr; 1899 1900 // Check that the alloca is being used in the expected way. 1901 if (InitTrampoline->getOperand(0) != TrampMem) 1902 return nullptr; 1903 1904 return InitTrampoline; 1905 } 1906 1907 static IntrinsicInst *findInitTrampolineFromBB(IntrinsicInst *AdjustTramp, 1908 Value *TrampMem) { 1909 // Visit all the previous instructions in the basic block, and try to find a 1910 // init.trampoline which has a direct path to the adjust.trampoline. 1911 for (BasicBlock::iterator I = AdjustTramp->getIterator(), 1912 E = AdjustTramp->getParent()->begin(); 1913 I != E;) { 1914 Instruction *Inst = &*--I; 1915 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) 1916 if (II->getIntrinsicID() == Intrinsic::init_trampoline && 1917 II->getOperand(0) == TrampMem) 1918 return II; 1919 if (Inst->mayWriteToMemory()) 1920 return nullptr; 1921 } 1922 return nullptr; 1923 } 1924 1925 // Given a call to llvm.adjust.trampoline, find and return the corresponding 1926 // call to llvm.init.trampoline if the call to the trampoline can be optimized 1927 // to a direct call to a function. Otherwise return NULL. 1928 static IntrinsicInst *findInitTrampoline(Value *Callee) { 1929 Callee = Callee->stripPointerCasts(); 1930 IntrinsicInst *AdjustTramp = dyn_cast<IntrinsicInst>(Callee); 1931 if (!AdjustTramp || 1932 AdjustTramp->getIntrinsicID() != Intrinsic::adjust_trampoline) 1933 return nullptr; 1934 1935 Value *TrampMem = AdjustTramp->getOperand(0); 1936 1937 if (IntrinsicInst *IT = findInitTrampolineFromAlloca(TrampMem)) 1938 return IT; 1939 if (IntrinsicInst *IT = findInitTrampolineFromBB(AdjustTramp, TrampMem)) 1940 return IT; 1941 return nullptr; 1942 } 1943 1944 static void annotateAnyAllocSite(CallBase &Call, const TargetLibraryInfo *TLI) { 1945 unsigned NumArgs = Call.getNumArgOperands(); 1946 ConstantInt *Op0C = dyn_cast<ConstantInt>(Call.getOperand(0)); 1947 ConstantInt *Op1C = 1948 (NumArgs == 1) ? nullptr : dyn_cast<ConstantInt>(Call.getOperand(1)); 1949 // Bail out if the allocation size is zero (or an invalid alignment of zero 1950 // with aligned_alloc). 1951 if ((Op0C && Op0C->isNullValue()) || (Op1C && Op1C->isNullValue())) 1952 return; 1953 1954 if (isMallocLikeFn(&Call, TLI) && Op0C) { 1955 if (isOpNewLikeFn(&Call, TLI)) 1956 Call.addAttribute(AttributeList::ReturnIndex, 1957 Attribute::getWithDereferenceableBytes( 1958 Call.getContext(), Op0C->getZExtValue())); 1959 else 1960 Call.addAttribute(AttributeList::ReturnIndex, 1961 Attribute::getWithDereferenceableOrNullBytes( 1962 Call.getContext(), Op0C->getZExtValue())); 1963 } else if (isAlignedAllocLikeFn(&Call, TLI) && Op1C) { 1964 Call.addAttribute(AttributeList::ReturnIndex, 1965 Attribute::getWithDereferenceableOrNullBytes( 1966 Call.getContext(), Op1C->getZExtValue())); 1967 // Add alignment attribute if alignment is a power of two constant. 1968 if (Op0C && Op0C->getValue().ult(llvm::Value::MaximumAlignment)) { 1969 uint64_t AlignmentVal = Op0C->getZExtValue(); 1970 if (llvm::isPowerOf2_64(AlignmentVal)) 1971 Call.addAttribute(AttributeList::ReturnIndex, 1972 Attribute::getWithAlignment(Call.getContext(), 1973 Align(AlignmentVal))); 1974 } 1975 } else if (isReallocLikeFn(&Call, TLI) && Op1C) { 1976 Call.addAttribute(AttributeList::ReturnIndex, 1977 Attribute::getWithDereferenceableOrNullBytes( 1978 Call.getContext(), Op1C->getZExtValue())); 1979 } else if (isCallocLikeFn(&Call, TLI) && Op0C && Op1C) { 1980 bool Overflow; 1981 const APInt &N = Op0C->getValue(); 1982 APInt Size = N.umul_ov(Op1C->getValue(), Overflow); 1983 if (!Overflow) 1984 Call.addAttribute(AttributeList::ReturnIndex, 1985 Attribute::getWithDereferenceableOrNullBytes( 1986 Call.getContext(), Size.getZExtValue())); 1987 } else if (isStrdupLikeFn(&Call, TLI)) { 1988 uint64_t Len = GetStringLength(Call.getOperand(0)); 1989 if (Len) { 1990 // strdup 1991 if (NumArgs == 1) 1992 Call.addAttribute(AttributeList::ReturnIndex, 1993 Attribute::getWithDereferenceableOrNullBytes( 1994 Call.getContext(), Len)); 1995 // strndup 1996 else if (NumArgs == 2 && Op1C) 1997 Call.addAttribute( 1998 AttributeList::ReturnIndex, 1999 Attribute::getWithDereferenceableOrNullBytes( 2000 Call.getContext(), std::min(Len, Op1C->getZExtValue() + 1))); 2001 } 2002 } 2003 } 2004 2005 /// Improvements for call, callbr and invoke instructions. 2006 Instruction *InstCombinerImpl::visitCallBase(CallBase &Call) { 2007 if (isAllocationFn(&Call, &TLI)) 2008 annotateAnyAllocSite(Call, &TLI); 2009 2010 bool Changed = false; 2011 2012 // Mark any parameters that are known to be non-null with the nonnull 2013 // attribute. This is helpful for inlining calls to functions with null 2014 // checks on their arguments. 2015 SmallVector<unsigned, 4> ArgNos; 2016 unsigned ArgNo = 0; 2017 2018 for (Value *V : Call.args()) { 2019 if (V->getType()->isPointerTy() && 2020 !Call.paramHasAttr(ArgNo, Attribute::NonNull) && 2021 isKnownNonZero(V, DL, 0, &AC, &Call, &DT)) 2022 ArgNos.push_back(ArgNo); 2023 ArgNo++; 2024 } 2025 2026 assert(ArgNo == Call.arg_size() && "sanity check"); 2027 2028 if (!ArgNos.empty()) { 2029 AttributeList AS = Call.getAttributes(); 2030 LLVMContext &Ctx = Call.getContext(); 2031 AS = AS.addParamAttribute(Ctx, ArgNos, 2032 Attribute::get(Ctx, Attribute::NonNull)); 2033 Call.setAttributes(AS); 2034 Changed = true; 2035 } 2036 2037 // If the callee is a pointer to a function, attempt to move any casts to the 2038 // arguments of the call/callbr/invoke. 2039 Value *Callee = Call.getCalledOperand(); 2040 if (!isa<Function>(Callee) && transformConstExprCastCall(Call)) 2041 return nullptr; 2042 2043 if (Function *CalleeF = dyn_cast<Function>(Callee)) { 2044 // Remove the convergent attr on calls when the callee is not convergent. 2045 if (Call.isConvergent() && !CalleeF->isConvergent() && 2046 !CalleeF->isIntrinsic()) { 2047 LLVM_DEBUG(dbgs() << "Removing convergent attr from instr " << Call 2048 << "\n"); 2049 Call.setNotConvergent(); 2050 return &Call; 2051 } 2052 2053 // If the call and callee calling conventions don't match, this call must 2054 // be unreachable, as the call is undefined. 2055 if (CalleeF->getCallingConv() != Call.getCallingConv() && 2056 // Only do this for calls to a function with a body. A prototype may 2057 // not actually end up matching the implementation's calling conv for a 2058 // variety of reasons (e.g. it may be written in assembly). 2059 !CalleeF->isDeclaration()) { 2060 Instruction *OldCall = &Call; 2061 CreateNonTerminatorUnreachable(OldCall); 2062 // If OldCall does not return void then replaceInstUsesWith undef. 2063 // This allows ValueHandlers and custom metadata to adjust itself. 2064 if (!OldCall->getType()->isVoidTy()) 2065 replaceInstUsesWith(*OldCall, UndefValue::get(OldCall->getType())); 2066 if (isa<CallInst>(OldCall)) 2067 return eraseInstFromFunction(*OldCall); 2068 2069 // We cannot remove an invoke or a callbr, because it would change thexi 2070 // CFG, just change the callee to a null pointer. 2071 cast<CallBase>(OldCall)->setCalledFunction( 2072 CalleeF->getFunctionType(), 2073 Constant::getNullValue(CalleeF->getType())); 2074 return nullptr; 2075 } 2076 } 2077 2078 if ((isa<ConstantPointerNull>(Callee) && 2079 !NullPointerIsDefined(Call.getFunction())) || 2080 isa<UndefValue>(Callee)) { 2081 // If Call does not return void then replaceInstUsesWith undef. 2082 // This allows ValueHandlers and custom metadata to adjust itself. 2083 if (!Call.getType()->isVoidTy()) 2084 replaceInstUsesWith(Call, UndefValue::get(Call.getType())); 2085 2086 if (Call.isTerminator()) { 2087 // Can't remove an invoke or callbr because we cannot change the CFG. 2088 return nullptr; 2089 } 2090 2091 // This instruction is not reachable, just remove it. 2092 CreateNonTerminatorUnreachable(&Call); 2093 return eraseInstFromFunction(Call); 2094 } 2095 2096 if (IntrinsicInst *II = findInitTrampoline(Callee)) 2097 return transformCallThroughTrampoline(Call, *II); 2098 2099 PointerType *PTy = cast<PointerType>(Callee->getType()); 2100 FunctionType *FTy = cast<FunctionType>(PTy->getElementType()); 2101 if (FTy->isVarArg()) { 2102 int ix = FTy->getNumParams(); 2103 // See if we can optimize any arguments passed through the varargs area of 2104 // the call. 2105 for (auto I = Call.arg_begin() + FTy->getNumParams(), E = Call.arg_end(); 2106 I != E; ++I, ++ix) { 2107 CastInst *CI = dyn_cast<CastInst>(*I); 2108 if (CI && isSafeToEliminateVarargsCast(Call, DL, CI, ix)) { 2109 replaceUse(*I, CI->getOperand(0)); 2110 2111 // Update the byval type to match the argument type. 2112 if (Call.isByValArgument(ix)) { 2113 Call.removeParamAttr(ix, Attribute::ByVal); 2114 Call.addParamAttr( 2115 ix, Attribute::getWithByValType( 2116 Call.getContext(), 2117 CI->getOperand(0)->getType()->getPointerElementType())); 2118 } 2119 Changed = true; 2120 } 2121 } 2122 } 2123 2124 if (isa<InlineAsm>(Callee) && !Call.doesNotThrow()) { 2125 // Inline asm calls cannot throw - mark them 'nounwind'. 2126 Call.setDoesNotThrow(); 2127 Changed = true; 2128 } 2129 2130 // Try to optimize the call if possible, we require DataLayout for most of 2131 // this. None of these calls are seen as possibly dead so go ahead and 2132 // delete the instruction now. 2133 if (CallInst *CI = dyn_cast<CallInst>(&Call)) { 2134 Instruction *I = tryOptimizeCall(CI); 2135 // If we changed something return the result, etc. Otherwise let 2136 // the fallthrough check. 2137 if (I) return eraseInstFromFunction(*I); 2138 } 2139 2140 if (!Call.use_empty() && !Call.isMustTailCall()) 2141 if (Value *ReturnedArg = Call.getReturnedArgOperand()) { 2142 Type *CallTy = Call.getType(); 2143 Type *RetArgTy = ReturnedArg->getType(); 2144 if (RetArgTy->canLosslesslyBitCastTo(CallTy)) 2145 return replaceInstUsesWith( 2146 Call, Builder.CreateBitOrPointerCast(ReturnedArg, CallTy)); 2147 } 2148 2149 if (isAllocLikeFn(&Call, &TLI)) 2150 return visitAllocSite(Call); 2151 2152 return Changed ? &Call : nullptr; 2153 } 2154 2155 /// If the callee is a constexpr cast of a function, attempt to move the cast to 2156 /// the arguments of the call/callbr/invoke. 2157 bool InstCombinerImpl::transformConstExprCastCall(CallBase &Call) { 2158 auto *Callee = 2159 dyn_cast<Function>(Call.getCalledOperand()->stripPointerCasts()); 2160 if (!Callee) 2161 return false; 2162 2163 // If this is a call to a thunk function, don't remove the cast. Thunks are 2164 // used to transparently forward all incoming parameters and outgoing return 2165 // values, so it's important to leave the cast in place. 2166 if (Callee->hasFnAttribute("thunk")) 2167 return false; 2168 2169 // If this is a musttail call, the callee's prototype must match the caller's 2170 // prototype with the exception of pointee types. The code below doesn't 2171 // implement that, so we can't do this transform. 2172 // TODO: Do the transform if it only requires adding pointer casts. 2173 if (Call.isMustTailCall()) 2174 return false; 2175 2176 Instruction *Caller = &Call; 2177 const AttributeList &CallerPAL = Call.getAttributes(); 2178 2179 // Okay, this is a cast from a function to a different type. Unless doing so 2180 // would cause a type conversion of one of our arguments, change this call to 2181 // be a direct call with arguments casted to the appropriate types. 2182 FunctionType *FT = Callee->getFunctionType(); 2183 Type *OldRetTy = Caller->getType(); 2184 Type *NewRetTy = FT->getReturnType(); 2185 2186 // Check to see if we are changing the return type... 2187 if (OldRetTy != NewRetTy) { 2188 2189 if (NewRetTy->isStructTy()) 2190 return false; // TODO: Handle multiple return values. 2191 2192 if (!CastInst::isBitOrNoopPointerCastable(NewRetTy, OldRetTy, DL)) { 2193 if (Callee->isDeclaration()) 2194 return false; // Cannot transform this return value. 2195 2196 if (!Caller->use_empty() && 2197 // void -> non-void is handled specially 2198 !NewRetTy->isVoidTy()) 2199 return false; // Cannot transform this return value. 2200 } 2201 2202 if (!CallerPAL.isEmpty() && !Caller->use_empty()) { 2203 AttrBuilder RAttrs(CallerPAL, AttributeList::ReturnIndex); 2204 if (RAttrs.overlaps(AttributeFuncs::typeIncompatible(NewRetTy))) 2205 return false; // Attribute not compatible with transformed value. 2206 } 2207 2208 // If the callbase is an invoke/callbr instruction, and the return value is 2209 // used by a PHI node in a successor, we cannot change the return type of 2210 // the call because there is no place to put the cast instruction (without 2211 // breaking the critical edge). Bail out in this case. 2212 if (!Caller->use_empty()) { 2213 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) 2214 for (User *U : II->users()) 2215 if (PHINode *PN = dyn_cast<PHINode>(U)) 2216 if (PN->getParent() == II->getNormalDest() || 2217 PN->getParent() == II->getUnwindDest()) 2218 return false; 2219 // FIXME: Be conservative for callbr to avoid a quadratic search. 2220 if (isa<CallBrInst>(Caller)) 2221 return false; 2222 } 2223 } 2224 2225 unsigned NumActualArgs = Call.arg_size(); 2226 unsigned NumCommonArgs = std::min(FT->getNumParams(), NumActualArgs); 2227 2228 // Prevent us turning: 2229 // declare void @takes_i32_inalloca(i32* inalloca) 2230 // call void bitcast (void (i32*)* @takes_i32_inalloca to void (i32)*)(i32 0) 2231 // 2232 // into: 2233 // call void @takes_i32_inalloca(i32* null) 2234 // 2235 // Similarly, avoid folding away bitcasts of byval calls. 2236 if (Callee->getAttributes().hasAttrSomewhere(Attribute::InAlloca) || 2237 Callee->getAttributes().hasAttrSomewhere(Attribute::Preallocated) || 2238 Callee->getAttributes().hasAttrSomewhere(Attribute::ByVal)) 2239 return false; 2240 2241 auto AI = Call.arg_begin(); 2242 for (unsigned i = 0, e = NumCommonArgs; i != e; ++i, ++AI) { 2243 Type *ParamTy = FT->getParamType(i); 2244 Type *ActTy = (*AI)->getType(); 2245 2246 if (!CastInst::isBitOrNoopPointerCastable(ActTy, ParamTy, DL)) 2247 return false; // Cannot transform this parameter value. 2248 2249 if (AttrBuilder(CallerPAL.getParamAttributes(i)) 2250 .overlaps(AttributeFuncs::typeIncompatible(ParamTy))) 2251 return false; // Attribute not compatible with transformed value. 2252 2253 if (Call.isInAllocaArgument(i)) 2254 return false; // Cannot transform to and from inalloca. 2255 2256 if (CallerPAL.hasParamAttribute(i, Attribute::SwiftError)) 2257 return false; 2258 2259 // If the parameter is passed as a byval argument, then we have to have a 2260 // sized type and the sized type has to have the same size as the old type. 2261 if (ParamTy != ActTy && CallerPAL.hasParamAttribute(i, Attribute::ByVal)) { 2262 PointerType *ParamPTy = dyn_cast<PointerType>(ParamTy); 2263 if (!ParamPTy || !ParamPTy->getElementType()->isSized()) 2264 return false; 2265 2266 Type *CurElTy = Call.getParamByValType(i); 2267 if (DL.getTypeAllocSize(CurElTy) != 2268 DL.getTypeAllocSize(ParamPTy->getElementType())) 2269 return false; 2270 } 2271 } 2272 2273 if (Callee->isDeclaration()) { 2274 // Do not delete arguments unless we have a function body. 2275 if (FT->getNumParams() < NumActualArgs && !FT->isVarArg()) 2276 return false; 2277 2278 // If the callee is just a declaration, don't change the varargsness of the 2279 // call. We don't want to introduce a varargs call where one doesn't 2280 // already exist. 2281 PointerType *APTy = cast<PointerType>(Call.getCalledOperand()->getType()); 2282 if (FT->isVarArg()!=cast<FunctionType>(APTy->getElementType())->isVarArg()) 2283 return false; 2284 2285 // If both the callee and the cast type are varargs, we still have to make 2286 // sure the number of fixed parameters are the same or we have the same 2287 // ABI issues as if we introduce a varargs call. 2288 if (FT->isVarArg() && 2289 cast<FunctionType>(APTy->getElementType())->isVarArg() && 2290 FT->getNumParams() != 2291 cast<FunctionType>(APTy->getElementType())->getNumParams()) 2292 return false; 2293 } 2294 2295 if (FT->getNumParams() < NumActualArgs && FT->isVarArg() && 2296 !CallerPAL.isEmpty()) { 2297 // In this case we have more arguments than the new function type, but we 2298 // won't be dropping them. Check that these extra arguments have attributes 2299 // that are compatible with being a vararg call argument. 2300 unsigned SRetIdx; 2301 if (CallerPAL.hasAttrSomewhere(Attribute::StructRet, &SRetIdx) && 2302 SRetIdx > FT->getNumParams()) 2303 return false; 2304 } 2305 2306 // Okay, we decided that this is a safe thing to do: go ahead and start 2307 // inserting cast instructions as necessary. 2308 SmallVector<Value *, 8> Args; 2309 SmallVector<AttributeSet, 8> ArgAttrs; 2310 Args.reserve(NumActualArgs); 2311 ArgAttrs.reserve(NumActualArgs); 2312 2313 // Get any return attributes. 2314 AttrBuilder RAttrs(CallerPAL, AttributeList::ReturnIndex); 2315 2316 // If the return value is not being used, the type may not be compatible 2317 // with the existing attributes. Wipe out any problematic attributes. 2318 RAttrs.remove(AttributeFuncs::typeIncompatible(NewRetTy)); 2319 2320 LLVMContext &Ctx = Call.getContext(); 2321 AI = Call.arg_begin(); 2322 for (unsigned i = 0; i != NumCommonArgs; ++i, ++AI) { 2323 Type *ParamTy = FT->getParamType(i); 2324 2325 Value *NewArg = *AI; 2326 if ((*AI)->getType() != ParamTy) 2327 NewArg = Builder.CreateBitOrPointerCast(*AI, ParamTy); 2328 Args.push_back(NewArg); 2329 2330 // Add any parameter attributes. 2331 if (CallerPAL.hasParamAttribute(i, Attribute::ByVal)) { 2332 AttrBuilder AB(CallerPAL.getParamAttributes(i)); 2333 AB.addByValAttr(NewArg->getType()->getPointerElementType()); 2334 ArgAttrs.push_back(AttributeSet::get(Ctx, AB)); 2335 } else 2336 ArgAttrs.push_back(CallerPAL.getParamAttributes(i)); 2337 } 2338 2339 // If the function takes more arguments than the call was taking, add them 2340 // now. 2341 for (unsigned i = NumCommonArgs; i != FT->getNumParams(); ++i) { 2342 Args.push_back(Constant::getNullValue(FT->getParamType(i))); 2343 ArgAttrs.push_back(AttributeSet()); 2344 } 2345 2346 // If we are removing arguments to the function, emit an obnoxious warning. 2347 if (FT->getNumParams() < NumActualArgs) { 2348 // TODO: if (!FT->isVarArg()) this call may be unreachable. PR14722 2349 if (FT->isVarArg()) { 2350 // Add all of the arguments in their promoted form to the arg list. 2351 for (unsigned i = FT->getNumParams(); i != NumActualArgs; ++i, ++AI) { 2352 Type *PTy = getPromotedType((*AI)->getType()); 2353 Value *NewArg = *AI; 2354 if (PTy != (*AI)->getType()) { 2355 // Must promote to pass through va_arg area! 2356 Instruction::CastOps opcode = 2357 CastInst::getCastOpcode(*AI, false, PTy, false); 2358 NewArg = Builder.CreateCast(opcode, *AI, PTy); 2359 } 2360 Args.push_back(NewArg); 2361 2362 // Add any parameter attributes. 2363 ArgAttrs.push_back(CallerPAL.getParamAttributes(i)); 2364 } 2365 } 2366 } 2367 2368 AttributeSet FnAttrs = CallerPAL.getFnAttributes(); 2369 2370 if (NewRetTy->isVoidTy()) 2371 Caller->setName(""); // Void type should not have a name. 2372 2373 assert((ArgAttrs.size() == FT->getNumParams() || FT->isVarArg()) && 2374 "missing argument attributes"); 2375 AttributeList NewCallerPAL = AttributeList::get( 2376 Ctx, FnAttrs, AttributeSet::get(Ctx, RAttrs), ArgAttrs); 2377 2378 SmallVector<OperandBundleDef, 1> OpBundles; 2379 Call.getOperandBundlesAsDefs(OpBundles); 2380 2381 CallBase *NewCall; 2382 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) { 2383 NewCall = Builder.CreateInvoke(Callee, II->getNormalDest(), 2384 II->getUnwindDest(), Args, OpBundles); 2385 } else if (CallBrInst *CBI = dyn_cast<CallBrInst>(Caller)) { 2386 NewCall = Builder.CreateCallBr(Callee, CBI->getDefaultDest(), 2387 CBI->getIndirectDests(), Args, OpBundles); 2388 } else { 2389 NewCall = Builder.CreateCall(Callee, Args, OpBundles); 2390 cast<CallInst>(NewCall)->setTailCallKind( 2391 cast<CallInst>(Caller)->getTailCallKind()); 2392 } 2393 NewCall->takeName(Caller); 2394 NewCall->setCallingConv(Call.getCallingConv()); 2395 NewCall->setAttributes(NewCallerPAL); 2396 2397 // Preserve prof metadata if any. 2398 NewCall->copyMetadata(*Caller, {LLVMContext::MD_prof}); 2399 2400 // Insert a cast of the return type as necessary. 2401 Instruction *NC = NewCall; 2402 Value *NV = NC; 2403 if (OldRetTy != NV->getType() && !Caller->use_empty()) { 2404 if (!NV->getType()->isVoidTy()) { 2405 NV = NC = CastInst::CreateBitOrPointerCast(NC, OldRetTy); 2406 NC->setDebugLoc(Caller->getDebugLoc()); 2407 2408 // If this is an invoke/callbr instruction, we should insert it after the 2409 // first non-phi instruction in the normal successor block. 2410 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) { 2411 BasicBlock::iterator I = II->getNormalDest()->getFirstInsertionPt(); 2412 InsertNewInstBefore(NC, *I); 2413 } else if (CallBrInst *CBI = dyn_cast<CallBrInst>(Caller)) { 2414 BasicBlock::iterator I = CBI->getDefaultDest()->getFirstInsertionPt(); 2415 InsertNewInstBefore(NC, *I); 2416 } else { 2417 // Otherwise, it's a call, just insert cast right after the call. 2418 InsertNewInstBefore(NC, *Caller); 2419 } 2420 Worklist.pushUsersToWorkList(*Caller); 2421 } else { 2422 NV = UndefValue::get(Caller->getType()); 2423 } 2424 } 2425 2426 if (!Caller->use_empty()) 2427 replaceInstUsesWith(*Caller, NV); 2428 else if (Caller->hasValueHandle()) { 2429 if (OldRetTy == NV->getType()) 2430 ValueHandleBase::ValueIsRAUWd(Caller, NV); 2431 else 2432 // We cannot call ValueIsRAUWd with a different type, and the 2433 // actual tracked value will disappear. 2434 ValueHandleBase::ValueIsDeleted(Caller); 2435 } 2436 2437 eraseInstFromFunction(*Caller); 2438 return true; 2439 } 2440 2441 /// Turn a call to a function created by init_trampoline / adjust_trampoline 2442 /// intrinsic pair into a direct call to the underlying function. 2443 Instruction * 2444 InstCombinerImpl::transformCallThroughTrampoline(CallBase &Call, 2445 IntrinsicInst &Tramp) { 2446 Value *Callee = Call.getCalledOperand(); 2447 Type *CalleeTy = Callee->getType(); 2448 FunctionType *FTy = Call.getFunctionType(); 2449 AttributeList Attrs = Call.getAttributes(); 2450 2451 // If the call already has the 'nest' attribute somewhere then give up - 2452 // otherwise 'nest' would occur twice after splicing in the chain. 2453 if (Attrs.hasAttrSomewhere(Attribute::Nest)) 2454 return nullptr; 2455 2456 Function *NestF = cast<Function>(Tramp.getArgOperand(1)->stripPointerCasts()); 2457 FunctionType *NestFTy = NestF->getFunctionType(); 2458 2459 AttributeList NestAttrs = NestF->getAttributes(); 2460 if (!NestAttrs.isEmpty()) { 2461 unsigned NestArgNo = 0; 2462 Type *NestTy = nullptr; 2463 AttributeSet NestAttr; 2464 2465 // Look for a parameter marked with the 'nest' attribute. 2466 for (FunctionType::param_iterator I = NestFTy->param_begin(), 2467 E = NestFTy->param_end(); 2468 I != E; ++NestArgNo, ++I) { 2469 AttributeSet AS = NestAttrs.getParamAttributes(NestArgNo); 2470 if (AS.hasAttribute(Attribute::Nest)) { 2471 // Record the parameter type and any other attributes. 2472 NestTy = *I; 2473 NestAttr = AS; 2474 break; 2475 } 2476 } 2477 2478 if (NestTy) { 2479 std::vector<Value*> NewArgs; 2480 std::vector<AttributeSet> NewArgAttrs; 2481 NewArgs.reserve(Call.arg_size() + 1); 2482 NewArgAttrs.reserve(Call.arg_size()); 2483 2484 // Insert the nest argument into the call argument list, which may 2485 // mean appending it. Likewise for attributes. 2486 2487 { 2488 unsigned ArgNo = 0; 2489 auto I = Call.arg_begin(), E = Call.arg_end(); 2490 do { 2491 if (ArgNo == NestArgNo) { 2492 // Add the chain argument and attributes. 2493 Value *NestVal = Tramp.getArgOperand(2); 2494 if (NestVal->getType() != NestTy) 2495 NestVal = Builder.CreateBitCast(NestVal, NestTy, "nest"); 2496 NewArgs.push_back(NestVal); 2497 NewArgAttrs.push_back(NestAttr); 2498 } 2499 2500 if (I == E) 2501 break; 2502 2503 // Add the original argument and attributes. 2504 NewArgs.push_back(*I); 2505 NewArgAttrs.push_back(Attrs.getParamAttributes(ArgNo)); 2506 2507 ++ArgNo; 2508 ++I; 2509 } while (true); 2510 } 2511 2512 // The trampoline may have been bitcast to a bogus type (FTy). 2513 // Handle this by synthesizing a new function type, equal to FTy 2514 // with the chain parameter inserted. 2515 2516 std::vector<Type*> NewTypes; 2517 NewTypes.reserve(FTy->getNumParams()+1); 2518 2519 // Insert the chain's type into the list of parameter types, which may 2520 // mean appending it. 2521 { 2522 unsigned ArgNo = 0; 2523 FunctionType::param_iterator I = FTy->param_begin(), 2524 E = FTy->param_end(); 2525 2526 do { 2527 if (ArgNo == NestArgNo) 2528 // Add the chain's type. 2529 NewTypes.push_back(NestTy); 2530 2531 if (I == E) 2532 break; 2533 2534 // Add the original type. 2535 NewTypes.push_back(*I); 2536 2537 ++ArgNo; 2538 ++I; 2539 } while (true); 2540 } 2541 2542 // Replace the trampoline call with a direct call. Let the generic 2543 // code sort out any function type mismatches. 2544 FunctionType *NewFTy = FunctionType::get(FTy->getReturnType(), NewTypes, 2545 FTy->isVarArg()); 2546 Constant *NewCallee = 2547 NestF->getType() == PointerType::getUnqual(NewFTy) ? 2548 NestF : ConstantExpr::getBitCast(NestF, 2549 PointerType::getUnqual(NewFTy)); 2550 AttributeList NewPAL = 2551 AttributeList::get(FTy->getContext(), Attrs.getFnAttributes(), 2552 Attrs.getRetAttributes(), NewArgAttrs); 2553 2554 SmallVector<OperandBundleDef, 1> OpBundles; 2555 Call.getOperandBundlesAsDefs(OpBundles); 2556 2557 Instruction *NewCaller; 2558 if (InvokeInst *II = dyn_cast<InvokeInst>(&Call)) { 2559 NewCaller = InvokeInst::Create(NewFTy, NewCallee, 2560 II->getNormalDest(), II->getUnwindDest(), 2561 NewArgs, OpBundles); 2562 cast<InvokeInst>(NewCaller)->setCallingConv(II->getCallingConv()); 2563 cast<InvokeInst>(NewCaller)->setAttributes(NewPAL); 2564 } else if (CallBrInst *CBI = dyn_cast<CallBrInst>(&Call)) { 2565 NewCaller = 2566 CallBrInst::Create(NewFTy, NewCallee, CBI->getDefaultDest(), 2567 CBI->getIndirectDests(), NewArgs, OpBundles); 2568 cast<CallBrInst>(NewCaller)->setCallingConv(CBI->getCallingConv()); 2569 cast<CallBrInst>(NewCaller)->setAttributes(NewPAL); 2570 } else { 2571 NewCaller = CallInst::Create(NewFTy, NewCallee, NewArgs, OpBundles); 2572 cast<CallInst>(NewCaller)->setTailCallKind( 2573 cast<CallInst>(Call).getTailCallKind()); 2574 cast<CallInst>(NewCaller)->setCallingConv( 2575 cast<CallInst>(Call).getCallingConv()); 2576 cast<CallInst>(NewCaller)->setAttributes(NewPAL); 2577 } 2578 NewCaller->setDebugLoc(Call.getDebugLoc()); 2579 2580 return NewCaller; 2581 } 2582 } 2583 2584 // Replace the trampoline call with a direct call. Since there is no 'nest' 2585 // parameter, there is no need to adjust the argument list. Let the generic 2586 // code sort out any function type mismatches. 2587 Constant *NewCallee = ConstantExpr::getBitCast(NestF, CalleeTy); 2588 Call.setCalledFunction(FTy, NewCallee); 2589 return &Call; 2590 } 2591