blob: 657d95b5b246f01571c0c9c6378cb17a0e530c40 [file] [log] [blame]
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001//===- InstCombineCalls.cpp -----------------------------------------------===//
2//
Chandler Carruth2946cd72019-01-19 08:50:56 +00003// 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
Chris Lattner7a9e47a2010-01-05 07:32:13 +00006//
7//===----------------------------------------------------------------------===//
8//
Craig Topper784929d2019-02-08 20:48:56 +00009// This file implements the visitCall, visitInvoke, and visitCallBr functions.
Chris Lattner7a9e47a2010-01-05 07:32:13 +000010//
11//===----------------------------------------------------------------------===//
12
Chandler Carrutha9174582015-01-22 05:25:13 +000013#include "InstCombineInternal.h"
Eugene Zelenkocdc71612016-08-11 17:20:18 +000014#include "llvm/ADT/APFloat.h"
15#include "llvm/ADT/APInt.h"
Nikita Popov53828032019-05-29 18:37:13 +000016#include "llvm/ADT/APSInt.h"
Eugene Zelenkocdc71612016-08-11 17:20:18 +000017#include "llvm/ADT/ArrayRef.h"
Matt Arsenaulta4451d82019-11-01 17:57:29 -070018#include "llvm/ADT/FloatingPointMode.h"
Eugene Zelenkocdc71612016-08-11 17:20:18 +000019#include "llvm/ADT/None.h"
Eugene Zelenko7f0f9bc2017-10-24 21:24:53 +000020#include "llvm/ADT/Optional.h"
Eugene Zelenkocdc71612016-08-11 17:20:18 +000021#include "llvm/ADT/STLExtras.h"
22#include "llvm/ADT/SmallVector.h"
Chandler Carruth6bda14b2017-06-06 11:49:48 +000023#include "llvm/ADT/Statistic.h"
Eugene Zelenkocdc71612016-08-11 17:20:18 +000024#include "llvm/ADT/Twine.h"
Eugene Zelenko7f0f9bc2017-10-24 21:24:53 +000025#include "llvm/Analysis/AssumptionCache.h"
David Majnemer15032582015-05-22 03:56:46 +000026#include "llvm/Analysis/InstructionSimplify.h"
Simon Pilgrim4b7d3c42019-04-25 09:49:37 +000027#include "llvm/Analysis/Loads.h"
Chris Lattner7a9e47a2010-01-05 07:32:13 +000028#include "llvm/Analysis/MemoryBuiltins.h"
Eugene Zelenkocdc71612016-08-11 17:20:18 +000029#include "llvm/Analysis/ValueTracking.h"
Philip Reamese4588bb2019-03-20 18:44:58 +000030#include "llvm/Analysis/VectorUtils.h"
Eugene Zelenko7f0f9bc2017-10-24 21:24:53 +000031#include "llvm/IR/Attributes.h"
Eugene Zelenkocdc71612016-08-11 17:20:18 +000032#include "llvm/IR/BasicBlock.h"
Eugene Zelenkocdc71612016-08-11 17:20:18 +000033#include "llvm/IR/Constant.h"
Eugene Zelenko7f0f9bc2017-10-24 21:24:53 +000034#include "llvm/IR/Constants.h"
Eugene Zelenkocdc71612016-08-11 17:20:18 +000035#include "llvm/IR/DataLayout.h"
36#include "llvm/IR/DerivedTypes.h"
37#include "llvm/IR/Function.h"
38#include "llvm/IR/GlobalVariable.h"
39#include "llvm/IR/InstrTypes.h"
40#include "llvm/IR/Instruction.h"
41#include "llvm/IR/Instructions.h"
42#include "llvm/IR/IntrinsicInst.h"
43#include "llvm/IR/Intrinsics.h"
Reid Kleckner5d986952019-12-11 07:55:26 -080044#include "llvm/IR/IntrinsicsX86.h"
45#include "llvm/IR/IntrinsicsARM.h"
46#include "llvm/IR/IntrinsicsAArch64.h"
47#include "llvm/IR/IntrinsicsNVPTX.h"
48#include "llvm/IR/IntrinsicsAMDGPU.h"
49#include "llvm/IR/IntrinsicsPowerPC.h"
Eugene Zelenkocdc71612016-08-11 17:20:18 +000050#include "llvm/IR/LLVMContext.h"
51#include "llvm/IR/Metadata.h"
Chandler Carruth820a9082014-03-04 11:08:18 +000052#include "llvm/IR/PatternMatch.h"
Philip Reames1a1bdb22014-12-02 18:50:36 +000053#include "llvm/IR/Statepoint.h"
Eugene Zelenkocdc71612016-08-11 17:20:18 +000054#include "llvm/IR/Type.h"
Eugene Zelenko7f0f9bc2017-10-24 21:24:53 +000055#include "llvm/IR/User.h"
Eugene Zelenkocdc71612016-08-11 17:20:18 +000056#include "llvm/IR/Value.h"
57#include "llvm/IR/ValueHandle.h"
Eugene Zelenko7f0f9bc2017-10-24 21:24:53 +000058#include "llvm/Support/AtomicOrdering.h"
Eugene Zelenkocdc71612016-08-11 17:20:18 +000059#include "llvm/Support/Casting.h"
Eugene Zelenko7f0f9bc2017-10-24 21:24:53 +000060#include "llvm/Support/CommandLine.h"
61#include "llvm/Support/Compiler.h"
Eugene Zelenkocdc71612016-08-11 17:20:18 +000062#include "llvm/Support/Debug.h"
Eugene Zelenko7f0f9bc2017-10-24 21:24:53 +000063#include "llvm/Support/ErrorHandling.h"
Craig Topperb45eabc2017-04-26 16:39:58 +000064#include "llvm/Support/KnownBits.h"
Eugene Zelenkocdc71612016-08-11 17:20:18 +000065#include "llvm/Support/MathExtras.h"
Eugene Zelenko7f0f9bc2017-10-24 21:24:53 +000066#include "llvm/Support/raw_ostream.h"
67#include "llvm/Transforms/InstCombine/InstCombineWorklist.h"
Philip Reames88cd69b2019-04-25 02:30:17 +000068#include "llvm/Transforms/Utils/Local.h"
Chandler Carruthba4c5172015-01-21 11:23:40 +000069#include "llvm/Transforms/Utils/SimplifyLibCalls.h"
Eugene Zelenkocdc71612016-08-11 17:20:18 +000070#include <algorithm>
71#include <cassert>
72#include <cstdint>
73#include <cstring>
Eugene Zelenko7f0f9bc2017-10-24 21:24:53 +000074#include <utility>
Eugene Zelenkocdc71612016-08-11 17:20:18 +000075#include <vector>
76
Chris Lattner7a9e47a2010-01-05 07:32:13 +000077using namespace llvm;
Michael Ilseman536cc322012-12-13 03:13:36 +000078using namespace PatternMatch;
Chris Lattner7a9e47a2010-01-05 07:32:13 +000079
Chandler Carruth964daaa2014-04-22 02:55:47 +000080#define DEBUG_TYPE "instcombine"
81
Meador Ingee3f2b262012-11-30 04:05:06 +000082STATISTIC(NumSimplified, "Number of library calls simplified");
83
Philip Reames79e917d2018-05-09 22:56:32 +000084static cl::opt<unsigned> GuardWideningWindow(
85 "instcombine-guard-widening-window",
86 cl::init(3),
87 cl::desc("How wide an instruction window to bypass looking for "
88 "another guard"));
89
Sanjay Patelcd4377c2016-01-20 22:24:38 +000090/// Return the specified type promoted as it would be to pass though a va_arg
91/// area.
Chris Lattner229907c2011-07-18 04:54:35 +000092static Type *getPromotedType(Type *Ty) {
93 if (IntegerType* ITy = dyn_cast<IntegerType>(Ty)) {
Chris Lattner7a9e47a2010-01-05 07:32:13 +000094 if (ITy->getBitWidth() < 32)
95 return Type::getInt32Ty(Ty->getContext());
96 }
97 return Ty;
98}
99
Sanjay Patel368ac5d2016-02-21 17:29:33 +0000100/// Return a constant boolean vector that has true elements in all positions
Sanjay Patel24401302016-02-21 17:33:31 +0000101/// where the input constant data vector has an element with the sign bit set.
Sanjay Patel368ac5d2016-02-21 17:29:33 +0000102static Constant *getNegativeIsTrueBoolVec(ConstantDataVector *V) {
103 SmallVector<Constant *, 32> BoolVec;
104 IntegerType *BoolTy = Type::getInt1Ty(V->getContext());
105 for (unsigned I = 0, E = V->getNumElements(); I != E; ++I) {
106 Constant *Elt = V->getElementAsConstant(I);
107 assert((isa<ConstantInt>(Elt) || isa<ConstantFP>(Elt)) &&
108 "Unexpected constant data vector element type");
109 bool Sign = V->getElementType()->isIntegerTy()
110 ? cast<ConstantInt>(Elt)->isNegative()
111 : cast<ConstantFP>(Elt)->isNegative();
112 BoolVec.push_back(ConstantInt::get(BoolTy, Sign));
113 }
114 return ConstantVector::get(BoolVec);
115}
116
Daniel Neilson8f30ec62018-05-11 14:30:02 +0000117Instruction *InstCombiner::SimplifyAnyMemTransfer(AnyMemTransferInst *MI) {
Daniel Neilson2363da92018-02-12 23:06:55 +0000118 unsigned DstAlign = getKnownAlignment(MI->getRawDest(), DL, MI, &AC, &DT);
119 unsigned CopyDstAlign = MI->getDestAlignment();
120 if (CopyDstAlign < DstAlign){
121 MI->setDestAlignment(DstAlign);
122 return MI;
123 }
Chris Lattner7a9e47a2010-01-05 07:32:13 +0000124
Daniel Neilson8f30ec62018-05-11 14:30:02 +0000125 unsigned SrcAlign = getKnownAlignment(MI->getRawSource(), DL, MI, &AC, &DT);
126 unsigned CopySrcAlign = MI->getSourceAlignment();
Daniel Neilson2363da92018-02-12 23:06:55 +0000127 if (CopySrcAlign < SrcAlign) {
Daniel Neilson8f30ec62018-05-11 14:30:02 +0000128 MI->setSourceAlignment(SrcAlign);
Chris Lattner7a9e47a2010-01-05 07:32:13 +0000129 return MI;
130 }
Jim Grosbach7815f562012-02-03 00:07:04 +0000131
Philip Reamesd7486892019-04-22 20:28:19 +0000132 // If we have a store to a location which is known constant, we can conclude
133 // that the store must be storing the constant value (else the memory
134 // wouldn't be constant), and this must be a noop.
135 if (AA->pointsToConstantMemory(MI->getDest())) {
136 // Set the size of the copy to 0, it will be deleted on the next iteration.
137 MI->setLength(Constant::getNullValue(MI->getLength()->getType()));
138 return MI;
139 }
140
Chris Lattner7a9e47a2010-01-05 07:32:13 +0000141 // If MemCpyInst length is 1/2/4/8 bytes then replace memcpy with
142 // load/store.
Daniel Neilson8f30ec62018-05-11 14:30:02 +0000143 ConstantInt *MemOpLength = dyn_cast<ConstantInt>(MI->getLength());
Craig Topperf40110f2014-04-25 05:29:35 +0000144 if (!MemOpLength) return nullptr;
Jim Grosbach7815f562012-02-03 00:07:04 +0000145
Chris Lattner7a9e47a2010-01-05 07:32:13 +0000146 // Source and destination pointer types are always "i8*" for intrinsic. See
147 // if the size is something we can handle with a single primitive load/store.
148 // A single load+store correctly handles overlapping memory in the memmove
149 // case.
Michael Liao69e172a2012-08-15 03:49:59 +0000150 uint64_t Size = MemOpLength->getLimitedValue();
Alp Tokercb402912014-01-24 17:20:08 +0000151 assert(Size && "0-sized memory transferring should be removed already.");
Jim Grosbach7815f562012-02-03 00:07:04 +0000152
Chris Lattner7a9e47a2010-01-05 07:32:13 +0000153 if (Size > 8 || (Size&(Size-1)))
Craig Topperf40110f2014-04-25 05:29:35 +0000154 return nullptr; // If not 1/2/4/8 bytes, exit.
Jim Grosbach7815f562012-02-03 00:07:04 +0000155
Serguei Katkova5b0e552019-01-16 04:36:26 +0000156 // If it is an atomic and alignment is less than the size then we will
157 // introduce the unaligned memory access which will be later transformed
158 // into libcall in CodeGen. This is not evident performance gain so disable
159 // it now.
160 if (isa<AtomicMemTransferInst>(MI))
161 if (CopyDstAlign < Size || CopySrcAlign < Size)
162 return nullptr;
163
Chris Lattner7a9e47a2010-01-05 07:32:13 +0000164 // Use an integer load+store unless we can find something better.
Mon P Wangc576ee92010-04-04 03:10:48 +0000165 unsigned SrcAddrSp =
Gabor Greif0a136c92010-06-24 13:54:33 +0000166 cast<PointerType>(MI->getArgOperand(1)->getType())->getAddressSpace();
Gabor Greiff3755202010-04-16 15:33:14 +0000167 unsigned DstAddrSp =
Gabor Greif0a136c92010-06-24 13:54:33 +0000168 cast<PointerType>(MI->getArgOperand(0)->getType())->getAddressSpace();
Mon P Wangc576ee92010-04-04 03:10:48 +0000169
Chris Lattner229907c2011-07-18 04:54:35 +0000170 IntegerType* IntType = IntegerType::get(MI->getContext(), Size<<3);
Mon P Wangc576ee92010-04-04 03:10:48 +0000171 Type *NewSrcPtrTy = PointerType::get(IntType, SrcAddrSp);
172 Type *NewDstPtrTy = PointerType::get(IntType, DstAddrSp);
Jim Grosbach7815f562012-02-03 00:07:04 +0000173
Mikael Holmen760dc9a2017-03-01 06:45:20 +0000174 // If the memcpy has metadata describing the members, see if we can get the
175 // TBAA tag describing our copy.
Craig Topperf40110f2014-04-25 05:29:35 +0000176 MDNode *CopyMD = nullptr;
Ivan A. Kosarevf03f5792018-02-19 12:10:20 +0000177 if (MDNode *M = MI->getMetadata(LLVMContext::MD_tbaa)) {
178 CopyMD = M;
179 } else if (MDNode *M = MI->getMetadata(LLVMContext::MD_tbaa_struct)) {
Mikael Holmen760dc9a2017-03-01 06:45:20 +0000180 if (M->getNumOperands() == 3 && M->getOperand(0) &&
181 mdconst::hasa<ConstantInt>(M->getOperand(0)) &&
Craig Topper79ab6432017-07-06 18:39:47 +0000182 mdconst::extract<ConstantInt>(M->getOperand(0))->isZero() &&
Mikael Holmen760dc9a2017-03-01 06:45:20 +0000183 M->getOperand(1) &&
184 mdconst::hasa<ConstantInt>(M->getOperand(1)) &&
185 mdconst::extract<ConstantInt>(M->getOperand(1))->getValue() ==
186 Size &&
187 M->getOperand(2) && isa<MDNode>(M->getOperand(2)))
188 CopyMD = cast<MDNode>(M->getOperand(2));
Chris Lattner7a9e47a2010-01-05 07:32:13 +0000189 }
Jim Grosbach7815f562012-02-03 00:07:04 +0000190
Craig Topperbb4069e2017-07-07 23:16:26 +0000191 Value *Src = Builder.CreateBitCast(MI->getArgOperand(1), NewSrcPtrTy);
192 Value *Dest = Builder.CreateBitCast(MI->getArgOperand(0), NewDstPtrTy);
James Y Knight14359ef2019-02-01 20:44:24 +0000193 LoadInst *L = Builder.CreateLoad(IntType, Src);
Daniel Neilson2363da92018-02-12 23:06:55 +0000194 // Alignment from the mem intrinsic will be better, so use it.
Guillaume Chateletd400d452019-10-03 13:17:21 +0000195 L->setAlignment(
196 MaybeAlign(CopySrcAlign)); // FIXME: Check if we can use Align instead.
Dan Gohman3f553c22012-09-13 21:51:01 +0000197 if (CopyMD)
198 L->setMetadata(LLVMContext::MD_tbaa, CopyMD);
Dorit Nuzmanabd15f62016-09-04 07:49:39 +0000199 MDNode *LoopMemParallelMD =
200 MI->getMetadata(LLVMContext::MD_mem_parallel_loop_access);
201 if (LoopMemParallelMD)
202 L->setMetadata(LLVMContext::MD_mem_parallel_loop_access, LoopMemParallelMD);
Michael Kruse978ba612018-12-20 04:58:07 +0000203 MDNode *AccessGroupMD = MI->getMetadata(LLVMContext::MD_access_group);
204 if (AccessGroupMD)
205 L->setMetadata(LLVMContext::MD_access_group, AccessGroupMD);
Dorit Nuzman7673ba72016-09-04 07:06:00 +0000206
Daniel Neilson8f30ec62018-05-11 14:30:02 +0000207 StoreInst *S = Builder.CreateStore(L, Dest);
Daniel Neilson2363da92018-02-12 23:06:55 +0000208 // Alignment from the mem intrinsic will be better, so use it.
Guillaume Chateletd400d452019-10-03 13:17:21 +0000209 S->setAlignment(
210 MaybeAlign(CopyDstAlign)); // FIXME: Check if we can use Align instead.
Dan Gohman3f553c22012-09-13 21:51:01 +0000211 if (CopyMD)
212 S->setMetadata(LLVMContext::MD_tbaa, CopyMD);
Dorit Nuzmanabd15f62016-09-04 07:49:39 +0000213 if (LoopMemParallelMD)
214 S->setMetadata(LLVMContext::MD_mem_parallel_loop_access, LoopMemParallelMD);
Michael Kruse978ba612018-12-20 04:58:07 +0000215 if (AccessGroupMD)
216 S->setMetadata(LLVMContext::MD_access_group, AccessGroupMD);
Chris Lattner7a9e47a2010-01-05 07:32:13 +0000217
Daniel Neilson8f30ec62018-05-11 14:30:02 +0000218 if (auto *MT = dyn_cast<MemTransferInst>(MI)) {
219 // non-atomics can be volatile
220 L->setVolatile(MT->isVolatile());
221 S->setVolatile(MT->isVolatile());
222 }
223 if (isa<AtomicMemTransferInst>(MI)) {
224 // atomics have to be unordered
225 L->setOrdering(AtomicOrdering::Unordered);
226 S->setOrdering(AtomicOrdering::Unordered);
227 }
228
Chris Lattner7a9e47a2010-01-05 07:32:13 +0000229 // Set the size of the copy to 0, it will be deleted on the next iteration.
Daniel Neilson8f30ec62018-05-11 14:30:02 +0000230 MI->setLength(Constant::getNullValue(MemOpLength->getType()));
Chris Lattner7a9e47a2010-01-05 07:32:13 +0000231 return MI;
232}
233
Daniel Neilsonf6651d42018-05-11 20:04:50 +0000234Instruction *InstCombiner::SimplifyAnyMemSet(AnyMemSetInst *MI) {
Guillaume Chateletd400d452019-10-03 13:17:21 +0000235 const unsigned KnownAlignment =
236 getKnownAlignment(MI->getDest(), DL, MI, &AC, &DT);
237 if (MI->getDestAlignment() < KnownAlignment) {
238 MI->setDestAlignment(KnownAlignment);
Chris Lattner7a9e47a2010-01-05 07:32:13 +0000239 return MI;
240 }
Jim Grosbach7815f562012-02-03 00:07:04 +0000241
Philip Reamesd7486892019-04-22 20:28:19 +0000242 // If we have a store to a location which is known constant, we can conclude
243 // that the store must be storing the constant value (else the memory
244 // wouldn't be constant), and this must be a noop.
245 if (AA->pointsToConstantMemory(MI->getDest())) {
246 // Set the size of the copy to 0, it will be deleted on the next iteration.
247 MI->setLength(Constant::getNullValue(MI->getLength()->getType()));
248 return MI;
249 }
250
Chris Lattner7a9e47a2010-01-05 07:32:13 +0000251 // Extract the length and alignment and fill if they are constant.
252 ConstantInt *LenC = dyn_cast<ConstantInt>(MI->getLength());
253 ConstantInt *FillC = dyn_cast<ConstantInt>(MI->getValue());
Duncan Sands9dff9be2010-02-15 16:12:20 +0000254 if (!LenC || !FillC || !FillC->getType()->isIntegerTy(8))
Craig Topperf40110f2014-04-25 05:29:35 +0000255 return nullptr;
Guillaume Chateletd400d452019-10-03 13:17:21 +0000256 const uint64_t Len = LenC->getLimitedValue();
Michael Liao69e172a2012-08-15 03:49:59 +0000257 assert(Len && "0-sized memory setting should be removed already.");
Guillaume Chateletd400d452019-10-03 13:17:21 +0000258 const Align Alignment = assumeAligned(MI->getDestAlignment());
Serguei Katkova5b0e552019-01-16 04:36:26 +0000259
260 // If it is an atomic and alignment is less than the size then we will
261 // introduce the unaligned memory access which will be later transformed
262 // into libcall in CodeGen. This is not evident performance gain so disable
263 // it now.
264 if (isa<AtomicMemSetInst>(MI))
265 if (Alignment < Len)
266 return nullptr;
267
Chris Lattner7a9e47a2010-01-05 07:32:13 +0000268 // memset(s,c,n) -> store s, c (for n=1,2,4,8)
269 if (Len <= 8 && isPowerOf2_32((uint32_t)Len)) {
Chris Lattner229907c2011-07-18 04:54:35 +0000270 Type *ITy = IntegerType::get(MI->getContext(), Len*8); // n=1 -> i8.
Jim Grosbach7815f562012-02-03 00:07:04 +0000271
Chris Lattner7a9e47a2010-01-05 07:32:13 +0000272 Value *Dest = MI->getDest();
Mon P Wang1991c472010-12-20 01:05:30 +0000273 unsigned DstAddrSp = cast<PointerType>(Dest->getType())->getAddressSpace();
274 Type *NewDstPtrTy = PointerType::get(ITy, DstAddrSp);
Craig Topperbb4069e2017-07-07 23:16:26 +0000275 Dest = Builder.CreateBitCast(Dest, NewDstPtrTy);
Chris Lattner7a9e47a2010-01-05 07:32:13 +0000276
Chris Lattner7a9e47a2010-01-05 07:32:13 +0000277 // Extract the fill value and store.
278 uint64_t Fill = FillC->getZExtValue()*0x0101010101010101ULL;
Craig Topperbb4069e2017-07-07 23:16:26 +0000279 StoreInst *S = Builder.CreateStore(ConstantInt::get(ITy, Fill), Dest,
280 MI->isVolatile());
Eli Friedman49346012011-05-18 19:57:14 +0000281 S->setAlignment(Alignment);
Daniel Neilsonf6651d42018-05-11 20:04:50 +0000282 if (isa<AtomicMemSetInst>(MI))
283 S->setOrdering(AtomicOrdering::Unordered);
Jim Grosbach7815f562012-02-03 00:07:04 +0000284
Chris Lattner7a9e47a2010-01-05 07:32:13 +0000285 // Set the size of the copy to 0, it will be deleted on the next iteration.
286 MI->setLength(Constant::getNullValue(LenC->getType()));
287 return MI;
288 }
289
Simon Pilgrim18617d12015-08-05 08:18:00 +0000290 return nullptr;
291}
292
Sanjay Patel6038d3e2016-01-29 23:27:03 +0000293static Value *simplifyX86immShift(const IntrinsicInst &II,
Simon Pilgrimbecd5e82015-08-13 07:39:03 +0000294 InstCombiner::BuilderTy &Builder) {
295 bool LogicalShift = false;
296 bool ShiftLeft = false;
297
298 switch (II.getIntrinsicID()) {
Craig Topperb4173a52016-11-13 07:26:19 +0000299 default: llvm_unreachable("Unexpected intrinsic!");
Simon Pilgrimbecd5e82015-08-13 07:39:03 +0000300 case Intrinsic::x86_sse2_psra_d:
301 case Intrinsic::x86_sse2_psra_w:
302 case Intrinsic::x86_sse2_psrai_d:
303 case Intrinsic::x86_sse2_psrai_w:
304 case Intrinsic::x86_avx2_psra_d:
305 case Intrinsic::x86_avx2_psra_w:
306 case Intrinsic::x86_avx2_psrai_d:
307 case Intrinsic::x86_avx2_psrai_w:
Craig Topper8b831cb2016-11-13 01:51:55 +0000308 case Intrinsic::x86_avx512_psra_q_128:
309 case Intrinsic::x86_avx512_psrai_q_128:
310 case Intrinsic::x86_avx512_psra_q_256:
311 case Intrinsic::x86_avx512_psrai_q_256:
312 case Intrinsic::x86_avx512_psra_d_512:
313 case Intrinsic::x86_avx512_psra_q_512:
314 case Intrinsic::x86_avx512_psra_w_512:
315 case Intrinsic::x86_avx512_psrai_d_512:
316 case Intrinsic::x86_avx512_psrai_q_512:
317 case Intrinsic::x86_avx512_psrai_w_512:
Simon Pilgrimbecd5e82015-08-13 07:39:03 +0000318 LogicalShift = false; ShiftLeft = false;
319 break;
320 case Intrinsic::x86_sse2_psrl_d:
321 case Intrinsic::x86_sse2_psrl_q:
322 case Intrinsic::x86_sse2_psrl_w:
323 case Intrinsic::x86_sse2_psrli_d:
324 case Intrinsic::x86_sse2_psrli_q:
325 case Intrinsic::x86_sse2_psrli_w:
326 case Intrinsic::x86_avx2_psrl_d:
327 case Intrinsic::x86_avx2_psrl_q:
328 case Intrinsic::x86_avx2_psrl_w:
329 case Intrinsic::x86_avx2_psrli_d:
330 case Intrinsic::x86_avx2_psrli_q:
331 case Intrinsic::x86_avx2_psrli_w:
Craig Topper8b831cb2016-11-13 01:51:55 +0000332 case Intrinsic::x86_avx512_psrl_d_512:
333 case Intrinsic::x86_avx512_psrl_q_512:
334 case Intrinsic::x86_avx512_psrl_w_512:
335 case Intrinsic::x86_avx512_psrli_d_512:
336 case Intrinsic::x86_avx512_psrli_q_512:
337 case Intrinsic::x86_avx512_psrli_w_512:
Simon Pilgrimbecd5e82015-08-13 07:39:03 +0000338 LogicalShift = true; ShiftLeft = false;
339 break;
340 case Intrinsic::x86_sse2_psll_d:
341 case Intrinsic::x86_sse2_psll_q:
342 case Intrinsic::x86_sse2_psll_w:
343 case Intrinsic::x86_sse2_pslli_d:
344 case Intrinsic::x86_sse2_pslli_q:
345 case Intrinsic::x86_sse2_pslli_w:
346 case Intrinsic::x86_avx2_psll_d:
347 case Intrinsic::x86_avx2_psll_q:
348 case Intrinsic::x86_avx2_psll_w:
349 case Intrinsic::x86_avx2_pslli_d:
350 case Intrinsic::x86_avx2_pslli_q:
351 case Intrinsic::x86_avx2_pslli_w:
Craig Topper8b831cb2016-11-13 01:51:55 +0000352 case Intrinsic::x86_avx512_psll_d_512:
353 case Intrinsic::x86_avx512_psll_q_512:
354 case Intrinsic::x86_avx512_psll_w_512:
355 case Intrinsic::x86_avx512_pslli_d_512:
356 case Intrinsic::x86_avx512_pslli_q_512:
357 case Intrinsic::x86_avx512_pslli_w_512:
Simon Pilgrimbecd5e82015-08-13 07:39:03 +0000358 LogicalShift = true; ShiftLeft = true;
359 break;
360 }
Simon Pilgrima3a72b42015-08-10 20:21:15 +0000361 assert((LogicalShift || !ShiftLeft) && "Only logical shifts can shift left");
362
Simon Pilgrim3815c162015-08-07 18:22:50 +0000363 // Simplify if count is constant.
364 auto Arg1 = II.getArgOperand(1);
365 auto CAZ = dyn_cast<ConstantAggregateZero>(Arg1);
366 auto CDV = dyn_cast<ConstantDataVector>(Arg1);
367 auto CInt = dyn_cast<ConstantInt>(Arg1);
368 if (!CAZ && !CDV && !CInt)
Simon Pilgrim18617d12015-08-05 08:18:00 +0000369 return nullptr;
Simon Pilgrim3815c162015-08-07 18:22:50 +0000370
371 APInt Count(64, 0);
372 if (CDV) {
373 // SSE2/AVX2 uses all the first 64-bits of the 128-bit vector
374 // operand to compute the shift amount.
375 auto VT = cast<VectorType>(CDV->getType());
376 unsigned BitWidth = VT->getElementType()->getPrimitiveSizeInBits();
377 assert((64 % BitWidth) == 0 && "Unexpected packed shift size");
378 unsigned NumSubElts = 64 / BitWidth;
379
380 // Concatenate the sub-elements to create the 64-bit value.
381 for (unsigned i = 0; i != NumSubElts; ++i) {
382 unsigned SubEltIdx = (NumSubElts - 1) - i;
383 auto SubElt = cast<ConstantInt>(CDV->getElementAsConstant(SubEltIdx));
Craig Topper24e71012017-04-28 03:36:24 +0000384 Count <<= BitWidth;
Simon Pilgrim3815c162015-08-07 18:22:50 +0000385 Count |= SubElt->getValue().zextOrTrunc(64);
386 }
387 }
388 else if (CInt)
389 Count = CInt->getValue();
Simon Pilgrim18617d12015-08-05 08:18:00 +0000390
391 auto Vec = II.getArgOperand(0);
392 auto VT = cast<VectorType>(Vec->getType());
393 auto SVT = VT->getElementType();
Simon Pilgrim3815c162015-08-07 18:22:50 +0000394 unsigned VWidth = VT->getNumElements();
395 unsigned BitWidth = SVT->getPrimitiveSizeInBits();
396
397 // If shift-by-zero then just return the original value.
Craig Topper73ba1c82017-06-07 07:40:37 +0000398 if (Count.isNullValue())
Simon Pilgrim3815c162015-08-07 18:22:50 +0000399 return Vec;
400
Simon Pilgrima3a72b42015-08-10 20:21:15 +0000401 // Handle cases when Shift >= BitWidth.
402 if (Count.uge(BitWidth)) {
403 // If LogicalShift - just return zero.
404 if (LogicalShift)
405 return ConstantAggregateZero::get(VT);
406
407 // If ArithmeticShift - clamp Shift to (BitWidth - 1).
408 Count = APInt(64, BitWidth - 1);
409 }
Simon Pilgrim18617d12015-08-05 08:18:00 +0000410
Simon Pilgrim18617d12015-08-05 08:18:00 +0000411 // Get a constant vector of the same type as the first operand.
Simon Pilgrim3815c162015-08-07 18:22:50 +0000412 auto ShiftAmt = ConstantInt::get(SVT, Count.zextOrTrunc(BitWidth));
413 auto ShiftVec = Builder.CreateVectorSplat(VWidth, ShiftAmt);
Simon Pilgrim18617d12015-08-05 08:18:00 +0000414
415 if (ShiftLeft)
Simon Pilgrim3815c162015-08-07 18:22:50 +0000416 return Builder.CreateShl(Vec, ShiftVec);
Simon Pilgrim18617d12015-08-05 08:18:00 +0000417
Simon Pilgrima3a72b42015-08-10 20:21:15 +0000418 if (LogicalShift)
419 return Builder.CreateLShr(Vec, ShiftVec);
420
421 return Builder.CreateAShr(Vec, ShiftVec);
Simon Pilgrim18617d12015-08-05 08:18:00 +0000422}
423
Simon Pilgrimdb9893f2016-06-07 10:27:15 +0000424// Attempt to simplify AVX2 per-element shift intrinsics to a generic IR shift.
425// Unlike the generic IR shifts, the intrinsics have defined behaviour for out
426// of range shift amounts (logical - set to zero, arithmetic - splat sign bit).
427static Value *simplifyX86varShift(const IntrinsicInst &II,
428 InstCombiner::BuilderTy &Builder) {
429 bool LogicalShift = false;
430 bool ShiftLeft = false;
431
432 switch (II.getIntrinsicID()) {
Craig Topperb4173a52016-11-13 07:26:19 +0000433 default: llvm_unreachable("Unexpected intrinsic!");
Simon Pilgrimdb9893f2016-06-07 10:27:15 +0000434 case Intrinsic::x86_avx2_psrav_d:
435 case Intrinsic::x86_avx2_psrav_d_256:
Craig Topperb4173a52016-11-13 07:26:19 +0000436 case Intrinsic::x86_avx512_psrav_q_128:
437 case Intrinsic::x86_avx512_psrav_q_256:
438 case Intrinsic::x86_avx512_psrav_d_512:
439 case Intrinsic::x86_avx512_psrav_q_512:
Craig Topper1de753f2016-11-18 06:04:33 +0000440 case Intrinsic::x86_avx512_psrav_w_128:
441 case Intrinsic::x86_avx512_psrav_w_256:
442 case Intrinsic::x86_avx512_psrav_w_512:
Simon Pilgrimdb9893f2016-06-07 10:27:15 +0000443 LogicalShift = false;
444 ShiftLeft = false;
445 break;
446 case Intrinsic::x86_avx2_psrlv_d:
447 case Intrinsic::x86_avx2_psrlv_d_256:
448 case Intrinsic::x86_avx2_psrlv_q:
449 case Intrinsic::x86_avx2_psrlv_q_256:
Craig Topperb4173a52016-11-13 07:26:19 +0000450 case Intrinsic::x86_avx512_psrlv_d_512:
451 case Intrinsic::x86_avx512_psrlv_q_512:
Craig Topper1de753f2016-11-18 06:04:33 +0000452 case Intrinsic::x86_avx512_psrlv_w_128:
453 case Intrinsic::x86_avx512_psrlv_w_256:
454 case Intrinsic::x86_avx512_psrlv_w_512:
Simon Pilgrimdb9893f2016-06-07 10:27:15 +0000455 LogicalShift = true;
456 ShiftLeft = false;
457 break;
458 case Intrinsic::x86_avx2_psllv_d:
459 case Intrinsic::x86_avx2_psllv_d_256:
460 case Intrinsic::x86_avx2_psllv_q:
461 case Intrinsic::x86_avx2_psllv_q_256:
Craig Topperb4173a52016-11-13 07:26:19 +0000462 case Intrinsic::x86_avx512_psllv_d_512:
463 case Intrinsic::x86_avx512_psllv_q_512:
Craig Topper1de753f2016-11-18 06:04:33 +0000464 case Intrinsic::x86_avx512_psllv_w_128:
465 case Intrinsic::x86_avx512_psllv_w_256:
466 case Intrinsic::x86_avx512_psllv_w_512:
Simon Pilgrimdb9893f2016-06-07 10:27:15 +0000467 LogicalShift = true;
468 ShiftLeft = true;
469 break;
470 }
471 assert((LogicalShift || !ShiftLeft) && "Only logical shifts can shift left");
472
473 // Simplify if all shift amounts are constant/undef.
474 auto *CShift = dyn_cast<Constant>(II.getArgOperand(1));
475 if (!CShift)
476 return nullptr;
477
478 auto Vec = II.getArgOperand(0);
479 auto VT = cast<VectorType>(II.getType());
480 auto SVT = VT->getVectorElementType();
481 int NumElts = VT->getNumElements();
482 int BitWidth = SVT->getIntegerBitWidth();
483
484 // Collect each element's shift amount.
485 // We also collect special cases: UNDEF = -1, OUT-OF-RANGE = BitWidth.
486 bool AnyOutOfRange = false;
487 SmallVector<int, 8> ShiftAmts;
488 for (int I = 0; I < NumElts; ++I) {
489 auto *CElt = CShift->getAggregateElement(I);
490 if (CElt && isa<UndefValue>(CElt)) {
491 ShiftAmts.push_back(-1);
492 continue;
493 }
494
495 auto *COp = dyn_cast_or_null<ConstantInt>(CElt);
496 if (!COp)
497 return nullptr;
498
499 // Handle out of range shifts.
500 // If LogicalShift - set to BitWidth (special case).
501 // If ArithmeticShift - set to (BitWidth - 1) (sign splat).
502 APInt ShiftVal = COp->getValue();
503 if (ShiftVal.uge(BitWidth)) {
504 AnyOutOfRange = LogicalShift;
505 ShiftAmts.push_back(LogicalShift ? BitWidth : BitWidth - 1);
506 continue;
507 }
508
509 ShiftAmts.push_back((int)ShiftVal.getZExtValue());
510 }
511
512 // If all elements out of range or UNDEF, return vector of zeros/undefs.
513 // ArithmeticShift should only hit this if they are all UNDEF.
514 auto OutOfRange = [&](int Idx) { return (Idx < 0) || (BitWidth <= Idx); };
Eugene Zelenko7f0f9bc2017-10-24 21:24:53 +0000515 if (llvm::all_of(ShiftAmts, OutOfRange)) {
Simon Pilgrimdb9893f2016-06-07 10:27:15 +0000516 SmallVector<Constant *, 8> ConstantVec;
517 for (int Idx : ShiftAmts) {
518 if (Idx < 0) {
519 ConstantVec.push_back(UndefValue::get(SVT));
520 } else {
521 assert(LogicalShift && "Logical shift expected");
522 ConstantVec.push_back(ConstantInt::getNullValue(SVT));
523 }
524 }
525 return ConstantVector::get(ConstantVec);
526 }
527
528 // We can't handle only some out of range values with generic logical shifts.
529 if (AnyOutOfRange)
530 return nullptr;
531
532 // Build the shift amount constant vector.
533 SmallVector<Constant *, 8> ShiftVecAmts;
534 for (int Idx : ShiftAmts) {
535 if (Idx < 0)
536 ShiftVecAmts.push_back(UndefValue::get(SVT));
537 else
538 ShiftVecAmts.push_back(ConstantInt::get(SVT, Idx));
539 }
540 auto ShiftVec = ConstantVector::get(ShiftVecAmts);
541
542 if (ShiftLeft)
543 return Builder.CreateShl(Vec, ShiftVec);
544
545 if (LogicalShift)
546 return Builder.CreateLShr(Vec, ShiftVec);
547
548 return Builder.CreateAShr(Vec, ShiftVec);
549}
550
Simon Pilgrim55f14da2019-04-24 16:53:17 +0000551static Value *simplifyX86pack(IntrinsicInst &II,
552 InstCombiner::BuilderTy &Builder, bool IsSigned) {
Simon Pilgrim6f6b2792017-01-25 14:37:24 +0000553 Value *Arg0 = II.getArgOperand(0);
554 Value *Arg1 = II.getArgOperand(1);
555 Type *ResTy = II.getType();
556
557 // Fast all undef handling.
558 if (isa<UndefValue>(Arg0) && isa<UndefValue>(Arg1))
559 return UndefValue::get(ResTy);
560
561 Type *ArgTy = Arg0->getType();
562 unsigned NumLanes = ResTy->getPrimitiveSizeInBits() / 128;
Simon Pilgrim6f6b2792017-01-25 14:37:24 +0000563 unsigned NumSrcElts = ArgTy->getVectorNumElements();
Simon Pilgrim55f14da2019-04-24 16:53:17 +0000564 assert(ResTy->getVectorNumElements() == (2 * NumSrcElts) &&
565 "Unexpected packing types");
Simon Pilgrim6f6b2792017-01-25 14:37:24 +0000566
Simon Pilgrim6f6b2792017-01-25 14:37:24 +0000567 unsigned NumSrcEltsPerLane = NumSrcElts / NumLanes;
568 unsigned DstScalarSizeInBits = ResTy->getScalarSizeInBits();
Simon Pilgrim55f14da2019-04-24 16:53:17 +0000569 unsigned SrcScalarSizeInBits = ArgTy->getScalarSizeInBits();
570 assert(SrcScalarSizeInBits == (2 * DstScalarSizeInBits) &&
Simon Pilgrim6f6b2792017-01-25 14:37:24 +0000571 "Unexpected packing types");
572
573 // Constant folding.
Simon Pilgrim55f14da2019-04-24 16:53:17 +0000574 if (!isa<Constant>(Arg0) || !isa<Constant>(Arg1))
Simon Pilgrim6f6b2792017-01-25 14:37:24 +0000575 return nullptr;
576
Simon Pilgrim55f14da2019-04-24 16:53:17 +0000577 // Clamp Values - signed/unsigned both use signed clamp values, but they
578 // differ on the min/max values.
579 APInt MinValue, MaxValue;
580 if (IsSigned) {
581 // PACKSS: Truncate signed value with signed saturation.
582 // Source values less than dst minint are saturated to minint.
583 // Source values greater than dst maxint are saturated to maxint.
584 MinValue =
585 APInt::getSignedMinValue(DstScalarSizeInBits).sext(SrcScalarSizeInBits);
586 MaxValue =
587 APInt::getSignedMaxValue(DstScalarSizeInBits).sext(SrcScalarSizeInBits);
588 } else {
589 // PACKUS: Truncate signed value with unsigned saturation.
590 // Source values less than zero are saturated to zero.
591 // Source values greater than dst maxuint are saturated to maxuint.
592 MinValue = APInt::getNullValue(SrcScalarSizeInBits);
593 MaxValue = APInt::getLowBitsSet(SrcScalarSizeInBits, DstScalarSizeInBits);
Simon Pilgrim6f6b2792017-01-25 14:37:24 +0000594 }
595
Simon Pilgrim55f14da2019-04-24 16:53:17 +0000596 auto *MinC = Constant::getIntegerValue(ArgTy, MinValue);
597 auto *MaxC = Constant::getIntegerValue(ArgTy, MaxValue);
598 Arg0 = Builder.CreateSelect(Builder.CreateICmpSLT(Arg0, MinC), MinC, Arg0);
599 Arg1 = Builder.CreateSelect(Builder.CreateICmpSLT(Arg1, MinC), MinC, Arg1);
600 Arg0 = Builder.CreateSelect(Builder.CreateICmpSGT(Arg0, MaxC), MaxC, Arg0);
601 Arg1 = Builder.CreateSelect(Builder.CreateICmpSGT(Arg1, MaxC), MaxC, Arg1);
602
Simon Pilgrim48a3b542019-04-25 13:51:57 +0000603 // Shuffle clamped args together at the lane level.
Simon Pilgrim55f14da2019-04-24 16:53:17 +0000604 SmallVector<unsigned, 32> PackMask;
605 for (unsigned Lane = 0; Lane != NumLanes; ++Lane) {
606 for (unsigned Elt = 0; Elt != NumSrcEltsPerLane; ++Elt)
607 PackMask.push_back(Elt + (Lane * NumSrcEltsPerLane));
608 for (unsigned Elt = 0; Elt != NumSrcEltsPerLane; ++Elt)
609 PackMask.push_back(Elt + (Lane * NumSrcEltsPerLane) + NumSrcElts);
610 }
Simon Pilgrim48a3b542019-04-25 13:51:57 +0000611 auto *Shuffle = Builder.CreateShuffleVector(Arg0, Arg1, PackMask);
Simon Pilgrim55f14da2019-04-24 16:53:17 +0000612
Simon Pilgrim48a3b542019-04-25 13:51:57 +0000613 // Truncate to dst size.
614 return Builder.CreateTrunc(Shuffle, ResTy);
Simon Pilgrim6f6b2792017-01-25 14:37:24 +0000615}
616
Sanjay Patel2aa2dc72018-12-11 16:38:03 +0000617static Value *simplifyX86movmsk(const IntrinsicInst &II,
618 InstCombiner::BuilderTy &Builder) {
Simon Pilgrim91e3ac82016-06-07 08:18:35 +0000619 Value *Arg = II.getArgOperand(0);
620 Type *ResTy = II.getType();
621 Type *ArgTy = Arg->getType();
622
623 // movmsk(undef) -> zero as we must ensure the upper bits are zero.
624 if (isa<UndefValue>(Arg))
625 return Constant::getNullValue(ResTy);
626
627 // We can't easily peek through x86_mmx types.
628 if (!ArgTy->isVectorTy())
629 return nullptr;
630
Simon Pilgrimb4f1bfa2019-04-08 13:17:51 +0000631 // Expand MOVMSK to compare/bitcast/zext:
632 // e.g. PMOVMSKB(v16i8 x):
633 // %cmp = icmp slt <16 x i8> %x, zeroinitializer
634 // %int = bitcast <16 x i1> %cmp to i16
635 // %res = zext i16 %int to i32
636 unsigned NumElts = ArgTy->getVectorNumElements();
637 Type *IntegerVecTy = VectorType::getInteger(cast<VectorType>(ArgTy));
638 Type *IntegerTy = Builder.getIntNTy(NumElts);
Simon Pilgrim91e3ac82016-06-07 08:18:35 +0000639
Simon Pilgrimb4f1bfa2019-04-08 13:17:51 +0000640 Value *Res = Builder.CreateBitCast(Arg, IntegerVecTy);
641 Res = Builder.CreateICmpSLT(Res, Constant::getNullValue(IntegerVecTy));
642 Res = Builder.CreateBitCast(Res, IntegerTy);
643 Res = Builder.CreateZExtOrTrunc(Res, ResTy);
644 return Res;
Simon Pilgrim91e3ac82016-06-07 08:18:35 +0000645}
646
Sanjay Patelbe23a912019-02-01 14:14:47 +0000647static Value *simplifyX86addcarry(const IntrinsicInst &II,
648 InstCombiner::BuilderTy &Builder) {
649 Value *CarryIn = II.getArgOperand(0);
650 Value *Op1 = II.getArgOperand(1);
651 Value *Op2 = II.getArgOperand(2);
652 Type *RetTy = II.getType();
653 Type *OpTy = Op1->getType();
654 assert(RetTy->getStructElementType(0)->isIntegerTy(8) &&
655 RetTy->getStructElementType(1) == OpTy && OpTy == Op2->getType() &&
656 "Unexpected types for x86 addcarry");
657
658 // If carry-in is zero, this is just an unsigned add with overflow.
659 if (match(CarryIn, m_ZeroInt())) {
660 Value *UAdd = Builder.CreateIntrinsic(Intrinsic::uadd_with_overflow, OpTy,
661 { Op1, Op2 });
662 // The types have to be adjusted to match the x86 call types.
663 Value *UAddResult = Builder.CreateExtractValue(UAdd, 0);
664 Value *UAddOV = Builder.CreateZExt(Builder.CreateExtractValue(UAdd, 1),
665 Builder.getInt8Ty());
Sanjay Patelfbcbac72019-02-01 14:37:49 +0000666 Value *Res = UndefValue::get(RetTy);
Sanjay Patelbe23a912019-02-01 14:14:47 +0000667 Res = Builder.CreateInsertValue(Res, UAddOV, 0);
668 return Builder.CreateInsertValue(Res, UAddResult, 1);
669 }
670
671 return nullptr;
672}
673
Sanjay Patel6038d3e2016-01-29 23:27:03 +0000674static Value *simplifyX86insertps(const IntrinsicInst &II,
Sanjay Patelc86867c2015-04-16 17:52:13 +0000675 InstCombiner::BuilderTy &Builder) {
Sanjay Patel03c03f52016-01-28 00:03:16 +0000676 auto *CInt = dyn_cast<ConstantInt>(II.getArgOperand(2));
677 if (!CInt)
678 return nullptr;
Simon Pilgrim54fcd622015-07-25 20:41:00 +0000679
Sanjay Patel03c03f52016-01-28 00:03:16 +0000680 VectorType *VecTy = cast<VectorType>(II.getType());
681 assert(VecTy->getNumElements() == 4 && "insertps with wrong vector type");
Sanjay Patelc86867c2015-04-16 17:52:13 +0000682
Sanjay Patel03c03f52016-01-28 00:03:16 +0000683 // The immediate permute control byte looks like this:
684 // [3:0] - zero mask for each 32-bit lane
685 // [5:4] - select one 32-bit destination lane
686 // [7:6] - select one 32-bit source lane
Sanjay Patelc86867c2015-04-16 17:52:13 +0000687
Sanjay Patel03c03f52016-01-28 00:03:16 +0000688 uint8_t Imm = CInt->getZExtValue();
689 uint8_t ZMask = Imm & 0xf;
690 uint8_t DestLane = (Imm >> 4) & 0x3;
691 uint8_t SourceLane = (Imm >> 6) & 0x3;
Sanjay Patelc1d20a32015-04-25 20:55:25 +0000692
Sanjay Patel03c03f52016-01-28 00:03:16 +0000693 ConstantAggregateZero *ZeroVector = ConstantAggregateZero::get(VecTy);
Sanjay Patelc86867c2015-04-16 17:52:13 +0000694
Sanjay Patel03c03f52016-01-28 00:03:16 +0000695 // If all zero mask bits are set, this was just a weird way to
696 // generate a zero vector.
697 if (ZMask == 0xf)
698 return ZeroVector;
Sanjay Patelc1d20a32015-04-25 20:55:25 +0000699
Sanjay Patel03c03f52016-01-28 00:03:16 +0000700 // Initialize by passing all of the first source bits through.
Craig Topper99d1eab2016-06-12 00:41:19 +0000701 uint32_t ShuffleMask[4] = { 0, 1, 2, 3 };
Sanjay Patelc1d20a32015-04-25 20:55:25 +0000702
Sanjay Patel03c03f52016-01-28 00:03:16 +0000703 // We may replace the second operand with the zero vector.
704 Value *V1 = II.getArgOperand(1);
705
706 if (ZMask) {
707 // If the zero mask is being used with a single input or the zero mask
708 // overrides the destination lane, this is a shuffle with the zero vector.
709 if ((II.getArgOperand(0) == II.getArgOperand(1)) ||
710 (ZMask & (1 << DestLane))) {
711 V1 = ZeroVector;
712 // We may still move 32-bits of the first source vector from one lane
713 // to another.
714 ShuffleMask[DestLane] = SourceLane;
715 // The zero mask may override the previous insert operation.
716 for (unsigned i = 0; i < 4; ++i)
717 if ((ZMask >> i) & 0x1)
718 ShuffleMask[i] = i + 4;
Sanjay Patelc1d20a32015-04-25 20:55:25 +0000719 } else {
Sanjay Patel03c03f52016-01-28 00:03:16 +0000720 // TODO: Model this case as 2 shuffles or a 'logical and' plus shuffle?
721 return nullptr;
Sanjay Patelc1d20a32015-04-25 20:55:25 +0000722 }
Sanjay Patel03c03f52016-01-28 00:03:16 +0000723 } else {
724 // Replace the selected destination lane with the selected source lane.
725 ShuffleMask[DestLane] = SourceLane + 4;
Sanjay Patelc86867c2015-04-16 17:52:13 +0000726 }
Sanjay Patel03c03f52016-01-28 00:03:16 +0000727
728 return Builder.CreateShuffleVector(II.getArgOperand(0), V1, ShuffleMask);
Sanjay Patelc86867c2015-04-16 17:52:13 +0000729}
730
Simon Pilgrim216b1bf2015-10-17 11:40:05 +0000731/// Attempt to simplify SSE4A EXTRQ/EXTRQI instructions using constant folding
732/// or conversion to a shuffle vector.
Sanjay Patel6038d3e2016-01-29 23:27:03 +0000733static Value *simplifyX86extrq(IntrinsicInst &II, Value *Op0,
Simon Pilgrim216b1bf2015-10-17 11:40:05 +0000734 ConstantInt *CILength, ConstantInt *CIIndex,
735 InstCombiner::BuilderTy &Builder) {
736 auto LowConstantHighUndef = [&](uint64_t Val) {
737 Type *IntTy64 = Type::getInt64Ty(II.getContext());
738 Constant *Args[] = {ConstantInt::get(IntTy64, Val),
739 UndefValue::get(IntTy64)};
740 return ConstantVector::get(Args);
741 };
742
743 // See if we're dealing with constant values.
744 Constant *C0 = dyn_cast<Constant>(Op0);
745 ConstantInt *CI0 =
Andrea Di Biagio8df5b9c2016-09-07 12:03:03 +0000746 C0 ? dyn_cast_or_null<ConstantInt>(C0->getAggregateElement((unsigned)0))
Simon Pilgrim216b1bf2015-10-17 11:40:05 +0000747 : nullptr;
748
749 // Attempt to constant fold.
750 if (CILength && CIIndex) {
751 // From AMD documentation: "The bit index and field length are each six
752 // bits in length other bits of the field are ignored."
753 APInt APIndex = CIIndex->getValue().zextOrTrunc(6);
754 APInt APLength = CILength->getValue().zextOrTrunc(6);
755
756 unsigned Index = APIndex.getZExtValue();
757
758 // From AMD documentation: "a value of zero in the field length is
759 // defined as length of 64".
760 unsigned Length = APLength == 0 ? 64 : APLength.getZExtValue();
761
762 // From AMD documentation: "If the sum of the bit index + length field
763 // is greater than 64, the results are undefined".
764 unsigned End = Index + Length;
765
766 // Note that both field index and field length are 8-bit quantities.
767 // Since variables 'Index' and 'Length' are unsigned values
768 // obtained from zero-extending field index and field length
769 // respectively, their sum should never wrap around.
770 if (End > 64)
771 return UndefValue::get(II.getType());
772
773 // If we are inserting whole bytes, we can convert this to a shuffle.
774 // Lowering can recognize EXTRQI shuffle masks.
775 if ((Length % 8) == 0 && (Index % 8) == 0) {
776 // Convert bit indices to byte indices.
777 Length /= 8;
778 Index /= 8;
779
780 Type *IntTy8 = Type::getInt8Ty(II.getContext());
781 Type *IntTy32 = Type::getInt32Ty(II.getContext());
782 VectorType *ShufTy = VectorType::get(IntTy8, 16);
783
784 SmallVector<Constant *, 16> ShuffleMask;
785 for (int i = 0; i != (int)Length; ++i)
786 ShuffleMask.push_back(
787 Constant::getIntegerValue(IntTy32, APInt(32, i + Index)));
788 for (int i = Length; i != 8; ++i)
789 ShuffleMask.push_back(
790 Constant::getIntegerValue(IntTy32, APInt(32, i + 16)));
791 for (int i = 8; i != 16; ++i)
792 ShuffleMask.push_back(UndefValue::get(IntTy32));
793
794 Value *SV = Builder.CreateShuffleVector(
795 Builder.CreateBitCast(Op0, ShufTy),
796 ConstantAggregateZero::get(ShufTy), ConstantVector::get(ShuffleMask));
797 return Builder.CreateBitCast(SV, II.getType());
798 }
799
800 // Constant Fold - shift Index'th bit to lowest position and mask off
801 // Length bits.
802 if (CI0) {
803 APInt Elt = CI0->getValue();
Craig Topperfc947bc2017-04-18 17:14:21 +0000804 Elt.lshrInPlace(Index);
805 Elt = Elt.zextOrTrunc(Length);
Simon Pilgrim216b1bf2015-10-17 11:40:05 +0000806 return LowConstantHighUndef(Elt.getZExtValue());
807 }
808
809 // If we were an EXTRQ call, we'll save registers if we convert to EXTRQI.
810 if (II.getIntrinsicID() == Intrinsic::x86_sse4a_extrq) {
811 Value *Args[] = {Op0, CILength, CIIndex};
Sanjay Patelaf674fb2015-12-14 17:24:23 +0000812 Module *M = II.getModule();
James Y Knight7976eb52019-02-01 20:43:25 +0000813 Function *F = Intrinsic::getDeclaration(M, Intrinsic::x86_sse4a_extrqi);
Simon Pilgrim216b1bf2015-10-17 11:40:05 +0000814 return Builder.CreateCall(F, Args);
815 }
816 }
817
818 // Constant Fold - extraction from zero is always {zero, undef}.
Craig Topperca2c8762017-07-06 18:39:49 +0000819 if (CI0 && CI0->isZero())
Simon Pilgrim216b1bf2015-10-17 11:40:05 +0000820 return LowConstantHighUndef(0);
821
822 return nullptr;
823}
824
825/// Attempt to simplify SSE4A INSERTQ/INSERTQI instructions using constant
826/// folding or conversion to a shuffle vector.
Sanjay Patel6038d3e2016-01-29 23:27:03 +0000827static Value *simplifyX86insertq(IntrinsicInst &II, Value *Op0, Value *Op1,
Simon Pilgrim216b1bf2015-10-17 11:40:05 +0000828 APInt APLength, APInt APIndex,
829 InstCombiner::BuilderTy &Builder) {
Simon Pilgrim216b1bf2015-10-17 11:40:05 +0000830 // From AMD documentation: "The bit index and field length are each six bits
831 // in length other bits of the field are ignored."
832 APIndex = APIndex.zextOrTrunc(6);
833 APLength = APLength.zextOrTrunc(6);
834
835 // Attempt to constant fold.
836 unsigned Index = APIndex.getZExtValue();
837
838 // From AMD documentation: "a value of zero in the field length is
839 // defined as length of 64".
840 unsigned Length = APLength == 0 ? 64 : APLength.getZExtValue();
841
842 // From AMD documentation: "If the sum of the bit index + length field
843 // is greater than 64, the results are undefined".
844 unsigned End = Index + Length;
845
846 // Note that both field index and field length are 8-bit quantities.
847 // Since variables 'Index' and 'Length' are unsigned values
848 // obtained from zero-extending field index and field length
849 // respectively, their sum should never wrap around.
850 if (End > 64)
851 return UndefValue::get(II.getType());
852
853 // If we are inserting whole bytes, we can convert this to a shuffle.
854 // Lowering can recognize INSERTQI shuffle masks.
855 if ((Length % 8) == 0 && (Index % 8) == 0) {
856 // Convert bit indices to byte indices.
857 Length /= 8;
858 Index /= 8;
859
860 Type *IntTy8 = Type::getInt8Ty(II.getContext());
861 Type *IntTy32 = Type::getInt32Ty(II.getContext());
862 VectorType *ShufTy = VectorType::get(IntTy8, 16);
863
864 SmallVector<Constant *, 16> ShuffleMask;
865 for (int i = 0; i != (int)Index; ++i)
866 ShuffleMask.push_back(Constant::getIntegerValue(IntTy32, APInt(32, i)));
867 for (int i = 0; i != (int)Length; ++i)
868 ShuffleMask.push_back(
869 Constant::getIntegerValue(IntTy32, APInt(32, i + 16)));
870 for (int i = Index + Length; i != 8; ++i)
871 ShuffleMask.push_back(Constant::getIntegerValue(IntTy32, APInt(32, i)));
872 for (int i = 8; i != 16; ++i)
873 ShuffleMask.push_back(UndefValue::get(IntTy32));
874
875 Value *SV = Builder.CreateShuffleVector(Builder.CreateBitCast(Op0, ShufTy),
876 Builder.CreateBitCast(Op1, ShufTy),
877 ConstantVector::get(ShuffleMask));
878 return Builder.CreateBitCast(SV, II.getType());
879 }
880
881 // See if we're dealing with constant values.
882 Constant *C0 = dyn_cast<Constant>(Op0);
883 Constant *C1 = dyn_cast<Constant>(Op1);
884 ConstantInt *CI00 =
Andrea Di Biagiof3fd3162016-09-07 12:47:53 +0000885 C0 ? dyn_cast_or_null<ConstantInt>(C0->getAggregateElement((unsigned)0))
Simon Pilgrim216b1bf2015-10-17 11:40:05 +0000886 : nullptr;
887 ConstantInt *CI10 =
Andrea Di Biagiof3fd3162016-09-07 12:47:53 +0000888 C1 ? dyn_cast_or_null<ConstantInt>(C1->getAggregateElement((unsigned)0))
Simon Pilgrim216b1bf2015-10-17 11:40:05 +0000889 : nullptr;
890
891 // Constant Fold - insert bottom Length bits starting at the Index'th bit.
892 if (CI00 && CI10) {
893 APInt V00 = CI00->getValue();
894 APInt V10 = CI10->getValue();
895 APInt Mask = APInt::getLowBitsSet(64, Length).shl(Index);
896 V00 = V00 & ~Mask;
897 V10 = V10.zextOrTrunc(Length).zextOrTrunc(64).shl(Index);
898 APInt Val = V00 | V10;
899 Type *IntTy64 = Type::getInt64Ty(II.getContext());
900 Constant *Args[] = {ConstantInt::get(IntTy64, Val.getZExtValue()),
901 UndefValue::get(IntTy64)};
902 return ConstantVector::get(Args);
903 }
904
905 // If we were an INSERTQ call, we'll save demanded elements if we convert to
906 // INSERTQI.
907 if (II.getIntrinsicID() == Intrinsic::x86_sse4a_insertq) {
908 Type *IntTy8 = Type::getInt8Ty(II.getContext());
909 Constant *CILength = ConstantInt::get(IntTy8, Length, false);
910 Constant *CIIndex = ConstantInt::get(IntTy8, Index, false);
911
912 Value *Args[] = {Op0, Op1, CILength, CIIndex};
Sanjay Patelaf674fb2015-12-14 17:24:23 +0000913 Module *M = II.getModule();
James Y Knight7976eb52019-02-01 20:43:25 +0000914 Function *F = Intrinsic::getDeclaration(M, Intrinsic::x86_sse4a_insertqi);
Simon Pilgrim216b1bf2015-10-17 11:40:05 +0000915 return Builder.CreateCall(F, Args);
916 }
917
918 return nullptr;
919}
920
Simon Pilgrimc0c56e72016-04-24 17:00:34 +0000921/// Attempt to convert pshufb* to shufflevector if the mask is constant.
922static Value *simplifyX86pshufb(const IntrinsicInst &II,
923 InstCombiner::BuilderTy &Builder) {
Simon Pilgrimbf60cc42016-04-29 21:34:54 +0000924 Constant *V = dyn_cast<Constant>(II.getArgOperand(1));
925 if (!V)
926 return nullptr;
927
Simon Pilgrime5e8c2f2016-05-01 19:26:21 +0000928 auto *VecTy = cast<VectorType>(II.getType());
929 auto *MaskEltTy = Type::getInt32Ty(II.getContext());
930 unsigned NumElts = VecTy->getNumElements();
Craig Topper9a63d7a2016-12-11 00:23:50 +0000931 assert((NumElts == 16 || NumElts == 32 || NumElts == 64) &&
Simon Pilgrimc0c56e72016-04-24 17:00:34 +0000932 "Unexpected number of elements in shuffle mask!");
Simon Pilgrimbf60cc42016-04-29 21:34:54 +0000933
Simon Pilgrime5e8c2f2016-05-01 19:26:21 +0000934 // Construct a shuffle mask from constant integers or UNDEFs.
Craig Topper9a63d7a2016-12-11 00:23:50 +0000935 Constant *Indexes[64] = {nullptr};
Simon Pilgrimc0c56e72016-04-24 17:00:34 +0000936
Simon Pilgrimbf60cc42016-04-29 21:34:54 +0000937 // Each byte in the shuffle control mask forms an index to permute the
938 // corresponding byte in the destination operand.
939 for (unsigned I = 0; I < NumElts; ++I) {
940 Constant *COp = V->getAggregateElement(I);
Simon Pilgrime5e8c2f2016-05-01 19:26:21 +0000941 if (!COp || (!isa<UndefValue>(COp) && !isa<ConstantInt>(COp)))
Simon Pilgrimbf60cc42016-04-29 21:34:54 +0000942 return nullptr;
Simon Pilgrimc0c56e72016-04-24 17:00:34 +0000943
Simon Pilgrime5e8c2f2016-05-01 19:26:21 +0000944 if (isa<UndefValue>(COp)) {
945 Indexes[I] = UndefValue::get(MaskEltTy);
946 continue;
947 }
948
Simon Pilgrimbf60cc42016-04-29 21:34:54 +0000949 int8_t Index = cast<ConstantInt>(COp)->getValue().getZExtValue();
950
951 // If the most significant bit (bit[7]) of each byte of the shuffle
952 // control mask is set, then zero is written in the result byte.
953 // The zero vector is in the right-hand side of the resulting
954 // shufflevector.
955
Simon Pilgrime5e8c2f2016-05-01 19:26:21 +0000956 // The value of each index for the high 128-bit lane is the least
957 // significant 4 bits of the respective shuffle control byte.
958 Index = ((Index < 0) ? NumElts : Index & 0x0F) + (I & 0xF0);
959 Indexes[I] = ConstantInt::get(MaskEltTy, Index);
Simon Pilgrimbf60cc42016-04-29 21:34:54 +0000960 }
Simon Pilgrimc0c56e72016-04-24 17:00:34 +0000961
Simon Pilgrime5e8c2f2016-05-01 19:26:21 +0000962 auto ShuffleMask = ConstantVector::get(makeArrayRef(Indexes, NumElts));
Simon Pilgrimc0c56e72016-04-24 17:00:34 +0000963 auto V1 = II.getArgOperand(0);
Simon Pilgrime5e8c2f2016-05-01 19:26:21 +0000964 auto V2 = Constant::getNullValue(VecTy);
Simon Pilgrimc0c56e72016-04-24 17:00:34 +0000965 return Builder.CreateShuffleVector(V1, V2, ShuffleMask);
966}
967
Simon Pilgrim2f6097d2016-04-24 17:23:46 +0000968/// Attempt to convert vpermilvar* to shufflevector if the mask is constant.
969static Value *simplifyX86vpermilvar(const IntrinsicInst &II,
970 InstCombiner::BuilderTy &Builder) {
Simon Pilgrim640f9962016-04-30 07:23:30 +0000971 Constant *V = dyn_cast<Constant>(II.getArgOperand(1));
972 if (!V)
973 return nullptr;
Simon Pilgrim2f6097d2016-04-24 17:23:46 +0000974
Craig Topper58917f32016-12-11 01:59:36 +0000975 auto *VecTy = cast<VectorType>(II.getType());
Simon Pilgrimeeacc402016-05-01 20:22:42 +0000976 auto *MaskEltTy = Type::getInt32Ty(II.getContext());
Craig Topper58917f32016-12-11 01:59:36 +0000977 unsigned NumElts = VecTy->getVectorNumElements();
978 bool IsPD = VecTy->getScalarType()->isDoubleTy();
979 unsigned NumLaneElts = IsPD ? 2 : 4;
980 assert(NumElts == 16 || NumElts == 8 || NumElts == 4 || NumElts == 2);
Simon Pilgrim2f6097d2016-04-24 17:23:46 +0000981
Simon Pilgrimeeacc402016-05-01 20:22:42 +0000982 // Construct a shuffle mask from constant integers or UNDEFs.
Craig Topper58917f32016-12-11 01:59:36 +0000983 Constant *Indexes[16] = {nullptr};
Simon Pilgrim640f9962016-04-30 07:23:30 +0000984
985 // The intrinsics only read one or two bits, clear the rest.
Simon Pilgrimeeacc402016-05-01 20:22:42 +0000986 for (unsigned I = 0; I < NumElts; ++I) {
Simon Pilgrim640f9962016-04-30 07:23:30 +0000987 Constant *COp = V->getAggregateElement(I);
Simon Pilgrimeeacc402016-05-01 20:22:42 +0000988 if (!COp || (!isa<UndefValue>(COp) && !isa<ConstantInt>(COp)))
Simon Pilgrim640f9962016-04-30 07:23:30 +0000989 return nullptr;
990
Simon Pilgrimeeacc402016-05-01 20:22:42 +0000991 if (isa<UndefValue>(COp)) {
992 Indexes[I] = UndefValue::get(MaskEltTy);
993 continue;
994 }
995
996 APInt Index = cast<ConstantInt>(COp)->getValue();
997 Index = Index.zextOrTrunc(32).getLoBits(2);
Simon Pilgrim640f9962016-04-30 07:23:30 +0000998
999 // The PD variants uses bit 1 to select per-lane element index, so
1000 // shift down to convert to generic shuffle mask index.
Craig Topper58917f32016-12-11 01:59:36 +00001001 if (IsPD)
Craig Topperfc947bc2017-04-18 17:14:21 +00001002 Index.lshrInPlace(1);
Simon Pilgrimeeacc402016-05-01 20:22:42 +00001003
1004 // The _256 variants are a bit trickier since the mask bits always index
1005 // into the corresponding 128 half. In order to convert to a generic
1006 // shuffle, we have to make that explicit.
Craig Topper58917f32016-12-11 01:59:36 +00001007 Index += APInt(32, (I / NumLaneElts) * NumLaneElts);
Simon Pilgrimeeacc402016-05-01 20:22:42 +00001008
1009 Indexes[I] = ConstantInt::get(MaskEltTy, Index);
Simon Pilgrim2f6097d2016-04-24 17:23:46 +00001010 }
1011
Simon Pilgrimeeacc402016-05-01 20:22:42 +00001012 auto ShuffleMask = ConstantVector::get(makeArrayRef(Indexes, NumElts));
Simon Pilgrim2f6097d2016-04-24 17:23:46 +00001013 auto V1 = II.getArgOperand(0);
1014 auto V2 = UndefValue::get(V1->getType());
1015 return Builder.CreateShuffleVector(V1, V2, ShuffleMask);
1016}
1017
Simon Pilgrim8cddf8b2016-05-01 16:41:22 +00001018/// Attempt to convert vpermd/vpermps to shufflevector if the mask is constant.
1019static Value *simplifyX86vpermv(const IntrinsicInst &II,
1020 InstCombiner::BuilderTy &Builder) {
1021 auto *V = dyn_cast<Constant>(II.getArgOperand(1));
1022 if (!V)
1023 return nullptr;
1024
Simon Pilgrimca140b12016-05-01 20:43:02 +00001025 auto *VecTy = cast<VectorType>(II.getType());
1026 auto *MaskEltTy = Type::getInt32Ty(II.getContext());
Simon Pilgrim8cddf8b2016-05-01 16:41:22 +00001027 unsigned Size = VecTy->getNumElements();
Craig Toppere3280452016-12-25 23:58:57 +00001028 assert((Size == 4 || Size == 8 || Size == 16 || Size == 32 || Size == 64) &&
1029 "Unexpected shuffle mask size");
Simon Pilgrim8cddf8b2016-05-01 16:41:22 +00001030
Simon Pilgrimca140b12016-05-01 20:43:02 +00001031 // Construct a shuffle mask from constant integers or UNDEFs.
Craig Toppere3280452016-12-25 23:58:57 +00001032 Constant *Indexes[64] = {nullptr};
Simon Pilgrim8cddf8b2016-05-01 16:41:22 +00001033
1034 for (unsigned I = 0; I < Size; ++I) {
1035 Constant *COp = V->getAggregateElement(I);
Simon Pilgrimca140b12016-05-01 20:43:02 +00001036 if (!COp || (!isa<UndefValue>(COp) && !isa<ConstantInt>(COp)))
Simon Pilgrim8cddf8b2016-05-01 16:41:22 +00001037 return nullptr;
1038
Simon Pilgrimca140b12016-05-01 20:43:02 +00001039 if (isa<UndefValue>(COp)) {
1040 Indexes[I] = UndefValue::get(MaskEltTy);
1041 continue;
1042 }
1043
Craig Toppere3280452016-12-25 23:58:57 +00001044 uint32_t Index = cast<ConstantInt>(COp)->getZExtValue();
1045 Index &= Size - 1;
Simon Pilgrimca140b12016-05-01 20:43:02 +00001046 Indexes[I] = ConstantInt::get(MaskEltTy, Index);
Simon Pilgrim8cddf8b2016-05-01 16:41:22 +00001047 }
1048
Simon Pilgrimca140b12016-05-01 20:43:02 +00001049 auto ShuffleMask = ConstantVector::get(makeArrayRef(Indexes, Size));
Simon Pilgrim8cddf8b2016-05-01 16:41:22 +00001050 auto V1 = II.getArgOperand(0);
1051 auto V2 = UndefValue::get(VecTy);
1052 return Builder.CreateShuffleVector(V1, V2, ShuffleMask);
1053}
1054
Philip Reames484d07c2019-03-20 03:36:05 +00001055// TODO, Obvious Missing Transforms:
Philip Reames484d07c2019-03-20 03:36:05 +00001056// * Narrow width by halfs excluding zero/undef lanes
Philip Reames7c8647b2019-04-25 01:18:56 +00001057Value *InstCombiner::simplifyMaskedLoad(IntrinsicInst &II) {
Philip Reames2ce01702019-04-23 15:25:14 +00001058 Value *LoadPtr = II.getArgOperand(0);
Guillaume Chatelet279fa8e2020-01-23 11:33:12 +01001059 const Align Alignment =
1060 cast<ConstantInt>(II.getArgOperand(1))->getAlignValue();
Philip Reames2ce01702019-04-23 15:25:14 +00001061
David Majnemer666aa942016-07-14 06:58:42 +00001062 // If the mask is all ones or undefs, this is a plain vector load of the 1st
1063 // argument.
Philip Reames2ce01702019-04-23 15:25:14 +00001064 if (maskIsAllOneOrUndef(II.getArgOperand(2)))
James Y Knight14359ef2019-02-01 20:44:24 +00001065 return Builder.CreateAlignedLoad(II.getType(), LoadPtr, Alignment,
1066 "unmaskedload");
Philip Reames2ce01702019-04-23 15:25:14 +00001067
1068 // If we can unconditionally load from this address, replace with a
1069 // load/select idiom. TODO: use DT for context sensitive query
Guillaume Chatelet279fa8e2020-01-23 11:33:12 +01001070 if (isDereferenceableAndAlignedPointer(LoadPtr, II.getType(), Alignment,
1071 II.getModule()->getDataLayout(), &II,
1072 nullptr)) {
Philip Reames2ce01702019-04-23 15:25:14 +00001073 Value *LI = Builder.CreateAlignedLoad(II.getType(), LoadPtr, Alignment,
1074 "unmaskedload");
1075 return Builder.CreateSelect(II.getArgOperand(2), LI, II.getArgOperand(3));
Sanjay Patelb695c552016-02-01 17:00:10 +00001076 }
1077
1078 return nullptr;
1079}
1080
Philip Reames484d07c2019-03-20 03:36:05 +00001081// TODO, Obvious Missing Transforms:
Philip Reames484d07c2019-03-20 03:36:05 +00001082// * Single constant active lane -> store
1083// * Narrow width by halfs excluding zero/undef lanes
Philip Reamese4588bb2019-03-20 18:44:58 +00001084Instruction *InstCombiner::simplifyMaskedStore(IntrinsicInst &II) {
Sanjay Patel04f792b2016-02-01 19:39:52 +00001085 auto *ConstMask = dyn_cast<Constant>(II.getArgOperand(3));
1086 if (!ConstMask)
1087 return nullptr;
1088
1089 // If the mask is all zeros, this instruction does nothing.
1090 if (ConstMask->isNullValue())
Philip Reamese4588bb2019-03-20 18:44:58 +00001091 return eraseInstFromFunction(II);
Sanjay Patel04f792b2016-02-01 19:39:52 +00001092
1093 // If the mask is all ones, this is a plain vector store of the 1st argument.
1094 if (ConstMask->isAllOnesValue()) {
1095 Value *StorePtr = II.getArgOperand(1);
Guillaume Chatelet5b99c182019-10-22 12:55:32 +00001096 MaybeAlign Alignment(
1097 cast<ConstantInt>(II.getArgOperand(2))->getZExtValue());
Sanjay Patel04f792b2016-02-01 19:39:52 +00001098 return new StoreInst(II.getArgOperand(0), StorePtr, false, Alignment);
1099 }
1100
Philip Reamese4588bb2019-03-20 18:44:58 +00001101 // Use masked off lanes to simplify operands via SimplifyDemandedVectorElts
1102 APInt DemandedElts = possiblyDemandedEltsInMask(ConstMask);
1103 APInt UndefElts(DemandedElts.getBitWidth(), 0);
1104 if (Value *V = SimplifyDemandedVectorElts(II.getOperand(0),
1105 DemandedElts, UndefElts)) {
1106 II.setOperand(0, V);
1107 return &II;
1108 }
1109
Sanjay Patel04f792b2016-02-01 19:39:52 +00001110 return nullptr;
1111}
1112
Philip Reames484d07c2019-03-20 03:36:05 +00001113// TODO, Obvious Missing Transforms:
1114// * Single constant active lane load -> load
1115// * Dereferenceable address & few lanes -> scalarize speculative load/selects
1116// * Adjacent vector addresses -> masked.load
1117// * Narrow width by halfs excluding zero/undef lanes
Philip Reames60212be2019-03-21 03:23:40 +00001118// * Vector splat address w/known mask -> scalar load
1119// * Vector incrementing address -> vector masked load
Philip Reames7c8647b2019-04-25 01:18:56 +00001120Instruction *InstCombiner::simplifyMaskedGather(IntrinsicInst &II) {
Sanjay Patel103ab7d2016-02-01 22:10:26 +00001121 return nullptr;
1122}
1123
Philip Reames60212be2019-03-21 03:23:40 +00001124// TODO, Obvious Missing Transforms:
1125// * Single constant active lane -> store
1126// * Adjacent vector addresses -> masked.store
1127// * Narrow store width by halfs excluding zero/undef lanes
1128// * Vector splat address w/known mask -> scalar store
1129// * Vector incrementing address -> vector masked store
1130Instruction *InstCombiner::simplifyMaskedScatter(IntrinsicInst &II) {
1131 auto *ConstMask = dyn_cast<Constant>(II.getArgOperand(3));
1132 if (!ConstMask)
1133 return nullptr;
1134
1135 // If the mask is all zeros, a scatter does nothing.
1136 if (ConstMask->isNullValue())
1137 return eraseInstFromFunction(II);
1138
1139 // Use masked off lanes to simplify operands via SimplifyDemandedVectorElts
1140 APInt DemandedElts = possiblyDemandedEltsInMask(ConstMask);
1141 APInt UndefElts(DemandedElts.getBitWidth(), 0);
1142 if (Value *V = SimplifyDemandedVectorElts(II.getOperand(0),
1143 DemandedElts, UndefElts)) {
1144 II.setOperand(0, V);
1145 return &II;
1146 }
1147 if (Value *V = SimplifyDemandedVectorElts(II.getOperand(1),
1148 DemandedElts, UndefElts)) {
1149 II.setOperand(1, V);
1150 return &II;
1151 }
1152
1153 return nullptr;
1154}
1155
Piotr Padlewskic63b4922018-07-12 23:55:20 +00001156/// This function transforms launder.invariant.group and strip.invariant.group
1157/// like:
1158/// launder(launder(%x)) -> launder(%x) (the result is not the argument)
1159/// launder(strip(%x)) -> launder(%x)
1160/// strip(strip(%x)) -> strip(%x) (the result is not the argument)
1161/// strip(launder(%x)) -> strip(%x)
1162/// This is legal because it preserves the most recent information about
1163/// the presence or absence of invariant.group.
1164static Instruction *simplifyInvariantGroupIntrinsic(IntrinsicInst &II,
1165 InstCombiner &IC) {
1166 auto *Arg = II.getArgOperand(0);
1167 auto *StrippedArg = Arg->stripPointerCasts();
1168 auto *StrippedInvariantGroupsArg = Arg->stripPointerCastsAndInvariantGroups();
1169 if (StrippedArg == StrippedInvariantGroupsArg)
1170 return nullptr; // No launders/strips to remove.
1171
1172 Value *Result = nullptr;
1173
1174 if (II.getIntrinsicID() == Intrinsic::launder_invariant_group)
1175 Result = IC.Builder.CreateLaunderInvariantGroup(StrippedInvariantGroupsArg);
1176 else if (II.getIntrinsicID() == Intrinsic::strip_invariant_group)
1177 Result = IC.Builder.CreateStripInvariantGroup(StrippedInvariantGroupsArg);
1178 else
1179 llvm_unreachable(
1180 "simplifyInvariantGroupIntrinsic only handles launder and strip");
1181 if (Result->getType()->getPointerAddressSpace() !=
1182 II.getType()->getPointerAddressSpace())
1183 Result = IC.Builder.CreateAddrSpaceCast(Result, II.getType());
1184 if (Result->getType() != II.getType())
1185 Result = IC.Builder.CreateBitCast(Result, II.getType());
1186
1187 return cast<Instruction>(Result);
1188}
1189
Amaury Sechet763c59d2016-08-18 20:43:50 +00001190static Instruction *foldCttzCtlz(IntrinsicInst &II, InstCombiner &IC) {
1191 assert((II.getIntrinsicID() == Intrinsic::cttz ||
1192 II.getIntrinsicID() == Intrinsic::ctlz) &&
1193 "Expected cttz or ctlz intrinsic");
David Bolvansky5ba60b22019-04-02 20:13:28 +00001194 bool IsTZ = II.getIntrinsicID() == Intrinsic::cttz;
Sanjay Patel8e3ab172016-08-05 22:42:46 +00001195 Value *Op0 = II.getArgOperand(0);
David Bolvansky5ba60b22019-04-02 20:13:28 +00001196 Value *X;
1197 // ctlz(bitreverse(x)) -> cttz(x)
1198 // cttz(bitreverse(x)) -> ctlz(x)
1199 if (match(Op0, m_BitReverse(m_Value(X)))) {
1200 Intrinsic::ID ID = IsTZ ? Intrinsic::ctlz : Intrinsic::cttz;
1201 Function *F = Intrinsic::getDeclaration(II.getModule(), ID, II.getType());
1202 return CallInst::Create(F, {X, II.getArgOperand(1)});
1203 }
Sanjay Patel8e3ab172016-08-05 22:42:46 +00001204
David Bolvansky4b284782019-06-21 15:26:22 +00001205 if (IsTZ) {
1206 // cttz(-x) -> cttz(x)
1207 if (match(Op0, m_Neg(m_Value(X)))) {
1208 II.setOperand(0, X);
1209 return &II;
1210 }
1211
1212 // cttz(abs(x)) -> cttz(x)
1213 // cttz(nabs(x)) -> cttz(x)
1214 Value *Y;
1215 SelectPatternFlavor SPF = matchSelectPattern(Op0, X, Y).Flavor;
1216 if (SPF == SPF_ABS || SPF == SPF_NABS) {
1217 II.setOperand(0, X);
1218 return &II;
1219 }
David Bolvansky01511192019-06-20 17:04:14 +00001220 }
1221
Craig Topper8205a1a2017-05-24 16:53:07 +00001222 KnownBits Known = IC.computeKnownBits(Op0, 0, &II);
Sanjay Patel8e3ab172016-08-05 22:42:46 +00001223
1224 // Create a mask for bits above (ctlz) or below (cttz) the first known one.
Craig Topper8df66c62017-05-12 17:20:30 +00001225 unsigned PossibleZeros = IsTZ ? Known.countMaxTrailingZeros()
1226 : Known.countMaxLeadingZeros();
1227 unsigned DefiniteZeros = IsTZ ? Known.countMinTrailingZeros()
1228 : Known.countMinLeadingZeros();
Sanjay Patel8e3ab172016-08-05 22:42:46 +00001229
1230 // If all bits above (ctlz) or below (cttz) the first known one are known
1231 // zero, this value is constant.
1232 // FIXME: This should be in InstSimplify because we're replacing an
1233 // instruction with a constant.
Craig Topper9474e9b2017-04-27 04:51:25 +00001234 if (PossibleZeros == DefiniteZeros) {
Craig Topper0799ff92017-06-03 18:50:32 +00001235 auto *C = ConstantInt::get(Op0->getType(), DefiniteZeros);
Amaury Sechet763c59d2016-08-18 20:43:50 +00001236 return IC.replaceInstUsesWith(II, C);
1237 }
1238
1239 // If the input to cttz/ctlz is known to be non-zero,
1240 // then change the 'ZeroIsUndef' parameter to 'true'
1241 // because we know the zero behavior can't affect the result.
Craig Topper73ba1c82017-06-07 07:40:37 +00001242 if (!Known.One.isNullValue() ||
Craig Topperd45185f2017-05-26 18:23:57 +00001243 isKnownNonZero(Op0, IC.getDataLayout(), 0, &IC.getAssumptionCache(), &II,
1244 &IC.getDominatorTree())) {
Amaury Sechet763c59d2016-08-18 20:43:50 +00001245 if (!match(II.getArgOperand(1), m_One())) {
Craig Topperbb4069e2017-07-07 23:16:26 +00001246 II.setOperand(1, IC.Builder.getTrue());
Amaury Sechet763c59d2016-08-18 20:43:50 +00001247 return &II;
1248 }
1249 }
Sanjay Patel8e3ab172016-08-05 22:42:46 +00001250
Craig Topper5b173f22017-06-21 16:32:35 +00001251 // Add range metadata since known bits can't completely reflect what we know.
1252 // TODO: Handle splat vectors.
1253 auto *IT = dyn_cast<IntegerType>(Op0->getType());
1254 if (IT && IT->getBitWidth() != 1 && !II.getMetadata(LLVMContext::MD_range)) {
1255 Metadata *LowAndHigh[] = {
1256 ConstantAsMetadata::get(ConstantInt::get(IT, DefiniteZeros)),
1257 ConstantAsMetadata::get(ConstantInt::get(IT, PossibleZeros + 1))};
1258 II.setMetadata(LLVMContext::MD_range,
1259 MDNode::get(II.getContext(), LowAndHigh));
1260 return &II;
1261 }
1262
1263 return nullptr;
1264}
1265
1266static Instruction *foldCtpop(IntrinsicInst &II, InstCombiner &IC) {
1267 assert(II.getIntrinsicID() == Intrinsic::ctpop &&
1268 "Expected ctpop intrinsic");
1269 Value *Op0 = II.getArgOperand(0);
David Bolvansky937720e2019-04-03 08:08:44 +00001270 Value *X;
1271 // ctpop(bitreverse(x)) -> ctpop(x)
1272 // ctpop(bswap(x)) -> ctpop(x)
1273 if (match(Op0, m_BitReverse(m_Value(X))) || match(Op0, m_BSwap(m_Value(X)))) {
1274 II.setOperand(0, X);
1275 return &II;
1276 }
1277
Craig Topper5b173f22017-06-21 16:32:35 +00001278 // FIXME: Try to simplify vectors of integers.
1279 auto *IT = dyn_cast<IntegerType>(Op0->getType());
1280 if (!IT)
1281 return nullptr;
1282
1283 unsigned BitWidth = IT->getBitWidth();
1284 KnownBits Known(BitWidth);
1285 IC.computeKnownBits(Op0, Known, 0, &II);
1286
1287 unsigned MinCount = Known.countMinPopulation();
1288 unsigned MaxCount = Known.countMaxPopulation();
1289
1290 // Add range metadata since known bits can't completely reflect what we know.
1291 if (IT->getBitWidth() != 1 && !II.getMetadata(LLVMContext::MD_range)) {
1292 Metadata *LowAndHigh[] = {
1293 ConstantAsMetadata::get(ConstantInt::get(IT, MinCount)),
1294 ConstantAsMetadata::get(ConstantInt::get(IT, MaxCount + 1))};
1295 II.setMetadata(LLVMContext::MD_range,
1296 MDNode::get(II.getContext(), LowAndHigh));
1297 return &II;
1298 }
1299
Sanjay Patel8e3ab172016-08-05 22:42:46 +00001300 return nullptr;
1301}
1302
Sanjay Patel1ace9932016-02-26 21:04:14 +00001303// TODO: If the x86 backend knew how to convert a bool vector mask back to an
1304// XMM register mask efficiently, we could transform all x86 masked intrinsics
1305// to LLVM masked intrinsics and remove the x86 masked intrinsic defs.
Sanjay Patel98a71502016-02-29 23:16:48 +00001306static Instruction *simplifyX86MaskedLoad(IntrinsicInst &II, InstCombiner &IC) {
1307 Value *Ptr = II.getOperand(0);
1308 Value *Mask = II.getOperand(1);
Sanjay Patel5e5056d2016-04-12 23:16:23 +00001309 Constant *ZeroVec = Constant::getNullValue(II.getType());
Sanjay Patel98a71502016-02-29 23:16:48 +00001310
1311 // Special case a zero mask since that's not a ConstantDataVector.
Sanjay Patel5e5056d2016-04-12 23:16:23 +00001312 // This masked load instruction creates a zero vector.
Sanjay Patel98a71502016-02-29 23:16:48 +00001313 if (isa<ConstantAggregateZero>(Mask))
Sanjay Patel5e5056d2016-04-12 23:16:23 +00001314 return IC.replaceInstUsesWith(II, ZeroVec);
Sanjay Patel98a71502016-02-29 23:16:48 +00001315
1316 auto *ConstMask = dyn_cast<ConstantDataVector>(Mask);
1317 if (!ConstMask)
1318 return nullptr;
1319
1320 // The mask is constant. Convert this x86 intrinsic to the LLVM instrinsic
1321 // to allow target-independent optimizations.
1322
1323 // First, cast the x86 intrinsic scalar pointer to a vector pointer to match
1324 // the LLVM intrinsic definition for the pointer argument.
1325 unsigned AddrSpace = cast<PointerType>(Ptr->getType())->getAddressSpace();
1326 PointerType *VecPtrTy = PointerType::get(II.getType(), AddrSpace);
Craig Topperbb4069e2017-07-07 23:16:26 +00001327 Value *PtrCast = IC.Builder.CreateBitCast(Ptr, VecPtrTy, "castvec");
Sanjay Patel98a71502016-02-29 23:16:48 +00001328
1329 // Second, convert the x86 XMM integer vector mask to a vector of bools based
1330 // on each element's most significant bit (the sign bit).
1331 Constant *BoolMask = getNegativeIsTrueBoolVec(ConstMask);
1332
Sanjay Patel5e5056d2016-04-12 23:16:23 +00001333 // The pass-through vector for an x86 masked load is a zero vector.
1334 CallInst *NewMaskedLoad =
Guillaume Chateletbc8a1ab2020-01-21 11:21:31 +01001335 IC.Builder.CreateMaskedLoad(PtrCast, Align::None(), BoolMask, ZeroVec);
Sanjay Patel98a71502016-02-29 23:16:48 +00001336 return IC.replaceInstUsesWith(II, NewMaskedLoad);
1337}
1338
1339// TODO: If the x86 backend knew how to convert a bool vector mask back to an
1340// XMM register mask efficiently, we could transform all x86 masked intrinsics
1341// to LLVM masked intrinsics and remove the x86 masked intrinsic defs.
Sanjay Patel1ace9932016-02-26 21:04:14 +00001342static bool simplifyX86MaskedStore(IntrinsicInst &II, InstCombiner &IC) {
1343 Value *Ptr = II.getOperand(0);
1344 Value *Mask = II.getOperand(1);
1345 Value *Vec = II.getOperand(2);
1346
1347 // Special case a zero mask since that's not a ConstantDataVector:
1348 // this masked store instruction does nothing.
1349 if (isa<ConstantAggregateZero>(Mask)) {
1350 IC.eraseInstFromFunction(II);
1351 return true;
1352 }
1353
Sanjay Patelc4acbae2016-03-12 15:16:59 +00001354 // The SSE2 version is too weird (eg, unaligned but non-temporal) to do
1355 // anything else at this level.
1356 if (II.getIntrinsicID() == Intrinsic::x86_sse2_maskmov_dqu)
1357 return false;
1358
Sanjay Patel1ace9932016-02-26 21:04:14 +00001359 auto *ConstMask = dyn_cast<ConstantDataVector>(Mask);
1360 if (!ConstMask)
1361 return false;
1362
1363 // The mask is constant. Convert this x86 intrinsic to the LLVM instrinsic
1364 // to allow target-independent optimizations.
1365
1366 // First, cast the x86 intrinsic scalar pointer to a vector pointer to match
1367 // the LLVM intrinsic definition for the pointer argument.
1368 unsigned AddrSpace = cast<PointerType>(Ptr->getType())->getAddressSpace();
1369 PointerType *VecPtrTy = PointerType::get(Vec->getType(), AddrSpace);
Craig Topperbb4069e2017-07-07 23:16:26 +00001370 Value *PtrCast = IC.Builder.CreateBitCast(Ptr, VecPtrTy, "castvec");
Sanjay Patel1ace9932016-02-26 21:04:14 +00001371
1372 // Second, convert the x86 XMM integer vector mask to a vector of bools based
1373 // on each element's most significant bit (the sign bit).
1374 Constant *BoolMask = getNegativeIsTrueBoolVec(ConstMask);
1375
Guillaume Chatelet09572332020-01-21 16:13:04 +01001376 IC.Builder.CreateMaskedStore(Vec, PtrCast, Align::None(), BoolMask);
Sanjay Patel1ace9932016-02-26 21:04:14 +00001377
1378 // 'Replace uses' doesn't work for stores. Erase the original masked store.
1379 IC.eraseInstFromFunction(II);
1380 return true;
1381}
1382
Matt Arsenaultcdb468c2017-02-27 23:08:49 +00001383// Constant fold llvm.amdgcn.fmed3 intrinsics for standard inputs.
1384//
1385// A single NaN input is folded to minnum, so we rely on that folding for
1386// handling NaNs.
1387static APFloat fmed3AMDGCN(const APFloat &Src0, const APFloat &Src1,
1388 const APFloat &Src2) {
1389 APFloat Max3 = maxnum(maxnum(Src0, Src1), Src2);
1390
1391 APFloat::cmpResult Cmp0 = Max3.compare(Src0);
1392 assert(Cmp0 != APFloat::cmpUnordered && "nans handled separately");
1393 if (Cmp0 == APFloat::cmpEqual)
1394 return maxnum(Src1, Src2);
1395
1396 APFloat::cmpResult Cmp1 = Max3.compare(Src1);
1397 assert(Cmp1 != APFloat::cmpUnordered && "nans handled separately");
1398 if (Cmp1 == APFloat::cmpEqual)
1399 return maxnum(Src0, Src2);
1400
1401 return maxnum(Src0, Src1);
1402}
1403
Alexandros Lamprineas52457d32018-05-30 14:38:50 +00001404/// Convert a table lookup to shufflevector if the mask is constant.
1405/// This could benefit tbl1 if the mask is { 7,6,5,4,3,2,1,0 }, in
1406/// which case we could lower the shufflevector with rev64 instructions
1407/// as it's actually a byte reverse.
1408static Value *simplifyNeonTbl1(const IntrinsicInst &II,
1409 InstCombiner::BuilderTy &Builder) {
1410 // Bail out if the mask is not a constant.
1411 auto *C = dyn_cast<Constant>(II.getArgOperand(1));
1412 if (!C)
1413 return nullptr;
1414
1415 auto *VecTy = cast<VectorType>(II.getType());
1416 unsigned NumElts = VecTy->getNumElements();
1417
1418 // Only perform this transformation for <8 x i8> vector types.
1419 if (!VecTy->getElementType()->isIntegerTy(8) || NumElts != 8)
1420 return nullptr;
1421
1422 uint32_t Indexes[8];
1423
1424 for (unsigned I = 0; I < NumElts; ++I) {
1425 Constant *COp = C->getAggregateElement(I);
1426
1427 if (!COp || !isa<ConstantInt>(COp))
1428 return nullptr;
1429
1430 Indexes[I] = cast<ConstantInt>(COp)->getLimitedValue();
1431
1432 // Make sure the mask indices are in range.
1433 if (Indexes[I] >= NumElts)
1434 return nullptr;
1435 }
1436
1437 auto *ShuffleMask = ConstantDataVector::get(II.getContext(),
1438 makeArrayRef(Indexes));
1439 auto *V1 = II.getArgOperand(0);
1440 auto *V2 = Constant::getNullValue(V1->getType());
1441 return Builder.CreateShuffleVector(V1, V2, ShuffleMask);
1442}
1443
Alexandros Lamprineas61f0ba12018-05-31 12:19:18 +00001444/// Convert a vector load intrinsic into a simple llvm load instruction.
1445/// This is beneficial when the underlying object being addressed comes
1446/// from a constant, since we get constant-folding for free.
1447static Value *simplifyNeonVld1(const IntrinsicInst &II,
1448 unsigned MemAlign,
1449 InstCombiner::BuilderTy &Builder) {
1450 auto *IntrAlign = dyn_cast<ConstantInt>(II.getArgOperand(1));
1451
1452 if (!IntrAlign)
1453 return nullptr;
1454
1455 unsigned Alignment = IntrAlign->getLimitedValue() < MemAlign ?
1456 MemAlign : IntrAlign->getLimitedValue();
1457
1458 if (!isPowerOf2_32(Alignment))
1459 return nullptr;
1460
1461 auto *BCastInst = Builder.CreateBitCast(II.getArgOperand(0),
1462 PointerType::get(II.getType(), 0));
Guillaume Chatelet279fa8e2020-01-23 11:33:12 +01001463 return Builder.CreateAlignedLoad(II.getType(), BCastInst, Align(Alignment));
Alexandros Lamprineas61f0ba12018-05-31 12:19:18 +00001464}
1465
Arnaud A. de Grandmaison333ef382016-05-10 09:24:49 +00001466// Returns true iff the 2 intrinsics have the same operands, limiting the
1467// comparison to the first NumOperands.
1468static bool haveSameOperands(const IntrinsicInst &I, const IntrinsicInst &E,
1469 unsigned NumOperands) {
1470 assert(I.getNumArgOperands() >= NumOperands && "Not enough operands");
1471 assert(E.getNumArgOperands() >= NumOperands && "Not enough operands");
1472 for (unsigned i = 0; i < NumOperands; i++)
1473 if (I.getArgOperand(i) != E.getArgOperand(i))
1474 return false;
1475 return true;
1476}
1477
1478// Remove trivially empty start/end intrinsic ranges, i.e. a start
1479// immediately followed by an end (ignoring debuginfo or other
1480// start/end intrinsics in between). As this handles only the most trivial
1481// cases, tracking the nesting level is not needed:
1482//
1483// call @llvm.foo.start(i1 0) ; &I
1484// call @llvm.foo.start(i1 0)
1485// call @llvm.foo.end(i1 0) ; This one will not be skipped: it will be removed
1486// call @llvm.foo.end(i1 0)
1487static bool removeTriviallyEmptyRange(IntrinsicInst &I, unsigned StartID,
1488 unsigned EndID, InstCombiner &IC) {
1489 assert(I.getIntrinsicID() == StartID &&
1490 "Start intrinsic does not have expected ID");
1491 BasicBlock::iterator BI(I), BE(I.getParent()->end());
1492 for (++BI; BI != BE; ++BI) {
1493 if (auto *E = dyn_cast<IntrinsicInst>(BI)) {
1494 if (isa<DbgInfoIntrinsic>(E) || E->getIntrinsicID() == StartID)
1495 continue;
1496 if (E->getIntrinsicID() == EndID &&
1497 haveSameOperands(I, *E, E->getNumArgOperands())) {
1498 IC.eraseInstFromFunction(*E);
1499 IC.eraseInstFromFunction(I);
1500 return true;
1501 }
1502 }
1503 break;
1504 }
1505
1506 return false;
1507}
1508
Justin Lebar698c31b2017-01-27 00:58:58 +00001509// Convert NVVM intrinsics to target-generic LLVM code where possible.
1510static Instruction *SimplifyNVVMIntrinsic(IntrinsicInst *II, InstCombiner &IC) {
1511 // Each NVVM intrinsic we can simplify can be replaced with one of:
1512 //
1513 // * an LLVM intrinsic,
1514 // * an LLVM cast operation,
1515 // * an LLVM binary operation, or
1516 // * ad-hoc LLVM IR for the particular operation.
1517
1518 // Some transformations are only valid when the module's
1519 // flush-denormals-to-zero (ftz) setting is true/false, whereas other
1520 // transformations are valid regardless of the module's ftz setting.
1521 enum FtzRequirementTy {
1522 FTZ_Any, // Any ftz setting is ok.
1523 FTZ_MustBeOn, // Transformation is valid only if ftz is on.
1524 FTZ_MustBeOff, // Transformation is valid only if ftz is off.
1525 };
1526 // Classes of NVVM intrinsics that can't be replaced one-to-one with a
1527 // target-generic intrinsic, cast op, or binary op but that we can nonetheless
1528 // simplify.
1529 enum SpecialCase {
1530 SPC_Reciprocal,
1531 };
1532
1533 // SimplifyAction is a poor-man's variant (plus an additional flag) that
1534 // represents how to replace an NVVM intrinsic with target-generic LLVM IR.
1535 struct SimplifyAction {
1536 // Invariant: At most one of these Optionals has a value.
1537 Optional<Intrinsic::ID> IID;
1538 Optional<Instruction::CastOps> CastOp;
1539 Optional<Instruction::BinaryOps> BinaryOp;
1540 Optional<SpecialCase> Special;
1541
1542 FtzRequirementTy FtzRequirement = FTZ_Any;
1543
1544 SimplifyAction() = default;
1545
1546 SimplifyAction(Intrinsic::ID IID, FtzRequirementTy FtzReq)
1547 : IID(IID), FtzRequirement(FtzReq) {}
1548
1549 // Cast operations don't have anything to do with FTZ, so we skip that
1550 // argument.
1551 SimplifyAction(Instruction::CastOps CastOp) : CastOp(CastOp) {}
1552
1553 SimplifyAction(Instruction::BinaryOps BinaryOp, FtzRequirementTy FtzReq)
1554 : BinaryOp(BinaryOp), FtzRequirement(FtzReq) {}
1555
1556 SimplifyAction(SpecialCase Special, FtzRequirementTy FtzReq)
1557 : Special(Special), FtzRequirement(FtzReq) {}
1558 };
1559
1560 // Try to generate a SimplifyAction describing how to replace our
1561 // IntrinsicInstr with target-generic LLVM IR.
1562 const SimplifyAction Action = [II]() -> SimplifyAction {
1563 switch (II->getIntrinsicID()) {
Justin Lebar698c31b2017-01-27 00:58:58 +00001564 // NVVM intrinsics that map directly to LLVM intrinsics.
1565 case Intrinsic::nvvm_ceil_d:
1566 return {Intrinsic::ceil, FTZ_Any};
1567 case Intrinsic::nvvm_ceil_f:
1568 return {Intrinsic::ceil, FTZ_MustBeOff};
1569 case Intrinsic::nvvm_ceil_ftz_f:
1570 return {Intrinsic::ceil, FTZ_MustBeOn};
1571 case Intrinsic::nvvm_fabs_d:
1572 return {Intrinsic::fabs, FTZ_Any};
1573 case Intrinsic::nvvm_fabs_f:
1574 return {Intrinsic::fabs, FTZ_MustBeOff};
1575 case Intrinsic::nvvm_fabs_ftz_f:
1576 return {Intrinsic::fabs, FTZ_MustBeOn};
1577 case Intrinsic::nvvm_floor_d:
1578 return {Intrinsic::floor, FTZ_Any};
1579 case Intrinsic::nvvm_floor_f:
1580 return {Intrinsic::floor, FTZ_MustBeOff};
1581 case Intrinsic::nvvm_floor_ftz_f:
1582 return {Intrinsic::floor, FTZ_MustBeOn};
1583 case Intrinsic::nvvm_fma_rn_d:
1584 return {Intrinsic::fma, FTZ_Any};
1585 case Intrinsic::nvvm_fma_rn_f:
1586 return {Intrinsic::fma, FTZ_MustBeOff};
1587 case Intrinsic::nvvm_fma_rn_ftz_f:
1588 return {Intrinsic::fma, FTZ_MustBeOn};
1589 case Intrinsic::nvvm_fmax_d:
1590 return {Intrinsic::maxnum, FTZ_Any};
1591 case Intrinsic::nvvm_fmax_f:
1592 return {Intrinsic::maxnum, FTZ_MustBeOff};
1593 case Intrinsic::nvvm_fmax_ftz_f:
1594 return {Intrinsic::maxnum, FTZ_MustBeOn};
1595 case Intrinsic::nvvm_fmin_d:
1596 return {Intrinsic::minnum, FTZ_Any};
1597 case Intrinsic::nvvm_fmin_f:
1598 return {Intrinsic::minnum, FTZ_MustBeOff};
1599 case Intrinsic::nvvm_fmin_ftz_f:
1600 return {Intrinsic::minnum, FTZ_MustBeOn};
1601 case Intrinsic::nvvm_round_d:
1602 return {Intrinsic::round, FTZ_Any};
1603 case Intrinsic::nvvm_round_f:
1604 return {Intrinsic::round, FTZ_MustBeOff};
1605 case Intrinsic::nvvm_round_ftz_f:
1606 return {Intrinsic::round, FTZ_MustBeOn};
1607 case Intrinsic::nvvm_sqrt_rn_d:
1608 return {Intrinsic::sqrt, FTZ_Any};
1609 case Intrinsic::nvvm_sqrt_f:
1610 // nvvm_sqrt_f is a special case. For most intrinsics, foo_ftz_f is the
1611 // ftz version, and foo_f is the non-ftz version. But nvvm_sqrt_f adopts
1612 // the ftz-ness of the surrounding code. sqrt_rn_f and sqrt_rn_ftz_f are
1613 // the versions with explicit ftz-ness.
1614 return {Intrinsic::sqrt, FTZ_Any};
1615 case Intrinsic::nvvm_sqrt_rn_f:
1616 return {Intrinsic::sqrt, FTZ_MustBeOff};
1617 case Intrinsic::nvvm_sqrt_rn_ftz_f:
1618 return {Intrinsic::sqrt, FTZ_MustBeOn};
1619 case Intrinsic::nvvm_trunc_d:
1620 return {Intrinsic::trunc, FTZ_Any};
1621 case Intrinsic::nvvm_trunc_f:
1622 return {Intrinsic::trunc, FTZ_MustBeOff};
1623 case Intrinsic::nvvm_trunc_ftz_f:
1624 return {Intrinsic::trunc, FTZ_MustBeOn};
1625
1626 // NVVM intrinsics that map to LLVM cast operations.
1627 //
1628 // Note that llvm's target-generic conversion operators correspond to the rz
1629 // (round to zero) versions of the nvvm conversion intrinsics, even though
1630 // most everything else here uses the rn (round to nearest even) nvvm ops.
1631 case Intrinsic::nvvm_d2i_rz:
1632 case Intrinsic::nvvm_f2i_rz:
1633 case Intrinsic::nvvm_d2ll_rz:
1634 case Intrinsic::nvvm_f2ll_rz:
1635 return {Instruction::FPToSI};
1636 case Intrinsic::nvvm_d2ui_rz:
1637 case Intrinsic::nvvm_f2ui_rz:
1638 case Intrinsic::nvvm_d2ull_rz:
1639 case Intrinsic::nvvm_f2ull_rz:
1640 return {Instruction::FPToUI};
1641 case Intrinsic::nvvm_i2d_rz:
1642 case Intrinsic::nvvm_i2f_rz:
1643 case Intrinsic::nvvm_ll2d_rz:
1644 case Intrinsic::nvvm_ll2f_rz:
1645 return {Instruction::SIToFP};
1646 case Intrinsic::nvvm_ui2d_rz:
1647 case Intrinsic::nvvm_ui2f_rz:
1648 case Intrinsic::nvvm_ull2d_rz:
1649 case Intrinsic::nvvm_ull2f_rz:
1650 return {Instruction::UIToFP};
1651
1652 // NVVM intrinsics that map to LLVM binary ops.
1653 case Intrinsic::nvvm_add_rn_d:
1654 return {Instruction::FAdd, FTZ_Any};
1655 case Intrinsic::nvvm_add_rn_f:
1656 return {Instruction::FAdd, FTZ_MustBeOff};
1657 case Intrinsic::nvvm_add_rn_ftz_f:
1658 return {Instruction::FAdd, FTZ_MustBeOn};
1659 case Intrinsic::nvvm_mul_rn_d:
1660 return {Instruction::FMul, FTZ_Any};
1661 case Intrinsic::nvvm_mul_rn_f:
1662 return {Instruction::FMul, FTZ_MustBeOff};
1663 case Intrinsic::nvvm_mul_rn_ftz_f:
1664 return {Instruction::FMul, FTZ_MustBeOn};
1665 case Intrinsic::nvvm_div_rn_d:
1666 return {Instruction::FDiv, FTZ_Any};
1667 case Intrinsic::nvvm_div_rn_f:
1668 return {Instruction::FDiv, FTZ_MustBeOff};
1669 case Intrinsic::nvvm_div_rn_ftz_f:
1670 return {Instruction::FDiv, FTZ_MustBeOn};
1671
1672 // The remainder of cases are NVVM intrinsics that map to LLVM idioms, but
1673 // need special handling.
1674 //
Hiroshi Inoue0ca79dc2017-07-11 06:04:59 +00001675 // We seem to be missing intrinsics for rcp.approx.{ftz.}f32, which is just
Justin Lebar698c31b2017-01-27 00:58:58 +00001676 // as well.
1677 case Intrinsic::nvvm_rcp_rn_d:
1678 return {SPC_Reciprocal, FTZ_Any};
1679 case Intrinsic::nvvm_rcp_rn_f:
1680 return {SPC_Reciprocal, FTZ_MustBeOff};
1681 case Intrinsic::nvvm_rcp_rn_ftz_f:
1682 return {SPC_Reciprocal, FTZ_MustBeOn};
1683
1684 // We do not currently simplify intrinsics that give an approximate answer.
1685 // These include:
1686 //
1687 // - nvvm_cos_approx_{f,ftz_f}
1688 // - nvvm_ex2_approx_{d,f,ftz_f}
1689 // - nvvm_lg2_approx_{d,f,ftz_f}
1690 // - nvvm_sin_approx_{f,ftz_f}
1691 // - nvvm_sqrt_approx_{f,ftz_f}
1692 // - nvvm_rsqrt_approx_{d,f,ftz_f}
1693 // - nvvm_div_approx_{ftz_d,ftz_f,f}
1694 // - nvvm_rcp_approx_ftz_d
1695 //
1696 // Ideally we'd encode them as e.g. "fast call @llvm.cos", where "fast"
1697 // means that fastmath is enabled in the intrinsic. Unfortunately only
1698 // binary operators (currently) have a fastmath bit in SelectionDAG, so this
1699 // information gets lost and we can't select on it.
1700 //
1701 // TODO: div and rcp are lowered to a binary op, so these we could in theory
1702 // lower them to "fast fdiv".
1703
1704 default:
1705 return {};
1706 }
1707 }();
1708
1709 // If Action.FtzRequirementTy is not satisfied by the module's ftz state, we
1710 // can bail out now. (Notice that in the case that IID is not an NVVM
1711 // intrinsic, we don't have to look up any module metadata, as
1712 // FtzRequirementTy will be FTZ_Any.)
1713 if (Action.FtzRequirement != FTZ_Any) {
Matt Arsenaulta4451d82019-11-01 17:57:29 -07001714 StringRef Attr = II->getFunction()
1715 ->getFnAttribute("denormal-fp-math-f32")
1716 .getValueAsString();
1717 bool FtzEnabled = parseDenormalFPAttribute(Attr) != DenormalMode::IEEE;
Justin Lebar698c31b2017-01-27 00:58:58 +00001718
1719 if (FtzEnabled != (Action.FtzRequirement == FTZ_MustBeOn))
1720 return nullptr;
1721 }
1722
1723 // Simplify to target-generic intrinsic.
1724 if (Action.IID) {
1725 SmallVector<Value *, 4> Args(II->arg_operands());
1726 // All the target-generic intrinsics currently of interest to us have one
1727 // type argument, equal to that of the nvvm intrinsic's argument.
Justin Lebare3ac0fb2017-01-27 01:49:39 +00001728 Type *Tys[] = {II->getArgOperand(0)->getType()};
Justin Lebar698c31b2017-01-27 00:58:58 +00001729 return CallInst::Create(
1730 Intrinsic::getDeclaration(II->getModule(), *Action.IID, Tys), Args);
1731 }
1732
1733 // Simplify to target-generic binary op.
1734 if (Action.BinaryOp)
1735 return BinaryOperator::Create(*Action.BinaryOp, II->getArgOperand(0),
1736 II->getArgOperand(1), II->getName());
1737
1738 // Simplify to target-generic cast op.
1739 if (Action.CastOp)
1740 return CastInst::Create(*Action.CastOp, II->getArgOperand(0), II->getType(),
1741 II->getName());
1742
1743 // All that's left are the special cases.
1744 if (!Action.Special)
1745 return nullptr;
1746
1747 switch (*Action.Special) {
1748 case SPC_Reciprocal:
1749 // Simplify reciprocal.
1750 return BinaryOperator::Create(
1751 Instruction::FDiv, ConstantFP::get(II->getArgOperand(0)->getType(), 1),
1752 II->getArgOperand(0), II->getName());
1753 }
Justin Lebar25ebe2d2017-01-27 02:04:07 +00001754 llvm_unreachable("All SpecialCase enumerators should be handled in switch.");
Justin Lebar698c31b2017-01-27 00:58:58 +00001755}
1756
Arnaud A. de Grandmaison333ef382016-05-10 09:24:49 +00001757Instruction *InstCombiner::visitVAStartInst(VAStartInst &I) {
1758 removeTriviallyEmptyRange(I, Intrinsic::vastart, Intrinsic::vaend, *this);
1759 return nullptr;
1760}
1761
1762Instruction *InstCombiner::visitVACopyInst(VACopyInst &I) {
1763 removeTriviallyEmptyRange(I, Intrinsic::vacopy, Intrinsic::vaend, *this);
1764 return nullptr;
1765}
1766
Sanjay Patel790af912018-11-26 22:00:41 +00001767static Instruction *canonicalizeConstantArg0ToArg1(CallInst &Call) {
1768 assert(Call.getNumArgOperands() > 1 && "Need at least 2 args to swap");
1769 Value *Arg0 = Call.getArgOperand(0), *Arg1 = Call.getArgOperand(1);
1770 if (isa<Constant>(Arg0) && !isa<Constant>(Arg1)) {
1771 Call.setArgOperand(0, Arg1);
1772 Call.setArgOperand(1, Arg0);
1773 return &Call;
1774 }
1775 return nullptr;
1776}
1777
Nikita Popov884feb12019-03-06 18:30:00 +00001778Instruction *InstCombiner::foldIntrinsicWithOverflowCommon(IntrinsicInst *II) {
Nikita Popov352f5982019-05-26 11:43:31 +00001779 WithOverflowInst *WO = cast<WithOverflowInst>(II);
Nikita Popov884feb12019-03-06 18:30:00 +00001780 Value *OperationResult = nullptr;
1781 Constant *OverflowResult = nullptr;
Nikita Popov352f5982019-05-26 11:43:31 +00001782 if (OptimizeOverflowCheck(WO->getBinaryOp(), WO->isSigned(), WO->getLHS(),
1783 WO->getRHS(), *WO, OperationResult, OverflowResult))
1784 return CreateOverflowTuple(WO, OperationResult, OverflowResult);
Nikita Popov884feb12019-03-06 18:30:00 +00001785 return nullptr;
1786}
1787
Sanjay Patelcd4377c2016-01-20 22:24:38 +00001788/// CallInst simplification. This mostly only handles folding of intrinsic
Craig Topperc1892ec2019-01-31 17:23:29 +00001789/// instructions. For normal calls, it allows visitCallBase to do the heavy
Sanjay Patelcd4377c2016-01-20 22:24:38 +00001790/// lifting.
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001791Instruction *InstCombiner::visitCallInst(CallInst &CI) {
Philip Reames7a6db4f2017-12-27 00:16:12 +00001792 if (Value *V = SimplifyCall(&CI, SQ.getWithInstruction(&CI)))
Sanjay Patel4b198802016-02-01 22:23:39 +00001793 return replaceInstUsesWith(CI, V);
David Majnemer15032582015-05-22 03:56:46 +00001794
Justin Bogner99798402016-08-05 01:06:44 +00001795 if (isFreeCall(&CI, &TLI))
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001796 return visitFree(CI);
1797
1798 // If the caller function is nounwind, mark the call as nounwind, even if the
1799 // callee isn't.
Sanjay Patel5a470952016-08-11 15:16:06 +00001800 if (CI.getFunction()->doesNotThrow() && !CI.doesNotThrow()) {
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001801 CI.setDoesNotThrow();
1802 return &CI;
1803 }
Jim Grosbach7815f562012-02-03 00:07:04 +00001804
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001805 IntrinsicInst *II = dyn_cast<IntrinsicInst>(&CI);
Craig Topperc1892ec2019-01-31 17:23:29 +00001806 if (!II) return visitCallBase(CI);
Gabor Greif589a0b92010-06-24 12:58:35 +00001807
Craig Topper784929d2019-02-08 20:48:56 +00001808 // Intrinsics cannot occur in an invoke or a callbr, so handle them here
1809 // instead of in visitCallBase.
Daniel Neilson8f30ec62018-05-11 14:30:02 +00001810 if (auto *MI = dyn_cast<AnyMemIntrinsic>(II)) {
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001811 bool Changed = false;
1812
1813 // memmove/cpy/set of zero bytes is a noop.
1814 if (Constant *NumBytes = dyn_cast<Constant>(MI->getLength())) {
Chris Lattnerc663a672010-10-01 05:51:02 +00001815 if (NumBytes->isNullValue())
Sanjay Patel4b198802016-02-01 22:23:39 +00001816 return eraseInstFromFunction(CI);
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001817
1818 if (ConstantInt *CI = dyn_cast<ConstantInt>(NumBytes))
1819 if (CI->getZExtValue() == 1) {
1820 // Replace the instruction with just byte operations. We would
1821 // transform other cases to loads/stores, but we don't know if
1822 // alignment is sufficient.
1823 }
1824 }
Jim Grosbach7815f562012-02-03 00:07:04 +00001825
Chris Lattnerc663a672010-10-01 05:51:02 +00001826 // No other transformations apply to volatile transfers.
Daniel Neilson8f30ec62018-05-11 14:30:02 +00001827 if (auto *M = dyn_cast<MemIntrinsic>(MI))
1828 if (M->isVolatile())
1829 return nullptr;
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001830
1831 // If we have a memmove and the source operation is a constant global,
1832 // then the source and dest pointers can't alias, so we can change this
1833 // into a call to memcpy.
Daniel Neilson8f30ec62018-05-11 14:30:02 +00001834 if (auto *MMI = dyn_cast<AnyMemMoveInst>(MI)) {
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001835 if (GlobalVariable *GVSrc = dyn_cast<GlobalVariable>(MMI->getSource()))
1836 if (GVSrc->isConstant()) {
Sanjay Patelaf674fb2015-12-14 17:24:23 +00001837 Module *M = CI.getModule();
Daniel Neilson8f30ec62018-05-11 14:30:02 +00001838 Intrinsic::ID MemCpyID =
1839 isa<AtomicMemMoveInst>(MMI)
1840 ? Intrinsic::memcpy_element_unordered_atomic
1841 : Intrinsic::memcpy;
Jay Foadb804a2b2011-07-12 14:06:48 +00001842 Type *Tys[3] = { CI.getArgOperand(0)->getType(),
1843 CI.getArgOperand(1)->getType(),
1844 CI.getArgOperand(2)->getType() };
Benjamin Kramere6e19332011-07-14 17:45:39 +00001845 CI.setCalledFunction(Intrinsic::getDeclaration(M, MemCpyID, Tys));
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001846 Changed = true;
1847 }
1848 }
1849
Daniel Neilson8f30ec62018-05-11 14:30:02 +00001850 if (AnyMemTransferInst *MTI = dyn_cast<AnyMemTransferInst>(MI)) {
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001851 // memmove(x,x,size) -> noop.
1852 if (MTI->getSource() == MTI->getDest())
Sanjay Patel4b198802016-02-01 22:23:39 +00001853 return eraseInstFromFunction(CI);
Eric Christopher7258dcd2010-04-16 23:37:20 +00001854 }
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001855
Eric Christopher7258dcd2010-04-16 23:37:20 +00001856 // If we can determine a pointer alignment that is bigger than currently
1857 // set, update the alignment.
Daniel Neilson8f30ec62018-05-11 14:30:02 +00001858 if (auto *MTI = dyn_cast<AnyMemTransferInst>(MI)) {
1859 if (Instruction *I = SimplifyAnyMemTransfer(MTI))
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001860 return I;
Daniel Neilsonf6651d42018-05-11 20:04:50 +00001861 } else if (auto *MSI = dyn_cast<AnyMemSetInst>(MI)) {
1862 if (Instruction *I = SimplifyAnyMemSet(MSI))
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001863 return I;
1864 }
Gabor Greif590d95e2010-06-24 13:42:49 +00001865
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001866 if (Changed) return II;
1867 }
Jim Grosbach7815f562012-02-03 00:07:04 +00001868
Philip Reames68a2e4d2019-03-15 19:54:06 +00001869 // For vector result intrinsics, use the generic demanded vector support.
Philip Reamesc71e9962019-01-30 19:21:11 +00001870 if (II->getType()->isVectorTy()) {
1871 auto VWidth = II->getType()->getVectorNumElements();
1872 APInt UndefElts(VWidth, 0);
1873 APInt AllOnesEltMask(APInt::getAllOnesValue(VWidth));
1874 if (Value *V = SimplifyDemandedVectorElts(II, AllOnesEltMask, UndefElts)) {
1875 if (V != II)
1876 return replaceInstUsesWith(*II, V);
1877 return II;
1878 }
1879 }
1880
Justin Lebar698c31b2017-01-27 00:58:58 +00001881 if (Instruction *I = SimplifyNVVMIntrinsic(II, *this))
1882 return I;
1883
Sanjay Patel1c600c62016-01-20 16:41:43 +00001884 auto SimplifyDemandedVectorEltsLow = [this](Value *Op, unsigned Width,
1885 unsigned DemandedWidth) {
Simon Pilgrim61116dd2015-09-17 20:32:45 +00001886 APInt UndefElts(Width, 0);
1887 APInt DemandedElts = APInt::getLowBitsSet(Width, DemandedWidth);
1888 return SimplifyDemandedVectorElts(Op, DemandedElts, UndefElts);
1889 };
1890
Sanjay Patel62f457b2019-05-06 15:35:02 +00001891 Intrinsic::ID IID = II->getIntrinsicID();
1892 switch (IID) {
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001893 default: break;
George Burgess IV3f089142016-12-20 23:46:36 +00001894 case Intrinsic::objectsize:
Erik Pilkington600e9de2019-01-30 20:34:35 +00001895 if (Value *V = lowerObjectSizeCall(II, DL, &TLI, /*MustSucceed=*/false))
1896 return replaceInstUsesWith(CI, V);
Craig Topperf40110f2014-04-25 05:29:35 +00001897 return nullptr;
Michael Ilseman536cc322012-12-13 03:13:36 +00001898 case Intrinsic::bswap: {
1899 Value *IIOperand = II->getArgOperand(0);
Craig Topperf40110f2014-04-25 05:29:35 +00001900 Value *X = nullptr;
Michael Ilseman536cc322012-12-13 03:13:36 +00001901
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001902 // bswap(trunc(bswap(x))) -> trunc(lshr(x, c))
Michael Ilseman536cc322012-12-13 03:13:36 +00001903 if (match(IIOperand, m_Trunc(m_BSwap(m_Value(X))))) {
1904 unsigned C = X->getType()->getPrimitiveSizeInBits() -
1905 IIOperand->getType()->getPrimitiveSizeInBits();
1906 Value *CV = ConstantInt::get(X->getType(), C);
Craig Topperbb4069e2017-07-07 23:16:26 +00001907 Value *V = Builder.CreateLShr(X, CV);
Michael Ilseman536cc322012-12-13 03:13:36 +00001908 return new TruncInst(V, IIOperand->getType());
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001909 }
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001910 break;
Michael Ilseman536cc322012-12-13 03:13:36 +00001911 }
Sanjay Patelb695c552016-02-01 17:00:10 +00001912 case Intrinsic::masked_load:
Philip Reames7c8647b2019-04-25 01:18:56 +00001913 if (Value *SimplifiedMaskedOp = simplifyMaskedLoad(*II))
Sanjay Patel4b198802016-02-01 22:23:39 +00001914 return replaceInstUsesWith(CI, SimplifiedMaskedOp);
Sanjay Patelb695c552016-02-01 17:00:10 +00001915 break;
Sanjay Patel04f792b2016-02-01 19:39:52 +00001916 case Intrinsic::masked_store:
Philip Reamese4588bb2019-03-20 18:44:58 +00001917 return simplifyMaskedStore(*II);
Sanjay Patel103ab7d2016-02-01 22:10:26 +00001918 case Intrinsic::masked_gather:
Philip Reames7c8647b2019-04-25 01:18:56 +00001919 return simplifyMaskedGather(*II);
Sanjay Patel103ab7d2016-02-01 22:10:26 +00001920 case Intrinsic::masked_scatter:
Philip Reamese4588bb2019-03-20 18:44:58 +00001921 return simplifyMaskedScatter(*II);
Piotr Padlewskic63b4922018-07-12 23:55:20 +00001922 case Intrinsic::launder_invariant_group:
1923 case Intrinsic::strip_invariant_group:
1924 if (auto *SkippedBarrier = simplifyInvariantGroupIntrinsic(*II, *this))
1925 return replaceInstUsesWith(*II, SkippedBarrier);
1926 break;
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001927 case Intrinsic::powi:
Gabor Greif589a0b92010-06-24 12:58:35 +00001928 if (ConstantInt *Power = dyn_cast<ConstantInt>(II->getArgOperand(1))) {
Philip Reames5000ba62017-12-27 01:14:30 +00001929 // 0 and 1 are handled in instsimplify
1930
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001931 // powi(x, -1) -> 1/x
Craig Topper79ab6432017-07-06 18:39:47 +00001932 if (Power->isMinusOne())
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001933 return BinaryOperator::CreateFDiv(ConstantFP::get(CI.getType(), 1.0),
Gabor Greif589a0b92010-06-24 12:58:35 +00001934 II->getArgOperand(0));
Philip Reamescd13a662017-12-27 01:30:12 +00001935 // powi(x, 2) -> x*x
1936 if (Power->equalsInt(2))
1937 return BinaryOperator::CreateFMul(II->getArgOperand(0),
1938 II->getArgOperand(0));
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001939 }
1940 break;
Jim Grosbach7815f562012-02-03 00:07:04 +00001941
Sanjay Patel8e3ab172016-08-05 22:42:46 +00001942 case Intrinsic::cttz:
1943 case Intrinsic::ctlz:
Amaury Sechet763c59d2016-08-18 20:43:50 +00001944 if (auto *I = foldCttzCtlz(*II, *this))
1945 return I;
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001946 break;
Sanjoy Dasb0984472015-04-08 04:27:22 +00001947
Craig Topper5b173f22017-06-21 16:32:35 +00001948 case Intrinsic::ctpop:
1949 if (auto *I = foldCtpop(*II, *this))
1950 return I;
1951 break;
1952
Sanjay Patela1395642018-11-13 23:27:23 +00001953 case Intrinsic::fshl:
1954 case Intrinsic::fshr: {
Sanjay Patelb3bcd952019-03-17 19:08:00 +00001955 Value *Op0 = II->getArgOperand(0), *Op1 = II->getArgOperand(1);
1956 Type *Ty = II->getType();
1957 unsigned BitWidth = Ty->getScalarSizeInBits();
Sanjay Patelde1d5d32019-03-14 19:22:08 +00001958 Constant *ShAmtC;
1959 if (match(II->getArgOperand(2), m_Constant(ShAmtC)) &&
1960 !isa<ConstantExpr>(ShAmtC) && !ShAmtC->containsConstantExpression()) {
Sanjay Patelb3bcd952019-03-17 19:08:00 +00001961 // Canonicalize a shift amount constant operand to modulo the bit-width.
1962 Constant *WidthC = ConstantInt::get(Ty, BitWidth);
Sanjay Patelde1d5d32019-03-14 19:22:08 +00001963 Constant *ModuloC = ConstantExpr::getURem(ShAmtC, WidthC);
1964 if (ModuloC != ShAmtC) {
1965 II->setArgOperand(2, ModuloC);
1966 return II;
1967 }
Sanjay Patel60633932019-03-18 14:27:51 +00001968 assert(ConstantExpr::getICmp(ICmpInst::ICMP_UGT, WidthC, ShAmtC) ==
1969 ConstantInt::getTrue(CmpInst::makeCmpResultType(Ty)) &&
1970 "Shift amount expected to be modulo bitwidth");
1971
Sanjay Patel84de8a32019-03-18 14:10:11 +00001972 // Canonicalize funnel shift right by constant to funnel shift left. This
1973 // is not entirely arbitrary. For historical reasons, the backend may
1974 // recognize rotate left patterns but miss rotate right patterns.
Sanjay Patel62f457b2019-05-06 15:35:02 +00001975 if (IID == Intrinsic::fshr) {
Sanjay Patel84de8a32019-03-18 14:10:11 +00001976 // fshr X, Y, C --> fshl X, Y, (BitWidth - C)
Sanjay Patelb3bcd952019-03-17 19:08:00 +00001977 Constant *LeftShiftC = ConstantExpr::getSub(WidthC, ShAmtC);
1978 Module *Mod = II->getModule();
1979 Function *Fshl = Intrinsic::getDeclaration(Mod, Intrinsic::fshl, Ty);
Sanjay Patel84de8a32019-03-18 14:10:11 +00001980 return CallInst::Create(Fshl, { Op0, Op1, LeftShiftC });
Sanjay Patelb3bcd952019-03-17 19:08:00 +00001981 }
Sanjay Patel62f457b2019-05-06 15:35:02 +00001982 assert(IID == Intrinsic::fshl &&
Sanjay Patel84de8a32019-03-18 14:10:11 +00001983 "All funnel shifts by simple constants should go left");
Nikita Popov6e81d422018-11-23 22:45:08 +00001984
Sanjay Patel60633932019-03-18 14:27:51 +00001985 // fshl(X, 0, C) --> shl X, C
1986 // fshl(X, undef, C) --> shl X, C
1987 if (match(Op1, m_ZeroInt()) || match(Op1, m_Undef()))
1988 return BinaryOperator::CreateShl(Op0, ShAmtC);
Nikita Popov6e81d422018-11-23 22:45:08 +00001989
Sanjay Patel60633932019-03-18 14:27:51 +00001990 // fshl(0, X, C) --> lshr X, (BW-C)
1991 // fshl(undef, X, C) --> lshr X, (BW-C)
1992 if (match(Op0, m_ZeroInt()) || match(Op0, m_Undef()))
1993 return BinaryOperator::CreateLShr(Op1,
1994 ConstantExpr::getSub(WidthC, ShAmtC));
Sanjay Patel89efefb2019-06-24 15:20:49 +00001995
1996 // fshl i16 X, X, 8 --> bswap i16 X (reduce to more-specific form)
1997 if (Op0 == Op1 && BitWidth == 16 && match(ShAmtC, m_SpecificInt(8))) {
1998 Module *Mod = II->getModule();
1999 Function *Bswap = Intrinsic::getDeclaration(Mod, Intrinsic::bswap, Ty);
2000 return CallInst::Create(Bswap, { Op0 });
2001 }
Nikita Popov6e81d422018-11-23 22:45:08 +00002002 }
2003
Nikita Popov5ecd6a42019-04-16 19:05:49 +00002004 // Left or right might be masked.
2005 if (SimplifyDemandedInstructionBits(*II))
2006 return &CI;
2007
Sanjay Patela1395642018-11-13 23:27:23 +00002008 // The shift amount (operand 2) of a funnel shift is modulo the bitwidth,
2009 // so only the low bits of the shift amount are demanded if the bitwidth is
2010 // a power-of-2.
Sanjay Patela1395642018-11-13 23:27:23 +00002011 if (!isPowerOf2_32(BitWidth))
2012 break;
2013 APInt Op2Demanded = APInt::getLowBitsSet(BitWidth, Log2_32_Ceil(BitWidth));
2014 KnownBits Op2Known(BitWidth);
2015 if (SimplifyDemandedBits(II, 2, Op2Demanded, Op2Known))
2016 return &CI;
2017 break;
2018 }
Nikita Popov37cf25c2019-03-20 18:00:27 +00002019 case Intrinsic::uadd_with_overflow:
Nikita Popov884feb12019-03-06 18:30:00 +00002020 case Intrinsic::sadd_with_overflow: {
2021 if (Instruction *I = canonicalizeConstantArg0ToArg1(CI))
2022 return I;
2023 if (Instruction *I = foldIntrinsicWithOverflowCommon(II))
2024 return I;
2025
2026 // Given 2 constant operands whose sum does not overflow:
Nikita Popov37cf25c2019-03-20 18:00:27 +00002027 // uaddo (X +nuw C0), C1 -> uaddo X, C0 + C1
Nikita Popov884feb12019-03-06 18:30:00 +00002028 // saddo (X +nsw C0), C1 -> saddo X, C0 + C1
2029 Value *X;
2030 const APInt *C0, *C1;
2031 Value *Arg0 = II->getArgOperand(0);
2032 Value *Arg1 = II->getArgOperand(1);
Sanjay Patel62f457b2019-05-06 15:35:02 +00002033 bool IsSigned = IID == Intrinsic::sadd_with_overflow;
Nikita Popov37cf25c2019-03-20 18:00:27 +00002034 bool HasNWAdd = IsSigned ? match(Arg0, m_NSWAdd(m_Value(X), m_APInt(C0)))
2035 : match(Arg0, m_NUWAdd(m_Value(X), m_APInt(C0)));
2036 if (HasNWAdd && match(Arg1, m_APInt(C1))) {
Nikita Popov884feb12019-03-06 18:30:00 +00002037 bool Overflow;
Nikita Popov37cf25c2019-03-20 18:00:27 +00002038 APInt NewC =
2039 IsSigned ? C1->sadd_ov(*C0, Overflow) : C1->uadd_ov(*C0, Overflow);
Nikita Popov884feb12019-03-06 18:30:00 +00002040 if (!Overflow)
2041 return replaceInstUsesWith(
2042 *II, Builder.CreateBinaryIntrinsic(
Sanjay Patel62f457b2019-05-06 15:35:02 +00002043 IID, X, ConstantInt::get(Arg1->getType(), NewC)));
Nikita Popov884feb12019-03-06 18:30:00 +00002044 }
Nikita Popov884feb12019-03-06 18:30:00 +00002045 break;
2046 }
Nikita Popov7a543c32019-04-10 16:27:36 +00002047
Nick Lewyckyabe2cc12015-04-13 19:17:37 +00002048 case Intrinsic::umul_with_overflow:
2049 case Intrinsic::smul_with_overflow:
Sanjay Patel790af912018-11-26 22:00:41 +00002050 if (Instruction *I = canonicalizeConstantArg0ToArg1(CI))
2051 return I;
Justin Bognercd1d5aa2016-08-17 20:30:52 +00002052 LLVM_FALLTHROUGH;
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002053
Nick Lewyckyabe2cc12015-04-13 19:17:37 +00002054 case Intrinsic::usub_with_overflow:
Nikita Popov7a543c32019-04-10 16:27:36 +00002055 if (Instruction *I = foldIntrinsicWithOverflowCommon(II))
2056 return I;
2057 break;
2058
Nick Lewyckyabe2cc12015-04-13 19:17:37 +00002059 case Intrinsic::ssub_with_overflow: {
Nikita Popov884feb12019-03-06 18:30:00 +00002060 if (Instruction *I = foldIntrinsicWithOverflowCommon(II))
2061 return I;
Benjamin Kramera420df22014-07-04 10:22:21 +00002062
Nikita Popov7a543c32019-04-10 16:27:36 +00002063 Constant *C;
2064 Value *Arg0 = II->getArgOperand(0);
2065 Value *Arg1 = II->getArgOperand(1);
2066 // Given a constant C that is not the minimum signed value
2067 // for an integer of a given bit width:
2068 //
2069 // ssubo X, C -> saddo X, -C
2070 if (match(Arg1, m_Constant(C)) && C->isNotMinSignedValue()) {
2071 Value *NegVal = ConstantExpr::getNeg(C);
2072 // Build a saddo call that is equivalent to the discovered
2073 // ssubo call.
2074 return replaceInstUsesWith(
2075 *II, Builder.CreateBinaryIntrinsic(Intrinsic::sadd_with_overflow,
2076 Arg0, NegVal));
2077 }
2078
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002079 break;
Erik Eckstein096ff7d2014-12-11 08:02:30 +00002080 }
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002081
Nikita Popov085d24a2018-11-28 16:36:52 +00002082 case Intrinsic::uadd_sat:
2083 case Intrinsic::sadd_sat:
2084 if (Instruction *I = canonicalizeConstantArg0ToArg1(CI))
2085 return I;
Nikita Popov78a92952018-11-28 16:36:59 +00002086 LLVM_FALLTHROUGH;
2087 case Intrinsic::usub_sat:
2088 case Intrinsic::ssub_sat: {
Nikita Popovc51cdac2019-05-28 18:59:21 +00002089 SaturatingInst *SI = cast<SaturatingInst>(II);
Nikita Popov53828032019-05-29 18:37:13 +00002090 Type *Ty = SI->getType();
Nikita Popovc51cdac2019-05-28 18:59:21 +00002091 Value *Arg0 = SI->getLHS();
2092 Value *Arg1 = SI->getRHS();
Nikita Popov78a92952018-11-28 16:36:59 +00002093
2094 // Make use of known overflow information.
Nikita Popovc51cdac2019-05-28 18:59:21 +00002095 OverflowResult OR = computeOverflow(SI->getBinaryOp(), SI->isSigned(),
2096 Arg0, Arg1, SI);
2097 switch (OR) {
2098 case OverflowResult::MayOverflow:
2099 break;
2100 case OverflowResult::NeverOverflows:
2101 if (SI->isSigned())
2102 return BinaryOperator::CreateNSW(SI->getBinaryOp(), Arg0, Arg1);
2103 else
2104 return BinaryOperator::CreateNUW(SI->getBinaryOp(), Arg0, Arg1);
Nikita Popov53828032019-05-29 18:37:13 +00002105 case OverflowResult::AlwaysOverflowsLow: {
2106 unsigned BitWidth = Ty->getScalarSizeInBits();
2107 APInt Min = APSInt::getMinValue(BitWidth, !SI->isSigned());
2108 return replaceInstUsesWith(*SI, ConstantInt::get(Ty, Min));
2109 }
2110 case OverflowResult::AlwaysOverflowsHigh: {
2111 unsigned BitWidth = Ty->getScalarSizeInBits();
2112 APInt Max = APSInt::getMaxValue(BitWidth, !SI->isSigned());
2113 return replaceInstUsesWith(*SI, ConstantInt::get(Ty, Max));
2114 }
Nikita Popov78a92952018-11-28 16:36:59 +00002115 }
Nikita Popov42f89982018-11-28 16:37:09 +00002116
2117 // ssub.sat(X, C) -> sadd.sat(X, -C) if C != MIN
Nikita Popov0c5d6cc2018-12-01 10:58:34 +00002118 Constant *C;
2119 if (IID == Intrinsic::ssub_sat && match(Arg1, m_Constant(C)) &&
2120 C->isNotMinSignedValue()) {
2121 Value *NegVal = ConstantExpr::getNeg(C);
Nikita Popov42f89982018-11-28 16:37:09 +00002122 return replaceInstUsesWith(
2123 *II, Builder.CreateBinaryIntrinsic(
2124 Intrinsic::sadd_sat, Arg0, NegVal));
2125 }
Nikita Popov8d63aed2018-11-28 16:37:15 +00002126
2127 // sat(sat(X + Val2) + Val) -> sat(X + (Val+Val2))
2128 // sat(sat(X - Val2) - Val) -> sat(X - (Val+Val2))
2129 // if Val and Val2 have the same sign
2130 if (auto *Other = dyn_cast<IntrinsicInst>(Arg0)) {
2131 Value *X;
2132 const APInt *Val, *Val2;
2133 APInt NewVal;
2134 bool IsUnsigned =
2135 IID == Intrinsic::uadd_sat || IID == Intrinsic::usub_sat;
Sanjay Patel62f457b2019-05-06 15:35:02 +00002136 if (Other->getIntrinsicID() == IID &&
Nikita Popov8d63aed2018-11-28 16:37:15 +00002137 match(Arg1, m_APInt(Val)) &&
2138 match(Other->getArgOperand(0), m_Value(X)) &&
2139 match(Other->getArgOperand(1), m_APInt(Val2))) {
2140 if (IsUnsigned)
2141 NewVal = Val->uadd_sat(*Val2);
2142 else if (Val->isNonNegative() == Val2->isNonNegative()) {
2143 bool Overflow;
2144 NewVal = Val->sadd_ov(*Val2, Overflow);
2145 if (Overflow) {
2146 // Both adds together may add more than SignedMaxValue
2147 // without saturating the final result.
2148 break;
2149 }
2150 } else {
2151 // Cannot fold saturated addition with different signs.
2152 break;
2153 }
2154
2155 return replaceInstUsesWith(
2156 *II, Builder.CreateBinaryIntrinsic(
2157 IID, X, ConstantInt::get(II->getType(), NewVal)));
2158 }
2159 }
Nikita Popov085d24a2018-11-28 16:36:52 +00002160 break;
Nikita Popov78a92952018-11-28 16:36:59 +00002161 }
Nikita Popov085d24a2018-11-28 16:36:52 +00002162
Matt Arsenaultd6511b42014-10-21 23:00:20 +00002163 case Intrinsic::minnum:
Thomas Livelyc3392502018-10-19 19:01:26 +00002164 case Intrinsic::maxnum:
2165 case Intrinsic::minimum:
2166 case Intrinsic::maximum: {
Sanjay Patel790af912018-11-26 22:00:41 +00002167 if (Instruction *I = canonicalizeConstantArg0ToArg1(CI))
2168 return I;
Matt Arsenaultd6511b42014-10-21 23:00:20 +00002169 Value *Arg0 = II->getArgOperand(0);
2170 Value *Arg1 = II->getArgOperand(1);
Sanjay Patelc7bb1432018-05-10 20:03:13 +00002171 Value *X, *Y;
2172 if (match(Arg0, m_FNeg(m_Value(X))) && match(Arg1, m_FNeg(m_Value(Y))) &&
2173 (Arg0->hasOneUse() || Arg1->hasOneUse())) {
2174 // If both operands are negated, invert the call and negate the result:
Thomas Livelyc3392502018-10-19 19:01:26 +00002175 // min(-X, -Y) --> -(max(X, Y))
2176 // max(-X, -Y) --> -(min(X, Y))
2177 Intrinsic::ID NewIID;
Volkan Keles3ca146d2018-10-31 17:50:52 +00002178 switch (IID) {
Thomas Livelyc3392502018-10-19 19:01:26 +00002179 case Intrinsic::maxnum:
2180 NewIID = Intrinsic::minnum;
2181 break;
2182 case Intrinsic::minnum:
2183 NewIID = Intrinsic::maxnum;
2184 break;
2185 case Intrinsic::maximum:
2186 NewIID = Intrinsic::minimum;
2187 break;
2188 case Intrinsic::minimum:
2189 NewIID = Intrinsic::maximum;
2190 break;
2191 default:
2192 llvm_unreachable("unexpected intrinsic ID");
2193 }
Neil Henning57f5d0a2018-10-08 10:32:33 +00002194 Value *NewCall = Builder.CreateBinaryIntrinsic(NewIID, X, Y, II);
Sanjay Patelc7bb1432018-05-10 20:03:13 +00002195 Instruction *FNeg = BinaryOperator::CreateFNeg(NewCall);
2196 FNeg->copyIRFlags(II);
2197 return FNeg;
2198 }
Volkan Keles3ca146d2018-10-31 17:50:52 +00002199
2200 // m(m(X, C2), C1) -> m(X, C)
2201 const APFloat *C1, *C2;
2202 if (auto *M = dyn_cast<IntrinsicInst>(Arg0)) {
2203 if (M->getIntrinsicID() == IID && match(Arg1, m_APFloat(C1)) &&
2204 ((match(M->getArgOperand(0), m_Value(X)) &&
2205 match(M->getArgOperand(1), m_APFloat(C2))) ||
2206 (match(M->getArgOperand(1), m_Value(X)) &&
2207 match(M->getArgOperand(0), m_APFloat(C2))))) {
2208 APFloat Res(0.0);
2209 switch (IID) {
2210 case Intrinsic::maxnum:
2211 Res = maxnum(*C1, *C2);
2212 break;
2213 case Intrinsic::minnum:
2214 Res = minnum(*C1, *C2);
2215 break;
2216 case Intrinsic::maximum:
2217 Res = maximum(*C1, *C2);
2218 break;
2219 case Intrinsic::minimum:
2220 Res = minimum(*C1, *C2);
2221 break;
2222 default:
2223 llvm_unreachable("unexpected intrinsic ID");
2224 }
2225 Instruction *NewCall = Builder.CreateBinaryIntrinsic(
2226 IID, X, ConstantFP::get(Arg0->getType(), Res));
2227 NewCall->copyIRFlags(II);
2228 return replaceInstUsesWith(*II, NewCall);
2229 }
2230 }
2231
Matt Arsenaultd6511b42014-10-21 23:00:20 +00002232 break;
2233 }
Matt Arsenault1cc294c2017-01-03 04:32:31 +00002234 case Intrinsic::fmuladd: {
Matt Arsenault92057602017-02-16 18:46:24 +00002235 // Canonicalize fast fmuladd to the separate fmul + fadd.
Sanjay Patel629c4112017-11-06 16:27:15 +00002236 if (II->isFast()) {
Craig Topperbb4069e2017-07-07 23:16:26 +00002237 BuilderTy::FastMathFlagGuard Guard(Builder);
2238 Builder.setFastMathFlags(II->getFastMathFlags());
2239 Value *Mul = Builder.CreateFMul(II->getArgOperand(0),
2240 II->getArgOperand(1));
2241 Value *Add = Builder.CreateFAdd(Mul, II->getArgOperand(2));
Matt Arsenault92057602017-02-16 18:46:24 +00002242 Add->takeName(II);
2243 return replaceInstUsesWith(*II, Add);
2244 }
2245
Florian Hahnf3ab99d2019-09-25 17:03:20 +00002246 // Try to simplify the underlying FMul.
2247 if (Value *V = SimplifyFMulInst(II->getArgOperand(0), II->getArgOperand(1),
2248 II->getFastMathFlags(),
2249 SQ.getWithInstruction(II))) {
2250 auto *FAdd = BinaryOperator::CreateFAdd(V, II->getArgOperand(2));
2251 FAdd->copyFastMathFlags(II);
2252 return FAdd;
2253 }
2254
Matt Arsenault92057602017-02-16 18:46:24 +00002255 LLVM_FALLTHROUGH;
2256 }
2257 case Intrinsic::fma: {
Sanjay Patel790af912018-11-26 22:00:41 +00002258 if (Instruction *I = canonicalizeConstantArg0ToArg1(CI))
2259 return I;
Matt Arsenaultb264c942017-01-03 04:32:35 +00002260
Matt Arsenault1cc294c2017-01-03 04:32:31 +00002261 // fma fneg(x), fneg(y), z -> fma x, y, z
Sanjay Patel790af912018-11-26 22:00:41 +00002262 Value *Src0 = II->getArgOperand(0);
2263 Value *Src1 = II->getArgOperand(1);
Sanjay Patel236442e2018-04-05 13:24:26 +00002264 Value *X, *Y;
2265 if (match(Src0, m_FNeg(m_Value(X))) && match(Src1, m_FNeg(m_Value(Y)))) {
2266 II->setArgOperand(0, X);
2267 II->setArgOperand(1, Y);
Matt Arsenault3f509042017-01-10 23:17:52 +00002268 return II;
Matt Arsenault1cc294c2017-01-03 04:32:31 +00002269 }
2270
2271 // fma fabs(x), fabs(x), z -> fma x, x, z
Matt Arsenaultd1496502018-07-27 09:04:35 +00002272 if (match(Src0, m_FAbs(m_Value(X))) &&
2273 match(Src1, m_FAbs(m_Specific(X)))) {
Sanjay Patel236442e2018-04-05 13:24:26 +00002274 II->setArgOperand(0, X);
2275 II->setArgOperand(1, X);
Matt Arsenault3f509042017-01-10 23:17:52 +00002276 return II;
Matt Arsenault1cc294c2017-01-03 04:32:31 +00002277 }
2278
Florian Hahnf3ab99d2019-09-25 17:03:20 +00002279 // Try to simplify the underlying FMul. We can only apply simplifications
2280 // that do not require rounding.
2281 if (Value *V = SimplifyFMAFMul(II->getArgOperand(0), II->getArgOperand(1),
2282 II->getFastMathFlags(),
2283 SQ.getWithInstruction(II))) {
2284 auto *FAdd = BinaryOperator::CreateFAdd(V, II->getArgOperand(2));
Sanjay Patel236442e2018-04-05 13:24:26 +00002285 FAdd->copyFastMathFlags(II);
2286 return FAdd;
Matt Arsenaultb264c942017-01-03 04:32:35 +00002287 }
2288
Matt Arsenault1cc294c2017-01-03 04:32:31 +00002289 break;
2290 }
Sanjay Patelaf0babc2019-12-02 09:21:59 -05002291 case Intrinsic::copysign: {
Sanjay Patel9cdcd812019-12-22 10:05:28 -05002292 if (SignBitMustBeZero(II->getArgOperand(1), &TLI)) {
2293 // If we know that the sign argument is positive, reduce to FABS:
2294 // copysign X, Pos --> fabs X
Sanjay Patelaf0babc2019-12-02 09:21:59 -05002295 Value *Fabs = Builder.CreateUnaryIntrinsic(Intrinsic::fabs,
2296 II->getArgOperand(0), II);
Sanjay Patelaf0babc2019-12-02 09:21:59 -05002297 return replaceInstUsesWith(*II, Fabs);
2298 }
Sanjay Patel9cdcd812019-12-22 10:05:28 -05002299 // TODO: There should be a ValueTracking sibling like SignBitMustBeOne.
2300 const APFloat *C;
2301 if (match(II->getArgOperand(1), m_APFloat(C)) && C->isNegative()) {
2302 // If we know that the sign argument is negative, reduce to FNABS:
2303 // copysign X, Neg --> fneg (fabs X)
2304 Value *Fabs = Builder.CreateUnaryIntrinsic(Intrinsic::fabs,
2305 II->getArgOperand(0), II);
2306 return replaceInstUsesWith(*II, Builder.CreateFNegFMF(Fabs, II));
2307 }
Sanjay Patel987eb8e2019-12-30 11:04:00 -05002308
2309 // Propagate sign argument through nested calls:
2310 // copysign X, (copysign ?, SignArg) --> copysign X, SignArg
2311 Value *SignArg;
2312 if (match(II->getArgOperand(1),
2313 m_Intrinsic<Intrinsic::copysign>(m_Value(), m_Value(SignArg)))) {
2314 II->setArgOperand(1, SignArg);
2315 return II;
2316 }
2317
Sanjay Patelaf0babc2019-12-02 09:21:59 -05002318 break;
2319 }
Matt Arsenault56ff4832017-01-03 22:40:34 +00002320 case Intrinsic::fabs: {
2321 Value *Cond;
2322 Constant *LHS, *RHS;
2323 if (match(II->getArgOperand(0),
2324 m_Select(m_Value(Cond), m_Constant(LHS), m_Constant(RHS)))) {
Craig Topperbb4069e2017-07-07 23:16:26 +00002325 CallInst *Call0 = Builder.CreateCall(II->getCalledFunction(), {LHS});
2326 CallInst *Call1 = Builder.CreateCall(II->getCalledFunction(), {RHS});
Matt Arsenault56ff4832017-01-03 22:40:34 +00002327 return SelectInst::Create(Cond, Call0, Call1);
2328 }
2329
Matt Arsenault954a6242017-01-23 23:55:08 +00002330 LLVM_FALLTHROUGH;
2331 }
2332 case Intrinsic::ceil:
2333 case Intrinsic::floor:
2334 case Intrinsic::round:
2335 case Intrinsic::nearbyint:
Joerg Sonnenberger28bed102017-03-31 19:58:07 +00002336 case Intrinsic::rint:
Matt Arsenault954a6242017-01-23 23:55:08 +00002337 case Intrinsic::trunc: {
Matt Arsenault72333442017-01-17 00:10:40 +00002338 Value *ExtSrc;
Sanjay Patel32381d72018-03-23 21:18:12 +00002339 if (match(II->getArgOperand(0), m_OneUse(m_FPExt(m_Value(ExtSrc))))) {
2340 // Narrow the call: intrinsic (fpext x) -> fpext (intrinsic x)
Sanjay Patel62f457b2019-05-06 15:35:02 +00002341 Value *NarrowII = Builder.CreateUnaryIntrinsic(IID, ExtSrc, II);
Sanjay Patel32381d72018-03-23 21:18:12 +00002342 return new FPExtInst(NarrowII, II->getType());
Matt Arsenault72333442017-01-17 00:10:40 +00002343 }
Matt Arsenault56ff4832017-01-03 22:40:34 +00002344 break;
2345 }
Matt Arsenault3bdd75d2017-01-04 22:49:03 +00002346 case Intrinsic::cos:
2347 case Intrinsic::amdgcn_cos: {
Sanjay Patel0f29e952018-08-29 18:27:49 +00002348 Value *X;
Matt Arsenault3bdd75d2017-01-04 22:49:03 +00002349 Value *Src = II->getArgOperand(0);
Sanjay Patel0f29e952018-08-29 18:27:49 +00002350 if (match(Src, m_FNeg(m_Value(X))) || match(Src, m_FAbs(m_Value(X)))) {
Matt Arsenault3bdd75d2017-01-04 22:49:03 +00002351 // cos(-x) -> cos(x)
2352 // cos(fabs(x)) -> cos(x)
Sanjay Patel0f29e952018-08-29 18:27:49 +00002353 II->setArgOperand(0, X);
Matt Arsenault3bdd75d2017-01-04 22:49:03 +00002354 return II;
2355 }
Sanjay Patel0f29e952018-08-29 18:27:49 +00002356 break;
2357 }
2358 case Intrinsic::sin: {
2359 Value *X;
2360 if (match(II->getArgOperand(0), m_OneUse(m_FNeg(m_Value(X))))) {
2361 // sin(-x) --> -sin(x)
Neil Henning57f5d0a2018-10-08 10:32:33 +00002362 Value *NewSin = Builder.CreateUnaryIntrinsic(Intrinsic::sin, X, II);
Sanjay Patel0f29e952018-08-29 18:27:49 +00002363 Instruction *FNeg = BinaryOperator::CreateFNeg(NewSin);
2364 FNeg->copyFastMathFlags(II);
2365 return FNeg;
2366 }
Matt Arsenault3bdd75d2017-01-04 22:49:03 +00002367 break;
2368 }
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002369 case Intrinsic::ppc_altivec_lvx:
2370 case Intrinsic::ppc_altivec_lvxl:
Bill Wendlingb902f1d2011-04-13 00:36:11 +00002371 // Turn PPC lvx -> load if the pointer is known aligned.
Daniel Jasperaec2fa32016-12-19 08:22:17 +00002372 if (getOrEnforceKnownAlignment(II->getArgOperand(0), 16, DL, II, &AC,
Justin Bogner99798402016-08-05 01:06:44 +00002373 &DT) >= 16) {
Craig Topperbb4069e2017-07-07 23:16:26 +00002374 Value *Ptr = Builder.CreateBitCast(II->getArgOperand(0),
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002375 PointerType::getUnqual(II->getType()));
James Y Knight14359ef2019-02-01 20:44:24 +00002376 return new LoadInst(II->getType(), Ptr);
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002377 }
2378 break;
Bill Schmidt72954782014-11-12 04:19:40 +00002379 case Intrinsic::ppc_vsx_lxvw4x:
2380 case Intrinsic::ppc_vsx_lxvd2x: {
2381 // Turn PPC VSX loads into normal loads.
Craig Topperbb4069e2017-07-07 23:16:26 +00002382 Value *Ptr = Builder.CreateBitCast(II->getArgOperand(0),
2383 PointerType::getUnqual(II->getType()));
Guillaume Chatelet734c74b2019-10-22 12:35:55 +00002384 return new LoadInst(II->getType(), Ptr, Twine(""), false, Align::None());
Bill Schmidt72954782014-11-12 04:19:40 +00002385 }
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002386 case Intrinsic::ppc_altivec_stvx:
2387 case Intrinsic::ppc_altivec_stvxl:
2388 // Turn stvx -> store if the pointer is known aligned.
Daniel Jasperaec2fa32016-12-19 08:22:17 +00002389 if (getOrEnforceKnownAlignment(II->getArgOperand(1), 16, DL, II, &AC,
Justin Bogner99798402016-08-05 01:06:44 +00002390 &DT) >= 16) {
Jim Grosbach7815f562012-02-03 00:07:04 +00002391 Type *OpPtrTy =
Gabor Greifa6d75e22010-06-24 15:51:11 +00002392 PointerType::getUnqual(II->getArgOperand(0)->getType());
Craig Topperbb4069e2017-07-07 23:16:26 +00002393 Value *Ptr = Builder.CreateBitCast(II->getArgOperand(1), OpPtrTy);
Gabor Greifa6d75e22010-06-24 15:51:11 +00002394 return new StoreInst(II->getArgOperand(0), Ptr);
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002395 }
2396 break;
Bill Schmidt72954782014-11-12 04:19:40 +00002397 case Intrinsic::ppc_vsx_stxvw4x:
2398 case Intrinsic::ppc_vsx_stxvd2x: {
2399 // Turn PPC VSX stores into normal stores.
2400 Type *OpPtrTy = PointerType::getUnqual(II->getArgOperand(0)->getType());
Craig Topperbb4069e2017-07-07 23:16:26 +00002401 Value *Ptr = Builder.CreateBitCast(II->getArgOperand(1), OpPtrTy);
Guillaume Chatelet5b99c182019-10-22 12:55:32 +00002402 return new StoreInst(II->getArgOperand(0), Ptr, false, Align::None());
Bill Schmidt72954782014-11-12 04:19:40 +00002403 }
Hal Finkel221f4672015-02-26 18:56:03 +00002404 case Intrinsic::ppc_qpx_qvlfs:
2405 // Turn PPC QPX qvlfs -> load if the pointer is known aligned.
Daniel Jasperaec2fa32016-12-19 08:22:17 +00002406 if (getOrEnforceKnownAlignment(II->getArgOperand(0), 16, DL, II, &AC,
Justin Bogner99798402016-08-05 01:06:44 +00002407 &DT) >= 16) {
Craig Topperbb4069e2017-07-07 23:16:26 +00002408 Type *VTy = VectorType::get(Builder.getFloatTy(),
Hal Finkelf0d68d72015-05-11 06:37:03 +00002409 II->getType()->getVectorNumElements());
Craig Topperbb4069e2017-07-07 23:16:26 +00002410 Value *Ptr = Builder.CreateBitCast(II->getArgOperand(0),
Hal Finkelf0d68d72015-05-11 06:37:03 +00002411 PointerType::getUnqual(VTy));
James Y Knight14359ef2019-02-01 20:44:24 +00002412 Value *Load = Builder.CreateLoad(VTy, Ptr);
Hal Finkelf0d68d72015-05-11 06:37:03 +00002413 return new FPExtInst(Load, II->getType());
Hal Finkel221f4672015-02-26 18:56:03 +00002414 }
2415 break;
2416 case Intrinsic::ppc_qpx_qvlfd:
2417 // Turn PPC QPX qvlfd -> load if the pointer is known aligned.
Daniel Jasperaec2fa32016-12-19 08:22:17 +00002418 if (getOrEnforceKnownAlignment(II->getArgOperand(0), 32, DL, II, &AC,
Justin Bogner99798402016-08-05 01:06:44 +00002419 &DT) >= 32) {
Craig Topperbb4069e2017-07-07 23:16:26 +00002420 Value *Ptr = Builder.CreateBitCast(II->getArgOperand(0),
Hal Finkel221f4672015-02-26 18:56:03 +00002421 PointerType::getUnqual(II->getType()));
James Y Knight14359ef2019-02-01 20:44:24 +00002422 return new LoadInst(II->getType(), Ptr);
Hal Finkel221f4672015-02-26 18:56:03 +00002423 }
2424 break;
2425 case Intrinsic::ppc_qpx_qvstfs:
2426 // Turn PPC QPX qvstfs -> store if the pointer is known aligned.
Daniel Jasperaec2fa32016-12-19 08:22:17 +00002427 if (getOrEnforceKnownAlignment(II->getArgOperand(1), 16, DL, II, &AC,
Justin Bogner99798402016-08-05 01:06:44 +00002428 &DT) >= 16) {
Craig Topperbb4069e2017-07-07 23:16:26 +00002429 Type *VTy = VectorType::get(Builder.getFloatTy(),
Hal Finkelf0d68d72015-05-11 06:37:03 +00002430 II->getArgOperand(0)->getType()->getVectorNumElements());
Craig Topperbb4069e2017-07-07 23:16:26 +00002431 Value *TOp = Builder.CreateFPTrunc(II->getArgOperand(0), VTy);
Hal Finkelf0d68d72015-05-11 06:37:03 +00002432 Type *OpPtrTy = PointerType::getUnqual(VTy);
Craig Topperbb4069e2017-07-07 23:16:26 +00002433 Value *Ptr = Builder.CreateBitCast(II->getArgOperand(1), OpPtrTy);
Hal Finkelf0d68d72015-05-11 06:37:03 +00002434 return new StoreInst(TOp, Ptr);
Hal Finkel221f4672015-02-26 18:56:03 +00002435 }
2436 break;
2437 case Intrinsic::ppc_qpx_qvstfd:
2438 // Turn PPC QPX qvstfd -> store if the pointer is known aligned.
Daniel Jasperaec2fa32016-12-19 08:22:17 +00002439 if (getOrEnforceKnownAlignment(II->getArgOperand(1), 32, DL, II, &AC,
Justin Bogner99798402016-08-05 01:06:44 +00002440 &DT) >= 32) {
Hal Finkel221f4672015-02-26 18:56:03 +00002441 Type *OpPtrTy =
2442 PointerType::getUnqual(II->getArgOperand(0)->getType());
Craig Topperbb4069e2017-07-07 23:16:26 +00002443 Value *Ptr = Builder.CreateBitCast(II->getArgOperand(1), OpPtrTy);
Hal Finkel221f4672015-02-26 18:56:03 +00002444 return new StoreInst(II->getArgOperand(0), Ptr);
2445 }
2446 break;
Simon Pilgrim20c607b2015-09-12 13:39:53 +00002447
Craig Topper83240032017-07-31 18:52:13 +00002448 case Intrinsic::x86_bmi_bextr_32:
2449 case Intrinsic::x86_bmi_bextr_64:
2450 case Intrinsic::x86_tbm_bextri_u32:
2451 case Intrinsic::x86_tbm_bextri_u64:
2452 // If the RHS is a constant we can try some simplifications.
2453 if (auto *C = dyn_cast<ConstantInt>(II->getArgOperand(1))) {
2454 uint64_t Shift = C->getZExtValue();
2455 uint64_t Length = (Shift >> 8) & 0xff;
2456 Shift &= 0xff;
2457 unsigned BitWidth = II->getType()->getIntegerBitWidth();
2458 // If the length is 0 or the shift is out of range, replace with zero.
2459 if (Length == 0 || Shift >= BitWidth)
2460 return replaceInstUsesWith(CI, ConstantInt::get(II->getType(), 0));
2461 // If the LHS is also a constant, we can completely constant fold this.
2462 if (auto *InC = dyn_cast<ConstantInt>(II->getArgOperand(0))) {
2463 uint64_t Result = InC->getZExtValue() >> Shift;
2464 if (Length > BitWidth)
2465 Length = BitWidth;
2466 Result &= maskTrailingOnes<uint64_t>(Length);
2467 return replaceInstUsesWith(CI, ConstantInt::get(II->getType(), Result));
2468 }
2469 // TODO should we turn this into 'and' if shift is 0? Or 'shl' if we
2470 // are only masking bits that a shift already cleared?
2471 }
2472 break;
2473
Craig Topper317a51e2017-07-31 18:52:15 +00002474 case Intrinsic::x86_bmi_bzhi_32:
2475 case Intrinsic::x86_bmi_bzhi_64:
2476 // If the RHS is a constant we can try some simplifications.
2477 if (auto *C = dyn_cast<ConstantInt>(II->getArgOperand(1))) {
2478 uint64_t Index = C->getZExtValue() & 0xff;
2479 unsigned BitWidth = II->getType()->getIntegerBitWidth();
2480 if (Index >= BitWidth)
2481 return replaceInstUsesWith(CI, II->getArgOperand(0));
2482 if (Index == 0)
2483 return replaceInstUsesWith(CI, ConstantInt::get(II->getType(), 0));
2484 // If the LHS is also a constant, we can completely constant fold this.
2485 if (auto *InC = dyn_cast<ConstantInt>(II->getArgOperand(0))) {
2486 uint64_t Result = InC->getZExtValue();
2487 Result &= maskTrailingOnes<uint64_t>(Index);
2488 return replaceInstUsesWith(CI, ConstantInt::get(II->getType(), Result));
2489 }
2490 // TODO should we convert this to an AND if the RHS is constant?
2491 }
2492 break;
Craig Topper374e0292019-12-31 15:06:47 -08002493 case Intrinsic::x86_bmi_pext_32:
2494 case Intrinsic::x86_bmi_pext_64:
2495 if (auto *MaskC = dyn_cast<ConstantInt>(II->getArgOperand(1))) {
2496 if (MaskC->isNullValue())
2497 return replaceInstUsesWith(CI, ConstantInt::get(II->getType(), 0));
2498 if (MaskC->isAllOnesValue())
2499 return replaceInstUsesWith(CI, II->getArgOperand(0));
2500
2501 if (auto *SrcC = dyn_cast<ConstantInt>(II->getArgOperand(0))) {
2502 uint64_t Src = SrcC->getZExtValue();
2503 uint64_t Mask = MaskC->getZExtValue();
2504 uint64_t Result = 0;
2505 uint64_t BitToSet = 1;
2506
2507 while (Mask) {
2508 // Isolate lowest set bit.
2509 uint64_t BitToTest = Mask & -Mask;
2510 if (BitToTest & Src)
2511 Result |= BitToSet;
2512
2513 BitToSet <<= 1;
2514 // Clear lowest set bit.
2515 Mask &= Mask - 1;
2516 }
2517
2518 return replaceInstUsesWith(CI, ConstantInt::get(II->getType(), Result));
2519 }
2520 }
2521 break;
2522 case Intrinsic::x86_bmi_pdep_32:
2523 case Intrinsic::x86_bmi_pdep_64:
2524 if (auto *MaskC = dyn_cast<ConstantInt>(II->getArgOperand(1))) {
2525 if (MaskC->isNullValue())
2526 return replaceInstUsesWith(CI, ConstantInt::get(II->getType(), 0));
2527 if (MaskC->isAllOnesValue())
2528 return replaceInstUsesWith(CI, II->getArgOperand(0));
2529
2530 if (auto *SrcC = dyn_cast<ConstantInt>(II->getArgOperand(0))) {
2531 uint64_t Src = SrcC->getZExtValue();
2532 uint64_t Mask = MaskC->getZExtValue();
2533 uint64_t Result = 0;
2534 uint64_t BitToTest = 1;
2535
2536 while (Mask) {
2537 // Isolate lowest set bit.
2538 uint64_t BitToSet = Mask & -Mask;
2539 if (BitToTest & Src)
2540 Result |= BitToSet;
2541
2542 BitToTest <<= 1;
2543 // Clear lowest set bit;
2544 Mask &= Mask - 1;
2545 }
2546
2547 return replaceInstUsesWith(CI, ConstantInt::get(II->getType(), Result));
2548 }
2549 }
2550 break;
Craig Topper317a51e2017-07-31 18:52:15 +00002551
Simon Pilgrim20c607b2015-09-12 13:39:53 +00002552 case Intrinsic::x86_vcvtph2ps_128:
2553 case Intrinsic::x86_vcvtph2ps_256: {
2554 auto Arg = II->getArgOperand(0);
2555 auto ArgType = cast<VectorType>(Arg->getType());
2556 auto RetType = cast<VectorType>(II->getType());
2557 unsigned ArgWidth = ArgType->getNumElements();
2558 unsigned RetWidth = RetType->getNumElements();
2559 assert(RetWidth <= ArgWidth && "Unexpected input/return vector widths");
2560 assert(ArgType->isIntOrIntVectorTy() &&
2561 ArgType->getScalarSizeInBits() == 16 &&
2562 "CVTPH2PS input type should be 16-bit integer vector");
2563 assert(RetType->getScalarType()->isFloatTy() &&
2564 "CVTPH2PS output type should be 32-bit float vector");
2565
2566 // Constant folding: Convert to generic half to single conversion.
Simon Pilgrim48ffca02015-09-12 14:00:17 +00002567 if (isa<ConstantAggregateZero>(Arg))
Sanjay Patel4b198802016-02-01 22:23:39 +00002568 return replaceInstUsesWith(*II, ConstantAggregateZero::get(RetType));
Simon Pilgrim20c607b2015-09-12 13:39:53 +00002569
Simon Pilgrim48ffca02015-09-12 14:00:17 +00002570 if (isa<ConstantDataVector>(Arg)) {
Simon Pilgrim20c607b2015-09-12 13:39:53 +00002571 auto VectorHalfAsShorts = Arg;
2572 if (RetWidth < ArgWidth) {
Craig Topper99d1eab2016-06-12 00:41:19 +00002573 SmallVector<uint32_t, 8> SubVecMask;
Simon Pilgrim20c607b2015-09-12 13:39:53 +00002574 for (unsigned i = 0; i != RetWidth; ++i)
2575 SubVecMask.push_back((int)i);
Craig Topperbb4069e2017-07-07 23:16:26 +00002576 VectorHalfAsShorts = Builder.CreateShuffleVector(
Simon Pilgrim20c607b2015-09-12 13:39:53 +00002577 Arg, UndefValue::get(ArgType), SubVecMask);
2578 }
2579
2580 auto VectorHalfType =
2581 VectorType::get(Type::getHalfTy(II->getContext()), RetWidth);
2582 auto VectorHalfs =
Craig Topperbb4069e2017-07-07 23:16:26 +00002583 Builder.CreateBitCast(VectorHalfAsShorts, VectorHalfType);
2584 auto VectorFloats = Builder.CreateFPExt(VectorHalfs, RetType);
Sanjay Patel4b198802016-02-01 22:23:39 +00002585 return replaceInstUsesWith(*II, VectorFloats);
Simon Pilgrim20c607b2015-09-12 13:39:53 +00002586 }
2587
2588 // We only use the lowest lanes of the argument.
Simon Pilgrim996725e2015-09-19 11:41:53 +00002589 if (Value *V = SimplifyDemandedVectorEltsLow(Arg, ArgWidth, RetWidth)) {
Simon Pilgrim20c607b2015-09-12 13:39:53 +00002590 II->setArgOperand(0, V);
2591 return II;
2592 }
2593 break;
2594 }
2595
Chandler Carruthcf414cf2011-01-10 07:19:37 +00002596 case Intrinsic::x86_sse_cvtss2si:
2597 case Intrinsic::x86_sse_cvtss2si64:
2598 case Intrinsic::x86_sse_cvttss2si:
2599 case Intrinsic::x86_sse_cvttss2si64:
2600 case Intrinsic::x86_sse2_cvtsd2si:
2601 case Intrinsic::x86_sse2_cvtsd2si64:
2602 case Intrinsic::x86_sse2_cvttsd2si:
Craig Topperaeaa52c2016-12-14 07:46:12 +00002603 case Intrinsic::x86_sse2_cvttsd2si64:
2604 case Intrinsic::x86_avx512_vcvtss2si32:
2605 case Intrinsic::x86_avx512_vcvtss2si64:
2606 case Intrinsic::x86_avx512_vcvtss2usi32:
2607 case Intrinsic::x86_avx512_vcvtss2usi64:
2608 case Intrinsic::x86_avx512_vcvtsd2si32:
2609 case Intrinsic::x86_avx512_vcvtsd2si64:
2610 case Intrinsic::x86_avx512_vcvtsd2usi32:
2611 case Intrinsic::x86_avx512_vcvtsd2usi64:
2612 case Intrinsic::x86_avx512_cvttss2si:
2613 case Intrinsic::x86_avx512_cvttss2si64:
2614 case Intrinsic::x86_avx512_cvttss2usi:
2615 case Intrinsic::x86_avx512_cvttss2usi64:
2616 case Intrinsic::x86_avx512_cvttsd2si:
2617 case Intrinsic::x86_avx512_cvttsd2si64:
2618 case Intrinsic::x86_avx512_cvttsd2usi:
2619 case Intrinsic::x86_avx512_cvttsd2usi64: {
Chandler Carruthcf414cf2011-01-10 07:19:37 +00002620 // These intrinsics only demand the 0th element of their input vectors. If
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002621 // we can simplify the input based on that, do so now.
Simon Pilgrim996725e2015-09-19 11:41:53 +00002622 Value *Arg = II->getArgOperand(0);
2623 unsigned VWidth = Arg->getType()->getVectorNumElements();
2624 if (Value *V = SimplifyDemandedVectorEltsLow(Arg, VWidth, 1)) {
Gabor Greif5b1370e2010-06-28 16:50:57 +00002625 II->setArgOperand(0, V);
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002626 return II;
2627 }
Simon Pilgrim18617d12015-08-05 08:18:00 +00002628 break;
2629 }
2630
Simon Pilgrim91e3ac82016-06-07 08:18:35 +00002631 case Intrinsic::x86_mmx_pmovmskb:
2632 case Intrinsic::x86_sse_movmsk_ps:
2633 case Intrinsic::x86_sse2_movmsk_pd:
2634 case Intrinsic::x86_sse2_pmovmskb_128:
2635 case Intrinsic::x86_avx_movmsk_pd_256:
2636 case Intrinsic::x86_avx_movmsk_ps_256:
Eugene Zelenko7f0f9bc2017-10-24 21:24:53 +00002637 case Intrinsic::x86_avx2_pmovmskb:
Sanjay Patel2aa2dc72018-12-11 16:38:03 +00002638 if (Value *V = simplifyX86movmsk(*II, Builder))
Simon Pilgrim91e3ac82016-06-07 08:18:35 +00002639 return replaceInstUsesWith(*II, V);
2640 break;
Simon Pilgrim91e3ac82016-06-07 08:18:35 +00002641
Simon Pilgrim471efd22016-02-20 23:17:35 +00002642 case Intrinsic::x86_sse_comieq_ss:
2643 case Intrinsic::x86_sse_comige_ss:
2644 case Intrinsic::x86_sse_comigt_ss:
2645 case Intrinsic::x86_sse_comile_ss:
2646 case Intrinsic::x86_sse_comilt_ss:
2647 case Intrinsic::x86_sse_comineq_ss:
2648 case Intrinsic::x86_sse_ucomieq_ss:
2649 case Intrinsic::x86_sse_ucomige_ss:
2650 case Intrinsic::x86_sse_ucomigt_ss:
2651 case Intrinsic::x86_sse_ucomile_ss:
2652 case Intrinsic::x86_sse_ucomilt_ss:
2653 case Intrinsic::x86_sse_ucomineq_ss:
2654 case Intrinsic::x86_sse2_comieq_sd:
2655 case Intrinsic::x86_sse2_comige_sd:
2656 case Intrinsic::x86_sse2_comigt_sd:
2657 case Intrinsic::x86_sse2_comile_sd:
2658 case Intrinsic::x86_sse2_comilt_sd:
2659 case Intrinsic::x86_sse2_comineq_sd:
2660 case Intrinsic::x86_sse2_ucomieq_sd:
2661 case Intrinsic::x86_sse2_ucomige_sd:
2662 case Intrinsic::x86_sse2_ucomigt_sd:
2663 case Intrinsic::x86_sse2_ucomile_sd:
2664 case Intrinsic::x86_sse2_ucomilt_sd:
Craig Topperd9639532016-12-11 07:42:04 +00002665 case Intrinsic::x86_sse2_ucomineq_sd:
Craig Topperd00db692016-12-31 00:45:06 +00002666 case Intrinsic::x86_avx512_vcomi_ss:
2667 case Intrinsic::x86_avx512_vcomi_sd:
Craig Topperd9639532016-12-11 07:42:04 +00002668 case Intrinsic::x86_avx512_mask_cmp_ss:
2669 case Intrinsic::x86_avx512_mask_cmp_sd: {
Simon Pilgrim471efd22016-02-20 23:17:35 +00002670 // These intrinsics only demand the 0th element of their input vectors. If
2671 // we can simplify the input based on that, do so now.
Simon Pilgrim1c9a9f22016-04-24 17:57:27 +00002672 bool MadeChange = false;
Simon Pilgrim471efd22016-02-20 23:17:35 +00002673 Value *Arg0 = II->getArgOperand(0);
2674 Value *Arg1 = II->getArgOperand(1);
2675 unsigned VWidth = Arg0->getType()->getVectorNumElements();
2676 if (Value *V = SimplifyDemandedVectorEltsLow(Arg0, VWidth, 1)) {
2677 II->setArgOperand(0, V);
Simon Pilgrim1c9a9f22016-04-24 17:57:27 +00002678 MadeChange = true;
Simon Pilgrim471efd22016-02-20 23:17:35 +00002679 }
2680 if (Value *V = SimplifyDemandedVectorEltsLow(Arg1, VWidth, 1)) {
2681 II->setArgOperand(1, V);
Simon Pilgrim1c9a9f22016-04-24 17:57:27 +00002682 MadeChange = true;
Simon Pilgrim471efd22016-02-20 23:17:35 +00002683 }
Simon Pilgrim1c9a9f22016-04-24 17:57:27 +00002684 if (MadeChange)
2685 return II;
Simon Pilgrim471efd22016-02-20 23:17:35 +00002686 break;
2687 }
Craig Topper31cbe752018-06-27 15:57:53 +00002688 case Intrinsic::x86_avx512_cmp_pd_128:
2689 case Intrinsic::x86_avx512_cmp_pd_256:
2690 case Intrinsic::x86_avx512_cmp_pd_512:
2691 case Intrinsic::x86_avx512_cmp_ps_128:
2692 case Intrinsic::x86_avx512_cmp_ps_256:
2693 case Intrinsic::x86_avx512_cmp_ps_512: {
Michael Zuckerman16b20d22017-04-16 13:26:08 +00002694 // Folding cmp(sub(a,b),0) -> cmp(a,b) and cmp(0,sub(a,b)) -> cmp(b,a)
2695 Value *Arg0 = II->getArgOperand(0);
2696 Value *Arg1 = II->getArgOperand(1);
Sanjay Patel93e64dd2018-03-25 21:16:33 +00002697 bool Arg0IsZero = match(Arg0, m_PosZeroFP());
Michael Zuckerman16b20d22017-04-16 13:26:08 +00002698 if (Arg0IsZero)
2699 std::swap(Arg0, Arg1);
2700 Value *A, *B;
2701 // This fold requires only the NINF(not +/- inf) since inf minus
2702 // inf is nan.
2703 // NSZ(No Signed Zeros) is not needed because zeros of any sign are
2704 // equal for both compares.
2705 // NNAN is not needed because nans compare the same for both compares.
2706 // The compare intrinsic uses the above assumptions and therefore
2707 // doesn't require additional flags.
2708 if ((match(Arg0, m_OneUse(m_FSub(m_Value(A), m_Value(B)))) &&
Sanjay Patel93e64dd2018-03-25 21:16:33 +00002709 match(Arg1, m_PosZeroFP()) && isa<Instruction>(Arg0) &&
Michael Zuckerman16b20d22017-04-16 13:26:08 +00002710 cast<Instruction>(Arg0)->getFastMathFlags().noInfs())) {
2711 if (Arg0IsZero)
2712 std::swap(A, B);
2713 II->setArgOperand(0, A);
2714 II->setArgOperand(1, B);
2715 return II;
2716 }
2717 break;
2718 }
Simon Pilgrim471efd22016-02-20 23:17:35 +00002719
Craig Topper98a79932018-06-10 06:01:36 +00002720 case Intrinsic::x86_avx512_add_ps_512:
2721 case Intrinsic::x86_avx512_div_ps_512:
2722 case Intrinsic::x86_avx512_mul_ps_512:
2723 case Intrinsic::x86_avx512_sub_ps_512:
2724 case Intrinsic::x86_avx512_add_pd_512:
2725 case Intrinsic::x86_avx512_div_pd_512:
2726 case Intrinsic::x86_avx512_mul_pd_512:
2727 case Intrinsic::x86_avx512_sub_pd_512:
Craig Topper020b2282016-12-27 00:23:16 +00002728 // If the rounding mode is CUR_DIRECTION(4) we can turn these into regular
2729 // IR operations.
Craig Topper98a79932018-06-10 06:01:36 +00002730 if (auto *R = dyn_cast<ConstantInt>(II->getArgOperand(2))) {
Craig Topper020b2282016-12-27 00:23:16 +00002731 if (R->getValue() == 4) {
2732 Value *Arg0 = II->getArgOperand(0);
2733 Value *Arg1 = II->getArgOperand(1);
2734
2735 Value *V;
Sanjay Patel62f457b2019-05-06 15:35:02 +00002736 switch (IID) {
Craig Topper020b2282016-12-27 00:23:16 +00002737 default: llvm_unreachable("Case stmts out of sync!");
Craig Topper98a79932018-06-10 06:01:36 +00002738 case Intrinsic::x86_avx512_add_ps_512:
2739 case Intrinsic::x86_avx512_add_pd_512:
Craig Topperbb4069e2017-07-07 23:16:26 +00002740 V = Builder.CreateFAdd(Arg0, Arg1);
Craig Topper020b2282016-12-27 00:23:16 +00002741 break;
Craig Topper98a79932018-06-10 06:01:36 +00002742 case Intrinsic::x86_avx512_sub_ps_512:
2743 case Intrinsic::x86_avx512_sub_pd_512:
Craig Topperbb4069e2017-07-07 23:16:26 +00002744 V = Builder.CreateFSub(Arg0, Arg1);
Craig Topper020b2282016-12-27 00:23:16 +00002745 break;
Craig Topper98a79932018-06-10 06:01:36 +00002746 case Intrinsic::x86_avx512_mul_ps_512:
2747 case Intrinsic::x86_avx512_mul_pd_512:
Craig Topperbb4069e2017-07-07 23:16:26 +00002748 V = Builder.CreateFMul(Arg0, Arg1);
Craig Topper020b2282016-12-27 00:23:16 +00002749 break;
Craig Topper98a79932018-06-10 06:01:36 +00002750 case Intrinsic::x86_avx512_div_ps_512:
2751 case Intrinsic::x86_avx512_div_pd_512:
Craig Topperbb4069e2017-07-07 23:16:26 +00002752 V = Builder.CreateFDiv(Arg0, Arg1);
Craig Topper020b2282016-12-27 00:23:16 +00002753 break;
2754 }
2755
Craig Topper020b2282016-12-27 00:23:16 +00002756 return replaceInstUsesWith(*II, V);
2757 }
2758 }
2759 break;
2760
Craig Topper790d0fa2016-12-11 07:42:01 +00002761 case Intrinsic::x86_avx512_mask_add_ss_round:
2762 case Intrinsic::x86_avx512_mask_div_ss_round:
2763 case Intrinsic::x86_avx512_mask_mul_ss_round:
2764 case Intrinsic::x86_avx512_mask_sub_ss_round:
Craig Topper790d0fa2016-12-11 07:42:01 +00002765 case Intrinsic::x86_avx512_mask_add_sd_round:
2766 case Intrinsic::x86_avx512_mask_div_sd_round:
2767 case Intrinsic::x86_avx512_mask_mul_sd_round:
2768 case Intrinsic::x86_avx512_mask_sub_sd_round:
Craig Topper7b788ada2016-12-26 06:33:19 +00002769 // If the rounding mode is CUR_DIRECTION(4) we can turn these into regular
2770 // IR operations.
2771 if (auto *R = dyn_cast<ConstantInt>(II->getArgOperand(4))) {
2772 if (R->getValue() == 4) {
Craig Topper7f8540b2016-12-27 01:56:30 +00002773 // Extract the element as scalars.
2774 Value *Arg0 = II->getArgOperand(0);
2775 Value *Arg1 = II->getArgOperand(1);
Craig Topperbb4069e2017-07-07 23:16:26 +00002776 Value *LHS = Builder.CreateExtractElement(Arg0, (uint64_t)0);
2777 Value *RHS = Builder.CreateExtractElement(Arg1, (uint64_t)0);
Craig Topper7b788ada2016-12-26 06:33:19 +00002778
Craig Topper7f8540b2016-12-27 01:56:30 +00002779 Value *V;
Sanjay Patel62f457b2019-05-06 15:35:02 +00002780 switch (IID) {
Craig Topper7f8540b2016-12-27 01:56:30 +00002781 default: llvm_unreachable("Case stmts out of sync!");
2782 case Intrinsic::x86_avx512_mask_add_ss_round:
2783 case Intrinsic::x86_avx512_mask_add_sd_round:
Craig Topperbb4069e2017-07-07 23:16:26 +00002784 V = Builder.CreateFAdd(LHS, RHS);
Craig Topper7f8540b2016-12-27 01:56:30 +00002785 break;
2786 case Intrinsic::x86_avx512_mask_sub_ss_round:
2787 case Intrinsic::x86_avx512_mask_sub_sd_round:
Craig Topperbb4069e2017-07-07 23:16:26 +00002788 V = Builder.CreateFSub(LHS, RHS);
Craig Topper7f8540b2016-12-27 01:56:30 +00002789 break;
2790 case Intrinsic::x86_avx512_mask_mul_ss_round:
2791 case Intrinsic::x86_avx512_mask_mul_sd_round:
Craig Topperbb4069e2017-07-07 23:16:26 +00002792 V = Builder.CreateFMul(LHS, RHS);
Craig Topper7f8540b2016-12-27 01:56:30 +00002793 break;
2794 case Intrinsic::x86_avx512_mask_div_ss_round:
2795 case Intrinsic::x86_avx512_mask_div_sd_round:
Craig Topperbb4069e2017-07-07 23:16:26 +00002796 V = Builder.CreateFDiv(LHS, RHS);
Craig Topper7f8540b2016-12-27 01:56:30 +00002797 break;
Craig Topper7b788ada2016-12-26 06:33:19 +00002798 }
Craig Topper7f8540b2016-12-27 01:56:30 +00002799
2800 // Handle the masking aspect of the intrinsic.
Craig Topper7f8540b2016-12-27 01:56:30 +00002801 Value *Mask = II->getArgOperand(3);
Craig Topper99163632016-12-30 23:06:28 +00002802 auto *C = dyn_cast<ConstantInt>(Mask);
2803 // We don't need a select if we know the mask bit is a 1.
2804 if (!C || !C->getValue()[0]) {
2805 // Cast the mask to an i1 vector and then extract the lowest element.
Craig Topperbb4069e2017-07-07 23:16:26 +00002806 auto *MaskTy = VectorType::get(Builder.getInt1Ty(),
Craig Topper7f8540b2016-12-27 01:56:30 +00002807 cast<IntegerType>(Mask->getType())->getBitWidth());
Craig Topperbb4069e2017-07-07 23:16:26 +00002808 Mask = Builder.CreateBitCast(Mask, MaskTy);
2809 Mask = Builder.CreateExtractElement(Mask, (uint64_t)0);
Craig Topper99163632016-12-30 23:06:28 +00002810 // Extract the lowest element from the passthru operand.
Craig Topperbb4069e2017-07-07 23:16:26 +00002811 Value *Passthru = Builder.CreateExtractElement(II->getArgOperand(2),
Craig Topper99163632016-12-30 23:06:28 +00002812 (uint64_t)0);
Craig Topperbb4069e2017-07-07 23:16:26 +00002813 V = Builder.CreateSelect(Mask, V, Passthru);
Craig Topper99163632016-12-30 23:06:28 +00002814 }
Craig Topper7f8540b2016-12-27 01:56:30 +00002815
2816 // Insert the result back into the original argument 0.
Craig Topperbb4069e2017-07-07 23:16:26 +00002817 V = Builder.CreateInsertElement(Arg0, V, (uint64_t)0);
Craig Topper7f8540b2016-12-27 01:56:30 +00002818
2819 return replaceInstUsesWith(*II, V);
Craig Topper7b788ada2016-12-26 06:33:19 +00002820 }
2821 }
Philip Reamesc71e9962019-01-30 19:21:11 +00002822 break;
Craig Topper7b788ada2016-12-26 06:33:19 +00002823
Simon Pilgrima3a72b42015-08-10 20:21:15 +00002824 // Constant fold ashr( <A x Bi>, Ci ).
Simon Pilgrimbecd5e82015-08-13 07:39:03 +00002825 // Constant fold lshr( <A x Bi>, Ci ).
2826 // Constant fold shl( <A x Bi>, Ci ).
Simon Pilgrima3a72b42015-08-10 20:21:15 +00002827 case Intrinsic::x86_sse2_psrai_d:
2828 case Intrinsic::x86_sse2_psrai_w:
Simon Pilgrima3a72b42015-08-10 20:21:15 +00002829 case Intrinsic::x86_avx2_psrai_d:
2830 case Intrinsic::x86_avx2_psrai_w:
Craig Topper8b831cb2016-11-13 01:51:55 +00002831 case Intrinsic::x86_avx512_psrai_q_128:
2832 case Intrinsic::x86_avx512_psrai_q_256:
2833 case Intrinsic::x86_avx512_psrai_d_512:
2834 case Intrinsic::x86_avx512_psrai_q_512:
2835 case Intrinsic::x86_avx512_psrai_w_512:
Simon Pilgrim18617d12015-08-05 08:18:00 +00002836 case Intrinsic::x86_sse2_psrli_d:
2837 case Intrinsic::x86_sse2_psrli_q:
2838 case Intrinsic::x86_sse2_psrli_w:
Simon Pilgrim18617d12015-08-05 08:18:00 +00002839 case Intrinsic::x86_avx2_psrli_d:
2840 case Intrinsic::x86_avx2_psrli_q:
2841 case Intrinsic::x86_avx2_psrli_w:
Craig Topper8b831cb2016-11-13 01:51:55 +00002842 case Intrinsic::x86_avx512_psrli_d_512:
2843 case Intrinsic::x86_avx512_psrli_q_512:
2844 case Intrinsic::x86_avx512_psrli_w_512:
Michael J. Spencerdee4b2c2014-04-24 00:58:18 +00002845 case Intrinsic::x86_sse2_pslli_d:
2846 case Intrinsic::x86_sse2_pslli_q:
2847 case Intrinsic::x86_sse2_pslli_w:
Simon Pilgrim18617d12015-08-05 08:18:00 +00002848 case Intrinsic::x86_avx2_pslli_d:
2849 case Intrinsic::x86_avx2_pslli_q:
2850 case Intrinsic::x86_avx2_pslli_w:
Craig Topper8b831cb2016-11-13 01:51:55 +00002851 case Intrinsic::x86_avx512_pslli_d_512:
2852 case Intrinsic::x86_avx512_pslli_q_512:
2853 case Intrinsic::x86_avx512_pslli_w_512:
Craig Topperbb4069e2017-07-07 23:16:26 +00002854 if (Value *V = simplifyX86immShift(*II, Builder))
Sanjay Patel4b198802016-02-01 22:23:39 +00002855 return replaceInstUsesWith(*II, V);
Simon Pilgrim18617d12015-08-05 08:18:00 +00002856 break;
2857
Simon Pilgrimbecd5e82015-08-13 07:39:03 +00002858 case Intrinsic::x86_sse2_psra_d:
2859 case Intrinsic::x86_sse2_psra_w:
2860 case Intrinsic::x86_avx2_psra_d:
2861 case Intrinsic::x86_avx2_psra_w:
Craig Topper8b831cb2016-11-13 01:51:55 +00002862 case Intrinsic::x86_avx512_psra_q_128:
2863 case Intrinsic::x86_avx512_psra_q_256:
2864 case Intrinsic::x86_avx512_psra_d_512:
2865 case Intrinsic::x86_avx512_psra_q_512:
2866 case Intrinsic::x86_avx512_psra_w_512:
Simon Pilgrimbecd5e82015-08-13 07:39:03 +00002867 case Intrinsic::x86_sse2_psrl_d:
2868 case Intrinsic::x86_sse2_psrl_q:
2869 case Intrinsic::x86_sse2_psrl_w:
2870 case Intrinsic::x86_avx2_psrl_d:
2871 case Intrinsic::x86_avx2_psrl_q:
2872 case Intrinsic::x86_avx2_psrl_w:
Craig Topper8b831cb2016-11-13 01:51:55 +00002873 case Intrinsic::x86_avx512_psrl_d_512:
2874 case Intrinsic::x86_avx512_psrl_q_512:
2875 case Intrinsic::x86_avx512_psrl_w_512:
Simon Pilgrimbecd5e82015-08-13 07:39:03 +00002876 case Intrinsic::x86_sse2_psll_d:
2877 case Intrinsic::x86_sse2_psll_q:
2878 case Intrinsic::x86_sse2_psll_w:
2879 case Intrinsic::x86_avx2_psll_d:
2880 case Intrinsic::x86_avx2_psll_q:
Craig Topper8b831cb2016-11-13 01:51:55 +00002881 case Intrinsic::x86_avx2_psll_w:
2882 case Intrinsic::x86_avx512_psll_d_512:
2883 case Intrinsic::x86_avx512_psll_q_512:
2884 case Intrinsic::x86_avx512_psll_w_512: {
Craig Topperbb4069e2017-07-07 23:16:26 +00002885 if (Value *V = simplifyX86immShift(*II, Builder))
Sanjay Patel4b198802016-02-01 22:23:39 +00002886 return replaceInstUsesWith(*II, V);
Simon Pilgrimbecd5e82015-08-13 07:39:03 +00002887
2888 // SSE2/AVX2 uses only the first 64-bits of the 128-bit vector
2889 // operand to compute the shift amount.
Simon Pilgrim996725e2015-09-19 11:41:53 +00002890 Value *Arg1 = II->getArgOperand(1);
2891 assert(Arg1->getType()->getPrimitiveSizeInBits() == 128 &&
Simon Pilgrimbecd5e82015-08-13 07:39:03 +00002892 "Unexpected packed shift size");
Simon Pilgrim996725e2015-09-19 11:41:53 +00002893 unsigned VWidth = Arg1->getType()->getVectorNumElements();
Simon Pilgrimbecd5e82015-08-13 07:39:03 +00002894
Simon Pilgrim996725e2015-09-19 11:41:53 +00002895 if (Value *V = SimplifyDemandedVectorEltsLow(Arg1, VWidth, VWidth / 2)) {
Simon Pilgrimbecd5e82015-08-13 07:39:03 +00002896 II->setArgOperand(1, V);
2897 return II;
2898 }
2899 break;
2900 }
2901
Simon Pilgrimdb9893f2016-06-07 10:27:15 +00002902 case Intrinsic::x86_avx2_psllv_d:
2903 case Intrinsic::x86_avx2_psllv_d_256:
2904 case Intrinsic::x86_avx2_psllv_q:
2905 case Intrinsic::x86_avx2_psllv_q_256:
Craig Topperb4173a52016-11-13 07:26:19 +00002906 case Intrinsic::x86_avx512_psllv_d_512:
2907 case Intrinsic::x86_avx512_psllv_q_512:
Craig Topper1de753f2016-11-18 06:04:33 +00002908 case Intrinsic::x86_avx512_psllv_w_128:
2909 case Intrinsic::x86_avx512_psllv_w_256:
2910 case Intrinsic::x86_avx512_psllv_w_512:
Simon Pilgrimdb9893f2016-06-07 10:27:15 +00002911 case Intrinsic::x86_avx2_psrav_d:
2912 case Intrinsic::x86_avx2_psrav_d_256:
Craig Topperb4173a52016-11-13 07:26:19 +00002913 case Intrinsic::x86_avx512_psrav_q_128:
2914 case Intrinsic::x86_avx512_psrav_q_256:
2915 case Intrinsic::x86_avx512_psrav_d_512:
2916 case Intrinsic::x86_avx512_psrav_q_512:
Craig Topper1de753f2016-11-18 06:04:33 +00002917 case Intrinsic::x86_avx512_psrav_w_128:
2918 case Intrinsic::x86_avx512_psrav_w_256:
2919 case Intrinsic::x86_avx512_psrav_w_512:
Simon Pilgrimdb9893f2016-06-07 10:27:15 +00002920 case Intrinsic::x86_avx2_psrlv_d:
2921 case Intrinsic::x86_avx2_psrlv_d_256:
2922 case Intrinsic::x86_avx2_psrlv_q:
2923 case Intrinsic::x86_avx2_psrlv_q_256:
Craig Topperb4173a52016-11-13 07:26:19 +00002924 case Intrinsic::x86_avx512_psrlv_d_512:
2925 case Intrinsic::x86_avx512_psrlv_q_512:
Craig Topper1de753f2016-11-18 06:04:33 +00002926 case Intrinsic::x86_avx512_psrlv_w_128:
2927 case Intrinsic::x86_avx512_psrlv_w_256:
2928 case Intrinsic::x86_avx512_psrlv_w_512:
Craig Topperbb4069e2017-07-07 23:16:26 +00002929 if (Value *V = simplifyX86varShift(*II, Builder))
Simon Pilgrimdb9893f2016-06-07 10:27:15 +00002930 return replaceInstUsesWith(*II, V);
2931 break;
2932
Simon Pilgrim6f6b2792017-01-25 14:37:24 +00002933 case Intrinsic::x86_sse2_packssdw_128:
2934 case Intrinsic::x86_sse2_packsswb_128:
2935 case Intrinsic::x86_avx2_packssdw:
2936 case Intrinsic::x86_avx2_packsswb:
Craig Topper3731f4d2017-02-16 07:35:23 +00002937 case Intrinsic::x86_avx512_packssdw_512:
2938 case Intrinsic::x86_avx512_packsswb_512:
Simon Pilgrim55f14da2019-04-24 16:53:17 +00002939 if (Value *V = simplifyX86pack(*II, Builder, true))
Simon Pilgrim6f6b2792017-01-25 14:37:24 +00002940 return replaceInstUsesWith(*II, V);
2941 break;
2942
2943 case Intrinsic::x86_sse2_packuswb_128:
2944 case Intrinsic::x86_sse41_packusdw:
2945 case Intrinsic::x86_avx2_packusdw:
2946 case Intrinsic::x86_avx2_packuswb:
Craig Topper3731f4d2017-02-16 07:35:23 +00002947 case Intrinsic::x86_avx512_packusdw_512:
2948 case Intrinsic::x86_avx512_packuswb_512:
Simon Pilgrim55f14da2019-04-24 16:53:17 +00002949 if (Value *V = simplifyX86pack(*II, Builder, false))
Simon Pilgrim6f6b2792017-01-25 14:37:24 +00002950 return replaceInstUsesWith(*II, V);
2951 break;
2952
Craig Topper911025b2018-05-13 21:56:32 +00002953 case Intrinsic::x86_pclmulqdq:
2954 case Intrinsic::x86_pclmulqdq_256:
2955 case Intrinsic::x86_pclmulqdq_512: {
Craig Topperb6122122017-01-26 05:17:13 +00002956 if (auto *C = dyn_cast<ConstantInt>(II->getArgOperand(2))) {
2957 unsigned Imm = C->getZExtValue();
2958
2959 bool MadeChange = false;
2960 Value *Arg0 = II->getArgOperand(0);
2961 Value *Arg1 = II->getArgOperand(1);
2962 unsigned VWidth = Arg0->getType()->getVectorNumElements();
Craig Topperb6122122017-01-26 05:17:13 +00002963
2964 APInt UndefElts1(VWidth, 0);
Craig Topper911025b2018-05-13 21:56:32 +00002965 APInt DemandedElts1 = APInt::getSplat(VWidth,
2966 APInt(2, (Imm & 0x01) ? 2 : 1));
2967 if (Value *V = SimplifyDemandedVectorElts(Arg0, DemandedElts1,
Craig Topperb6122122017-01-26 05:17:13 +00002968 UndefElts1)) {
2969 II->setArgOperand(0, V);
2970 MadeChange = true;
2971 }
2972
2973 APInt UndefElts2(VWidth, 0);
Craig Topper911025b2018-05-13 21:56:32 +00002974 APInt DemandedElts2 = APInt::getSplat(VWidth,
2975 APInt(2, (Imm & 0x10) ? 2 : 1));
2976 if (Value *V = SimplifyDemandedVectorElts(Arg1, DemandedElts2,
Craig Topperb6122122017-01-26 05:17:13 +00002977 UndefElts2)) {
2978 II->setArgOperand(1, V);
2979 MadeChange = true;
2980 }
2981
Craig Topper911025b2018-05-13 21:56:32 +00002982 // If either input elements are undef, the result is zero.
2983 if (DemandedElts1.isSubsetOf(UndefElts1) ||
2984 DemandedElts2.isSubsetOf(UndefElts2))
Craig Topperb6122122017-01-26 05:17:13 +00002985 return replaceInstUsesWith(*II,
2986 ConstantAggregateZero::get(II->getType()));
2987
2988 if (MadeChange)
2989 return II;
2990 }
2991 break;
2992 }
2993
Sanjay Patelc86867c2015-04-16 17:52:13 +00002994 case Intrinsic::x86_sse41_insertps:
Craig Topperbb4069e2017-07-07 23:16:26 +00002995 if (Value *V = simplifyX86insertps(*II, Builder))
Sanjay Patel4b198802016-02-01 22:23:39 +00002996 return replaceInstUsesWith(*II, V);
Sanjay Patelc86867c2015-04-16 17:52:13 +00002997 break;
Simon Pilgrim54fcd622015-07-25 20:41:00 +00002998
Simon Pilgrim61116dd2015-09-17 20:32:45 +00002999 case Intrinsic::x86_sse4a_extrq: {
Simon Pilgrim61116dd2015-09-17 20:32:45 +00003000 Value *Op0 = II->getArgOperand(0);
3001 Value *Op1 = II->getArgOperand(1);
3002 unsigned VWidth0 = Op0->getType()->getVectorNumElements();
3003 unsigned VWidth1 = Op1->getType()->getVectorNumElements();
Simon Pilgrim216b1bf2015-10-17 11:40:05 +00003004 assert(Op0->getType()->getPrimitiveSizeInBits() == 128 &&
3005 Op1->getType()->getPrimitiveSizeInBits() == 128 && VWidth0 == 2 &&
3006 VWidth1 == 16 && "Unexpected operand sizes");
Simon Pilgrim61116dd2015-09-17 20:32:45 +00003007
Simon Pilgrim216b1bf2015-10-17 11:40:05 +00003008 // See if we're dealing with constant values.
3009 Constant *C1 = dyn_cast<Constant>(Op1);
3010 ConstantInt *CILength =
Andrea Di Biagio8df5b9c2016-09-07 12:03:03 +00003011 C1 ? dyn_cast_or_null<ConstantInt>(C1->getAggregateElement((unsigned)0))
Simon Pilgrim216b1bf2015-10-17 11:40:05 +00003012 : nullptr;
3013 ConstantInt *CIIndex =
Andrea Di Biagio8df5b9c2016-09-07 12:03:03 +00003014 C1 ? dyn_cast_or_null<ConstantInt>(C1->getAggregateElement((unsigned)1))
Simon Pilgrim216b1bf2015-10-17 11:40:05 +00003015 : nullptr;
3016
3017 // Attempt to simplify to a constant, shuffle vector or EXTRQI call.
Craig Topperbb4069e2017-07-07 23:16:26 +00003018 if (Value *V = simplifyX86extrq(*II, Op0, CILength, CIIndex, Builder))
Sanjay Patel4b198802016-02-01 22:23:39 +00003019 return replaceInstUsesWith(*II, V);
Simon Pilgrim216b1bf2015-10-17 11:40:05 +00003020
3021 // EXTRQ only uses the lowest 64-bits of the first 128-bit vector
3022 // operands and the lowest 16-bits of the second.
Simon Pilgrim1c9a9f22016-04-24 17:57:27 +00003023 bool MadeChange = false;
Simon Pilgrim61116dd2015-09-17 20:32:45 +00003024 if (Value *V = SimplifyDemandedVectorEltsLow(Op0, VWidth0, 1)) {
3025 II->setArgOperand(0, V);
Simon Pilgrim1c9a9f22016-04-24 17:57:27 +00003026 MadeChange = true;
Simon Pilgrim61116dd2015-09-17 20:32:45 +00003027 }
3028 if (Value *V = SimplifyDemandedVectorEltsLow(Op1, VWidth1, 2)) {
3029 II->setArgOperand(1, V);
Simon Pilgrim1c9a9f22016-04-24 17:57:27 +00003030 MadeChange = true;
Simon Pilgrim61116dd2015-09-17 20:32:45 +00003031 }
Simon Pilgrim1c9a9f22016-04-24 17:57:27 +00003032 if (MadeChange)
3033 return II;
Simon Pilgrim61116dd2015-09-17 20:32:45 +00003034 break;
3035 }
3036
3037 case Intrinsic::x86_sse4a_extrqi: {
Simon Pilgrim216b1bf2015-10-17 11:40:05 +00003038 // EXTRQI: Extract Length bits starting from Index. Zero pad the remaining
3039 // bits of the lower 64-bits. The upper 64-bits are undefined.
3040 Value *Op0 = II->getArgOperand(0);
3041 unsigned VWidth = Op0->getType()->getVectorNumElements();
3042 assert(Op0->getType()->getPrimitiveSizeInBits() == 128 && VWidth == 2 &&
3043 "Unexpected operand size");
Simon Pilgrim61116dd2015-09-17 20:32:45 +00003044
Simon Pilgrim216b1bf2015-10-17 11:40:05 +00003045 // See if we're dealing with constant values.
3046 ConstantInt *CILength = dyn_cast<ConstantInt>(II->getArgOperand(1));
3047 ConstantInt *CIIndex = dyn_cast<ConstantInt>(II->getArgOperand(2));
3048
3049 // Attempt to simplify to a constant or shuffle vector.
Craig Topperbb4069e2017-07-07 23:16:26 +00003050 if (Value *V = simplifyX86extrq(*II, Op0, CILength, CIIndex, Builder))
Sanjay Patel4b198802016-02-01 22:23:39 +00003051 return replaceInstUsesWith(*II, V);
Simon Pilgrim216b1bf2015-10-17 11:40:05 +00003052
3053 // EXTRQI only uses the lowest 64-bits of the first 128-bit vector
3054 // operand.
3055 if (Value *V = SimplifyDemandedVectorEltsLow(Op0, VWidth, 1)) {
Simon Pilgrim61116dd2015-09-17 20:32:45 +00003056 II->setArgOperand(0, V);
3057 return II;
3058 }
3059 break;
3060 }
3061
3062 case Intrinsic::x86_sse4a_insertq: {
Simon Pilgrim216b1bf2015-10-17 11:40:05 +00003063 Value *Op0 = II->getArgOperand(0);
3064 Value *Op1 = II->getArgOperand(1);
3065 unsigned VWidth = Op0->getType()->getVectorNumElements();
3066 assert(Op0->getType()->getPrimitiveSizeInBits() == 128 &&
3067 Op1->getType()->getPrimitiveSizeInBits() == 128 && VWidth == 2 &&
3068 Op1->getType()->getVectorNumElements() == 2 &&
3069 "Unexpected operand size");
Simon Pilgrim61116dd2015-09-17 20:32:45 +00003070
Simon Pilgrim216b1bf2015-10-17 11:40:05 +00003071 // See if we're dealing with constant values.
3072 Constant *C1 = dyn_cast<Constant>(Op1);
3073 ConstantInt *CI11 =
Andrea Di Biagiof3fd3162016-09-07 12:47:53 +00003074 C1 ? dyn_cast_or_null<ConstantInt>(C1->getAggregateElement((unsigned)1))
Simon Pilgrim216b1bf2015-10-17 11:40:05 +00003075 : nullptr;
3076
3077 // Attempt to simplify to a constant, shuffle vector or INSERTQI call.
3078 if (CI11) {
Benjamin Kramer46e38f32016-06-08 10:01:20 +00003079 const APInt &V11 = CI11->getValue();
Simon Pilgrim216b1bf2015-10-17 11:40:05 +00003080 APInt Len = V11.zextOrTrunc(6);
3081 APInt Idx = V11.lshr(8).zextOrTrunc(6);
Craig Topperbb4069e2017-07-07 23:16:26 +00003082 if (Value *V = simplifyX86insertq(*II, Op0, Op1, Len, Idx, Builder))
Sanjay Patel4b198802016-02-01 22:23:39 +00003083 return replaceInstUsesWith(*II, V);
Simon Pilgrim216b1bf2015-10-17 11:40:05 +00003084 }
3085
3086 // INSERTQ only uses the lowest 64-bits of the first 128-bit vector
3087 // operand.
3088 if (Value *V = SimplifyDemandedVectorEltsLow(Op0, VWidth, 1)) {
Simon Pilgrim61116dd2015-09-17 20:32:45 +00003089 II->setArgOperand(0, V);
3090 return II;
3091 }
3092 break;
3093 }
3094
Filipe Cabecinhas1a805952014-04-24 00:38:14 +00003095 case Intrinsic::x86_sse4a_insertqi: {
Simon Pilgrim216b1bf2015-10-17 11:40:05 +00003096 // INSERTQI: Extract lowest Length bits from lower half of second source and
3097 // insert over first source starting at Index bit. The upper 64-bits are
3098 // undefined.
Simon Pilgrim61116dd2015-09-17 20:32:45 +00003099 Value *Op0 = II->getArgOperand(0);
3100 Value *Op1 = II->getArgOperand(1);
3101 unsigned VWidth0 = Op0->getType()->getVectorNumElements();
3102 unsigned VWidth1 = Op1->getType()->getVectorNumElements();
Simon Pilgrim216b1bf2015-10-17 11:40:05 +00003103 assert(Op0->getType()->getPrimitiveSizeInBits() == 128 &&
3104 Op1->getType()->getPrimitiveSizeInBits() == 128 && VWidth0 == 2 &&
3105 VWidth1 == 2 && "Unexpected operand sizes");
Simon Pilgrim61116dd2015-09-17 20:32:45 +00003106
Simon Pilgrim216b1bf2015-10-17 11:40:05 +00003107 // See if we're dealing with constant values.
3108 ConstantInt *CILength = dyn_cast<ConstantInt>(II->getArgOperand(2));
3109 ConstantInt *CIIndex = dyn_cast<ConstantInt>(II->getArgOperand(3));
3110
3111 // Attempt to simplify to a constant or shuffle vector.
3112 if (CILength && CIIndex) {
3113 APInt Len = CILength->getValue().zextOrTrunc(6);
3114 APInt Idx = CIIndex->getValue().zextOrTrunc(6);
Craig Topperbb4069e2017-07-07 23:16:26 +00003115 if (Value *V = simplifyX86insertq(*II, Op0, Op1, Len, Idx, Builder))
Sanjay Patel4b198802016-02-01 22:23:39 +00003116 return replaceInstUsesWith(*II, V);
Simon Pilgrim216b1bf2015-10-17 11:40:05 +00003117 }
3118
3119 // INSERTQI only uses the lowest 64-bits of the first two 128-bit vector
3120 // operands.
Simon Pilgrim1c9a9f22016-04-24 17:57:27 +00003121 bool MadeChange = false;
Simon Pilgrim61116dd2015-09-17 20:32:45 +00003122 if (Value *V = SimplifyDemandedVectorEltsLow(Op0, VWidth0, 1)) {
3123 II->setArgOperand(0, V);
Simon Pilgrim1c9a9f22016-04-24 17:57:27 +00003124 MadeChange = true;
Simon Pilgrim61116dd2015-09-17 20:32:45 +00003125 }
Simon Pilgrim61116dd2015-09-17 20:32:45 +00003126 if (Value *V = SimplifyDemandedVectorEltsLow(Op1, VWidth1, 1)) {
3127 II->setArgOperand(1, V);
Simon Pilgrim1c9a9f22016-04-24 17:57:27 +00003128 MadeChange = true;
Simon Pilgrim61116dd2015-09-17 20:32:45 +00003129 }
Simon Pilgrim1c9a9f22016-04-24 17:57:27 +00003130 if (MadeChange)
3131 return II;
Filipe Cabecinhas1a805952014-04-24 00:38:14 +00003132 break;
3133 }
3134
Filipe Cabecinhas82ac07c2014-05-27 03:42:20 +00003135 case Intrinsic::x86_sse41_pblendvb:
3136 case Intrinsic::x86_sse41_blendvps:
3137 case Intrinsic::x86_sse41_blendvpd:
3138 case Intrinsic::x86_avx_blendv_ps_256:
3139 case Intrinsic::x86_avx_blendv_pd_256:
3140 case Intrinsic::x86_avx2_pblendvb: {
Sanjay Patel296d35a2018-09-15 14:25:44 +00003141 // fold (blend A, A, Mask) -> A
Simon Pilgrim8c049d52015-08-12 08:08:56 +00003142 Value *Op0 = II->getArgOperand(0);
3143 Value *Op1 = II->getArgOperand(1);
Filipe Cabecinhas82ac07c2014-05-27 03:42:20 +00003144 Value *Mask = II->getArgOperand(2);
Simon Pilgrim8c049d52015-08-12 08:08:56 +00003145 if (Op0 == Op1)
Sanjay Patel4b198802016-02-01 22:23:39 +00003146 return replaceInstUsesWith(CI, Op0);
Simon Pilgrim8c049d52015-08-12 08:08:56 +00003147
3148 // Zero Mask - select 1st argument.
Simon Pilgrim93f59f52015-08-12 08:23:36 +00003149 if (isa<ConstantAggregateZero>(Mask))
Sanjay Patel4b198802016-02-01 22:23:39 +00003150 return replaceInstUsesWith(CI, Op0);
Simon Pilgrim8c049d52015-08-12 08:08:56 +00003151
3152 // Constant Mask - select 1st/2nd argument lane based on top bit of mask.
Sanjay Patel368ac5d2016-02-21 17:29:33 +00003153 if (auto *ConstantMask = dyn_cast<ConstantDataVector>(Mask)) {
3154 Constant *NewSelector = getNegativeIsTrueBoolVec(ConstantMask);
Simon Pilgrim8c049d52015-08-12 08:08:56 +00003155 return SelectInst::Create(NewSelector, Op1, Op0, "blendv");
Filipe Cabecinhas82ac07c2014-05-27 03:42:20 +00003156 }
Sanjay Patel296d35a2018-09-15 14:25:44 +00003157
3158 // Convert to a vector select if we can bypass casts and find a boolean
3159 // vector condition value.
3160 Value *BoolVec;
Sanjay Patel09e02fb2018-09-22 14:43:55 +00003161 Mask = peekThroughBitcast(Mask);
3162 if (match(Mask, m_SExt(m_Value(BoolVec))) &&
3163 BoolVec->getType()->isVectorTy() &&
3164 BoolVec->getType()->getScalarSizeInBits() == 1) {
3165 assert(Mask->getType()->getPrimitiveSizeInBits() ==
3166 II->getType()->getPrimitiveSizeInBits() &&
3167 "Not expecting mask and operands with different sizes");
3168
3169 unsigned NumMaskElts = Mask->getType()->getVectorNumElements();
3170 unsigned NumOperandElts = II->getType()->getVectorNumElements();
3171 if (NumMaskElts == NumOperandElts)
Sanjay Patel296d35a2018-09-15 14:25:44 +00003172 return SelectInst::Create(BoolVec, Op1, Op0);
Sanjay Patel09e02fb2018-09-22 14:43:55 +00003173
3174 // If the mask has less elements than the operands, each mask bit maps to
3175 // multiple elements of the operands. Bitcast back and forth.
3176 if (NumMaskElts < NumOperandElts) {
3177 Value *CastOp0 = Builder.CreateBitCast(Op0, Mask->getType());
3178 Value *CastOp1 = Builder.CreateBitCast(Op1, Mask->getType());
3179 Value *Sel = Builder.CreateSelect(BoolVec, CastOp1, CastOp0);
3180 return new BitCastInst(Sel, II->getType());
3181 }
Sanjay Patel296d35a2018-09-15 14:25:44 +00003182 }
3183
Simon Pilgrim8c049d52015-08-12 08:08:56 +00003184 break;
Filipe Cabecinhas82ac07c2014-05-27 03:42:20 +00003185 }
3186
Andrea Di Biagio0594e2a2015-09-30 16:44:39 +00003187 case Intrinsic::x86_ssse3_pshuf_b_128:
Simon Pilgrimc0c56e72016-04-24 17:00:34 +00003188 case Intrinsic::x86_avx2_pshuf_b:
Simon Pilgrima22c3a12017-01-18 13:44:04 +00003189 case Intrinsic::x86_avx512_pshuf_b_512:
Craig Topperbb4069e2017-07-07 23:16:26 +00003190 if (Value *V = simplifyX86pshufb(*II, Builder))
Simon Pilgrimc0c56e72016-04-24 17:00:34 +00003191 return replaceInstUsesWith(*II, V);
3192 break;
Andrea Di Biagio0594e2a2015-09-30 16:44:39 +00003193
Rafael Espindolabad3f772014-04-21 22:06:04 +00003194 case Intrinsic::x86_avx_vpermilvar_ps:
3195 case Intrinsic::x86_avx_vpermilvar_ps_256:
Craig Topper58917f32016-12-11 01:59:36 +00003196 case Intrinsic::x86_avx512_vpermilvar_ps_512:
Rafael Espindolabad3f772014-04-21 22:06:04 +00003197 case Intrinsic::x86_avx_vpermilvar_pd:
Simon Pilgrim2f6097d2016-04-24 17:23:46 +00003198 case Intrinsic::x86_avx_vpermilvar_pd_256:
Simon Pilgrima22c3a12017-01-18 13:44:04 +00003199 case Intrinsic::x86_avx512_vpermilvar_pd_512:
Craig Topperbb4069e2017-07-07 23:16:26 +00003200 if (Value *V = simplifyX86vpermilvar(*II, Builder))
Simon Pilgrim2f6097d2016-04-24 17:23:46 +00003201 return replaceInstUsesWith(*II, V);
3202 break;
Rafael Espindolabad3f772014-04-21 22:06:04 +00003203
Simon Pilgrim8cddf8b2016-05-01 16:41:22 +00003204 case Intrinsic::x86_avx2_permd:
3205 case Intrinsic::x86_avx2_permps:
Craig Toppere4c045b2018-05-20 23:34:04 +00003206 case Intrinsic::x86_avx512_permvar_df_256:
3207 case Intrinsic::x86_avx512_permvar_df_512:
3208 case Intrinsic::x86_avx512_permvar_di_256:
3209 case Intrinsic::x86_avx512_permvar_di_512:
3210 case Intrinsic::x86_avx512_permvar_hi_128:
3211 case Intrinsic::x86_avx512_permvar_hi_256:
3212 case Intrinsic::x86_avx512_permvar_hi_512:
3213 case Intrinsic::x86_avx512_permvar_qi_128:
3214 case Intrinsic::x86_avx512_permvar_qi_256:
3215 case Intrinsic::x86_avx512_permvar_qi_512:
3216 case Intrinsic::x86_avx512_permvar_sf_512:
3217 case Intrinsic::x86_avx512_permvar_si_512:
Craig Topperbb4069e2017-07-07 23:16:26 +00003218 if (Value *V = simplifyX86vpermv(*II, Builder))
Simon Pilgrim8cddf8b2016-05-01 16:41:22 +00003219 return replaceInstUsesWith(*II, V);
3220 break;
3221
Sanjay Patel98a71502016-02-29 23:16:48 +00003222 case Intrinsic::x86_avx_maskload_ps:
Sanjay Patel6f2c01f2016-02-29 23:59:00 +00003223 case Intrinsic::x86_avx_maskload_pd:
3224 case Intrinsic::x86_avx_maskload_ps_256:
3225 case Intrinsic::x86_avx_maskload_pd_256:
3226 case Intrinsic::x86_avx2_maskload_d:
3227 case Intrinsic::x86_avx2_maskload_q:
3228 case Intrinsic::x86_avx2_maskload_d_256:
3229 case Intrinsic::x86_avx2_maskload_q_256:
Sanjay Patel98a71502016-02-29 23:16:48 +00003230 if (Instruction *I = simplifyX86MaskedLoad(*II, *this))
3231 return I;
3232 break;
3233
Sanjay Patelc4acbae2016-03-12 15:16:59 +00003234 case Intrinsic::x86_sse2_maskmov_dqu:
Sanjay Patel1ace9932016-02-26 21:04:14 +00003235 case Intrinsic::x86_avx_maskstore_ps:
3236 case Intrinsic::x86_avx_maskstore_pd:
3237 case Intrinsic::x86_avx_maskstore_ps_256:
3238 case Intrinsic::x86_avx_maskstore_pd_256:
Sanjay Patelfc7e7eb2016-02-26 21:51:44 +00003239 case Intrinsic::x86_avx2_maskstore_d:
3240 case Intrinsic::x86_avx2_maskstore_q:
3241 case Intrinsic::x86_avx2_maskstore_d_256:
3242 case Intrinsic::x86_avx2_maskstore_q_256:
Sanjay Patel1ace9932016-02-26 21:04:14 +00003243 if (simplifyX86MaskedStore(*II, *this))
3244 return nullptr;
3245 break;
3246
Sanjay Patelbe23a912019-02-01 14:14:47 +00003247 case Intrinsic::x86_addcarry_32:
3248 case Intrinsic::x86_addcarry_64:
3249 if (Value *V = simplifyX86addcarry(*II, Builder))
3250 return replaceInstUsesWith(*II, V);
3251 break;
3252
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003253 case Intrinsic::ppc_altivec_vperm:
3254 // Turn vperm(V1,V2,mask) -> shuffle(V1,V2,mask) if mask is a constant.
Bill Schmidta1184632014-06-05 19:46:04 +00003255 // Note that ppc_altivec_vperm has a big-endian bias, so when creating
3256 // a vectorshuffle for little endian, we must undo the transformation
3257 // performed on vec_perm in altivec.h. That is, we must complement
3258 // the permutation mask with respect to 31 and reverse the order of
3259 // V1 and V2.
Chris Lattner0256be92012-01-27 03:08:05 +00003260 if (Constant *Mask = dyn_cast<Constant>(II->getArgOperand(2))) {
3261 assert(Mask->getType()->getVectorNumElements() == 16 &&
3262 "Bad type for intrinsic!");
Jim Grosbach7815f562012-02-03 00:07:04 +00003263
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003264 // Check that all of the elements are integer constants or undefs.
3265 bool AllEltsOk = true;
3266 for (unsigned i = 0; i != 16; ++i) {
Chris Lattner0256be92012-01-27 03:08:05 +00003267 Constant *Elt = Mask->getAggregateElement(i);
Craig Topperf40110f2014-04-25 05:29:35 +00003268 if (!Elt || !(isa<ConstantInt>(Elt) || isa<UndefValue>(Elt))) {
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003269 AllEltsOk = false;
3270 break;
3271 }
3272 }
Jim Grosbach7815f562012-02-03 00:07:04 +00003273
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003274 if (AllEltsOk) {
3275 // Cast the input vectors to byte vectors.
Craig Topperbb4069e2017-07-07 23:16:26 +00003276 Value *Op0 = Builder.CreateBitCast(II->getArgOperand(0),
3277 Mask->getType());
3278 Value *Op1 = Builder.CreateBitCast(II->getArgOperand(1),
3279 Mask->getType());
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003280 Value *Result = UndefValue::get(Op0->getType());
Jim Grosbach7815f562012-02-03 00:07:04 +00003281
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003282 // Only extract each element once.
3283 Value *ExtractedElts[32];
3284 memset(ExtractedElts, 0, sizeof(ExtractedElts));
Jim Grosbach7815f562012-02-03 00:07:04 +00003285
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003286 for (unsigned i = 0; i != 16; ++i) {
Chris Lattner0256be92012-01-27 03:08:05 +00003287 if (isa<UndefValue>(Mask->getAggregateElement(i)))
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003288 continue;
Jim Grosbach7815f562012-02-03 00:07:04 +00003289 unsigned Idx =
Chris Lattner0256be92012-01-27 03:08:05 +00003290 cast<ConstantInt>(Mask->getAggregateElement(i))->getZExtValue();
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003291 Idx &= 31; // Match the hardware behavior.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003292 if (DL.isLittleEndian())
Bill Schmidta1184632014-06-05 19:46:04 +00003293 Idx = 31 - Idx;
Jim Grosbach7815f562012-02-03 00:07:04 +00003294
Craig Topperf40110f2014-04-25 05:29:35 +00003295 if (!ExtractedElts[Idx]) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003296 Value *Op0ToUse = (DL.isLittleEndian()) ? Op1 : Op0;
3297 Value *Op1ToUse = (DL.isLittleEndian()) ? Op0 : Op1;
Jim Grosbach7815f562012-02-03 00:07:04 +00003298 ExtractedElts[Idx] =
Craig Topperbb4069e2017-07-07 23:16:26 +00003299 Builder.CreateExtractElement(Idx < 16 ? Op0ToUse : Op1ToUse,
3300 Builder.getInt32(Idx&15));
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003301 }
Jim Grosbach7815f562012-02-03 00:07:04 +00003302
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003303 // Insert this value into the result vector.
Craig Topperbb4069e2017-07-07 23:16:26 +00003304 Result = Builder.CreateInsertElement(Result, ExtractedElts[Idx],
3305 Builder.getInt32(i));
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003306 }
3307 return CastInst::Create(Instruction::BitCast, Result, CI.getType());
3308 }
3309 }
3310 break;
3311
Alexandros Lamprineas61f0ba12018-05-31 12:19:18 +00003312 case Intrinsic::arm_neon_vld1: {
3313 unsigned MemAlign = getKnownAlignment(II->getArgOperand(0),
3314 DL, II, &AC, &DT);
3315 if (Value *V = simplifyNeonVld1(*II, MemAlign, Builder))
3316 return replaceInstUsesWith(*II, V);
3317 break;
3318 }
3319
Bob Wilsona4e231c2010-10-22 21:41:48 +00003320 case Intrinsic::arm_neon_vld2:
3321 case Intrinsic::arm_neon_vld3:
3322 case Intrinsic::arm_neon_vld4:
3323 case Intrinsic::arm_neon_vld2lane:
3324 case Intrinsic::arm_neon_vld3lane:
3325 case Intrinsic::arm_neon_vld4lane:
3326 case Intrinsic::arm_neon_vst1:
3327 case Intrinsic::arm_neon_vst2:
3328 case Intrinsic::arm_neon_vst3:
3329 case Intrinsic::arm_neon_vst4:
3330 case Intrinsic::arm_neon_vst2lane:
3331 case Intrinsic::arm_neon_vst3lane:
3332 case Intrinsic::arm_neon_vst4lane: {
Justin Bogner99798402016-08-05 01:06:44 +00003333 unsigned MemAlign =
Daniel Jasperaec2fa32016-12-19 08:22:17 +00003334 getKnownAlignment(II->getArgOperand(0), DL, II, &AC, &DT);
Bob Wilsona4e231c2010-10-22 21:41:48 +00003335 unsigned AlignArg = II->getNumArgOperands() - 1;
3336 ConstantInt *IntrAlign = dyn_cast<ConstantInt>(II->getArgOperand(AlignArg));
3337 if (IntrAlign && IntrAlign->getZExtValue() < MemAlign) {
3338 II->setArgOperand(AlignArg,
3339 ConstantInt::get(Type::getInt32Ty(II->getContext()),
3340 MemAlign, false));
3341 return II;
3342 }
3343 break;
3344 }
3345
Alexandros Lamprineas52457d32018-05-30 14:38:50 +00003346 case Intrinsic::arm_neon_vtbl1:
3347 case Intrinsic::aarch64_neon_tbl1:
3348 if (Value *V = simplifyNeonTbl1(*II, Builder))
3349 return replaceInstUsesWith(*II, V);
3350 break;
3351
Lang Hames3a90fab2012-05-01 00:20:38 +00003352 case Intrinsic::arm_neon_vmulls:
Tim Northover00ed9962014-03-29 10:18:08 +00003353 case Intrinsic::arm_neon_vmullu:
Tim Northover3b0846e2014-05-24 12:50:23 +00003354 case Intrinsic::aarch64_neon_smull:
3355 case Intrinsic::aarch64_neon_umull: {
Lang Hames3a90fab2012-05-01 00:20:38 +00003356 Value *Arg0 = II->getArgOperand(0);
3357 Value *Arg1 = II->getArgOperand(1);
3358
3359 // Handle mul by zero first:
3360 if (isa<ConstantAggregateZero>(Arg0) || isa<ConstantAggregateZero>(Arg1)) {
Sanjay Patel4b198802016-02-01 22:23:39 +00003361 return replaceInstUsesWith(CI, ConstantAggregateZero::get(II->getType()));
Lang Hames3a90fab2012-05-01 00:20:38 +00003362 }
3363
3364 // Check for constant LHS & RHS - in this case we just simplify.
Sanjay Patel62f457b2019-05-06 15:35:02 +00003365 bool Zext = (IID == Intrinsic::arm_neon_vmullu ||
3366 IID == Intrinsic::aarch64_neon_umull);
Lang Hames3a90fab2012-05-01 00:20:38 +00003367 VectorType *NewVT = cast<VectorType>(II->getType());
Benjamin Kramer92040952014-02-13 18:23:24 +00003368 if (Constant *CV0 = dyn_cast<Constant>(Arg0)) {
3369 if (Constant *CV1 = dyn_cast<Constant>(Arg1)) {
3370 CV0 = ConstantExpr::getIntegerCast(CV0, NewVT, /*isSigned=*/!Zext);
3371 CV1 = ConstantExpr::getIntegerCast(CV1, NewVT, /*isSigned=*/!Zext);
3372
Sanjay Patel4b198802016-02-01 22:23:39 +00003373 return replaceInstUsesWith(CI, ConstantExpr::getMul(CV0, CV1));
Lang Hames3a90fab2012-05-01 00:20:38 +00003374 }
3375
Alp Tokercb402912014-01-24 17:20:08 +00003376 // Couldn't simplify - canonicalize constant to the RHS.
Lang Hames3a90fab2012-05-01 00:20:38 +00003377 std::swap(Arg0, Arg1);
3378 }
3379
3380 // Handle mul by one:
Benjamin Kramer92040952014-02-13 18:23:24 +00003381 if (Constant *CV1 = dyn_cast<Constant>(Arg1))
Lang Hames3a90fab2012-05-01 00:20:38 +00003382 if (ConstantInt *Splat =
Benjamin Kramer92040952014-02-13 18:23:24 +00003383 dyn_cast_or_null<ConstantInt>(CV1->getSplatValue()))
3384 if (Splat->isOne())
3385 return CastInst::CreateIntegerCast(Arg0, II->getType(),
3386 /*isSigned=*/!Zext);
Lang Hames3a90fab2012-05-01 00:20:38 +00003387
3388 break;
3389 }
Chad Rosier274d72f2018-05-24 15:26:42 +00003390 case Intrinsic::arm_neon_aesd:
3391 case Intrinsic::arm_neon_aese:
3392 case Intrinsic::aarch64_crypto_aesd:
3393 case Intrinsic::aarch64_crypto_aese: {
3394 Value *DataArg = II->getArgOperand(0);
3395 Value *KeyArg = II->getArgOperand(1);
3396
3397 // Try to use the builtin XOR in AESE and AESD to eliminate a prior XOR
3398 Value *Data, *Key;
3399 if (match(KeyArg, m_ZeroInt()) &&
3400 match(DataArg, m_Xor(m_Value(Data), m_Value(Key)))) {
3401 II->setArgOperand(0, Data);
3402 II->setArgOperand(1, Key);
3403 return II;
3404 }
3405 break;
3406 }
Simon Tathamf4f77aa2019-11-18 10:38:17 +00003407 case Intrinsic::arm_mve_pred_i2v: {
3408 Value *Arg = II->getArgOperand(0);
3409 Value *ArgArg;
3410 if (match(Arg, m_Intrinsic<Intrinsic::arm_mve_pred_v2i>(m_Value(ArgArg))) &&
3411 II->getType() == ArgArg->getType())
3412 return replaceInstUsesWith(*II, ArgArg);
Simon Tatham01aefae2019-12-02 16:18:34 +00003413 Constant *XorMask;
3414 if (match(Arg,
3415 m_Xor(m_Intrinsic<Intrinsic::arm_mve_pred_v2i>(m_Value(ArgArg)),
3416 m_Constant(XorMask))) &&
3417 II->getType() == ArgArg->getType()) {
3418 if (auto *CI = dyn_cast<ConstantInt>(XorMask)) {
3419 if (CI->getValue().trunc(16).isAllOnesValue()) {
3420 auto TrueVector = Builder.CreateVectorSplat(
3421 II->getType()->getVectorNumElements(), Builder.getTrue());
3422 return BinaryOperator::Create(Instruction::Xor, ArgArg, TrueVector);
3423 }
3424 }
3425 }
Simon Tathamf4f77aa2019-11-18 10:38:17 +00003426 KnownBits ScalarKnown(32);
3427 if (SimplifyDemandedBits(II, 0, APInt::getLowBitsSet(32, 16),
3428 ScalarKnown, 0))
3429 return II;
3430 break;
3431 }
3432 case Intrinsic::arm_mve_pred_v2i: {
3433 Value *Arg = II->getArgOperand(0);
3434 Value *ArgArg;
3435 if (match(Arg, m_Intrinsic<Intrinsic::arm_mve_pred_i2v>(m_Value(ArgArg))))
3436 return replaceInstUsesWith(*II, ArgArg);
3437 if (!II->getMetadata(LLVMContext::MD_range)) {
3438 Type *IntTy32 = Type::getInt32Ty(II->getContext());
3439 Metadata *M[] = {
3440 ConstantAsMetadata::get(ConstantInt::get(IntTy32, 0)),
3441 ConstantAsMetadata::get(ConstantInt::get(IntTy32, 0xFFFF))
3442 };
3443 II->setMetadata(LLVMContext::MD_range, MDNode::get(II->getContext(), M));
3444 return II;
3445 }
3446 break;
3447 }
Simon Tathame5f485c2019-09-11 10:29:56 +01003448 case Intrinsic::arm_mve_vadc:
3449 case Intrinsic::arm_mve_vadc_predicated: {
3450 unsigned CarryOp =
3451 (II->getIntrinsicID() == Intrinsic::arm_mve_vadc_predicated) ? 3 : 2;
Benjamin Kramer6f0bb772019-10-24 17:57:24 +02003452 assert(II->getArgOperand(CarryOp)->getType()->getScalarSizeInBits() == 32 &&
Simon Tathame5f485c2019-09-11 10:29:56 +01003453 "Bad type for intrinsic!");
3454
3455 KnownBits CarryKnown(32);
3456 if (SimplifyDemandedBits(II, CarryOp, APInt::getOneBitSet(32, 29),
3457 CarryKnown))
3458 return II;
3459 break;
3460 }
Matt Arsenaultbef34e22016-01-22 21:30:34 +00003461 case Intrinsic::amdgcn_rcp: {
Matt Arsenault4c7795d2017-03-24 19:04:57 +00003462 Value *Src = II->getArgOperand(0);
3463
3464 // TODO: Move to ConstantFolding/InstSimplify?
3465 if (isa<UndefValue>(Src))
3466 return replaceInstUsesWith(CI, Src);
3467
3468 if (const ConstantFP *C = dyn_cast<ConstantFP>(Src)) {
Matt Arsenaulta0050b02014-06-19 01:19:19 +00003469 const APFloat &ArgVal = C->getValueAPF();
Ehud Katz2b6b8cb2019-12-04 11:57:38 +02003470 APFloat Val(ArgVal.getSemantics(), 1);
Matt Arsenaulta0050b02014-06-19 01:19:19 +00003471 APFloat::opStatus Status = Val.divide(ArgVal,
3472 APFloat::rmNearestTiesToEven);
3473 // Only do this if it was exact and therefore not dependent on the
3474 // rounding mode.
3475 if (Status == APFloat::opOK)
Sanjay Patel4b198802016-02-01 22:23:39 +00003476 return replaceInstUsesWith(CI, ConstantFP::get(II->getContext(), Val));
Matt Arsenaulta0050b02014-06-19 01:19:19 +00003477 }
3478
3479 break;
3480 }
Matt Arsenault4c7795d2017-03-24 19:04:57 +00003481 case Intrinsic::amdgcn_rsq: {
3482 Value *Src = II->getArgOperand(0);
3483
3484 // TODO: Move to ConstantFolding/InstSimplify?
3485 if (isa<UndefValue>(Src))
3486 return replaceInstUsesWith(CI, Src);
3487 break;
3488 }
Matt Arsenault2fe4fbc2016-03-30 22:28:52 +00003489 case Intrinsic::amdgcn_frexp_mant:
3490 case Intrinsic::amdgcn_frexp_exp: {
Matt Arsenault5cd4f8f2016-03-30 22:28:26 +00003491 Value *Src = II->getArgOperand(0);
3492 if (const ConstantFP *C = dyn_cast<ConstantFP>(Src)) {
3493 int Exp;
3494 APFloat Significand = frexp(C->getValueAPF(), Exp,
3495 APFloat::rmNearestTiesToEven);
3496
Sanjay Patel62f457b2019-05-06 15:35:02 +00003497 if (IID == Intrinsic::amdgcn_frexp_mant) {
Matt Arsenault2fe4fbc2016-03-30 22:28:52 +00003498 return replaceInstUsesWith(CI, ConstantFP::get(II->getContext(),
3499 Significand));
3500 }
3501
3502 // Match instruction special case behavior.
3503 if (Exp == APFloat::IEK_NaN || Exp == APFloat::IEK_Inf)
3504 Exp = 0;
3505
3506 return replaceInstUsesWith(CI, ConstantInt::get(II->getType(), Exp));
3507 }
3508
3509 if (isa<UndefValue>(Src))
3510 return replaceInstUsesWith(CI, UndefValue::get(II->getType()));
Matt Arsenault5cd4f8f2016-03-30 22:28:26 +00003511
3512 break;
3513 }
Matt Arsenault46a03822016-09-03 07:06:58 +00003514 case Intrinsic::amdgcn_class: {
3515 enum {
3516 S_NAN = 1 << 0, // Signaling NaN
3517 Q_NAN = 1 << 1, // Quiet NaN
3518 N_INFINITY = 1 << 2, // Negative infinity
3519 N_NORMAL = 1 << 3, // Negative normal
3520 N_SUBNORMAL = 1 << 4, // Negative subnormal
3521 N_ZERO = 1 << 5, // Negative zero
3522 P_ZERO = 1 << 6, // Positive zero
3523 P_SUBNORMAL = 1 << 7, // Positive subnormal
3524 P_NORMAL = 1 << 8, // Positive normal
3525 P_INFINITY = 1 << 9 // Positive infinity
3526 };
3527
3528 const uint32_t FullMask = S_NAN | Q_NAN | N_INFINITY | N_NORMAL |
3529 N_SUBNORMAL | N_ZERO | P_ZERO | P_SUBNORMAL | P_NORMAL | P_INFINITY;
3530
3531 Value *Src0 = II->getArgOperand(0);
3532 Value *Src1 = II->getArgOperand(1);
3533 const ConstantInt *CMask = dyn_cast<ConstantInt>(Src1);
3534 if (!CMask) {
3535 if (isa<UndefValue>(Src0))
3536 return replaceInstUsesWith(*II, UndefValue::get(II->getType()));
3537
3538 if (isa<UndefValue>(Src1))
3539 return replaceInstUsesWith(*II, ConstantInt::get(II->getType(), false));
3540 break;
3541 }
3542
3543 uint32_t Mask = CMask->getZExtValue();
3544
3545 // If all tests are made, it doesn't matter what the value is.
3546 if ((Mask & FullMask) == FullMask)
3547 return replaceInstUsesWith(*II, ConstantInt::get(II->getType(), true));
3548
3549 if ((Mask & FullMask) == 0)
3550 return replaceInstUsesWith(*II, ConstantInt::get(II->getType(), false));
3551
3552 if (Mask == (S_NAN | Q_NAN)) {
3553 // Equivalent of isnan. Replace with standard fcmp.
Craig Topperbb4069e2017-07-07 23:16:26 +00003554 Value *FCmp = Builder.CreateFCmpUNO(Src0, Src0);
Matt Arsenault46a03822016-09-03 07:06:58 +00003555 FCmp->takeName(II);
3556 return replaceInstUsesWith(*II, FCmp);
3557 }
3558
Matt Arsenaultd35f46c2018-08-10 18:58:49 +00003559 if (Mask == (N_ZERO | P_ZERO)) {
3560 // Equivalent of == 0.
3561 Value *FCmp = Builder.CreateFCmpOEQ(
3562 Src0, ConstantFP::get(Src0->getType(), 0.0));
3563
3564 FCmp->takeName(II);
3565 return replaceInstUsesWith(*II, FCmp);
3566 }
3567
Matt Arsenault10de2772018-08-28 18:10:02 +00003568 // fp_class (nnan x), qnan|snan|other -> fp_class (nnan x), other
3569 if (((Mask & S_NAN) || (Mask & Q_NAN)) && isKnownNeverNaN(Src0, &TLI)) {
3570 II->setArgOperand(1, ConstantInt::get(Src1->getType(),
3571 Mask & ~(S_NAN | Q_NAN)));
3572 return II;
3573 }
3574
Matt Arsenault46a03822016-09-03 07:06:58 +00003575 const ConstantFP *CVal = dyn_cast<ConstantFP>(Src0);
3576 if (!CVal) {
3577 if (isa<UndefValue>(Src0))
3578 return replaceInstUsesWith(*II, UndefValue::get(II->getType()));
3579
3580 // Clamp mask to used bits
3581 if ((Mask & FullMask) != Mask) {
Craig Topperbb4069e2017-07-07 23:16:26 +00003582 CallInst *NewCall = Builder.CreateCall(II->getCalledFunction(),
Matt Arsenault46a03822016-09-03 07:06:58 +00003583 { Src0, ConstantInt::get(Src1->getType(), Mask & FullMask) }
3584 );
3585
3586 NewCall->takeName(II);
3587 return replaceInstUsesWith(*II, NewCall);
3588 }
3589
3590 break;
3591 }
3592
3593 const APFloat &Val = CVal->getValueAPF();
3594
3595 bool Result =
3596 ((Mask & S_NAN) && Val.isNaN() && Val.isSignaling()) ||
3597 ((Mask & Q_NAN) && Val.isNaN() && !Val.isSignaling()) ||
3598 ((Mask & N_INFINITY) && Val.isInfinity() && Val.isNegative()) ||
3599 ((Mask & N_NORMAL) && Val.isNormal() && Val.isNegative()) ||
3600 ((Mask & N_SUBNORMAL) && Val.isDenormal() && Val.isNegative()) ||
3601 ((Mask & N_ZERO) && Val.isZero() && Val.isNegative()) ||
3602 ((Mask & P_ZERO) && Val.isZero() && !Val.isNegative()) ||
3603 ((Mask & P_SUBNORMAL) && Val.isDenormal() && !Val.isNegative()) ||
3604 ((Mask & P_NORMAL) && Val.isNormal() && !Val.isNegative()) ||
3605 ((Mask & P_INFINITY) && Val.isInfinity() && !Val.isNegative());
3606
3607 return replaceInstUsesWith(*II, ConstantInt::get(II->getType(), Result));
3608 }
Matt Arsenault1f17c662017-02-22 00:27:34 +00003609 case Intrinsic::amdgcn_cvt_pkrtz: {
3610 Value *Src0 = II->getArgOperand(0);
3611 Value *Src1 = II->getArgOperand(1);
3612 if (const ConstantFP *C0 = dyn_cast<ConstantFP>(Src0)) {
3613 if (const ConstantFP *C1 = dyn_cast<ConstantFP>(Src1)) {
3614 const fltSemantics &HalfSem
3615 = II->getType()->getScalarType()->getFltSemantics();
3616 bool LosesInfo;
3617 APFloat Val0 = C0->getValueAPF();
3618 APFloat Val1 = C1->getValueAPF();
3619 Val0.convert(HalfSem, APFloat::rmTowardZero, &LosesInfo);
3620 Val1.convert(HalfSem, APFloat::rmTowardZero, &LosesInfo);
3621
3622 Constant *Folded = ConstantVector::get({
3623 ConstantFP::get(II->getContext(), Val0),
3624 ConstantFP::get(II->getContext(), Val1) });
3625 return replaceInstUsesWith(*II, Folded);
3626 }
3627 }
3628
3629 if (isa<UndefValue>(Src0) && isa<UndefValue>(Src1))
3630 return replaceInstUsesWith(*II, UndefValue::get(II->getType()));
3631
3632 break;
3633 }
Marek Olsak13e47412018-01-31 20:18:04 +00003634 case Intrinsic::amdgcn_cvt_pknorm_i16:
3635 case Intrinsic::amdgcn_cvt_pknorm_u16:
3636 case Intrinsic::amdgcn_cvt_pk_i16:
3637 case Intrinsic::amdgcn_cvt_pk_u16: {
3638 Value *Src0 = II->getArgOperand(0);
3639 Value *Src1 = II->getArgOperand(1);
3640
3641 if (isa<UndefValue>(Src0) && isa<UndefValue>(Src1))
3642 return replaceInstUsesWith(*II, UndefValue::get(II->getType()));
3643
3644 break;
3645 }
Matt Arsenaultf5262252017-02-22 23:04:58 +00003646 case Intrinsic::amdgcn_ubfe:
3647 case Intrinsic::amdgcn_sbfe: {
3648 // Decompose simple cases into standard shifts.
3649 Value *Src = II->getArgOperand(0);
3650 if (isa<UndefValue>(Src))
3651 return replaceInstUsesWith(*II, Src);
3652
3653 unsigned Width;
3654 Type *Ty = II->getType();
3655 unsigned IntSize = Ty->getIntegerBitWidth();
3656
3657 ConstantInt *CWidth = dyn_cast<ConstantInt>(II->getArgOperand(2));
3658 if (CWidth) {
3659 Width = CWidth->getZExtValue();
3660 if ((Width & (IntSize - 1)) == 0)
3661 return replaceInstUsesWith(*II, ConstantInt::getNullValue(Ty));
3662
3663 if (Width >= IntSize) {
3664 // Hardware ignores high bits, so remove those.
3665 II->setArgOperand(2, ConstantInt::get(CWidth->getType(),
3666 Width & (IntSize - 1)));
3667 return II;
3668 }
3669 }
3670
3671 unsigned Offset;
3672 ConstantInt *COffset = dyn_cast<ConstantInt>(II->getArgOperand(1));
3673 if (COffset) {
3674 Offset = COffset->getZExtValue();
3675 if (Offset >= IntSize) {
3676 II->setArgOperand(1, ConstantInt::get(COffset->getType(),
3677 Offset & (IntSize - 1)));
3678 return II;
3679 }
3680 }
3681
Sanjay Patel62f457b2019-05-06 15:35:02 +00003682 bool Signed = IID == Intrinsic::amdgcn_sbfe;
Matt Arsenaultf5262252017-02-22 23:04:58 +00003683
Matt Arsenaultf5262252017-02-22 23:04:58 +00003684 if (!CWidth || !COffset)
3685 break;
3686
Tom Stellard28d66212018-11-08 17:57:57 +00003687 // The case of Width == 0 is handled above, which makes this tranformation
3688 // safe. If Width == 0, then the ashr and lshr instructions become poison
3689 // value since the shift amount would be equal to the bit size.
3690 assert(Width != 0);
3691
Matt Arsenaultf5262252017-02-22 23:04:58 +00003692 // TODO: This allows folding to undef when the hardware has specific
3693 // behavior?
3694 if (Offset + Width < IntSize) {
Craig Topperbb4069e2017-07-07 23:16:26 +00003695 Value *Shl = Builder.CreateShl(Src, IntSize - Offset - Width);
3696 Value *RightShift = Signed ? Builder.CreateAShr(Shl, IntSize - Width)
3697 : Builder.CreateLShr(Shl, IntSize - Width);
Matt Arsenaultf5262252017-02-22 23:04:58 +00003698 RightShift->takeName(II);
3699 return replaceInstUsesWith(*II, RightShift);
3700 }
3701
Craig Topperbb4069e2017-07-07 23:16:26 +00003702 Value *RightShift = Signed ? Builder.CreateAShr(Src, Offset)
3703 : Builder.CreateLShr(Src, Offset);
Matt Arsenaultf5262252017-02-22 23:04:58 +00003704
3705 RightShift->takeName(II);
3706 return replaceInstUsesWith(*II, RightShift);
3707 }
Matt Arsenaultd4bca1e2017-02-23 00:44:03 +00003708 case Intrinsic::amdgcn_exp:
3709 case Intrinsic::amdgcn_exp_compr: {
Matt Arsenaultcaf13162019-03-12 21:02:54 +00003710 ConstantInt *En = cast<ConstantInt>(II->getArgOperand(1));
Matt Arsenaultd4bca1e2017-02-23 00:44:03 +00003711 unsigned EnBits = En->getZExtValue();
3712 if (EnBits == 0xf)
3713 break; // All inputs enabled.
3714
Sanjay Patel62f457b2019-05-06 15:35:02 +00003715 bool IsCompr = IID == Intrinsic::amdgcn_exp_compr;
Matt Arsenaultd4bca1e2017-02-23 00:44:03 +00003716 bool Changed = false;
3717 for (int I = 0; I < (IsCompr ? 2 : 4); ++I) {
3718 if ((!IsCompr && (EnBits & (1 << I)) == 0) ||
3719 (IsCompr && ((EnBits & (0x3 << (2 * I))) == 0))) {
3720 Value *Src = II->getArgOperand(I + 2);
3721 if (!isa<UndefValue>(Src)) {
3722 II->setArgOperand(I + 2, UndefValue::get(Src->getType()));
3723 Changed = true;
3724 }
3725 }
3726 }
3727
3728 if (Changed)
3729 return II;
3730
3731 break;
Matt Arsenaultcdb468c2017-02-27 23:08:49 +00003732 }
3733 case Intrinsic::amdgcn_fmed3: {
3734 // Note this does not preserve proper sNaN behavior if IEEE-mode is enabled
3735 // for the shader.
3736
3737 Value *Src0 = II->getArgOperand(0);
3738 Value *Src1 = II->getArgOperand(1);
3739 Value *Src2 = II->getArgOperand(2);
3740
Matt Arsenault24ce89b2018-07-05 17:05:36 +00003741 // Checking for NaN before canonicalization provides better fidelity when
3742 // mapping other operations onto fmed3 since the order of operands is
3743 // unchanged.
3744 CallInst *NewCall = nullptr;
3745 if (match(Src0, m_NaN()) || isa<UndefValue>(Src0)) {
3746 NewCall = Builder.CreateMinNum(Src1, Src2);
3747 } else if (match(Src1, m_NaN()) || isa<UndefValue>(Src1)) {
3748 NewCall = Builder.CreateMinNum(Src0, Src2);
3749 } else if (match(Src2, m_NaN()) || isa<UndefValue>(Src2)) {
3750 NewCall = Builder.CreateMaxNum(Src0, Src1);
3751 }
3752
3753 if (NewCall) {
3754 NewCall->copyFastMathFlags(II);
3755 NewCall->takeName(II);
3756 return replaceInstUsesWith(*II, NewCall);
3757 }
3758
Matt Arsenaultcdb468c2017-02-27 23:08:49 +00003759 bool Swap = false;
3760 // Canonicalize constants to RHS operands.
3761 //
3762 // fmed3(c0, x, c1) -> fmed3(x, c0, c1)
3763 if (isa<Constant>(Src0) && !isa<Constant>(Src1)) {
3764 std::swap(Src0, Src1);
3765 Swap = true;
3766 }
3767
3768 if (isa<Constant>(Src1) && !isa<Constant>(Src2)) {
3769 std::swap(Src1, Src2);
3770 Swap = true;
3771 }
3772
3773 if (isa<Constant>(Src0) && !isa<Constant>(Src1)) {
3774 std::swap(Src0, Src1);
3775 Swap = true;
3776 }
3777
3778 if (Swap) {
3779 II->setArgOperand(0, Src0);
3780 II->setArgOperand(1, Src1);
3781 II->setArgOperand(2, Src2);
3782 return II;
3783 }
3784
Matt Arsenaultcdb468c2017-02-27 23:08:49 +00003785 if (const ConstantFP *C0 = dyn_cast<ConstantFP>(Src0)) {
3786 if (const ConstantFP *C1 = dyn_cast<ConstantFP>(Src1)) {
3787 if (const ConstantFP *C2 = dyn_cast<ConstantFP>(Src2)) {
3788 APFloat Result = fmed3AMDGCN(C0->getValueAPF(), C1->getValueAPF(),
3789 C2->getValueAPF());
3790 return replaceInstUsesWith(*II,
Craig Topperbb4069e2017-07-07 23:16:26 +00003791 ConstantFP::get(Builder.getContext(), Result));
Matt Arsenaultcdb468c2017-02-27 23:08:49 +00003792 }
3793 }
3794 }
3795
3796 break;
Matt Arsenaultd4bca1e2017-02-23 00:44:03 +00003797 }
Matt Arsenaultd81f5572017-03-13 18:14:02 +00003798 case Intrinsic::amdgcn_icmp:
3799 case Intrinsic::amdgcn_fcmp: {
Matt Arsenaultcaf13162019-03-12 21:02:54 +00003800 const ConstantInt *CC = cast<ConstantInt>(II->getArgOperand(2));
Matt Arsenaultd81f5572017-03-13 18:14:02 +00003801 // Guard against invalid arguments.
3802 int64_t CCVal = CC->getZExtValue();
Sanjay Patel62f457b2019-05-06 15:35:02 +00003803 bool IsInteger = IID == Intrinsic::amdgcn_icmp;
Matt Arsenaultd81f5572017-03-13 18:14:02 +00003804 if ((IsInteger && (CCVal < CmpInst::FIRST_ICMP_PREDICATE ||
3805 CCVal > CmpInst::LAST_ICMP_PREDICATE)) ||
3806 (!IsInteger && (CCVal < CmpInst::FIRST_FCMP_PREDICATE ||
3807 CCVal > CmpInst::LAST_FCMP_PREDICATE)))
3808 break;
3809
3810 Value *Src0 = II->getArgOperand(0);
3811 Value *Src1 = II->getArgOperand(1);
3812
3813 if (auto *CSrc0 = dyn_cast<Constant>(Src0)) {
3814 if (auto *CSrc1 = dyn_cast<Constant>(Src1)) {
3815 Constant *CCmp = ConstantExpr::getCompare(CCVal, CSrc0, CSrc1);
Nicolai Haehnle9c661852017-04-24 17:08:43 +00003816 if (CCmp->isNullValue()) {
3817 return replaceInstUsesWith(
3818 *II, ConstantExpr::getSExt(CCmp, II->getType()));
3819 }
3820
3821 // The result of V_ICMP/V_FCMP assembly instructions (which this
3822 // intrinsic exposes) is one bit per thread, masked with the EXEC
3823 // register (which contains the bitmask of live threads). So a
3824 // comparison that always returns true is the same as a read of the
3825 // EXEC register.
James Y Knight7976eb52019-02-01 20:43:25 +00003826 Function *NewF = Intrinsic::getDeclaration(
Nicolai Haehnle9c661852017-04-24 17:08:43 +00003827 II->getModule(), Intrinsic::read_register, II->getType());
3828 Metadata *MDArgs[] = {MDString::get(II->getContext(), "exec")};
3829 MDNode *MD = MDNode::get(II->getContext(), MDArgs);
3830 Value *Args[] = {MetadataAsValue::get(II->getContext(), MD)};
Craig Topperbb4069e2017-07-07 23:16:26 +00003831 CallInst *NewCall = Builder.CreateCall(NewF, Args);
Nicolai Haehnle9c661852017-04-24 17:08:43 +00003832 NewCall->addAttribute(AttributeList::FunctionIndex,
3833 Attribute::Convergent);
3834 NewCall->takeName(II);
3835 return replaceInstUsesWith(*II, NewCall);
Matt Arsenaultd81f5572017-03-13 18:14:02 +00003836 }
3837
3838 // Canonicalize constants to RHS.
3839 CmpInst::Predicate SwapPred
3840 = CmpInst::getSwappedPredicate(static_cast<CmpInst::Predicate>(CCVal));
3841 II->setArgOperand(0, Src1);
3842 II->setArgOperand(1, Src0);
3843 II->setArgOperand(2, ConstantInt::get(CC->getType(),
3844 static_cast<int>(SwapPred)));
3845 return II;
3846 }
3847
3848 if (CCVal != CmpInst::ICMP_EQ && CCVal != CmpInst::ICMP_NE)
3849 break;
3850
3851 // Canonicalize compare eq with true value to compare != 0
3852 // llvm.amdgcn.icmp(zext (i1 x), 1, eq)
3853 // -> llvm.amdgcn.icmp(zext (i1 x), 0, ne)
3854 // llvm.amdgcn.icmp(sext (i1 x), -1, eq)
3855 // -> llvm.amdgcn.icmp(sext (i1 x), 0, ne)
3856 Value *ExtSrc;
3857 if (CCVal == CmpInst::ICMP_EQ &&
3858 ((match(Src1, m_One()) && match(Src0, m_ZExt(m_Value(ExtSrc)))) ||
3859 (match(Src1, m_AllOnes()) && match(Src0, m_SExt(m_Value(ExtSrc))))) &&
3860 ExtSrc->getType()->isIntegerTy(1)) {
3861 II->setArgOperand(1, ConstantInt::getNullValue(Src1->getType()));
3862 II->setArgOperand(2, ConstantInt::get(CC->getType(), CmpInst::ICMP_NE));
3863 return II;
3864 }
3865
3866 CmpInst::Predicate SrcPred;
3867 Value *SrcLHS;
3868 Value *SrcRHS;
3869
3870 // Fold compare eq/ne with 0 from a compare result as the predicate to the
3871 // intrinsic. The typical use is a wave vote function in the library, which
3872 // will be fed from a user code condition compared with 0. Fold in the
3873 // redundant compare.
3874
3875 // llvm.amdgcn.icmp([sz]ext ([if]cmp pred a, b), 0, ne)
3876 // -> llvm.amdgcn.[if]cmp(a, b, pred)
3877 //
3878 // llvm.amdgcn.icmp([sz]ext ([if]cmp pred a, b), 0, eq)
3879 // -> llvm.amdgcn.[if]cmp(a, b, inv pred)
3880 if (match(Src1, m_Zero()) &&
3881 match(Src0,
3882 m_ZExtOrSExt(m_Cmp(SrcPred, m_Value(SrcLHS), m_Value(SrcRHS))))) {
3883 if (CCVal == CmpInst::ICMP_EQ)
3884 SrcPred = CmpInst::getInversePredicate(SrcPred);
3885
3886 Intrinsic::ID NewIID = CmpInst::isFPPredicate(SrcPred) ?
3887 Intrinsic::amdgcn_fcmp : Intrinsic::amdgcn_icmp;
3888
Matt Arsenault9a389fb2018-08-15 21:14:25 +00003889 Type *Ty = SrcLHS->getType();
3890 if (auto *CmpType = dyn_cast<IntegerType>(Ty)) {
3891 // Promote to next legal integer type.
3892 unsigned Width = CmpType->getBitWidth();
3893 unsigned NewWidth = Width;
Marek Olsak33eb4d92019-01-15 02:13:18 +00003894
3895 // Don't do anything for i1 comparisons.
3896 if (Width == 1)
3897 break;
3898
Matt Arsenault9a389fb2018-08-15 21:14:25 +00003899 if (Width <= 16)
3900 NewWidth = 16;
3901 else if (Width <= 32)
3902 NewWidth = 32;
3903 else if (Width <= 64)
3904 NewWidth = 64;
3905 else if (Width > 64)
3906 break; // Can't handle this.
3907
3908 if (Width != NewWidth) {
3909 IntegerType *CmpTy = Builder.getIntNTy(NewWidth);
3910 if (CmpInst::isSigned(SrcPred)) {
3911 SrcLHS = Builder.CreateSExt(SrcLHS, CmpTy);
3912 SrcRHS = Builder.CreateSExt(SrcRHS, CmpTy);
3913 } else {
3914 SrcLHS = Builder.CreateZExt(SrcLHS, CmpTy);
3915 SrcRHS = Builder.CreateZExt(SrcRHS, CmpTy);
3916 }
3917 }
3918 } else if (!Ty->isFloatTy() && !Ty->isDoubleTy() && !Ty->isHalfTy())
3919 break;
3920
James Y Knight7976eb52019-02-01 20:43:25 +00003921 Function *NewF =
Stanislav Mekhanoshin68a2fef2019-06-13 23:47:36 +00003922 Intrinsic::getDeclaration(II->getModule(), NewIID,
3923 { II->getType(),
3924 SrcLHS->getType() });
Matt Arsenaultd81f5572017-03-13 18:14:02 +00003925 Value *Args[] = { SrcLHS, SrcRHS,
3926 ConstantInt::get(CC->getType(), SrcPred) };
Craig Topperbb4069e2017-07-07 23:16:26 +00003927 CallInst *NewCall = Builder.CreateCall(NewF, Args);
Matt Arsenaultd81f5572017-03-13 18:14:02 +00003928 NewCall->takeName(II);
3929 return replaceInstUsesWith(*II, NewCall);
3930 }
3931
3932 break;
3933 }
Marek Olsak2114fc32017-10-24 10:26:59 +00003934 case Intrinsic::amdgcn_wqm_vote: {
3935 // wqm_vote is identity when the argument is constant.
3936 if (!isa<Constant>(II->getArgOperand(0)))
3937 break;
3938
3939 return replaceInstUsesWith(*II, II->getArgOperand(0));
3940 }
Marek Olsakce76ea02017-10-24 10:27:13 +00003941 case Intrinsic::amdgcn_kill: {
3942 const ConstantInt *C = dyn_cast<ConstantInt>(II->getArgOperand(0));
3943 if (!C || !C->getZExtValue())
3944 break;
3945
3946 // amdgcn.kill(i1 1) is a no-op
3947 return eraseInstFromFunction(CI);
3948 }
Stanislav Mekhanoshin0e132dc2018-05-22 08:04:33 +00003949 case Intrinsic::amdgcn_update_dpp: {
3950 Value *Old = II->getArgOperand(0);
3951
Matt Arsenaultcaf13162019-03-12 21:02:54 +00003952 auto BC = cast<ConstantInt>(II->getArgOperand(5));
3953 auto RM = cast<ConstantInt>(II->getArgOperand(3));
3954 auto BM = cast<ConstantInt>(II->getArgOperand(4));
3955 if (BC->isZeroValue() ||
Stanislav Mekhanoshin0e132dc2018-05-22 08:04:33 +00003956 RM->getZExtValue() != 0xF ||
3957 BM->getZExtValue() != 0xF ||
3958 isa<UndefValue>(Old))
3959 break;
3960
3961 // If bound_ctrl = 1, row mask = bank mask = 0xf we can omit old value.
3962 II->setOperand(0, UndefValue::get(Old->getType()));
3963 return II;
3964 }
Matt Arsenault3ef8cdf2020-01-16 09:59:56 -05003965 case Intrinsic::amdgcn_permlane16:
3966 case Intrinsic::amdgcn_permlanex16: {
3967 // Discard vdst_in if it's not going to be read.
3968 Value *VDstIn = II->getArgOperand(0);
3969 if (isa<UndefValue>(VDstIn))
3970 break;
3971
3972 ConstantInt *FetchInvalid = cast<ConstantInt>(II->getArgOperand(4));
3973 ConstantInt *BoundCtrl = cast<ConstantInt>(II->getArgOperand(5));
3974 if (!FetchInvalid->getZExtValue() && !BoundCtrl->getZExtValue())
3975 break;
3976
3977 II->setArgOperand(0, UndefValue::get(VDstIn->getType()));
3978 return II;
3979 }
Matt Arsenault492d71c2019-06-14 14:51:26 +00003980 case Intrinsic::amdgcn_readfirstlane:
3981 case Intrinsic::amdgcn_readlane: {
3982 // A constant value is trivially uniform.
3983 if (Constant *C = dyn_cast<Constant>(II->getArgOperand(0)))
3984 return replaceInstUsesWith(*II, C);
Matt Arsenault6d741f22019-06-17 17:52:35 +00003985
3986 // The rest of these may not be safe if the exec may not be the same between
3987 // the def and use.
3988 Value *Src = II->getArgOperand(0);
3989 Instruction *SrcInst = dyn_cast<Instruction>(Src);
3990 if (SrcInst && SrcInst->getParent() != II->getParent())
3991 break;
3992
3993 // readfirstlane (readfirstlane x) -> readfirstlane x
3994 // readlane (readfirstlane x), y -> readfirstlane x
3995 if (match(Src, m_Intrinsic<Intrinsic::amdgcn_readfirstlane>()))
3996 return replaceInstUsesWith(*II, Src);
3997
3998 if (IID == Intrinsic::amdgcn_readfirstlane) {
3999 // readfirstlane (readlane x, y) -> readlane x, y
4000 if (match(Src, m_Intrinsic<Intrinsic::amdgcn_readlane>()))
4001 return replaceInstUsesWith(*II, Src);
4002 } else {
4003 // readlane (readlane x, y), y -> readlane x, y
4004 if (match(Src, m_Intrinsic<Intrinsic::amdgcn_readlane>(
4005 m_Value(), m_Specific(II->getArgOperand(1)))))
4006 return replaceInstUsesWith(*II, Src);
4007 }
4008
Matt Arsenault492d71c2019-06-14 14:51:26 +00004009 break;
4010 }
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004011 case Intrinsic::stackrestore: {
4012 // If the save is right next to the restore, remove the restore. This can
4013 // happen when variable allocas are DCE'd.
Gabor Greif589a0b92010-06-24 12:58:35 +00004014 if (IntrinsicInst *SS = dyn_cast<IntrinsicInst>(II->getArgOperand(0))) {
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004015 if (SS->getIntrinsicID() == Intrinsic::stacksave) {
Vedant Kumarf01827f2018-06-19 23:42:17 +00004016 // Skip over debug info.
4017 if (SS->getNextNonDebugInstruction() == II) {
Sanjay Patel4b198802016-02-01 22:23:39 +00004018 return eraseInstFromFunction(CI);
Davide Italiano189c2cf2018-06-08 20:42:36 +00004019 }
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004020 }
4021 }
Jim Grosbach7815f562012-02-03 00:07:04 +00004022
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004023 // Scan down this block to see if there is another stack restore in the
4024 // same block without an intervening call/alloca.
Duncan P. N. Exon Smith9f8aaf22015-10-13 16:59:33 +00004025 BasicBlock::iterator BI(II);
Chandler Carruthedb12a82018-10-15 10:04:59 +00004026 Instruction *TI = II->getParent()->getTerminator();
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004027 bool CannotRemove = false;
4028 for (++BI; &*BI != TI; ++BI) {
Nuno Lopes55fff832012-06-21 15:45:28 +00004029 if (isa<AllocaInst>(BI)) {
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004030 CannotRemove = true;
4031 break;
4032 }
4033 if (CallInst *BCI = dyn_cast<CallInst>(BI)) {
Sanjay Patel62f457b2019-05-06 15:35:02 +00004034 if (auto *II2 = dyn_cast<IntrinsicInst>(BCI)) {
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004035 // If there is a stackrestore below this one, remove this one.
Sanjay Patel62f457b2019-05-06 15:35:02 +00004036 if (II2->getIntrinsicID() == Intrinsic::stackrestore)
Sanjay Patel4b198802016-02-01 22:23:39 +00004037 return eraseInstFromFunction(CI);
Reid Kleckner892ae2e2016-02-27 00:53:54 +00004038
4039 // Bail if we cross over an intrinsic with side effects, such as
Fangrui Song7a733462019-12-26 23:32:53 -08004040 // llvm.stacksave, or llvm.read_register.
Sanjay Patel62f457b2019-05-06 15:35:02 +00004041 if (II2->mayHaveSideEffects()) {
Reid Kleckner892ae2e2016-02-27 00:53:54 +00004042 CannotRemove = true;
4043 break;
4044 }
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004045 } else {
4046 // If we found a non-intrinsic call, we can't remove the stack
4047 // restore.
4048 CannotRemove = true;
4049 break;
4050 }
4051 }
4052 }
Jim Grosbach7815f562012-02-03 00:07:04 +00004053
Bill Wendlingf891bf82011-07-31 06:30:59 +00004054 // If the stack restore is in a return, resume, or unwind block and if there
4055 // are no allocas or calls between the restore and the return, nuke the
4056 // restore.
Bill Wendlingd5d95b02012-02-06 21:16:41 +00004057 if (!CannotRemove && (isa<ReturnInst>(TI) || isa<ResumeInst>(TI)))
Sanjay Patel4b198802016-02-01 22:23:39 +00004058 return eraseInstFromFunction(CI);
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004059 break;
4060 }
Vitaly Bukaf0500b62016-07-28 22:50:48 +00004061 case Intrinsic::lifetime_start:
Vitaly Buka0ab23cf2016-07-28 22:59:03 +00004062 // Asan needs to poison memory to detect invalid access which is possible
4063 // even for empty lifetime range.
Evgeniy Stepanovc667c1f2017-12-09 00:21:41 +00004064 if (II->getFunction()->hasFnAttribute(Attribute::SanitizeAddress) ||
Vitaly Bukaaeca5692019-08-26 22:15:50 +00004065 II->getFunction()->hasFnAttribute(Attribute::SanitizeMemory) ||
Evgeniy Stepanovc667c1f2017-12-09 00:21:41 +00004066 II->getFunction()->hasFnAttribute(Attribute::SanitizeHWAddress))
Vitaly Buka0ab23cf2016-07-28 22:59:03 +00004067 break;
4068
Arnaud A. de Grandmaison333ef382016-05-10 09:24:49 +00004069 if (removeTriviallyEmptyRange(*II, Intrinsic::lifetime_start,
4070 Intrinsic::lifetime_end, *this))
4071 return nullptr;
Arnaud A. de Grandmaison849f3bf2015-10-01 14:54:31 +00004072 break;
Hal Finkelf5867a72014-07-25 21:45:17 +00004073 case Intrinsic::assume: {
David Majnemerfcc58112016-04-08 16:37:12 +00004074 Value *IIOperand = II->getArgOperand(0);
Sanjay Patel825a4fa2018-06-20 13:22:26 +00004075 // Remove an assume if it is followed by an identical assume.
4076 // TODO: Do we need this? Unless there are conflicting assumptions, the
4077 // computeKnownBits(IIOperand) below here eliminates redundant assumes.
4078 Instruction *Next = II->getNextNonDebugInstruction();
4079 if (match(Next, m_Intrinsic<Intrinsic::assume>(m_Specific(IIOperand))))
David Majnemerfcc58112016-04-08 16:37:12 +00004080 return eraseInstFromFunction(CI);
4081
Hal Finkelf5867a72014-07-25 21:45:17 +00004082 // Canonicalize assume(a && b) -> assume(a); assume(b);
Hal Finkel74c2f352014-09-07 12:44:26 +00004083 // Note: New assumption intrinsics created here are registered by
4084 // the InstCombineIRInserter object.
James Y Knight7976eb52019-02-01 20:43:25 +00004085 FunctionType *AssumeIntrinsicTy = II->getFunctionType();
4086 Value *AssumeIntrinsic = II->getCalledValue();
4087 Value *A, *B;
Hal Finkelf5867a72014-07-25 21:45:17 +00004088 if (match(IIOperand, m_And(m_Value(A), m_Value(B)))) {
James Y Knight7976eb52019-02-01 20:43:25 +00004089 Builder.CreateCall(AssumeIntrinsicTy, AssumeIntrinsic, A, II->getName());
4090 Builder.CreateCall(AssumeIntrinsicTy, AssumeIntrinsic, B, II->getName());
Sanjay Patel4b198802016-02-01 22:23:39 +00004091 return eraseInstFromFunction(*II);
Hal Finkelf5867a72014-07-25 21:45:17 +00004092 }
4093 // assume(!(a || b)) -> assume(!a); assume(!b);
4094 if (match(IIOperand, m_Not(m_Or(m_Value(A), m_Value(B))))) {
James Y Knight7976eb52019-02-01 20:43:25 +00004095 Builder.CreateCall(AssumeIntrinsicTy, AssumeIntrinsic,
4096 Builder.CreateNot(A), II->getName());
4097 Builder.CreateCall(AssumeIntrinsicTy, AssumeIntrinsic,
4098 Builder.CreateNot(B), II->getName());
Sanjay Patel4b198802016-02-01 22:23:39 +00004099 return eraseInstFromFunction(*II);
Hal Finkelf5867a72014-07-25 21:45:17 +00004100 }
Hal Finkel04a15612014-10-04 21:27:06 +00004101
Philip Reames66c6de62014-11-11 23:33:19 +00004102 // assume( (load addr) != null ) -> add 'nonnull' metadata to load
4103 // (if assume is valid at the load)
Sanjay Patelf0d1e7732017-01-03 22:25:31 +00004104 CmpInst::Predicate Pred;
4105 Instruction *LHS;
4106 if (match(IIOperand, m_ICmp(Pred, m_Instruction(LHS), m_Zero())) &&
4107 Pred == ICmpInst::ICMP_NE && LHS->getOpcode() == Instruction::Load &&
4108 LHS->getType()->isPointerTy() &&
4109 isValidAssumeForContext(II, LHS, &DT)) {
4110 MDNode *MD = MDNode::get(II->getContext(), None);
4111 LHS->setMetadata(LLVMContext::MD_nonnull, MD);
4112 return eraseInstFromFunction(*II);
4113
Chandler Carruth24969102015-02-10 08:07:32 +00004114 // TODO: apply nonnull return attributes to calls and invokes
Philip Reames66c6de62014-11-11 23:33:19 +00004115 // TODO: apply range metadata for range check patterns?
4116 }
Sanjay Patelf0d1e7732017-01-03 22:25:31 +00004117
Hal Finkel04a15612014-10-04 21:27:06 +00004118 // If there is a dominating assume with the same condition as this one,
4119 // then this one is redundant, and should be removed.
Craig Topperb45eabc2017-04-26 16:39:58 +00004120 KnownBits Known(1);
4121 computeKnownBits(IIOperand, Known, 0, II);
Craig Topperf0aeee02017-05-05 17:36:09 +00004122 if (Known.isAllOnes())
Sanjay Patel4b198802016-02-01 22:23:39 +00004123 return eraseInstFromFunction(*II);
Hal Finkel04a15612014-10-04 21:27:06 +00004124
Hal Finkel8a9a7832017-01-11 13:24:24 +00004125 // Update the cache of affected values for this assumption (we might be
4126 // here because we just simplified the condition).
4127 AC.updateAffectedValues(II);
Hal Finkelf5867a72014-07-25 21:45:17 +00004128 break;
4129 }
Philip Reames9db26ff2014-12-29 23:27:30 +00004130 case Intrinsic::experimental_gc_relocate: {
Philip Reamesd9629b82019-09-24 17:24:16 +00004131 auto &GCR = *cast<GCRelocateInst>(II);
4132
4133 // If we have two copies of the same pointer in the statepoint argument
4134 // list, canonicalize to one. This may let us common gc.relocates.
4135 if (GCR.getBasePtr() == GCR.getDerivedPtr() &&
4136 GCR.getBasePtrIndex() != GCR.getDerivedPtrIndex()) {
4137 auto *OpIntTy = GCR.getOperand(2)->getType();
4138 II->setOperand(2, ConstantInt::get(OpIntTy, GCR.getBasePtrIndex()));
4139 return II;
4140 }
4141
Philip Reames9db26ff2014-12-29 23:27:30 +00004142 // Translate facts known about a pointer before relocating into
4143 // facts about the relocate value, while being careful to
4144 // preserve relocation semantics.
Philip Reamesd9629b82019-09-24 17:24:16 +00004145 Value *DerivedPtr = GCR.getDerivedPtr();
Philip Reames9db26ff2014-12-29 23:27:30 +00004146
4147 // Remove the relocation if unused, note that this check is required
4148 // to prevent the cases below from looping forever.
4149 if (II->use_empty())
Sanjay Patel4b198802016-02-01 22:23:39 +00004150 return eraseInstFromFunction(*II);
Philip Reames9db26ff2014-12-29 23:27:30 +00004151
4152 // Undef is undef, even after relocation.
4153 // TODO: provide a hook for this in GCStrategy. This is clearly legal for
4154 // most practical collectors, but there was discussion in the review thread
4155 // about whether it was legal for all possible collectors.
Philip Reamesea4d8e82016-02-09 21:09:22 +00004156 if (isa<UndefValue>(DerivedPtr))
4157 // Use undef of gc_relocate's type to replace it.
4158 return replaceInstUsesWith(*II, UndefValue::get(II->getType()));
Philip Reames9db26ff2014-12-29 23:27:30 +00004159
Philip Reamesea4d8e82016-02-09 21:09:22 +00004160 if (auto *PT = dyn_cast<PointerType>(II->getType())) {
4161 // The relocation of null will be null for most any collector.
4162 // TODO: provide a hook for this in GCStrategy. There might be some
4163 // weird collector this property does not hold for.
4164 if (isa<ConstantPointerNull>(DerivedPtr))
4165 // Use null-pointer of gc_relocate's type to replace it.
4166 return replaceInstUsesWith(*II, ConstantPointerNull::get(PT));
Simon Pilgrimc0c56e72016-04-24 17:00:34 +00004167
Philip Reamesea4d8e82016-02-09 21:09:22 +00004168 // isKnownNonNull -> nonnull attribute
Philip Reamesb8d8db32018-11-12 20:00:53 +00004169 if (!II->hasRetAttr(Attribute::NonNull) &&
4170 isKnownNonZero(DerivedPtr, DL, 0, &AC, II, &DT)) {
Reid Klecknerb5180542017-03-21 16:57:19 +00004171 II->addAttribute(AttributeList::ReturnIndex, Attribute::NonNull);
Philip Reamesb8d8db32018-11-12 20:00:53 +00004172 return II;
4173 }
Ramkumar Ramachandra8fcb4982015-02-14 19:37:54 +00004174 }
Philip Reames9db26ff2014-12-29 23:27:30 +00004175
4176 // TODO: bitcast(relocate(p)) -> relocate(bitcast(p))
4177 // Canonicalize on the type from the uses to the defs
Ramkumar Ramachandra8fcb4982015-02-14 19:37:54 +00004178
Philip Reames9db26ff2014-12-29 23:27:30 +00004179 // TODO: relocate((gep p, C, C2, ...)) -> gep(relocate(p), C, C2, ...)
Philip Reamesea4d8e82016-02-09 21:09:22 +00004180 break;
Philip Reames9db26ff2014-12-29 23:27:30 +00004181 }
Artur Pilipenkoe812ca02017-01-25 14:12:12 +00004182
4183 case Intrinsic::experimental_guard: {
Philip Reames79e917d2018-05-09 22:56:32 +00004184 // Is this guard followed by another guard? We scan forward over a small
4185 // fixed window of instructions to handle common cases with conditions
4186 // computed between guards.
Davide Italianoc32f0ff2019-11-22 13:02:18 -08004187 Instruction *NextInst = II->getNextNonDebugInstruction();
Philip Reames913a7792018-05-10 00:05:29 +00004188 for (unsigned i = 0; i < GuardWideningWindow; i++) {
Philip Reames79e917d2018-05-09 22:56:32 +00004189 // Note: Using context-free form to avoid compile time blow up
4190 if (!isSafeToSpeculativelyExecute(NextInst))
4191 break;
Davide Italianoc32f0ff2019-11-22 13:02:18 -08004192 NextInst = NextInst->getNextNonDebugInstruction();
Philip Reames79e917d2018-05-09 22:56:32 +00004193 }
Sanjoy Dase0e57952017-02-01 16:34:55 +00004194 Value *NextCond = nullptr;
4195 if (match(NextInst,
4196 m_Intrinsic<Intrinsic::experimental_guard>(m_Value(NextCond)))) {
4197 Value *CurrCond = II->getArgOperand(0);
Artur Pilipenkoe812ca02017-01-25 14:12:12 +00004198
Simon Pilgrim68168d12017-03-30 12:59:53 +00004199 // Remove a guard that it is immediately preceded by an identical guard.
Sanjoy Dase0e57952017-02-01 16:34:55 +00004200 // Otherwise canonicalize guard(a); guard(b) -> guard(a & b).
Nikita Popov04e58612020-01-11 15:10:50 +01004201 if (CurrCond != NextCond) {
4202 Instruction *MoveI = II->getNextNonDebugInstruction();
4203 while (MoveI != NextInst) {
4204 auto *Temp = MoveI;
4205 MoveI = MoveI->getNextNonDebugInstruction();
4206 Temp->moveBefore(II);
4207 }
4208 II->setArgOperand(0, Builder.CreateAnd(CurrCond, NextCond));
Philip Reames79e917d2018-05-09 22:56:32 +00004209 }
Nikita Popov04e58612020-01-11 15:10:50 +01004210 eraseInstFromFunction(*NextInst);
4211 return II;
Sanjoy Dase0e57952017-02-01 16:34:55 +00004212 }
Artur Pilipenkoe812ca02017-01-25 14:12:12 +00004213 break;
4214 }
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004215 }
Craig Topperc1892ec2019-01-31 17:23:29 +00004216 return visitCallBase(*II);
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004217}
4218
Davide Italianoaec46172017-01-31 18:09:05 +00004219// Fence instruction simplification
4220Instruction *InstCombiner::visitFenceInst(FenceInst &FI) {
4221 // Remove identical consecutive fences.
Vedant Kumarf01827f2018-06-19 23:42:17 +00004222 Instruction *Next = FI.getNextNonDebugInstruction();
Tim Northover9b800602018-06-06 12:46:02 +00004223 if (auto *NFI = dyn_cast<FenceInst>(Next))
Davide Italianoaec46172017-01-31 18:09:05 +00004224 if (FI.isIdenticalTo(NFI))
4225 return eraseInstFromFunction(FI);
4226 return nullptr;
4227}
4228
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004229// InvokeInst simplification
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004230Instruction *InstCombiner::visitInvokeInst(InvokeInst &II) {
Craig Topperc1892ec2019-01-31 17:23:29 +00004231 return visitCallBase(II);
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004232}
4233
Craig Topper784929d2019-02-08 20:48:56 +00004234// CallBrInst simplification
4235Instruction *InstCombiner::visitCallBrInst(CallBrInst &CBI) {
4236 return visitCallBase(CBI);
4237}
4238
Sanjay Patelcd4377c2016-01-20 22:24:38 +00004239/// If this cast does not affect the value passed through the varargs area, we
4240/// can eliminate the use of the cast.
Craig Topperc1892ec2019-01-31 17:23:29 +00004241static bool isSafeToEliminateVarargsCast(const CallBase &Call,
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004242 const DataLayout &DL,
4243 const CastInst *const CI,
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004244 const int ix) {
4245 if (!CI->isLosslessCast())
4246 return false;
4247
Philip Reames1a1bdb22014-12-02 18:50:36 +00004248 // If this is a GC intrinsic, avoid munging types. We need types for
4249 // statepoint reconstruction in SelectionDAG.
4250 // TODO: This is probably something which should be expanded to all
4251 // intrinsics since the entire point of intrinsics is that
4252 // they are understandable by the optimizer.
Craig Topperc1892ec2019-01-31 17:23:29 +00004253 if (isStatepoint(&Call) || isGCRelocate(&Call) || isGCResult(&Call))
Philip Reames1a1bdb22014-12-02 18:50:36 +00004254 return false;
4255
Reid Kleckner26af2ca2014-01-28 02:38:36 +00004256 // The size of ByVal or InAlloca arguments is derived from the type, so we
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004257 // can't change to a type with a different size. If the size were
4258 // passed explicitly we could avoid this check.
Craig Topperc1892ec2019-01-31 17:23:29 +00004259 if (!Call.isByValOrInAllocaArgument(ix))
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004260 return true;
4261
Jim Grosbach7815f562012-02-03 00:07:04 +00004262 Type* SrcTy =
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004263 cast<PointerType>(CI->getOperand(0)->getType())->getElementType();
Tim Northover8d7f1182019-06-05 20:38:17 +00004264 Type *DstTy = Call.isByValArgument(ix)
4265 ? Call.getParamByValType(ix)
4266 : cast<PointerType>(CI->getType())->getElementType();
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004267 if (!SrcTy->isSized() || !DstTy->isSized())
4268 return false;
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004269 if (DL.getTypeAllocSize(SrcTy) != DL.getTypeAllocSize(DstTy))
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004270 return false;
4271 return true;
4272}
4273
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004274Instruction *InstCombiner::tryOptimizeCall(CallInst *CI) {
Craig Topperf40110f2014-04-25 05:29:35 +00004275 if (!CI->getCalledFunction()) return nullptr;
Eric Christophera7fb58f2010-03-06 10:50:38 +00004276
Chandler Carruthba4c5172015-01-21 11:23:40 +00004277 auto InstCombineRAUW = [this](Instruction *From, Value *With) {
Sanjay Patel4b198802016-02-01 22:23:39 +00004278 replaceInstUsesWith(*From, With);
Chandler Carruthba4c5172015-01-21 11:23:40 +00004279 };
Amara Emerson54f60252018-10-11 14:51:11 +00004280 auto InstCombineErase = [this](Instruction *I) {
4281 eraseInstFromFunction(*I);
4282 };
Hiroshi Yamauchi09e539f2019-04-15 16:49:00 +00004283 LibCallSimplifier Simplifier(DL, &TLI, ORE, BFI, PSI, InstCombineRAUW,
Amara Emerson54f60252018-10-11 14:51:11 +00004284 InstCombineErase);
Chandler Carruthba4c5172015-01-21 11:23:40 +00004285 if (Value *With = Simplifier.optimizeCall(CI)) {
Meador Ingee3f2b262012-11-30 04:05:06 +00004286 ++NumSimplified;
Sanjay Patel4b198802016-02-01 22:23:39 +00004287 return CI->use_empty() ? CI : replaceInstUsesWith(*CI, With);
Meador Ingee3f2b262012-11-30 04:05:06 +00004288 }
Meador Ingedf796f82012-10-13 16:45:24 +00004289
Craig Topperf40110f2014-04-25 05:29:35 +00004290 return nullptr;
Eric Christophera7fb58f2010-03-06 10:50:38 +00004291}
4292
Sanjay Patel6038d3e2016-01-29 23:27:03 +00004293static IntrinsicInst *findInitTrampolineFromAlloca(Value *TrampMem) {
Duncan Sandsa0984362011-09-06 13:37:06 +00004294 // Strip off at most one level of pointer casts, looking for an alloca. This
4295 // is good enough in practice and simpler than handling any number of casts.
4296 Value *Underlying = TrampMem->stripPointerCasts();
4297 if (Underlying != TrampMem &&
Chandler Carruthcdf47882014-03-09 03:16:01 +00004298 (!Underlying->hasOneUse() || Underlying->user_back() != TrampMem))
Craig Topperf40110f2014-04-25 05:29:35 +00004299 return nullptr;
Duncan Sandsa0984362011-09-06 13:37:06 +00004300 if (!isa<AllocaInst>(Underlying))
Craig Topperf40110f2014-04-25 05:29:35 +00004301 return nullptr;
Duncan Sandsa0984362011-09-06 13:37:06 +00004302
Craig Topperf40110f2014-04-25 05:29:35 +00004303 IntrinsicInst *InitTrampoline = nullptr;
Chandler Carruthcdf47882014-03-09 03:16:01 +00004304 for (User *U : TrampMem->users()) {
4305 IntrinsicInst *II = dyn_cast<IntrinsicInst>(U);
Duncan Sandsa0984362011-09-06 13:37:06 +00004306 if (!II)
Craig Topperf40110f2014-04-25 05:29:35 +00004307 return nullptr;
Duncan Sandsa0984362011-09-06 13:37:06 +00004308 if (II->getIntrinsicID() == Intrinsic::init_trampoline) {
4309 if (InitTrampoline)
4310 // More than one init_trampoline writes to this value. Give up.
Craig Topperf40110f2014-04-25 05:29:35 +00004311 return nullptr;
Duncan Sandsa0984362011-09-06 13:37:06 +00004312 InitTrampoline = II;
4313 continue;
4314 }
4315 if (II->getIntrinsicID() == Intrinsic::adjust_trampoline)
4316 // Allow any number of calls to adjust.trampoline.
4317 continue;
Craig Topperf40110f2014-04-25 05:29:35 +00004318 return nullptr;
Duncan Sandsa0984362011-09-06 13:37:06 +00004319 }
4320
4321 // No call to init.trampoline found.
4322 if (!InitTrampoline)
Craig Topperf40110f2014-04-25 05:29:35 +00004323 return nullptr;
Duncan Sandsa0984362011-09-06 13:37:06 +00004324
4325 // Check that the alloca is being used in the expected way.
4326 if (InitTrampoline->getOperand(0) != TrampMem)
Craig Topperf40110f2014-04-25 05:29:35 +00004327 return nullptr;
Duncan Sandsa0984362011-09-06 13:37:06 +00004328
4329 return InitTrampoline;
4330}
4331
Sanjay Patel6038d3e2016-01-29 23:27:03 +00004332static IntrinsicInst *findInitTrampolineFromBB(IntrinsicInst *AdjustTramp,
Duncan Sandsa0984362011-09-06 13:37:06 +00004333 Value *TrampMem) {
4334 // Visit all the previous instructions in the basic block, and try to find a
4335 // init.trampoline which has a direct path to the adjust.trampoline.
Duncan P. N. Exon Smith9f8aaf22015-10-13 16:59:33 +00004336 for (BasicBlock::iterator I = AdjustTramp->getIterator(),
4337 E = AdjustTramp->getParent()->begin();
4338 I != E;) {
4339 Instruction *Inst = &*--I;
Duncan Sandsa0984362011-09-06 13:37:06 +00004340 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I))
4341 if (II->getIntrinsicID() == Intrinsic::init_trampoline &&
4342 II->getOperand(0) == TrampMem)
4343 return II;
4344 if (Inst->mayWriteToMemory())
Craig Topperf40110f2014-04-25 05:29:35 +00004345 return nullptr;
Duncan Sandsa0984362011-09-06 13:37:06 +00004346 }
Craig Topperf40110f2014-04-25 05:29:35 +00004347 return nullptr;
Duncan Sandsa0984362011-09-06 13:37:06 +00004348}
4349
4350// Given a call to llvm.adjust.trampoline, find and return the corresponding
4351// call to llvm.init.trampoline if the call to the trampoline can be optimized
4352// to a direct call to a function. Otherwise return NULL.
Sanjay Patel6038d3e2016-01-29 23:27:03 +00004353static IntrinsicInst *findInitTrampoline(Value *Callee) {
Duncan Sandsa0984362011-09-06 13:37:06 +00004354 Callee = Callee->stripPointerCasts();
4355 IntrinsicInst *AdjustTramp = dyn_cast<IntrinsicInst>(Callee);
4356 if (!AdjustTramp ||
4357 AdjustTramp->getIntrinsicID() != Intrinsic::adjust_trampoline)
Craig Topperf40110f2014-04-25 05:29:35 +00004358 return nullptr;
Duncan Sandsa0984362011-09-06 13:37:06 +00004359
4360 Value *TrampMem = AdjustTramp->getOperand(0);
4361
Sanjay Patel6038d3e2016-01-29 23:27:03 +00004362 if (IntrinsicInst *IT = findInitTrampolineFromAlloca(TrampMem))
Duncan Sandsa0984362011-09-06 13:37:06 +00004363 return IT;
Sanjay Patel6038d3e2016-01-29 23:27:03 +00004364 if (IntrinsicInst *IT = findInitTrampolineFromBB(AdjustTramp, TrampMem))
Duncan Sandsa0984362011-09-06 13:37:06 +00004365 return IT;
Craig Topperf40110f2014-04-25 05:29:35 +00004366 return nullptr;
Duncan Sandsa0984362011-09-06 13:37:06 +00004367}
4368
David Bolvansky05bda8b2019-08-28 08:28:20 +00004369static void annotateAnyAllocSite(CallBase &Call, const TargetLibraryInfo *TLI) {
David Bolvansky48db0272019-09-23 19:55:45 +00004370 unsigned NumArgs = Call.getNumArgOperands();
David Bolvansky05bda8b2019-08-28 08:28:20 +00004371 ConstantInt *Op0C = dyn_cast<ConstantInt>(Call.getOperand(0));
David Bolvansky48db0272019-09-23 19:55:45 +00004372 ConstantInt *Op1C =
4373 (NumArgs == 1) ? nullptr : dyn_cast<ConstantInt>(Call.getOperand(1));
David Bolvanskyaf118bb2019-08-28 15:04:48 +00004374 // Bail out if the allocation size is zero.
David Bolvansky05bda8b2019-08-28 08:28:20 +00004375 if ((Op0C && Op0C->isNullValue()) || (Op1C && Op1C->isNullValue()))
4376 return;
David Bolvanskyaf118bb2019-08-28 15:04:48 +00004377
David Bolvansky05bda8b2019-08-28 08:28:20 +00004378 if (isMallocLikeFn(&Call, TLI) && Op0C) {
David Bolvansky4dae2832019-09-11 10:37:03 +00004379 if (isOpNewLikeFn(&Call, TLI))
4380 Call.addAttribute(AttributeList::ReturnIndex,
4381 Attribute::getWithDereferenceableBytes(
4382 Call.getContext(), Op0C->getZExtValue()));
4383 else
4384 Call.addAttribute(AttributeList::ReturnIndex,
4385 Attribute::getWithDereferenceableOrNullBytes(
4386 Call.getContext(), Op0C->getZExtValue()));
David Bolvansky05bda8b2019-08-28 08:28:20 +00004387 } else if (isReallocLikeFn(&Call, TLI) && Op1C) {
4388 Call.addAttribute(AttributeList::ReturnIndex,
4389 Attribute::getWithDereferenceableOrNullBytes(
4390 Call.getContext(), Op1C->getZExtValue()));
4391 } else if (isCallocLikeFn(&Call, TLI) && Op0C && Op1C) {
4392 bool Overflow;
4393 const APInt &N = Op0C->getValue();
4394 APInt Size = N.umul_ov(Op1C->getValue(), Overflow);
4395 if (!Overflow)
4396 Call.addAttribute(AttributeList::ReturnIndex,
4397 Attribute::getWithDereferenceableOrNullBytes(
4398 Call.getContext(), Size.getZExtValue()));
David Bolvansky48db0272019-09-23 19:55:45 +00004399 } else if (isStrdupLikeFn(&Call, TLI)) {
4400 uint64_t Len = GetStringLength(Call.getOperand(0));
4401 if (Len) {
4402 // strdup
4403 if (NumArgs == 1)
4404 Call.addAttribute(AttributeList::ReturnIndex,
4405 Attribute::getWithDereferenceableOrNullBytes(
4406 Call.getContext(), Len));
4407 // strndup
4408 else if (NumArgs == 2 && Op1C)
4409 Call.addAttribute(
4410 AttributeList::ReturnIndex,
4411 Attribute::getWithDereferenceableOrNullBytes(
4412 Call.getContext(), std::min(Len, Op1C->getZExtValue() + 1)));
4413 }
David Bolvansky05bda8b2019-08-28 08:28:20 +00004414 }
4415}
4416
Craig Topper784929d2019-02-08 20:48:56 +00004417/// Improvements for call, callbr and invoke instructions.
Craig Topperc1892ec2019-01-31 17:23:29 +00004418Instruction *InstCombiner::visitCallBase(CallBase &Call) {
David Bolvansky05bda8b2019-08-28 08:28:20 +00004419 if (isAllocationFn(&Call, &TLI))
4420 annotateAnyAllocSite(Call, &TLI);
4421
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004422 bool Changed = false;
4423
Philip Reamesc25df112015-06-16 20:24:25 +00004424 // Mark any parameters that are known to be non-null with the nonnull
4425 // attribute. This is helpful for inlining calls to functions with null
4426 // checks on their arguments.
Reid Kleckner5fbdd172017-05-31 19:23:09 +00004427 SmallVector<unsigned, 4> ArgNos;
Philip Reamesc25df112015-06-16 20:24:25 +00004428 unsigned ArgNo = 0;
Akira Hatanaka237916b2015-12-02 06:58:49 +00004429
Craig Topperc1892ec2019-01-31 17:23:29 +00004430 for (Value *V : Call.args()) {
Sanjay Patelf9f5d3c2016-01-29 23:14:58 +00004431 if (V->getType()->isPointerTy() &&
Craig Topperc1892ec2019-01-31 17:23:29 +00004432 !Call.paramHasAttr(ArgNo, Attribute::NonNull) &&
4433 isKnownNonZero(V, DL, 0, &AC, &Call, &DT))
Reid Kleckner5fbdd172017-05-31 19:23:09 +00004434 ArgNos.push_back(ArgNo);
Philip Reamesc25df112015-06-16 20:24:25 +00004435 ArgNo++;
4436 }
Akira Hatanaka237916b2015-12-02 06:58:49 +00004437
Craig Topperc1892ec2019-01-31 17:23:29 +00004438 assert(ArgNo == Call.arg_size() && "sanity check");
Philip Reamesc25df112015-06-16 20:24:25 +00004439
Reid Kleckner5fbdd172017-05-31 19:23:09 +00004440 if (!ArgNos.empty()) {
Craig Topperc1892ec2019-01-31 17:23:29 +00004441 AttributeList AS = Call.getAttributes();
4442 LLVMContext &Ctx = Call.getContext();
Reid Kleckner5fbdd172017-05-31 19:23:09 +00004443 AS = AS.addParamAttribute(Ctx, ArgNos,
4444 Attribute::get(Ctx, Attribute::NonNull));
Craig Topperc1892ec2019-01-31 17:23:29 +00004445 Call.setAttributes(AS);
Akira Hatanaka237916b2015-12-02 06:58:49 +00004446 Changed = true;
4447 }
4448
Chris Lattner73989652010-12-20 08:25:06 +00004449 // If the callee is a pointer to a function, attempt to move any casts to the
Craig Topper784929d2019-02-08 20:48:56 +00004450 // arguments of the call/callbr/invoke.
Craig Topperc1892ec2019-01-31 17:23:29 +00004451 Value *Callee = Call.getCalledValue();
4452 if (!isa<Function>(Callee) && transformConstExprCastCall(Call))
Craig Topperf40110f2014-04-25 05:29:35 +00004453 return nullptr;
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004454
Justin Lebar9d943972016-03-14 20:18:54 +00004455 if (Function *CalleeF = dyn_cast<Function>(Callee)) {
4456 // Remove the convergent attr on calls when the callee is not convergent.
Craig Topperc1892ec2019-01-31 17:23:29 +00004457 if (Call.isConvergent() && !CalleeF->isConvergent() &&
Matt Arsenault802ebcb2016-06-20 19:04:44 +00004458 !CalleeF->isIntrinsic()) {
Craig Topperc1892ec2019-01-31 17:23:29 +00004459 LLVM_DEBUG(dbgs() << "Removing convergent attr from instr " << Call
4460 << "\n");
4461 Call.setNotConvergent();
4462 return &Call;
Justin Lebar9d943972016-03-14 20:18:54 +00004463 }
4464
Chris Lattner846a52e2010-02-01 18:11:34 +00004465 // If the call and callee calling conventions don't match, this call must
4466 // be unreachable, as the call is undefined.
Craig Topperc1892ec2019-01-31 17:23:29 +00004467 if (CalleeF->getCallingConv() != Call.getCallingConv() &&
Chris Lattner846a52e2010-02-01 18:11:34 +00004468 // Only do this for calls to a function with a body. A prototype may
4469 // not actually end up matching the implementation's calling conv for a
4470 // variety of reasons (e.g. it may be written in assembly).
4471 !CalleeF->isDeclaration()) {
Craig Topperc1892ec2019-01-31 17:23:29 +00004472 Instruction *OldCall = &Call;
Philip Reames88679712019-04-17 17:37:58 +00004473 CreateNonTerminatorUnreachable(OldCall);
Chad Rosiere28ae302012-12-13 00:18:46 +00004474 // If OldCall does not return void then replaceAllUsesWith undef.
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004475 // This allows ValueHandlers and custom metadata to adjust itself.
4476 if (!OldCall->getType()->isVoidTy())
Sanjay Patel4b198802016-02-01 22:23:39 +00004477 replaceInstUsesWith(*OldCall, UndefValue::get(OldCall->getType()));
Chris Lattner2cecedf2010-02-01 18:04:58 +00004478 if (isa<CallInst>(OldCall))
Sanjay Patel4b198802016-02-01 22:23:39 +00004479 return eraseInstFromFunction(*OldCall);
Jim Grosbach7815f562012-02-03 00:07:04 +00004480
Craig Topper784929d2019-02-08 20:48:56 +00004481 // We cannot remove an invoke or a callbr, because it would change thexi
4482 // CFG, just change the callee to a null pointer.
4483 cast<CallBase>(OldCall)->setCalledFunction(
James Y Knight291f7912019-02-01 20:44:54 +00004484 CalleeF->getFunctionType(),
4485 Constant::getNullValue(CalleeF->getType()));
Craig Topperf40110f2014-04-25 05:29:35 +00004486 return nullptr;
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004487 }
Justin Lebar9d943972016-03-14 20:18:54 +00004488 }
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004489
Manoj Gupta77eeac32018-07-09 22:27:23 +00004490 if ((isa<ConstantPointerNull>(Callee) &&
Craig Topperc1892ec2019-01-31 17:23:29 +00004491 !NullPointerIsDefined(Call.getFunction())) ||
Manoj Gupta77eeac32018-07-09 22:27:23 +00004492 isa<UndefValue>(Callee)) {
Craig Topperc1892ec2019-01-31 17:23:29 +00004493 // If Call does not return void then replaceAllUsesWith undef.
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004494 // This allows ValueHandlers and custom metadata to adjust itself.
Craig Topperc1892ec2019-01-31 17:23:29 +00004495 if (!Call.getType()->isVoidTy())
4496 replaceInstUsesWith(Call, UndefValue::get(Call.getType()));
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004497
Craig Topper784929d2019-02-08 20:48:56 +00004498 if (Call.isTerminator()) {
4499 // Can't remove an invoke or callbr because we cannot change the CFG.
Craig Topperf40110f2014-04-25 05:29:35 +00004500 return nullptr;
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004501 }
Nuno Lopes771e7bd2012-06-21 23:52:14 +00004502
Philip Reames88679712019-04-17 17:37:58 +00004503 // This instruction is not reachable, just remove it.
4504 CreateNonTerminatorUnreachable(&Call);
Craig Topperc1892ec2019-01-31 17:23:29 +00004505 return eraseInstFromFunction(Call);
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004506 }
4507
Sanjay Patel6038d3e2016-01-29 23:27:03 +00004508 if (IntrinsicInst *II = findInitTrampoline(Callee))
Craig Topperc1892ec2019-01-31 17:23:29 +00004509 return transformCallThroughTrampoline(Call, *II);
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004510
Chris Lattner229907c2011-07-18 04:54:35 +00004511 PointerType *PTy = cast<PointerType>(Callee->getType());
4512 FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004513 if (FTy->isVarArg()) {
Eli Friedman7534b4682011-11-29 01:18:23 +00004514 int ix = FTy->getNumParams();
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004515 // See if we can optimize any arguments passed through the varargs area of
4516 // the call.
Craig Topperc1892ec2019-01-31 17:23:29 +00004517 for (auto I = Call.arg_begin() + FTy->getNumParams(), E = Call.arg_end();
4518 I != E; ++I, ++ix) {
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004519 CastInst *CI = dyn_cast<CastInst>(*I);
Craig Topperc1892ec2019-01-31 17:23:29 +00004520 if (CI && isSafeToEliminateVarargsCast(Call, DL, CI, ix)) {
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004521 *I = CI->getOperand(0);
Tim Northover8d7f1182019-06-05 20:38:17 +00004522
4523 // Update the byval type to match the argument type.
4524 if (Call.isByValArgument(ix)) {
4525 Call.removeParamAttr(ix, Attribute::ByVal);
4526 Call.addParamAttr(
4527 ix, Attribute::getWithByValType(
4528 Call.getContext(),
4529 CI->getOperand(0)->getType()->getPointerElementType()));
4530 }
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004531 Changed = true;
4532 }
4533 }
4534 }
4535
Craig Topperc1892ec2019-01-31 17:23:29 +00004536 if (isa<InlineAsm>(Callee) && !Call.doesNotThrow()) {
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004537 // Inline asm calls cannot throw - mark them 'nounwind'.
Craig Topperc1892ec2019-01-31 17:23:29 +00004538 Call.setDoesNotThrow();
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004539 Changed = true;
4540 }
4541
Micah Villmowcdfe20b2012-10-08 16:38:25 +00004542 // Try to optimize the call if possible, we require DataLayout for most of
Eric Christophera7fb58f2010-03-06 10:50:38 +00004543 // this. None of these calls are seen as possibly dead so go ahead and
4544 // delete the instruction now.
Craig Topperc1892ec2019-01-31 17:23:29 +00004545 if (CallInst *CI = dyn_cast<CallInst>(&Call)) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004546 Instruction *I = tryOptimizeCall(CI);
Eric Christopher1810d772010-03-06 10:59:25 +00004547 // If we changed something return the result, etc. Otherwise let
4548 // the fallthrough check.
Sanjay Patel4b198802016-02-01 22:23:39 +00004549 if (I) return eraseInstFromFunction(*I);
Eric Christophera7fb58f2010-03-06 10:50:38 +00004550 }
4551
David Bolvansky8d520162019-09-23 18:20:01 +00004552 if (isAllocLikeFn(&Call, &TLI))
4553 return visitAllocSite(Call);
4554
Craig Topperc1892ec2019-01-31 17:23:29 +00004555 return Changed ? &Call : nullptr;
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004556}
4557
Sanjay Patelcd4377c2016-01-20 22:24:38 +00004558/// If the callee is a constexpr cast of a function, attempt to move the cast to
Craig Topper784929d2019-02-08 20:48:56 +00004559/// the arguments of the call/callbr/invoke.
Craig Topperc1892ec2019-01-31 17:23:29 +00004560bool InstCombiner::transformConstExprCastCall(CallBase &Call) {
4561 auto *Callee = dyn_cast<Function>(Call.getCalledValue()->stripPointerCasts());
Craig Topperf40110f2014-04-25 05:29:35 +00004562 if (!Callee)
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004563 return false;
Sanjay Patel38ae83d2016-08-11 15:23:56 +00004564
Reid Kleckner298ffc62018-04-02 22:49:44 +00004565 // If this is a call to a thunk function, don't remove the cast. Thunks are
4566 // used to transparently forward all incoming parameters and outgoing return
4567 // values, so it's important to leave the cast in place.
David Majnemer4c0a6e92015-01-21 22:32:04 +00004568 if (Callee->hasFnAttribute("thunk"))
4569 return false;
Sanjay Patel38ae83d2016-08-11 15:23:56 +00004570
Reid Kleckner298ffc62018-04-02 22:49:44 +00004571 // If this is a musttail call, the callee's prototype must match the caller's
4572 // prototype with the exception of pointee types. The code below doesn't
4573 // implement that, so we can't do this transform.
4574 // TODO: Do the transform if it only requires adding pointer casts.
Craig Topperc1892ec2019-01-31 17:23:29 +00004575 if (Call.isMustTailCall())
Reid Kleckner298ffc62018-04-02 22:49:44 +00004576 return false;
4577
Craig Topperc1892ec2019-01-31 17:23:29 +00004578 Instruction *Caller = &Call;
4579 const AttributeList &CallerPAL = Call.getAttributes();
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004580
4581 // Okay, this is a cast from a function to a different type. Unless doing so
4582 // would cause a type conversion of one of our arguments, change this call to
4583 // be a direct call with arguments casted to the appropriate types.
Chris Lattner229907c2011-07-18 04:54:35 +00004584 FunctionType *FT = Callee->getFunctionType();
4585 Type *OldRetTy = Caller->getType();
4586 Type *NewRetTy = FT->getReturnType();
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004587
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004588 // Check to see if we are changing the return type...
4589 if (OldRetTy != NewRetTy) {
Nick Lewyckya6a17d72014-01-18 22:47:12 +00004590
4591 if (NewRetTy->isStructTy())
4592 return false; // TODO: Handle multiple return values.
4593
David Majnemer9b6b8222015-01-06 08:41:31 +00004594 if (!CastInst::isBitOrNoopPointerCastable(NewRetTy, OldRetTy, DL)) {
Matt Arsenaulte6952f22013-09-17 21:10:14 +00004595 if (Callee->isDeclaration())
4596 return false; // Cannot transform this return value.
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004597
Matt Arsenaulte6952f22013-09-17 21:10:14 +00004598 if (!Caller->use_empty() &&
4599 // void -> non-void is handled specially
4600 !NewRetTy->isVoidTy())
Frederic Rissc1892e22014-10-23 04:08:42 +00004601 return false; // Cannot transform this return value.
Matt Arsenaulte6952f22013-09-17 21:10:14 +00004602 }
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004603
4604 if (!CallerPAL.isEmpty() && !Caller->use_empty()) {
Reid Klecknerb5180542017-03-21 16:57:19 +00004605 AttrBuilder RAttrs(CallerPAL, AttributeList::ReturnIndex);
Pete Cooper2777d8872015-05-06 23:19:56 +00004606 if (RAttrs.overlaps(AttributeFuncs::typeIncompatible(NewRetTy)))
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004607 return false; // Attribute not compatible with transformed value.
4608 }
4609
Craig Topper784929d2019-02-08 20:48:56 +00004610 // If the callbase is an invoke/callbr instruction, and the return value is
4611 // used by a PHI node in a successor, we cannot change the return type of
4612 // the call because there is no place to put the cast instruction (without
4613 // breaking the critical edge). Bail out in this case.
4614 if (!Caller->use_empty()) {
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004615 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller))
Chandler Carruthcdf47882014-03-09 03:16:01 +00004616 for (User *U : II->users())
4617 if (PHINode *PN = dyn_cast<PHINode>(U))
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004618 if (PN->getParent() == II->getNormalDest() ||
4619 PN->getParent() == II->getUnwindDest())
4620 return false;
Craig Topper784929d2019-02-08 20:48:56 +00004621 // FIXME: Be conservative for callbr to avoid a quadratic search.
Craig Toppera97857b2019-02-10 02:21:29 +00004622 if (isa<CallBrInst>(Caller))
Craig Topper784929d2019-02-08 20:48:56 +00004623 return false;
4624 }
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004625 }
4626
Craig Topperc1892ec2019-01-31 17:23:29 +00004627 unsigned NumActualArgs = Call.arg_size();
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004628 unsigned NumCommonArgs = std::min(FT->getNumParams(), NumActualArgs);
4629
David Majnemer9b6b8222015-01-06 08:41:31 +00004630 // Prevent us turning:
4631 // declare void @takes_i32_inalloca(i32* inalloca)
4632 // call void bitcast (void (i32*)* @takes_i32_inalloca to void (i32)*)(i32 0)
4633 //
4634 // into:
4635 // call void @takes_i32_inalloca(i32* null)
David Majnemerd61a6fd2015-03-11 18:03:05 +00004636 //
4637 // Similarly, avoid folding away bitcasts of byval calls.
4638 if (Callee->getAttributes().hasAttrSomewhere(Attribute::InAlloca) ||
4639 Callee->getAttributes().hasAttrSomewhere(Attribute::ByVal))
David Majnemer9b6b8222015-01-06 08:41:31 +00004640 return false;
4641
Craig Topperc1892ec2019-01-31 17:23:29 +00004642 auto AI = Call.arg_begin();
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004643 for (unsigned i = 0, e = NumCommonArgs; i != e; ++i, ++AI) {
Chris Lattner229907c2011-07-18 04:54:35 +00004644 Type *ParamTy = FT->getParamType(i);
4645 Type *ActTy = (*AI)->getType();
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004646
David Majnemer9b6b8222015-01-06 08:41:31 +00004647 if (!CastInst::isBitOrNoopPointerCastable(ActTy, ParamTy, DL))
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004648 return false; // Cannot transform this parameter value.
4649
Reid Klecknerf021fab2017-04-13 23:12:13 +00004650 if (AttrBuilder(CallerPAL.getParamAttributes(i))
4651 .overlaps(AttributeFuncs::typeIncompatible(ParamTy)))
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004652 return false; // Attribute not compatible with transformed value.
Jim Grosbach7815f562012-02-03 00:07:04 +00004653
Craig Topperc1892ec2019-01-31 17:23:29 +00004654 if (Call.isInAllocaArgument(i))
Reid Kleckner26af2ca2014-01-28 02:38:36 +00004655 return false; // Cannot transform to and from inalloca.
4656
Chris Lattner27ca8eb2010-12-20 08:36:38 +00004657 // If the parameter is passed as a byval argument, then we have to have a
4658 // sized type and the sized type has to have the same size as the old type.
Reid Klecknerf021fab2017-04-13 23:12:13 +00004659 if (ParamTy != ActTy && CallerPAL.hasParamAttribute(i, Attribute::ByVal)) {
Chris Lattner229907c2011-07-18 04:54:35 +00004660 PointerType *ParamPTy = dyn_cast<PointerType>(ParamTy);
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004661 if (!ParamPTy || !ParamPTy->getElementType()->isSized())
Chris Lattner27ca8eb2010-12-20 08:36:38 +00004662 return false;
Jim Grosbach7815f562012-02-03 00:07:04 +00004663
Tim Northover8d7f1182019-06-05 20:38:17 +00004664 Type *CurElTy = Call.getParamByValType(i);
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004665 if (DL.getTypeAllocSize(CurElTy) !=
4666 DL.getTypeAllocSize(ParamPTy->getElementType()))
Chris Lattner27ca8eb2010-12-20 08:36:38 +00004667 return false;
4668 }
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004669 }
4670
Chris Lattneradf38b32011-02-24 05:10:56 +00004671 if (Callee->isDeclaration()) {
4672 // Do not delete arguments unless we have a function body.
4673 if (FT->getNumParams() < NumActualArgs && !FT->isVarArg())
4674 return false;
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004675
Chris Lattneradf38b32011-02-24 05:10:56 +00004676 // If the callee is just a declaration, don't change the varargsness of the
4677 // call. We don't want to introduce a varargs call where one doesn't
4678 // already exist.
Craig Topperc1892ec2019-01-31 17:23:29 +00004679 PointerType *APTy = cast<PointerType>(Call.getCalledValue()->getType());
Chris Lattneradf38b32011-02-24 05:10:56 +00004680 if (FT->isVarArg()!=cast<FunctionType>(APTy->getElementType())->isVarArg())
4681 return false;
Jim Grosbache84ae7b2012-02-03 00:00:55 +00004682
4683 // If both the callee and the cast type are varargs, we still have to make
4684 // sure the number of fixed parameters are the same or we have the same
4685 // ABI issues as if we introduce a varargs call.
Jim Grosbach1df8cdc2012-02-03 00:26:07 +00004686 if (FT->isVarArg() &&
4687 cast<FunctionType>(APTy->getElementType())->isVarArg() &&
4688 FT->getNumParams() !=
Jim Grosbache84ae7b2012-02-03 00:00:55 +00004689 cast<FunctionType>(APTy->getElementType())->getNumParams())
4690 return false;
Chris Lattneradf38b32011-02-24 05:10:56 +00004691 }
Jim Grosbach7815f562012-02-03 00:07:04 +00004692
Jim Grosbach0ab54182012-02-03 00:00:50 +00004693 if (FT->getNumParams() < NumActualArgs && FT->isVarArg() &&
Reid Kleckneraa0cec72017-04-19 23:17:47 +00004694 !CallerPAL.isEmpty()) {
Jim Grosbach0ab54182012-02-03 00:00:50 +00004695 // In this case we have more arguments than the new function type, but we
4696 // won't be dropping them. Check that these extra arguments have attributes
4697 // that are compatible with being a vararg call argument.
Reid Kleckneraa0cec72017-04-19 23:17:47 +00004698 unsigned SRetIdx;
4699 if (CallerPAL.hasAttrSomewhere(Attribute::StructRet, &SRetIdx) &&
4700 SRetIdx > FT->getNumParams())
4701 return false;
4702 }
Jim Grosbach7815f562012-02-03 00:07:04 +00004703
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004704 // Okay, we decided that this is a safe thing to do: go ahead and start
Chris Lattneradf38b32011-02-24 05:10:56 +00004705 // inserting cast instructions as necessary.
Reid Klecknerc3fae792017-04-13 18:11:03 +00004706 SmallVector<Value *, 8> Args;
4707 SmallVector<AttributeSet, 8> ArgAttrs;
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004708 Args.reserve(NumActualArgs);
Reid Klecknerc3fae792017-04-13 18:11:03 +00004709 ArgAttrs.reserve(NumActualArgs);
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004710
4711 // Get any return attributes.
Reid Klecknerb5180542017-03-21 16:57:19 +00004712 AttrBuilder RAttrs(CallerPAL, AttributeList::ReturnIndex);
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004713
4714 // If the return value is not being used, the type may not be compatible
4715 // with the existing attributes. Wipe out any problematic attributes.
Pete Cooper2777d8872015-05-06 23:19:56 +00004716 RAttrs.remove(AttributeFuncs::typeIncompatible(NewRetTy));
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004717
Tim Northover8d7f1182019-06-05 20:38:17 +00004718 LLVMContext &Ctx = Call.getContext();
Craig Topperc1892ec2019-01-31 17:23:29 +00004719 AI = Call.arg_begin();
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004720 for (unsigned i = 0; i != NumCommonArgs; ++i, ++AI) {
Chris Lattner229907c2011-07-18 04:54:35 +00004721 Type *ParamTy = FT->getParamType(i);
Matt Arsenaultcacbb232013-07-30 20:45:05 +00004722
Reid Klecknerc3fae792017-04-13 18:11:03 +00004723 Value *NewArg = *AI;
4724 if ((*AI)->getType() != ParamTy)
Craig Topperbb4069e2017-07-07 23:16:26 +00004725 NewArg = Builder.CreateBitOrPointerCast(*AI, ParamTy);
Reid Klecknerc3fae792017-04-13 18:11:03 +00004726 Args.push_back(NewArg);
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004727
4728 // Add any parameter attributes.
Tim Northover8d7f1182019-06-05 20:38:17 +00004729 if (CallerPAL.hasParamAttribute(i, Attribute::ByVal)) {
4730 AttrBuilder AB(CallerPAL.getParamAttributes(i));
4731 AB.addByValAttr(NewArg->getType()->getPointerElementType());
4732 ArgAttrs.push_back(AttributeSet::get(Ctx, AB));
4733 } else
4734 ArgAttrs.push_back(CallerPAL.getParamAttributes(i));
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004735 }
4736
4737 // If the function takes more arguments than the call was taking, add them
4738 // now.
Reid Klecknerc3fae792017-04-13 18:11:03 +00004739 for (unsigned i = NumCommonArgs; i != FT->getNumParams(); ++i) {
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004740 Args.push_back(Constant::getNullValue(FT->getParamType(i)));
Reid Klecknerc3fae792017-04-13 18:11:03 +00004741 ArgAttrs.push_back(AttributeSet());
4742 }
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004743
4744 // If we are removing arguments to the function, emit an obnoxious warning.
4745 if (FT->getNumParams() < NumActualArgs) {
Nick Lewycky90053a12012-12-26 22:00:35 +00004746 // TODO: if (!FT->isVarArg()) this call may be unreachable. PR14722
4747 if (FT->isVarArg()) {
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004748 // Add all of the arguments in their promoted form to the arg list.
4749 for (unsigned i = FT->getNumParams(); i != NumActualArgs; ++i, ++AI) {
Chris Lattner229907c2011-07-18 04:54:35 +00004750 Type *PTy = getPromotedType((*AI)->getType());
Reid Klecknerc3fae792017-04-13 18:11:03 +00004751 Value *NewArg = *AI;
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004752 if (PTy != (*AI)->getType()) {
4753 // Must promote to pass through va_arg area!
4754 Instruction::CastOps opcode =
4755 CastInst::getCastOpcode(*AI, false, PTy, false);
Craig Topperbb4069e2017-07-07 23:16:26 +00004756 NewArg = Builder.CreateCast(opcode, *AI, PTy);
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004757 }
Reid Klecknerc3fae792017-04-13 18:11:03 +00004758 Args.push_back(NewArg);
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004759
4760 // Add any parameter attributes.
Reid Klecknerf021fab2017-04-13 23:12:13 +00004761 ArgAttrs.push_back(CallerPAL.getParamAttributes(i));
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004762 }
4763 }
4764 }
4765
Reid Klecknerc2cb5602017-04-12 00:38:00 +00004766 AttributeSet FnAttrs = CallerPAL.getFnAttributes();
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004767
4768 if (NewRetTy->isVoidTy())
4769 Caller->setName(""); // Void type should not have a name.
4770
Reid Klecknerc3fae792017-04-13 18:11:03 +00004771 assert((ArgAttrs.size() == FT->getNumParams() || FT->isVarArg()) &&
4772 "missing argument attributes");
Reid Klecknerc3fae792017-04-13 18:11:03 +00004773 AttributeList NewCallerPAL = AttributeList::get(
4774 Ctx, FnAttrs, AttributeSet::get(Ctx, RAttrs), ArgAttrs);
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004775
Sanjoy Das76293462015-11-25 00:42:19 +00004776 SmallVector<OperandBundleDef, 1> OpBundles;
Craig Topperc1892ec2019-01-31 17:23:29 +00004777 Call.getOperandBundlesAsDefs(OpBundles);
Sanjoy Das76293462015-11-25 00:42:19 +00004778
Craig Topperc1892ec2019-01-31 17:23:29 +00004779 CallBase *NewCall;
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004780 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Craig Topperc1892ec2019-01-31 17:23:29 +00004781 NewCall = Builder.CreateInvoke(Callee, II->getNormalDest(),
4782 II->getUnwindDest(), Args, OpBundles);
Craig Topper784929d2019-02-08 20:48:56 +00004783 } else if (CallBrInst *CBI = dyn_cast<CallBrInst>(Caller)) {
4784 NewCall = Builder.CreateCallBr(Callee, CBI->getDefaultDest(),
4785 CBI->getIndirectDests(), Args, OpBundles);
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004786 } else {
Craig Topperc1892ec2019-01-31 17:23:29 +00004787 NewCall = Builder.CreateCall(Callee, Args, OpBundles);
4788 cast<CallInst>(NewCall)->setTailCallKind(
4789 cast<CallInst>(Caller)->getTailCallKind());
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004790 }
Craig Topperc1892ec2019-01-31 17:23:29 +00004791 NewCall->takeName(Caller);
4792 NewCall->setCallingConv(Call.getCallingConv());
4793 NewCall->setAttributes(NewCallerPAL);
Reid Kleckner257cb4e2017-04-13 20:26:38 +00004794
4795 // Preserve the weight metadata for the new call instruction. The metadata
4796 // is used by SamplePGO to check callsite's hotness.
4797 uint64_t W;
4798 if (Caller->extractProfTotalWeight(W))
Craig Topperc1892ec2019-01-31 17:23:29 +00004799 NewCall->setProfWeight(W);
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004800
4801 // Insert a cast of the return type as necessary.
Craig Topperc1892ec2019-01-31 17:23:29 +00004802 Instruction *NC = NewCall;
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004803 Value *NV = NC;
4804 if (OldRetTy != NV->getType() && !Caller->use_empty()) {
4805 if (!NV->getType()->isVoidTy()) {
David Majnemer9b6b8222015-01-06 08:41:31 +00004806 NV = NC = CastInst::CreateBitOrPointerCast(NC, OldRetTy);
Eli Friedman35211c62011-05-27 00:19:40 +00004807 NC->setDebugLoc(Caller->getDebugLoc());
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004808
Craig Topper784929d2019-02-08 20:48:56 +00004809 // If this is an invoke/callbr instruction, we should insert it after the
4810 // first non-phi instruction in the normal successor block.
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004811 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Bill Wendling07efd6f2011-08-25 01:08:34 +00004812 BasicBlock::iterator I = II->getNormalDest()->getFirstInsertionPt();
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004813 InsertNewInstBefore(NC, *I);
Craig Topper784929d2019-02-08 20:48:56 +00004814 } else if (CallBrInst *CBI = dyn_cast<CallBrInst>(Caller)) {
4815 BasicBlock::iterator I = CBI->getDefaultDest()->getFirstInsertionPt();
4816 InsertNewInstBefore(NC, *I);
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004817 } else {
Chris Lattner73989652010-12-20 08:25:06 +00004818 // Otherwise, it's a call, just insert cast right after the call.
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004819 InsertNewInstBefore(NC, *Caller);
4820 }
4821 Worklist.AddUsersToWorkList(*Caller);
4822 } else {
4823 NV = UndefValue::get(Caller->getType());
4824 }
4825 }
4826
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004827 if (!Caller->use_empty())
Sanjay Patel4b198802016-02-01 22:23:39 +00004828 replaceInstUsesWith(*Caller, NV);
Frederic Rissc1892e22014-10-23 04:08:42 +00004829 else if (Caller->hasValueHandle()) {
4830 if (OldRetTy == NV->getType())
4831 ValueHandleBase::ValueIsRAUWd(Caller, NV);
4832 else
4833 // We cannot call ValueIsRAUWd with a different type, and the
4834 // actual tracked value will disappear.
4835 ValueHandleBase::ValueIsDeleted(Caller);
4836 }
Eli Friedmanb9ed18f2011-05-18 00:32:01 +00004837
Sanjay Patel4b198802016-02-01 22:23:39 +00004838 eraseInstFromFunction(*Caller);
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004839 return true;
4840}
4841
Sanjay Patelcd4377c2016-01-20 22:24:38 +00004842/// Turn a call to a function created by init_trampoline / adjust_trampoline
4843/// intrinsic pair into a direct call to the underlying function.
Duncan Sandsa0984362011-09-06 13:37:06 +00004844Instruction *
Craig Topperc1892ec2019-01-31 17:23:29 +00004845InstCombiner::transformCallThroughTrampoline(CallBase &Call,
4846 IntrinsicInst &Tramp) {
4847 Value *Callee = Call.getCalledValue();
James Y Knight291f7912019-02-01 20:44:54 +00004848 Type *CalleeTy = Callee->getType();
4849 FunctionType *FTy = Call.getFunctionType();
Craig Topperc1892ec2019-01-31 17:23:29 +00004850 AttributeList Attrs = Call.getAttributes();
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004851
4852 // If the call already has the 'nest' attribute somewhere then give up -
4853 // otherwise 'nest' would occur twice after splicing in the chain.
Bill Wendling6e95ae82012-12-31 00:49:59 +00004854 if (Attrs.hasAttrSomewhere(Attribute::Nest))
Craig Topperf40110f2014-04-25 05:29:35 +00004855 return nullptr;
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004856
Craig Topperc1892ec2019-01-31 17:23:29 +00004857 Function *NestF = cast<Function>(Tramp.getArgOperand(1)->stripPointerCasts());
James Y Knight291f7912019-02-01 20:44:54 +00004858 FunctionType *NestFTy = NestF->getFunctionType();
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004859
Reid Klecknereb9dd5b2017-04-10 23:31:05 +00004860 AttributeList NestAttrs = NestF->getAttributes();
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004861 if (!NestAttrs.isEmpty()) {
Reid Klecknerf021fab2017-04-13 23:12:13 +00004862 unsigned NestArgNo = 0;
Craig Topperf40110f2014-04-25 05:29:35 +00004863 Type *NestTy = nullptr;
Reid Klecknerc2cb5602017-04-12 00:38:00 +00004864 AttributeSet NestAttr;
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004865
4866 // Look for a parameter marked with the 'nest' attribute.
4867 for (FunctionType::param_iterator I = NestFTy->param_begin(),
Reid Klecknerf021fab2017-04-13 23:12:13 +00004868 E = NestFTy->param_end();
4869 I != E; ++NestArgNo, ++I) {
4870 AttributeSet AS = NestAttrs.getParamAttributes(NestArgNo);
4871 if (AS.hasAttribute(Attribute::Nest)) {
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004872 // Record the parameter type and any other attributes.
4873 NestTy = *I;
Reid Klecknerf021fab2017-04-13 23:12:13 +00004874 NestAttr = AS;
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004875 break;
4876 }
Reid Klecknerf021fab2017-04-13 23:12:13 +00004877 }
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004878
4879 if (NestTy) {
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004880 std::vector<Value*> NewArgs;
Reid Kleckner7f720332017-04-13 00:58:09 +00004881 std::vector<AttributeSet> NewArgAttrs;
Craig Topperc1892ec2019-01-31 17:23:29 +00004882 NewArgs.reserve(Call.arg_size() + 1);
4883 NewArgAttrs.reserve(Call.arg_size());
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004884
4885 // Insert the nest argument into the call argument list, which may
4886 // mean appending it. Likewise for attributes.
4887
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004888 {
Reid Klecknerf021fab2017-04-13 23:12:13 +00004889 unsigned ArgNo = 0;
Craig Topperc1892ec2019-01-31 17:23:29 +00004890 auto I = Call.arg_begin(), E = Call.arg_end();
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004891 do {
Reid Klecknerf021fab2017-04-13 23:12:13 +00004892 if (ArgNo == NestArgNo) {
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004893 // Add the chain argument and attributes.
Craig Topperc1892ec2019-01-31 17:23:29 +00004894 Value *NestVal = Tramp.getArgOperand(2);
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004895 if (NestVal->getType() != NestTy)
Craig Topperbb4069e2017-07-07 23:16:26 +00004896 NestVal = Builder.CreateBitCast(NestVal, NestTy, "nest");
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004897 NewArgs.push_back(NestVal);
Reid Kleckner7f720332017-04-13 00:58:09 +00004898 NewArgAttrs.push_back(NestAttr);
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004899 }
4900
4901 if (I == E)
4902 break;
4903
4904 // Add the original argument and attributes.
4905 NewArgs.push_back(*I);
Reid Klecknerf021fab2017-04-13 23:12:13 +00004906 NewArgAttrs.push_back(Attrs.getParamAttributes(ArgNo));
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004907
Reid Klecknerf021fab2017-04-13 23:12:13 +00004908 ++ArgNo;
Richard Trieu7a083812016-02-18 22:09:30 +00004909 ++I;
Eugene Zelenkocdc71612016-08-11 17:20:18 +00004910 } while (true);
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004911 }
4912
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004913 // The trampoline may have been bitcast to a bogus type (FTy).
4914 // Handle this by synthesizing a new function type, equal to FTy
4915 // with the chain parameter inserted.
4916
Jay Foadb804a2b2011-07-12 14:06:48 +00004917 std::vector<Type*> NewTypes;
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004918 NewTypes.reserve(FTy->getNumParams()+1);
4919
4920 // Insert the chain's type into the list of parameter types, which may
4921 // mean appending it.
4922 {
Reid Klecknerf021fab2017-04-13 23:12:13 +00004923 unsigned ArgNo = 0;
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004924 FunctionType::param_iterator I = FTy->param_begin(),
4925 E = FTy->param_end();
4926
4927 do {
Reid Klecknerf021fab2017-04-13 23:12:13 +00004928 if (ArgNo == NestArgNo)
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004929 // Add the chain's type.
4930 NewTypes.push_back(NestTy);
4931
4932 if (I == E)
4933 break;
4934
4935 // Add the original type.
4936 NewTypes.push_back(*I);
4937
Reid Klecknerf021fab2017-04-13 23:12:13 +00004938 ++ArgNo;
Richard Trieu7a083812016-02-18 22:09:30 +00004939 ++I;
Eugene Zelenkocdc71612016-08-11 17:20:18 +00004940 } while (true);
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004941 }
4942
4943 // Replace the trampoline call with a direct call. Let the generic
4944 // code sort out any function type mismatches.
Jim Grosbach7815f562012-02-03 00:07:04 +00004945 FunctionType *NewFTy = FunctionType::get(FTy->getReturnType(), NewTypes,
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004946 FTy->isVarArg());
4947 Constant *NewCallee =
4948 NestF->getType() == PointerType::getUnqual(NewFTy) ?
Jim Grosbach7815f562012-02-03 00:07:04 +00004949 NestF : ConstantExpr::getBitCast(NestF,
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004950 PointerType::getUnqual(NewFTy));
Reid Kleckner7f720332017-04-13 00:58:09 +00004951 AttributeList NewPAL =
4952 AttributeList::get(FTy->getContext(), Attrs.getFnAttributes(),
4953 Attrs.getRetAttributes(), NewArgAttrs);
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004954
David Majnemer231a68c2016-04-29 08:07:20 +00004955 SmallVector<OperandBundleDef, 1> OpBundles;
Craig Topperc1892ec2019-01-31 17:23:29 +00004956 Call.getOperandBundlesAsDefs(OpBundles);
David Majnemer231a68c2016-04-29 08:07:20 +00004957
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004958 Instruction *NewCaller;
Craig Topperc1892ec2019-01-31 17:23:29 +00004959 if (InvokeInst *II = dyn_cast<InvokeInst>(&Call)) {
James Y Knight7976eb52019-02-01 20:43:25 +00004960 NewCaller = InvokeInst::Create(NewFTy, NewCallee,
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004961 II->getNormalDest(), II->getUnwindDest(),
David Majnemer231a68c2016-04-29 08:07:20 +00004962 NewArgs, OpBundles);
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004963 cast<InvokeInst>(NewCaller)->setCallingConv(II->getCallingConv());
4964 cast<InvokeInst>(NewCaller)->setAttributes(NewPAL);
Craig Topper784929d2019-02-08 20:48:56 +00004965 } else if (CallBrInst *CBI = dyn_cast<CallBrInst>(&Call)) {
4966 NewCaller =
4967 CallBrInst::Create(NewFTy, NewCallee, CBI->getDefaultDest(),
4968 CBI->getIndirectDests(), NewArgs, OpBundles);
4969 cast<CallBrInst>(NewCaller)->setCallingConv(CBI->getCallingConv());
4970 cast<CallBrInst>(NewCaller)->setAttributes(NewPAL);
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004971 } else {
James Y Knight7976eb52019-02-01 20:43:25 +00004972 NewCaller = CallInst::Create(NewFTy, NewCallee, NewArgs, OpBundles);
David Majnemerd5648c72016-11-25 22:35:09 +00004973 cast<CallInst>(NewCaller)->setTailCallKind(
Craig Topperc1892ec2019-01-31 17:23:29 +00004974 cast<CallInst>(Call).getTailCallKind());
David Majnemerd5648c72016-11-25 22:35:09 +00004975 cast<CallInst>(NewCaller)->setCallingConv(
Craig Topperc1892ec2019-01-31 17:23:29 +00004976 cast<CallInst>(Call).getCallingConv());
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004977 cast<CallInst>(NewCaller)->setAttributes(NewPAL);
4978 }
Craig Topperc1892ec2019-01-31 17:23:29 +00004979 NewCaller->setDebugLoc(Call.getDebugLoc());
Eli Friedman49346012011-05-18 19:57:14 +00004980
4981 return NewCaller;
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004982 }
4983 }
4984
4985 // Replace the trampoline call with a direct call. Since there is no 'nest'
4986 // parameter, there is no need to adjust the argument list. Let the generic
4987 // code sort out any function type mismatches.
James Y Knight291f7912019-02-01 20:44:54 +00004988 Constant *NewCallee = ConstantExpr::getBitCast(NestF, CalleeTy);
4989 Call.setCalledFunction(FTy, NewCallee);
Craig Topperc1892ec2019-01-31 17:23:29 +00004990 return &Call;
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004991}