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/None.h" 19 #include "llvm/ADT/Optional.h" 20 #include "llvm/ADT/STLFunctionalExtras.h" 21 #include "llvm/ADT/SmallBitVector.h" 22 #include "llvm/ADT/SmallVector.h" 23 #include "llvm/ADT/Statistic.h" 24 #include "llvm/Analysis/AliasAnalysis.h" 25 #include "llvm/Analysis/AssumeBundleQueries.h" 26 #include "llvm/Analysis/AssumptionCache.h" 27 #include "llvm/Analysis/InstructionSimplify.h" 28 #include "llvm/Analysis/Loads.h" 29 #include "llvm/Analysis/MemoryBuiltins.h" 30 #include "llvm/Analysis/ValueTracking.h" 31 #include "llvm/Analysis/VectorUtils.h" 32 #include "llvm/IR/Attributes.h" 33 #include "llvm/IR/BasicBlock.h" 34 #include "llvm/IR/Constant.h" 35 #include "llvm/IR/Constants.h" 36 #include "llvm/IR/DataLayout.h" 37 #include "llvm/IR/DerivedTypes.h" 38 #include "llvm/IR/Function.h" 39 #include "llvm/IR/GlobalVariable.h" 40 #include "llvm/IR/InlineAsm.h" 41 #include "llvm/IR/InstrTypes.h" 42 #include "llvm/IR/Instruction.h" 43 #include "llvm/IR/Instructions.h" 44 #include "llvm/IR/IntrinsicInst.h" 45 #include "llvm/IR/Intrinsics.h" 46 #include "llvm/IR/IntrinsicsAArch64.h" 47 #include "llvm/IR/IntrinsicsAMDGPU.h" 48 #include "llvm/IR/IntrinsicsARM.h" 49 #include "llvm/IR/IntrinsicsHexagon.h" 50 #include "llvm/IR/LLVMContext.h" 51 #include "llvm/IR/Metadata.h" 52 #include "llvm/IR/PatternMatch.h" 53 #include "llvm/IR/Statepoint.h" 54 #include "llvm/IR/Type.h" 55 #include "llvm/IR/User.h" 56 #include "llvm/IR/Value.h" 57 #include "llvm/IR/ValueHandle.h" 58 #include "llvm/Support/AtomicOrdering.h" 59 #include "llvm/Support/Casting.h" 60 #include "llvm/Support/CommandLine.h" 61 #include "llvm/Support/Compiler.h" 62 #include "llvm/Support/Debug.h" 63 #include "llvm/Support/ErrorHandling.h" 64 #include "llvm/Support/KnownBits.h" 65 #include "llvm/Support/MathExtras.h" 66 #include "llvm/Support/raw_ostream.h" 67 #include "llvm/Transforms/InstCombine/InstCombiner.h" 68 #include "llvm/Transforms/Utils/AssumeBundleBuilder.h" 69 #include "llvm/Transforms/Utils/Local.h" 70 #include "llvm/Transforms/Utils/SimplifyLibCalls.h" 71 #include <algorithm> 72 #include <cassert> 73 #include <cstdint> 74 #include <utility> 75 #include <vector> 76 77 #define DEBUG_TYPE "instcombine" 78 #include "llvm/Transforms/Utils/InstructionWorklist.h" 79 80 using namespace llvm; 81 using namespace PatternMatch; 82 83 STATISTIC(NumSimplified, "Number of library calls simplified"); 84 85 static cl::opt<unsigned> GuardWideningWindow( 86 "instcombine-guard-widening-window", 87 cl::init(3), 88 cl::desc("How wide an instruction window to bypass looking for " 89 "another guard")); 90 91 namespace llvm { 92 /// enable preservation of attributes in assume like: 93 /// call void @llvm.assume(i1 true) [ "nonnull"(i32* %PTR) ] 94 extern cl::opt<bool> EnableKnowledgeRetention; 95 } // namespace llvm 96 97 /// Return the specified type promoted as it would be to pass though a va_arg 98 /// area. 99 static Type *getPromotedType(Type *Ty) { 100 if (IntegerType* ITy = dyn_cast<IntegerType>(Ty)) { 101 if (ITy->getBitWidth() < 32) 102 return Type::getInt32Ty(Ty->getContext()); 103 } 104 return Ty; 105 } 106 107 /// Recognize a memcpy/memmove from a trivially otherwise unused alloca. 108 /// TODO: This should probably be integrated with visitAllocSites, but that 109 /// requires a deeper change to allow either unread or unwritten objects. 110 static bool hasUndefSource(AnyMemTransferInst *MI) { 111 auto *Src = MI->getRawSource(); 112 while (isa<GetElementPtrInst>(Src) || isa<BitCastInst>(Src)) { 113 if (!Src->hasOneUse()) 114 return false; 115 Src = cast<Instruction>(Src)->getOperand(0); 116 } 117 return isa<AllocaInst>(Src) && Src->hasOneUse(); 118 } 119 120 Instruction *InstCombinerImpl::SimplifyAnyMemTransfer(AnyMemTransferInst *MI) { 121 Align DstAlign = getKnownAlignment(MI->getRawDest(), DL, MI, &AC, &DT); 122 MaybeAlign CopyDstAlign = MI->getDestAlign(); 123 if (!CopyDstAlign || *CopyDstAlign < DstAlign) { 124 MI->setDestAlignment(DstAlign); 125 return MI; 126 } 127 128 Align SrcAlign = getKnownAlignment(MI->getRawSource(), DL, MI, &AC, &DT); 129 MaybeAlign CopySrcAlign = MI->getSourceAlign(); 130 if (!CopySrcAlign || *CopySrcAlign < SrcAlign) { 131 MI->setSourceAlignment(SrcAlign); 132 return MI; 133 } 134 135 // If we have a store to a location which is known constant, we can conclude 136 // that the store must be storing the constant value (else the memory 137 // wouldn't be constant), and this must be a noop. 138 if (AA->pointsToConstantMemory(MI->getDest())) { 139 // Set the size of the copy to 0, it will be deleted on the next iteration. 140 MI->setLength(Constant::getNullValue(MI->getLength()->getType())); 141 return MI; 142 } 143 144 // If the source is provably undef, the memcpy/memmove doesn't do anything 145 // (unless the transfer is volatile). 146 if (hasUndefSource(MI) && !MI->isVolatile()) { 147 // Set the size of the copy to 0, it will be deleted on the next iteration. 148 MI->setLength(Constant::getNullValue(MI->getLength()->getType())); 149 return MI; 150 } 151 152 // If MemCpyInst length is 1/2/4/8 bytes then replace memcpy with 153 // load/store. 154 ConstantInt *MemOpLength = dyn_cast<ConstantInt>(MI->getLength()); 155 if (!MemOpLength) return nullptr; 156 157 // Source and destination pointer types are always "i8*" for intrinsic. See 158 // if the size is something we can handle with a single primitive load/store. 159 // A single load+store correctly handles overlapping memory in the memmove 160 // case. 161 uint64_t Size = MemOpLength->getLimitedValue(); 162 assert(Size && "0-sized memory transferring should be removed already."); 163 164 if (Size > 8 || (Size&(Size-1))) 165 return nullptr; // If not 1/2/4/8 bytes, exit. 166 167 // If it is an atomic and alignment is less than the size then we will 168 // introduce the unaligned memory access which will be later transformed 169 // into libcall in CodeGen. This is not evident performance gain so disable 170 // it now. 171 if (isa<AtomicMemTransferInst>(MI)) 172 if (*CopyDstAlign < Size || *CopySrcAlign < Size) 173 return nullptr; 174 175 // Use an integer load+store unless we can find something better. 176 unsigned SrcAddrSp = 177 cast<PointerType>(MI->getArgOperand(1)->getType())->getAddressSpace(); 178 unsigned DstAddrSp = 179 cast<PointerType>(MI->getArgOperand(0)->getType())->getAddressSpace(); 180 181 IntegerType* IntType = IntegerType::get(MI->getContext(), Size<<3); 182 Type *NewSrcPtrTy = PointerType::get(IntType, SrcAddrSp); 183 Type *NewDstPtrTy = PointerType::get(IntType, DstAddrSp); 184 185 // If the memcpy has metadata describing the members, see if we can get the 186 // TBAA tag describing our copy. 187 MDNode *CopyMD = nullptr; 188 if (MDNode *M = MI->getMetadata(LLVMContext::MD_tbaa)) { 189 CopyMD = M; 190 } else if (MDNode *M = MI->getMetadata(LLVMContext::MD_tbaa_struct)) { 191 if (M->getNumOperands() == 3 && M->getOperand(0) && 192 mdconst::hasa<ConstantInt>(M->getOperand(0)) && 193 mdconst::extract<ConstantInt>(M->getOperand(0))->isZero() && 194 M->getOperand(1) && 195 mdconst::hasa<ConstantInt>(M->getOperand(1)) && 196 mdconst::extract<ConstantInt>(M->getOperand(1))->getValue() == 197 Size && 198 M->getOperand(2) && isa<MDNode>(M->getOperand(2))) 199 CopyMD = cast<MDNode>(M->getOperand(2)); 200 } 201 202 Value *Src = Builder.CreateBitCast(MI->getArgOperand(1), NewSrcPtrTy); 203 Value *Dest = Builder.CreateBitCast(MI->getArgOperand(0), NewDstPtrTy); 204 LoadInst *L = Builder.CreateLoad(IntType, Src); 205 // Alignment from the mem intrinsic will be better, so use it. 206 L->setAlignment(*CopySrcAlign); 207 if (CopyMD) 208 L->setMetadata(LLVMContext::MD_tbaa, CopyMD); 209 MDNode *LoopMemParallelMD = 210 MI->getMetadata(LLVMContext::MD_mem_parallel_loop_access); 211 if (LoopMemParallelMD) 212 L->setMetadata(LLVMContext::MD_mem_parallel_loop_access, LoopMemParallelMD); 213 MDNode *AccessGroupMD = MI->getMetadata(LLVMContext::MD_access_group); 214 if (AccessGroupMD) 215 L->setMetadata(LLVMContext::MD_access_group, AccessGroupMD); 216 217 StoreInst *S = Builder.CreateStore(L, Dest); 218 // Alignment from the mem intrinsic will be better, so use it. 219 S->setAlignment(*CopyDstAlign); 220 if (CopyMD) 221 S->setMetadata(LLVMContext::MD_tbaa, CopyMD); 222 if (LoopMemParallelMD) 223 S->setMetadata(LLVMContext::MD_mem_parallel_loop_access, LoopMemParallelMD); 224 if (AccessGroupMD) 225 S->setMetadata(LLVMContext::MD_access_group, AccessGroupMD); 226 227 if (auto *MT = dyn_cast<MemTransferInst>(MI)) { 228 // non-atomics can be volatile 229 L->setVolatile(MT->isVolatile()); 230 S->setVolatile(MT->isVolatile()); 231 } 232 if (isa<AtomicMemTransferInst>(MI)) { 233 // atomics have to be unordered 234 L->setOrdering(AtomicOrdering::Unordered); 235 S->setOrdering(AtomicOrdering::Unordered); 236 } 237 238 // Set the size of the copy to 0, it will be deleted on the next iteration. 239 MI->setLength(Constant::getNullValue(MemOpLength->getType())); 240 return MI; 241 } 242 243 Instruction *InstCombinerImpl::SimplifyAnyMemSet(AnyMemSetInst *MI) { 244 const Align KnownAlignment = 245 getKnownAlignment(MI->getDest(), DL, MI, &AC, &DT); 246 MaybeAlign MemSetAlign = MI->getDestAlign(); 247 if (!MemSetAlign || *MemSetAlign < KnownAlignment) { 248 MI->setDestAlignment(KnownAlignment); 249 return MI; 250 } 251 252 // If we have a store to a location which is known constant, we can conclude 253 // that the store must be storing the constant value (else the memory 254 // wouldn't be constant), and this must be a noop. 255 if (AA->pointsToConstantMemory(MI->getDest())) { 256 // Set the size of the copy to 0, it will be deleted on the next iteration. 257 MI->setLength(Constant::getNullValue(MI->getLength()->getType())); 258 return MI; 259 } 260 261 // Extract the length and alignment and fill if they are constant. 262 ConstantInt *LenC = dyn_cast<ConstantInt>(MI->getLength()); 263 ConstantInt *FillC = dyn_cast<ConstantInt>(MI->getValue()); 264 if (!LenC || !FillC || !FillC->getType()->isIntegerTy(8)) 265 return nullptr; 266 const uint64_t Len = LenC->getLimitedValue(); 267 assert(Len && "0-sized memory setting should be removed already."); 268 const Align Alignment = assumeAligned(MI->getDestAlignment()); 269 270 // If it is an atomic and alignment is less than the size then we will 271 // introduce the unaligned memory access which will be later transformed 272 // into libcall in CodeGen. This is not evident performance gain so disable 273 // it now. 274 if (isa<AtomicMemSetInst>(MI)) 275 if (Alignment < Len) 276 return nullptr; 277 278 // memset(s,c,n) -> store s, c (for n=1,2,4,8) 279 if (Len <= 8 && isPowerOf2_32((uint32_t)Len)) { 280 Type *ITy = IntegerType::get(MI->getContext(), Len*8); // n=1 -> i8. 281 282 Value *Dest = MI->getDest(); 283 unsigned DstAddrSp = cast<PointerType>(Dest->getType())->getAddressSpace(); 284 Type *NewDstPtrTy = PointerType::get(ITy, DstAddrSp); 285 Dest = Builder.CreateBitCast(Dest, NewDstPtrTy); 286 287 // Extract the fill value and store. 288 uint64_t Fill = FillC->getZExtValue()*0x0101010101010101ULL; 289 StoreInst *S = Builder.CreateStore(ConstantInt::get(ITy, Fill), Dest, 290 MI->isVolatile()); 291 S->setAlignment(Alignment); 292 if (isa<AtomicMemSetInst>(MI)) 293 S->setOrdering(AtomicOrdering::Unordered); 294 295 // Set the size of the copy to 0, it will be deleted on the next iteration. 296 MI->setLength(Constant::getNullValue(LenC->getType())); 297 return MI; 298 } 299 300 return nullptr; 301 } 302 303 // TODO, Obvious Missing Transforms: 304 // * Narrow width by halfs excluding zero/undef lanes 305 Value *InstCombinerImpl::simplifyMaskedLoad(IntrinsicInst &II) { 306 Value *LoadPtr = II.getArgOperand(0); 307 const Align Alignment = 308 cast<ConstantInt>(II.getArgOperand(1))->getAlignValue(); 309 310 // If the mask is all ones or undefs, this is a plain vector load of the 1st 311 // argument. 312 if (maskIsAllOneOrUndef(II.getArgOperand(2))) { 313 LoadInst *L = Builder.CreateAlignedLoad(II.getType(), LoadPtr, Alignment, 314 "unmaskedload"); 315 L->copyMetadata(II); 316 return L; 317 } 318 319 // If we can unconditionally load from this address, replace with a 320 // load/select idiom. TODO: use DT for context sensitive query 321 if (isDereferenceablePointer(LoadPtr, II.getType(), 322 II.getModule()->getDataLayout(), &II, nullptr)) { 323 LoadInst *LI = Builder.CreateAlignedLoad(II.getType(), LoadPtr, Alignment, 324 "unmaskedload"); 325 LI->copyMetadata(II); 326 return Builder.CreateSelect(II.getArgOperand(2), LI, II.getArgOperand(3)); 327 } 328 329 return nullptr; 330 } 331 332 // TODO, Obvious Missing Transforms: 333 // * Single constant active lane -> store 334 // * Narrow width by halfs excluding zero/undef lanes 335 Instruction *InstCombinerImpl::simplifyMaskedStore(IntrinsicInst &II) { 336 auto *ConstMask = dyn_cast<Constant>(II.getArgOperand(3)); 337 if (!ConstMask) 338 return nullptr; 339 340 // If the mask is all zeros, this instruction does nothing. 341 if (ConstMask->isNullValue()) 342 return eraseInstFromFunction(II); 343 344 // If the mask is all ones, this is a plain vector store of the 1st argument. 345 if (ConstMask->isAllOnesValue()) { 346 Value *StorePtr = II.getArgOperand(1); 347 Align Alignment = cast<ConstantInt>(II.getArgOperand(2))->getAlignValue(); 348 StoreInst *S = 349 new StoreInst(II.getArgOperand(0), StorePtr, false, Alignment); 350 S->copyMetadata(II); 351 return S; 352 } 353 354 if (isa<ScalableVectorType>(ConstMask->getType())) 355 return nullptr; 356 357 // Use masked off lanes to simplify operands via SimplifyDemandedVectorElts 358 APInt DemandedElts = possiblyDemandedEltsInMask(ConstMask); 359 APInt UndefElts(DemandedElts.getBitWidth(), 0); 360 if (Value *V = 361 SimplifyDemandedVectorElts(II.getOperand(0), DemandedElts, UndefElts)) 362 return replaceOperand(II, 0, V); 363 364 return nullptr; 365 } 366 367 // TODO, Obvious Missing Transforms: 368 // * Single constant active lane load -> load 369 // * Dereferenceable address & few lanes -> scalarize speculative load/selects 370 // * Adjacent vector addresses -> masked.load 371 // * Narrow width by halfs excluding zero/undef lanes 372 // * Vector incrementing address -> vector masked load 373 Instruction *InstCombinerImpl::simplifyMaskedGather(IntrinsicInst &II) { 374 auto *ConstMask = dyn_cast<Constant>(II.getArgOperand(2)); 375 if (!ConstMask) 376 return nullptr; 377 378 // Vector splat address w/known mask -> scalar load 379 // Fold the gather to load the source vector first lane 380 // because it is reloading the same value each time 381 if (ConstMask->isAllOnesValue()) 382 if (auto *SplatPtr = getSplatValue(II.getArgOperand(0))) { 383 auto *VecTy = cast<VectorType>(II.getType()); 384 const Align Alignment = 385 cast<ConstantInt>(II.getArgOperand(1))->getAlignValue(); 386 LoadInst *L = Builder.CreateAlignedLoad(VecTy->getElementType(), SplatPtr, 387 Alignment, "load.scalar"); 388 Value *Shuf = 389 Builder.CreateVectorSplat(VecTy->getElementCount(), L, "broadcast"); 390 return replaceInstUsesWith(II, cast<Instruction>(Shuf)); 391 } 392 393 return nullptr; 394 } 395 396 // TODO, Obvious Missing Transforms: 397 // * Single constant active lane -> store 398 // * Adjacent vector addresses -> masked.store 399 // * Narrow store width by halfs excluding zero/undef lanes 400 // * Vector incrementing address -> vector masked store 401 Instruction *InstCombinerImpl::simplifyMaskedScatter(IntrinsicInst &II) { 402 auto *ConstMask = dyn_cast<Constant>(II.getArgOperand(3)); 403 if (!ConstMask) 404 return nullptr; 405 406 // If the mask is all zeros, a scatter does nothing. 407 if (ConstMask->isNullValue()) 408 return eraseInstFromFunction(II); 409 410 // Vector splat address -> scalar store 411 if (auto *SplatPtr = getSplatValue(II.getArgOperand(1))) { 412 // scatter(splat(value), splat(ptr), non-zero-mask) -> store value, ptr 413 if (auto *SplatValue = getSplatValue(II.getArgOperand(0))) { 414 Align Alignment = cast<ConstantInt>(II.getArgOperand(2))->getAlignValue(); 415 StoreInst *S = 416 new StoreInst(SplatValue, SplatPtr, /*IsVolatile=*/false, Alignment); 417 S->copyMetadata(II); 418 return S; 419 } 420 // scatter(vector, splat(ptr), splat(true)) -> store extract(vector, 421 // lastlane), ptr 422 if (ConstMask->isAllOnesValue()) { 423 Align Alignment = cast<ConstantInt>(II.getArgOperand(2))->getAlignValue(); 424 VectorType *WideLoadTy = cast<VectorType>(II.getArgOperand(1)->getType()); 425 ElementCount VF = WideLoadTy->getElementCount(); 426 Constant *EC = 427 ConstantInt::get(Builder.getInt32Ty(), VF.getKnownMinValue()); 428 Value *RunTimeVF = VF.isScalable() ? Builder.CreateVScale(EC) : EC; 429 Value *LastLane = Builder.CreateSub(RunTimeVF, Builder.getInt32(1)); 430 Value *Extract = 431 Builder.CreateExtractElement(II.getArgOperand(0), LastLane); 432 StoreInst *S = 433 new StoreInst(Extract, SplatPtr, /*IsVolatile=*/false, Alignment); 434 S->copyMetadata(II); 435 return S; 436 } 437 } 438 if (isa<ScalableVectorType>(ConstMask->getType())) 439 return nullptr; 440 441 // Use masked off lanes to simplify operands via SimplifyDemandedVectorElts 442 APInt DemandedElts = possiblyDemandedEltsInMask(ConstMask); 443 APInt UndefElts(DemandedElts.getBitWidth(), 0); 444 if (Value *V = 445 SimplifyDemandedVectorElts(II.getOperand(0), DemandedElts, UndefElts)) 446 return replaceOperand(II, 0, V); 447 if (Value *V = 448 SimplifyDemandedVectorElts(II.getOperand(1), DemandedElts, UndefElts)) 449 return replaceOperand(II, 1, V); 450 451 return nullptr; 452 } 453 454 /// This function transforms launder.invariant.group and strip.invariant.group 455 /// like: 456 /// launder(launder(%x)) -> launder(%x) (the result is not the argument) 457 /// launder(strip(%x)) -> launder(%x) 458 /// strip(strip(%x)) -> strip(%x) (the result is not the argument) 459 /// strip(launder(%x)) -> strip(%x) 460 /// This is legal because it preserves the most recent information about 461 /// the presence or absence of invariant.group. 462 static Instruction *simplifyInvariantGroupIntrinsic(IntrinsicInst &II, 463 InstCombinerImpl &IC) { 464 auto *Arg = II.getArgOperand(0); 465 auto *StrippedArg = Arg->stripPointerCasts(); 466 auto *StrippedInvariantGroupsArg = StrippedArg; 467 while (auto *Intr = dyn_cast<IntrinsicInst>(StrippedInvariantGroupsArg)) { 468 if (Intr->getIntrinsicID() != Intrinsic::launder_invariant_group && 469 Intr->getIntrinsicID() != Intrinsic::strip_invariant_group) 470 break; 471 StrippedInvariantGroupsArg = Intr->getArgOperand(0)->stripPointerCasts(); 472 } 473 if (StrippedArg == StrippedInvariantGroupsArg) 474 return nullptr; // No launders/strips to remove. 475 476 Value *Result = nullptr; 477 478 if (II.getIntrinsicID() == Intrinsic::launder_invariant_group) 479 Result = IC.Builder.CreateLaunderInvariantGroup(StrippedInvariantGroupsArg); 480 else if (II.getIntrinsicID() == Intrinsic::strip_invariant_group) 481 Result = IC.Builder.CreateStripInvariantGroup(StrippedInvariantGroupsArg); 482 else 483 llvm_unreachable( 484 "simplifyInvariantGroupIntrinsic only handles launder and strip"); 485 if (Result->getType()->getPointerAddressSpace() != 486 II.getType()->getPointerAddressSpace()) 487 Result = IC.Builder.CreateAddrSpaceCast(Result, II.getType()); 488 if (Result->getType() != II.getType()) 489 Result = IC.Builder.CreateBitCast(Result, II.getType()); 490 491 return cast<Instruction>(Result); 492 } 493 494 static Instruction *foldCttzCtlz(IntrinsicInst &II, InstCombinerImpl &IC) { 495 assert((II.getIntrinsicID() == Intrinsic::cttz || 496 II.getIntrinsicID() == Intrinsic::ctlz) && 497 "Expected cttz or ctlz intrinsic"); 498 bool IsTZ = II.getIntrinsicID() == Intrinsic::cttz; 499 Value *Op0 = II.getArgOperand(0); 500 Value *Op1 = II.getArgOperand(1); 501 Value *X; 502 // ctlz(bitreverse(x)) -> cttz(x) 503 // cttz(bitreverse(x)) -> ctlz(x) 504 if (match(Op0, m_BitReverse(m_Value(X)))) { 505 Intrinsic::ID ID = IsTZ ? Intrinsic::ctlz : Intrinsic::cttz; 506 Function *F = Intrinsic::getDeclaration(II.getModule(), ID, II.getType()); 507 return CallInst::Create(F, {X, II.getArgOperand(1)}); 508 } 509 510 if (II.getType()->isIntOrIntVectorTy(1)) { 511 // ctlz/cttz i1 Op0 --> not Op0 512 if (match(Op1, m_Zero())) 513 return BinaryOperator::CreateNot(Op0); 514 // If zero is poison, then the input can be assumed to be "true", so the 515 // instruction simplifies to "false". 516 assert(match(Op1, m_One()) && "Expected ctlz/cttz operand to be 0 or 1"); 517 return IC.replaceInstUsesWith(II, ConstantInt::getNullValue(II.getType())); 518 } 519 520 // If the operand is a select with constant arm(s), try to hoist ctlz/cttz. 521 if (auto *Sel = dyn_cast<SelectInst>(Op0)) 522 if (Instruction *R = IC.FoldOpIntoSelect(II, Sel)) 523 return R; 524 525 if (IsTZ) { 526 // cttz(-x) -> cttz(x) 527 if (match(Op0, m_Neg(m_Value(X)))) 528 return IC.replaceOperand(II, 0, X); 529 530 // cttz(sext(x)) -> cttz(zext(x)) 531 if (match(Op0, m_OneUse(m_SExt(m_Value(X))))) { 532 auto *Zext = IC.Builder.CreateZExt(X, II.getType()); 533 auto *CttzZext = 534 IC.Builder.CreateBinaryIntrinsic(Intrinsic::cttz, Zext, Op1); 535 return IC.replaceInstUsesWith(II, CttzZext); 536 } 537 538 // Zext doesn't change the number of trailing zeros, so narrow: 539 // cttz(zext(x)) -> zext(cttz(x)) if the 'ZeroIsPoison' parameter is 'true'. 540 if (match(Op0, m_OneUse(m_ZExt(m_Value(X)))) && match(Op1, m_One())) { 541 auto *Cttz = IC.Builder.CreateBinaryIntrinsic(Intrinsic::cttz, X, 542 IC.Builder.getTrue()); 543 auto *ZextCttz = IC.Builder.CreateZExt(Cttz, II.getType()); 544 return IC.replaceInstUsesWith(II, ZextCttz); 545 } 546 547 // cttz(abs(x)) -> cttz(x) 548 // cttz(nabs(x)) -> cttz(x) 549 Value *Y; 550 SelectPatternFlavor SPF = matchSelectPattern(Op0, X, Y).Flavor; 551 if (SPF == SPF_ABS || SPF == SPF_NABS) 552 return IC.replaceOperand(II, 0, X); 553 554 if (match(Op0, m_Intrinsic<Intrinsic::abs>(m_Value(X)))) 555 return IC.replaceOperand(II, 0, X); 556 } 557 558 KnownBits Known = IC.computeKnownBits(Op0, 0, &II); 559 560 // Create a mask for bits above (ctlz) or below (cttz) the first known one. 561 unsigned PossibleZeros = IsTZ ? Known.countMaxTrailingZeros() 562 : Known.countMaxLeadingZeros(); 563 unsigned DefiniteZeros = IsTZ ? Known.countMinTrailingZeros() 564 : Known.countMinLeadingZeros(); 565 566 // If all bits above (ctlz) or below (cttz) the first known one are known 567 // zero, this value is constant. 568 // FIXME: This should be in InstSimplify because we're replacing an 569 // instruction with a constant. 570 if (PossibleZeros == DefiniteZeros) { 571 auto *C = ConstantInt::get(Op0->getType(), DefiniteZeros); 572 return IC.replaceInstUsesWith(II, C); 573 } 574 575 // If the input to cttz/ctlz is known to be non-zero, 576 // then change the 'ZeroIsPoison' parameter to 'true' 577 // because we know the zero behavior can't affect the result. 578 if (!Known.One.isZero() || 579 isKnownNonZero(Op0, IC.getDataLayout(), 0, &IC.getAssumptionCache(), &II, 580 &IC.getDominatorTree())) { 581 if (!match(II.getArgOperand(1), m_One())) 582 return IC.replaceOperand(II, 1, IC.Builder.getTrue()); 583 } 584 585 // Add range metadata since known bits can't completely reflect what we know. 586 // TODO: Handle splat vectors. 587 auto *IT = dyn_cast<IntegerType>(Op0->getType()); 588 if (IT && IT->getBitWidth() != 1 && !II.getMetadata(LLVMContext::MD_range)) { 589 Metadata *LowAndHigh[] = { 590 ConstantAsMetadata::get(ConstantInt::get(IT, DefiniteZeros)), 591 ConstantAsMetadata::get(ConstantInt::get(IT, PossibleZeros + 1))}; 592 II.setMetadata(LLVMContext::MD_range, 593 MDNode::get(II.getContext(), LowAndHigh)); 594 return &II; 595 } 596 597 return nullptr; 598 } 599 600 static Instruction *foldCtpop(IntrinsicInst &II, InstCombinerImpl &IC) { 601 assert(II.getIntrinsicID() == Intrinsic::ctpop && 602 "Expected ctpop intrinsic"); 603 Type *Ty = II.getType(); 604 unsigned BitWidth = Ty->getScalarSizeInBits(); 605 Value *Op0 = II.getArgOperand(0); 606 Value *X, *Y; 607 608 // ctpop(bitreverse(x)) -> ctpop(x) 609 // ctpop(bswap(x)) -> ctpop(x) 610 if (match(Op0, m_BitReverse(m_Value(X))) || match(Op0, m_BSwap(m_Value(X)))) 611 return IC.replaceOperand(II, 0, X); 612 613 // ctpop(rot(x)) -> ctpop(x) 614 if ((match(Op0, m_FShl(m_Value(X), m_Value(Y), m_Value())) || 615 match(Op0, m_FShr(m_Value(X), m_Value(Y), m_Value()))) && 616 X == Y) 617 return IC.replaceOperand(II, 0, X); 618 619 // ctpop(x | -x) -> bitwidth - cttz(x, false) 620 if (Op0->hasOneUse() && 621 match(Op0, m_c_Or(m_Value(X), m_Neg(m_Deferred(X))))) { 622 Function *F = 623 Intrinsic::getDeclaration(II.getModule(), Intrinsic::cttz, Ty); 624 auto *Cttz = IC.Builder.CreateCall(F, {X, IC.Builder.getFalse()}); 625 auto *Bw = ConstantInt::get(Ty, APInt(BitWidth, BitWidth)); 626 return IC.replaceInstUsesWith(II, IC.Builder.CreateSub(Bw, Cttz)); 627 } 628 629 // ctpop(~x & (x - 1)) -> cttz(x, false) 630 if (match(Op0, 631 m_c_And(m_Not(m_Value(X)), m_Add(m_Deferred(X), m_AllOnes())))) { 632 Function *F = 633 Intrinsic::getDeclaration(II.getModule(), Intrinsic::cttz, Ty); 634 return CallInst::Create(F, {X, IC.Builder.getFalse()}); 635 } 636 637 // Zext doesn't change the number of set bits, so narrow: 638 // ctpop (zext X) --> zext (ctpop X) 639 if (match(Op0, m_OneUse(m_ZExt(m_Value(X))))) { 640 Value *NarrowPop = IC.Builder.CreateUnaryIntrinsic(Intrinsic::ctpop, X); 641 return CastInst::Create(Instruction::ZExt, NarrowPop, Ty); 642 } 643 644 // If the operand is a select with constant arm(s), try to hoist ctpop. 645 if (auto *Sel = dyn_cast<SelectInst>(Op0)) 646 if (Instruction *R = IC.FoldOpIntoSelect(II, Sel)) 647 return R; 648 649 KnownBits Known(BitWidth); 650 IC.computeKnownBits(Op0, Known, 0, &II); 651 652 // If all bits are zero except for exactly one fixed bit, then the result 653 // must be 0 or 1, and we can get that answer by shifting to LSB: 654 // ctpop (X & 32) --> (X & 32) >> 5 655 if ((~Known.Zero).isPowerOf2()) 656 return BinaryOperator::CreateLShr( 657 Op0, ConstantInt::get(Ty, (~Known.Zero).exactLogBase2())); 658 659 // FIXME: Try to simplify vectors of integers. 660 auto *IT = dyn_cast<IntegerType>(Ty); 661 if (!IT) 662 return nullptr; 663 664 // Add range metadata since known bits can't completely reflect what we know. 665 unsigned MinCount = Known.countMinPopulation(); 666 unsigned MaxCount = Known.countMaxPopulation(); 667 if (IT->getBitWidth() != 1 && !II.getMetadata(LLVMContext::MD_range)) { 668 Metadata *LowAndHigh[] = { 669 ConstantAsMetadata::get(ConstantInt::get(IT, MinCount)), 670 ConstantAsMetadata::get(ConstantInt::get(IT, MaxCount + 1))}; 671 II.setMetadata(LLVMContext::MD_range, 672 MDNode::get(II.getContext(), LowAndHigh)); 673 return &II; 674 } 675 676 return nullptr; 677 } 678 679 /// Convert a table lookup to shufflevector if the mask is constant. 680 /// This could benefit tbl1 if the mask is { 7,6,5,4,3,2,1,0 }, in 681 /// which case we could lower the shufflevector with rev64 instructions 682 /// as it's actually a byte reverse. 683 static Value *simplifyNeonTbl1(const IntrinsicInst &II, 684 InstCombiner::BuilderTy &Builder) { 685 // Bail out if the mask is not a constant. 686 auto *C = dyn_cast<Constant>(II.getArgOperand(1)); 687 if (!C) 688 return nullptr; 689 690 auto *VecTy = cast<FixedVectorType>(II.getType()); 691 unsigned NumElts = VecTy->getNumElements(); 692 693 // Only perform this transformation for <8 x i8> vector types. 694 if (!VecTy->getElementType()->isIntegerTy(8) || NumElts != 8) 695 return nullptr; 696 697 int Indexes[8]; 698 699 for (unsigned I = 0; I < NumElts; ++I) { 700 Constant *COp = C->getAggregateElement(I); 701 702 if (!COp || !isa<ConstantInt>(COp)) 703 return nullptr; 704 705 Indexes[I] = cast<ConstantInt>(COp)->getLimitedValue(); 706 707 // Make sure the mask indices are in range. 708 if ((unsigned)Indexes[I] >= NumElts) 709 return nullptr; 710 } 711 712 auto *V1 = II.getArgOperand(0); 713 auto *V2 = Constant::getNullValue(V1->getType()); 714 return Builder.CreateShuffleVector(V1, V2, makeArrayRef(Indexes)); 715 } 716 717 // Returns true iff the 2 intrinsics have the same operands, limiting the 718 // comparison to the first NumOperands. 719 static bool haveSameOperands(const IntrinsicInst &I, const IntrinsicInst &E, 720 unsigned NumOperands) { 721 assert(I.arg_size() >= NumOperands && "Not enough operands"); 722 assert(E.arg_size() >= NumOperands && "Not enough operands"); 723 for (unsigned i = 0; i < NumOperands; i++) 724 if (I.getArgOperand(i) != E.getArgOperand(i)) 725 return false; 726 return true; 727 } 728 729 // Remove trivially empty start/end intrinsic ranges, i.e. a start 730 // immediately followed by an end (ignoring debuginfo or other 731 // start/end intrinsics in between). As this handles only the most trivial 732 // cases, tracking the nesting level is not needed: 733 // 734 // call @llvm.foo.start(i1 0) 735 // call @llvm.foo.start(i1 0) ; This one won't be skipped: it will be removed 736 // call @llvm.foo.end(i1 0) 737 // call @llvm.foo.end(i1 0) ; &I 738 static bool 739 removeTriviallyEmptyRange(IntrinsicInst &EndI, InstCombinerImpl &IC, 740 std::function<bool(const IntrinsicInst &)> IsStart) { 741 // We start from the end intrinsic and scan backwards, so that InstCombine 742 // has already processed (and potentially removed) all the instructions 743 // before the end intrinsic. 744 BasicBlock::reverse_iterator BI(EndI), BE(EndI.getParent()->rend()); 745 for (; BI != BE; ++BI) { 746 if (auto *I = dyn_cast<IntrinsicInst>(&*BI)) { 747 if (I->isDebugOrPseudoInst() || 748 I->getIntrinsicID() == EndI.getIntrinsicID()) 749 continue; 750 if (IsStart(*I)) { 751 if (haveSameOperands(EndI, *I, EndI.arg_size())) { 752 IC.eraseInstFromFunction(*I); 753 IC.eraseInstFromFunction(EndI); 754 return true; 755 } 756 // Skip start intrinsics that don't pair with this end intrinsic. 757 continue; 758 } 759 } 760 break; 761 } 762 763 return false; 764 } 765 766 Instruction *InstCombinerImpl::visitVAEndInst(VAEndInst &I) { 767 removeTriviallyEmptyRange(I, *this, [](const IntrinsicInst &I) { 768 return I.getIntrinsicID() == Intrinsic::vastart || 769 I.getIntrinsicID() == Intrinsic::vacopy; 770 }); 771 return nullptr; 772 } 773 774 static CallInst *canonicalizeConstantArg0ToArg1(CallInst &Call) { 775 assert(Call.arg_size() > 1 && "Need at least 2 args to swap"); 776 Value *Arg0 = Call.getArgOperand(0), *Arg1 = Call.getArgOperand(1); 777 if (isa<Constant>(Arg0) && !isa<Constant>(Arg1)) { 778 Call.setArgOperand(0, Arg1); 779 Call.setArgOperand(1, Arg0); 780 return &Call; 781 } 782 return nullptr; 783 } 784 785 /// Creates a result tuple for an overflow intrinsic \p II with a given 786 /// \p Result and a constant \p Overflow value. 787 static Instruction *createOverflowTuple(IntrinsicInst *II, Value *Result, 788 Constant *Overflow) { 789 Constant *V[] = {UndefValue::get(Result->getType()), Overflow}; 790 StructType *ST = cast<StructType>(II->getType()); 791 Constant *Struct = ConstantStruct::get(ST, V); 792 return InsertValueInst::Create(Struct, Result, 0); 793 } 794 795 Instruction * 796 InstCombinerImpl::foldIntrinsicWithOverflowCommon(IntrinsicInst *II) { 797 WithOverflowInst *WO = cast<WithOverflowInst>(II); 798 Value *OperationResult = nullptr; 799 Constant *OverflowResult = nullptr; 800 if (OptimizeOverflowCheck(WO->getBinaryOp(), WO->isSigned(), WO->getLHS(), 801 WO->getRHS(), *WO, OperationResult, OverflowResult)) 802 return createOverflowTuple(WO, OperationResult, OverflowResult); 803 return nullptr; 804 } 805 806 static Optional<bool> getKnownSign(Value *Op, Instruction *CxtI, 807 const DataLayout &DL, AssumptionCache *AC, 808 DominatorTree *DT) { 809 KnownBits Known = computeKnownBits(Op, DL, 0, AC, CxtI, DT); 810 if (Known.isNonNegative()) 811 return false; 812 if (Known.isNegative()) 813 return true; 814 815 Value *X, *Y; 816 if (match(Op, m_NSWSub(m_Value(X), m_Value(Y)))) 817 return isImpliedByDomCondition(ICmpInst::ICMP_SLT, X, Y, CxtI, DL); 818 819 return isImpliedByDomCondition( 820 ICmpInst::ICMP_SLT, Op, Constant::getNullValue(Op->getType()), CxtI, DL); 821 } 822 823 /// Try to canonicalize min/max(X + C0, C1) as min/max(X, C1 - C0) + C0. This 824 /// can trigger other combines. 825 static Instruction *moveAddAfterMinMax(IntrinsicInst *II, 826 InstCombiner::BuilderTy &Builder) { 827 Intrinsic::ID MinMaxID = II->getIntrinsicID(); 828 assert((MinMaxID == Intrinsic::smax || MinMaxID == Intrinsic::smin || 829 MinMaxID == Intrinsic::umax || MinMaxID == Intrinsic::umin) && 830 "Expected a min or max intrinsic"); 831 832 // TODO: Match vectors with undef elements, but undef may not propagate. 833 Value *Op0 = II->getArgOperand(0), *Op1 = II->getArgOperand(1); 834 Value *X; 835 const APInt *C0, *C1; 836 if (!match(Op0, m_OneUse(m_Add(m_Value(X), m_APInt(C0)))) || 837 !match(Op1, m_APInt(C1))) 838 return nullptr; 839 840 // Check for necessary no-wrap and overflow constraints. 841 bool IsSigned = MinMaxID == Intrinsic::smax || MinMaxID == Intrinsic::smin; 842 auto *Add = cast<BinaryOperator>(Op0); 843 if ((IsSigned && !Add->hasNoSignedWrap()) || 844 (!IsSigned && !Add->hasNoUnsignedWrap())) 845 return nullptr; 846 847 // If the constant difference overflows, then instsimplify should reduce the 848 // min/max to the add or C1. 849 bool Overflow; 850 APInt CDiff = 851 IsSigned ? C1->ssub_ov(*C0, Overflow) : C1->usub_ov(*C0, Overflow); 852 assert(!Overflow && "Expected simplify of min/max"); 853 854 // min/max (add X, C0), C1 --> add (min/max X, C1 - C0), C0 855 // Note: the "mismatched" no-overflow setting does not propagate. 856 Constant *NewMinMaxC = ConstantInt::get(II->getType(), CDiff); 857 Value *NewMinMax = Builder.CreateBinaryIntrinsic(MinMaxID, X, NewMinMaxC); 858 return IsSigned ? BinaryOperator::CreateNSWAdd(NewMinMax, Add->getOperand(1)) 859 : BinaryOperator::CreateNUWAdd(NewMinMax, Add->getOperand(1)); 860 } 861 /// Match a sadd_sat or ssub_sat which is using min/max to clamp the value. 862 Instruction *InstCombinerImpl::matchSAddSubSat(IntrinsicInst &MinMax1) { 863 Type *Ty = MinMax1.getType(); 864 865 // We are looking for a tree of: 866 // max(INT_MIN, min(INT_MAX, add(sext(A), sext(B)))) 867 // Where the min and max could be reversed 868 Instruction *MinMax2; 869 BinaryOperator *AddSub; 870 const APInt *MinValue, *MaxValue; 871 if (match(&MinMax1, m_SMin(m_Instruction(MinMax2), m_APInt(MaxValue)))) { 872 if (!match(MinMax2, m_SMax(m_BinOp(AddSub), m_APInt(MinValue)))) 873 return nullptr; 874 } else if (match(&MinMax1, 875 m_SMax(m_Instruction(MinMax2), m_APInt(MinValue)))) { 876 if (!match(MinMax2, m_SMin(m_BinOp(AddSub), m_APInt(MaxValue)))) 877 return nullptr; 878 } else 879 return nullptr; 880 881 // Check that the constants clamp a saturate, and that the new type would be 882 // sensible to convert to. 883 if (!(*MaxValue + 1).isPowerOf2() || -*MinValue != *MaxValue + 1) 884 return nullptr; 885 // In what bitwidth can this be treated as saturating arithmetics? 886 unsigned NewBitWidth = (*MaxValue + 1).logBase2() + 1; 887 // FIXME: This isn't quite right for vectors, but using the scalar type is a 888 // good first approximation for what should be done there. 889 if (!shouldChangeType(Ty->getScalarType()->getIntegerBitWidth(), NewBitWidth)) 890 return nullptr; 891 892 // Also make sure that the inner min/max and the add/sub have one use. 893 if (!MinMax2->hasOneUse() || !AddSub->hasOneUse()) 894 return nullptr; 895 896 // Create the new type (which can be a vector type) 897 Type *NewTy = Ty->getWithNewBitWidth(NewBitWidth); 898 899 Intrinsic::ID IntrinsicID; 900 if (AddSub->getOpcode() == Instruction::Add) 901 IntrinsicID = Intrinsic::sadd_sat; 902 else if (AddSub->getOpcode() == Instruction::Sub) 903 IntrinsicID = Intrinsic::ssub_sat; 904 else 905 return nullptr; 906 907 // The two operands of the add/sub must be nsw-truncatable to the NewTy. This 908 // is usually achieved via a sext from a smaller type. 909 if (ComputeMaxSignificantBits(AddSub->getOperand(0), 0, AddSub) > 910 NewBitWidth || 911 ComputeMaxSignificantBits(AddSub->getOperand(1), 0, AddSub) > NewBitWidth) 912 return nullptr; 913 914 // Finally create and return the sat intrinsic, truncated to the new type 915 Function *F = Intrinsic::getDeclaration(MinMax1.getModule(), IntrinsicID, NewTy); 916 Value *AT = Builder.CreateTrunc(AddSub->getOperand(0), NewTy); 917 Value *BT = Builder.CreateTrunc(AddSub->getOperand(1), NewTy); 918 Value *Sat = Builder.CreateCall(F, {AT, BT}); 919 return CastInst::Create(Instruction::SExt, Sat, Ty); 920 } 921 922 923 /// If we have a clamp pattern like max (min X, 42), 41 -- where the output 924 /// can only be one of two possible constant values -- turn that into a select 925 /// of constants. 926 static Instruction *foldClampRangeOfTwo(IntrinsicInst *II, 927 InstCombiner::BuilderTy &Builder) { 928 Value *I0 = II->getArgOperand(0), *I1 = II->getArgOperand(1); 929 Value *X; 930 const APInt *C0, *C1; 931 if (!match(I1, m_APInt(C1)) || !I0->hasOneUse()) 932 return nullptr; 933 934 CmpInst::Predicate Pred = CmpInst::BAD_ICMP_PREDICATE; 935 switch (II->getIntrinsicID()) { 936 case Intrinsic::smax: 937 if (match(I0, m_SMin(m_Value(X), m_APInt(C0))) && *C0 == *C1 + 1) 938 Pred = ICmpInst::ICMP_SGT; 939 break; 940 case Intrinsic::smin: 941 if (match(I0, m_SMax(m_Value(X), m_APInt(C0))) && *C1 == *C0 + 1) 942 Pred = ICmpInst::ICMP_SLT; 943 break; 944 case Intrinsic::umax: 945 if (match(I0, m_UMin(m_Value(X), m_APInt(C0))) && *C0 == *C1 + 1) 946 Pred = ICmpInst::ICMP_UGT; 947 break; 948 case Intrinsic::umin: 949 if (match(I0, m_UMax(m_Value(X), m_APInt(C0))) && *C1 == *C0 + 1) 950 Pred = ICmpInst::ICMP_ULT; 951 break; 952 default: 953 llvm_unreachable("Expected min/max intrinsic"); 954 } 955 if (Pred == CmpInst::BAD_ICMP_PREDICATE) 956 return nullptr; 957 958 // max (min X, 42), 41 --> X > 41 ? 42 : 41 959 // min (max X, 42), 43 --> X < 43 ? 42 : 43 960 Value *Cmp = Builder.CreateICmp(Pred, X, I1); 961 return SelectInst::Create(Cmp, ConstantInt::get(II->getType(), *C0), I1); 962 } 963 964 /// If this min/max has a constant operand and an operand that is a matching 965 /// min/max with a constant operand, constant-fold the 2 constant operands. 966 static Instruction *reassociateMinMaxWithConstants(IntrinsicInst *II) { 967 Intrinsic::ID MinMaxID = II->getIntrinsicID(); 968 auto *LHS = dyn_cast<IntrinsicInst>(II->getArgOperand(0)); 969 if (!LHS || LHS->getIntrinsicID() != MinMaxID) 970 return nullptr; 971 972 Constant *C0, *C1; 973 if (!match(LHS->getArgOperand(1), m_ImmConstant(C0)) || 974 !match(II->getArgOperand(1), m_ImmConstant(C1))) 975 return nullptr; 976 977 // max (max X, C0), C1 --> max X, (max C0, C1) --> max X, NewC 978 ICmpInst::Predicate Pred = MinMaxIntrinsic::getPredicate(MinMaxID); 979 Constant *CondC = ConstantExpr::getICmp(Pred, C0, C1); 980 Constant *NewC = ConstantExpr::getSelect(CondC, C0, C1); 981 982 Module *Mod = II->getModule(); 983 Function *MinMax = Intrinsic::getDeclaration(Mod, MinMaxID, II->getType()); 984 return CallInst::Create(MinMax, {LHS->getArgOperand(0), NewC}); 985 } 986 987 /// If this min/max has a matching min/max operand with a constant, try to push 988 /// the constant operand into this instruction. This can enable more folds. 989 static Instruction * 990 reassociateMinMaxWithConstantInOperand(IntrinsicInst *II, 991 InstCombiner::BuilderTy &Builder) { 992 // Match and capture a min/max operand candidate. 993 Value *X, *Y; 994 Constant *C; 995 Instruction *Inner; 996 if (!match(II, m_c_MaxOrMin(m_OneUse(m_CombineAnd( 997 m_Instruction(Inner), 998 m_MaxOrMin(m_Value(X), m_ImmConstant(C)))), 999 m_Value(Y)))) 1000 return nullptr; 1001 1002 // The inner op must match. Check for constants to avoid infinite loops. 1003 Intrinsic::ID MinMaxID = II->getIntrinsicID(); 1004 auto *InnerMM = dyn_cast<IntrinsicInst>(Inner); 1005 if (!InnerMM || InnerMM->getIntrinsicID() != MinMaxID || 1006 match(X, m_ImmConstant()) || match(Y, m_ImmConstant())) 1007 return nullptr; 1008 1009 // max (max X, C), Y --> max (max X, Y), C 1010 Function *MinMax = 1011 Intrinsic::getDeclaration(II->getModule(), MinMaxID, II->getType()); 1012 Value *NewInner = Builder.CreateBinaryIntrinsic(MinMaxID, X, Y); 1013 NewInner->takeName(Inner); 1014 return CallInst::Create(MinMax, {NewInner, C}); 1015 } 1016 1017 /// Reduce a sequence of min/max intrinsics with a common operand. 1018 static Instruction *factorizeMinMaxTree(IntrinsicInst *II) { 1019 // Match 3 of the same min/max ops. Example: umin(umin(), umin()). 1020 auto *LHS = dyn_cast<IntrinsicInst>(II->getArgOperand(0)); 1021 auto *RHS = dyn_cast<IntrinsicInst>(II->getArgOperand(1)); 1022 Intrinsic::ID MinMaxID = II->getIntrinsicID(); 1023 if (!LHS || !RHS || LHS->getIntrinsicID() != MinMaxID || 1024 RHS->getIntrinsicID() != MinMaxID || 1025 (!LHS->hasOneUse() && !RHS->hasOneUse())) 1026 return nullptr; 1027 1028 Value *A = LHS->getArgOperand(0); 1029 Value *B = LHS->getArgOperand(1); 1030 Value *C = RHS->getArgOperand(0); 1031 Value *D = RHS->getArgOperand(1); 1032 1033 // Look for a common operand. 1034 Value *MinMaxOp = nullptr; 1035 Value *ThirdOp = nullptr; 1036 if (LHS->hasOneUse()) { 1037 // If the LHS is only used in this chain and the RHS is used outside of it, 1038 // reuse the RHS min/max because that will eliminate the LHS. 1039 if (D == A || C == A) { 1040 // min(min(a, b), min(c, a)) --> min(min(c, a), b) 1041 // min(min(a, b), min(a, d)) --> min(min(a, d), b) 1042 MinMaxOp = RHS; 1043 ThirdOp = B; 1044 } else if (D == B || C == B) { 1045 // min(min(a, b), min(c, b)) --> min(min(c, b), a) 1046 // min(min(a, b), min(b, d)) --> min(min(b, d), a) 1047 MinMaxOp = RHS; 1048 ThirdOp = A; 1049 } 1050 } else { 1051 assert(RHS->hasOneUse() && "Expected one-use operand"); 1052 // Reuse the LHS. This will eliminate the RHS. 1053 if (D == A || D == B) { 1054 // min(min(a, b), min(c, a)) --> min(min(a, b), c) 1055 // min(min(a, b), min(c, b)) --> min(min(a, b), c) 1056 MinMaxOp = LHS; 1057 ThirdOp = C; 1058 } else if (C == A || C == B) { 1059 // min(min(a, b), min(b, d)) --> min(min(a, b), d) 1060 // min(min(a, b), min(c, b)) --> min(min(a, b), d) 1061 MinMaxOp = LHS; 1062 ThirdOp = D; 1063 } 1064 } 1065 1066 if (!MinMaxOp || !ThirdOp) 1067 return nullptr; 1068 1069 Module *Mod = II->getModule(); 1070 Function *MinMax = Intrinsic::getDeclaration(Mod, MinMaxID, II->getType()); 1071 return CallInst::Create(MinMax, { MinMaxOp, ThirdOp }); 1072 } 1073 1074 /// CallInst simplification. This mostly only handles folding of intrinsic 1075 /// instructions. For normal calls, it allows visitCallBase to do the heavy 1076 /// lifting. 1077 Instruction *InstCombinerImpl::visitCallInst(CallInst &CI) { 1078 // Don't try to simplify calls without uses. It will not do anything useful, 1079 // but will result in the following folds being skipped. 1080 if (!CI.use_empty()) 1081 if (Value *V = SimplifyCall(&CI, SQ.getWithInstruction(&CI))) 1082 return replaceInstUsesWith(CI, V); 1083 1084 if (isFreeCall(&CI, &TLI)) 1085 return visitFree(CI); 1086 1087 // If the caller function (i.e. us, the function that contains this CallInst) 1088 // is nounwind, mark the call as nounwind, even if the callee isn't. 1089 if (CI.getFunction()->doesNotThrow() && !CI.doesNotThrow()) { 1090 CI.setDoesNotThrow(); 1091 return &CI; 1092 } 1093 1094 IntrinsicInst *II = dyn_cast<IntrinsicInst>(&CI); 1095 if (!II) return visitCallBase(CI); 1096 1097 // For atomic unordered mem intrinsics if len is not a positive or 1098 // not a multiple of element size then behavior is undefined. 1099 if (auto *AMI = dyn_cast<AtomicMemIntrinsic>(II)) 1100 if (ConstantInt *NumBytes = dyn_cast<ConstantInt>(AMI->getLength())) 1101 if (NumBytes->getSExtValue() < 0 || 1102 (NumBytes->getZExtValue() % AMI->getElementSizeInBytes() != 0)) { 1103 CreateNonTerminatorUnreachable(AMI); 1104 assert(AMI->getType()->isVoidTy() && 1105 "non void atomic unordered mem intrinsic"); 1106 return eraseInstFromFunction(*AMI); 1107 } 1108 1109 // Intrinsics cannot occur in an invoke or a callbr, so handle them here 1110 // instead of in visitCallBase. 1111 if (auto *MI = dyn_cast<AnyMemIntrinsic>(II)) { 1112 bool Changed = false; 1113 1114 // memmove/cpy/set of zero bytes is a noop. 1115 if (Constant *NumBytes = dyn_cast<Constant>(MI->getLength())) { 1116 if (NumBytes->isNullValue()) 1117 return eraseInstFromFunction(CI); 1118 } 1119 1120 // No other transformations apply to volatile transfers. 1121 if (auto *M = dyn_cast<MemIntrinsic>(MI)) 1122 if (M->isVolatile()) 1123 return nullptr; 1124 1125 // If we have a memmove and the source operation is a constant global, 1126 // then the source and dest pointers can't alias, so we can change this 1127 // into a call to memcpy. 1128 if (auto *MMI = dyn_cast<AnyMemMoveInst>(MI)) { 1129 if (GlobalVariable *GVSrc = dyn_cast<GlobalVariable>(MMI->getSource())) 1130 if (GVSrc->isConstant()) { 1131 Module *M = CI.getModule(); 1132 Intrinsic::ID MemCpyID = 1133 isa<AtomicMemMoveInst>(MMI) 1134 ? Intrinsic::memcpy_element_unordered_atomic 1135 : Intrinsic::memcpy; 1136 Type *Tys[3] = { CI.getArgOperand(0)->getType(), 1137 CI.getArgOperand(1)->getType(), 1138 CI.getArgOperand(2)->getType() }; 1139 CI.setCalledFunction(Intrinsic::getDeclaration(M, MemCpyID, Tys)); 1140 Changed = true; 1141 } 1142 } 1143 1144 if (AnyMemTransferInst *MTI = dyn_cast<AnyMemTransferInst>(MI)) { 1145 // memmove(x,x,size) -> noop. 1146 if (MTI->getSource() == MTI->getDest()) 1147 return eraseInstFromFunction(CI); 1148 } 1149 1150 // If we can determine a pointer alignment that is bigger than currently 1151 // set, update the alignment. 1152 if (auto *MTI = dyn_cast<AnyMemTransferInst>(MI)) { 1153 if (Instruction *I = SimplifyAnyMemTransfer(MTI)) 1154 return I; 1155 } else if (auto *MSI = dyn_cast<AnyMemSetInst>(MI)) { 1156 if (Instruction *I = SimplifyAnyMemSet(MSI)) 1157 return I; 1158 } 1159 1160 if (Changed) return II; 1161 } 1162 1163 // For fixed width vector result intrinsics, use the generic demanded vector 1164 // support. 1165 if (auto *IIFVTy = dyn_cast<FixedVectorType>(II->getType())) { 1166 auto VWidth = IIFVTy->getNumElements(); 1167 APInt UndefElts(VWidth, 0); 1168 APInt AllOnesEltMask(APInt::getAllOnes(VWidth)); 1169 if (Value *V = SimplifyDemandedVectorElts(II, AllOnesEltMask, UndefElts)) { 1170 if (V != II) 1171 return replaceInstUsesWith(*II, V); 1172 return II; 1173 } 1174 } 1175 1176 if (II->isCommutative()) { 1177 if (CallInst *NewCall = canonicalizeConstantArg0ToArg1(CI)) 1178 return NewCall; 1179 } 1180 1181 Intrinsic::ID IID = II->getIntrinsicID(); 1182 switch (IID) { 1183 case Intrinsic::objectsize: 1184 if (Value *V = lowerObjectSizeCall(II, DL, &TLI, AA, /*MustSucceed=*/false)) 1185 return replaceInstUsesWith(CI, V); 1186 return nullptr; 1187 case Intrinsic::abs: { 1188 Value *IIOperand = II->getArgOperand(0); 1189 bool IntMinIsPoison = cast<Constant>(II->getArgOperand(1))->isOneValue(); 1190 1191 // abs(-x) -> abs(x) 1192 // TODO: Copy nsw if it was present on the neg? 1193 Value *X; 1194 if (match(IIOperand, m_Neg(m_Value(X)))) 1195 return replaceOperand(*II, 0, X); 1196 if (match(IIOperand, m_Select(m_Value(), m_Value(X), m_Neg(m_Deferred(X))))) 1197 return replaceOperand(*II, 0, X); 1198 if (match(IIOperand, m_Select(m_Value(), m_Neg(m_Value(X)), m_Deferred(X)))) 1199 return replaceOperand(*II, 0, X); 1200 1201 if (Optional<bool> Sign = getKnownSign(IIOperand, II, DL, &AC, &DT)) { 1202 // abs(x) -> x if x >= 0 1203 if (!*Sign) 1204 return replaceInstUsesWith(*II, IIOperand); 1205 1206 // abs(x) -> -x if x < 0 1207 if (IntMinIsPoison) 1208 return BinaryOperator::CreateNSWNeg(IIOperand); 1209 return BinaryOperator::CreateNeg(IIOperand); 1210 } 1211 1212 // abs (sext X) --> zext (abs X*) 1213 // Clear the IsIntMin (nsw) bit on the abs to allow narrowing. 1214 if (match(IIOperand, m_OneUse(m_SExt(m_Value(X))))) { 1215 Value *NarrowAbs = 1216 Builder.CreateBinaryIntrinsic(Intrinsic::abs, X, Builder.getFalse()); 1217 return CastInst::Create(Instruction::ZExt, NarrowAbs, II->getType()); 1218 } 1219 1220 // Match a complicated way to check if a number is odd/even: 1221 // abs (srem X, 2) --> and X, 1 1222 const APInt *C; 1223 if (match(IIOperand, m_SRem(m_Value(X), m_APInt(C))) && *C == 2) 1224 return BinaryOperator::CreateAnd(X, ConstantInt::get(II->getType(), 1)); 1225 1226 break; 1227 } 1228 case Intrinsic::umin: { 1229 Value *I0 = II->getArgOperand(0), *I1 = II->getArgOperand(1); 1230 // umin(x, 1) == zext(x != 0) 1231 if (match(I1, m_One())) { 1232 Value *Zero = Constant::getNullValue(I0->getType()); 1233 Value *Cmp = Builder.CreateICmpNE(I0, Zero); 1234 return CastInst::Create(Instruction::ZExt, Cmp, II->getType()); 1235 } 1236 LLVM_FALLTHROUGH; 1237 } 1238 case Intrinsic::umax: { 1239 Value *I0 = II->getArgOperand(0), *I1 = II->getArgOperand(1); 1240 Value *X, *Y; 1241 if (match(I0, m_ZExt(m_Value(X))) && match(I1, m_ZExt(m_Value(Y))) && 1242 (I0->hasOneUse() || I1->hasOneUse()) && X->getType() == Y->getType()) { 1243 Value *NarrowMaxMin = Builder.CreateBinaryIntrinsic(IID, X, Y); 1244 return CastInst::Create(Instruction::ZExt, NarrowMaxMin, II->getType()); 1245 } 1246 Constant *C; 1247 if (match(I0, m_ZExt(m_Value(X))) && match(I1, m_Constant(C)) && 1248 I0->hasOneUse()) { 1249 Constant *NarrowC = ConstantExpr::getTrunc(C, X->getType()); 1250 if (ConstantExpr::getZExt(NarrowC, II->getType()) == C) { 1251 Value *NarrowMaxMin = Builder.CreateBinaryIntrinsic(IID, X, NarrowC); 1252 return CastInst::Create(Instruction::ZExt, NarrowMaxMin, II->getType()); 1253 } 1254 } 1255 // If both operands of unsigned min/max are sign-extended, it is still ok 1256 // to narrow the operation. 1257 LLVM_FALLTHROUGH; 1258 } 1259 case Intrinsic::smax: 1260 case Intrinsic::smin: { 1261 Value *I0 = II->getArgOperand(0), *I1 = II->getArgOperand(1); 1262 Value *X, *Y; 1263 if (match(I0, m_SExt(m_Value(X))) && match(I1, m_SExt(m_Value(Y))) && 1264 (I0->hasOneUse() || I1->hasOneUse()) && X->getType() == Y->getType()) { 1265 Value *NarrowMaxMin = Builder.CreateBinaryIntrinsic(IID, X, Y); 1266 return CastInst::Create(Instruction::SExt, NarrowMaxMin, II->getType()); 1267 } 1268 1269 Constant *C; 1270 if (match(I0, m_SExt(m_Value(X))) && match(I1, m_Constant(C)) && 1271 I0->hasOneUse()) { 1272 Constant *NarrowC = ConstantExpr::getTrunc(C, X->getType()); 1273 if (ConstantExpr::getSExt(NarrowC, II->getType()) == C) { 1274 Value *NarrowMaxMin = Builder.CreateBinaryIntrinsic(IID, X, NarrowC); 1275 return CastInst::Create(Instruction::SExt, NarrowMaxMin, II->getType()); 1276 } 1277 } 1278 1279 if (IID == Intrinsic::smax || IID == Intrinsic::smin) { 1280 // smax (neg nsw X), (neg nsw Y) --> neg nsw (smin X, Y) 1281 // smin (neg nsw X), (neg nsw Y) --> neg nsw (smax X, Y) 1282 // TODO: Canonicalize neg after min/max if I1 is constant. 1283 if (match(I0, m_NSWNeg(m_Value(X))) && match(I1, m_NSWNeg(m_Value(Y))) && 1284 (I0->hasOneUse() || I1->hasOneUse())) { 1285 Intrinsic::ID InvID = getInverseMinMaxIntrinsic(IID); 1286 Value *InvMaxMin = Builder.CreateBinaryIntrinsic(InvID, X, Y); 1287 return BinaryOperator::CreateNSWNeg(InvMaxMin); 1288 } 1289 } 1290 1291 // If we can eliminate ~A and Y is free to invert: 1292 // max ~A, Y --> ~(min A, ~Y) 1293 // 1294 // Examples: 1295 // max ~A, ~Y --> ~(min A, Y) 1296 // max ~A, C --> ~(min A, ~C) 1297 // max ~A, (max ~Y, ~Z) --> ~min( A, (min Y, Z)) 1298 auto moveNotAfterMinMax = [&](Value *X, Value *Y) -> Instruction * { 1299 Value *A; 1300 if (match(X, m_OneUse(m_Not(m_Value(A)))) && 1301 !isFreeToInvert(A, A->hasOneUse()) && 1302 isFreeToInvert(Y, Y->hasOneUse())) { 1303 Value *NotY = Builder.CreateNot(Y); 1304 Intrinsic::ID InvID = getInverseMinMaxIntrinsic(IID); 1305 Value *InvMaxMin = Builder.CreateBinaryIntrinsic(InvID, A, NotY); 1306 return BinaryOperator::CreateNot(InvMaxMin); 1307 } 1308 return nullptr; 1309 }; 1310 1311 if (Instruction *I = moveNotAfterMinMax(I0, I1)) 1312 return I; 1313 if (Instruction *I = moveNotAfterMinMax(I1, I0)) 1314 return I; 1315 1316 if (Instruction *I = moveAddAfterMinMax(II, Builder)) 1317 return I; 1318 1319 // smax(X, -X) --> abs(X) 1320 // smin(X, -X) --> -abs(X) 1321 // umax(X, -X) --> -abs(X) 1322 // umin(X, -X) --> abs(X) 1323 if (isKnownNegation(I0, I1)) { 1324 // We can choose either operand as the input to abs(), but if we can 1325 // eliminate the only use of a value, that's better for subsequent 1326 // transforms/analysis. 1327 if (I0->hasOneUse() && !I1->hasOneUse()) 1328 std::swap(I0, I1); 1329 1330 // This is some variant of abs(). See if we can propagate 'nsw' to the abs 1331 // operation and potentially its negation. 1332 bool IntMinIsPoison = isKnownNegation(I0, I1, /* NeedNSW */ true); 1333 Value *Abs = Builder.CreateBinaryIntrinsic( 1334 Intrinsic::abs, I0, 1335 ConstantInt::getBool(II->getContext(), IntMinIsPoison)); 1336 1337 // We don't have a "nabs" intrinsic, so negate if needed based on the 1338 // max/min operation. 1339 if (IID == Intrinsic::smin || IID == Intrinsic::umax) 1340 Abs = Builder.CreateNeg(Abs, "nabs", /* NUW */ false, IntMinIsPoison); 1341 return replaceInstUsesWith(CI, Abs); 1342 } 1343 1344 if (Instruction *Sel = foldClampRangeOfTwo(II, Builder)) 1345 return Sel; 1346 1347 if (Instruction *SAdd = matchSAddSubSat(*II)) 1348 return SAdd; 1349 1350 if (match(I1, m_ImmConstant())) 1351 if (auto *Sel = dyn_cast<SelectInst>(I0)) 1352 if (Instruction *R = FoldOpIntoSelect(*II, Sel)) 1353 return R; 1354 1355 if (Instruction *NewMinMax = reassociateMinMaxWithConstants(II)) 1356 return NewMinMax; 1357 1358 if (Instruction *R = reassociateMinMaxWithConstantInOperand(II, Builder)) 1359 return R; 1360 1361 if (Instruction *NewMinMax = factorizeMinMaxTree(II)) 1362 return NewMinMax; 1363 1364 break; 1365 } 1366 case Intrinsic::bswap: { 1367 Value *IIOperand = II->getArgOperand(0); 1368 Value *X = nullptr; 1369 1370 // Try to canonicalize bswap-of-logical-shift-by-8-bit-multiple as 1371 // inverse-shift-of-bswap: 1372 // bswap (shl X, C) --> lshr (bswap X), C 1373 // bswap (lshr X, C) --> shl (bswap X), C 1374 // TODO: Use knownbits to allow variable shift and non-splat vector match. 1375 BinaryOperator *BO; 1376 if (match(IIOperand, m_OneUse(m_BinOp(BO)))) { 1377 const APInt *C; 1378 if (match(BO, m_LogicalShift(m_Value(X), m_APIntAllowUndef(C))) && 1379 (*C & 7) == 0) { 1380 Value *NewSwap = Builder.CreateUnaryIntrinsic(Intrinsic::bswap, X); 1381 BinaryOperator::BinaryOps InverseShift = 1382 BO->getOpcode() == Instruction::Shl ? Instruction::LShr 1383 : Instruction::Shl; 1384 return BinaryOperator::Create(InverseShift, NewSwap, BO->getOperand(1)); 1385 } 1386 } 1387 1388 KnownBits Known = computeKnownBits(IIOperand, 0, II); 1389 uint64_t LZ = alignDown(Known.countMinLeadingZeros(), 8); 1390 uint64_t TZ = alignDown(Known.countMinTrailingZeros(), 8); 1391 unsigned BW = Known.getBitWidth(); 1392 1393 // bswap(x) -> shift(x) if x has exactly one "active byte" 1394 if (BW - LZ - TZ == 8) { 1395 assert(LZ != TZ && "active byte cannot be in the middle"); 1396 if (LZ > TZ) // -> shl(x) if the "active byte" is in the low part of x 1397 return BinaryOperator::CreateNUWShl( 1398 IIOperand, ConstantInt::get(IIOperand->getType(), LZ - TZ)); 1399 // -> lshr(x) if the "active byte" is in the high part of x 1400 return BinaryOperator::CreateExactLShr( 1401 IIOperand, ConstantInt::get(IIOperand->getType(), TZ - LZ)); 1402 } 1403 1404 // bswap(trunc(bswap(x))) -> trunc(lshr(x, c)) 1405 if (match(IIOperand, m_Trunc(m_BSwap(m_Value(X))))) { 1406 unsigned C = X->getType()->getScalarSizeInBits() - BW; 1407 Value *CV = ConstantInt::get(X->getType(), C); 1408 Value *V = Builder.CreateLShr(X, CV); 1409 return new TruncInst(V, IIOperand->getType()); 1410 } 1411 break; 1412 } 1413 case Intrinsic::masked_load: 1414 if (Value *SimplifiedMaskedOp = simplifyMaskedLoad(*II)) 1415 return replaceInstUsesWith(CI, SimplifiedMaskedOp); 1416 break; 1417 case Intrinsic::masked_store: 1418 return simplifyMaskedStore(*II); 1419 case Intrinsic::masked_gather: 1420 return simplifyMaskedGather(*II); 1421 case Intrinsic::masked_scatter: 1422 return simplifyMaskedScatter(*II); 1423 case Intrinsic::launder_invariant_group: 1424 case Intrinsic::strip_invariant_group: 1425 if (auto *SkippedBarrier = simplifyInvariantGroupIntrinsic(*II, *this)) 1426 return replaceInstUsesWith(*II, SkippedBarrier); 1427 break; 1428 case Intrinsic::powi: 1429 if (ConstantInt *Power = dyn_cast<ConstantInt>(II->getArgOperand(1))) { 1430 // 0 and 1 are handled in instsimplify 1431 // powi(x, -1) -> 1/x 1432 if (Power->isMinusOne()) 1433 return BinaryOperator::CreateFDivFMF(ConstantFP::get(CI.getType(), 1.0), 1434 II->getArgOperand(0), II); 1435 // powi(x, 2) -> x*x 1436 if (Power->equalsInt(2)) 1437 return BinaryOperator::CreateFMulFMF(II->getArgOperand(0), 1438 II->getArgOperand(0), II); 1439 1440 if (!Power->getValue()[0]) { 1441 Value *X; 1442 // If power is even: 1443 // powi(-x, p) -> powi(x, p) 1444 // powi(fabs(x), p) -> powi(x, p) 1445 // powi(copysign(x, y), p) -> powi(x, p) 1446 if (match(II->getArgOperand(0), m_FNeg(m_Value(X))) || 1447 match(II->getArgOperand(0), m_FAbs(m_Value(X))) || 1448 match(II->getArgOperand(0), 1449 m_Intrinsic<Intrinsic::copysign>(m_Value(X), m_Value()))) 1450 return replaceOperand(*II, 0, X); 1451 } 1452 } 1453 break; 1454 1455 case Intrinsic::cttz: 1456 case Intrinsic::ctlz: 1457 if (auto *I = foldCttzCtlz(*II, *this)) 1458 return I; 1459 break; 1460 1461 case Intrinsic::ctpop: 1462 if (auto *I = foldCtpop(*II, *this)) 1463 return I; 1464 break; 1465 1466 case Intrinsic::fshl: 1467 case Intrinsic::fshr: { 1468 Value *Op0 = II->getArgOperand(0), *Op1 = II->getArgOperand(1); 1469 Type *Ty = II->getType(); 1470 unsigned BitWidth = Ty->getScalarSizeInBits(); 1471 Constant *ShAmtC; 1472 if (match(II->getArgOperand(2), m_ImmConstant(ShAmtC)) && 1473 !ShAmtC->containsConstantExpression()) { 1474 // Canonicalize a shift amount constant operand to modulo the bit-width. 1475 Constant *WidthC = ConstantInt::get(Ty, BitWidth); 1476 Constant *ModuloC = ConstantExpr::getURem(ShAmtC, WidthC); 1477 if (ModuloC != ShAmtC) 1478 return replaceOperand(*II, 2, ModuloC); 1479 1480 assert(ConstantExpr::getICmp(ICmpInst::ICMP_UGT, WidthC, ShAmtC) == 1481 ConstantInt::getTrue(CmpInst::makeCmpResultType(Ty)) && 1482 "Shift amount expected to be modulo bitwidth"); 1483 1484 // Canonicalize funnel shift right by constant to funnel shift left. This 1485 // is not entirely arbitrary. For historical reasons, the backend may 1486 // recognize rotate left patterns but miss rotate right patterns. 1487 if (IID == Intrinsic::fshr) { 1488 // fshr X, Y, C --> fshl X, Y, (BitWidth - C) 1489 Constant *LeftShiftC = ConstantExpr::getSub(WidthC, ShAmtC); 1490 Module *Mod = II->getModule(); 1491 Function *Fshl = Intrinsic::getDeclaration(Mod, Intrinsic::fshl, Ty); 1492 return CallInst::Create(Fshl, { Op0, Op1, LeftShiftC }); 1493 } 1494 assert(IID == Intrinsic::fshl && 1495 "All funnel shifts by simple constants should go left"); 1496 1497 // fshl(X, 0, C) --> shl X, C 1498 // fshl(X, undef, C) --> shl X, C 1499 if (match(Op1, m_ZeroInt()) || match(Op1, m_Undef())) 1500 return BinaryOperator::CreateShl(Op0, ShAmtC); 1501 1502 // fshl(0, X, C) --> lshr X, (BW-C) 1503 // fshl(undef, X, C) --> lshr X, (BW-C) 1504 if (match(Op0, m_ZeroInt()) || match(Op0, m_Undef())) 1505 return BinaryOperator::CreateLShr(Op1, 1506 ConstantExpr::getSub(WidthC, ShAmtC)); 1507 1508 // fshl i16 X, X, 8 --> bswap i16 X (reduce to more-specific form) 1509 if (Op0 == Op1 && BitWidth == 16 && match(ShAmtC, m_SpecificInt(8))) { 1510 Module *Mod = II->getModule(); 1511 Function *Bswap = Intrinsic::getDeclaration(Mod, Intrinsic::bswap, Ty); 1512 return CallInst::Create(Bswap, { Op0 }); 1513 } 1514 } 1515 1516 // Left or right might be masked. 1517 if (SimplifyDemandedInstructionBits(*II)) 1518 return &CI; 1519 1520 // The shift amount (operand 2) of a funnel shift is modulo the bitwidth, 1521 // so only the low bits of the shift amount are demanded if the bitwidth is 1522 // a power-of-2. 1523 if (!isPowerOf2_32(BitWidth)) 1524 break; 1525 APInt Op2Demanded = APInt::getLowBitsSet(BitWidth, Log2_32_Ceil(BitWidth)); 1526 KnownBits Op2Known(BitWidth); 1527 if (SimplifyDemandedBits(II, 2, Op2Demanded, Op2Known)) 1528 return &CI; 1529 break; 1530 } 1531 case Intrinsic::uadd_with_overflow: 1532 case Intrinsic::sadd_with_overflow: { 1533 if (Instruction *I = foldIntrinsicWithOverflowCommon(II)) 1534 return I; 1535 1536 // Given 2 constant operands whose sum does not overflow: 1537 // uaddo (X +nuw C0), C1 -> uaddo X, C0 + C1 1538 // saddo (X +nsw C0), C1 -> saddo X, C0 + C1 1539 Value *X; 1540 const APInt *C0, *C1; 1541 Value *Arg0 = II->getArgOperand(0); 1542 Value *Arg1 = II->getArgOperand(1); 1543 bool IsSigned = IID == Intrinsic::sadd_with_overflow; 1544 bool HasNWAdd = IsSigned ? match(Arg0, m_NSWAdd(m_Value(X), m_APInt(C0))) 1545 : match(Arg0, m_NUWAdd(m_Value(X), m_APInt(C0))); 1546 if (HasNWAdd && match(Arg1, m_APInt(C1))) { 1547 bool Overflow; 1548 APInt NewC = 1549 IsSigned ? C1->sadd_ov(*C0, Overflow) : C1->uadd_ov(*C0, Overflow); 1550 if (!Overflow) 1551 return replaceInstUsesWith( 1552 *II, Builder.CreateBinaryIntrinsic( 1553 IID, X, ConstantInt::get(Arg1->getType(), NewC))); 1554 } 1555 break; 1556 } 1557 1558 case Intrinsic::umul_with_overflow: 1559 case Intrinsic::smul_with_overflow: 1560 case Intrinsic::usub_with_overflow: 1561 if (Instruction *I = foldIntrinsicWithOverflowCommon(II)) 1562 return I; 1563 break; 1564 1565 case Intrinsic::ssub_with_overflow: { 1566 if (Instruction *I = foldIntrinsicWithOverflowCommon(II)) 1567 return I; 1568 1569 Constant *C; 1570 Value *Arg0 = II->getArgOperand(0); 1571 Value *Arg1 = II->getArgOperand(1); 1572 // Given a constant C that is not the minimum signed value 1573 // for an integer of a given bit width: 1574 // 1575 // ssubo X, C -> saddo X, -C 1576 if (match(Arg1, m_Constant(C)) && C->isNotMinSignedValue()) { 1577 Value *NegVal = ConstantExpr::getNeg(C); 1578 // Build a saddo call that is equivalent to the discovered 1579 // ssubo call. 1580 return replaceInstUsesWith( 1581 *II, Builder.CreateBinaryIntrinsic(Intrinsic::sadd_with_overflow, 1582 Arg0, NegVal)); 1583 } 1584 1585 break; 1586 } 1587 1588 case Intrinsic::uadd_sat: 1589 case Intrinsic::sadd_sat: 1590 case Intrinsic::usub_sat: 1591 case Intrinsic::ssub_sat: { 1592 SaturatingInst *SI = cast<SaturatingInst>(II); 1593 Type *Ty = SI->getType(); 1594 Value *Arg0 = SI->getLHS(); 1595 Value *Arg1 = SI->getRHS(); 1596 1597 // Make use of known overflow information. 1598 OverflowResult OR = computeOverflow(SI->getBinaryOp(), SI->isSigned(), 1599 Arg0, Arg1, SI); 1600 switch (OR) { 1601 case OverflowResult::MayOverflow: 1602 break; 1603 case OverflowResult::NeverOverflows: 1604 if (SI->isSigned()) 1605 return BinaryOperator::CreateNSW(SI->getBinaryOp(), Arg0, Arg1); 1606 else 1607 return BinaryOperator::CreateNUW(SI->getBinaryOp(), Arg0, Arg1); 1608 case OverflowResult::AlwaysOverflowsLow: { 1609 unsigned BitWidth = Ty->getScalarSizeInBits(); 1610 APInt Min = APSInt::getMinValue(BitWidth, !SI->isSigned()); 1611 return replaceInstUsesWith(*SI, ConstantInt::get(Ty, Min)); 1612 } 1613 case OverflowResult::AlwaysOverflowsHigh: { 1614 unsigned BitWidth = Ty->getScalarSizeInBits(); 1615 APInt Max = APSInt::getMaxValue(BitWidth, !SI->isSigned()); 1616 return replaceInstUsesWith(*SI, ConstantInt::get(Ty, Max)); 1617 } 1618 } 1619 1620 // ssub.sat(X, C) -> sadd.sat(X, -C) if C != MIN 1621 Constant *C; 1622 if (IID == Intrinsic::ssub_sat && match(Arg1, m_Constant(C)) && 1623 C->isNotMinSignedValue()) { 1624 Value *NegVal = ConstantExpr::getNeg(C); 1625 return replaceInstUsesWith( 1626 *II, Builder.CreateBinaryIntrinsic( 1627 Intrinsic::sadd_sat, Arg0, NegVal)); 1628 } 1629 1630 // sat(sat(X + Val2) + Val) -> sat(X + (Val+Val2)) 1631 // sat(sat(X - Val2) - Val) -> sat(X - (Val+Val2)) 1632 // if Val and Val2 have the same sign 1633 if (auto *Other = dyn_cast<IntrinsicInst>(Arg0)) { 1634 Value *X; 1635 const APInt *Val, *Val2; 1636 APInt NewVal; 1637 bool IsUnsigned = 1638 IID == Intrinsic::uadd_sat || IID == Intrinsic::usub_sat; 1639 if (Other->getIntrinsicID() == IID && 1640 match(Arg1, m_APInt(Val)) && 1641 match(Other->getArgOperand(0), m_Value(X)) && 1642 match(Other->getArgOperand(1), m_APInt(Val2))) { 1643 if (IsUnsigned) 1644 NewVal = Val->uadd_sat(*Val2); 1645 else if (Val->isNonNegative() == Val2->isNonNegative()) { 1646 bool Overflow; 1647 NewVal = Val->sadd_ov(*Val2, Overflow); 1648 if (Overflow) { 1649 // Both adds together may add more than SignedMaxValue 1650 // without saturating the final result. 1651 break; 1652 } 1653 } else { 1654 // Cannot fold saturated addition with different signs. 1655 break; 1656 } 1657 1658 return replaceInstUsesWith( 1659 *II, Builder.CreateBinaryIntrinsic( 1660 IID, X, ConstantInt::get(II->getType(), NewVal))); 1661 } 1662 } 1663 break; 1664 } 1665 1666 case Intrinsic::minnum: 1667 case Intrinsic::maxnum: 1668 case Intrinsic::minimum: 1669 case Intrinsic::maximum: { 1670 Value *Arg0 = II->getArgOperand(0); 1671 Value *Arg1 = II->getArgOperand(1); 1672 Value *X, *Y; 1673 if (match(Arg0, m_FNeg(m_Value(X))) && match(Arg1, m_FNeg(m_Value(Y))) && 1674 (Arg0->hasOneUse() || Arg1->hasOneUse())) { 1675 // If both operands are negated, invert the call and negate the result: 1676 // min(-X, -Y) --> -(max(X, Y)) 1677 // max(-X, -Y) --> -(min(X, Y)) 1678 Intrinsic::ID NewIID; 1679 switch (IID) { 1680 case Intrinsic::maxnum: 1681 NewIID = Intrinsic::minnum; 1682 break; 1683 case Intrinsic::minnum: 1684 NewIID = Intrinsic::maxnum; 1685 break; 1686 case Intrinsic::maximum: 1687 NewIID = Intrinsic::minimum; 1688 break; 1689 case Intrinsic::minimum: 1690 NewIID = Intrinsic::maximum; 1691 break; 1692 default: 1693 llvm_unreachable("unexpected intrinsic ID"); 1694 } 1695 Value *NewCall = Builder.CreateBinaryIntrinsic(NewIID, X, Y, II); 1696 Instruction *FNeg = UnaryOperator::CreateFNeg(NewCall); 1697 FNeg->copyIRFlags(II); 1698 return FNeg; 1699 } 1700 1701 // m(m(X, C2), C1) -> m(X, C) 1702 const APFloat *C1, *C2; 1703 if (auto *M = dyn_cast<IntrinsicInst>(Arg0)) { 1704 if (M->getIntrinsicID() == IID && match(Arg1, m_APFloat(C1)) && 1705 ((match(M->getArgOperand(0), m_Value(X)) && 1706 match(M->getArgOperand(1), m_APFloat(C2))) || 1707 (match(M->getArgOperand(1), m_Value(X)) && 1708 match(M->getArgOperand(0), m_APFloat(C2))))) { 1709 APFloat Res(0.0); 1710 switch (IID) { 1711 case Intrinsic::maxnum: 1712 Res = maxnum(*C1, *C2); 1713 break; 1714 case Intrinsic::minnum: 1715 Res = minnum(*C1, *C2); 1716 break; 1717 case Intrinsic::maximum: 1718 Res = maximum(*C1, *C2); 1719 break; 1720 case Intrinsic::minimum: 1721 Res = minimum(*C1, *C2); 1722 break; 1723 default: 1724 llvm_unreachable("unexpected intrinsic ID"); 1725 } 1726 Instruction *NewCall = Builder.CreateBinaryIntrinsic( 1727 IID, X, ConstantFP::get(Arg0->getType(), Res), II); 1728 // TODO: Conservatively intersecting FMF. If Res == C2, the transform 1729 // was a simplification (so Arg0 and its original flags could 1730 // propagate?) 1731 NewCall->andIRFlags(M); 1732 return replaceInstUsesWith(*II, NewCall); 1733 } 1734 } 1735 1736 // m((fpext X), (fpext Y)) -> fpext (m(X, Y)) 1737 if (match(Arg0, m_OneUse(m_FPExt(m_Value(X)))) && 1738 match(Arg1, m_OneUse(m_FPExt(m_Value(Y)))) && 1739 X->getType() == Y->getType()) { 1740 Value *NewCall = 1741 Builder.CreateBinaryIntrinsic(IID, X, Y, II, II->getName()); 1742 return new FPExtInst(NewCall, II->getType()); 1743 } 1744 1745 // max X, -X --> fabs X 1746 // min X, -X --> -(fabs X) 1747 // TODO: Remove one-use limitation? That is obviously better for max. 1748 // It would be an extra instruction for min (fnabs), but that is 1749 // still likely better for analysis and codegen. 1750 if ((match(Arg0, m_OneUse(m_FNeg(m_Value(X)))) && Arg1 == X) || 1751 (match(Arg1, m_OneUse(m_FNeg(m_Value(X)))) && Arg0 == X)) { 1752 Value *R = Builder.CreateUnaryIntrinsic(Intrinsic::fabs, X, II); 1753 if (IID == Intrinsic::minimum || IID == Intrinsic::minnum) 1754 R = Builder.CreateFNegFMF(R, II); 1755 return replaceInstUsesWith(*II, R); 1756 } 1757 1758 break; 1759 } 1760 case Intrinsic::fmuladd: { 1761 // Canonicalize fast fmuladd to the separate fmul + fadd. 1762 if (II->isFast()) { 1763 BuilderTy::FastMathFlagGuard Guard(Builder); 1764 Builder.setFastMathFlags(II->getFastMathFlags()); 1765 Value *Mul = Builder.CreateFMul(II->getArgOperand(0), 1766 II->getArgOperand(1)); 1767 Value *Add = Builder.CreateFAdd(Mul, II->getArgOperand(2)); 1768 Add->takeName(II); 1769 return replaceInstUsesWith(*II, Add); 1770 } 1771 1772 // Try to simplify the underlying FMul. 1773 if (Value *V = SimplifyFMulInst(II->getArgOperand(0), II->getArgOperand(1), 1774 II->getFastMathFlags(), 1775 SQ.getWithInstruction(II))) { 1776 auto *FAdd = BinaryOperator::CreateFAdd(V, II->getArgOperand(2)); 1777 FAdd->copyFastMathFlags(II); 1778 return FAdd; 1779 } 1780 1781 LLVM_FALLTHROUGH; 1782 } 1783 case Intrinsic::fma: { 1784 // fma fneg(x), fneg(y), z -> fma x, y, z 1785 Value *Src0 = II->getArgOperand(0); 1786 Value *Src1 = II->getArgOperand(1); 1787 Value *X, *Y; 1788 if (match(Src0, m_FNeg(m_Value(X))) && match(Src1, m_FNeg(m_Value(Y)))) { 1789 replaceOperand(*II, 0, X); 1790 replaceOperand(*II, 1, Y); 1791 return II; 1792 } 1793 1794 // fma fabs(x), fabs(x), z -> fma x, x, z 1795 if (match(Src0, m_FAbs(m_Value(X))) && 1796 match(Src1, m_FAbs(m_Specific(X)))) { 1797 replaceOperand(*II, 0, X); 1798 replaceOperand(*II, 1, X); 1799 return II; 1800 } 1801 1802 // Try to simplify the underlying FMul. We can only apply simplifications 1803 // that do not require rounding. 1804 if (Value *V = SimplifyFMAFMul(II->getArgOperand(0), II->getArgOperand(1), 1805 II->getFastMathFlags(), 1806 SQ.getWithInstruction(II))) { 1807 auto *FAdd = BinaryOperator::CreateFAdd(V, II->getArgOperand(2)); 1808 FAdd->copyFastMathFlags(II); 1809 return FAdd; 1810 } 1811 1812 // fma x, y, 0 -> fmul x, y 1813 // This is always valid for -0.0, but requires nsz for +0.0 as 1814 // -0.0 + 0.0 = 0.0, which would not be the same as the fmul on its own. 1815 if (match(II->getArgOperand(2), m_NegZeroFP()) || 1816 (match(II->getArgOperand(2), m_PosZeroFP()) && 1817 II->getFastMathFlags().noSignedZeros())) 1818 return BinaryOperator::CreateFMulFMF(Src0, Src1, II); 1819 1820 break; 1821 } 1822 case Intrinsic::copysign: { 1823 Value *Mag = II->getArgOperand(0), *Sign = II->getArgOperand(1); 1824 if (SignBitMustBeZero(Sign, &TLI)) { 1825 // If we know that the sign argument is positive, reduce to FABS: 1826 // copysign Mag, +Sign --> fabs Mag 1827 Value *Fabs = Builder.CreateUnaryIntrinsic(Intrinsic::fabs, Mag, II); 1828 return replaceInstUsesWith(*II, Fabs); 1829 } 1830 // TODO: There should be a ValueTracking sibling like SignBitMustBeOne. 1831 const APFloat *C; 1832 if (match(Sign, m_APFloat(C)) && C->isNegative()) { 1833 // If we know that the sign argument is negative, reduce to FNABS: 1834 // copysign Mag, -Sign --> fneg (fabs Mag) 1835 Value *Fabs = Builder.CreateUnaryIntrinsic(Intrinsic::fabs, Mag, II); 1836 return replaceInstUsesWith(*II, Builder.CreateFNegFMF(Fabs, II)); 1837 } 1838 1839 // Propagate sign argument through nested calls: 1840 // copysign Mag, (copysign ?, X) --> copysign Mag, X 1841 Value *X; 1842 if (match(Sign, m_Intrinsic<Intrinsic::copysign>(m_Value(), m_Value(X)))) 1843 return replaceOperand(*II, 1, X); 1844 1845 // Peek through changes of magnitude's sign-bit. This call rewrites those: 1846 // copysign (fabs X), Sign --> copysign X, Sign 1847 // copysign (fneg X), Sign --> copysign X, Sign 1848 if (match(Mag, m_FAbs(m_Value(X))) || match(Mag, m_FNeg(m_Value(X)))) 1849 return replaceOperand(*II, 0, X); 1850 1851 break; 1852 } 1853 case Intrinsic::fabs: { 1854 Value *Cond, *TVal, *FVal; 1855 if (match(II->getArgOperand(0), 1856 m_Select(m_Value(Cond), m_Value(TVal), m_Value(FVal)))) { 1857 // fabs (select Cond, TrueC, FalseC) --> select Cond, AbsT, AbsF 1858 if (isa<Constant>(TVal) && isa<Constant>(FVal)) { 1859 CallInst *AbsT = Builder.CreateCall(II->getCalledFunction(), {TVal}); 1860 CallInst *AbsF = Builder.CreateCall(II->getCalledFunction(), {FVal}); 1861 return SelectInst::Create(Cond, AbsT, AbsF); 1862 } 1863 // fabs (select Cond, -FVal, FVal) --> fabs FVal 1864 if (match(TVal, m_FNeg(m_Specific(FVal)))) 1865 return replaceOperand(*II, 0, FVal); 1866 // fabs (select Cond, TVal, -TVal) --> fabs TVal 1867 if (match(FVal, m_FNeg(m_Specific(TVal)))) 1868 return replaceOperand(*II, 0, TVal); 1869 } 1870 1871 LLVM_FALLTHROUGH; 1872 } 1873 case Intrinsic::ceil: 1874 case Intrinsic::floor: 1875 case Intrinsic::round: 1876 case Intrinsic::roundeven: 1877 case Intrinsic::nearbyint: 1878 case Intrinsic::rint: 1879 case Intrinsic::trunc: { 1880 Value *ExtSrc; 1881 if (match(II->getArgOperand(0), m_OneUse(m_FPExt(m_Value(ExtSrc))))) { 1882 // Narrow the call: intrinsic (fpext x) -> fpext (intrinsic x) 1883 Value *NarrowII = Builder.CreateUnaryIntrinsic(IID, ExtSrc, II); 1884 return new FPExtInst(NarrowII, II->getType()); 1885 } 1886 break; 1887 } 1888 case Intrinsic::cos: 1889 case Intrinsic::amdgcn_cos: { 1890 Value *X; 1891 Value *Src = II->getArgOperand(0); 1892 if (match(Src, m_FNeg(m_Value(X))) || match(Src, m_FAbs(m_Value(X)))) { 1893 // cos(-x) -> cos(x) 1894 // cos(fabs(x)) -> cos(x) 1895 return replaceOperand(*II, 0, X); 1896 } 1897 break; 1898 } 1899 case Intrinsic::sin: { 1900 Value *X; 1901 if (match(II->getArgOperand(0), m_OneUse(m_FNeg(m_Value(X))))) { 1902 // sin(-x) --> -sin(x) 1903 Value *NewSin = Builder.CreateUnaryIntrinsic(Intrinsic::sin, X, II); 1904 Instruction *FNeg = UnaryOperator::CreateFNeg(NewSin); 1905 FNeg->copyFastMathFlags(II); 1906 return FNeg; 1907 } 1908 break; 1909 } 1910 1911 case Intrinsic::arm_neon_vtbl1: 1912 case Intrinsic::aarch64_neon_tbl1: 1913 if (Value *V = simplifyNeonTbl1(*II, Builder)) 1914 return replaceInstUsesWith(*II, V); 1915 break; 1916 1917 case Intrinsic::arm_neon_vmulls: 1918 case Intrinsic::arm_neon_vmullu: 1919 case Intrinsic::aarch64_neon_smull: 1920 case Intrinsic::aarch64_neon_umull: { 1921 Value *Arg0 = II->getArgOperand(0); 1922 Value *Arg1 = II->getArgOperand(1); 1923 1924 // Handle mul by zero first: 1925 if (isa<ConstantAggregateZero>(Arg0) || isa<ConstantAggregateZero>(Arg1)) { 1926 return replaceInstUsesWith(CI, ConstantAggregateZero::get(II->getType())); 1927 } 1928 1929 // Check for constant LHS & RHS - in this case we just simplify. 1930 bool Zext = (IID == Intrinsic::arm_neon_vmullu || 1931 IID == Intrinsic::aarch64_neon_umull); 1932 VectorType *NewVT = cast<VectorType>(II->getType()); 1933 if (Constant *CV0 = dyn_cast<Constant>(Arg0)) { 1934 if (Constant *CV1 = dyn_cast<Constant>(Arg1)) { 1935 CV0 = ConstantExpr::getIntegerCast(CV0, NewVT, /*isSigned=*/!Zext); 1936 CV1 = ConstantExpr::getIntegerCast(CV1, NewVT, /*isSigned=*/!Zext); 1937 1938 return replaceInstUsesWith(CI, ConstantExpr::getMul(CV0, CV1)); 1939 } 1940 1941 // Couldn't simplify - canonicalize constant to the RHS. 1942 std::swap(Arg0, Arg1); 1943 } 1944 1945 // Handle mul by one: 1946 if (Constant *CV1 = dyn_cast<Constant>(Arg1)) 1947 if (ConstantInt *Splat = 1948 dyn_cast_or_null<ConstantInt>(CV1->getSplatValue())) 1949 if (Splat->isOne()) 1950 return CastInst::CreateIntegerCast(Arg0, II->getType(), 1951 /*isSigned=*/!Zext); 1952 1953 break; 1954 } 1955 case Intrinsic::arm_neon_aesd: 1956 case Intrinsic::arm_neon_aese: 1957 case Intrinsic::aarch64_crypto_aesd: 1958 case Intrinsic::aarch64_crypto_aese: { 1959 Value *DataArg = II->getArgOperand(0); 1960 Value *KeyArg = II->getArgOperand(1); 1961 1962 // Try to use the builtin XOR in AESE and AESD to eliminate a prior XOR 1963 Value *Data, *Key; 1964 if (match(KeyArg, m_ZeroInt()) && 1965 match(DataArg, m_Xor(m_Value(Data), m_Value(Key)))) { 1966 replaceOperand(*II, 0, Data); 1967 replaceOperand(*II, 1, Key); 1968 return II; 1969 } 1970 break; 1971 } 1972 case Intrinsic::hexagon_V6_vandvrt: 1973 case Intrinsic::hexagon_V6_vandvrt_128B: { 1974 // Simplify Q -> V -> Q conversion. 1975 if (auto Op0 = dyn_cast<IntrinsicInst>(II->getArgOperand(0))) { 1976 Intrinsic::ID ID0 = Op0->getIntrinsicID(); 1977 if (ID0 != Intrinsic::hexagon_V6_vandqrt && 1978 ID0 != Intrinsic::hexagon_V6_vandqrt_128B) 1979 break; 1980 Value *Bytes = Op0->getArgOperand(1), *Mask = II->getArgOperand(1); 1981 uint64_t Bytes1 = computeKnownBits(Bytes, 0, Op0).One.getZExtValue(); 1982 uint64_t Mask1 = computeKnownBits(Mask, 0, II).One.getZExtValue(); 1983 // Check if every byte has common bits in Bytes and Mask. 1984 uint64_t C = Bytes1 & Mask1; 1985 if ((C & 0xFF) && (C & 0xFF00) && (C & 0xFF0000) && (C & 0xFF000000)) 1986 return replaceInstUsesWith(*II, Op0->getArgOperand(0)); 1987 } 1988 break; 1989 } 1990 case Intrinsic::stackrestore: { 1991 enum class ClassifyResult { 1992 None, 1993 Alloca, 1994 StackRestore, 1995 CallWithSideEffects, 1996 }; 1997 auto Classify = [](const Instruction *I) { 1998 if (isa<AllocaInst>(I)) 1999 return ClassifyResult::Alloca; 2000 2001 if (auto *CI = dyn_cast<CallInst>(I)) { 2002 if (auto *II = dyn_cast<IntrinsicInst>(CI)) { 2003 if (II->getIntrinsicID() == Intrinsic::stackrestore) 2004 return ClassifyResult::StackRestore; 2005 2006 if (II->mayHaveSideEffects()) 2007 return ClassifyResult::CallWithSideEffects; 2008 } else { 2009 // Consider all non-intrinsic calls to be side effects 2010 return ClassifyResult::CallWithSideEffects; 2011 } 2012 } 2013 2014 return ClassifyResult::None; 2015 }; 2016 2017 // If the stacksave and the stackrestore are in the same BB, and there is 2018 // no intervening call, alloca, or stackrestore of a different stacksave, 2019 // remove the restore. This can happen when variable allocas are DCE'd. 2020 if (IntrinsicInst *SS = dyn_cast<IntrinsicInst>(II->getArgOperand(0))) { 2021 if (SS->getIntrinsicID() == Intrinsic::stacksave && 2022 SS->getParent() == II->getParent()) { 2023 BasicBlock::iterator BI(SS); 2024 bool CannotRemove = false; 2025 for (++BI; &*BI != II; ++BI) { 2026 switch (Classify(&*BI)) { 2027 case ClassifyResult::None: 2028 // So far so good, look at next instructions. 2029 break; 2030 2031 case ClassifyResult::StackRestore: 2032 // If we found an intervening stackrestore for a different 2033 // stacksave, we can't remove the stackrestore. Otherwise, continue. 2034 if (cast<IntrinsicInst>(*BI).getArgOperand(0) != SS) 2035 CannotRemove = true; 2036 break; 2037 2038 case ClassifyResult::Alloca: 2039 case ClassifyResult::CallWithSideEffects: 2040 // If we found an alloca, a non-intrinsic call, or an intrinsic 2041 // call with side effects, we can't remove the stackrestore. 2042 CannotRemove = true; 2043 break; 2044 } 2045 if (CannotRemove) 2046 break; 2047 } 2048 2049 if (!CannotRemove) 2050 return eraseInstFromFunction(CI); 2051 } 2052 } 2053 2054 // Scan down this block to see if there is another stack restore in the 2055 // same block without an intervening call/alloca. 2056 BasicBlock::iterator BI(II); 2057 Instruction *TI = II->getParent()->getTerminator(); 2058 bool CannotRemove = false; 2059 for (++BI; &*BI != TI; ++BI) { 2060 switch (Classify(&*BI)) { 2061 case ClassifyResult::None: 2062 // So far so good, look at next instructions. 2063 break; 2064 2065 case ClassifyResult::StackRestore: 2066 // If there is a stackrestore below this one, remove this one. 2067 return eraseInstFromFunction(CI); 2068 2069 case ClassifyResult::Alloca: 2070 case ClassifyResult::CallWithSideEffects: 2071 // If we found an alloca, a non-intrinsic call, or an intrinsic call 2072 // with side effects (such as llvm.stacksave and llvm.read_register), 2073 // we can't remove the stack restore. 2074 CannotRemove = true; 2075 break; 2076 } 2077 if (CannotRemove) 2078 break; 2079 } 2080 2081 // If the stack restore is in a return, resume, or unwind block and if there 2082 // are no allocas or calls between the restore and the return, nuke the 2083 // restore. 2084 if (!CannotRemove && (isa<ReturnInst>(TI) || isa<ResumeInst>(TI))) 2085 return eraseInstFromFunction(CI); 2086 break; 2087 } 2088 case Intrinsic::lifetime_end: 2089 // Asan needs to poison memory to detect invalid access which is possible 2090 // even for empty lifetime range. 2091 if (II->getFunction()->hasFnAttribute(Attribute::SanitizeAddress) || 2092 II->getFunction()->hasFnAttribute(Attribute::SanitizeMemory) || 2093 II->getFunction()->hasFnAttribute(Attribute::SanitizeHWAddress)) 2094 break; 2095 2096 if (removeTriviallyEmptyRange(*II, *this, [](const IntrinsicInst &I) { 2097 return I.getIntrinsicID() == Intrinsic::lifetime_start; 2098 })) 2099 return nullptr; 2100 break; 2101 case Intrinsic::assume: { 2102 Value *IIOperand = II->getArgOperand(0); 2103 SmallVector<OperandBundleDef, 4> OpBundles; 2104 II->getOperandBundlesAsDefs(OpBundles); 2105 2106 /// This will remove the boolean Condition from the assume given as 2107 /// argument and remove the assume if it becomes useless. 2108 /// always returns nullptr for use as a return values. 2109 auto RemoveConditionFromAssume = [&](Instruction *Assume) -> Instruction * { 2110 assert(isa<AssumeInst>(Assume)); 2111 if (isAssumeWithEmptyBundle(*cast<AssumeInst>(II))) 2112 return eraseInstFromFunction(CI); 2113 replaceUse(II->getOperandUse(0), ConstantInt::getTrue(II->getContext())); 2114 return nullptr; 2115 }; 2116 // Remove an assume if it is followed by an identical assume. 2117 // TODO: Do we need this? Unless there are conflicting assumptions, the 2118 // computeKnownBits(IIOperand) below here eliminates redundant assumes. 2119 Instruction *Next = II->getNextNonDebugInstruction(); 2120 if (match(Next, m_Intrinsic<Intrinsic::assume>(m_Specific(IIOperand)))) 2121 return RemoveConditionFromAssume(Next); 2122 2123 // Canonicalize assume(a && b) -> assume(a); assume(b); 2124 // Note: New assumption intrinsics created here are registered by 2125 // the InstCombineIRInserter object. 2126 FunctionType *AssumeIntrinsicTy = II->getFunctionType(); 2127 Value *AssumeIntrinsic = II->getCalledOperand(); 2128 Value *A, *B; 2129 if (match(IIOperand, m_LogicalAnd(m_Value(A), m_Value(B)))) { 2130 Builder.CreateCall(AssumeIntrinsicTy, AssumeIntrinsic, A, OpBundles, 2131 II->getName()); 2132 Builder.CreateCall(AssumeIntrinsicTy, AssumeIntrinsic, B, II->getName()); 2133 return eraseInstFromFunction(*II); 2134 } 2135 // assume(!(a || b)) -> assume(!a); assume(!b); 2136 if (match(IIOperand, m_Not(m_LogicalOr(m_Value(A), m_Value(B))))) { 2137 Builder.CreateCall(AssumeIntrinsicTy, AssumeIntrinsic, 2138 Builder.CreateNot(A), OpBundles, II->getName()); 2139 Builder.CreateCall(AssumeIntrinsicTy, AssumeIntrinsic, 2140 Builder.CreateNot(B), II->getName()); 2141 return eraseInstFromFunction(*II); 2142 } 2143 2144 // assume( (load addr) != null ) -> add 'nonnull' metadata to load 2145 // (if assume is valid at the load) 2146 CmpInst::Predicate Pred; 2147 Instruction *LHS; 2148 if (match(IIOperand, m_ICmp(Pred, m_Instruction(LHS), m_Zero())) && 2149 Pred == ICmpInst::ICMP_NE && LHS->getOpcode() == Instruction::Load && 2150 LHS->getType()->isPointerTy() && 2151 isValidAssumeForContext(II, LHS, &DT)) { 2152 MDNode *MD = MDNode::get(II->getContext(), None); 2153 LHS->setMetadata(LLVMContext::MD_nonnull, MD); 2154 return RemoveConditionFromAssume(II); 2155 2156 // TODO: apply nonnull return attributes to calls and invokes 2157 // TODO: apply range metadata for range check patterns? 2158 } 2159 2160 // Convert nonnull assume like: 2161 // %A = icmp ne i32* %PTR, null 2162 // call void @llvm.assume(i1 %A) 2163 // into 2164 // call void @llvm.assume(i1 true) [ "nonnull"(i32* %PTR) ] 2165 if (EnableKnowledgeRetention && 2166 match(IIOperand, m_Cmp(Pred, m_Value(A), m_Zero())) && 2167 Pred == CmpInst::ICMP_NE && A->getType()->isPointerTy()) { 2168 if (auto *Replacement = buildAssumeFromKnowledge( 2169 {RetainedKnowledge{Attribute::NonNull, 0, A}}, Next, &AC, &DT)) { 2170 2171 Replacement->insertBefore(Next); 2172 AC.registerAssumption(Replacement); 2173 return RemoveConditionFromAssume(II); 2174 } 2175 } 2176 2177 // Convert alignment assume like: 2178 // %B = ptrtoint i32* %A to i64 2179 // %C = and i64 %B, Constant 2180 // %D = icmp eq i64 %C, 0 2181 // call void @llvm.assume(i1 %D) 2182 // into 2183 // call void @llvm.assume(i1 true) [ "align"(i32* [[A]], i64 Constant + 1)] 2184 uint64_t AlignMask; 2185 if (EnableKnowledgeRetention && 2186 match(IIOperand, 2187 m_Cmp(Pred, m_And(m_Value(A), m_ConstantInt(AlignMask)), 2188 m_Zero())) && 2189 Pred == CmpInst::ICMP_EQ) { 2190 if (isPowerOf2_64(AlignMask + 1)) { 2191 uint64_t Offset = 0; 2192 match(A, m_Add(m_Value(A), m_ConstantInt(Offset))); 2193 if (match(A, m_PtrToInt(m_Value(A)))) { 2194 /// Note: this doesn't preserve the offset information but merges 2195 /// offset and alignment. 2196 /// TODO: we can generate a GEP instead of merging the alignment with 2197 /// the offset. 2198 RetainedKnowledge RK{Attribute::Alignment, 2199 (unsigned)MinAlign(Offset, AlignMask + 1), A}; 2200 if (auto *Replacement = 2201 buildAssumeFromKnowledge(RK, Next, &AC, &DT)) { 2202 2203 Replacement->insertAfter(II); 2204 AC.registerAssumption(Replacement); 2205 } 2206 return RemoveConditionFromAssume(II); 2207 } 2208 } 2209 } 2210 2211 /// Canonicalize Knowledge in operand bundles. 2212 if (EnableKnowledgeRetention && II->hasOperandBundles()) { 2213 for (unsigned Idx = 0; Idx < II->getNumOperandBundles(); Idx++) { 2214 auto &BOI = II->bundle_op_info_begin()[Idx]; 2215 RetainedKnowledge RK = 2216 llvm::getKnowledgeFromBundle(cast<AssumeInst>(*II), BOI); 2217 if (BOI.End - BOI.Begin > 2) 2218 continue; // Prevent reducing knowledge in an align with offset since 2219 // extracting a RetainedKnowledge form them looses offset 2220 // information 2221 RetainedKnowledge CanonRK = 2222 llvm::simplifyRetainedKnowledge(cast<AssumeInst>(II), RK, 2223 &getAssumptionCache(), 2224 &getDominatorTree()); 2225 if (CanonRK == RK) 2226 continue; 2227 if (!CanonRK) { 2228 if (BOI.End - BOI.Begin > 0) { 2229 Worklist.pushValue(II->op_begin()[BOI.Begin]); 2230 Value::dropDroppableUse(II->op_begin()[BOI.Begin]); 2231 } 2232 continue; 2233 } 2234 assert(RK.AttrKind == CanonRK.AttrKind); 2235 if (BOI.End - BOI.Begin > 0) 2236 II->op_begin()[BOI.Begin].set(CanonRK.WasOn); 2237 if (BOI.End - BOI.Begin > 1) 2238 II->op_begin()[BOI.Begin + 1].set(ConstantInt::get( 2239 Type::getInt64Ty(II->getContext()), CanonRK.ArgValue)); 2240 if (RK.WasOn) 2241 Worklist.pushValue(RK.WasOn); 2242 return II; 2243 } 2244 } 2245 2246 // If there is a dominating assume with the same condition as this one, 2247 // then this one is redundant, and should be removed. 2248 KnownBits Known(1); 2249 computeKnownBits(IIOperand, Known, 0, II); 2250 if (Known.isAllOnes() && isAssumeWithEmptyBundle(cast<AssumeInst>(*II))) 2251 return eraseInstFromFunction(*II); 2252 2253 // Update the cache of affected values for this assumption (we might be 2254 // here because we just simplified the condition). 2255 AC.updateAffectedValues(cast<AssumeInst>(II)); 2256 break; 2257 } 2258 case Intrinsic::experimental_guard: { 2259 // Is this guard followed by another guard? We scan forward over a small 2260 // fixed window of instructions to handle common cases with conditions 2261 // computed between guards. 2262 Instruction *NextInst = II->getNextNonDebugInstruction(); 2263 for (unsigned i = 0; i < GuardWideningWindow; i++) { 2264 // Note: Using context-free form to avoid compile time blow up 2265 if (!isSafeToSpeculativelyExecute(NextInst)) 2266 break; 2267 NextInst = NextInst->getNextNonDebugInstruction(); 2268 } 2269 Value *NextCond = nullptr; 2270 if (match(NextInst, 2271 m_Intrinsic<Intrinsic::experimental_guard>(m_Value(NextCond)))) { 2272 Value *CurrCond = II->getArgOperand(0); 2273 2274 // Remove a guard that it is immediately preceded by an identical guard. 2275 // Otherwise canonicalize guard(a); guard(b) -> guard(a & b). 2276 if (CurrCond != NextCond) { 2277 Instruction *MoveI = II->getNextNonDebugInstruction(); 2278 while (MoveI != NextInst) { 2279 auto *Temp = MoveI; 2280 MoveI = MoveI->getNextNonDebugInstruction(); 2281 Temp->moveBefore(II); 2282 } 2283 replaceOperand(*II, 0, Builder.CreateAnd(CurrCond, NextCond)); 2284 } 2285 eraseInstFromFunction(*NextInst); 2286 return II; 2287 } 2288 break; 2289 } 2290 case Intrinsic::experimental_vector_insert: { 2291 Value *Vec = II->getArgOperand(0); 2292 Value *SubVec = II->getArgOperand(1); 2293 Value *Idx = II->getArgOperand(2); 2294 auto *DstTy = dyn_cast<FixedVectorType>(II->getType()); 2295 auto *VecTy = dyn_cast<FixedVectorType>(Vec->getType()); 2296 auto *SubVecTy = dyn_cast<FixedVectorType>(SubVec->getType()); 2297 2298 // Only canonicalize if the destination vector, Vec, and SubVec are all 2299 // fixed vectors. 2300 if (DstTy && VecTy && SubVecTy) { 2301 unsigned DstNumElts = DstTy->getNumElements(); 2302 unsigned VecNumElts = VecTy->getNumElements(); 2303 unsigned SubVecNumElts = SubVecTy->getNumElements(); 2304 unsigned IdxN = cast<ConstantInt>(Idx)->getZExtValue(); 2305 2306 // An insert that entirely overwrites Vec with SubVec is a nop. 2307 if (VecNumElts == SubVecNumElts) 2308 return replaceInstUsesWith(CI, SubVec); 2309 2310 // Widen SubVec into a vector of the same width as Vec, since 2311 // shufflevector requires the two input vectors to be the same width. 2312 // Elements beyond the bounds of SubVec within the widened vector are 2313 // undefined. 2314 SmallVector<int, 8> WidenMask; 2315 unsigned i; 2316 for (i = 0; i != SubVecNumElts; ++i) 2317 WidenMask.push_back(i); 2318 for (; i != VecNumElts; ++i) 2319 WidenMask.push_back(UndefMaskElem); 2320 2321 Value *WidenShuffle = Builder.CreateShuffleVector(SubVec, WidenMask); 2322 2323 SmallVector<int, 8> Mask; 2324 for (unsigned i = 0; i != IdxN; ++i) 2325 Mask.push_back(i); 2326 for (unsigned i = DstNumElts; i != DstNumElts + SubVecNumElts; ++i) 2327 Mask.push_back(i); 2328 for (unsigned i = IdxN + SubVecNumElts; i != DstNumElts; ++i) 2329 Mask.push_back(i); 2330 2331 Value *Shuffle = Builder.CreateShuffleVector(Vec, WidenShuffle, Mask); 2332 return replaceInstUsesWith(CI, Shuffle); 2333 } 2334 break; 2335 } 2336 case Intrinsic::experimental_vector_extract: { 2337 Value *Vec = II->getArgOperand(0); 2338 Value *Idx = II->getArgOperand(1); 2339 2340 auto *DstTy = dyn_cast<FixedVectorType>(II->getType()); 2341 auto *VecTy = dyn_cast<FixedVectorType>(Vec->getType()); 2342 2343 // Only canonicalize if the the destination vector and Vec are fixed 2344 // vectors. 2345 if (DstTy && VecTy) { 2346 unsigned DstNumElts = DstTy->getNumElements(); 2347 unsigned VecNumElts = VecTy->getNumElements(); 2348 unsigned IdxN = cast<ConstantInt>(Idx)->getZExtValue(); 2349 2350 // Extracting the entirety of Vec is a nop. 2351 if (VecNumElts == DstNumElts) { 2352 replaceInstUsesWith(CI, Vec); 2353 return eraseInstFromFunction(CI); 2354 } 2355 2356 SmallVector<int, 8> Mask; 2357 for (unsigned i = 0; i != DstNumElts; ++i) 2358 Mask.push_back(IdxN + i); 2359 2360 Value *Shuffle = Builder.CreateShuffleVector(Vec, Mask); 2361 return replaceInstUsesWith(CI, Shuffle); 2362 } 2363 break; 2364 } 2365 case Intrinsic::experimental_vector_reverse: { 2366 Value *BO0, *BO1, *X, *Y; 2367 Value *Vec = II->getArgOperand(0); 2368 if (match(Vec, m_OneUse(m_BinOp(m_Value(BO0), m_Value(BO1))))) { 2369 auto *OldBinOp = cast<BinaryOperator>(Vec); 2370 if (match(BO0, m_Intrinsic<Intrinsic::experimental_vector_reverse>( 2371 m_Value(X)))) { 2372 // rev(binop rev(X), rev(Y)) --> binop X, Y 2373 if (match(BO1, m_Intrinsic<Intrinsic::experimental_vector_reverse>( 2374 m_Value(Y)))) 2375 return replaceInstUsesWith(CI, 2376 BinaryOperator::CreateWithCopiedFlags( 2377 OldBinOp->getOpcode(), X, Y, OldBinOp, 2378 OldBinOp->getName(), II)); 2379 // rev(binop rev(X), BO1Splat) --> binop X, BO1Splat 2380 if (isSplatValue(BO1)) 2381 return replaceInstUsesWith(CI, 2382 BinaryOperator::CreateWithCopiedFlags( 2383 OldBinOp->getOpcode(), X, BO1, 2384 OldBinOp, OldBinOp->getName(), II)); 2385 } 2386 // rev(binop BO0Splat, rev(Y)) --> binop BO0Splat, Y 2387 if (match(BO1, m_Intrinsic<Intrinsic::experimental_vector_reverse>( 2388 m_Value(Y))) && 2389 isSplatValue(BO0)) 2390 return replaceInstUsesWith(CI, BinaryOperator::CreateWithCopiedFlags( 2391 OldBinOp->getOpcode(), BO0, Y, 2392 OldBinOp, OldBinOp->getName(), II)); 2393 } 2394 // rev(unop rev(X)) --> unop X 2395 if (match(Vec, m_OneUse(m_UnOp( 2396 m_Intrinsic<Intrinsic::experimental_vector_reverse>( 2397 m_Value(X)))))) { 2398 auto *OldUnOp = cast<UnaryOperator>(Vec); 2399 auto *NewUnOp = UnaryOperator::CreateWithCopiedFlags( 2400 OldUnOp->getOpcode(), X, OldUnOp, OldUnOp->getName(), II); 2401 return replaceInstUsesWith(CI, NewUnOp); 2402 } 2403 break; 2404 } 2405 case Intrinsic::vector_reduce_or: 2406 case Intrinsic::vector_reduce_and: { 2407 // Canonicalize logical or/and reductions: 2408 // Or reduction for i1 is represented as: 2409 // %val = bitcast <ReduxWidth x i1> to iReduxWidth 2410 // %res = cmp ne iReduxWidth %val, 0 2411 // And reduction for i1 is represented as: 2412 // %val = bitcast <ReduxWidth x i1> to iReduxWidth 2413 // %res = cmp eq iReduxWidth %val, 11111 2414 Value *Arg = II->getArgOperand(0); 2415 Value *Vect; 2416 if (match(Arg, m_ZExtOrSExtOrSelf(m_Value(Vect)))) { 2417 if (auto *FTy = dyn_cast<FixedVectorType>(Vect->getType())) 2418 if (FTy->getElementType() == Builder.getInt1Ty()) { 2419 Value *Res = Builder.CreateBitCast( 2420 Vect, Builder.getIntNTy(FTy->getNumElements())); 2421 if (IID == Intrinsic::vector_reduce_and) { 2422 Res = Builder.CreateICmpEQ( 2423 Res, ConstantInt::getAllOnesValue(Res->getType())); 2424 } else { 2425 assert(IID == Intrinsic::vector_reduce_or && 2426 "Expected or reduction."); 2427 Res = Builder.CreateIsNotNull(Res); 2428 } 2429 if (Arg != Vect) 2430 Res = Builder.CreateCast(cast<CastInst>(Arg)->getOpcode(), Res, 2431 II->getType()); 2432 return replaceInstUsesWith(CI, Res); 2433 } 2434 } 2435 LLVM_FALLTHROUGH; 2436 } 2437 case Intrinsic::vector_reduce_add: { 2438 if (IID == Intrinsic::vector_reduce_add) { 2439 // Convert vector_reduce_add(ZExt(<n x i1>)) to 2440 // ZExtOrTrunc(ctpop(bitcast <n x i1> to in)). 2441 // Convert vector_reduce_add(SExt(<n x i1>)) to 2442 // -ZExtOrTrunc(ctpop(bitcast <n x i1> to in)). 2443 // Convert vector_reduce_add(<n x i1>) to 2444 // Trunc(ctpop(bitcast <n x i1> to in)). 2445 Value *Arg = II->getArgOperand(0); 2446 Value *Vect; 2447 if (match(Arg, m_ZExtOrSExtOrSelf(m_Value(Vect)))) { 2448 if (auto *FTy = dyn_cast<FixedVectorType>(Vect->getType())) 2449 if (FTy->getElementType() == Builder.getInt1Ty()) { 2450 Value *V = Builder.CreateBitCast( 2451 Vect, Builder.getIntNTy(FTy->getNumElements())); 2452 Value *Res = Builder.CreateUnaryIntrinsic(Intrinsic::ctpop, V); 2453 if (Res->getType() != II->getType()) 2454 Res = Builder.CreateZExtOrTrunc(Res, II->getType()); 2455 if (Arg != Vect && 2456 cast<Instruction>(Arg)->getOpcode() == Instruction::SExt) 2457 Res = Builder.CreateNeg(Res); 2458 return replaceInstUsesWith(CI, Res); 2459 } 2460 } 2461 } 2462 LLVM_FALLTHROUGH; 2463 } 2464 case Intrinsic::vector_reduce_xor: { 2465 if (IID == Intrinsic::vector_reduce_xor) { 2466 // Exclusive disjunction reduction over the vector with 2467 // (potentially-extended) i1 element type is actually a 2468 // (potentially-extended) arithmetic `add` reduction over the original 2469 // non-extended value: 2470 // vector_reduce_xor(?ext(<n x i1>)) 2471 // --> 2472 // ?ext(vector_reduce_add(<n x i1>)) 2473 Value *Arg = II->getArgOperand(0); 2474 Value *Vect; 2475 if (match(Arg, m_ZExtOrSExtOrSelf(m_Value(Vect)))) { 2476 if (auto *FTy = dyn_cast<FixedVectorType>(Vect->getType())) 2477 if (FTy->getElementType() == Builder.getInt1Ty()) { 2478 Value *Res = Builder.CreateAddReduce(Vect); 2479 if (Arg != Vect) 2480 Res = Builder.CreateCast(cast<CastInst>(Arg)->getOpcode(), Res, 2481 II->getType()); 2482 return replaceInstUsesWith(CI, Res); 2483 } 2484 } 2485 } 2486 LLVM_FALLTHROUGH; 2487 } 2488 case Intrinsic::vector_reduce_mul: { 2489 if (IID == Intrinsic::vector_reduce_mul) { 2490 // Multiplicative reduction over the vector with (potentially-extended) 2491 // i1 element type is actually a (potentially zero-extended) 2492 // logical `and` reduction over the original non-extended value: 2493 // vector_reduce_mul(?ext(<n x i1>)) 2494 // --> 2495 // zext(vector_reduce_and(<n x i1>)) 2496 Value *Arg = II->getArgOperand(0); 2497 Value *Vect; 2498 if (match(Arg, m_ZExtOrSExtOrSelf(m_Value(Vect)))) { 2499 if (auto *FTy = dyn_cast<FixedVectorType>(Vect->getType())) 2500 if (FTy->getElementType() == Builder.getInt1Ty()) { 2501 Value *Res = Builder.CreateAndReduce(Vect); 2502 if (Res->getType() != II->getType()) 2503 Res = Builder.CreateZExt(Res, II->getType()); 2504 return replaceInstUsesWith(CI, Res); 2505 } 2506 } 2507 } 2508 LLVM_FALLTHROUGH; 2509 } 2510 case Intrinsic::vector_reduce_umin: 2511 case Intrinsic::vector_reduce_umax: { 2512 if (IID == Intrinsic::vector_reduce_umin || 2513 IID == Intrinsic::vector_reduce_umax) { 2514 // UMin/UMax reduction over the vector with (potentially-extended) 2515 // i1 element type is actually a (potentially-extended) 2516 // logical `and`/`or` reduction over the original non-extended value: 2517 // vector_reduce_u{min,max}(?ext(<n x i1>)) 2518 // --> 2519 // ?ext(vector_reduce_{and,or}(<n x i1>)) 2520 Value *Arg = II->getArgOperand(0); 2521 Value *Vect; 2522 if (match(Arg, m_ZExtOrSExtOrSelf(m_Value(Vect)))) { 2523 if (auto *FTy = dyn_cast<FixedVectorType>(Vect->getType())) 2524 if (FTy->getElementType() == Builder.getInt1Ty()) { 2525 Value *Res = IID == Intrinsic::vector_reduce_umin 2526 ? Builder.CreateAndReduce(Vect) 2527 : Builder.CreateOrReduce(Vect); 2528 if (Arg != Vect) 2529 Res = Builder.CreateCast(cast<CastInst>(Arg)->getOpcode(), Res, 2530 II->getType()); 2531 return replaceInstUsesWith(CI, Res); 2532 } 2533 } 2534 } 2535 LLVM_FALLTHROUGH; 2536 } 2537 case Intrinsic::vector_reduce_smin: 2538 case Intrinsic::vector_reduce_smax: { 2539 if (IID == Intrinsic::vector_reduce_smin || 2540 IID == Intrinsic::vector_reduce_smax) { 2541 // SMin/SMax reduction over the vector with (potentially-extended) 2542 // i1 element type is actually a (potentially-extended) 2543 // logical `and`/`or` reduction over the original non-extended value: 2544 // vector_reduce_s{min,max}(<n x i1>) 2545 // --> 2546 // vector_reduce_{or,and}(<n x i1>) 2547 // and 2548 // vector_reduce_s{min,max}(sext(<n x i1>)) 2549 // --> 2550 // sext(vector_reduce_{or,and}(<n x i1>)) 2551 // and 2552 // vector_reduce_s{min,max}(zext(<n x i1>)) 2553 // --> 2554 // zext(vector_reduce_{and,or}(<n x i1>)) 2555 Value *Arg = II->getArgOperand(0); 2556 Value *Vect; 2557 if (match(Arg, m_ZExtOrSExtOrSelf(m_Value(Vect)))) { 2558 if (auto *FTy = dyn_cast<FixedVectorType>(Vect->getType())) 2559 if (FTy->getElementType() == Builder.getInt1Ty()) { 2560 Instruction::CastOps ExtOpc = Instruction::CastOps::CastOpsEnd; 2561 if (Arg != Vect) 2562 ExtOpc = cast<CastInst>(Arg)->getOpcode(); 2563 Value *Res = ((IID == Intrinsic::vector_reduce_smin) == 2564 (ExtOpc == Instruction::CastOps::ZExt)) 2565 ? Builder.CreateAndReduce(Vect) 2566 : Builder.CreateOrReduce(Vect); 2567 if (Arg != Vect) 2568 Res = Builder.CreateCast(ExtOpc, Res, II->getType()); 2569 return replaceInstUsesWith(CI, Res); 2570 } 2571 } 2572 } 2573 LLVM_FALLTHROUGH; 2574 } 2575 case Intrinsic::vector_reduce_fmax: 2576 case Intrinsic::vector_reduce_fmin: 2577 case Intrinsic::vector_reduce_fadd: 2578 case Intrinsic::vector_reduce_fmul: { 2579 bool CanBeReassociated = (IID != Intrinsic::vector_reduce_fadd && 2580 IID != Intrinsic::vector_reduce_fmul) || 2581 II->hasAllowReassoc(); 2582 const unsigned ArgIdx = (IID == Intrinsic::vector_reduce_fadd || 2583 IID == Intrinsic::vector_reduce_fmul) 2584 ? 1 2585 : 0; 2586 Value *Arg = II->getArgOperand(ArgIdx); 2587 Value *V; 2588 ArrayRef<int> Mask; 2589 if (!isa<FixedVectorType>(Arg->getType()) || !CanBeReassociated || 2590 !match(Arg, m_Shuffle(m_Value(V), m_Undef(), m_Mask(Mask))) || 2591 !cast<ShuffleVectorInst>(Arg)->isSingleSource()) 2592 break; 2593 int Sz = Mask.size(); 2594 SmallBitVector UsedIndices(Sz); 2595 for (int Idx : Mask) { 2596 if (Idx == UndefMaskElem || UsedIndices.test(Idx)) 2597 break; 2598 UsedIndices.set(Idx); 2599 } 2600 // Can remove shuffle iff just shuffled elements, no repeats, undefs, or 2601 // other changes. 2602 if (UsedIndices.all()) { 2603 replaceUse(II->getOperandUse(ArgIdx), V); 2604 return nullptr; 2605 } 2606 break; 2607 } 2608 default: { 2609 // Handle target specific intrinsics 2610 Optional<Instruction *> V = targetInstCombineIntrinsic(*II); 2611 if (V.hasValue()) 2612 return V.getValue(); 2613 break; 2614 } 2615 } 2616 // Some intrinsics (like experimental_gc_statepoint) can be used in invoke 2617 // context, so it is handled in visitCallBase and we should trigger it. 2618 return visitCallBase(*II); 2619 } 2620 2621 // Fence instruction simplification 2622 Instruction *InstCombinerImpl::visitFenceInst(FenceInst &FI) { 2623 auto *NFI = dyn_cast<FenceInst>(FI.getNextNonDebugInstruction()); 2624 // This check is solely here to handle arbitrary target-dependent syncscopes. 2625 // TODO: Can remove if does not matter in practice. 2626 if (NFI && FI.isIdenticalTo(NFI)) 2627 return eraseInstFromFunction(FI); 2628 2629 // Returns true if FI1 is identical or stronger fence than FI2. 2630 auto isIdenticalOrStrongerFence = [](FenceInst *FI1, FenceInst *FI2) { 2631 auto FI1SyncScope = FI1->getSyncScopeID(); 2632 // Consider same scope, where scope is global or single-thread. 2633 if (FI1SyncScope != FI2->getSyncScopeID() || 2634 (FI1SyncScope != SyncScope::System && 2635 FI1SyncScope != SyncScope::SingleThread)) 2636 return false; 2637 2638 return isAtLeastOrStrongerThan(FI1->getOrdering(), FI2->getOrdering()); 2639 }; 2640 if (NFI && isIdenticalOrStrongerFence(NFI, &FI)) 2641 return eraseInstFromFunction(FI); 2642 2643 if (auto *PFI = dyn_cast_or_null<FenceInst>(FI.getPrevNonDebugInstruction())) 2644 if (isIdenticalOrStrongerFence(PFI, &FI)) 2645 return eraseInstFromFunction(FI); 2646 return nullptr; 2647 } 2648 2649 // InvokeInst simplification 2650 Instruction *InstCombinerImpl::visitInvokeInst(InvokeInst &II) { 2651 return visitCallBase(II); 2652 } 2653 2654 // CallBrInst simplification 2655 Instruction *InstCombinerImpl::visitCallBrInst(CallBrInst &CBI) { 2656 return visitCallBase(CBI); 2657 } 2658 2659 /// If this cast does not affect the value passed through the varargs area, we 2660 /// can eliminate the use of the cast. 2661 static bool isSafeToEliminateVarargsCast(const CallBase &Call, 2662 const DataLayout &DL, 2663 const CastInst *const CI, 2664 const int ix) { 2665 if (!CI->isLosslessCast()) 2666 return false; 2667 2668 // If this is a GC intrinsic, avoid munging types. We need types for 2669 // statepoint reconstruction in SelectionDAG. 2670 // TODO: This is probably something which should be expanded to all 2671 // intrinsics since the entire point of intrinsics is that 2672 // they are understandable by the optimizer. 2673 if (isa<GCStatepointInst>(Call) || isa<GCRelocateInst>(Call) || 2674 isa<GCResultInst>(Call)) 2675 return false; 2676 2677 // Opaque pointers are compatible with any byval types. 2678 PointerType *SrcTy = cast<PointerType>(CI->getOperand(0)->getType()); 2679 if (SrcTy->isOpaque()) 2680 return true; 2681 2682 // The size of ByVal or InAlloca arguments is derived from the type, so we 2683 // can't change to a type with a different size. If the size were 2684 // passed explicitly we could avoid this check. 2685 if (!Call.isPassPointeeByValueArgument(ix)) 2686 return true; 2687 2688 // The transform currently only handles type replacement for byval, not other 2689 // type-carrying attributes. 2690 if (!Call.isByValArgument(ix)) 2691 return false; 2692 2693 Type *SrcElemTy = SrcTy->getNonOpaquePointerElementType(); 2694 Type *DstElemTy = Call.getParamByValType(ix); 2695 if (!SrcElemTy->isSized() || !DstElemTy->isSized()) 2696 return false; 2697 if (DL.getTypeAllocSize(SrcElemTy) != DL.getTypeAllocSize(DstElemTy)) 2698 return false; 2699 return true; 2700 } 2701 2702 Instruction *InstCombinerImpl::tryOptimizeCall(CallInst *CI) { 2703 if (!CI->getCalledFunction()) return nullptr; 2704 2705 // Skip optimizing notail and musttail calls so 2706 // LibCallSimplifier::optimizeCall doesn't have to preserve those invariants. 2707 // LibCallSimplifier::optimizeCall should try to preseve tail calls though. 2708 if (CI->isMustTailCall() || CI->isNoTailCall()) 2709 return nullptr; 2710 2711 auto InstCombineRAUW = [this](Instruction *From, Value *With) { 2712 replaceInstUsesWith(*From, With); 2713 }; 2714 auto InstCombineErase = [this](Instruction *I) { 2715 eraseInstFromFunction(*I); 2716 }; 2717 LibCallSimplifier Simplifier(DL, &TLI, ORE, BFI, PSI, InstCombineRAUW, 2718 InstCombineErase); 2719 if (Value *With = Simplifier.optimizeCall(CI, Builder)) { 2720 ++NumSimplified; 2721 return CI->use_empty() ? CI : replaceInstUsesWith(*CI, With); 2722 } 2723 2724 return nullptr; 2725 } 2726 2727 static IntrinsicInst *findInitTrampolineFromAlloca(Value *TrampMem) { 2728 // Strip off at most one level of pointer casts, looking for an alloca. This 2729 // is good enough in practice and simpler than handling any number of casts. 2730 Value *Underlying = TrampMem->stripPointerCasts(); 2731 if (Underlying != TrampMem && 2732 (!Underlying->hasOneUse() || Underlying->user_back() != TrampMem)) 2733 return nullptr; 2734 if (!isa<AllocaInst>(Underlying)) 2735 return nullptr; 2736 2737 IntrinsicInst *InitTrampoline = nullptr; 2738 for (User *U : TrampMem->users()) { 2739 IntrinsicInst *II = dyn_cast<IntrinsicInst>(U); 2740 if (!II) 2741 return nullptr; 2742 if (II->getIntrinsicID() == Intrinsic::init_trampoline) { 2743 if (InitTrampoline) 2744 // More than one init_trampoline writes to this value. Give up. 2745 return nullptr; 2746 InitTrampoline = II; 2747 continue; 2748 } 2749 if (II->getIntrinsicID() == Intrinsic::adjust_trampoline) 2750 // Allow any number of calls to adjust.trampoline. 2751 continue; 2752 return nullptr; 2753 } 2754 2755 // No call to init.trampoline found. 2756 if (!InitTrampoline) 2757 return nullptr; 2758 2759 // Check that the alloca is being used in the expected way. 2760 if (InitTrampoline->getOperand(0) != TrampMem) 2761 return nullptr; 2762 2763 return InitTrampoline; 2764 } 2765 2766 static IntrinsicInst *findInitTrampolineFromBB(IntrinsicInst *AdjustTramp, 2767 Value *TrampMem) { 2768 // Visit all the previous instructions in the basic block, and try to find a 2769 // init.trampoline which has a direct path to the adjust.trampoline. 2770 for (BasicBlock::iterator I = AdjustTramp->getIterator(), 2771 E = AdjustTramp->getParent()->begin(); 2772 I != E;) { 2773 Instruction *Inst = &*--I; 2774 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) 2775 if (II->getIntrinsicID() == Intrinsic::init_trampoline && 2776 II->getOperand(0) == TrampMem) 2777 return II; 2778 if (Inst->mayWriteToMemory()) 2779 return nullptr; 2780 } 2781 return nullptr; 2782 } 2783 2784 // Given a call to llvm.adjust.trampoline, find and return the corresponding 2785 // call to llvm.init.trampoline if the call to the trampoline can be optimized 2786 // to a direct call to a function. Otherwise return NULL. 2787 static IntrinsicInst *findInitTrampoline(Value *Callee) { 2788 Callee = Callee->stripPointerCasts(); 2789 IntrinsicInst *AdjustTramp = dyn_cast<IntrinsicInst>(Callee); 2790 if (!AdjustTramp || 2791 AdjustTramp->getIntrinsicID() != Intrinsic::adjust_trampoline) 2792 return nullptr; 2793 2794 Value *TrampMem = AdjustTramp->getOperand(0); 2795 2796 if (IntrinsicInst *IT = findInitTrampolineFromAlloca(TrampMem)) 2797 return IT; 2798 if (IntrinsicInst *IT = findInitTrampolineFromBB(AdjustTramp, TrampMem)) 2799 return IT; 2800 return nullptr; 2801 } 2802 2803 bool InstCombinerImpl::annotateAnyAllocSite(CallBase &Call, 2804 const TargetLibraryInfo *TLI) { 2805 // Note: We only handle cases which can't be driven from generic attributes 2806 // here. So, for example, nonnull and noalias (which are common properties 2807 // of some allocation functions) are expected to be handled via annotation 2808 // of the respective allocator declaration with generic attributes. 2809 bool Changed = false; 2810 2811 if (isAllocationFn(&Call, TLI)) { 2812 uint64_t Size; 2813 ObjectSizeOpts Opts; 2814 if (getObjectSize(&Call, Size, DL, TLI, Opts) && Size > 0) { 2815 // TODO: We really should just emit deref_or_null here and then 2816 // let the generic inference code combine that with nonnull. 2817 if (Call.hasRetAttr(Attribute::NonNull)) { 2818 Changed = !Call.hasRetAttr(Attribute::Dereferenceable); 2819 Call.addRetAttr( 2820 Attribute::getWithDereferenceableBytes(Call.getContext(), Size)); 2821 } else { 2822 Changed = !Call.hasRetAttr(Attribute::DereferenceableOrNull); 2823 Call.addRetAttr(Attribute::getWithDereferenceableOrNullBytes( 2824 Call.getContext(), Size)); 2825 } 2826 } 2827 } 2828 2829 // Add alignment attribute if alignment is a power of two constant. 2830 Value *Alignment = getAllocAlignment(&Call, TLI); 2831 if (!Alignment) 2832 return Changed; 2833 2834 ConstantInt *AlignOpC = dyn_cast<ConstantInt>(Alignment); 2835 if (AlignOpC && AlignOpC->getValue().ult(llvm::Value::MaximumAlignment)) { 2836 uint64_t AlignmentVal = AlignOpC->getZExtValue(); 2837 if (llvm::isPowerOf2_64(AlignmentVal)) { 2838 Align ExistingAlign = Call.getRetAlign().valueOrOne(); 2839 Align NewAlign = Align(AlignmentVal); 2840 if (NewAlign > ExistingAlign) { 2841 Call.addRetAttr( 2842 Attribute::getWithAlignment(Call.getContext(), NewAlign)); 2843 Changed = true; 2844 } 2845 } 2846 } 2847 return Changed; 2848 } 2849 2850 /// Improvements for call, callbr and invoke instructions. 2851 Instruction *InstCombinerImpl::visitCallBase(CallBase &Call) { 2852 bool Changed = annotateAnyAllocSite(Call, &TLI); 2853 2854 // Mark any parameters that are known to be non-null with the nonnull 2855 // attribute. This is helpful for inlining calls to functions with null 2856 // checks on their arguments. 2857 SmallVector<unsigned, 4> ArgNos; 2858 unsigned ArgNo = 0; 2859 2860 for (Value *V : Call.args()) { 2861 if (V->getType()->isPointerTy() && 2862 !Call.paramHasAttr(ArgNo, Attribute::NonNull) && 2863 isKnownNonZero(V, DL, 0, &AC, &Call, &DT)) 2864 ArgNos.push_back(ArgNo); 2865 ArgNo++; 2866 } 2867 2868 assert(ArgNo == Call.arg_size() && "Call arguments not processed correctly."); 2869 2870 if (!ArgNos.empty()) { 2871 AttributeList AS = Call.getAttributes(); 2872 LLVMContext &Ctx = Call.getContext(); 2873 AS = AS.addParamAttribute(Ctx, ArgNos, 2874 Attribute::get(Ctx, Attribute::NonNull)); 2875 Call.setAttributes(AS); 2876 Changed = true; 2877 } 2878 2879 // If the callee is a pointer to a function, attempt to move any casts to the 2880 // arguments of the call/callbr/invoke. 2881 Value *Callee = Call.getCalledOperand(); 2882 Function *CalleeF = dyn_cast<Function>(Callee); 2883 if ((!CalleeF || CalleeF->getFunctionType() != Call.getFunctionType()) && 2884 transformConstExprCastCall(Call)) 2885 return nullptr; 2886 2887 if (CalleeF) { 2888 // Remove the convergent attr on calls when the callee is not convergent. 2889 if (Call.isConvergent() && !CalleeF->isConvergent() && 2890 !CalleeF->isIntrinsic()) { 2891 LLVM_DEBUG(dbgs() << "Removing convergent attr from instr " << Call 2892 << "\n"); 2893 Call.setNotConvergent(); 2894 return &Call; 2895 } 2896 2897 // If the call and callee calling conventions don't match, and neither one 2898 // of the calling conventions is compatible with C calling convention 2899 // this call must be unreachable, as the call is undefined. 2900 if ((CalleeF->getCallingConv() != Call.getCallingConv() && 2901 !(CalleeF->getCallingConv() == llvm::CallingConv::C && 2902 TargetLibraryInfoImpl::isCallingConvCCompatible(&Call)) && 2903 !(Call.getCallingConv() == llvm::CallingConv::C && 2904 TargetLibraryInfoImpl::isCallingConvCCompatible(CalleeF))) && 2905 // Only do this for calls to a function with a body. A prototype may 2906 // not actually end up matching the implementation's calling conv for a 2907 // variety of reasons (e.g. it may be written in assembly). 2908 !CalleeF->isDeclaration()) { 2909 Instruction *OldCall = &Call; 2910 CreateNonTerminatorUnreachable(OldCall); 2911 // If OldCall does not return void then replaceInstUsesWith poison. 2912 // This allows ValueHandlers and custom metadata to adjust itself. 2913 if (!OldCall->getType()->isVoidTy()) 2914 replaceInstUsesWith(*OldCall, PoisonValue::get(OldCall->getType())); 2915 if (isa<CallInst>(OldCall)) 2916 return eraseInstFromFunction(*OldCall); 2917 2918 // We cannot remove an invoke or a callbr, because it would change thexi 2919 // CFG, just change the callee to a null pointer. 2920 cast<CallBase>(OldCall)->setCalledFunction( 2921 CalleeF->getFunctionType(), 2922 Constant::getNullValue(CalleeF->getType())); 2923 return nullptr; 2924 } 2925 } 2926 2927 // Calling a null function pointer is undefined if a null address isn't 2928 // dereferenceable. 2929 if ((isa<ConstantPointerNull>(Callee) && 2930 !NullPointerIsDefined(Call.getFunction())) || 2931 isa<UndefValue>(Callee)) { 2932 // If Call does not return void then replaceInstUsesWith poison. 2933 // This allows ValueHandlers and custom metadata to adjust itself. 2934 if (!Call.getType()->isVoidTy()) 2935 replaceInstUsesWith(Call, PoisonValue::get(Call.getType())); 2936 2937 if (Call.isTerminator()) { 2938 // Can't remove an invoke or callbr because we cannot change the CFG. 2939 return nullptr; 2940 } 2941 2942 // This instruction is not reachable, just remove it. 2943 CreateNonTerminatorUnreachable(&Call); 2944 return eraseInstFromFunction(Call); 2945 } 2946 2947 if (IntrinsicInst *II = findInitTrampoline(Callee)) 2948 return transformCallThroughTrampoline(Call, *II); 2949 2950 // TODO: Drop this transform once opaque pointer transition is done. 2951 FunctionType *FTy = Call.getFunctionType(); 2952 if (FTy->isVarArg()) { 2953 int ix = FTy->getNumParams(); 2954 // See if we can optimize any arguments passed through the varargs area of 2955 // the call. 2956 for (auto I = Call.arg_begin() + FTy->getNumParams(), E = Call.arg_end(); 2957 I != E; ++I, ++ix) { 2958 CastInst *CI = dyn_cast<CastInst>(*I); 2959 if (CI && isSafeToEliminateVarargsCast(Call, DL, CI, ix)) { 2960 replaceUse(*I, CI->getOperand(0)); 2961 2962 // Update the byval type to match the pointer type. 2963 // Not necessary for opaque pointers. 2964 PointerType *NewTy = cast<PointerType>(CI->getOperand(0)->getType()); 2965 if (!NewTy->isOpaque() && Call.isByValArgument(ix)) { 2966 Call.removeParamAttr(ix, Attribute::ByVal); 2967 Call.addParamAttr(ix, Attribute::getWithByValType( 2968 Call.getContext(), 2969 NewTy->getNonOpaquePointerElementType())); 2970 } 2971 Changed = true; 2972 } 2973 } 2974 } 2975 2976 if (isa<InlineAsm>(Callee) && !Call.doesNotThrow()) { 2977 InlineAsm *IA = cast<InlineAsm>(Callee); 2978 if (!IA->canThrow()) { 2979 // Normal inline asm calls cannot throw - mark them 2980 // 'nounwind'. 2981 Call.setDoesNotThrow(); 2982 Changed = true; 2983 } 2984 } 2985 2986 // Try to optimize the call if possible, we require DataLayout for most of 2987 // this. None of these calls are seen as possibly dead so go ahead and 2988 // delete the instruction now. 2989 if (CallInst *CI = dyn_cast<CallInst>(&Call)) { 2990 Instruction *I = tryOptimizeCall(CI); 2991 // If we changed something return the result, etc. Otherwise let 2992 // the fallthrough check. 2993 if (I) return eraseInstFromFunction(*I); 2994 } 2995 2996 if (!Call.use_empty() && !Call.isMustTailCall()) 2997 if (Value *ReturnedArg = Call.getReturnedArgOperand()) { 2998 Type *CallTy = Call.getType(); 2999 Type *RetArgTy = ReturnedArg->getType(); 3000 if (RetArgTy->canLosslesslyBitCastTo(CallTy)) 3001 return replaceInstUsesWith( 3002 Call, Builder.CreateBitOrPointerCast(ReturnedArg, CallTy)); 3003 } 3004 3005 if (isAllocationFn(&Call, &TLI) && 3006 isAllocRemovable(&cast<CallBase>(Call), &TLI)) 3007 return visitAllocSite(Call); 3008 3009 // Handle intrinsics which can be used in both call and invoke context. 3010 switch (Call.getIntrinsicID()) { 3011 case Intrinsic::experimental_gc_statepoint: { 3012 GCStatepointInst &GCSP = *cast<GCStatepointInst>(&Call); 3013 SmallPtrSet<Value *, 32> LiveGcValues; 3014 for (const GCRelocateInst *Reloc : GCSP.getGCRelocates()) { 3015 GCRelocateInst &GCR = *const_cast<GCRelocateInst *>(Reloc); 3016 3017 // Remove the relocation if unused. 3018 if (GCR.use_empty()) { 3019 eraseInstFromFunction(GCR); 3020 continue; 3021 } 3022 3023 Value *DerivedPtr = GCR.getDerivedPtr(); 3024 Value *BasePtr = GCR.getBasePtr(); 3025 3026 // Undef is undef, even after relocation. 3027 if (isa<UndefValue>(DerivedPtr) || isa<UndefValue>(BasePtr)) { 3028 replaceInstUsesWith(GCR, UndefValue::get(GCR.getType())); 3029 eraseInstFromFunction(GCR); 3030 continue; 3031 } 3032 3033 if (auto *PT = dyn_cast<PointerType>(GCR.getType())) { 3034 // The relocation of null will be null for most any collector. 3035 // TODO: provide a hook for this in GCStrategy. There might be some 3036 // weird collector this property does not hold for. 3037 if (isa<ConstantPointerNull>(DerivedPtr)) { 3038 // Use null-pointer of gc_relocate's type to replace it. 3039 replaceInstUsesWith(GCR, ConstantPointerNull::get(PT)); 3040 eraseInstFromFunction(GCR); 3041 continue; 3042 } 3043 3044 // isKnownNonNull -> nonnull attribute 3045 if (!GCR.hasRetAttr(Attribute::NonNull) && 3046 isKnownNonZero(DerivedPtr, DL, 0, &AC, &Call, &DT)) { 3047 GCR.addRetAttr(Attribute::NonNull); 3048 // We discovered new fact, re-check users. 3049 Worklist.pushUsersToWorkList(GCR); 3050 } 3051 } 3052 3053 // If we have two copies of the same pointer in the statepoint argument 3054 // list, canonicalize to one. This may let us common gc.relocates. 3055 if (GCR.getBasePtr() == GCR.getDerivedPtr() && 3056 GCR.getBasePtrIndex() != GCR.getDerivedPtrIndex()) { 3057 auto *OpIntTy = GCR.getOperand(2)->getType(); 3058 GCR.setOperand(2, ConstantInt::get(OpIntTy, GCR.getBasePtrIndex())); 3059 } 3060 3061 // TODO: bitcast(relocate(p)) -> relocate(bitcast(p)) 3062 // Canonicalize on the type from the uses to the defs 3063 3064 // TODO: relocate((gep p, C, C2, ...)) -> gep(relocate(p), C, C2, ...) 3065 LiveGcValues.insert(BasePtr); 3066 LiveGcValues.insert(DerivedPtr); 3067 } 3068 Optional<OperandBundleUse> Bundle = 3069 GCSP.getOperandBundle(LLVMContext::OB_gc_live); 3070 unsigned NumOfGCLives = LiveGcValues.size(); 3071 if (!Bundle.hasValue() || NumOfGCLives == Bundle->Inputs.size()) 3072 break; 3073 // We can reduce the size of gc live bundle. 3074 DenseMap<Value *, unsigned> Val2Idx; 3075 std::vector<Value *> NewLiveGc; 3076 for (unsigned I = 0, E = Bundle->Inputs.size(); I < E; ++I) { 3077 Value *V = Bundle->Inputs[I]; 3078 if (Val2Idx.count(V)) 3079 continue; 3080 if (LiveGcValues.count(V)) { 3081 Val2Idx[V] = NewLiveGc.size(); 3082 NewLiveGc.push_back(V); 3083 } else 3084 Val2Idx[V] = NumOfGCLives; 3085 } 3086 // Update all gc.relocates 3087 for (const GCRelocateInst *Reloc : GCSP.getGCRelocates()) { 3088 GCRelocateInst &GCR = *const_cast<GCRelocateInst *>(Reloc); 3089 Value *BasePtr = GCR.getBasePtr(); 3090 assert(Val2Idx.count(BasePtr) && Val2Idx[BasePtr] != NumOfGCLives && 3091 "Missed live gc for base pointer"); 3092 auto *OpIntTy1 = GCR.getOperand(1)->getType(); 3093 GCR.setOperand(1, ConstantInt::get(OpIntTy1, Val2Idx[BasePtr])); 3094 Value *DerivedPtr = GCR.getDerivedPtr(); 3095 assert(Val2Idx.count(DerivedPtr) && Val2Idx[DerivedPtr] != NumOfGCLives && 3096 "Missed live gc for derived pointer"); 3097 auto *OpIntTy2 = GCR.getOperand(2)->getType(); 3098 GCR.setOperand(2, ConstantInt::get(OpIntTy2, Val2Idx[DerivedPtr])); 3099 } 3100 // Create new statepoint instruction. 3101 OperandBundleDef NewBundle("gc-live", NewLiveGc); 3102 return CallBase::Create(&Call, NewBundle); 3103 } 3104 default: { break; } 3105 } 3106 3107 return Changed ? &Call : nullptr; 3108 } 3109 3110 /// If the callee is a constexpr cast of a function, attempt to move the cast to 3111 /// the arguments of the call/callbr/invoke. 3112 bool InstCombinerImpl::transformConstExprCastCall(CallBase &Call) { 3113 auto *Callee = 3114 dyn_cast<Function>(Call.getCalledOperand()->stripPointerCasts()); 3115 if (!Callee) 3116 return false; 3117 3118 // If this is a call to a thunk function, don't remove the cast. Thunks are 3119 // used to transparently forward all incoming parameters and outgoing return 3120 // values, so it's important to leave the cast in place. 3121 if (Callee->hasFnAttribute("thunk")) 3122 return false; 3123 3124 // If this is a musttail call, the callee's prototype must match the caller's 3125 // prototype with the exception of pointee types. The code below doesn't 3126 // implement that, so we can't do this transform. 3127 // TODO: Do the transform if it only requires adding pointer casts. 3128 if (Call.isMustTailCall()) 3129 return false; 3130 3131 Instruction *Caller = &Call; 3132 const AttributeList &CallerPAL = Call.getAttributes(); 3133 3134 // Okay, this is a cast from a function to a different type. Unless doing so 3135 // would cause a type conversion of one of our arguments, change this call to 3136 // be a direct call with arguments casted to the appropriate types. 3137 FunctionType *FT = Callee->getFunctionType(); 3138 Type *OldRetTy = Caller->getType(); 3139 Type *NewRetTy = FT->getReturnType(); 3140 3141 // Check to see if we are changing the return type... 3142 if (OldRetTy != NewRetTy) { 3143 3144 if (NewRetTy->isStructTy()) 3145 return false; // TODO: Handle multiple return values. 3146 3147 if (!CastInst::isBitOrNoopPointerCastable(NewRetTy, OldRetTy, DL)) { 3148 if (Callee->isDeclaration()) 3149 return false; // Cannot transform this return value. 3150 3151 if (!Caller->use_empty() && 3152 // void -> non-void is handled specially 3153 !NewRetTy->isVoidTy()) 3154 return false; // Cannot transform this return value. 3155 } 3156 3157 if (!CallerPAL.isEmpty() && !Caller->use_empty()) { 3158 AttrBuilder RAttrs(FT->getContext(), CallerPAL.getRetAttrs()); 3159 if (RAttrs.overlaps(AttributeFuncs::typeIncompatible(NewRetTy))) 3160 return false; // Attribute not compatible with transformed value. 3161 } 3162 3163 // If the callbase is an invoke/callbr instruction, and the return value is 3164 // used by a PHI node in a successor, we cannot change the return type of 3165 // the call because there is no place to put the cast instruction (without 3166 // breaking the critical edge). Bail out in this case. 3167 if (!Caller->use_empty()) { 3168 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) 3169 for (User *U : II->users()) 3170 if (PHINode *PN = dyn_cast<PHINode>(U)) 3171 if (PN->getParent() == II->getNormalDest() || 3172 PN->getParent() == II->getUnwindDest()) 3173 return false; 3174 // FIXME: Be conservative for callbr to avoid a quadratic search. 3175 if (isa<CallBrInst>(Caller)) 3176 return false; 3177 } 3178 } 3179 3180 unsigned NumActualArgs = Call.arg_size(); 3181 unsigned NumCommonArgs = std::min(FT->getNumParams(), NumActualArgs); 3182 3183 // Prevent us turning: 3184 // declare void @takes_i32_inalloca(i32* inalloca) 3185 // call void bitcast (void (i32*)* @takes_i32_inalloca to void (i32)*)(i32 0) 3186 // 3187 // into: 3188 // call void @takes_i32_inalloca(i32* null) 3189 // 3190 // Similarly, avoid folding away bitcasts of byval calls. 3191 if (Callee->getAttributes().hasAttrSomewhere(Attribute::InAlloca) || 3192 Callee->getAttributes().hasAttrSomewhere(Attribute::Preallocated)) 3193 return false; 3194 3195 auto AI = Call.arg_begin(); 3196 for (unsigned i = 0, e = NumCommonArgs; i != e; ++i, ++AI) { 3197 Type *ParamTy = FT->getParamType(i); 3198 Type *ActTy = (*AI)->getType(); 3199 3200 if (!CastInst::isBitOrNoopPointerCastable(ActTy, ParamTy, DL)) 3201 return false; // Cannot transform this parameter value. 3202 3203 // Check if there are any incompatible attributes we cannot drop safely. 3204 if (AttrBuilder(FT->getContext(), CallerPAL.getParamAttrs(i)) 3205 .overlaps(AttributeFuncs::typeIncompatible( 3206 ParamTy, AttributeFuncs::ASK_UNSAFE_TO_DROP))) 3207 return false; // Attribute not compatible with transformed value. 3208 3209 if (Call.isInAllocaArgument(i) || 3210 CallerPAL.hasParamAttr(i, Attribute::Preallocated)) 3211 return false; // Cannot transform to and from inalloca/preallocated. 3212 3213 if (CallerPAL.hasParamAttr(i, Attribute::SwiftError)) 3214 return false; 3215 3216 // If the parameter is passed as a byval argument, then we have to have a 3217 // sized type and the sized type has to have the same size as the old type. 3218 if (ParamTy != ActTy && CallerPAL.hasParamAttr(i, Attribute::ByVal)) { 3219 PointerType *ParamPTy = dyn_cast<PointerType>(ParamTy); 3220 if (!ParamPTy) 3221 return false; 3222 3223 if (!ParamPTy->isOpaque()) { 3224 Type *ParamElTy = ParamPTy->getNonOpaquePointerElementType(); 3225 if (!ParamElTy->isSized()) 3226 return false; 3227 3228 Type *CurElTy = Call.getParamByValType(i); 3229 if (DL.getTypeAllocSize(CurElTy) != DL.getTypeAllocSize(ParamElTy)) 3230 return false; 3231 } 3232 } 3233 } 3234 3235 if (Callee->isDeclaration()) { 3236 // Do not delete arguments unless we have a function body. 3237 if (FT->getNumParams() < NumActualArgs && !FT->isVarArg()) 3238 return false; 3239 3240 // If the callee is just a declaration, don't change the varargsness of the 3241 // call. We don't want to introduce a varargs call where one doesn't 3242 // already exist. 3243 if (FT->isVarArg() != Call.getFunctionType()->isVarArg()) 3244 return false; 3245 3246 // If both the callee and the cast type are varargs, we still have to make 3247 // sure the number of fixed parameters are the same or we have the same 3248 // ABI issues as if we introduce a varargs call. 3249 if (FT->isVarArg() && Call.getFunctionType()->isVarArg() && 3250 FT->getNumParams() != Call.getFunctionType()->getNumParams()) 3251 return false; 3252 } 3253 3254 if (FT->getNumParams() < NumActualArgs && FT->isVarArg() && 3255 !CallerPAL.isEmpty()) { 3256 // In this case we have more arguments than the new function type, but we 3257 // won't be dropping them. Check that these extra arguments have attributes 3258 // that are compatible with being a vararg call argument. 3259 unsigned SRetIdx; 3260 if (CallerPAL.hasAttrSomewhere(Attribute::StructRet, &SRetIdx) && 3261 SRetIdx - AttributeList::FirstArgIndex >= FT->getNumParams()) 3262 return false; 3263 } 3264 3265 // Okay, we decided that this is a safe thing to do: go ahead and start 3266 // inserting cast instructions as necessary. 3267 SmallVector<Value *, 8> Args; 3268 SmallVector<AttributeSet, 8> ArgAttrs; 3269 Args.reserve(NumActualArgs); 3270 ArgAttrs.reserve(NumActualArgs); 3271 3272 // Get any return attributes. 3273 AttrBuilder RAttrs(FT->getContext(), CallerPAL.getRetAttrs()); 3274 3275 // If the return value is not being used, the type may not be compatible 3276 // with the existing attributes. Wipe out any problematic attributes. 3277 RAttrs.remove(AttributeFuncs::typeIncompatible(NewRetTy)); 3278 3279 LLVMContext &Ctx = Call.getContext(); 3280 AI = Call.arg_begin(); 3281 for (unsigned i = 0; i != NumCommonArgs; ++i, ++AI) { 3282 Type *ParamTy = FT->getParamType(i); 3283 3284 Value *NewArg = *AI; 3285 if ((*AI)->getType() != ParamTy) 3286 NewArg = Builder.CreateBitOrPointerCast(*AI, ParamTy); 3287 Args.push_back(NewArg); 3288 3289 // Add any parameter attributes except the ones incompatible with the new 3290 // type. Note that we made sure all incompatible ones are safe to drop. 3291 AttributeMask IncompatibleAttrs = AttributeFuncs::typeIncompatible( 3292 ParamTy, AttributeFuncs::ASK_SAFE_TO_DROP); 3293 if (CallerPAL.hasParamAttr(i, Attribute::ByVal) && 3294 !ParamTy->isOpaquePointerTy()) { 3295 AttrBuilder AB(Ctx, CallerPAL.getParamAttrs(i).removeAttributes( 3296 Ctx, IncompatibleAttrs)); 3297 AB.addByValAttr(ParamTy->getNonOpaquePointerElementType()); 3298 ArgAttrs.push_back(AttributeSet::get(Ctx, AB)); 3299 } else { 3300 ArgAttrs.push_back( 3301 CallerPAL.getParamAttrs(i).removeAttributes(Ctx, IncompatibleAttrs)); 3302 } 3303 } 3304 3305 // If the function takes more arguments than the call was taking, add them 3306 // now. 3307 for (unsigned i = NumCommonArgs; i != FT->getNumParams(); ++i) { 3308 Args.push_back(Constant::getNullValue(FT->getParamType(i))); 3309 ArgAttrs.push_back(AttributeSet()); 3310 } 3311 3312 // If we are removing arguments to the function, emit an obnoxious warning. 3313 if (FT->getNumParams() < NumActualArgs) { 3314 // TODO: if (!FT->isVarArg()) this call may be unreachable. PR14722 3315 if (FT->isVarArg()) { 3316 // Add all of the arguments in their promoted form to the arg list. 3317 for (unsigned i = FT->getNumParams(); i != NumActualArgs; ++i, ++AI) { 3318 Type *PTy = getPromotedType((*AI)->getType()); 3319 Value *NewArg = *AI; 3320 if (PTy != (*AI)->getType()) { 3321 // Must promote to pass through va_arg area! 3322 Instruction::CastOps opcode = 3323 CastInst::getCastOpcode(*AI, false, PTy, false); 3324 NewArg = Builder.CreateCast(opcode, *AI, PTy); 3325 } 3326 Args.push_back(NewArg); 3327 3328 // Add any parameter attributes. 3329 ArgAttrs.push_back(CallerPAL.getParamAttrs(i)); 3330 } 3331 } 3332 } 3333 3334 AttributeSet FnAttrs = CallerPAL.getFnAttrs(); 3335 3336 if (NewRetTy->isVoidTy()) 3337 Caller->setName(""); // Void type should not have a name. 3338 3339 assert((ArgAttrs.size() == FT->getNumParams() || FT->isVarArg()) && 3340 "missing argument attributes"); 3341 AttributeList NewCallerPAL = AttributeList::get( 3342 Ctx, FnAttrs, AttributeSet::get(Ctx, RAttrs), ArgAttrs); 3343 3344 SmallVector<OperandBundleDef, 1> OpBundles; 3345 Call.getOperandBundlesAsDefs(OpBundles); 3346 3347 CallBase *NewCall; 3348 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) { 3349 NewCall = Builder.CreateInvoke(Callee, II->getNormalDest(), 3350 II->getUnwindDest(), Args, OpBundles); 3351 } else if (CallBrInst *CBI = dyn_cast<CallBrInst>(Caller)) { 3352 NewCall = Builder.CreateCallBr(Callee, CBI->getDefaultDest(), 3353 CBI->getIndirectDests(), Args, OpBundles); 3354 } else { 3355 NewCall = Builder.CreateCall(Callee, Args, OpBundles); 3356 cast<CallInst>(NewCall)->setTailCallKind( 3357 cast<CallInst>(Caller)->getTailCallKind()); 3358 } 3359 NewCall->takeName(Caller); 3360 NewCall->setCallingConv(Call.getCallingConv()); 3361 NewCall->setAttributes(NewCallerPAL); 3362 3363 // Preserve prof metadata if any. 3364 NewCall->copyMetadata(*Caller, {LLVMContext::MD_prof}); 3365 3366 // Insert a cast of the return type as necessary. 3367 Instruction *NC = NewCall; 3368 Value *NV = NC; 3369 if (OldRetTy != NV->getType() && !Caller->use_empty()) { 3370 if (!NV->getType()->isVoidTy()) { 3371 NV = NC = CastInst::CreateBitOrPointerCast(NC, OldRetTy); 3372 NC->setDebugLoc(Caller->getDebugLoc()); 3373 3374 // If this is an invoke/callbr instruction, we should insert it after the 3375 // first non-phi instruction in the normal successor block. 3376 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) { 3377 BasicBlock::iterator I = II->getNormalDest()->getFirstInsertionPt(); 3378 InsertNewInstBefore(NC, *I); 3379 } else if (CallBrInst *CBI = dyn_cast<CallBrInst>(Caller)) { 3380 BasicBlock::iterator I = CBI->getDefaultDest()->getFirstInsertionPt(); 3381 InsertNewInstBefore(NC, *I); 3382 } else { 3383 // Otherwise, it's a call, just insert cast right after the call. 3384 InsertNewInstBefore(NC, *Caller); 3385 } 3386 Worklist.pushUsersToWorkList(*Caller); 3387 } else { 3388 NV = UndefValue::get(Caller->getType()); 3389 } 3390 } 3391 3392 if (!Caller->use_empty()) 3393 replaceInstUsesWith(*Caller, NV); 3394 else if (Caller->hasValueHandle()) { 3395 if (OldRetTy == NV->getType()) 3396 ValueHandleBase::ValueIsRAUWd(Caller, NV); 3397 else 3398 // We cannot call ValueIsRAUWd with a different type, and the 3399 // actual tracked value will disappear. 3400 ValueHandleBase::ValueIsDeleted(Caller); 3401 } 3402 3403 eraseInstFromFunction(*Caller); 3404 return true; 3405 } 3406 3407 /// Turn a call to a function created by init_trampoline / adjust_trampoline 3408 /// intrinsic pair into a direct call to the underlying function. 3409 Instruction * 3410 InstCombinerImpl::transformCallThroughTrampoline(CallBase &Call, 3411 IntrinsicInst &Tramp) { 3412 Value *Callee = Call.getCalledOperand(); 3413 Type *CalleeTy = Callee->getType(); 3414 FunctionType *FTy = Call.getFunctionType(); 3415 AttributeList Attrs = Call.getAttributes(); 3416 3417 // If the call already has the 'nest' attribute somewhere then give up - 3418 // otherwise 'nest' would occur twice after splicing in the chain. 3419 if (Attrs.hasAttrSomewhere(Attribute::Nest)) 3420 return nullptr; 3421 3422 Function *NestF = cast<Function>(Tramp.getArgOperand(1)->stripPointerCasts()); 3423 FunctionType *NestFTy = NestF->getFunctionType(); 3424 3425 AttributeList NestAttrs = NestF->getAttributes(); 3426 if (!NestAttrs.isEmpty()) { 3427 unsigned NestArgNo = 0; 3428 Type *NestTy = nullptr; 3429 AttributeSet NestAttr; 3430 3431 // Look for a parameter marked with the 'nest' attribute. 3432 for (FunctionType::param_iterator I = NestFTy->param_begin(), 3433 E = NestFTy->param_end(); 3434 I != E; ++NestArgNo, ++I) { 3435 AttributeSet AS = NestAttrs.getParamAttrs(NestArgNo); 3436 if (AS.hasAttribute(Attribute::Nest)) { 3437 // Record the parameter type and any other attributes. 3438 NestTy = *I; 3439 NestAttr = AS; 3440 break; 3441 } 3442 } 3443 3444 if (NestTy) { 3445 std::vector<Value*> NewArgs; 3446 std::vector<AttributeSet> NewArgAttrs; 3447 NewArgs.reserve(Call.arg_size() + 1); 3448 NewArgAttrs.reserve(Call.arg_size()); 3449 3450 // Insert the nest argument into the call argument list, which may 3451 // mean appending it. Likewise for attributes. 3452 3453 { 3454 unsigned ArgNo = 0; 3455 auto I = Call.arg_begin(), E = Call.arg_end(); 3456 do { 3457 if (ArgNo == NestArgNo) { 3458 // Add the chain argument and attributes. 3459 Value *NestVal = Tramp.getArgOperand(2); 3460 if (NestVal->getType() != NestTy) 3461 NestVal = Builder.CreateBitCast(NestVal, NestTy, "nest"); 3462 NewArgs.push_back(NestVal); 3463 NewArgAttrs.push_back(NestAttr); 3464 } 3465 3466 if (I == E) 3467 break; 3468 3469 // Add the original argument and attributes. 3470 NewArgs.push_back(*I); 3471 NewArgAttrs.push_back(Attrs.getParamAttrs(ArgNo)); 3472 3473 ++ArgNo; 3474 ++I; 3475 } while (true); 3476 } 3477 3478 // The trampoline may have been bitcast to a bogus type (FTy). 3479 // Handle this by synthesizing a new function type, equal to FTy 3480 // with the chain parameter inserted. 3481 3482 std::vector<Type*> NewTypes; 3483 NewTypes.reserve(FTy->getNumParams()+1); 3484 3485 // Insert the chain's type into the list of parameter types, which may 3486 // mean appending it. 3487 { 3488 unsigned ArgNo = 0; 3489 FunctionType::param_iterator I = FTy->param_begin(), 3490 E = FTy->param_end(); 3491 3492 do { 3493 if (ArgNo == NestArgNo) 3494 // Add the chain's type. 3495 NewTypes.push_back(NestTy); 3496 3497 if (I == E) 3498 break; 3499 3500 // Add the original type. 3501 NewTypes.push_back(*I); 3502 3503 ++ArgNo; 3504 ++I; 3505 } while (true); 3506 } 3507 3508 // Replace the trampoline call with a direct call. Let the generic 3509 // code sort out any function type mismatches. 3510 FunctionType *NewFTy = FunctionType::get(FTy->getReturnType(), NewTypes, 3511 FTy->isVarArg()); 3512 Constant *NewCallee = 3513 NestF->getType() == PointerType::getUnqual(NewFTy) ? 3514 NestF : ConstantExpr::getBitCast(NestF, 3515 PointerType::getUnqual(NewFTy)); 3516 AttributeList NewPAL = 3517 AttributeList::get(FTy->getContext(), Attrs.getFnAttrs(), 3518 Attrs.getRetAttrs(), NewArgAttrs); 3519 3520 SmallVector<OperandBundleDef, 1> OpBundles; 3521 Call.getOperandBundlesAsDefs(OpBundles); 3522 3523 Instruction *NewCaller; 3524 if (InvokeInst *II = dyn_cast<InvokeInst>(&Call)) { 3525 NewCaller = InvokeInst::Create(NewFTy, NewCallee, 3526 II->getNormalDest(), II->getUnwindDest(), 3527 NewArgs, OpBundles); 3528 cast<InvokeInst>(NewCaller)->setCallingConv(II->getCallingConv()); 3529 cast<InvokeInst>(NewCaller)->setAttributes(NewPAL); 3530 } else if (CallBrInst *CBI = dyn_cast<CallBrInst>(&Call)) { 3531 NewCaller = 3532 CallBrInst::Create(NewFTy, NewCallee, CBI->getDefaultDest(), 3533 CBI->getIndirectDests(), NewArgs, OpBundles); 3534 cast<CallBrInst>(NewCaller)->setCallingConv(CBI->getCallingConv()); 3535 cast<CallBrInst>(NewCaller)->setAttributes(NewPAL); 3536 } else { 3537 NewCaller = CallInst::Create(NewFTy, NewCallee, NewArgs, OpBundles); 3538 cast<CallInst>(NewCaller)->setTailCallKind( 3539 cast<CallInst>(Call).getTailCallKind()); 3540 cast<CallInst>(NewCaller)->setCallingConv( 3541 cast<CallInst>(Call).getCallingConv()); 3542 cast<CallInst>(NewCaller)->setAttributes(NewPAL); 3543 } 3544 NewCaller->setDebugLoc(Call.getDebugLoc()); 3545 3546 return NewCaller; 3547 } 3548 } 3549 3550 // Replace the trampoline call with a direct call. Since there is no 'nest' 3551 // parameter, there is no need to adjust the argument list. Let the generic 3552 // code sort out any function type mismatches. 3553 Constant *NewCallee = ConstantExpr::getBitCast(NestF, CalleeTy); 3554 Call.setCalledFunction(FTy, NewCallee); 3555 return &Call; 3556 } 3557