blob: e8b0d521ae7f71d47ab509503fd256619c5b3ced [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//
9// This file implements the visitCall and visitInvoke functions.
10//
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"
16#include "llvm/ADT/ArrayRef.h"
17#include "llvm/ADT/None.h"
Eugene Zelenko7f0f9bc2017-10-24 21:24:53 +000018#include "llvm/ADT/Optional.h"
Eugene Zelenkocdc71612016-08-11 17:20:18 +000019#include "llvm/ADT/STLExtras.h"
20#include "llvm/ADT/SmallVector.h"
Chandler Carruth6bda14b2017-06-06 11:49:48 +000021#include "llvm/ADT/Statistic.h"
Eugene Zelenkocdc71612016-08-11 17:20:18 +000022#include "llvm/ADT/Twine.h"
Eugene Zelenko7f0f9bc2017-10-24 21:24:53 +000023#include "llvm/Analysis/AssumptionCache.h"
David Majnemer15032582015-05-22 03:56:46 +000024#include "llvm/Analysis/InstructionSimplify.h"
Chris Lattner7a9e47a2010-01-05 07:32:13 +000025#include "llvm/Analysis/MemoryBuiltins.h"
David Blaikie31b98d22018-06-04 21:23:21 +000026#include "llvm/Transforms/Utils/Local.h"
Eugene Zelenkocdc71612016-08-11 17:20:18 +000027#include "llvm/Analysis/ValueTracking.h"
Eugene Zelenko7f0f9bc2017-10-24 21:24:53 +000028#include "llvm/IR/Attributes.h"
Eugene Zelenkocdc71612016-08-11 17:20:18 +000029#include "llvm/IR/BasicBlock.h"
Chandler Carruth219b89b2014-03-04 11:01:28 +000030#include "llvm/IR/CallSite.h"
Eugene Zelenkocdc71612016-08-11 17:20:18 +000031#include "llvm/IR/Constant.h"
Eugene Zelenko7f0f9bc2017-10-24 21:24:53 +000032#include "llvm/IR/Constants.h"
Eugene Zelenkocdc71612016-08-11 17:20:18 +000033#include "llvm/IR/DataLayout.h"
34#include "llvm/IR/DerivedTypes.h"
35#include "llvm/IR/Function.h"
36#include "llvm/IR/GlobalVariable.h"
37#include "llvm/IR/InstrTypes.h"
38#include "llvm/IR/Instruction.h"
39#include "llvm/IR/Instructions.h"
40#include "llvm/IR/IntrinsicInst.h"
41#include "llvm/IR/Intrinsics.h"
42#include "llvm/IR/LLVMContext.h"
43#include "llvm/IR/Metadata.h"
Chandler Carruth820a9082014-03-04 11:08:18 +000044#include "llvm/IR/PatternMatch.h"
Philip Reames1a1bdb22014-12-02 18:50:36 +000045#include "llvm/IR/Statepoint.h"
Eugene Zelenkocdc71612016-08-11 17:20:18 +000046#include "llvm/IR/Type.h"
Eugene Zelenko7f0f9bc2017-10-24 21:24:53 +000047#include "llvm/IR/User.h"
Eugene Zelenkocdc71612016-08-11 17:20:18 +000048#include "llvm/IR/Value.h"
49#include "llvm/IR/ValueHandle.h"
Eugene Zelenko7f0f9bc2017-10-24 21:24:53 +000050#include "llvm/Support/AtomicOrdering.h"
Eugene Zelenkocdc71612016-08-11 17:20:18 +000051#include "llvm/Support/Casting.h"
Eugene Zelenko7f0f9bc2017-10-24 21:24:53 +000052#include "llvm/Support/CommandLine.h"
53#include "llvm/Support/Compiler.h"
Eugene Zelenkocdc71612016-08-11 17:20:18 +000054#include "llvm/Support/Debug.h"
Eugene Zelenko7f0f9bc2017-10-24 21:24:53 +000055#include "llvm/Support/ErrorHandling.h"
Craig Topperb45eabc2017-04-26 16:39:58 +000056#include "llvm/Support/KnownBits.h"
Eugene Zelenkocdc71612016-08-11 17:20:18 +000057#include "llvm/Support/MathExtras.h"
Eugene Zelenko7f0f9bc2017-10-24 21:24:53 +000058#include "llvm/Support/raw_ostream.h"
59#include "llvm/Transforms/InstCombine/InstCombineWorklist.h"
Chandler Carruthba4c5172015-01-21 11:23:40 +000060#include "llvm/Transforms/Utils/SimplifyLibCalls.h"
Eugene Zelenkocdc71612016-08-11 17:20:18 +000061#include <algorithm>
62#include <cassert>
63#include <cstdint>
64#include <cstring>
Eugene Zelenko7f0f9bc2017-10-24 21:24:53 +000065#include <utility>
Eugene Zelenkocdc71612016-08-11 17:20:18 +000066#include <vector>
67
Chris Lattner7a9e47a2010-01-05 07:32:13 +000068using namespace llvm;
Michael Ilseman536cc322012-12-13 03:13:36 +000069using namespace PatternMatch;
Chris Lattner7a9e47a2010-01-05 07:32:13 +000070
Chandler Carruth964daaa2014-04-22 02:55:47 +000071#define DEBUG_TYPE "instcombine"
72
Meador Ingee3f2b262012-11-30 04:05:06 +000073STATISTIC(NumSimplified, "Number of library calls simplified");
74
Philip Reames79e917d2018-05-09 22:56:32 +000075static cl::opt<unsigned> GuardWideningWindow(
76 "instcombine-guard-widening-window",
77 cl::init(3),
78 cl::desc("How wide an instruction window to bypass looking for "
79 "another guard"));
80
Sanjay Patelcd4377c2016-01-20 22:24:38 +000081/// Return the specified type promoted as it would be to pass though a va_arg
82/// area.
Chris Lattner229907c2011-07-18 04:54:35 +000083static Type *getPromotedType(Type *Ty) {
84 if (IntegerType* ITy = dyn_cast<IntegerType>(Ty)) {
Chris Lattner7a9e47a2010-01-05 07:32:13 +000085 if (ITy->getBitWidth() < 32)
86 return Type::getInt32Ty(Ty->getContext());
87 }
88 return Ty;
89}
90
Sanjay Patel368ac5d2016-02-21 17:29:33 +000091/// Return a constant boolean vector that has true elements in all positions
Sanjay Patel24401302016-02-21 17:33:31 +000092/// where the input constant data vector has an element with the sign bit set.
Sanjay Patel368ac5d2016-02-21 17:29:33 +000093static Constant *getNegativeIsTrueBoolVec(ConstantDataVector *V) {
94 SmallVector<Constant *, 32> BoolVec;
95 IntegerType *BoolTy = Type::getInt1Ty(V->getContext());
96 for (unsigned I = 0, E = V->getNumElements(); I != E; ++I) {
97 Constant *Elt = V->getElementAsConstant(I);
98 assert((isa<ConstantInt>(Elt) || isa<ConstantFP>(Elt)) &&
99 "Unexpected constant data vector element type");
100 bool Sign = V->getElementType()->isIntegerTy()
101 ? cast<ConstantInt>(Elt)->isNegative()
102 : cast<ConstantFP>(Elt)->isNegative();
103 BoolVec.push_back(ConstantInt::get(BoolTy, Sign));
104 }
105 return ConstantVector::get(BoolVec);
106}
107
Daniel Neilson8f30ec62018-05-11 14:30:02 +0000108Instruction *InstCombiner::SimplifyAnyMemTransfer(AnyMemTransferInst *MI) {
Daniel Neilson2363da92018-02-12 23:06:55 +0000109 unsigned DstAlign = getKnownAlignment(MI->getRawDest(), DL, MI, &AC, &DT);
110 unsigned CopyDstAlign = MI->getDestAlignment();
111 if (CopyDstAlign < DstAlign){
112 MI->setDestAlignment(DstAlign);
113 return MI;
114 }
Chris Lattner7a9e47a2010-01-05 07:32:13 +0000115
Daniel Neilson8f30ec62018-05-11 14:30:02 +0000116 unsigned SrcAlign = getKnownAlignment(MI->getRawSource(), DL, MI, &AC, &DT);
117 unsigned CopySrcAlign = MI->getSourceAlignment();
Daniel Neilson2363da92018-02-12 23:06:55 +0000118 if (CopySrcAlign < SrcAlign) {
Daniel Neilson8f30ec62018-05-11 14:30:02 +0000119 MI->setSourceAlignment(SrcAlign);
Chris Lattner7a9e47a2010-01-05 07:32:13 +0000120 return MI;
121 }
Jim Grosbach7815f562012-02-03 00:07:04 +0000122
Chris Lattner7a9e47a2010-01-05 07:32:13 +0000123 // If MemCpyInst length is 1/2/4/8 bytes then replace memcpy with
124 // load/store.
Daniel Neilson8f30ec62018-05-11 14:30:02 +0000125 ConstantInt *MemOpLength = dyn_cast<ConstantInt>(MI->getLength());
Craig Topperf40110f2014-04-25 05:29:35 +0000126 if (!MemOpLength) return nullptr;
Jim Grosbach7815f562012-02-03 00:07:04 +0000127
Chris Lattner7a9e47a2010-01-05 07:32:13 +0000128 // Source and destination pointer types are always "i8*" for intrinsic. See
129 // if the size is something we can handle with a single primitive load/store.
130 // A single load+store correctly handles overlapping memory in the memmove
131 // case.
Michael Liao69e172a2012-08-15 03:49:59 +0000132 uint64_t Size = MemOpLength->getLimitedValue();
Alp Tokercb402912014-01-24 17:20:08 +0000133 assert(Size && "0-sized memory transferring should be removed already.");
Jim Grosbach7815f562012-02-03 00:07:04 +0000134
Chris Lattner7a9e47a2010-01-05 07:32:13 +0000135 if (Size > 8 || (Size&(Size-1)))
Craig Topperf40110f2014-04-25 05:29:35 +0000136 return nullptr; // If not 1/2/4/8 bytes, exit.
Jim Grosbach7815f562012-02-03 00:07:04 +0000137
Serguei Katkova5b0e552019-01-16 04:36:26 +0000138 // If it is an atomic and alignment is less than the size then we will
139 // introduce the unaligned memory access which will be later transformed
140 // into libcall in CodeGen. This is not evident performance gain so disable
141 // it now.
142 if (isa<AtomicMemTransferInst>(MI))
143 if (CopyDstAlign < Size || CopySrcAlign < Size)
144 return nullptr;
145
Chris Lattner7a9e47a2010-01-05 07:32:13 +0000146 // Use an integer load+store unless we can find something better.
Mon P Wangc576ee92010-04-04 03:10:48 +0000147 unsigned SrcAddrSp =
Gabor Greif0a136c92010-06-24 13:54:33 +0000148 cast<PointerType>(MI->getArgOperand(1)->getType())->getAddressSpace();
Gabor Greiff3755202010-04-16 15:33:14 +0000149 unsigned DstAddrSp =
Gabor Greif0a136c92010-06-24 13:54:33 +0000150 cast<PointerType>(MI->getArgOperand(0)->getType())->getAddressSpace();
Mon P Wangc576ee92010-04-04 03:10:48 +0000151
Chris Lattner229907c2011-07-18 04:54:35 +0000152 IntegerType* IntType = IntegerType::get(MI->getContext(), Size<<3);
Mon P Wangc576ee92010-04-04 03:10:48 +0000153 Type *NewSrcPtrTy = PointerType::get(IntType, SrcAddrSp);
154 Type *NewDstPtrTy = PointerType::get(IntType, DstAddrSp);
Jim Grosbach7815f562012-02-03 00:07:04 +0000155
Mikael Holmen760dc9a2017-03-01 06:45:20 +0000156 // If the memcpy has metadata describing the members, see if we can get the
157 // TBAA tag describing our copy.
Craig Topperf40110f2014-04-25 05:29:35 +0000158 MDNode *CopyMD = nullptr;
Ivan A. Kosarevf03f5792018-02-19 12:10:20 +0000159 if (MDNode *M = MI->getMetadata(LLVMContext::MD_tbaa)) {
160 CopyMD = M;
161 } else if (MDNode *M = MI->getMetadata(LLVMContext::MD_tbaa_struct)) {
Mikael Holmen760dc9a2017-03-01 06:45:20 +0000162 if (M->getNumOperands() == 3 && M->getOperand(0) &&
163 mdconst::hasa<ConstantInt>(M->getOperand(0)) &&
Craig Topper79ab6432017-07-06 18:39:47 +0000164 mdconst::extract<ConstantInt>(M->getOperand(0))->isZero() &&
Mikael Holmen760dc9a2017-03-01 06:45:20 +0000165 M->getOperand(1) &&
166 mdconst::hasa<ConstantInt>(M->getOperand(1)) &&
167 mdconst::extract<ConstantInt>(M->getOperand(1))->getValue() ==
168 Size &&
169 M->getOperand(2) && isa<MDNode>(M->getOperand(2)))
170 CopyMD = cast<MDNode>(M->getOperand(2));
Chris Lattner7a9e47a2010-01-05 07:32:13 +0000171 }
Jim Grosbach7815f562012-02-03 00:07:04 +0000172
Craig Topperbb4069e2017-07-07 23:16:26 +0000173 Value *Src = Builder.CreateBitCast(MI->getArgOperand(1), NewSrcPtrTy);
174 Value *Dest = Builder.CreateBitCast(MI->getArgOperand(0), NewDstPtrTy);
Daniel Neilson8f30ec62018-05-11 14:30:02 +0000175 LoadInst *L = Builder.CreateLoad(Src);
Daniel Neilson2363da92018-02-12 23:06:55 +0000176 // Alignment from the mem intrinsic will be better, so use it.
177 L->setAlignment(CopySrcAlign);
Dan Gohman3f553c22012-09-13 21:51:01 +0000178 if (CopyMD)
179 L->setMetadata(LLVMContext::MD_tbaa, CopyMD);
Dorit Nuzmanabd15f62016-09-04 07:49:39 +0000180 MDNode *LoopMemParallelMD =
181 MI->getMetadata(LLVMContext::MD_mem_parallel_loop_access);
182 if (LoopMemParallelMD)
183 L->setMetadata(LLVMContext::MD_mem_parallel_loop_access, LoopMemParallelMD);
Michael Kruse978ba612018-12-20 04:58:07 +0000184 MDNode *AccessGroupMD = MI->getMetadata(LLVMContext::MD_access_group);
185 if (AccessGroupMD)
186 L->setMetadata(LLVMContext::MD_access_group, AccessGroupMD);
Dorit Nuzman7673ba72016-09-04 07:06:00 +0000187
Daniel Neilson8f30ec62018-05-11 14:30:02 +0000188 StoreInst *S = Builder.CreateStore(L, Dest);
Daniel Neilson2363da92018-02-12 23:06:55 +0000189 // Alignment from the mem intrinsic will be better, so use it.
190 S->setAlignment(CopyDstAlign);
Dan Gohman3f553c22012-09-13 21:51:01 +0000191 if (CopyMD)
192 S->setMetadata(LLVMContext::MD_tbaa, CopyMD);
Dorit Nuzmanabd15f62016-09-04 07:49:39 +0000193 if (LoopMemParallelMD)
194 S->setMetadata(LLVMContext::MD_mem_parallel_loop_access, LoopMemParallelMD);
Michael Kruse978ba612018-12-20 04:58:07 +0000195 if (AccessGroupMD)
196 S->setMetadata(LLVMContext::MD_access_group, AccessGroupMD);
Chris Lattner7a9e47a2010-01-05 07:32:13 +0000197
Daniel Neilson8f30ec62018-05-11 14:30:02 +0000198 if (auto *MT = dyn_cast<MemTransferInst>(MI)) {
199 // non-atomics can be volatile
200 L->setVolatile(MT->isVolatile());
201 S->setVolatile(MT->isVolatile());
202 }
203 if (isa<AtomicMemTransferInst>(MI)) {
204 // atomics have to be unordered
205 L->setOrdering(AtomicOrdering::Unordered);
206 S->setOrdering(AtomicOrdering::Unordered);
207 }
208
Chris Lattner7a9e47a2010-01-05 07:32:13 +0000209 // Set the size of the copy to 0, it will be deleted on the next iteration.
Daniel Neilson8f30ec62018-05-11 14:30:02 +0000210 MI->setLength(Constant::getNullValue(MemOpLength->getType()));
Chris Lattner7a9e47a2010-01-05 07:32:13 +0000211 return MI;
212}
213
Daniel Neilsonf6651d42018-05-11 20:04:50 +0000214Instruction *InstCombiner::SimplifyAnyMemSet(AnyMemSetInst *MI) {
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000215 unsigned Alignment = getKnownAlignment(MI->getDest(), DL, MI, &AC, &DT);
Daniel Neilson38af2ee2018-02-02 22:03:03 +0000216 if (MI->getDestAlignment() < Alignment) {
217 MI->setDestAlignment(Alignment);
Chris Lattner7a9e47a2010-01-05 07:32:13 +0000218 return MI;
219 }
Jim Grosbach7815f562012-02-03 00:07:04 +0000220
Chris Lattner7a9e47a2010-01-05 07:32:13 +0000221 // Extract the length and alignment and fill if they are constant.
222 ConstantInt *LenC = dyn_cast<ConstantInt>(MI->getLength());
223 ConstantInt *FillC = dyn_cast<ConstantInt>(MI->getValue());
Duncan Sands9dff9be2010-02-15 16:12:20 +0000224 if (!LenC || !FillC || !FillC->getType()->isIntegerTy(8))
Craig Topperf40110f2014-04-25 05:29:35 +0000225 return nullptr;
Michael Liao69e172a2012-08-15 03:49:59 +0000226 uint64_t Len = LenC->getLimitedValue();
Daniel Neilson710d7b92018-03-22 18:36:15 +0000227 Alignment = MI->getDestAlignment();
Michael Liao69e172a2012-08-15 03:49:59 +0000228 assert(Len && "0-sized memory setting should be removed already.");
Jim Grosbach7815f562012-02-03 00:07:04 +0000229
Serguei Katkova5b0e552019-01-16 04:36:26 +0000230 // Alignment 0 is identity for alignment 1 for memset, but not store.
231 if (Alignment == 0)
232 Alignment = 1;
233
234 // If it is an atomic and alignment is less than the size then we will
235 // introduce the unaligned memory access which will be later transformed
236 // into libcall in CodeGen. This is not evident performance gain so disable
237 // it now.
238 if (isa<AtomicMemSetInst>(MI))
239 if (Alignment < Len)
240 return nullptr;
241
Chris Lattner7a9e47a2010-01-05 07:32:13 +0000242 // memset(s,c,n) -> store s, c (for n=1,2,4,8)
243 if (Len <= 8 && isPowerOf2_32((uint32_t)Len)) {
Chris Lattner229907c2011-07-18 04:54:35 +0000244 Type *ITy = IntegerType::get(MI->getContext(), Len*8); // n=1 -> i8.
Jim Grosbach7815f562012-02-03 00:07:04 +0000245
Chris Lattner7a9e47a2010-01-05 07:32:13 +0000246 Value *Dest = MI->getDest();
Mon P Wang1991c472010-12-20 01:05:30 +0000247 unsigned DstAddrSp = cast<PointerType>(Dest->getType())->getAddressSpace();
248 Type *NewDstPtrTy = PointerType::get(ITy, DstAddrSp);
Craig Topperbb4069e2017-07-07 23:16:26 +0000249 Dest = Builder.CreateBitCast(Dest, NewDstPtrTy);
Chris Lattner7a9e47a2010-01-05 07:32:13 +0000250
Chris Lattner7a9e47a2010-01-05 07:32:13 +0000251 // Extract the fill value and store.
252 uint64_t Fill = FillC->getZExtValue()*0x0101010101010101ULL;
Craig Topperbb4069e2017-07-07 23:16:26 +0000253 StoreInst *S = Builder.CreateStore(ConstantInt::get(ITy, Fill), Dest,
254 MI->isVolatile());
Eli Friedman49346012011-05-18 19:57:14 +0000255 S->setAlignment(Alignment);
Daniel Neilsonf6651d42018-05-11 20:04:50 +0000256 if (isa<AtomicMemSetInst>(MI))
257 S->setOrdering(AtomicOrdering::Unordered);
Jim Grosbach7815f562012-02-03 00:07:04 +0000258
Chris Lattner7a9e47a2010-01-05 07:32:13 +0000259 // Set the size of the copy to 0, it will be deleted on the next iteration.
260 MI->setLength(Constant::getNullValue(LenC->getType()));
261 return MI;
262 }
263
Simon Pilgrim18617d12015-08-05 08:18:00 +0000264 return nullptr;
265}
266
Sanjay Patel6038d3e2016-01-29 23:27:03 +0000267static Value *simplifyX86immShift(const IntrinsicInst &II,
Simon Pilgrimbecd5e82015-08-13 07:39:03 +0000268 InstCombiner::BuilderTy &Builder) {
269 bool LogicalShift = false;
270 bool ShiftLeft = false;
271
272 switch (II.getIntrinsicID()) {
Craig Topperb4173a52016-11-13 07:26:19 +0000273 default: llvm_unreachable("Unexpected intrinsic!");
Simon Pilgrimbecd5e82015-08-13 07:39:03 +0000274 case Intrinsic::x86_sse2_psra_d:
275 case Intrinsic::x86_sse2_psra_w:
276 case Intrinsic::x86_sse2_psrai_d:
277 case Intrinsic::x86_sse2_psrai_w:
278 case Intrinsic::x86_avx2_psra_d:
279 case Intrinsic::x86_avx2_psra_w:
280 case Intrinsic::x86_avx2_psrai_d:
281 case Intrinsic::x86_avx2_psrai_w:
Craig Topper8b831cb2016-11-13 01:51:55 +0000282 case Intrinsic::x86_avx512_psra_q_128:
283 case Intrinsic::x86_avx512_psrai_q_128:
284 case Intrinsic::x86_avx512_psra_q_256:
285 case Intrinsic::x86_avx512_psrai_q_256:
286 case Intrinsic::x86_avx512_psra_d_512:
287 case Intrinsic::x86_avx512_psra_q_512:
288 case Intrinsic::x86_avx512_psra_w_512:
289 case Intrinsic::x86_avx512_psrai_d_512:
290 case Intrinsic::x86_avx512_psrai_q_512:
291 case Intrinsic::x86_avx512_psrai_w_512:
Simon Pilgrimbecd5e82015-08-13 07:39:03 +0000292 LogicalShift = false; ShiftLeft = false;
293 break;
294 case Intrinsic::x86_sse2_psrl_d:
295 case Intrinsic::x86_sse2_psrl_q:
296 case Intrinsic::x86_sse2_psrl_w:
297 case Intrinsic::x86_sse2_psrli_d:
298 case Intrinsic::x86_sse2_psrli_q:
299 case Intrinsic::x86_sse2_psrli_w:
300 case Intrinsic::x86_avx2_psrl_d:
301 case Intrinsic::x86_avx2_psrl_q:
302 case Intrinsic::x86_avx2_psrl_w:
303 case Intrinsic::x86_avx2_psrli_d:
304 case Intrinsic::x86_avx2_psrli_q:
305 case Intrinsic::x86_avx2_psrli_w:
Craig Topper8b831cb2016-11-13 01:51:55 +0000306 case Intrinsic::x86_avx512_psrl_d_512:
307 case Intrinsic::x86_avx512_psrl_q_512:
308 case Intrinsic::x86_avx512_psrl_w_512:
309 case Intrinsic::x86_avx512_psrli_d_512:
310 case Intrinsic::x86_avx512_psrli_q_512:
311 case Intrinsic::x86_avx512_psrli_w_512:
Simon Pilgrimbecd5e82015-08-13 07:39:03 +0000312 LogicalShift = true; ShiftLeft = false;
313 break;
314 case Intrinsic::x86_sse2_psll_d:
315 case Intrinsic::x86_sse2_psll_q:
316 case Intrinsic::x86_sse2_psll_w:
317 case Intrinsic::x86_sse2_pslli_d:
318 case Intrinsic::x86_sse2_pslli_q:
319 case Intrinsic::x86_sse2_pslli_w:
320 case Intrinsic::x86_avx2_psll_d:
321 case Intrinsic::x86_avx2_psll_q:
322 case Intrinsic::x86_avx2_psll_w:
323 case Intrinsic::x86_avx2_pslli_d:
324 case Intrinsic::x86_avx2_pslli_q:
325 case Intrinsic::x86_avx2_pslli_w:
Craig Topper8b831cb2016-11-13 01:51:55 +0000326 case Intrinsic::x86_avx512_psll_d_512:
327 case Intrinsic::x86_avx512_psll_q_512:
328 case Intrinsic::x86_avx512_psll_w_512:
329 case Intrinsic::x86_avx512_pslli_d_512:
330 case Intrinsic::x86_avx512_pslli_q_512:
331 case Intrinsic::x86_avx512_pslli_w_512:
Simon Pilgrimbecd5e82015-08-13 07:39:03 +0000332 LogicalShift = true; ShiftLeft = true;
333 break;
334 }
Simon Pilgrima3a72b42015-08-10 20:21:15 +0000335 assert((LogicalShift || !ShiftLeft) && "Only logical shifts can shift left");
336
Simon Pilgrim3815c162015-08-07 18:22:50 +0000337 // Simplify if count is constant.
338 auto Arg1 = II.getArgOperand(1);
339 auto CAZ = dyn_cast<ConstantAggregateZero>(Arg1);
340 auto CDV = dyn_cast<ConstantDataVector>(Arg1);
341 auto CInt = dyn_cast<ConstantInt>(Arg1);
342 if (!CAZ && !CDV && !CInt)
Simon Pilgrim18617d12015-08-05 08:18:00 +0000343 return nullptr;
Simon Pilgrim3815c162015-08-07 18:22:50 +0000344
345 APInt Count(64, 0);
346 if (CDV) {
347 // SSE2/AVX2 uses all the first 64-bits of the 128-bit vector
348 // operand to compute the shift amount.
349 auto VT = cast<VectorType>(CDV->getType());
350 unsigned BitWidth = VT->getElementType()->getPrimitiveSizeInBits();
351 assert((64 % BitWidth) == 0 && "Unexpected packed shift size");
352 unsigned NumSubElts = 64 / BitWidth;
353
354 // Concatenate the sub-elements to create the 64-bit value.
355 for (unsigned i = 0; i != NumSubElts; ++i) {
356 unsigned SubEltIdx = (NumSubElts - 1) - i;
357 auto SubElt = cast<ConstantInt>(CDV->getElementAsConstant(SubEltIdx));
Craig Topper24e71012017-04-28 03:36:24 +0000358 Count <<= BitWidth;
Simon Pilgrim3815c162015-08-07 18:22:50 +0000359 Count |= SubElt->getValue().zextOrTrunc(64);
360 }
361 }
362 else if (CInt)
363 Count = CInt->getValue();
Simon Pilgrim18617d12015-08-05 08:18:00 +0000364
365 auto Vec = II.getArgOperand(0);
366 auto VT = cast<VectorType>(Vec->getType());
367 auto SVT = VT->getElementType();
Simon Pilgrim3815c162015-08-07 18:22:50 +0000368 unsigned VWidth = VT->getNumElements();
369 unsigned BitWidth = SVT->getPrimitiveSizeInBits();
370
371 // If shift-by-zero then just return the original value.
Craig Topper73ba1c82017-06-07 07:40:37 +0000372 if (Count.isNullValue())
Simon Pilgrim3815c162015-08-07 18:22:50 +0000373 return Vec;
374
Simon Pilgrima3a72b42015-08-10 20:21:15 +0000375 // Handle cases when Shift >= BitWidth.
376 if (Count.uge(BitWidth)) {
377 // If LogicalShift - just return zero.
378 if (LogicalShift)
379 return ConstantAggregateZero::get(VT);
380
381 // If ArithmeticShift - clamp Shift to (BitWidth - 1).
382 Count = APInt(64, BitWidth - 1);
383 }
Simon Pilgrim18617d12015-08-05 08:18:00 +0000384
Simon Pilgrim18617d12015-08-05 08:18:00 +0000385 // Get a constant vector of the same type as the first operand.
Simon Pilgrim3815c162015-08-07 18:22:50 +0000386 auto ShiftAmt = ConstantInt::get(SVT, Count.zextOrTrunc(BitWidth));
387 auto ShiftVec = Builder.CreateVectorSplat(VWidth, ShiftAmt);
Simon Pilgrim18617d12015-08-05 08:18:00 +0000388
389 if (ShiftLeft)
Simon Pilgrim3815c162015-08-07 18:22:50 +0000390 return Builder.CreateShl(Vec, ShiftVec);
Simon Pilgrim18617d12015-08-05 08:18:00 +0000391
Simon Pilgrima3a72b42015-08-10 20:21:15 +0000392 if (LogicalShift)
393 return Builder.CreateLShr(Vec, ShiftVec);
394
395 return Builder.CreateAShr(Vec, ShiftVec);
Simon Pilgrim18617d12015-08-05 08:18:00 +0000396}
397
Simon Pilgrimdb9893f2016-06-07 10:27:15 +0000398// Attempt to simplify AVX2 per-element shift intrinsics to a generic IR shift.
399// Unlike the generic IR shifts, the intrinsics have defined behaviour for out
400// of range shift amounts (logical - set to zero, arithmetic - splat sign bit).
401static Value *simplifyX86varShift(const IntrinsicInst &II,
402 InstCombiner::BuilderTy &Builder) {
403 bool LogicalShift = false;
404 bool ShiftLeft = false;
405
406 switch (II.getIntrinsicID()) {
Craig Topperb4173a52016-11-13 07:26:19 +0000407 default: llvm_unreachable("Unexpected intrinsic!");
Simon Pilgrimdb9893f2016-06-07 10:27:15 +0000408 case Intrinsic::x86_avx2_psrav_d:
409 case Intrinsic::x86_avx2_psrav_d_256:
Craig Topperb4173a52016-11-13 07:26:19 +0000410 case Intrinsic::x86_avx512_psrav_q_128:
411 case Intrinsic::x86_avx512_psrav_q_256:
412 case Intrinsic::x86_avx512_psrav_d_512:
413 case Intrinsic::x86_avx512_psrav_q_512:
Craig Topper1de753f2016-11-18 06:04:33 +0000414 case Intrinsic::x86_avx512_psrav_w_128:
415 case Intrinsic::x86_avx512_psrav_w_256:
416 case Intrinsic::x86_avx512_psrav_w_512:
Simon Pilgrimdb9893f2016-06-07 10:27:15 +0000417 LogicalShift = false;
418 ShiftLeft = false;
419 break;
420 case Intrinsic::x86_avx2_psrlv_d:
421 case Intrinsic::x86_avx2_psrlv_d_256:
422 case Intrinsic::x86_avx2_psrlv_q:
423 case Intrinsic::x86_avx2_psrlv_q_256:
Craig Topperb4173a52016-11-13 07:26:19 +0000424 case Intrinsic::x86_avx512_psrlv_d_512:
425 case Intrinsic::x86_avx512_psrlv_q_512:
Craig Topper1de753f2016-11-18 06:04:33 +0000426 case Intrinsic::x86_avx512_psrlv_w_128:
427 case Intrinsic::x86_avx512_psrlv_w_256:
428 case Intrinsic::x86_avx512_psrlv_w_512:
Simon Pilgrimdb9893f2016-06-07 10:27:15 +0000429 LogicalShift = true;
430 ShiftLeft = false;
431 break;
432 case Intrinsic::x86_avx2_psllv_d:
433 case Intrinsic::x86_avx2_psllv_d_256:
434 case Intrinsic::x86_avx2_psllv_q:
435 case Intrinsic::x86_avx2_psllv_q_256:
Craig Topperb4173a52016-11-13 07:26:19 +0000436 case Intrinsic::x86_avx512_psllv_d_512:
437 case Intrinsic::x86_avx512_psllv_q_512:
Craig Topper1de753f2016-11-18 06:04:33 +0000438 case Intrinsic::x86_avx512_psllv_w_128:
439 case Intrinsic::x86_avx512_psllv_w_256:
440 case Intrinsic::x86_avx512_psllv_w_512:
Simon Pilgrimdb9893f2016-06-07 10:27:15 +0000441 LogicalShift = true;
442 ShiftLeft = true;
443 break;
444 }
445 assert((LogicalShift || !ShiftLeft) && "Only logical shifts can shift left");
446
447 // Simplify if all shift amounts are constant/undef.
448 auto *CShift = dyn_cast<Constant>(II.getArgOperand(1));
449 if (!CShift)
450 return nullptr;
451
452 auto Vec = II.getArgOperand(0);
453 auto VT = cast<VectorType>(II.getType());
454 auto SVT = VT->getVectorElementType();
455 int NumElts = VT->getNumElements();
456 int BitWidth = SVT->getIntegerBitWidth();
457
458 // Collect each element's shift amount.
459 // We also collect special cases: UNDEF = -1, OUT-OF-RANGE = BitWidth.
460 bool AnyOutOfRange = false;
461 SmallVector<int, 8> ShiftAmts;
462 for (int I = 0; I < NumElts; ++I) {
463 auto *CElt = CShift->getAggregateElement(I);
464 if (CElt && isa<UndefValue>(CElt)) {
465 ShiftAmts.push_back(-1);
466 continue;
467 }
468
469 auto *COp = dyn_cast_or_null<ConstantInt>(CElt);
470 if (!COp)
471 return nullptr;
472
473 // Handle out of range shifts.
474 // If LogicalShift - set to BitWidth (special case).
475 // If ArithmeticShift - set to (BitWidth - 1) (sign splat).
476 APInt ShiftVal = COp->getValue();
477 if (ShiftVal.uge(BitWidth)) {
478 AnyOutOfRange = LogicalShift;
479 ShiftAmts.push_back(LogicalShift ? BitWidth : BitWidth - 1);
480 continue;
481 }
482
483 ShiftAmts.push_back((int)ShiftVal.getZExtValue());
484 }
485
486 // If all elements out of range or UNDEF, return vector of zeros/undefs.
487 // ArithmeticShift should only hit this if they are all UNDEF.
488 auto OutOfRange = [&](int Idx) { return (Idx < 0) || (BitWidth <= Idx); };
Eugene Zelenko7f0f9bc2017-10-24 21:24:53 +0000489 if (llvm::all_of(ShiftAmts, OutOfRange)) {
Simon Pilgrimdb9893f2016-06-07 10:27:15 +0000490 SmallVector<Constant *, 8> ConstantVec;
491 for (int Idx : ShiftAmts) {
492 if (Idx < 0) {
493 ConstantVec.push_back(UndefValue::get(SVT));
494 } else {
495 assert(LogicalShift && "Logical shift expected");
496 ConstantVec.push_back(ConstantInt::getNullValue(SVT));
497 }
498 }
499 return ConstantVector::get(ConstantVec);
500 }
501
502 // We can't handle only some out of range values with generic logical shifts.
503 if (AnyOutOfRange)
504 return nullptr;
505
506 // Build the shift amount constant vector.
507 SmallVector<Constant *, 8> ShiftVecAmts;
508 for (int Idx : ShiftAmts) {
509 if (Idx < 0)
510 ShiftVecAmts.push_back(UndefValue::get(SVT));
511 else
512 ShiftVecAmts.push_back(ConstantInt::get(SVT, Idx));
513 }
514 auto ShiftVec = ConstantVector::get(ShiftVecAmts);
515
516 if (ShiftLeft)
517 return Builder.CreateShl(Vec, ShiftVec);
518
519 if (LogicalShift)
520 return Builder.CreateLShr(Vec, ShiftVec);
521
522 return Builder.CreateAShr(Vec, ShiftVec);
523}
524
Craig Topper4853c432017-07-06 23:18:42 +0000525static Value *simplifyX86pack(IntrinsicInst &II, bool IsSigned) {
Simon Pilgrim6f6b2792017-01-25 14:37:24 +0000526 Value *Arg0 = II.getArgOperand(0);
527 Value *Arg1 = II.getArgOperand(1);
528 Type *ResTy = II.getType();
529
530 // Fast all undef handling.
531 if (isa<UndefValue>(Arg0) && isa<UndefValue>(Arg1))
532 return UndefValue::get(ResTy);
533
534 Type *ArgTy = Arg0->getType();
535 unsigned NumLanes = ResTy->getPrimitiveSizeInBits() / 128;
536 unsigned NumDstElts = ResTy->getVectorNumElements();
537 unsigned NumSrcElts = ArgTy->getVectorNumElements();
538 assert(NumDstElts == (2 * NumSrcElts) && "Unexpected packing types");
539
540 unsigned NumDstEltsPerLane = NumDstElts / NumLanes;
541 unsigned NumSrcEltsPerLane = NumSrcElts / NumLanes;
542 unsigned DstScalarSizeInBits = ResTy->getScalarSizeInBits();
543 assert(ArgTy->getScalarSizeInBits() == (2 * DstScalarSizeInBits) &&
544 "Unexpected packing types");
545
546 // Constant folding.
547 auto *Cst0 = dyn_cast<Constant>(Arg0);
548 auto *Cst1 = dyn_cast<Constant>(Arg1);
549 if (!Cst0 || !Cst1)
550 return nullptr;
551
552 SmallVector<Constant *, 32> Vals;
553 for (unsigned Lane = 0; Lane != NumLanes; ++Lane) {
554 for (unsigned Elt = 0; Elt != NumDstEltsPerLane; ++Elt) {
555 unsigned SrcIdx = Lane * NumSrcEltsPerLane + Elt % NumSrcEltsPerLane;
556 auto *Cst = (Elt >= NumSrcEltsPerLane) ? Cst1 : Cst0;
557 auto *COp = Cst->getAggregateElement(SrcIdx);
558 if (COp && isa<UndefValue>(COp)) {
559 Vals.push_back(UndefValue::get(ResTy->getScalarType()));
560 continue;
561 }
562
563 auto *CInt = dyn_cast_or_null<ConstantInt>(COp);
564 if (!CInt)
565 return nullptr;
566
567 APInt Val = CInt->getValue();
568 assert(Val.getBitWidth() == ArgTy->getScalarSizeInBits() &&
569 "Unexpected constant bitwidth");
570
571 if (IsSigned) {
572 // PACKSS: Truncate signed value with signed saturation.
573 // Source values less than dst minint are saturated to minint.
574 // Source values greater than dst maxint are saturated to maxint.
575 if (Val.isSignedIntN(DstScalarSizeInBits))
576 Val = Val.trunc(DstScalarSizeInBits);
577 else if (Val.isNegative())
578 Val = APInt::getSignedMinValue(DstScalarSizeInBits);
579 else
580 Val = APInt::getSignedMaxValue(DstScalarSizeInBits);
581 } else {
582 // PACKUS: Truncate signed value with unsigned saturation.
583 // Source values less than zero are saturated to zero.
584 // Source values greater than dst maxuint are saturated to maxuint.
585 if (Val.isIntN(DstScalarSizeInBits))
586 Val = Val.trunc(DstScalarSizeInBits);
587 else if (Val.isNegative())
588 Val = APInt::getNullValue(DstScalarSizeInBits);
589 else
590 Val = APInt::getAllOnesValue(DstScalarSizeInBits);
591 }
592
593 Vals.push_back(ConstantInt::get(ResTy->getScalarType(), Val));
594 }
595 }
596
597 return ConstantVector::get(Vals);
598}
599
Mikhail Dvoretckii8393f902018-06-19 10:49:12 +0000600// Replace X86-specific intrinsics with generic floor-ceil where applicable.
601static Value *simplifyX86round(IntrinsicInst &II,
602 InstCombiner::BuilderTy &Builder) {
603 ConstantInt *Arg = nullptr;
604 Intrinsic::ID IntrinsicID = II.getIntrinsicID();
605
606 if (IntrinsicID == Intrinsic::x86_sse41_round_ss ||
607 IntrinsicID == Intrinsic::x86_sse41_round_sd)
608 Arg = dyn_cast<ConstantInt>(II.getArgOperand(2));
609 else if (IntrinsicID == Intrinsic::x86_avx512_mask_rndscale_ss ||
610 IntrinsicID == Intrinsic::x86_avx512_mask_rndscale_sd)
611 Arg = dyn_cast<ConstantInt>(II.getArgOperand(4));
612 else
613 Arg = dyn_cast<ConstantInt>(II.getArgOperand(1));
614 if (!Arg)
615 return nullptr;
616 unsigned RoundControl = Arg->getZExtValue();
617
618 Arg = nullptr;
619 unsigned SAE = 0;
620 if (IntrinsicID == Intrinsic::x86_avx512_mask_rndscale_ps_512 ||
621 IntrinsicID == Intrinsic::x86_avx512_mask_rndscale_pd_512)
622 Arg = dyn_cast<ConstantInt>(II.getArgOperand(4));
623 else if (IntrinsicID == Intrinsic::x86_avx512_mask_rndscale_ss ||
624 IntrinsicID == Intrinsic::x86_avx512_mask_rndscale_sd)
625 Arg = dyn_cast<ConstantInt>(II.getArgOperand(5));
626 else
627 SAE = 4;
628 if (!SAE) {
629 if (!Arg)
630 return nullptr;
631 SAE = Arg->getZExtValue();
632 }
633
634 if (SAE != 4 || (RoundControl != 2 /*ceil*/ && RoundControl != 1 /*floor*/))
635 return nullptr;
636
637 Value *Src, *Dst, *Mask;
638 bool IsScalar = false;
639 if (IntrinsicID == Intrinsic::x86_sse41_round_ss ||
640 IntrinsicID == Intrinsic::x86_sse41_round_sd ||
641 IntrinsicID == Intrinsic::x86_avx512_mask_rndscale_ss ||
642 IntrinsicID == Intrinsic::x86_avx512_mask_rndscale_sd) {
643 IsScalar = true;
644 if (IntrinsicID == Intrinsic::x86_avx512_mask_rndscale_ss ||
645 IntrinsicID == Intrinsic::x86_avx512_mask_rndscale_sd) {
646 Mask = II.getArgOperand(3);
647 Value *Zero = Constant::getNullValue(Mask->getType());
648 Mask = Builder.CreateAnd(Mask, 1);
649 Mask = Builder.CreateICmp(ICmpInst::ICMP_NE, Mask, Zero);
650 Dst = II.getArgOperand(2);
651 } else
652 Dst = II.getArgOperand(0);
653 Src = Builder.CreateExtractElement(II.getArgOperand(1), (uint64_t)0);
654 } else {
655 Src = II.getArgOperand(0);
656 if (IntrinsicID == Intrinsic::x86_avx512_mask_rndscale_ps_128 ||
657 IntrinsicID == Intrinsic::x86_avx512_mask_rndscale_ps_256 ||
658 IntrinsicID == Intrinsic::x86_avx512_mask_rndscale_ps_512 ||
659 IntrinsicID == Intrinsic::x86_avx512_mask_rndscale_pd_128 ||
660 IntrinsicID == Intrinsic::x86_avx512_mask_rndscale_pd_256 ||
661 IntrinsicID == Intrinsic::x86_avx512_mask_rndscale_pd_512) {
662 Dst = II.getArgOperand(2);
663 Mask = II.getArgOperand(3);
664 } else {
665 Dst = Src;
666 Mask = ConstantInt::getAllOnesValue(
667 Builder.getIntNTy(Src->getType()->getVectorNumElements()));
668 }
669 }
670
671 Intrinsic::ID ID = (RoundControl == 2) ? Intrinsic::ceil : Intrinsic::floor;
Neil Henning57f5d0a2018-10-08 10:32:33 +0000672 Value *Res = Builder.CreateUnaryIntrinsic(ID, Src, &II);
Mikhail Dvoretckii8393f902018-06-19 10:49:12 +0000673 if (!IsScalar) {
674 if (auto *C = dyn_cast<Constant>(Mask))
675 if (C->isAllOnesValue())
676 return Res;
677 auto *MaskTy = VectorType::get(
678 Builder.getInt1Ty(), cast<IntegerType>(Mask->getType())->getBitWidth());
679 Mask = Builder.CreateBitCast(Mask, MaskTy);
680 unsigned Width = Src->getType()->getVectorNumElements();
681 if (MaskTy->getVectorNumElements() > Width) {
682 uint32_t Indices[4];
683 for (unsigned i = 0; i != Width; ++i)
684 Indices[i] = i;
685 Mask = Builder.CreateShuffleVector(Mask, Mask,
686 makeArrayRef(Indices, Width));
687 }
688 return Builder.CreateSelect(Mask, Res, Dst);
689 }
690 if (IntrinsicID == Intrinsic::x86_avx512_mask_rndscale_ss ||
691 IntrinsicID == Intrinsic::x86_avx512_mask_rndscale_sd) {
692 Dst = Builder.CreateExtractElement(Dst, (uint64_t)0);
693 Res = Builder.CreateSelect(Mask, Res, Dst);
694 Dst = II.getArgOperand(0);
695 }
696 return Builder.CreateInsertElement(Dst, Res, (uint64_t)0);
697}
698
Sanjay Patel2aa2dc72018-12-11 16:38:03 +0000699static Value *simplifyX86movmsk(const IntrinsicInst &II,
700 InstCombiner::BuilderTy &Builder) {
Simon Pilgrim91e3ac82016-06-07 08:18:35 +0000701 Value *Arg = II.getArgOperand(0);
702 Type *ResTy = II.getType();
703 Type *ArgTy = Arg->getType();
704
705 // movmsk(undef) -> zero as we must ensure the upper bits are zero.
706 if (isa<UndefValue>(Arg))
707 return Constant::getNullValue(ResTy);
708
709 // We can't easily peek through x86_mmx types.
710 if (!ArgTy->isVectorTy())
711 return nullptr;
712
Sanjay Patel2aa2dc72018-12-11 16:38:03 +0000713 if (auto *C = dyn_cast<Constant>(Arg)) {
714 // Extract signbits of the vector input and pack into integer result.
715 APInt Result(ResTy->getPrimitiveSizeInBits(), 0);
716 for (unsigned I = 0, E = ArgTy->getVectorNumElements(); I != E; ++I) {
717 auto *COp = C->getAggregateElement(I);
718 if (!COp)
719 return nullptr;
720 if (isa<UndefValue>(COp))
721 continue;
Simon Pilgrim91e3ac82016-06-07 08:18:35 +0000722
Sanjay Patel2aa2dc72018-12-11 16:38:03 +0000723 auto *CInt = dyn_cast<ConstantInt>(COp);
724 auto *CFp = dyn_cast<ConstantFP>(COp);
725 if (!CInt && !CFp)
726 return nullptr;
Simon Pilgrim91e3ac82016-06-07 08:18:35 +0000727
Sanjay Patel2aa2dc72018-12-11 16:38:03 +0000728 if ((CInt && CInt->isNegative()) || (CFp && CFp->isNegative()))
729 Result.setBit(I);
730 }
731 return Constant::getIntegerValue(ResTy, Result);
Simon Pilgrim91e3ac82016-06-07 08:18:35 +0000732 }
733
Sanjay Patel2aa2dc72018-12-11 16:38:03 +0000734 // Look for a sign-extended boolean source vector as the argument to this
735 // movmsk. If the argument is bitcast, look through that, but make sure the
736 // source of that bitcast is still a vector with the same number of elements.
737 // TODO: We can also convert a bitcast with wider elements, but that requires
738 // duplicating the bool source sign bits to match the number of elements
739 // expected by the movmsk call.
740 Arg = peekThroughBitcast(Arg);
741 Value *X;
742 if (Arg->getType()->isVectorTy() &&
743 Arg->getType()->getVectorNumElements() == ArgTy->getVectorNumElements() &&
744 match(Arg, m_SExt(m_Value(X))) && X->getType()->isIntOrIntVectorTy(1)) {
745 // call iM movmsk(sext <N x i1> X) --> zext (bitcast <N x i1> X to iN) to iM
746 unsigned NumElts = X->getType()->getVectorNumElements();
747 Type *ScalarTy = Type::getIntNTy(Arg->getContext(), NumElts);
748 Value *BC = Builder.CreateBitCast(X, ScalarTy);
749 return Builder.CreateZExtOrTrunc(BC, ResTy);
750 }
751
752 return nullptr;
Simon Pilgrim91e3ac82016-06-07 08:18:35 +0000753}
754
Sanjay Patel6038d3e2016-01-29 23:27:03 +0000755static Value *simplifyX86insertps(const IntrinsicInst &II,
Sanjay Patelc86867c2015-04-16 17:52:13 +0000756 InstCombiner::BuilderTy &Builder) {
Sanjay Patel03c03f52016-01-28 00:03:16 +0000757 auto *CInt = dyn_cast<ConstantInt>(II.getArgOperand(2));
758 if (!CInt)
759 return nullptr;
Simon Pilgrim54fcd622015-07-25 20:41:00 +0000760
Sanjay Patel03c03f52016-01-28 00:03:16 +0000761 VectorType *VecTy = cast<VectorType>(II.getType());
762 assert(VecTy->getNumElements() == 4 && "insertps with wrong vector type");
Sanjay Patelc86867c2015-04-16 17:52:13 +0000763
Sanjay Patel03c03f52016-01-28 00:03:16 +0000764 // The immediate permute control byte looks like this:
765 // [3:0] - zero mask for each 32-bit lane
766 // [5:4] - select one 32-bit destination lane
767 // [7:6] - select one 32-bit source lane
Sanjay Patelc86867c2015-04-16 17:52:13 +0000768
Sanjay Patel03c03f52016-01-28 00:03:16 +0000769 uint8_t Imm = CInt->getZExtValue();
770 uint8_t ZMask = Imm & 0xf;
771 uint8_t DestLane = (Imm >> 4) & 0x3;
772 uint8_t SourceLane = (Imm >> 6) & 0x3;
Sanjay Patelc1d20a32015-04-25 20:55:25 +0000773
Sanjay Patel03c03f52016-01-28 00:03:16 +0000774 ConstantAggregateZero *ZeroVector = ConstantAggregateZero::get(VecTy);
Sanjay Patelc86867c2015-04-16 17:52:13 +0000775
Sanjay Patel03c03f52016-01-28 00:03:16 +0000776 // If all zero mask bits are set, this was just a weird way to
777 // generate a zero vector.
778 if (ZMask == 0xf)
779 return ZeroVector;
Sanjay Patelc1d20a32015-04-25 20:55:25 +0000780
Sanjay Patel03c03f52016-01-28 00:03:16 +0000781 // Initialize by passing all of the first source bits through.
Craig Topper99d1eab2016-06-12 00:41:19 +0000782 uint32_t ShuffleMask[4] = { 0, 1, 2, 3 };
Sanjay Patelc1d20a32015-04-25 20:55:25 +0000783
Sanjay Patel03c03f52016-01-28 00:03:16 +0000784 // We may replace the second operand with the zero vector.
785 Value *V1 = II.getArgOperand(1);
786
787 if (ZMask) {
788 // If the zero mask is being used with a single input or the zero mask
789 // overrides the destination lane, this is a shuffle with the zero vector.
790 if ((II.getArgOperand(0) == II.getArgOperand(1)) ||
791 (ZMask & (1 << DestLane))) {
792 V1 = ZeroVector;
793 // We may still move 32-bits of the first source vector from one lane
794 // to another.
795 ShuffleMask[DestLane] = SourceLane;
796 // The zero mask may override the previous insert operation.
797 for (unsigned i = 0; i < 4; ++i)
798 if ((ZMask >> i) & 0x1)
799 ShuffleMask[i] = i + 4;
Sanjay Patelc1d20a32015-04-25 20:55:25 +0000800 } else {
Sanjay Patel03c03f52016-01-28 00:03:16 +0000801 // TODO: Model this case as 2 shuffles or a 'logical and' plus shuffle?
802 return nullptr;
Sanjay Patelc1d20a32015-04-25 20:55:25 +0000803 }
Sanjay Patel03c03f52016-01-28 00:03:16 +0000804 } else {
805 // Replace the selected destination lane with the selected source lane.
806 ShuffleMask[DestLane] = SourceLane + 4;
Sanjay Patelc86867c2015-04-16 17:52:13 +0000807 }
Sanjay Patel03c03f52016-01-28 00:03:16 +0000808
809 return Builder.CreateShuffleVector(II.getArgOperand(0), V1, ShuffleMask);
Sanjay Patelc86867c2015-04-16 17:52:13 +0000810}
811
Simon Pilgrim216b1bf2015-10-17 11:40:05 +0000812/// Attempt to simplify SSE4A EXTRQ/EXTRQI instructions using constant folding
813/// or conversion to a shuffle vector.
Sanjay Patel6038d3e2016-01-29 23:27:03 +0000814static Value *simplifyX86extrq(IntrinsicInst &II, Value *Op0,
Simon Pilgrim216b1bf2015-10-17 11:40:05 +0000815 ConstantInt *CILength, ConstantInt *CIIndex,
816 InstCombiner::BuilderTy &Builder) {
817 auto LowConstantHighUndef = [&](uint64_t Val) {
818 Type *IntTy64 = Type::getInt64Ty(II.getContext());
819 Constant *Args[] = {ConstantInt::get(IntTy64, Val),
820 UndefValue::get(IntTy64)};
821 return ConstantVector::get(Args);
822 };
823
824 // See if we're dealing with constant values.
825 Constant *C0 = dyn_cast<Constant>(Op0);
826 ConstantInt *CI0 =
Andrea Di Biagio8df5b9c2016-09-07 12:03:03 +0000827 C0 ? dyn_cast_or_null<ConstantInt>(C0->getAggregateElement((unsigned)0))
Simon Pilgrim216b1bf2015-10-17 11:40:05 +0000828 : nullptr;
829
830 // Attempt to constant fold.
831 if (CILength && CIIndex) {
832 // From AMD documentation: "The bit index and field length are each six
833 // bits in length other bits of the field are ignored."
834 APInt APIndex = CIIndex->getValue().zextOrTrunc(6);
835 APInt APLength = CILength->getValue().zextOrTrunc(6);
836
837 unsigned Index = APIndex.getZExtValue();
838
839 // From AMD documentation: "a value of zero in the field length is
840 // defined as length of 64".
841 unsigned Length = APLength == 0 ? 64 : APLength.getZExtValue();
842
843 // From AMD documentation: "If the sum of the bit index + length field
844 // is greater than 64, the results are undefined".
845 unsigned End = Index + Length;
846
847 // Note that both field index and field length are 8-bit quantities.
848 // Since variables 'Index' and 'Length' are unsigned values
849 // obtained from zero-extending field index and field length
850 // respectively, their sum should never wrap around.
851 if (End > 64)
852 return UndefValue::get(II.getType());
853
854 // If we are inserting whole bytes, we can convert this to a shuffle.
855 // Lowering can recognize EXTRQI shuffle masks.
856 if ((Length % 8) == 0 && (Index % 8) == 0) {
857 // Convert bit indices to byte indices.
858 Length /= 8;
859 Index /= 8;
860
861 Type *IntTy8 = Type::getInt8Ty(II.getContext());
862 Type *IntTy32 = Type::getInt32Ty(II.getContext());
863 VectorType *ShufTy = VectorType::get(IntTy8, 16);
864
865 SmallVector<Constant *, 16> ShuffleMask;
866 for (int i = 0; i != (int)Length; ++i)
867 ShuffleMask.push_back(
868 Constant::getIntegerValue(IntTy32, APInt(32, i + Index)));
869 for (int i = Length; i != 8; ++i)
870 ShuffleMask.push_back(
871 Constant::getIntegerValue(IntTy32, APInt(32, i + 16)));
872 for (int i = 8; i != 16; ++i)
873 ShuffleMask.push_back(UndefValue::get(IntTy32));
874
875 Value *SV = Builder.CreateShuffleVector(
876 Builder.CreateBitCast(Op0, ShufTy),
877 ConstantAggregateZero::get(ShufTy), ConstantVector::get(ShuffleMask));
878 return Builder.CreateBitCast(SV, II.getType());
879 }
880
881 // Constant Fold - shift Index'th bit to lowest position and mask off
882 // Length bits.
883 if (CI0) {
884 APInt Elt = CI0->getValue();
Craig Topperfc947bc2017-04-18 17:14:21 +0000885 Elt.lshrInPlace(Index);
886 Elt = Elt.zextOrTrunc(Length);
Simon Pilgrim216b1bf2015-10-17 11:40:05 +0000887 return LowConstantHighUndef(Elt.getZExtValue());
888 }
889
890 // If we were an EXTRQ call, we'll save registers if we convert to EXTRQI.
891 if (II.getIntrinsicID() == Intrinsic::x86_sse4a_extrq) {
892 Value *Args[] = {Op0, CILength, CIIndex};
Sanjay Patelaf674fb2015-12-14 17:24:23 +0000893 Module *M = II.getModule();
Simon Pilgrim216b1bf2015-10-17 11:40:05 +0000894 Value *F = Intrinsic::getDeclaration(M, Intrinsic::x86_sse4a_extrqi);
895 return Builder.CreateCall(F, Args);
896 }
897 }
898
899 // Constant Fold - extraction from zero is always {zero, undef}.
Craig Topperca2c8762017-07-06 18:39:49 +0000900 if (CI0 && CI0->isZero())
Simon Pilgrim216b1bf2015-10-17 11:40:05 +0000901 return LowConstantHighUndef(0);
902
903 return nullptr;
904}
905
906/// Attempt to simplify SSE4A INSERTQ/INSERTQI instructions using constant
907/// folding or conversion to a shuffle vector.
Sanjay Patel6038d3e2016-01-29 23:27:03 +0000908static Value *simplifyX86insertq(IntrinsicInst &II, Value *Op0, Value *Op1,
Simon Pilgrim216b1bf2015-10-17 11:40:05 +0000909 APInt APLength, APInt APIndex,
910 InstCombiner::BuilderTy &Builder) {
Simon Pilgrim216b1bf2015-10-17 11:40:05 +0000911 // From AMD documentation: "The bit index and field length are each six bits
912 // in length other bits of the field are ignored."
913 APIndex = APIndex.zextOrTrunc(6);
914 APLength = APLength.zextOrTrunc(6);
915
916 // Attempt to constant fold.
917 unsigned Index = APIndex.getZExtValue();
918
919 // From AMD documentation: "a value of zero in the field length is
920 // defined as length of 64".
921 unsigned Length = APLength == 0 ? 64 : APLength.getZExtValue();
922
923 // From AMD documentation: "If the sum of the bit index + length field
924 // is greater than 64, the results are undefined".
925 unsigned End = Index + Length;
926
927 // Note that both field index and field length are 8-bit quantities.
928 // Since variables 'Index' and 'Length' are unsigned values
929 // obtained from zero-extending field index and field length
930 // respectively, their sum should never wrap around.
931 if (End > 64)
932 return UndefValue::get(II.getType());
933
934 // If we are inserting whole bytes, we can convert this to a shuffle.
935 // Lowering can recognize INSERTQI shuffle masks.
936 if ((Length % 8) == 0 && (Index % 8) == 0) {
937 // Convert bit indices to byte indices.
938 Length /= 8;
939 Index /= 8;
940
941 Type *IntTy8 = Type::getInt8Ty(II.getContext());
942 Type *IntTy32 = Type::getInt32Ty(II.getContext());
943 VectorType *ShufTy = VectorType::get(IntTy8, 16);
944
945 SmallVector<Constant *, 16> ShuffleMask;
946 for (int i = 0; i != (int)Index; ++i)
947 ShuffleMask.push_back(Constant::getIntegerValue(IntTy32, APInt(32, i)));
948 for (int i = 0; i != (int)Length; ++i)
949 ShuffleMask.push_back(
950 Constant::getIntegerValue(IntTy32, APInt(32, i + 16)));
951 for (int i = Index + Length; i != 8; ++i)
952 ShuffleMask.push_back(Constant::getIntegerValue(IntTy32, APInt(32, i)));
953 for (int i = 8; i != 16; ++i)
954 ShuffleMask.push_back(UndefValue::get(IntTy32));
955
956 Value *SV = Builder.CreateShuffleVector(Builder.CreateBitCast(Op0, ShufTy),
957 Builder.CreateBitCast(Op1, ShufTy),
958 ConstantVector::get(ShuffleMask));
959 return Builder.CreateBitCast(SV, II.getType());
960 }
961
962 // See if we're dealing with constant values.
963 Constant *C0 = dyn_cast<Constant>(Op0);
964 Constant *C1 = dyn_cast<Constant>(Op1);
965 ConstantInt *CI00 =
Andrea Di Biagiof3fd3162016-09-07 12:47:53 +0000966 C0 ? dyn_cast_or_null<ConstantInt>(C0->getAggregateElement((unsigned)0))
Simon Pilgrim216b1bf2015-10-17 11:40:05 +0000967 : nullptr;
968 ConstantInt *CI10 =
Andrea Di Biagiof3fd3162016-09-07 12:47:53 +0000969 C1 ? dyn_cast_or_null<ConstantInt>(C1->getAggregateElement((unsigned)0))
Simon Pilgrim216b1bf2015-10-17 11:40:05 +0000970 : nullptr;
971
972 // Constant Fold - insert bottom Length bits starting at the Index'th bit.
973 if (CI00 && CI10) {
974 APInt V00 = CI00->getValue();
975 APInt V10 = CI10->getValue();
976 APInt Mask = APInt::getLowBitsSet(64, Length).shl(Index);
977 V00 = V00 & ~Mask;
978 V10 = V10.zextOrTrunc(Length).zextOrTrunc(64).shl(Index);
979 APInt Val = V00 | V10;
980 Type *IntTy64 = Type::getInt64Ty(II.getContext());
981 Constant *Args[] = {ConstantInt::get(IntTy64, Val.getZExtValue()),
982 UndefValue::get(IntTy64)};
983 return ConstantVector::get(Args);
984 }
985
986 // If we were an INSERTQ call, we'll save demanded elements if we convert to
987 // INSERTQI.
988 if (II.getIntrinsicID() == Intrinsic::x86_sse4a_insertq) {
989 Type *IntTy8 = Type::getInt8Ty(II.getContext());
990 Constant *CILength = ConstantInt::get(IntTy8, Length, false);
991 Constant *CIIndex = ConstantInt::get(IntTy8, Index, false);
992
993 Value *Args[] = {Op0, Op1, CILength, CIIndex};
Sanjay Patelaf674fb2015-12-14 17:24:23 +0000994 Module *M = II.getModule();
Simon Pilgrim216b1bf2015-10-17 11:40:05 +0000995 Value *F = Intrinsic::getDeclaration(M, Intrinsic::x86_sse4a_insertqi);
996 return Builder.CreateCall(F, Args);
997 }
998
999 return nullptr;
1000}
1001
Simon Pilgrimc0c56e72016-04-24 17:00:34 +00001002/// Attempt to convert pshufb* to shufflevector if the mask is constant.
1003static Value *simplifyX86pshufb(const IntrinsicInst &II,
1004 InstCombiner::BuilderTy &Builder) {
Simon Pilgrimbf60cc42016-04-29 21:34:54 +00001005 Constant *V = dyn_cast<Constant>(II.getArgOperand(1));
1006 if (!V)
1007 return nullptr;
1008
Simon Pilgrime5e8c2f2016-05-01 19:26:21 +00001009 auto *VecTy = cast<VectorType>(II.getType());
1010 auto *MaskEltTy = Type::getInt32Ty(II.getContext());
1011 unsigned NumElts = VecTy->getNumElements();
Craig Topper9a63d7a2016-12-11 00:23:50 +00001012 assert((NumElts == 16 || NumElts == 32 || NumElts == 64) &&
Simon Pilgrimc0c56e72016-04-24 17:00:34 +00001013 "Unexpected number of elements in shuffle mask!");
Simon Pilgrimbf60cc42016-04-29 21:34:54 +00001014
Simon Pilgrime5e8c2f2016-05-01 19:26:21 +00001015 // Construct a shuffle mask from constant integers or UNDEFs.
Craig Topper9a63d7a2016-12-11 00:23:50 +00001016 Constant *Indexes[64] = {nullptr};
Simon Pilgrimc0c56e72016-04-24 17:00:34 +00001017
Simon Pilgrimbf60cc42016-04-29 21:34:54 +00001018 // Each byte in the shuffle control mask forms an index to permute the
1019 // corresponding byte in the destination operand.
1020 for (unsigned I = 0; I < NumElts; ++I) {
1021 Constant *COp = V->getAggregateElement(I);
Simon Pilgrime5e8c2f2016-05-01 19:26:21 +00001022 if (!COp || (!isa<UndefValue>(COp) && !isa<ConstantInt>(COp)))
Simon Pilgrimbf60cc42016-04-29 21:34:54 +00001023 return nullptr;
Simon Pilgrimc0c56e72016-04-24 17:00:34 +00001024
Simon Pilgrime5e8c2f2016-05-01 19:26:21 +00001025 if (isa<UndefValue>(COp)) {
1026 Indexes[I] = UndefValue::get(MaskEltTy);
1027 continue;
1028 }
1029
Simon Pilgrimbf60cc42016-04-29 21:34:54 +00001030 int8_t Index = cast<ConstantInt>(COp)->getValue().getZExtValue();
1031
1032 // If the most significant bit (bit[7]) of each byte of the shuffle
1033 // control mask is set, then zero is written in the result byte.
1034 // The zero vector is in the right-hand side of the resulting
1035 // shufflevector.
1036
Simon Pilgrime5e8c2f2016-05-01 19:26:21 +00001037 // The value of each index for the high 128-bit lane is the least
1038 // significant 4 bits of the respective shuffle control byte.
1039 Index = ((Index < 0) ? NumElts : Index & 0x0F) + (I & 0xF0);
1040 Indexes[I] = ConstantInt::get(MaskEltTy, Index);
Simon Pilgrimbf60cc42016-04-29 21:34:54 +00001041 }
Simon Pilgrimc0c56e72016-04-24 17:00:34 +00001042
Simon Pilgrime5e8c2f2016-05-01 19:26:21 +00001043 auto ShuffleMask = ConstantVector::get(makeArrayRef(Indexes, NumElts));
Simon Pilgrimc0c56e72016-04-24 17:00:34 +00001044 auto V1 = II.getArgOperand(0);
Simon Pilgrime5e8c2f2016-05-01 19:26:21 +00001045 auto V2 = Constant::getNullValue(VecTy);
Simon Pilgrimc0c56e72016-04-24 17:00:34 +00001046 return Builder.CreateShuffleVector(V1, V2, ShuffleMask);
1047}
1048
Simon Pilgrim2f6097d2016-04-24 17:23:46 +00001049/// Attempt to convert vpermilvar* to shufflevector if the mask is constant.
1050static Value *simplifyX86vpermilvar(const IntrinsicInst &II,
1051 InstCombiner::BuilderTy &Builder) {
Simon Pilgrim640f9962016-04-30 07:23:30 +00001052 Constant *V = dyn_cast<Constant>(II.getArgOperand(1));
1053 if (!V)
1054 return nullptr;
Simon Pilgrim2f6097d2016-04-24 17:23:46 +00001055
Craig Topper58917f32016-12-11 01:59:36 +00001056 auto *VecTy = cast<VectorType>(II.getType());
Simon Pilgrimeeacc402016-05-01 20:22:42 +00001057 auto *MaskEltTy = Type::getInt32Ty(II.getContext());
Craig Topper58917f32016-12-11 01:59:36 +00001058 unsigned NumElts = VecTy->getVectorNumElements();
1059 bool IsPD = VecTy->getScalarType()->isDoubleTy();
1060 unsigned NumLaneElts = IsPD ? 2 : 4;
1061 assert(NumElts == 16 || NumElts == 8 || NumElts == 4 || NumElts == 2);
Simon Pilgrim2f6097d2016-04-24 17:23:46 +00001062
Simon Pilgrimeeacc402016-05-01 20:22:42 +00001063 // Construct a shuffle mask from constant integers or UNDEFs.
Craig Topper58917f32016-12-11 01:59:36 +00001064 Constant *Indexes[16] = {nullptr};
Simon Pilgrim640f9962016-04-30 07:23:30 +00001065
1066 // The intrinsics only read one or two bits, clear the rest.
Simon Pilgrimeeacc402016-05-01 20:22:42 +00001067 for (unsigned I = 0; I < NumElts; ++I) {
Simon Pilgrim640f9962016-04-30 07:23:30 +00001068 Constant *COp = V->getAggregateElement(I);
Simon Pilgrimeeacc402016-05-01 20:22:42 +00001069 if (!COp || (!isa<UndefValue>(COp) && !isa<ConstantInt>(COp)))
Simon Pilgrim640f9962016-04-30 07:23:30 +00001070 return nullptr;
1071
Simon Pilgrimeeacc402016-05-01 20:22:42 +00001072 if (isa<UndefValue>(COp)) {
1073 Indexes[I] = UndefValue::get(MaskEltTy);
1074 continue;
1075 }
1076
1077 APInt Index = cast<ConstantInt>(COp)->getValue();
1078 Index = Index.zextOrTrunc(32).getLoBits(2);
Simon Pilgrim640f9962016-04-30 07:23:30 +00001079
1080 // The PD variants uses bit 1 to select per-lane element index, so
1081 // shift down to convert to generic shuffle mask index.
Craig Topper58917f32016-12-11 01:59:36 +00001082 if (IsPD)
Craig Topperfc947bc2017-04-18 17:14:21 +00001083 Index.lshrInPlace(1);
Simon Pilgrimeeacc402016-05-01 20:22:42 +00001084
1085 // The _256 variants are a bit trickier since the mask bits always index
1086 // into the corresponding 128 half. In order to convert to a generic
1087 // shuffle, we have to make that explicit.
Craig Topper58917f32016-12-11 01:59:36 +00001088 Index += APInt(32, (I / NumLaneElts) * NumLaneElts);
Simon Pilgrimeeacc402016-05-01 20:22:42 +00001089
1090 Indexes[I] = ConstantInt::get(MaskEltTy, Index);
Simon Pilgrim2f6097d2016-04-24 17:23:46 +00001091 }
1092
Simon Pilgrimeeacc402016-05-01 20:22:42 +00001093 auto ShuffleMask = ConstantVector::get(makeArrayRef(Indexes, NumElts));
Simon Pilgrim2f6097d2016-04-24 17:23:46 +00001094 auto V1 = II.getArgOperand(0);
1095 auto V2 = UndefValue::get(V1->getType());
1096 return Builder.CreateShuffleVector(V1, V2, ShuffleMask);
1097}
1098
Simon Pilgrim8cddf8b2016-05-01 16:41:22 +00001099/// Attempt to convert vpermd/vpermps to shufflevector if the mask is constant.
1100static Value *simplifyX86vpermv(const IntrinsicInst &II,
1101 InstCombiner::BuilderTy &Builder) {
1102 auto *V = dyn_cast<Constant>(II.getArgOperand(1));
1103 if (!V)
1104 return nullptr;
1105
Simon Pilgrimca140b12016-05-01 20:43:02 +00001106 auto *VecTy = cast<VectorType>(II.getType());
1107 auto *MaskEltTy = Type::getInt32Ty(II.getContext());
Simon Pilgrim8cddf8b2016-05-01 16:41:22 +00001108 unsigned Size = VecTy->getNumElements();
Craig Toppere3280452016-12-25 23:58:57 +00001109 assert((Size == 4 || Size == 8 || Size == 16 || Size == 32 || Size == 64) &&
1110 "Unexpected shuffle mask size");
Simon Pilgrim8cddf8b2016-05-01 16:41:22 +00001111
Simon Pilgrimca140b12016-05-01 20:43:02 +00001112 // Construct a shuffle mask from constant integers or UNDEFs.
Craig Toppere3280452016-12-25 23:58:57 +00001113 Constant *Indexes[64] = {nullptr};
Simon Pilgrim8cddf8b2016-05-01 16:41:22 +00001114
1115 for (unsigned I = 0; I < Size; ++I) {
1116 Constant *COp = V->getAggregateElement(I);
Simon Pilgrimca140b12016-05-01 20:43:02 +00001117 if (!COp || (!isa<UndefValue>(COp) && !isa<ConstantInt>(COp)))
Simon Pilgrim8cddf8b2016-05-01 16:41:22 +00001118 return nullptr;
1119
Simon Pilgrimca140b12016-05-01 20:43:02 +00001120 if (isa<UndefValue>(COp)) {
1121 Indexes[I] = UndefValue::get(MaskEltTy);
1122 continue;
1123 }
1124
Craig Toppere3280452016-12-25 23:58:57 +00001125 uint32_t Index = cast<ConstantInt>(COp)->getZExtValue();
1126 Index &= Size - 1;
Simon Pilgrimca140b12016-05-01 20:43:02 +00001127 Indexes[I] = ConstantInt::get(MaskEltTy, Index);
Simon Pilgrim8cddf8b2016-05-01 16:41:22 +00001128 }
1129
Simon Pilgrimca140b12016-05-01 20:43:02 +00001130 auto ShuffleMask = ConstantVector::get(makeArrayRef(Indexes, Size));
Simon Pilgrim8cddf8b2016-05-01 16:41:22 +00001131 auto V1 = II.getArgOperand(0);
1132 auto V2 = UndefValue::get(VecTy);
1133 return Builder.CreateShuffleVector(V1, V2, ShuffleMask);
1134}
1135
David Majnemer666aa942016-07-14 06:58:42 +00001136static bool maskIsAllOneOrUndef(Value *Mask) {
1137 auto *ConstMask = dyn_cast<Constant>(Mask);
1138 if (!ConstMask)
1139 return false;
1140 if (ConstMask->isAllOnesValue() || isa<UndefValue>(ConstMask))
1141 return true;
1142 for (unsigned I = 0, E = ConstMask->getType()->getVectorNumElements(); I != E;
1143 ++I) {
1144 if (auto *MaskElt = ConstMask->getAggregateElement(I))
1145 if (MaskElt->isAllOnesValue() || isa<UndefValue>(MaskElt))
1146 continue;
1147 return false;
1148 }
1149 return true;
1150}
1151
Sanjay Patelb695c552016-02-01 17:00:10 +00001152static Value *simplifyMaskedLoad(const IntrinsicInst &II,
1153 InstCombiner::BuilderTy &Builder) {
David Majnemer666aa942016-07-14 06:58:42 +00001154 // If the mask is all ones or undefs, this is a plain vector load of the 1st
1155 // argument.
1156 if (maskIsAllOneOrUndef(II.getArgOperand(2))) {
Sanjay Patelb695c552016-02-01 17:00:10 +00001157 Value *LoadPtr = II.getArgOperand(0);
1158 unsigned Alignment = cast<ConstantInt>(II.getArgOperand(1))->getZExtValue();
1159 return Builder.CreateAlignedLoad(LoadPtr, Alignment, "unmaskedload");
1160 }
1161
1162 return nullptr;
1163}
1164
Sanjay Patel04f792b2016-02-01 19:39:52 +00001165static Instruction *simplifyMaskedStore(IntrinsicInst &II, InstCombiner &IC) {
1166 auto *ConstMask = dyn_cast<Constant>(II.getArgOperand(3));
1167 if (!ConstMask)
1168 return nullptr;
1169
1170 // If the mask is all zeros, this instruction does nothing.
1171 if (ConstMask->isNullValue())
Sanjay Patel4b198802016-02-01 22:23:39 +00001172 return IC.eraseInstFromFunction(II);
Sanjay Patel04f792b2016-02-01 19:39:52 +00001173
1174 // If the mask is all ones, this is a plain vector store of the 1st argument.
1175 if (ConstMask->isAllOnesValue()) {
1176 Value *StorePtr = II.getArgOperand(1);
1177 unsigned Alignment = cast<ConstantInt>(II.getArgOperand(2))->getZExtValue();
1178 return new StoreInst(II.getArgOperand(0), StorePtr, false, Alignment);
1179 }
1180
1181 return nullptr;
1182}
1183
Sanjay Patel103ab7d2016-02-01 22:10:26 +00001184static Instruction *simplifyMaskedGather(IntrinsicInst &II, InstCombiner &IC) {
1185 // If the mask is all zeros, return the "passthru" argument of the gather.
1186 auto *ConstMask = dyn_cast<Constant>(II.getArgOperand(2));
1187 if (ConstMask && ConstMask->isNullValue())
Sanjay Patel4b198802016-02-01 22:23:39 +00001188 return IC.replaceInstUsesWith(II, II.getArgOperand(3));
Sanjay Patel103ab7d2016-02-01 22:10:26 +00001189
1190 return nullptr;
1191}
1192
Piotr Padlewskic63b4922018-07-12 23:55:20 +00001193/// This function transforms launder.invariant.group and strip.invariant.group
1194/// like:
1195/// launder(launder(%x)) -> launder(%x) (the result is not the argument)
1196/// launder(strip(%x)) -> launder(%x)
1197/// strip(strip(%x)) -> strip(%x) (the result is not the argument)
1198/// strip(launder(%x)) -> strip(%x)
1199/// This is legal because it preserves the most recent information about
1200/// the presence or absence of invariant.group.
1201static Instruction *simplifyInvariantGroupIntrinsic(IntrinsicInst &II,
1202 InstCombiner &IC) {
1203 auto *Arg = II.getArgOperand(0);
1204 auto *StrippedArg = Arg->stripPointerCasts();
1205 auto *StrippedInvariantGroupsArg = Arg->stripPointerCastsAndInvariantGroups();
1206 if (StrippedArg == StrippedInvariantGroupsArg)
1207 return nullptr; // No launders/strips to remove.
1208
1209 Value *Result = nullptr;
1210
1211 if (II.getIntrinsicID() == Intrinsic::launder_invariant_group)
1212 Result = IC.Builder.CreateLaunderInvariantGroup(StrippedInvariantGroupsArg);
1213 else if (II.getIntrinsicID() == Intrinsic::strip_invariant_group)
1214 Result = IC.Builder.CreateStripInvariantGroup(StrippedInvariantGroupsArg);
1215 else
1216 llvm_unreachable(
1217 "simplifyInvariantGroupIntrinsic only handles launder and strip");
1218 if (Result->getType()->getPointerAddressSpace() !=
1219 II.getType()->getPointerAddressSpace())
1220 Result = IC.Builder.CreateAddrSpaceCast(Result, II.getType());
1221 if (Result->getType() != II.getType())
1222 Result = IC.Builder.CreateBitCast(Result, II.getType());
1223
1224 return cast<Instruction>(Result);
1225}
1226
Sanjay Patel103ab7d2016-02-01 22:10:26 +00001227static Instruction *simplifyMaskedScatter(IntrinsicInst &II, InstCombiner &IC) {
1228 // If the mask is all zeros, a scatter does nothing.
1229 auto *ConstMask = dyn_cast<Constant>(II.getArgOperand(3));
1230 if (ConstMask && ConstMask->isNullValue())
Sanjay Patel4b198802016-02-01 22:23:39 +00001231 return IC.eraseInstFromFunction(II);
Sanjay Patel103ab7d2016-02-01 22:10:26 +00001232
1233 return nullptr;
1234}
1235
Amaury Sechet763c59d2016-08-18 20:43:50 +00001236static Instruction *foldCttzCtlz(IntrinsicInst &II, InstCombiner &IC) {
1237 assert((II.getIntrinsicID() == Intrinsic::cttz ||
1238 II.getIntrinsicID() == Intrinsic::ctlz) &&
1239 "Expected cttz or ctlz intrinsic");
Sanjay Patel8e3ab172016-08-05 22:42:46 +00001240 Value *Op0 = II.getArgOperand(0);
Sanjay Patel8e3ab172016-08-05 22:42:46 +00001241
Craig Topper8205a1a2017-05-24 16:53:07 +00001242 KnownBits Known = IC.computeKnownBits(Op0, 0, &II);
Sanjay Patel8e3ab172016-08-05 22:42:46 +00001243
1244 // Create a mask for bits above (ctlz) or below (cttz) the first known one.
1245 bool IsTZ = II.getIntrinsicID() == Intrinsic::cttz;
Craig Topper8df66c62017-05-12 17:20:30 +00001246 unsigned PossibleZeros = IsTZ ? Known.countMaxTrailingZeros()
1247 : Known.countMaxLeadingZeros();
1248 unsigned DefiniteZeros = IsTZ ? Known.countMinTrailingZeros()
1249 : Known.countMinLeadingZeros();
Sanjay Patel8e3ab172016-08-05 22:42:46 +00001250
1251 // If all bits above (ctlz) or below (cttz) the first known one are known
1252 // zero, this value is constant.
1253 // FIXME: This should be in InstSimplify because we're replacing an
1254 // instruction with a constant.
Craig Topper9474e9b2017-04-27 04:51:25 +00001255 if (PossibleZeros == DefiniteZeros) {
Craig Topper0799ff92017-06-03 18:50:32 +00001256 auto *C = ConstantInt::get(Op0->getType(), DefiniteZeros);
Amaury Sechet763c59d2016-08-18 20:43:50 +00001257 return IC.replaceInstUsesWith(II, C);
1258 }
1259
1260 // If the input to cttz/ctlz is known to be non-zero,
1261 // then change the 'ZeroIsUndef' parameter to 'true'
1262 // because we know the zero behavior can't affect the result.
Craig Topper73ba1c82017-06-07 07:40:37 +00001263 if (!Known.One.isNullValue() ||
Craig Topperd45185f2017-05-26 18:23:57 +00001264 isKnownNonZero(Op0, IC.getDataLayout(), 0, &IC.getAssumptionCache(), &II,
1265 &IC.getDominatorTree())) {
Amaury Sechet763c59d2016-08-18 20:43:50 +00001266 if (!match(II.getArgOperand(1), m_One())) {
Craig Topperbb4069e2017-07-07 23:16:26 +00001267 II.setOperand(1, IC.Builder.getTrue());
Amaury Sechet763c59d2016-08-18 20:43:50 +00001268 return &II;
1269 }
1270 }
Sanjay Patel8e3ab172016-08-05 22:42:46 +00001271
Craig Topper5b173f22017-06-21 16:32:35 +00001272 // Add range metadata since known bits can't completely reflect what we know.
1273 // TODO: Handle splat vectors.
1274 auto *IT = dyn_cast<IntegerType>(Op0->getType());
1275 if (IT && IT->getBitWidth() != 1 && !II.getMetadata(LLVMContext::MD_range)) {
1276 Metadata *LowAndHigh[] = {
1277 ConstantAsMetadata::get(ConstantInt::get(IT, DefiniteZeros)),
1278 ConstantAsMetadata::get(ConstantInt::get(IT, PossibleZeros + 1))};
1279 II.setMetadata(LLVMContext::MD_range,
1280 MDNode::get(II.getContext(), LowAndHigh));
1281 return &II;
1282 }
1283
1284 return nullptr;
1285}
1286
1287static Instruction *foldCtpop(IntrinsicInst &II, InstCombiner &IC) {
1288 assert(II.getIntrinsicID() == Intrinsic::ctpop &&
1289 "Expected ctpop intrinsic");
1290 Value *Op0 = II.getArgOperand(0);
1291 // FIXME: Try to simplify vectors of integers.
1292 auto *IT = dyn_cast<IntegerType>(Op0->getType());
1293 if (!IT)
1294 return nullptr;
1295
1296 unsigned BitWidth = IT->getBitWidth();
1297 KnownBits Known(BitWidth);
1298 IC.computeKnownBits(Op0, Known, 0, &II);
1299
1300 unsigned MinCount = Known.countMinPopulation();
1301 unsigned MaxCount = Known.countMaxPopulation();
1302
1303 // Add range metadata since known bits can't completely reflect what we know.
1304 if (IT->getBitWidth() != 1 && !II.getMetadata(LLVMContext::MD_range)) {
1305 Metadata *LowAndHigh[] = {
1306 ConstantAsMetadata::get(ConstantInt::get(IT, MinCount)),
1307 ConstantAsMetadata::get(ConstantInt::get(IT, MaxCount + 1))};
1308 II.setMetadata(LLVMContext::MD_range,
1309 MDNode::get(II.getContext(), LowAndHigh));
1310 return &II;
1311 }
1312
Sanjay Patel8e3ab172016-08-05 22:42:46 +00001313 return nullptr;
1314}
1315
Sanjay Patel1ace9932016-02-26 21:04:14 +00001316// TODO: If the x86 backend knew how to convert a bool vector mask back to an
1317// XMM register mask efficiently, we could transform all x86 masked intrinsics
1318// to LLVM masked intrinsics and remove the x86 masked intrinsic defs.
Sanjay Patel98a71502016-02-29 23:16:48 +00001319static Instruction *simplifyX86MaskedLoad(IntrinsicInst &II, InstCombiner &IC) {
1320 Value *Ptr = II.getOperand(0);
1321 Value *Mask = II.getOperand(1);
Sanjay Patel5e5056d2016-04-12 23:16:23 +00001322 Constant *ZeroVec = Constant::getNullValue(II.getType());
Sanjay Patel98a71502016-02-29 23:16:48 +00001323
1324 // Special case a zero mask since that's not a ConstantDataVector.
Sanjay Patel5e5056d2016-04-12 23:16:23 +00001325 // This masked load instruction creates a zero vector.
Sanjay Patel98a71502016-02-29 23:16:48 +00001326 if (isa<ConstantAggregateZero>(Mask))
Sanjay Patel5e5056d2016-04-12 23:16:23 +00001327 return IC.replaceInstUsesWith(II, ZeroVec);
Sanjay Patel98a71502016-02-29 23:16:48 +00001328
1329 auto *ConstMask = dyn_cast<ConstantDataVector>(Mask);
1330 if (!ConstMask)
1331 return nullptr;
1332
1333 // The mask is constant. Convert this x86 intrinsic to the LLVM instrinsic
1334 // to allow target-independent optimizations.
1335
1336 // First, cast the x86 intrinsic scalar pointer to a vector pointer to match
1337 // the LLVM intrinsic definition for the pointer argument.
1338 unsigned AddrSpace = cast<PointerType>(Ptr->getType())->getAddressSpace();
1339 PointerType *VecPtrTy = PointerType::get(II.getType(), AddrSpace);
Craig Topperbb4069e2017-07-07 23:16:26 +00001340 Value *PtrCast = IC.Builder.CreateBitCast(Ptr, VecPtrTy, "castvec");
Sanjay Patel98a71502016-02-29 23:16:48 +00001341
1342 // Second, convert the x86 XMM integer vector mask to a vector of bools based
1343 // on each element's most significant bit (the sign bit).
1344 Constant *BoolMask = getNegativeIsTrueBoolVec(ConstMask);
1345
Sanjay Patel5e5056d2016-04-12 23:16:23 +00001346 // The pass-through vector for an x86 masked load is a zero vector.
1347 CallInst *NewMaskedLoad =
Craig Topperbb4069e2017-07-07 23:16:26 +00001348 IC.Builder.CreateMaskedLoad(PtrCast, 1, BoolMask, ZeroVec);
Sanjay Patel98a71502016-02-29 23:16:48 +00001349 return IC.replaceInstUsesWith(II, NewMaskedLoad);
1350}
1351
1352// TODO: If the x86 backend knew how to convert a bool vector mask back to an
1353// XMM register mask efficiently, we could transform all x86 masked intrinsics
1354// to LLVM masked intrinsics and remove the x86 masked intrinsic defs.
Sanjay Patel1ace9932016-02-26 21:04:14 +00001355static bool simplifyX86MaskedStore(IntrinsicInst &II, InstCombiner &IC) {
1356 Value *Ptr = II.getOperand(0);
1357 Value *Mask = II.getOperand(1);
1358 Value *Vec = II.getOperand(2);
1359
1360 // Special case a zero mask since that's not a ConstantDataVector:
1361 // this masked store instruction does nothing.
1362 if (isa<ConstantAggregateZero>(Mask)) {
1363 IC.eraseInstFromFunction(II);
1364 return true;
1365 }
1366
Sanjay Patelc4acbae2016-03-12 15:16:59 +00001367 // The SSE2 version is too weird (eg, unaligned but non-temporal) to do
1368 // anything else at this level.
1369 if (II.getIntrinsicID() == Intrinsic::x86_sse2_maskmov_dqu)
1370 return false;
1371
Sanjay Patel1ace9932016-02-26 21:04:14 +00001372 auto *ConstMask = dyn_cast<ConstantDataVector>(Mask);
1373 if (!ConstMask)
1374 return false;
1375
1376 // The mask is constant. Convert this x86 intrinsic to the LLVM instrinsic
1377 // to allow target-independent optimizations.
1378
1379 // First, cast the x86 intrinsic scalar pointer to a vector pointer to match
1380 // the LLVM intrinsic definition for the pointer argument.
1381 unsigned AddrSpace = cast<PointerType>(Ptr->getType())->getAddressSpace();
1382 PointerType *VecPtrTy = PointerType::get(Vec->getType(), AddrSpace);
Craig Topperbb4069e2017-07-07 23:16:26 +00001383 Value *PtrCast = IC.Builder.CreateBitCast(Ptr, VecPtrTy, "castvec");
Sanjay Patel1ace9932016-02-26 21:04:14 +00001384
1385 // Second, convert the x86 XMM integer vector mask to a vector of bools based
1386 // on each element's most significant bit (the sign bit).
1387 Constant *BoolMask = getNegativeIsTrueBoolVec(ConstMask);
1388
Craig Topperbb4069e2017-07-07 23:16:26 +00001389 IC.Builder.CreateMaskedStore(Vec, PtrCast, 1, BoolMask);
Sanjay Patel1ace9932016-02-26 21:04:14 +00001390
1391 // 'Replace uses' doesn't work for stores. Erase the original masked store.
1392 IC.eraseInstFromFunction(II);
1393 return true;
1394}
1395
Matt Arsenaultcdb468c2017-02-27 23:08:49 +00001396// Constant fold llvm.amdgcn.fmed3 intrinsics for standard inputs.
1397//
1398// A single NaN input is folded to minnum, so we rely on that folding for
1399// handling NaNs.
1400static APFloat fmed3AMDGCN(const APFloat &Src0, const APFloat &Src1,
1401 const APFloat &Src2) {
1402 APFloat Max3 = maxnum(maxnum(Src0, Src1), Src2);
1403
1404 APFloat::cmpResult Cmp0 = Max3.compare(Src0);
1405 assert(Cmp0 != APFloat::cmpUnordered && "nans handled separately");
1406 if (Cmp0 == APFloat::cmpEqual)
1407 return maxnum(Src1, Src2);
1408
1409 APFloat::cmpResult Cmp1 = Max3.compare(Src1);
1410 assert(Cmp1 != APFloat::cmpUnordered && "nans handled separately");
1411 if (Cmp1 == APFloat::cmpEqual)
1412 return maxnum(Src0, Src2);
1413
1414 return maxnum(Src0, Src1);
1415}
1416
Alexandros Lamprineas52457d32018-05-30 14:38:50 +00001417/// Convert a table lookup to shufflevector if the mask is constant.
1418/// This could benefit tbl1 if the mask is { 7,6,5,4,3,2,1,0 }, in
1419/// which case we could lower the shufflevector with rev64 instructions
1420/// as it's actually a byte reverse.
1421static Value *simplifyNeonTbl1(const IntrinsicInst &II,
1422 InstCombiner::BuilderTy &Builder) {
1423 // Bail out if the mask is not a constant.
1424 auto *C = dyn_cast<Constant>(II.getArgOperand(1));
1425 if (!C)
1426 return nullptr;
1427
1428 auto *VecTy = cast<VectorType>(II.getType());
1429 unsigned NumElts = VecTy->getNumElements();
1430
1431 // Only perform this transformation for <8 x i8> vector types.
1432 if (!VecTy->getElementType()->isIntegerTy(8) || NumElts != 8)
1433 return nullptr;
1434
1435 uint32_t Indexes[8];
1436
1437 for (unsigned I = 0; I < NumElts; ++I) {
1438 Constant *COp = C->getAggregateElement(I);
1439
1440 if (!COp || !isa<ConstantInt>(COp))
1441 return nullptr;
1442
1443 Indexes[I] = cast<ConstantInt>(COp)->getLimitedValue();
1444
1445 // Make sure the mask indices are in range.
1446 if (Indexes[I] >= NumElts)
1447 return nullptr;
1448 }
1449
1450 auto *ShuffleMask = ConstantDataVector::get(II.getContext(),
1451 makeArrayRef(Indexes));
1452 auto *V1 = II.getArgOperand(0);
1453 auto *V2 = Constant::getNullValue(V1->getType());
1454 return Builder.CreateShuffleVector(V1, V2, ShuffleMask);
1455}
1456
Alexandros Lamprineas61f0ba12018-05-31 12:19:18 +00001457/// Convert a vector load intrinsic into a simple llvm load instruction.
1458/// This is beneficial when the underlying object being addressed comes
1459/// from a constant, since we get constant-folding for free.
1460static Value *simplifyNeonVld1(const IntrinsicInst &II,
1461 unsigned MemAlign,
1462 InstCombiner::BuilderTy &Builder) {
1463 auto *IntrAlign = dyn_cast<ConstantInt>(II.getArgOperand(1));
1464
1465 if (!IntrAlign)
1466 return nullptr;
1467
1468 unsigned Alignment = IntrAlign->getLimitedValue() < MemAlign ?
1469 MemAlign : IntrAlign->getLimitedValue();
1470
1471 if (!isPowerOf2_32(Alignment))
1472 return nullptr;
1473
1474 auto *BCastInst = Builder.CreateBitCast(II.getArgOperand(0),
1475 PointerType::get(II.getType(), 0));
1476 return Builder.CreateAlignedLoad(BCastInst, Alignment);
1477}
1478
Arnaud A. de Grandmaison333ef382016-05-10 09:24:49 +00001479// Returns true iff the 2 intrinsics have the same operands, limiting the
1480// comparison to the first NumOperands.
1481static bool haveSameOperands(const IntrinsicInst &I, const IntrinsicInst &E,
1482 unsigned NumOperands) {
1483 assert(I.getNumArgOperands() >= NumOperands && "Not enough operands");
1484 assert(E.getNumArgOperands() >= NumOperands && "Not enough operands");
1485 for (unsigned i = 0; i < NumOperands; i++)
1486 if (I.getArgOperand(i) != E.getArgOperand(i))
1487 return false;
1488 return true;
1489}
1490
1491// Remove trivially empty start/end intrinsic ranges, i.e. a start
1492// immediately followed by an end (ignoring debuginfo or other
1493// start/end intrinsics in between). As this handles only the most trivial
1494// cases, tracking the nesting level is not needed:
1495//
1496// call @llvm.foo.start(i1 0) ; &I
1497// call @llvm.foo.start(i1 0)
1498// call @llvm.foo.end(i1 0) ; This one will not be skipped: it will be removed
1499// call @llvm.foo.end(i1 0)
1500static bool removeTriviallyEmptyRange(IntrinsicInst &I, unsigned StartID,
1501 unsigned EndID, InstCombiner &IC) {
1502 assert(I.getIntrinsicID() == StartID &&
1503 "Start intrinsic does not have expected ID");
1504 BasicBlock::iterator BI(I), BE(I.getParent()->end());
1505 for (++BI; BI != BE; ++BI) {
1506 if (auto *E = dyn_cast<IntrinsicInst>(BI)) {
1507 if (isa<DbgInfoIntrinsic>(E) || E->getIntrinsicID() == StartID)
1508 continue;
1509 if (E->getIntrinsicID() == EndID &&
1510 haveSameOperands(I, *E, E->getNumArgOperands())) {
1511 IC.eraseInstFromFunction(*E);
1512 IC.eraseInstFromFunction(I);
1513 return true;
1514 }
1515 }
1516 break;
1517 }
1518
1519 return false;
1520}
1521
Justin Lebar698c31b2017-01-27 00:58:58 +00001522// Convert NVVM intrinsics to target-generic LLVM code where possible.
1523static Instruction *SimplifyNVVMIntrinsic(IntrinsicInst *II, InstCombiner &IC) {
1524 // Each NVVM intrinsic we can simplify can be replaced with one of:
1525 //
1526 // * an LLVM intrinsic,
1527 // * an LLVM cast operation,
1528 // * an LLVM binary operation, or
1529 // * ad-hoc LLVM IR for the particular operation.
1530
1531 // Some transformations are only valid when the module's
1532 // flush-denormals-to-zero (ftz) setting is true/false, whereas other
1533 // transformations are valid regardless of the module's ftz setting.
1534 enum FtzRequirementTy {
1535 FTZ_Any, // Any ftz setting is ok.
1536 FTZ_MustBeOn, // Transformation is valid only if ftz is on.
1537 FTZ_MustBeOff, // Transformation is valid only if ftz is off.
1538 };
1539 // Classes of NVVM intrinsics that can't be replaced one-to-one with a
1540 // target-generic intrinsic, cast op, or binary op but that we can nonetheless
1541 // simplify.
1542 enum SpecialCase {
1543 SPC_Reciprocal,
1544 };
1545
1546 // SimplifyAction is a poor-man's variant (plus an additional flag) that
1547 // represents how to replace an NVVM intrinsic with target-generic LLVM IR.
1548 struct SimplifyAction {
1549 // Invariant: At most one of these Optionals has a value.
1550 Optional<Intrinsic::ID> IID;
1551 Optional<Instruction::CastOps> CastOp;
1552 Optional<Instruction::BinaryOps> BinaryOp;
1553 Optional<SpecialCase> Special;
1554
1555 FtzRequirementTy FtzRequirement = FTZ_Any;
1556
1557 SimplifyAction() = default;
1558
1559 SimplifyAction(Intrinsic::ID IID, FtzRequirementTy FtzReq)
1560 : IID(IID), FtzRequirement(FtzReq) {}
1561
1562 // Cast operations don't have anything to do with FTZ, so we skip that
1563 // argument.
1564 SimplifyAction(Instruction::CastOps CastOp) : CastOp(CastOp) {}
1565
1566 SimplifyAction(Instruction::BinaryOps BinaryOp, FtzRequirementTy FtzReq)
1567 : BinaryOp(BinaryOp), FtzRequirement(FtzReq) {}
1568
1569 SimplifyAction(SpecialCase Special, FtzRequirementTy FtzReq)
1570 : Special(Special), FtzRequirement(FtzReq) {}
1571 };
1572
1573 // Try to generate a SimplifyAction describing how to replace our
1574 // IntrinsicInstr with target-generic LLVM IR.
1575 const SimplifyAction Action = [II]() -> SimplifyAction {
1576 switch (II->getIntrinsicID()) {
Justin Lebar698c31b2017-01-27 00:58:58 +00001577 // NVVM intrinsics that map directly to LLVM intrinsics.
1578 case Intrinsic::nvvm_ceil_d:
1579 return {Intrinsic::ceil, FTZ_Any};
1580 case Intrinsic::nvvm_ceil_f:
1581 return {Intrinsic::ceil, FTZ_MustBeOff};
1582 case Intrinsic::nvvm_ceil_ftz_f:
1583 return {Intrinsic::ceil, FTZ_MustBeOn};
1584 case Intrinsic::nvvm_fabs_d:
1585 return {Intrinsic::fabs, FTZ_Any};
1586 case Intrinsic::nvvm_fabs_f:
1587 return {Intrinsic::fabs, FTZ_MustBeOff};
1588 case Intrinsic::nvvm_fabs_ftz_f:
1589 return {Intrinsic::fabs, FTZ_MustBeOn};
1590 case Intrinsic::nvvm_floor_d:
1591 return {Intrinsic::floor, FTZ_Any};
1592 case Intrinsic::nvvm_floor_f:
1593 return {Intrinsic::floor, FTZ_MustBeOff};
1594 case Intrinsic::nvvm_floor_ftz_f:
1595 return {Intrinsic::floor, FTZ_MustBeOn};
1596 case Intrinsic::nvvm_fma_rn_d:
1597 return {Intrinsic::fma, FTZ_Any};
1598 case Intrinsic::nvvm_fma_rn_f:
1599 return {Intrinsic::fma, FTZ_MustBeOff};
1600 case Intrinsic::nvvm_fma_rn_ftz_f:
1601 return {Intrinsic::fma, FTZ_MustBeOn};
1602 case Intrinsic::nvvm_fmax_d:
1603 return {Intrinsic::maxnum, FTZ_Any};
1604 case Intrinsic::nvvm_fmax_f:
1605 return {Intrinsic::maxnum, FTZ_MustBeOff};
1606 case Intrinsic::nvvm_fmax_ftz_f:
1607 return {Intrinsic::maxnum, FTZ_MustBeOn};
1608 case Intrinsic::nvvm_fmin_d:
1609 return {Intrinsic::minnum, FTZ_Any};
1610 case Intrinsic::nvvm_fmin_f:
1611 return {Intrinsic::minnum, FTZ_MustBeOff};
1612 case Intrinsic::nvvm_fmin_ftz_f:
1613 return {Intrinsic::minnum, FTZ_MustBeOn};
1614 case Intrinsic::nvvm_round_d:
1615 return {Intrinsic::round, FTZ_Any};
1616 case Intrinsic::nvvm_round_f:
1617 return {Intrinsic::round, FTZ_MustBeOff};
1618 case Intrinsic::nvvm_round_ftz_f:
1619 return {Intrinsic::round, FTZ_MustBeOn};
1620 case Intrinsic::nvvm_sqrt_rn_d:
1621 return {Intrinsic::sqrt, FTZ_Any};
1622 case Intrinsic::nvvm_sqrt_f:
1623 // nvvm_sqrt_f is a special case. For most intrinsics, foo_ftz_f is the
1624 // ftz version, and foo_f is the non-ftz version. But nvvm_sqrt_f adopts
1625 // the ftz-ness of the surrounding code. sqrt_rn_f and sqrt_rn_ftz_f are
1626 // the versions with explicit ftz-ness.
1627 return {Intrinsic::sqrt, FTZ_Any};
1628 case Intrinsic::nvvm_sqrt_rn_f:
1629 return {Intrinsic::sqrt, FTZ_MustBeOff};
1630 case Intrinsic::nvvm_sqrt_rn_ftz_f:
1631 return {Intrinsic::sqrt, FTZ_MustBeOn};
1632 case Intrinsic::nvvm_trunc_d:
1633 return {Intrinsic::trunc, FTZ_Any};
1634 case Intrinsic::nvvm_trunc_f:
1635 return {Intrinsic::trunc, FTZ_MustBeOff};
1636 case Intrinsic::nvvm_trunc_ftz_f:
1637 return {Intrinsic::trunc, FTZ_MustBeOn};
1638
1639 // NVVM intrinsics that map to LLVM cast operations.
1640 //
1641 // Note that llvm's target-generic conversion operators correspond to the rz
1642 // (round to zero) versions of the nvvm conversion intrinsics, even though
1643 // most everything else here uses the rn (round to nearest even) nvvm ops.
1644 case Intrinsic::nvvm_d2i_rz:
1645 case Intrinsic::nvvm_f2i_rz:
1646 case Intrinsic::nvvm_d2ll_rz:
1647 case Intrinsic::nvvm_f2ll_rz:
1648 return {Instruction::FPToSI};
1649 case Intrinsic::nvvm_d2ui_rz:
1650 case Intrinsic::nvvm_f2ui_rz:
1651 case Intrinsic::nvvm_d2ull_rz:
1652 case Intrinsic::nvvm_f2ull_rz:
1653 return {Instruction::FPToUI};
1654 case Intrinsic::nvvm_i2d_rz:
1655 case Intrinsic::nvvm_i2f_rz:
1656 case Intrinsic::nvvm_ll2d_rz:
1657 case Intrinsic::nvvm_ll2f_rz:
1658 return {Instruction::SIToFP};
1659 case Intrinsic::nvvm_ui2d_rz:
1660 case Intrinsic::nvvm_ui2f_rz:
1661 case Intrinsic::nvvm_ull2d_rz:
1662 case Intrinsic::nvvm_ull2f_rz:
1663 return {Instruction::UIToFP};
1664
1665 // NVVM intrinsics that map to LLVM binary ops.
1666 case Intrinsic::nvvm_add_rn_d:
1667 return {Instruction::FAdd, FTZ_Any};
1668 case Intrinsic::nvvm_add_rn_f:
1669 return {Instruction::FAdd, FTZ_MustBeOff};
1670 case Intrinsic::nvvm_add_rn_ftz_f:
1671 return {Instruction::FAdd, FTZ_MustBeOn};
1672 case Intrinsic::nvvm_mul_rn_d:
1673 return {Instruction::FMul, FTZ_Any};
1674 case Intrinsic::nvvm_mul_rn_f:
1675 return {Instruction::FMul, FTZ_MustBeOff};
1676 case Intrinsic::nvvm_mul_rn_ftz_f:
1677 return {Instruction::FMul, FTZ_MustBeOn};
1678 case Intrinsic::nvvm_div_rn_d:
1679 return {Instruction::FDiv, FTZ_Any};
1680 case Intrinsic::nvvm_div_rn_f:
1681 return {Instruction::FDiv, FTZ_MustBeOff};
1682 case Intrinsic::nvvm_div_rn_ftz_f:
1683 return {Instruction::FDiv, FTZ_MustBeOn};
1684
1685 // The remainder of cases are NVVM intrinsics that map to LLVM idioms, but
1686 // need special handling.
1687 //
Hiroshi Inoue0ca79dc2017-07-11 06:04:59 +00001688 // We seem to be missing intrinsics for rcp.approx.{ftz.}f32, which is just
Justin Lebar698c31b2017-01-27 00:58:58 +00001689 // as well.
1690 case Intrinsic::nvvm_rcp_rn_d:
1691 return {SPC_Reciprocal, FTZ_Any};
1692 case Intrinsic::nvvm_rcp_rn_f:
1693 return {SPC_Reciprocal, FTZ_MustBeOff};
1694 case Intrinsic::nvvm_rcp_rn_ftz_f:
1695 return {SPC_Reciprocal, FTZ_MustBeOn};
1696
1697 // We do not currently simplify intrinsics that give an approximate answer.
1698 // These include:
1699 //
1700 // - nvvm_cos_approx_{f,ftz_f}
1701 // - nvvm_ex2_approx_{d,f,ftz_f}
1702 // - nvvm_lg2_approx_{d,f,ftz_f}
1703 // - nvvm_sin_approx_{f,ftz_f}
1704 // - nvvm_sqrt_approx_{f,ftz_f}
1705 // - nvvm_rsqrt_approx_{d,f,ftz_f}
1706 // - nvvm_div_approx_{ftz_d,ftz_f,f}
1707 // - nvvm_rcp_approx_ftz_d
1708 //
1709 // Ideally we'd encode them as e.g. "fast call @llvm.cos", where "fast"
1710 // means that fastmath is enabled in the intrinsic. Unfortunately only
1711 // binary operators (currently) have a fastmath bit in SelectionDAG, so this
1712 // information gets lost and we can't select on it.
1713 //
1714 // TODO: div and rcp are lowered to a binary op, so these we could in theory
1715 // lower them to "fast fdiv".
1716
1717 default:
1718 return {};
1719 }
1720 }();
1721
1722 // If Action.FtzRequirementTy is not satisfied by the module's ftz state, we
1723 // can bail out now. (Notice that in the case that IID is not an NVVM
1724 // intrinsic, we don't have to look up any module metadata, as
1725 // FtzRequirementTy will be FTZ_Any.)
1726 if (Action.FtzRequirement != FTZ_Any) {
1727 bool FtzEnabled =
1728 II->getFunction()->getFnAttribute("nvptx-f32ftz").getValueAsString() ==
1729 "true";
1730
1731 if (FtzEnabled != (Action.FtzRequirement == FTZ_MustBeOn))
1732 return nullptr;
1733 }
1734
1735 // Simplify to target-generic intrinsic.
1736 if (Action.IID) {
1737 SmallVector<Value *, 4> Args(II->arg_operands());
1738 // All the target-generic intrinsics currently of interest to us have one
1739 // type argument, equal to that of the nvvm intrinsic's argument.
Justin Lebare3ac0fb2017-01-27 01:49:39 +00001740 Type *Tys[] = {II->getArgOperand(0)->getType()};
Justin Lebar698c31b2017-01-27 00:58:58 +00001741 return CallInst::Create(
1742 Intrinsic::getDeclaration(II->getModule(), *Action.IID, Tys), Args);
1743 }
1744
1745 // Simplify to target-generic binary op.
1746 if (Action.BinaryOp)
1747 return BinaryOperator::Create(*Action.BinaryOp, II->getArgOperand(0),
1748 II->getArgOperand(1), II->getName());
1749
1750 // Simplify to target-generic cast op.
1751 if (Action.CastOp)
1752 return CastInst::Create(*Action.CastOp, II->getArgOperand(0), II->getType(),
1753 II->getName());
1754
1755 // All that's left are the special cases.
1756 if (!Action.Special)
1757 return nullptr;
1758
1759 switch (*Action.Special) {
1760 case SPC_Reciprocal:
1761 // Simplify reciprocal.
1762 return BinaryOperator::Create(
1763 Instruction::FDiv, ConstantFP::get(II->getArgOperand(0)->getType(), 1),
1764 II->getArgOperand(0), II->getName());
1765 }
Justin Lebar25ebe2d2017-01-27 02:04:07 +00001766 llvm_unreachable("All SpecialCase enumerators should be handled in switch.");
Justin Lebar698c31b2017-01-27 00:58:58 +00001767}
1768
Arnaud A. de Grandmaison333ef382016-05-10 09:24:49 +00001769Instruction *InstCombiner::visitVAStartInst(VAStartInst &I) {
1770 removeTriviallyEmptyRange(I, Intrinsic::vastart, Intrinsic::vaend, *this);
1771 return nullptr;
1772}
1773
1774Instruction *InstCombiner::visitVACopyInst(VACopyInst &I) {
1775 removeTriviallyEmptyRange(I, Intrinsic::vacopy, Intrinsic::vaend, *this);
1776 return nullptr;
1777}
1778
Sanjay Patel790af912018-11-26 22:00:41 +00001779static Instruction *canonicalizeConstantArg0ToArg1(CallInst &Call) {
1780 assert(Call.getNumArgOperands() > 1 && "Need at least 2 args to swap");
1781 Value *Arg0 = Call.getArgOperand(0), *Arg1 = Call.getArgOperand(1);
1782 if (isa<Constant>(Arg0) && !isa<Constant>(Arg1)) {
1783 Call.setArgOperand(0, Arg1);
1784 Call.setArgOperand(1, Arg0);
1785 return &Call;
1786 }
1787 return nullptr;
1788}
1789
Sanjay Patelcd4377c2016-01-20 22:24:38 +00001790/// CallInst simplification. This mostly only handles folding of intrinsic
1791/// instructions. For normal calls, it allows visitCallSite to do the heavy
1792/// lifting.
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001793Instruction *InstCombiner::visitCallInst(CallInst &CI) {
Philip Reames7a6db4f2017-12-27 00:16:12 +00001794 if (Value *V = SimplifyCall(&CI, SQ.getWithInstruction(&CI)))
Sanjay Patel4b198802016-02-01 22:23:39 +00001795 return replaceInstUsesWith(CI, V);
David Majnemer15032582015-05-22 03:56:46 +00001796
Justin Bogner99798402016-08-05 01:06:44 +00001797 if (isFreeCall(&CI, &TLI))
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001798 return visitFree(CI);
1799
1800 // If the caller function is nounwind, mark the call as nounwind, even if the
1801 // callee isn't.
Sanjay Patel5a470952016-08-11 15:16:06 +00001802 if (CI.getFunction()->doesNotThrow() && !CI.doesNotThrow()) {
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001803 CI.setDoesNotThrow();
1804 return &CI;
1805 }
Jim Grosbach7815f562012-02-03 00:07:04 +00001806
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001807 IntrinsicInst *II = dyn_cast<IntrinsicInst>(&CI);
1808 if (!II) return visitCallSite(&CI);
Gabor Greif589a0b92010-06-24 12:58:35 +00001809
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001810 // Intrinsics cannot occur in an invoke, so handle them here instead of in
1811 // visitCallSite.
Daniel Neilson8f30ec62018-05-11 14:30:02 +00001812 if (auto *MI = dyn_cast<AnyMemIntrinsic>(II)) {
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001813 bool Changed = false;
1814
1815 // memmove/cpy/set of zero bytes is a noop.
1816 if (Constant *NumBytes = dyn_cast<Constant>(MI->getLength())) {
Chris Lattnerc663a672010-10-01 05:51:02 +00001817 if (NumBytes->isNullValue())
Sanjay Patel4b198802016-02-01 22:23:39 +00001818 return eraseInstFromFunction(CI);
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001819
1820 if (ConstantInt *CI = dyn_cast<ConstantInt>(NumBytes))
1821 if (CI->getZExtValue() == 1) {
1822 // Replace the instruction with just byte operations. We would
1823 // transform other cases to loads/stores, but we don't know if
1824 // alignment is sufficient.
1825 }
1826 }
Jim Grosbach7815f562012-02-03 00:07:04 +00001827
Chris Lattnerc663a672010-10-01 05:51:02 +00001828 // No other transformations apply to volatile transfers.
Daniel Neilson8f30ec62018-05-11 14:30:02 +00001829 if (auto *M = dyn_cast<MemIntrinsic>(MI))
1830 if (M->isVolatile())
1831 return nullptr;
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001832
1833 // If we have a memmove and the source operation is a constant global,
1834 // then the source and dest pointers can't alias, so we can change this
1835 // into a call to memcpy.
Daniel Neilson8f30ec62018-05-11 14:30:02 +00001836 if (auto *MMI = dyn_cast<AnyMemMoveInst>(MI)) {
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001837 if (GlobalVariable *GVSrc = dyn_cast<GlobalVariable>(MMI->getSource()))
1838 if (GVSrc->isConstant()) {
Sanjay Patelaf674fb2015-12-14 17:24:23 +00001839 Module *M = CI.getModule();
Daniel Neilson8f30ec62018-05-11 14:30:02 +00001840 Intrinsic::ID MemCpyID =
1841 isa<AtomicMemMoveInst>(MMI)
1842 ? Intrinsic::memcpy_element_unordered_atomic
1843 : Intrinsic::memcpy;
Jay Foadb804a2b2011-07-12 14:06:48 +00001844 Type *Tys[3] = { CI.getArgOperand(0)->getType(),
1845 CI.getArgOperand(1)->getType(),
1846 CI.getArgOperand(2)->getType() };
Benjamin Kramere6e19332011-07-14 17:45:39 +00001847 CI.setCalledFunction(Intrinsic::getDeclaration(M, MemCpyID, Tys));
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001848 Changed = true;
1849 }
1850 }
1851
Daniel Neilson8f30ec62018-05-11 14:30:02 +00001852 if (AnyMemTransferInst *MTI = dyn_cast<AnyMemTransferInst>(MI)) {
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001853 // memmove(x,x,size) -> noop.
1854 if (MTI->getSource() == MTI->getDest())
Sanjay Patel4b198802016-02-01 22:23:39 +00001855 return eraseInstFromFunction(CI);
Eric Christopher7258dcd2010-04-16 23:37:20 +00001856 }
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001857
Eric Christopher7258dcd2010-04-16 23:37:20 +00001858 // If we can determine a pointer alignment that is bigger than currently
1859 // set, update the alignment.
Daniel Neilson8f30ec62018-05-11 14:30:02 +00001860 if (auto *MTI = dyn_cast<AnyMemTransferInst>(MI)) {
1861 if (Instruction *I = SimplifyAnyMemTransfer(MTI))
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001862 return I;
Daniel Neilsonf6651d42018-05-11 20:04:50 +00001863 } else if (auto *MSI = dyn_cast<AnyMemSetInst>(MI)) {
1864 if (Instruction *I = SimplifyAnyMemSet(MSI))
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001865 return I;
1866 }
Gabor Greif590d95e2010-06-24 13:42:49 +00001867
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001868 if (Changed) return II;
1869 }
Jim Grosbach7815f562012-02-03 00:07:04 +00001870
Justin Lebar698c31b2017-01-27 00:58:58 +00001871 if (Instruction *I = SimplifyNVVMIntrinsic(II, *this))
1872 return I;
1873
Sanjay Patel1c600c62016-01-20 16:41:43 +00001874 auto SimplifyDemandedVectorEltsLow = [this](Value *Op, unsigned Width,
1875 unsigned DemandedWidth) {
Simon Pilgrim61116dd2015-09-17 20:32:45 +00001876 APInt UndefElts(Width, 0);
1877 APInt DemandedElts = APInt::getLowBitsSet(Width, DemandedWidth);
1878 return SimplifyDemandedVectorElts(Op, DemandedElts, UndefElts);
1879 };
1880
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001881 switch (II->getIntrinsicID()) {
1882 default: break;
George Burgess IV3f089142016-12-20 23:46:36 +00001883 case Intrinsic::objectsize:
1884 if (ConstantInt *N =
1885 lowerObjectSizeCall(II, DL, &TLI, /*MustSucceed=*/false))
1886 return replaceInstUsesWith(CI, N);
Craig Topperf40110f2014-04-25 05:29:35 +00001887 return nullptr;
Michael Ilseman536cc322012-12-13 03:13:36 +00001888 case Intrinsic::bswap: {
1889 Value *IIOperand = II->getArgOperand(0);
Craig Topperf40110f2014-04-25 05:29:35 +00001890 Value *X = nullptr;
Michael Ilseman536cc322012-12-13 03:13:36 +00001891
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001892 // bswap(trunc(bswap(x))) -> trunc(lshr(x, c))
Michael Ilseman536cc322012-12-13 03:13:36 +00001893 if (match(IIOperand, m_Trunc(m_BSwap(m_Value(X))))) {
1894 unsigned C = X->getType()->getPrimitiveSizeInBits() -
1895 IIOperand->getType()->getPrimitiveSizeInBits();
1896 Value *CV = ConstantInt::get(X->getType(), C);
Craig Topperbb4069e2017-07-07 23:16:26 +00001897 Value *V = Builder.CreateLShr(X, CV);
Michael Ilseman536cc322012-12-13 03:13:36 +00001898 return new TruncInst(V, IIOperand->getType());
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001899 }
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001900 break;
Michael Ilseman536cc322012-12-13 03:13:36 +00001901 }
Sanjay Patelb695c552016-02-01 17:00:10 +00001902 case Intrinsic::masked_load:
Craig Topperbb4069e2017-07-07 23:16:26 +00001903 if (Value *SimplifiedMaskedOp = simplifyMaskedLoad(*II, Builder))
Sanjay Patel4b198802016-02-01 22:23:39 +00001904 return replaceInstUsesWith(CI, SimplifiedMaskedOp);
Sanjay Patelb695c552016-02-01 17:00:10 +00001905 break;
Sanjay Patel04f792b2016-02-01 19:39:52 +00001906 case Intrinsic::masked_store:
1907 return simplifyMaskedStore(*II, *this);
Sanjay Patel103ab7d2016-02-01 22:10:26 +00001908 case Intrinsic::masked_gather:
1909 return simplifyMaskedGather(*II, *this);
1910 case Intrinsic::masked_scatter:
1911 return simplifyMaskedScatter(*II, *this);
Piotr Padlewskic63b4922018-07-12 23:55:20 +00001912 case Intrinsic::launder_invariant_group:
1913 case Intrinsic::strip_invariant_group:
1914 if (auto *SkippedBarrier = simplifyInvariantGroupIntrinsic(*II, *this))
1915 return replaceInstUsesWith(*II, SkippedBarrier);
1916 break;
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001917 case Intrinsic::powi:
Gabor Greif589a0b92010-06-24 12:58:35 +00001918 if (ConstantInt *Power = dyn_cast<ConstantInt>(II->getArgOperand(1))) {
Philip Reames5000ba62017-12-27 01:14:30 +00001919 // 0 and 1 are handled in instsimplify
1920
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001921 // powi(x, -1) -> 1/x
Craig Topper79ab6432017-07-06 18:39:47 +00001922 if (Power->isMinusOne())
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001923 return BinaryOperator::CreateFDiv(ConstantFP::get(CI.getType(), 1.0),
Gabor Greif589a0b92010-06-24 12:58:35 +00001924 II->getArgOperand(0));
Philip Reamescd13a662017-12-27 01:30:12 +00001925 // powi(x, 2) -> x*x
1926 if (Power->equalsInt(2))
1927 return BinaryOperator::CreateFMul(II->getArgOperand(0),
1928 II->getArgOperand(0));
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001929 }
1930 break;
Jim Grosbach7815f562012-02-03 00:07:04 +00001931
Sanjay Patel8e3ab172016-08-05 22:42:46 +00001932 case Intrinsic::cttz:
1933 case Intrinsic::ctlz:
Amaury Sechet763c59d2016-08-18 20:43:50 +00001934 if (auto *I = foldCttzCtlz(*II, *this))
1935 return I;
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001936 break;
Sanjoy Dasb0984472015-04-08 04:27:22 +00001937
Craig Topper5b173f22017-06-21 16:32:35 +00001938 case Intrinsic::ctpop:
1939 if (auto *I = foldCtpop(*II, *this))
1940 return I;
1941 break;
1942
Sanjay Patela1395642018-11-13 23:27:23 +00001943 case Intrinsic::fshl:
1944 case Intrinsic::fshr: {
Nikita Popov6e81d422018-11-23 22:45:08 +00001945 const APInt *SA;
1946 if (match(II->getArgOperand(2), m_APInt(SA))) {
1947 Value *Op0 = II->getArgOperand(0), *Op1 = II->getArgOperand(1);
1948 unsigned BitWidth = SA->getBitWidth();
1949 uint64_t ShiftAmt = SA->urem(BitWidth);
1950 assert(ShiftAmt != 0 && "SimplifyCall should have handled zero shift");
1951 // Normalize to funnel shift left.
1952 if (II->getIntrinsicID() == Intrinsic::fshr)
1953 ShiftAmt = BitWidth - ShiftAmt;
1954
1955 // fshl(X, 0, C) -> shl X, C
1956 // fshl(X, undef, C) -> shl X, C
1957 if (match(Op1, m_Zero()) || match(Op1, m_Undef()))
1958 return BinaryOperator::CreateShl(
1959 Op0, ConstantInt::get(II->getType(), ShiftAmt));
1960
1961 // fshl(0, X, C) -> lshr X, (BW-C)
1962 // fshl(undef, X, C) -> lshr X, (BW-C)
1963 if (match(Op0, m_Zero()) || match(Op0, m_Undef()))
1964 return BinaryOperator::CreateLShr(
1965 Op1, ConstantInt::get(II->getType(), BitWidth - ShiftAmt));
1966 }
1967
Sanjay Patela1395642018-11-13 23:27:23 +00001968 // The shift amount (operand 2) of a funnel shift is modulo the bitwidth,
1969 // so only the low bits of the shift amount are demanded if the bitwidth is
1970 // a power-of-2.
1971 unsigned BitWidth = II->getType()->getScalarSizeInBits();
1972 if (!isPowerOf2_32(BitWidth))
1973 break;
1974 APInt Op2Demanded = APInt::getLowBitsSet(BitWidth, Log2_32_Ceil(BitWidth));
1975 KnownBits Op2Known(BitWidth);
1976 if (SimplifyDemandedBits(II, 2, Op2Demanded, Op2Known))
1977 return &CI;
1978 break;
1979 }
Nick Lewyckyabe2cc12015-04-13 19:17:37 +00001980 case Intrinsic::uadd_with_overflow:
1981 case Intrinsic::sadd_with_overflow:
1982 case Intrinsic::umul_with_overflow:
1983 case Intrinsic::smul_with_overflow:
Sanjay Patel790af912018-11-26 22:00:41 +00001984 if (Instruction *I = canonicalizeConstantArg0ToArg1(CI))
1985 return I;
Justin Bognercd1d5aa2016-08-17 20:30:52 +00001986 LLVM_FALLTHROUGH;
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001987
Nick Lewyckyabe2cc12015-04-13 19:17:37 +00001988 case Intrinsic::usub_with_overflow:
1989 case Intrinsic::ssub_with_overflow: {
Sanjoy Dasb0984472015-04-08 04:27:22 +00001990 OverflowCheckFlavor OCF =
1991 IntrinsicIDToOverflowCheckFlavor(II->getIntrinsicID());
1992 assert(OCF != OCF_INVALID && "unexpected!");
Jim Grosbach7815f562012-02-03 00:07:04 +00001993
Sanjoy Dasb0984472015-04-08 04:27:22 +00001994 Value *OperationResult = nullptr;
1995 Constant *OverflowResult = nullptr;
1996 if (OptimizeOverflowCheck(OCF, II->getArgOperand(0), II->getArgOperand(1),
1997 *II, OperationResult, OverflowResult))
1998 return CreateOverflowTuple(II, OperationResult, OverflowResult);
Benjamin Kramera420df22014-07-04 10:22:21 +00001999
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002000 break;
Erik Eckstein096ff7d2014-12-11 08:02:30 +00002001 }
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002002
Nikita Popov085d24a2018-11-28 16:36:52 +00002003 case Intrinsic::uadd_sat:
2004 case Intrinsic::sadd_sat:
2005 if (Instruction *I = canonicalizeConstantArg0ToArg1(CI))
2006 return I;
Nikita Popov78a92952018-11-28 16:36:59 +00002007 LLVM_FALLTHROUGH;
2008 case Intrinsic::usub_sat:
2009 case Intrinsic::ssub_sat: {
2010 Value *Arg0 = II->getArgOperand(0);
2011 Value *Arg1 = II->getArgOperand(1);
2012 Intrinsic::ID IID = II->getIntrinsicID();
2013
2014 // Make use of known overflow information.
2015 OverflowResult OR;
2016 switch (IID) {
2017 default:
2018 llvm_unreachable("Unexpected intrinsic!");
2019 case Intrinsic::uadd_sat:
2020 OR = computeOverflowForUnsignedAdd(Arg0, Arg1, II);
2021 if (OR == OverflowResult::NeverOverflows)
2022 return BinaryOperator::CreateNUWAdd(Arg0, Arg1);
2023 if (OR == OverflowResult::AlwaysOverflows)
2024 return replaceInstUsesWith(*II,
2025 ConstantInt::getAllOnesValue(II->getType()));
2026 break;
2027 case Intrinsic::usub_sat:
2028 OR = computeOverflowForUnsignedSub(Arg0, Arg1, II);
2029 if (OR == OverflowResult::NeverOverflows)
2030 return BinaryOperator::CreateNUWSub(Arg0, Arg1);
2031 if (OR == OverflowResult::AlwaysOverflows)
2032 return replaceInstUsesWith(*II,
2033 ConstantInt::getNullValue(II->getType()));
2034 break;
2035 case Intrinsic::sadd_sat:
2036 if (willNotOverflowSignedAdd(Arg0, Arg1, *II))
2037 return BinaryOperator::CreateNSWAdd(Arg0, Arg1);
2038 break;
2039 case Intrinsic::ssub_sat:
2040 if (willNotOverflowSignedSub(Arg0, Arg1, *II))
2041 return BinaryOperator::CreateNSWSub(Arg0, Arg1);
2042 break;
2043 }
Nikita Popov42f89982018-11-28 16:37:09 +00002044
2045 // ssub.sat(X, C) -> sadd.sat(X, -C) if C != MIN
Nikita Popov0c5d6cc2018-12-01 10:58:34 +00002046 Constant *C;
2047 if (IID == Intrinsic::ssub_sat && match(Arg1, m_Constant(C)) &&
2048 C->isNotMinSignedValue()) {
2049 Value *NegVal = ConstantExpr::getNeg(C);
Nikita Popov42f89982018-11-28 16:37:09 +00002050 return replaceInstUsesWith(
2051 *II, Builder.CreateBinaryIntrinsic(
2052 Intrinsic::sadd_sat, Arg0, NegVal));
2053 }
Nikita Popov8d63aed2018-11-28 16:37:15 +00002054
2055 // sat(sat(X + Val2) + Val) -> sat(X + (Val+Val2))
2056 // sat(sat(X - Val2) - Val) -> sat(X - (Val+Val2))
2057 // if Val and Val2 have the same sign
2058 if (auto *Other = dyn_cast<IntrinsicInst>(Arg0)) {
2059 Value *X;
2060 const APInt *Val, *Val2;
2061 APInt NewVal;
2062 bool IsUnsigned =
2063 IID == Intrinsic::uadd_sat || IID == Intrinsic::usub_sat;
2064 if (Other->getIntrinsicID() == II->getIntrinsicID() &&
2065 match(Arg1, m_APInt(Val)) &&
2066 match(Other->getArgOperand(0), m_Value(X)) &&
2067 match(Other->getArgOperand(1), m_APInt(Val2))) {
2068 if (IsUnsigned)
2069 NewVal = Val->uadd_sat(*Val2);
2070 else if (Val->isNonNegative() == Val2->isNonNegative()) {
2071 bool Overflow;
2072 NewVal = Val->sadd_ov(*Val2, Overflow);
2073 if (Overflow) {
2074 // Both adds together may add more than SignedMaxValue
2075 // without saturating the final result.
2076 break;
2077 }
2078 } else {
2079 // Cannot fold saturated addition with different signs.
2080 break;
2081 }
2082
2083 return replaceInstUsesWith(
2084 *II, Builder.CreateBinaryIntrinsic(
2085 IID, X, ConstantInt::get(II->getType(), NewVal)));
2086 }
2087 }
Nikita Popov085d24a2018-11-28 16:36:52 +00002088 break;
Nikita Popov78a92952018-11-28 16:36:59 +00002089 }
Nikita Popov085d24a2018-11-28 16:36:52 +00002090
Matt Arsenaultd6511b42014-10-21 23:00:20 +00002091 case Intrinsic::minnum:
Thomas Livelyc3392502018-10-19 19:01:26 +00002092 case Intrinsic::maxnum:
2093 case Intrinsic::minimum:
2094 case Intrinsic::maximum: {
Sanjay Patel790af912018-11-26 22:00:41 +00002095 if (Instruction *I = canonicalizeConstantArg0ToArg1(CI))
2096 return I;
Matt Arsenaultd6511b42014-10-21 23:00:20 +00002097 Value *Arg0 = II->getArgOperand(0);
2098 Value *Arg1 = II->getArgOperand(1);
Volkan Keles3ca146d2018-10-31 17:50:52 +00002099 Intrinsic::ID IID = II->getIntrinsicID();
Sanjay Patelc7bb1432018-05-10 20:03:13 +00002100 Value *X, *Y;
2101 if (match(Arg0, m_FNeg(m_Value(X))) && match(Arg1, m_FNeg(m_Value(Y))) &&
2102 (Arg0->hasOneUse() || Arg1->hasOneUse())) {
2103 // If both operands are negated, invert the call and negate the result:
Thomas Livelyc3392502018-10-19 19:01:26 +00002104 // min(-X, -Y) --> -(max(X, Y))
2105 // max(-X, -Y) --> -(min(X, Y))
2106 Intrinsic::ID NewIID;
Volkan Keles3ca146d2018-10-31 17:50:52 +00002107 switch (IID) {
Thomas Livelyc3392502018-10-19 19:01:26 +00002108 case Intrinsic::maxnum:
2109 NewIID = Intrinsic::minnum;
2110 break;
2111 case Intrinsic::minnum:
2112 NewIID = Intrinsic::maxnum;
2113 break;
2114 case Intrinsic::maximum:
2115 NewIID = Intrinsic::minimum;
2116 break;
2117 case Intrinsic::minimum:
2118 NewIID = Intrinsic::maximum;
2119 break;
2120 default:
2121 llvm_unreachable("unexpected intrinsic ID");
2122 }
Neil Henning57f5d0a2018-10-08 10:32:33 +00002123 Value *NewCall = Builder.CreateBinaryIntrinsic(NewIID, X, Y, II);
Sanjay Patelc7bb1432018-05-10 20:03:13 +00002124 Instruction *FNeg = BinaryOperator::CreateFNeg(NewCall);
2125 FNeg->copyIRFlags(II);
2126 return FNeg;
2127 }
Volkan Keles3ca146d2018-10-31 17:50:52 +00002128
2129 // m(m(X, C2), C1) -> m(X, C)
2130 const APFloat *C1, *C2;
2131 if (auto *M = dyn_cast<IntrinsicInst>(Arg0)) {
2132 if (M->getIntrinsicID() == IID && match(Arg1, m_APFloat(C1)) &&
2133 ((match(M->getArgOperand(0), m_Value(X)) &&
2134 match(M->getArgOperand(1), m_APFloat(C2))) ||
2135 (match(M->getArgOperand(1), m_Value(X)) &&
2136 match(M->getArgOperand(0), m_APFloat(C2))))) {
2137 APFloat Res(0.0);
2138 switch (IID) {
2139 case Intrinsic::maxnum:
2140 Res = maxnum(*C1, *C2);
2141 break;
2142 case Intrinsic::minnum:
2143 Res = minnum(*C1, *C2);
2144 break;
2145 case Intrinsic::maximum:
2146 Res = maximum(*C1, *C2);
2147 break;
2148 case Intrinsic::minimum:
2149 Res = minimum(*C1, *C2);
2150 break;
2151 default:
2152 llvm_unreachable("unexpected intrinsic ID");
2153 }
2154 Instruction *NewCall = Builder.CreateBinaryIntrinsic(
2155 IID, X, ConstantFP::get(Arg0->getType(), Res));
2156 NewCall->copyIRFlags(II);
2157 return replaceInstUsesWith(*II, NewCall);
2158 }
2159 }
2160
Matt Arsenaultd6511b42014-10-21 23:00:20 +00002161 break;
2162 }
Matt Arsenault1cc294c2017-01-03 04:32:31 +00002163 case Intrinsic::fmuladd: {
Matt Arsenault92057602017-02-16 18:46:24 +00002164 // Canonicalize fast fmuladd to the separate fmul + fadd.
Sanjay Patel629c4112017-11-06 16:27:15 +00002165 if (II->isFast()) {
Craig Topperbb4069e2017-07-07 23:16:26 +00002166 BuilderTy::FastMathFlagGuard Guard(Builder);
2167 Builder.setFastMathFlags(II->getFastMathFlags());
2168 Value *Mul = Builder.CreateFMul(II->getArgOperand(0),
2169 II->getArgOperand(1));
2170 Value *Add = Builder.CreateFAdd(Mul, II->getArgOperand(2));
Matt Arsenault92057602017-02-16 18:46:24 +00002171 Add->takeName(II);
2172 return replaceInstUsesWith(*II, Add);
2173 }
2174
2175 LLVM_FALLTHROUGH;
2176 }
2177 case Intrinsic::fma: {
Sanjay Patel790af912018-11-26 22:00:41 +00002178 if (Instruction *I = canonicalizeConstantArg0ToArg1(CI))
2179 return I;
Matt Arsenaultb264c942017-01-03 04:32:35 +00002180
Matt Arsenault1cc294c2017-01-03 04:32:31 +00002181 // fma fneg(x), fneg(y), z -> fma x, y, z
Sanjay Patel790af912018-11-26 22:00:41 +00002182 Value *Src0 = II->getArgOperand(0);
2183 Value *Src1 = II->getArgOperand(1);
Sanjay Patel236442e2018-04-05 13:24:26 +00002184 Value *X, *Y;
2185 if (match(Src0, m_FNeg(m_Value(X))) && match(Src1, m_FNeg(m_Value(Y)))) {
2186 II->setArgOperand(0, X);
2187 II->setArgOperand(1, Y);
Matt Arsenault3f509042017-01-10 23:17:52 +00002188 return II;
Matt Arsenault1cc294c2017-01-03 04:32:31 +00002189 }
2190
2191 // fma fabs(x), fabs(x), z -> fma x, x, z
Matt Arsenaultd1496502018-07-27 09:04:35 +00002192 if (match(Src0, m_FAbs(m_Value(X))) &&
2193 match(Src1, m_FAbs(m_Specific(X)))) {
Sanjay Patel236442e2018-04-05 13:24:26 +00002194 II->setArgOperand(0, X);
2195 II->setArgOperand(1, X);
Matt Arsenault3f509042017-01-10 23:17:52 +00002196 return II;
Matt Arsenault1cc294c2017-01-03 04:32:31 +00002197 }
2198
Matt Arsenaultb264c942017-01-03 04:32:35 +00002199 // fma x, 1, z -> fadd x, z
2200 if (match(Src1, m_FPOne())) {
Sanjay Patel236442e2018-04-05 13:24:26 +00002201 auto *FAdd = BinaryOperator::CreateFAdd(Src0, II->getArgOperand(2));
2202 FAdd->copyFastMathFlags(II);
2203 return FAdd;
Matt Arsenaultb264c942017-01-03 04:32:35 +00002204 }
2205
Matt Arsenault1cc294c2017-01-03 04:32:31 +00002206 break;
2207 }
Matt Arsenault56ff4832017-01-03 22:40:34 +00002208 case Intrinsic::fabs: {
2209 Value *Cond;
2210 Constant *LHS, *RHS;
2211 if (match(II->getArgOperand(0),
2212 m_Select(m_Value(Cond), m_Constant(LHS), m_Constant(RHS)))) {
Craig Topperbb4069e2017-07-07 23:16:26 +00002213 CallInst *Call0 = Builder.CreateCall(II->getCalledFunction(), {LHS});
2214 CallInst *Call1 = Builder.CreateCall(II->getCalledFunction(), {RHS});
Matt Arsenault56ff4832017-01-03 22:40:34 +00002215 return SelectInst::Create(Cond, Call0, Call1);
2216 }
2217
Matt Arsenault954a6242017-01-23 23:55:08 +00002218 LLVM_FALLTHROUGH;
2219 }
2220 case Intrinsic::ceil:
2221 case Intrinsic::floor:
2222 case Intrinsic::round:
2223 case Intrinsic::nearbyint:
Joerg Sonnenberger28bed102017-03-31 19:58:07 +00002224 case Intrinsic::rint:
Matt Arsenault954a6242017-01-23 23:55:08 +00002225 case Intrinsic::trunc: {
Matt Arsenault72333442017-01-17 00:10:40 +00002226 Value *ExtSrc;
Sanjay Patel32381d72018-03-23 21:18:12 +00002227 if (match(II->getArgOperand(0), m_OneUse(m_FPExt(m_Value(ExtSrc))))) {
2228 // Narrow the call: intrinsic (fpext x) -> fpext (intrinsic x)
Neil Henning57f5d0a2018-10-08 10:32:33 +00002229 Value *NarrowII =
2230 Builder.CreateUnaryIntrinsic(II->getIntrinsicID(), ExtSrc, II);
Sanjay Patel32381d72018-03-23 21:18:12 +00002231 return new FPExtInst(NarrowII, II->getType());
Matt Arsenault72333442017-01-17 00:10:40 +00002232 }
Matt Arsenault56ff4832017-01-03 22:40:34 +00002233 break;
2234 }
Matt Arsenault3bdd75d2017-01-04 22:49:03 +00002235 case Intrinsic::cos:
2236 case Intrinsic::amdgcn_cos: {
Sanjay Patel0f29e952018-08-29 18:27:49 +00002237 Value *X;
Matt Arsenault3bdd75d2017-01-04 22:49:03 +00002238 Value *Src = II->getArgOperand(0);
Sanjay Patel0f29e952018-08-29 18:27:49 +00002239 if (match(Src, m_FNeg(m_Value(X))) || match(Src, m_FAbs(m_Value(X)))) {
Matt Arsenault3bdd75d2017-01-04 22:49:03 +00002240 // cos(-x) -> cos(x)
2241 // cos(fabs(x)) -> cos(x)
Sanjay Patel0f29e952018-08-29 18:27:49 +00002242 II->setArgOperand(0, X);
Matt Arsenault3bdd75d2017-01-04 22:49:03 +00002243 return II;
2244 }
Sanjay Patel0f29e952018-08-29 18:27:49 +00002245 break;
2246 }
2247 case Intrinsic::sin: {
2248 Value *X;
2249 if (match(II->getArgOperand(0), m_OneUse(m_FNeg(m_Value(X))))) {
2250 // sin(-x) --> -sin(x)
Neil Henning57f5d0a2018-10-08 10:32:33 +00002251 Value *NewSin = Builder.CreateUnaryIntrinsic(Intrinsic::sin, X, II);
Sanjay Patel0f29e952018-08-29 18:27:49 +00002252 Instruction *FNeg = BinaryOperator::CreateFNeg(NewSin);
2253 FNeg->copyFastMathFlags(II);
2254 return FNeg;
2255 }
Matt Arsenault3bdd75d2017-01-04 22:49:03 +00002256 break;
2257 }
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002258 case Intrinsic::ppc_altivec_lvx:
2259 case Intrinsic::ppc_altivec_lvxl:
Bill Wendlingb902f1d2011-04-13 00:36:11 +00002260 // Turn PPC lvx -> load if the pointer is known aligned.
Daniel Jasperaec2fa32016-12-19 08:22:17 +00002261 if (getOrEnforceKnownAlignment(II->getArgOperand(0), 16, DL, II, &AC,
Justin Bogner99798402016-08-05 01:06:44 +00002262 &DT) >= 16) {
Craig Topperbb4069e2017-07-07 23:16:26 +00002263 Value *Ptr = Builder.CreateBitCast(II->getArgOperand(0),
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002264 PointerType::getUnqual(II->getType()));
2265 return new LoadInst(Ptr);
2266 }
2267 break;
Bill Schmidt72954782014-11-12 04:19:40 +00002268 case Intrinsic::ppc_vsx_lxvw4x:
2269 case Intrinsic::ppc_vsx_lxvd2x: {
2270 // Turn PPC VSX loads into normal loads.
Craig Topperbb4069e2017-07-07 23:16:26 +00002271 Value *Ptr = Builder.CreateBitCast(II->getArgOperand(0),
2272 PointerType::getUnqual(II->getType()));
Bill Schmidt72954782014-11-12 04:19:40 +00002273 return new LoadInst(Ptr, Twine(""), false, 1);
2274 }
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002275 case Intrinsic::ppc_altivec_stvx:
2276 case Intrinsic::ppc_altivec_stvxl:
2277 // Turn stvx -> store if the pointer is known aligned.
Daniel Jasperaec2fa32016-12-19 08:22:17 +00002278 if (getOrEnforceKnownAlignment(II->getArgOperand(1), 16, DL, II, &AC,
Justin Bogner99798402016-08-05 01:06:44 +00002279 &DT) >= 16) {
Jim Grosbach7815f562012-02-03 00:07:04 +00002280 Type *OpPtrTy =
Gabor Greifa6d75e22010-06-24 15:51:11 +00002281 PointerType::getUnqual(II->getArgOperand(0)->getType());
Craig Topperbb4069e2017-07-07 23:16:26 +00002282 Value *Ptr = Builder.CreateBitCast(II->getArgOperand(1), OpPtrTy);
Gabor Greifa6d75e22010-06-24 15:51:11 +00002283 return new StoreInst(II->getArgOperand(0), Ptr);
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002284 }
2285 break;
Bill Schmidt72954782014-11-12 04:19:40 +00002286 case Intrinsic::ppc_vsx_stxvw4x:
2287 case Intrinsic::ppc_vsx_stxvd2x: {
2288 // Turn PPC VSX stores into normal stores.
2289 Type *OpPtrTy = PointerType::getUnqual(II->getArgOperand(0)->getType());
Craig Topperbb4069e2017-07-07 23:16:26 +00002290 Value *Ptr = Builder.CreateBitCast(II->getArgOperand(1), OpPtrTy);
Bill Schmidt72954782014-11-12 04:19:40 +00002291 return new StoreInst(II->getArgOperand(0), Ptr, false, 1);
2292 }
Hal Finkel221f4672015-02-26 18:56:03 +00002293 case Intrinsic::ppc_qpx_qvlfs:
2294 // Turn PPC QPX qvlfs -> load if the pointer is known aligned.
Daniel Jasperaec2fa32016-12-19 08:22:17 +00002295 if (getOrEnforceKnownAlignment(II->getArgOperand(0), 16, DL, II, &AC,
Justin Bogner99798402016-08-05 01:06:44 +00002296 &DT) >= 16) {
Craig Topperbb4069e2017-07-07 23:16:26 +00002297 Type *VTy = VectorType::get(Builder.getFloatTy(),
Hal Finkelf0d68d72015-05-11 06:37:03 +00002298 II->getType()->getVectorNumElements());
Craig Topperbb4069e2017-07-07 23:16:26 +00002299 Value *Ptr = Builder.CreateBitCast(II->getArgOperand(0),
Hal Finkelf0d68d72015-05-11 06:37:03 +00002300 PointerType::getUnqual(VTy));
Craig Topperbb4069e2017-07-07 23:16:26 +00002301 Value *Load = Builder.CreateLoad(Ptr);
Hal Finkelf0d68d72015-05-11 06:37:03 +00002302 return new FPExtInst(Load, II->getType());
Hal Finkel221f4672015-02-26 18:56:03 +00002303 }
2304 break;
2305 case Intrinsic::ppc_qpx_qvlfd:
2306 // Turn PPC QPX qvlfd -> load if the pointer is known aligned.
Daniel Jasperaec2fa32016-12-19 08:22:17 +00002307 if (getOrEnforceKnownAlignment(II->getArgOperand(0), 32, DL, II, &AC,
Justin Bogner99798402016-08-05 01:06:44 +00002308 &DT) >= 32) {
Craig Topperbb4069e2017-07-07 23:16:26 +00002309 Value *Ptr = Builder.CreateBitCast(II->getArgOperand(0),
Hal Finkel221f4672015-02-26 18:56:03 +00002310 PointerType::getUnqual(II->getType()));
2311 return new LoadInst(Ptr);
2312 }
2313 break;
2314 case Intrinsic::ppc_qpx_qvstfs:
2315 // Turn PPC QPX qvstfs -> store if the pointer is known aligned.
Daniel Jasperaec2fa32016-12-19 08:22:17 +00002316 if (getOrEnforceKnownAlignment(II->getArgOperand(1), 16, DL, II, &AC,
Justin Bogner99798402016-08-05 01:06:44 +00002317 &DT) >= 16) {
Craig Topperbb4069e2017-07-07 23:16:26 +00002318 Type *VTy = VectorType::get(Builder.getFloatTy(),
Hal Finkelf0d68d72015-05-11 06:37:03 +00002319 II->getArgOperand(0)->getType()->getVectorNumElements());
Craig Topperbb4069e2017-07-07 23:16:26 +00002320 Value *TOp = Builder.CreateFPTrunc(II->getArgOperand(0), VTy);
Hal Finkelf0d68d72015-05-11 06:37:03 +00002321 Type *OpPtrTy = PointerType::getUnqual(VTy);
Craig Topperbb4069e2017-07-07 23:16:26 +00002322 Value *Ptr = Builder.CreateBitCast(II->getArgOperand(1), OpPtrTy);
Hal Finkelf0d68d72015-05-11 06:37:03 +00002323 return new StoreInst(TOp, Ptr);
Hal Finkel221f4672015-02-26 18:56:03 +00002324 }
2325 break;
2326 case Intrinsic::ppc_qpx_qvstfd:
2327 // Turn PPC QPX qvstfd -> store if the pointer is known aligned.
Daniel Jasperaec2fa32016-12-19 08:22:17 +00002328 if (getOrEnforceKnownAlignment(II->getArgOperand(1), 32, DL, II, &AC,
Justin Bogner99798402016-08-05 01:06:44 +00002329 &DT) >= 32) {
Hal Finkel221f4672015-02-26 18:56:03 +00002330 Type *OpPtrTy =
2331 PointerType::getUnqual(II->getArgOperand(0)->getType());
Craig Topperbb4069e2017-07-07 23:16:26 +00002332 Value *Ptr = Builder.CreateBitCast(II->getArgOperand(1), OpPtrTy);
Hal Finkel221f4672015-02-26 18:56:03 +00002333 return new StoreInst(II->getArgOperand(0), Ptr);
2334 }
2335 break;
Simon Pilgrim20c607b2015-09-12 13:39:53 +00002336
Craig Topper83240032017-07-31 18:52:13 +00002337 case Intrinsic::x86_bmi_bextr_32:
2338 case Intrinsic::x86_bmi_bextr_64:
2339 case Intrinsic::x86_tbm_bextri_u32:
2340 case Intrinsic::x86_tbm_bextri_u64:
2341 // If the RHS is a constant we can try some simplifications.
2342 if (auto *C = dyn_cast<ConstantInt>(II->getArgOperand(1))) {
2343 uint64_t Shift = C->getZExtValue();
2344 uint64_t Length = (Shift >> 8) & 0xff;
2345 Shift &= 0xff;
2346 unsigned BitWidth = II->getType()->getIntegerBitWidth();
2347 // If the length is 0 or the shift is out of range, replace with zero.
2348 if (Length == 0 || Shift >= BitWidth)
2349 return replaceInstUsesWith(CI, ConstantInt::get(II->getType(), 0));
2350 // If the LHS is also a constant, we can completely constant fold this.
2351 if (auto *InC = dyn_cast<ConstantInt>(II->getArgOperand(0))) {
2352 uint64_t Result = InC->getZExtValue() >> Shift;
2353 if (Length > BitWidth)
2354 Length = BitWidth;
2355 Result &= maskTrailingOnes<uint64_t>(Length);
2356 return replaceInstUsesWith(CI, ConstantInt::get(II->getType(), Result));
2357 }
2358 // TODO should we turn this into 'and' if shift is 0? Or 'shl' if we
2359 // are only masking bits that a shift already cleared?
2360 }
2361 break;
2362
Craig Topper317a51e2017-07-31 18:52:15 +00002363 case Intrinsic::x86_bmi_bzhi_32:
2364 case Intrinsic::x86_bmi_bzhi_64:
2365 // If the RHS is a constant we can try some simplifications.
2366 if (auto *C = dyn_cast<ConstantInt>(II->getArgOperand(1))) {
2367 uint64_t Index = C->getZExtValue() & 0xff;
2368 unsigned BitWidth = II->getType()->getIntegerBitWidth();
2369 if (Index >= BitWidth)
2370 return replaceInstUsesWith(CI, II->getArgOperand(0));
2371 if (Index == 0)
2372 return replaceInstUsesWith(CI, ConstantInt::get(II->getType(), 0));
2373 // If the LHS is also a constant, we can completely constant fold this.
2374 if (auto *InC = dyn_cast<ConstantInt>(II->getArgOperand(0))) {
2375 uint64_t Result = InC->getZExtValue();
2376 Result &= maskTrailingOnes<uint64_t>(Index);
2377 return replaceInstUsesWith(CI, ConstantInt::get(II->getType(), Result));
2378 }
2379 // TODO should we convert this to an AND if the RHS is constant?
2380 }
2381 break;
2382
Simon Pilgrim20c607b2015-09-12 13:39:53 +00002383 case Intrinsic::x86_vcvtph2ps_128:
2384 case Intrinsic::x86_vcvtph2ps_256: {
2385 auto Arg = II->getArgOperand(0);
2386 auto ArgType = cast<VectorType>(Arg->getType());
2387 auto RetType = cast<VectorType>(II->getType());
2388 unsigned ArgWidth = ArgType->getNumElements();
2389 unsigned RetWidth = RetType->getNumElements();
2390 assert(RetWidth <= ArgWidth && "Unexpected input/return vector widths");
2391 assert(ArgType->isIntOrIntVectorTy() &&
2392 ArgType->getScalarSizeInBits() == 16 &&
2393 "CVTPH2PS input type should be 16-bit integer vector");
2394 assert(RetType->getScalarType()->isFloatTy() &&
2395 "CVTPH2PS output type should be 32-bit float vector");
2396
2397 // Constant folding: Convert to generic half to single conversion.
Simon Pilgrim48ffca02015-09-12 14:00:17 +00002398 if (isa<ConstantAggregateZero>(Arg))
Sanjay Patel4b198802016-02-01 22:23:39 +00002399 return replaceInstUsesWith(*II, ConstantAggregateZero::get(RetType));
Simon Pilgrim20c607b2015-09-12 13:39:53 +00002400
Simon Pilgrim48ffca02015-09-12 14:00:17 +00002401 if (isa<ConstantDataVector>(Arg)) {
Simon Pilgrim20c607b2015-09-12 13:39:53 +00002402 auto VectorHalfAsShorts = Arg;
2403 if (RetWidth < ArgWidth) {
Craig Topper99d1eab2016-06-12 00:41:19 +00002404 SmallVector<uint32_t, 8> SubVecMask;
Simon Pilgrim20c607b2015-09-12 13:39:53 +00002405 for (unsigned i = 0; i != RetWidth; ++i)
2406 SubVecMask.push_back((int)i);
Craig Topperbb4069e2017-07-07 23:16:26 +00002407 VectorHalfAsShorts = Builder.CreateShuffleVector(
Simon Pilgrim20c607b2015-09-12 13:39:53 +00002408 Arg, UndefValue::get(ArgType), SubVecMask);
2409 }
2410
2411 auto VectorHalfType =
2412 VectorType::get(Type::getHalfTy(II->getContext()), RetWidth);
2413 auto VectorHalfs =
Craig Topperbb4069e2017-07-07 23:16:26 +00002414 Builder.CreateBitCast(VectorHalfAsShorts, VectorHalfType);
2415 auto VectorFloats = Builder.CreateFPExt(VectorHalfs, RetType);
Sanjay Patel4b198802016-02-01 22:23:39 +00002416 return replaceInstUsesWith(*II, VectorFloats);
Simon Pilgrim20c607b2015-09-12 13:39:53 +00002417 }
2418
2419 // We only use the lowest lanes of the argument.
Simon Pilgrim996725e2015-09-19 11:41:53 +00002420 if (Value *V = SimplifyDemandedVectorEltsLow(Arg, ArgWidth, RetWidth)) {
Simon Pilgrim20c607b2015-09-12 13:39:53 +00002421 II->setArgOperand(0, V);
2422 return II;
2423 }
2424 break;
2425 }
2426
Chandler Carruthcf414cf2011-01-10 07:19:37 +00002427 case Intrinsic::x86_sse_cvtss2si:
2428 case Intrinsic::x86_sse_cvtss2si64:
2429 case Intrinsic::x86_sse_cvttss2si:
2430 case Intrinsic::x86_sse_cvttss2si64:
2431 case Intrinsic::x86_sse2_cvtsd2si:
2432 case Intrinsic::x86_sse2_cvtsd2si64:
2433 case Intrinsic::x86_sse2_cvttsd2si:
Craig Topperaeaa52c2016-12-14 07:46:12 +00002434 case Intrinsic::x86_sse2_cvttsd2si64:
2435 case Intrinsic::x86_avx512_vcvtss2si32:
2436 case Intrinsic::x86_avx512_vcvtss2si64:
2437 case Intrinsic::x86_avx512_vcvtss2usi32:
2438 case Intrinsic::x86_avx512_vcvtss2usi64:
2439 case Intrinsic::x86_avx512_vcvtsd2si32:
2440 case Intrinsic::x86_avx512_vcvtsd2si64:
2441 case Intrinsic::x86_avx512_vcvtsd2usi32:
2442 case Intrinsic::x86_avx512_vcvtsd2usi64:
2443 case Intrinsic::x86_avx512_cvttss2si:
2444 case Intrinsic::x86_avx512_cvttss2si64:
2445 case Intrinsic::x86_avx512_cvttss2usi:
2446 case Intrinsic::x86_avx512_cvttss2usi64:
2447 case Intrinsic::x86_avx512_cvttsd2si:
2448 case Intrinsic::x86_avx512_cvttsd2si64:
2449 case Intrinsic::x86_avx512_cvttsd2usi:
2450 case Intrinsic::x86_avx512_cvttsd2usi64: {
Chandler Carruthcf414cf2011-01-10 07:19:37 +00002451 // These intrinsics only demand the 0th element of their input vectors. If
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002452 // we can simplify the input based on that, do so now.
Simon Pilgrim996725e2015-09-19 11:41:53 +00002453 Value *Arg = II->getArgOperand(0);
2454 unsigned VWidth = Arg->getType()->getVectorNumElements();
2455 if (Value *V = SimplifyDemandedVectorEltsLow(Arg, VWidth, 1)) {
Gabor Greif5b1370e2010-06-28 16:50:57 +00002456 II->setArgOperand(0, V);
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002457 return II;
2458 }
Simon Pilgrim18617d12015-08-05 08:18:00 +00002459 break;
2460 }
2461
Mikhail Dvoretckii8393f902018-06-19 10:49:12 +00002462 case Intrinsic::x86_sse41_round_ps:
2463 case Intrinsic::x86_sse41_round_pd:
2464 case Intrinsic::x86_avx_round_ps_256:
2465 case Intrinsic::x86_avx_round_pd_256:
2466 case Intrinsic::x86_avx512_mask_rndscale_ps_128:
2467 case Intrinsic::x86_avx512_mask_rndscale_ps_256:
2468 case Intrinsic::x86_avx512_mask_rndscale_ps_512:
2469 case Intrinsic::x86_avx512_mask_rndscale_pd_128:
2470 case Intrinsic::x86_avx512_mask_rndscale_pd_256:
2471 case Intrinsic::x86_avx512_mask_rndscale_pd_512:
2472 case Intrinsic::x86_avx512_mask_rndscale_ss:
2473 case Intrinsic::x86_avx512_mask_rndscale_sd:
2474 if (Value *V = simplifyX86round(*II, Builder))
2475 return replaceInstUsesWith(*II, V);
2476 break;
2477
Simon Pilgrim91e3ac82016-06-07 08:18:35 +00002478 case Intrinsic::x86_mmx_pmovmskb:
2479 case Intrinsic::x86_sse_movmsk_ps:
2480 case Intrinsic::x86_sse2_movmsk_pd:
2481 case Intrinsic::x86_sse2_pmovmskb_128:
2482 case Intrinsic::x86_avx_movmsk_pd_256:
2483 case Intrinsic::x86_avx_movmsk_ps_256:
Eugene Zelenko7f0f9bc2017-10-24 21:24:53 +00002484 case Intrinsic::x86_avx2_pmovmskb:
Sanjay Patel2aa2dc72018-12-11 16:38:03 +00002485 if (Value *V = simplifyX86movmsk(*II, Builder))
Simon Pilgrim91e3ac82016-06-07 08:18:35 +00002486 return replaceInstUsesWith(*II, V);
2487 break;
Simon Pilgrim91e3ac82016-06-07 08:18:35 +00002488
Simon Pilgrim471efd22016-02-20 23:17:35 +00002489 case Intrinsic::x86_sse_comieq_ss:
2490 case Intrinsic::x86_sse_comige_ss:
2491 case Intrinsic::x86_sse_comigt_ss:
2492 case Intrinsic::x86_sse_comile_ss:
2493 case Intrinsic::x86_sse_comilt_ss:
2494 case Intrinsic::x86_sse_comineq_ss:
2495 case Intrinsic::x86_sse_ucomieq_ss:
2496 case Intrinsic::x86_sse_ucomige_ss:
2497 case Intrinsic::x86_sse_ucomigt_ss:
2498 case Intrinsic::x86_sse_ucomile_ss:
2499 case Intrinsic::x86_sse_ucomilt_ss:
2500 case Intrinsic::x86_sse_ucomineq_ss:
2501 case Intrinsic::x86_sse2_comieq_sd:
2502 case Intrinsic::x86_sse2_comige_sd:
2503 case Intrinsic::x86_sse2_comigt_sd:
2504 case Intrinsic::x86_sse2_comile_sd:
2505 case Intrinsic::x86_sse2_comilt_sd:
2506 case Intrinsic::x86_sse2_comineq_sd:
2507 case Intrinsic::x86_sse2_ucomieq_sd:
2508 case Intrinsic::x86_sse2_ucomige_sd:
2509 case Intrinsic::x86_sse2_ucomigt_sd:
2510 case Intrinsic::x86_sse2_ucomile_sd:
2511 case Intrinsic::x86_sse2_ucomilt_sd:
Craig Topperd9639532016-12-11 07:42:04 +00002512 case Intrinsic::x86_sse2_ucomineq_sd:
Craig Topperd00db692016-12-31 00:45:06 +00002513 case Intrinsic::x86_avx512_vcomi_ss:
2514 case Intrinsic::x86_avx512_vcomi_sd:
Craig Topperd9639532016-12-11 07:42:04 +00002515 case Intrinsic::x86_avx512_mask_cmp_ss:
2516 case Intrinsic::x86_avx512_mask_cmp_sd: {
Simon Pilgrim471efd22016-02-20 23:17:35 +00002517 // These intrinsics only demand the 0th element of their input vectors. If
2518 // we can simplify the input based on that, do so now.
Simon Pilgrim1c9a9f22016-04-24 17:57:27 +00002519 bool MadeChange = false;
Simon Pilgrim471efd22016-02-20 23:17:35 +00002520 Value *Arg0 = II->getArgOperand(0);
2521 Value *Arg1 = II->getArgOperand(1);
2522 unsigned VWidth = Arg0->getType()->getVectorNumElements();
2523 if (Value *V = SimplifyDemandedVectorEltsLow(Arg0, VWidth, 1)) {
2524 II->setArgOperand(0, V);
Simon Pilgrim1c9a9f22016-04-24 17:57:27 +00002525 MadeChange = true;
Simon Pilgrim471efd22016-02-20 23:17:35 +00002526 }
2527 if (Value *V = SimplifyDemandedVectorEltsLow(Arg1, VWidth, 1)) {
2528 II->setArgOperand(1, V);
Simon Pilgrim1c9a9f22016-04-24 17:57:27 +00002529 MadeChange = true;
Simon Pilgrim471efd22016-02-20 23:17:35 +00002530 }
Simon Pilgrim1c9a9f22016-04-24 17:57:27 +00002531 if (MadeChange)
2532 return II;
Simon Pilgrim471efd22016-02-20 23:17:35 +00002533 break;
2534 }
Craig Topper31cbe752018-06-27 15:57:53 +00002535 case Intrinsic::x86_avx512_cmp_pd_128:
2536 case Intrinsic::x86_avx512_cmp_pd_256:
2537 case Intrinsic::x86_avx512_cmp_pd_512:
2538 case Intrinsic::x86_avx512_cmp_ps_128:
2539 case Intrinsic::x86_avx512_cmp_ps_256:
2540 case Intrinsic::x86_avx512_cmp_ps_512: {
Michael Zuckerman16b20d22017-04-16 13:26:08 +00002541 // Folding cmp(sub(a,b),0) -> cmp(a,b) and cmp(0,sub(a,b)) -> cmp(b,a)
2542 Value *Arg0 = II->getArgOperand(0);
2543 Value *Arg1 = II->getArgOperand(1);
Sanjay Patel93e64dd2018-03-25 21:16:33 +00002544 bool Arg0IsZero = match(Arg0, m_PosZeroFP());
Michael Zuckerman16b20d22017-04-16 13:26:08 +00002545 if (Arg0IsZero)
2546 std::swap(Arg0, Arg1);
2547 Value *A, *B;
2548 // This fold requires only the NINF(not +/- inf) since inf minus
2549 // inf is nan.
2550 // NSZ(No Signed Zeros) is not needed because zeros of any sign are
2551 // equal for both compares.
2552 // NNAN is not needed because nans compare the same for both compares.
2553 // The compare intrinsic uses the above assumptions and therefore
2554 // doesn't require additional flags.
2555 if ((match(Arg0, m_OneUse(m_FSub(m_Value(A), m_Value(B)))) &&
Sanjay Patel93e64dd2018-03-25 21:16:33 +00002556 match(Arg1, m_PosZeroFP()) && isa<Instruction>(Arg0) &&
Michael Zuckerman16b20d22017-04-16 13:26:08 +00002557 cast<Instruction>(Arg0)->getFastMathFlags().noInfs())) {
2558 if (Arg0IsZero)
2559 std::swap(A, B);
2560 II->setArgOperand(0, A);
2561 II->setArgOperand(1, B);
2562 return II;
2563 }
2564 break;
2565 }
Simon Pilgrim471efd22016-02-20 23:17:35 +00002566
Craig Topper98a79932018-06-10 06:01:36 +00002567 case Intrinsic::x86_avx512_add_ps_512:
2568 case Intrinsic::x86_avx512_div_ps_512:
2569 case Intrinsic::x86_avx512_mul_ps_512:
2570 case Intrinsic::x86_avx512_sub_ps_512:
2571 case Intrinsic::x86_avx512_add_pd_512:
2572 case Intrinsic::x86_avx512_div_pd_512:
2573 case Intrinsic::x86_avx512_mul_pd_512:
2574 case Intrinsic::x86_avx512_sub_pd_512:
Craig Topper020b2282016-12-27 00:23:16 +00002575 // If the rounding mode is CUR_DIRECTION(4) we can turn these into regular
2576 // IR operations.
Craig Topper98a79932018-06-10 06:01:36 +00002577 if (auto *R = dyn_cast<ConstantInt>(II->getArgOperand(2))) {
Craig Topper020b2282016-12-27 00:23:16 +00002578 if (R->getValue() == 4) {
2579 Value *Arg0 = II->getArgOperand(0);
2580 Value *Arg1 = II->getArgOperand(1);
2581
2582 Value *V;
2583 switch (II->getIntrinsicID()) {
2584 default: llvm_unreachable("Case stmts out of sync!");
Craig Topper98a79932018-06-10 06:01:36 +00002585 case Intrinsic::x86_avx512_add_ps_512:
2586 case Intrinsic::x86_avx512_add_pd_512:
Craig Topperbb4069e2017-07-07 23:16:26 +00002587 V = Builder.CreateFAdd(Arg0, Arg1);
Craig Topper020b2282016-12-27 00:23:16 +00002588 break;
Craig Topper98a79932018-06-10 06:01:36 +00002589 case Intrinsic::x86_avx512_sub_ps_512:
2590 case Intrinsic::x86_avx512_sub_pd_512:
Craig Topperbb4069e2017-07-07 23:16:26 +00002591 V = Builder.CreateFSub(Arg0, Arg1);
Craig Topper020b2282016-12-27 00:23:16 +00002592 break;
Craig Topper98a79932018-06-10 06:01:36 +00002593 case Intrinsic::x86_avx512_mul_ps_512:
2594 case Intrinsic::x86_avx512_mul_pd_512:
Craig Topperbb4069e2017-07-07 23:16:26 +00002595 V = Builder.CreateFMul(Arg0, Arg1);
Craig Topper020b2282016-12-27 00:23:16 +00002596 break;
Craig Topper98a79932018-06-10 06:01:36 +00002597 case Intrinsic::x86_avx512_div_ps_512:
2598 case Intrinsic::x86_avx512_div_pd_512:
Craig Topperbb4069e2017-07-07 23:16:26 +00002599 V = Builder.CreateFDiv(Arg0, Arg1);
Craig Topper020b2282016-12-27 00:23:16 +00002600 break;
2601 }
2602
Craig Topper020b2282016-12-27 00:23:16 +00002603 return replaceInstUsesWith(*II, V);
2604 }
2605 }
2606 break;
2607
Craig Topper790d0fa2016-12-11 07:42:01 +00002608 case Intrinsic::x86_avx512_mask_add_ss_round:
2609 case Intrinsic::x86_avx512_mask_div_ss_round:
2610 case Intrinsic::x86_avx512_mask_mul_ss_round:
2611 case Intrinsic::x86_avx512_mask_sub_ss_round:
Craig Topper790d0fa2016-12-11 07:42:01 +00002612 case Intrinsic::x86_avx512_mask_add_sd_round:
2613 case Intrinsic::x86_avx512_mask_div_sd_round:
2614 case Intrinsic::x86_avx512_mask_mul_sd_round:
2615 case Intrinsic::x86_avx512_mask_sub_sd_round:
Craig Topper7b788ada2016-12-26 06:33:19 +00002616 // If the rounding mode is CUR_DIRECTION(4) we can turn these into regular
2617 // IR operations.
2618 if (auto *R = dyn_cast<ConstantInt>(II->getArgOperand(4))) {
2619 if (R->getValue() == 4) {
Craig Topper7f8540b2016-12-27 01:56:30 +00002620 // Extract the element as scalars.
2621 Value *Arg0 = II->getArgOperand(0);
2622 Value *Arg1 = II->getArgOperand(1);
Craig Topperbb4069e2017-07-07 23:16:26 +00002623 Value *LHS = Builder.CreateExtractElement(Arg0, (uint64_t)0);
2624 Value *RHS = Builder.CreateExtractElement(Arg1, (uint64_t)0);
Craig Topper7b788ada2016-12-26 06:33:19 +00002625
Craig Topper7f8540b2016-12-27 01:56:30 +00002626 Value *V;
2627 switch (II->getIntrinsicID()) {
2628 default: llvm_unreachable("Case stmts out of sync!");
2629 case Intrinsic::x86_avx512_mask_add_ss_round:
2630 case Intrinsic::x86_avx512_mask_add_sd_round:
Craig Topperbb4069e2017-07-07 23:16:26 +00002631 V = Builder.CreateFAdd(LHS, RHS);
Craig Topper7f8540b2016-12-27 01:56:30 +00002632 break;
2633 case Intrinsic::x86_avx512_mask_sub_ss_round:
2634 case Intrinsic::x86_avx512_mask_sub_sd_round:
Craig Topperbb4069e2017-07-07 23:16:26 +00002635 V = Builder.CreateFSub(LHS, RHS);
Craig Topper7f8540b2016-12-27 01:56:30 +00002636 break;
2637 case Intrinsic::x86_avx512_mask_mul_ss_round:
2638 case Intrinsic::x86_avx512_mask_mul_sd_round:
Craig Topperbb4069e2017-07-07 23:16:26 +00002639 V = Builder.CreateFMul(LHS, RHS);
Craig Topper7f8540b2016-12-27 01:56:30 +00002640 break;
2641 case Intrinsic::x86_avx512_mask_div_ss_round:
2642 case Intrinsic::x86_avx512_mask_div_sd_round:
Craig Topperbb4069e2017-07-07 23:16:26 +00002643 V = Builder.CreateFDiv(LHS, RHS);
Craig Topper7f8540b2016-12-27 01:56:30 +00002644 break;
Craig Topper7b788ada2016-12-26 06:33:19 +00002645 }
Craig Topper7f8540b2016-12-27 01:56:30 +00002646
2647 // Handle the masking aspect of the intrinsic.
Craig Topper7f8540b2016-12-27 01:56:30 +00002648 Value *Mask = II->getArgOperand(3);
Craig Topper99163632016-12-30 23:06:28 +00002649 auto *C = dyn_cast<ConstantInt>(Mask);
2650 // We don't need a select if we know the mask bit is a 1.
2651 if (!C || !C->getValue()[0]) {
2652 // Cast the mask to an i1 vector and then extract the lowest element.
Craig Topperbb4069e2017-07-07 23:16:26 +00002653 auto *MaskTy = VectorType::get(Builder.getInt1Ty(),
Craig Topper7f8540b2016-12-27 01:56:30 +00002654 cast<IntegerType>(Mask->getType())->getBitWidth());
Craig Topperbb4069e2017-07-07 23:16:26 +00002655 Mask = Builder.CreateBitCast(Mask, MaskTy);
2656 Mask = Builder.CreateExtractElement(Mask, (uint64_t)0);
Craig Topper99163632016-12-30 23:06:28 +00002657 // Extract the lowest element from the passthru operand.
Craig Topperbb4069e2017-07-07 23:16:26 +00002658 Value *Passthru = Builder.CreateExtractElement(II->getArgOperand(2),
Craig Topper99163632016-12-30 23:06:28 +00002659 (uint64_t)0);
Craig Topperbb4069e2017-07-07 23:16:26 +00002660 V = Builder.CreateSelect(Mask, V, Passthru);
Craig Topper99163632016-12-30 23:06:28 +00002661 }
Craig Topper7f8540b2016-12-27 01:56:30 +00002662
2663 // Insert the result back into the original argument 0.
Craig Topperbb4069e2017-07-07 23:16:26 +00002664 V = Builder.CreateInsertElement(Arg0, V, (uint64_t)0);
Craig Topper7f8540b2016-12-27 01:56:30 +00002665
2666 return replaceInstUsesWith(*II, V);
Craig Topper7b788ada2016-12-26 06:33:19 +00002667 }
2668 }
2669 LLVM_FALLTHROUGH;
2670
2671 // X86 scalar intrinsics simplified with SimplifyDemandedVectorElts.
2672 case Intrinsic::x86_avx512_mask_max_ss_round:
2673 case Intrinsic::x86_avx512_mask_min_ss_round:
Craig Topper790d0fa2016-12-11 07:42:01 +00002674 case Intrinsic::x86_avx512_mask_max_sd_round:
Craig Topper268b3ab2016-12-14 06:06:58 +00002675 case Intrinsic::x86_avx512_mask_min_sd_round:
Craig Toppera0372de2016-12-14 03:17:27 +00002676 case Intrinsic::x86_sse_cmp_ss:
2677 case Intrinsic::x86_sse_min_ss:
2678 case Intrinsic::x86_sse_max_ss:
2679 case Intrinsic::x86_sse2_cmp_sd:
2680 case Intrinsic::x86_sse2_min_sd:
2681 case Intrinsic::x86_sse2_max_sd:
Craig Topperac75bca2016-12-13 07:45:45 +00002682 case Intrinsic::x86_xop_vfrcz_ss:
2683 case Intrinsic::x86_xop_vfrcz_sd: {
2684 unsigned VWidth = II->getType()->getVectorNumElements();
2685 APInt UndefElts(VWidth, 0);
2686 APInt AllOnesEltMask(APInt::getAllOnesValue(VWidth));
2687 if (Value *V = SimplifyDemandedVectorElts(II, AllOnesEltMask, UndefElts)) {
2688 if (V != II)
2689 return replaceInstUsesWith(*II, V);
2690 return II;
2691 }
2692 break;
2693 }
Mikhail Dvoretckii8393f902018-06-19 10:49:12 +00002694 case Intrinsic::x86_sse41_round_ss:
2695 case Intrinsic::x86_sse41_round_sd: {
2696 unsigned VWidth = II->getType()->getVectorNumElements();
2697 APInt UndefElts(VWidth, 0);
2698 APInt AllOnesEltMask(APInt::getAllOnesValue(VWidth));
2699 if (Value *V = SimplifyDemandedVectorElts(II, AllOnesEltMask, UndefElts)) {
2700 if (V != II)
2701 return replaceInstUsesWith(*II, V);
2702 return II;
2703 } else if (Value *V = simplifyX86round(*II, Builder))
2704 return replaceInstUsesWith(*II, V);
2705 break;
2706 }
Craig Topperac75bca2016-12-13 07:45:45 +00002707
Simon Pilgrima3a72b42015-08-10 20:21:15 +00002708 // Constant fold ashr( <A x Bi>, Ci ).
Simon Pilgrimbecd5e82015-08-13 07:39:03 +00002709 // Constant fold lshr( <A x Bi>, Ci ).
2710 // Constant fold shl( <A x Bi>, Ci ).
Simon Pilgrima3a72b42015-08-10 20:21:15 +00002711 case Intrinsic::x86_sse2_psrai_d:
2712 case Intrinsic::x86_sse2_psrai_w:
Simon Pilgrima3a72b42015-08-10 20:21:15 +00002713 case Intrinsic::x86_avx2_psrai_d:
2714 case Intrinsic::x86_avx2_psrai_w:
Craig Topper8b831cb2016-11-13 01:51:55 +00002715 case Intrinsic::x86_avx512_psrai_q_128:
2716 case Intrinsic::x86_avx512_psrai_q_256:
2717 case Intrinsic::x86_avx512_psrai_d_512:
2718 case Intrinsic::x86_avx512_psrai_q_512:
2719 case Intrinsic::x86_avx512_psrai_w_512:
Simon Pilgrim18617d12015-08-05 08:18:00 +00002720 case Intrinsic::x86_sse2_psrli_d:
2721 case Intrinsic::x86_sse2_psrli_q:
2722 case Intrinsic::x86_sse2_psrli_w:
Simon Pilgrim18617d12015-08-05 08:18:00 +00002723 case Intrinsic::x86_avx2_psrli_d:
2724 case Intrinsic::x86_avx2_psrli_q:
2725 case Intrinsic::x86_avx2_psrli_w:
Craig Topper8b831cb2016-11-13 01:51:55 +00002726 case Intrinsic::x86_avx512_psrli_d_512:
2727 case Intrinsic::x86_avx512_psrli_q_512:
2728 case Intrinsic::x86_avx512_psrli_w_512:
Michael J. Spencerdee4b2c2014-04-24 00:58:18 +00002729 case Intrinsic::x86_sse2_pslli_d:
2730 case Intrinsic::x86_sse2_pslli_q:
2731 case Intrinsic::x86_sse2_pslli_w:
Simon Pilgrim18617d12015-08-05 08:18:00 +00002732 case Intrinsic::x86_avx2_pslli_d:
2733 case Intrinsic::x86_avx2_pslli_q:
2734 case Intrinsic::x86_avx2_pslli_w:
Craig Topper8b831cb2016-11-13 01:51:55 +00002735 case Intrinsic::x86_avx512_pslli_d_512:
2736 case Intrinsic::x86_avx512_pslli_q_512:
2737 case Intrinsic::x86_avx512_pslli_w_512:
Craig Topperbb4069e2017-07-07 23:16:26 +00002738 if (Value *V = simplifyX86immShift(*II, Builder))
Sanjay Patel4b198802016-02-01 22:23:39 +00002739 return replaceInstUsesWith(*II, V);
Simon Pilgrim18617d12015-08-05 08:18:00 +00002740 break;
2741
Simon Pilgrimbecd5e82015-08-13 07:39:03 +00002742 case Intrinsic::x86_sse2_psra_d:
2743 case Intrinsic::x86_sse2_psra_w:
2744 case Intrinsic::x86_avx2_psra_d:
2745 case Intrinsic::x86_avx2_psra_w:
Craig Topper8b831cb2016-11-13 01:51:55 +00002746 case Intrinsic::x86_avx512_psra_q_128:
2747 case Intrinsic::x86_avx512_psra_q_256:
2748 case Intrinsic::x86_avx512_psra_d_512:
2749 case Intrinsic::x86_avx512_psra_q_512:
2750 case Intrinsic::x86_avx512_psra_w_512:
Simon Pilgrimbecd5e82015-08-13 07:39:03 +00002751 case Intrinsic::x86_sse2_psrl_d:
2752 case Intrinsic::x86_sse2_psrl_q:
2753 case Intrinsic::x86_sse2_psrl_w:
2754 case Intrinsic::x86_avx2_psrl_d:
2755 case Intrinsic::x86_avx2_psrl_q:
2756 case Intrinsic::x86_avx2_psrl_w:
Craig Topper8b831cb2016-11-13 01:51:55 +00002757 case Intrinsic::x86_avx512_psrl_d_512:
2758 case Intrinsic::x86_avx512_psrl_q_512:
2759 case Intrinsic::x86_avx512_psrl_w_512:
Simon Pilgrimbecd5e82015-08-13 07:39:03 +00002760 case Intrinsic::x86_sse2_psll_d:
2761 case Intrinsic::x86_sse2_psll_q:
2762 case Intrinsic::x86_sse2_psll_w:
2763 case Intrinsic::x86_avx2_psll_d:
2764 case Intrinsic::x86_avx2_psll_q:
Craig Topper8b831cb2016-11-13 01:51:55 +00002765 case Intrinsic::x86_avx2_psll_w:
2766 case Intrinsic::x86_avx512_psll_d_512:
2767 case Intrinsic::x86_avx512_psll_q_512:
2768 case Intrinsic::x86_avx512_psll_w_512: {
Craig Topperbb4069e2017-07-07 23:16:26 +00002769 if (Value *V = simplifyX86immShift(*II, Builder))
Sanjay Patel4b198802016-02-01 22:23:39 +00002770 return replaceInstUsesWith(*II, V);
Simon Pilgrimbecd5e82015-08-13 07:39:03 +00002771
2772 // SSE2/AVX2 uses only the first 64-bits of the 128-bit vector
2773 // operand to compute the shift amount.
Simon Pilgrim996725e2015-09-19 11:41:53 +00002774 Value *Arg1 = II->getArgOperand(1);
2775 assert(Arg1->getType()->getPrimitiveSizeInBits() == 128 &&
Simon Pilgrimbecd5e82015-08-13 07:39:03 +00002776 "Unexpected packed shift size");
Simon Pilgrim996725e2015-09-19 11:41:53 +00002777 unsigned VWidth = Arg1->getType()->getVectorNumElements();
Simon Pilgrimbecd5e82015-08-13 07:39:03 +00002778
Simon Pilgrim996725e2015-09-19 11:41:53 +00002779 if (Value *V = SimplifyDemandedVectorEltsLow(Arg1, VWidth, VWidth / 2)) {
Simon Pilgrimbecd5e82015-08-13 07:39:03 +00002780 II->setArgOperand(1, V);
2781 return II;
2782 }
2783 break;
2784 }
2785
Simon Pilgrimdb9893f2016-06-07 10:27:15 +00002786 case Intrinsic::x86_avx2_psllv_d:
2787 case Intrinsic::x86_avx2_psllv_d_256:
2788 case Intrinsic::x86_avx2_psllv_q:
2789 case Intrinsic::x86_avx2_psllv_q_256:
Craig Topperb4173a52016-11-13 07:26:19 +00002790 case Intrinsic::x86_avx512_psllv_d_512:
2791 case Intrinsic::x86_avx512_psllv_q_512:
Craig Topper1de753f2016-11-18 06:04:33 +00002792 case Intrinsic::x86_avx512_psllv_w_128:
2793 case Intrinsic::x86_avx512_psllv_w_256:
2794 case Intrinsic::x86_avx512_psllv_w_512:
Simon Pilgrimdb9893f2016-06-07 10:27:15 +00002795 case Intrinsic::x86_avx2_psrav_d:
2796 case Intrinsic::x86_avx2_psrav_d_256:
Craig Topperb4173a52016-11-13 07:26:19 +00002797 case Intrinsic::x86_avx512_psrav_q_128:
2798 case Intrinsic::x86_avx512_psrav_q_256:
2799 case Intrinsic::x86_avx512_psrav_d_512:
2800 case Intrinsic::x86_avx512_psrav_q_512:
Craig Topper1de753f2016-11-18 06:04:33 +00002801 case Intrinsic::x86_avx512_psrav_w_128:
2802 case Intrinsic::x86_avx512_psrav_w_256:
2803 case Intrinsic::x86_avx512_psrav_w_512:
Simon Pilgrimdb9893f2016-06-07 10:27:15 +00002804 case Intrinsic::x86_avx2_psrlv_d:
2805 case Intrinsic::x86_avx2_psrlv_d_256:
2806 case Intrinsic::x86_avx2_psrlv_q:
2807 case Intrinsic::x86_avx2_psrlv_q_256:
Craig Topperb4173a52016-11-13 07:26:19 +00002808 case Intrinsic::x86_avx512_psrlv_d_512:
2809 case Intrinsic::x86_avx512_psrlv_q_512:
Craig Topper1de753f2016-11-18 06:04:33 +00002810 case Intrinsic::x86_avx512_psrlv_w_128:
2811 case Intrinsic::x86_avx512_psrlv_w_256:
2812 case Intrinsic::x86_avx512_psrlv_w_512:
Craig Topperbb4069e2017-07-07 23:16:26 +00002813 if (Value *V = simplifyX86varShift(*II, Builder))
Simon Pilgrimdb9893f2016-06-07 10:27:15 +00002814 return replaceInstUsesWith(*II, V);
2815 break;
2816
Simon Pilgrim6f6b2792017-01-25 14:37:24 +00002817 case Intrinsic::x86_sse2_packssdw_128:
2818 case Intrinsic::x86_sse2_packsswb_128:
2819 case Intrinsic::x86_avx2_packssdw:
2820 case Intrinsic::x86_avx2_packsswb:
Craig Topper3731f4d2017-02-16 07:35:23 +00002821 case Intrinsic::x86_avx512_packssdw_512:
2822 case Intrinsic::x86_avx512_packsswb_512:
Craig Topper4853c432017-07-06 23:18:42 +00002823 if (Value *V = simplifyX86pack(*II, true))
Simon Pilgrim6f6b2792017-01-25 14:37:24 +00002824 return replaceInstUsesWith(*II, V);
2825 break;
2826
2827 case Intrinsic::x86_sse2_packuswb_128:
2828 case Intrinsic::x86_sse41_packusdw:
2829 case Intrinsic::x86_avx2_packusdw:
2830 case Intrinsic::x86_avx2_packuswb:
Craig Topper3731f4d2017-02-16 07:35:23 +00002831 case Intrinsic::x86_avx512_packusdw_512:
2832 case Intrinsic::x86_avx512_packuswb_512:
Craig Topper4853c432017-07-06 23:18:42 +00002833 if (Value *V = simplifyX86pack(*II, false))
Simon Pilgrim6f6b2792017-01-25 14:37:24 +00002834 return replaceInstUsesWith(*II, V);
2835 break;
2836
Craig Topper911025b2018-05-13 21:56:32 +00002837 case Intrinsic::x86_pclmulqdq:
2838 case Intrinsic::x86_pclmulqdq_256:
2839 case Intrinsic::x86_pclmulqdq_512: {
Craig Topperb6122122017-01-26 05:17:13 +00002840 if (auto *C = dyn_cast<ConstantInt>(II->getArgOperand(2))) {
2841 unsigned Imm = C->getZExtValue();
2842
2843 bool MadeChange = false;
2844 Value *Arg0 = II->getArgOperand(0);
2845 Value *Arg1 = II->getArgOperand(1);
2846 unsigned VWidth = Arg0->getType()->getVectorNumElements();
Craig Topperb6122122017-01-26 05:17:13 +00002847
2848 APInt UndefElts1(VWidth, 0);
Craig Topper911025b2018-05-13 21:56:32 +00002849 APInt DemandedElts1 = APInt::getSplat(VWidth,
2850 APInt(2, (Imm & 0x01) ? 2 : 1));
2851 if (Value *V = SimplifyDemandedVectorElts(Arg0, DemandedElts1,
Craig Topperb6122122017-01-26 05:17:13 +00002852 UndefElts1)) {
2853 II->setArgOperand(0, V);
2854 MadeChange = true;
2855 }
2856
2857 APInt UndefElts2(VWidth, 0);
Craig Topper911025b2018-05-13 21:56:32 +00002858 APInt DemandedElts2 = APInt::getSplat(VWidth,
2859 APInt(2, (Imm & 0x10) ? 2 : 1));
2860 if (Value *V = SimplifyDemandedVectorElts(Arg1, DemandedElts2,
Craig Topperb6122122017-01-26 05:17:13 +00002861 UndefElts2)) {
2862 II->setArgOperand(1, V);
2863 MadeChange = true;
2864 }
2865
Craig Topper911025b2018-05-13 21:56:32 +00002866 // If either input elements are undef, the result is zero.
2867 if (DemandedElts1.isSubsetOf(UndefElts1) ||
2868 DemandedElts2.isSubsetOf(UndefElts2))
Craig Topperb6122122017-01-26 05:17:13 +00002869 return replaceInstUsesWith(*II,
2870 ConstantAggregateZero::get(II->getType()));
2871
2872 if (MadeChange)
2873 return II;
2874 }
2875 break;
2876 }
2877
Sanjay Patelc86867c2015-04-16 17:52:13 +00002878 case Intrinsic::x86_sse41_insertps:
Craig Topperbb4069e2017-07-07 23:16:26 +00002879 if (Value *V = simplifyX86insertps(*II, Builder))
Sanjay Patel4b198802016-02-01 22:23:39 +00002880 return replaceInstUsesWith(*II, V);
Sanjay Patelc86867c2015-04-16 17:52:13 +00002881 break;
Simon Pilgrim54fcd622015-07-25 20:41:00 +00002882
Simon Pilgrim61116dd2015-09-17 20:32:45 +00002883 case Intrinsic::x86_sse4a_extrq: {
Simon Pilgrim61116dd2015-09-17 20:32:45 +00002884 Value *Op0 = II->getArgOperand(0);
2885 Value *Op1 = II->getArgOperand(1);
2886 unsigned VWidth0 = Op0->getType()->getVectorNumElements();
2887 unsigned VWidth1 = Op1->getType()->getVectorNumElements();
Simon Pilgrim216b1bf2015-10-17 11:40:05 +00002888 assert(Op0->getType()->getPrimitiveSizeInBits() == 128 &&
2889 Op1->getType()->getPrimitiveSizeInBits() == 128 && VWidth0 == 2 &&
2890 VWidth1 == 16 && "Unexpected operand sizes");
Simon Pilgrim61116dd2015-09-17 20:32:45 +00002891
Simon Pilgrim216b1bf2015-10-17 11:40:05 +00002892 // See if we're dealing with constant values.
2893 Constant *C1 = dyn_cast<Constant>(Op1);
2894 ConstantInt *CILength =
Andrea Di Biagio8df5b9c2016-09-07 12:03:03 +00002895 C1 ? dyn_cast_or_null<ConstantInt>(C1->getAggregateElement((unsigned)0))
Simon Pilgrim216b1bf2015-10-17 11:40:05 +00002896 : nullptr;
2897 ConstantInt *CIIndex =
Andrea Di Biagio8df5b9c2016-09-07 12:03:03 +00002898 C1 ? dyn_cast_or_null<ConstantInt>(C1->getAggregateElement((unsigned)1))
Simon Pilgrim216b1bf2015-10-17 11:40:05 +00002899 : nullptr;
2900
2901 // Attempt to simplify to a constant, shuffle vector or EXTRQI call.
Craig Topperbb4069e2017-07-07 23:16:26 +00002902 if (Value *V = simplifyX86extrq(*II, Op0, CILength, CIIndex, Builder))
Sanjay Patel4b198802016-02-01 22:23:39 +00002903 return replaceInstUsesWith(*II, V);
Simon Pilgrim216b1bf2015-10-17 11:40:05 +00002904
2905 // EXTRQ only uses the lowest 64-bits of the first 128-bit vector
2906 // operands and the lowest 16-bits of the second.
Simon Pilgrim1c9a9f22016-04-24 17:57:27 +00002907 bool MadeChange = false;
Simon Pilgrim61116dd2015-09-17 20:32:45 +00002908 if (Value *V = SimplifyDemandedVectorEltsLow(Op0, VWidth0, 1)) {
2909 II->setArgOperand(0, V);
Simon Pilgrim1c9a9f22016-04-24 17:57:27 +00002910 MadeChange = true;
Simon Pilgrim61116dd2015-09-17 20:32:45 +00002911 }
2912 if (Value *V = SimplifyDemandedVectorEltsLow(Op1, VWidth1, 2)) {
2913 II->setArgOperand(1, V);
Simon Pilgrim1c9a9f22016-04-24 17:57:27 +00002914 MadeChange = true;
Simon Pilgrim61116dd2015-09-17 20:32:45 +00002915 }
Simon Pilgrim1c9a9f22016-04-24 17:57:27 +00002916 if (MadeChange)
2917 return II;
Simon Pilgrim61116dd2015-09-17 20:32:45 +00002918 break;
2919 }
2920
2921 case Intrinsic::x86_sse4a_extrqi: {
Simon Pilgrim216b1bf2015-10-17 11:40:05 +00002922 // EXTRQI: Extract Length bits starting from Index. Zero pad the remaining
2923 // bits of the lower 64-bits. The upper 64-bits are undefined.
2924 Value *Op0 = II->getArgOperand(0);
2925 unsigned VWidth = Op0->getType()->getVectorNumElements();
2926 assert(Op0->getType()->getPrimitiveSizeInBits() == 128 && VWidth == 2 &&
2927 "Unexpected operand size");
Simon Pilgrim61116dd2015-09-17 20:32:45 +00002928
Simon Pilgrim216b1bf2015-10-17 11:40:05 +00002929 // See if we're dealing with constant values.
2930 ConstantInt *CILength = dyn_cast<ConstantInt>(II->getArgOperand(1));
2931 ConstantInt *CIIndex = dyn_cast<ConstantInt>(II->getArgOperand(2));
2932
2933 // Attempt to simplify to a constant or shuffle vector.
Craig Topperbb4069e2017-07-07 23:16:26 +00002934 if (Value *V = simplifyX86extrq(*II, Op0, CILength, CIIndex, Builder))
Sanjay Patel4b198802016-02-01 22:23:39 +00002935 return replaceInstUsesWith(*II, V);
Simon Pilgrim216b1bf2015-10-17 11:40:05 +00002936
2937 // EXTRQI only uses the lowest 64-bits of the first 128-bit vector
2938 // operand.
2939 if (Value *V = SimplifyDemandedVectorEltsLow(Op0, VWidth, 1)) {
Simon Pilgrim61116dd2015-09-17 20:32:45 +00002940 II->setArgOperand(0, V);
2941 return II;
2942 }
2943 break;
2944 }
2945
2946 case Intrinsic::x86_sse4a_insertq: {
Simon Pilgrim216b1bf2015-10-17 11:40:05 +00002947 Value *Op0 = II->getArgOperand(0);
2948 Value *Op1 = II->getArgOperand(1);
2949 unsigned VWidth = Op0->getType()->getVectorNumElements();
2950 assert(Op0->getType()->getPrimitiveSizeInBits() == 128 &&
2951 Op1->getType()->getPrimitiveSizeInBits() == 128 && VWidth == 2 &&
2952 Op1->getType()->getVectorNumElements() == 2 &&
2953 "Unexpected operand size");
Simon Pilgrim61116dd2015-09-17 20:32:45 +00002954
Simon Pilgrim216b1bf2015-10-17 11:40:05 +00002955 // See if we're dealing with constant values.
2956 Constant *C1 = dyn_cast<Constant>(Op1);
2957 ConstantInt *CI11 =
Andrea Di Biagiof3fd3162016-09-07 12:47:53 +00002958 C1 ? dyn_cast_or_null<ConstantInt>(C1->getAggregateElement((unsigned)1))
Simon Pilgrim216b1bf2015-10-17 11:40:05 +00002959 : nullptr;
2960
2961 // Attempt to simplify to a constant, shuffle vector or INSERTQI call.
2962 if (CI11) {
Benjamin Kramer46e38f32016-06-08 10:01:20 +00002963 const APInt &V11 = CI11->getValue();
Simon Pilgrim216b1bf2015-10-17 11:40:05 +00002964 APInt Len = V11.zextOrTrunc(6);
2965 APInt Idx = V11.lshr(8).zextOrTrunc(6);
Craig Topperbb4069e2017-07-07 23:16:26 +00002966 if (Value *V = simplifyX86insertq(*II, Op0, Op1, Len, Idx, Builder))
Sanjay Patel4b198802016-02-01 22:23:39 +00002967 return replaceInstUsesWith(*II, V);
Simon Pilgrim216b1bf2015-10-17 11:40:05 +00002968 }
2969
2970 // INSERTQ only uses the lowest 64-bits of the first 128-bit vector
2971 // operand.
2972 if (Value *V = SimplifyDemandedVectorEltsLow(Op0, VWidth, 1)) {
Simon Pilgrim61116dd2015-09-17 20:32:45 +00002973 II->setArgOperand(0, V);
2974 return II;
2975 }
2976 break;
2977 }
2978
Filipe Cabecinhas1a805952014-04-24 00:38:14 +00002979 case Intrinsic::x86_sse4a_insertqi: {
Simon Pilgrim216b1bf2015-10-17 11:40:05 +00002980 // INSERTQI: Extract lowest Length bits from lower half of second source and
2981 // insert over first source starting at Index bit. The upper 64-bits are
2982 // undefined.
Simon Pilgrim61116dd2015-09-17 20:32:45 +00002983 Value *Op0 = II->getArgOperand(0);
2984 Value *Op1 = II->getArgOperand(1);
2985 unsigned VWidth0 = Op0->getType()->getVectorNumElements();
2986 unsigned VWidth1 = Op1->getType()->getVectorNumElements();
Simon Pilgrim216b1bf2015-10-17 11:40:05 +00002987 assert(Op0->getType()->getPrimitiveSizeInBits() == 128 &&
2988 Op1->getType()->getPrimitiveSizeInBits() == 128 && VWidth0 == 2 &&
2989 VWidth1 == 2 && "Unexpected operand sizes");
Simon Pilgrim61116dd2015-09-17 20:32:45 +00002990
Simon Pilgrim216b1bf2015-10-17 11:40:05 +00002991 // See if we're dealing with constant values.
2992 ConstantInt *CILength = dyn_cast<ConstantInt>(II->getArgOperand(2));
2993 ConstantInt *CIIndex = dyn_cast<ConstantInt>(II->getArgOperand(3));
2994
2995 // Attempt to simplify to a constant or shuffle vector.
2996 if (CILength && CIIndex) {
2997 APInt Len = CILength->getValue().zextOrTrunc(6);
2998 APInt Idx = CIIndex->getValue().zextOrTrunc(6);
Craig Topperbb4069e2017-07-07 23:16:26 +00002999 if (Value *V = simplifyX86insertq(*II, Op0, Op1, Len, Idx, Builder))
Sanjay Patel4b198802016-02-01 22:23:39 +00003000 return replaceInstUsesWith(*II, V);
Simon Pilgrim216b1bf2015-10-17 11:40:05 +00003001 }
3002
3003 // INSERTQI only uses the lowest 64-bits of the first two 128-bit vector
3004 // operands.
Simon Pilgrim1c9a9f22016-04-24 17:57:27 +00003005 bool MadeChange = false;
Simon Pilgrim61116dd2015-09-17 20:32:45 +00003006 if (Value *V = SimplifyDemandedVectorEltsLow(Op0, VWidth0, 1)) {
3007 II->setArgOperand(0, V);
Simon Pilgrim1c9a9f22016-04-24 17:57:27 +00003008 MadeChange = true;
Simon Pilgrim61116dd2015-09-17 20:32:45 +00003009 }
Simon Pilgrim61116dd2015-09-17 20:32:45 +00003010 if (Value *V = SimplifyDemandedVectorEltsLow(Op1, VWidth1, 1)) {
3011 II->setArgOperand(1, V);
Simon Pilgrim1c9a9f22016-04-24 17:57:27 +00003012 MadeChange = true;
Simon Pilgrim61116dd2015-09-17 20:32:45 +00003013 }
Simon Pilgrim1c9a9f22016-04-24 17:57:27 +00003014 if (MadeChange)
3015 return II;
Filipe Cabecinhas1a805952014-04-24 00:38:14 +00003016 break;
3017 }
3018
Filipe Cabecinhas82ac07c2014-05-27 03:42:20 +00003019 case Intrinsic::x86_sse41_pblendvb:
3020 case Intrinsic::x86_sse41_blendvps:
3021 case Intrinsic::x86_sse41_blendvpd:
3022 case Intrinsic::x86_avx_blendv_ps_256:
3023 case Intrinsic::x86_avx_blendv_pd_256:
3024 case Intrinsic::x86_avx2_pblendvb: {
Sanjay Patel296d35a2018-09-15 14:25:44 +00003025 // fold (blend A, A, Mask) -> A
Simon Pilgrim8c049d52015-08-12 08:08:56 +00003026 Value *Op0 = II->getArgOperand(0);
3027 Value *Op1 = II->getArgOperand(1);
Filipe Cabecinhas82ac07c2014-05-27 03:42:20 +00003028 Value *Mask = II->getArgOperand(2);
Simon Pilgrim8c049d52015-08-12 08:08:56 +00003029 if (Op0 == Op1)
Sanjay Patel4b198802016-02-01 22:23:39 +00003030 return replaceInstUsesWith(CI, Op0);
Simon Pilgrim8c049d52015-08-12 08:08:56 +00003031
3032 // Zero Mask - select 1st argument.
Simon Pilgrim93f59f52015-08-12 08:23:36 +00003033 if (isa<ConstantAggregateZero>(Mask))
Sanjay Patel4b198802016-02-01 22:23:39 +00003034 return replaceInstUsesWith(CI, Op0);
Simon Pilgrim8c049d52015-08-12 08:08:56 +00003035
3036 // Constant Mask - select 1st/2nd argument lane based on top bit of mask.
Sanjay Patel368ac5d2016-02-21 17:29:33 +00003037 if (auto *ConstantMask = dyn_cast<ConstantDataVector>(Mask)) {
3038 Constant *NewSelector = getNegativeIsTrueBoolVec(ConstantMask);
Simon Pilgrim8c049d52015-08-12 08:08:56 +00003039 return SelectInst::Create(NewSelector, Op1, Op0, "blendv");
Filipe Cabecinhas82ac07c2014-05-27 03:42:20 +00003040 }
Sanjay Patel296d35a2018-09-15 14:25:44 +00003041
3042 // Convert to a vector select if we can bypass casts and find a boolean
3043 // vector condition value.
3044 Value *BoolVec;
Sanjay Patel09e02fb2018-09-22 14:43:55 +00003045 Mask = peekThroughBitcast(Mask);
3046 if (match(Mask, m_SExt(m_Value(BoolVec))) &&
3047 BoolVec->getType()->isVectorTy() &&
3048 BoolVec->getType()->getScalarSizeInBits() == 1) {
3049 assert(Mask->getType()->getPrimitiveSizeInBits() ==
3050 II->getType()->getPrimitiveSizeInBits() &&
3051 "Not expecting mask and operands with different sizes");
3052
3053 unsigned NumMaskElts = Mask->getType()->getVectorNumElements();
3054 unsigned NumOperandElts = II->getType()->getVectorNumElements();
3055 if (NumMaskElts == NumOperandElts)
Sanjay Patel296d35a2018-09-15 14:25:44 +00003056 return SelectInst::Create(BoolVec, Op1, Op0);
Sanjay Patel09e02fb2018-09-22 14:43:55 +00003057
3058 // If the mask has less elements than the operands, each mask bit maps to
3059 // multiple elements of the operands. Bitcast back and forth.
3060 if (NumMaskElts < NumOperandElts) {
3061 Value *CastOp0 = Builder.CreateBitCast(Op0, Mask->getType());
3062 Value *CastOp1 = Builder.CreateBitCast(Op1, Mask->getType());
3063 Value *Sel = Builder.CreateSelect(BoolVec, CastOp1, CastOp0);
3064 return new BitCastInst(Sel, II->getType());
3065 }
Sanjay Patel296d35a2018-09-15 14:25:44 +00003066 }
3067
Simon Pilgrim8c049d52015-08-12 08:08:56 +00003068 break;
Filipe Cabecinhas82ac07c2014-05-27 03:42:20 +00003069 }
3070
Andrea Di Biagio0594e2a2015-09-30 16:44:39 +00003071 case Intrinsic::x86_ssse3_pshuf_b_128:
Simon Pilgrimc0c56e72016-04-24 17:00:34 +00003072 case Intrinsic::x86_avx2_pshuf_b:
Simon Pilgrima22c3a12017-01-18 13:44:04 +00003073 case Intrinsic::x86_avx512_pshuf_b_512:
Craig Topperbb4069e2017-07-07 23:16:26 +00003074 if (Value *V = simplifyX86pshufb(*II, Builder))
Simon Pilgrimc0c56e72016-04-24 17:00:34 +00003075 return replaceInstUsesWith(*II, V);
3076 break;
Andrea Di Biagio0594e2a2015-09-30 16:44:39 +00003077
Rafael Espindolabad3f772014-04-21 22:06:04 +00003078 case Intrinsic::x86_avx_vpermilvar_ps:
3079 case Intrinsic::x86_avx_vpermilvar_ps_256:
Craig Topper58917f32016-12-11 01:59:36 +00003080 case Intrinsic::x86_avx512_vpermilvar_ps_512:
Rafael Espindolabad3f772014-04-21 22:06:04 +00003081 case Intrinsic::x86_avx_vpermilvar_pd:
Simon Pilgrim2f6097d2016-04-24 17:23:46 +00003082 case Intrinsic::x86_avx_vpermilvar_pd_256:
Simon Pilgrima22c3a12017-01-18 13:44:04 +00003083 case Intrinsic::x86_avx512_vpermilvar_pd_512:
Craig Topperbb4069e2017-07-07 23:16:26 +00003084 if (Value *V = simplifyX86vpermilvar(*II, Builder))
Simon Pilgrim2f6097d2016-04-24 17:23:46 +00003085 return replaceInstUsesWith(*II, V);
3086 break;
Rafael Espindolabad3f772014-04-21 22:06:04 +00003087
Simon Pilgrim8cddf8b2016-05-01 16:41:22 +00003088 case Intrinsic::x86_avx2_permd:
3089 case Intrinsic::x86_avx2_permps:
Craig Toppere4c045b2018-05-20 23:34:04 +00003090 case Intrinsic::x86_avx512_permvar_df_256:
3091 case Intrinsic::x86_avx512_permvar_df_512:
3092 case Intrinsic::x86_avx512_permvar_di_256:
3093 case Intrinsic::x86_avx512_permvar_di_512:
3094 case Intrinsic::x86_avx512_permvar_hi_128:
3095 case Intrinsic::x86_avx512_permvar_hi_256:
3096 case Intrinsic::x86_avx512_permvar_hi_512:
3097 case Intrinsic::x86_avx512_permvar_qi_128:
3098 case Intrinsic::x86_avx512_permvar_qi_256:
3099 case Intrinsic::x86_avx512_permvar_qi_512:
3100 case Intrinsic::x86_avx512_permvar_sf_512:
3101 case Intrinsic::x86_avx512_permvar_si_512:
Craig Topperbb4069e2017-07-07 23:16:26 +00003102 if (Value *V = simplifyX86vpermv(*II, Builder))
Simon Pilgrim8cddf8b2016-05-01 16:41:22 +00003103 return replaceInstUsesWith(*II, V);
3104 break;
3105
Sanjay Patel98a71502016-02-29 23:16:48 +00003106 case Intrinsic::x86_avx_maskload_ps:
Sanjay Patel6f2c01f2016-02-29 23:59:00 +00003107 case Intrinsic::x86_avx_maskload_pd:
3108 case Intrinsic::x86_avx_maskload_ps_256:
3109 case Intrinsic::x86_avx_maskload_pd_256:
3110 case Intrinsic::x86_avx2_maskload_d:
3111 case Intrinsic::x86_avx2_maskload_q:
3112 case Intrinsic::x86_avx2_maskload_d_256:
3113 case Intrinsic::x86_avx2_maskload_q_256:
Sanjay Patel98a71502016-02-29 23:16:48 +00003114 if (Instruction *I = simplifyX86MaskedLoad(*II, *this))
3115 return I;
3116 break;
3117
Sanjay Patelc4acbae2016-03-12 15:16:59 +00003118 case Intrinsic::x86_sse2_maskmov_dqu:
Sanjay Patel1ace9932016-02-26 21:04:14 +00003119 case Intrinsic::x86_avx_maskstore_ps:
3120 case Intrinsic::x86_avx_maskstore_pd:
3121 case Intrinsic::x86_avx_maskstore_ps_256:
3122 case Intrinsic::x86_avx_maskstore_pd_256:
Sanjay Patelfc7e7eb2016-02-26 21:51:44 +00003123 case Intrinsic::x86_avx2_maskstore_d:
3124 case Intrinsic::x86_avx2_maskstore_q:
3125 case Intrinsic::x86_avx2_maskstore_d_256:
3126 case Intrinsic::x86_avx2_maskstore_q_256:
Sanjay Patel1ace9932016-02-26 21:04:14 +00003127 if (simplifyX86MaskedStore(*II, *this))
3128 return nullptr;
3129 break;
3130
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003131 case Intrinsic::ppc_altivec_vperm:
3132 // Turn vperm(V1,V2,mask) -> shuffle(V1,V2,mask) if mask is a constant.
Bill Schmidta1184632014-06-05 19:46:04 +00003133 // Note that ppc_altivec_vperm has a big-endian bias, so when creating
3134 // a vectorshuffle for little endian, we must undo the transformation
3135 // performed on vec_perm in altivec.h. That is, we must complement
3136 // the permutation mask with respect to 31 and reverse the order of
3137 // V1 and V2.
Chris Lattner0256be92012-01-27 03:08:05 +00003138 if (Constant *Mask = dyn_cast<Constant>(II->getArgOperand(2))) {
3139 assert(Mask->getType()->getVectorNumElements() == 16 &&
3140 "Bad type for intrinsic!");
Jim Grosbach7815f562012-02-03 00:07:04 +00003141
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003142 // Check that all of the elements are integer constants or undefs.
3143 bool AllEltsOk = true;
3144 for (unsigned i = 0; i != 16; ++i) {
Chris Lattner0256be92012-01-27 03:08:05 +00003145 Constant *Elt = Mask->getAggregateElement(i);
Craig Topperf40110f2014-04-25 05:29:35 +00003146 if (!Elt || !(isa<ConstantInt>(Elt) || isa<UndefValue>(Elt))) {
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003147 AllEltsOk = false;
3148 break;
3149 }
3150 }
Jim Grosbach7815f562012-02-03 00:07:04 +00003151
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003152 if (AllEltsOk) {
3153 // Cast the input vectors to byte vectors.
Craig Topperbb4069e2017-07-07 23:16:26 +00003154 Value *Op0 = Builder.CreateBitCast(II->getArgOperand(0),
3155 Mask->getType());
3156 Value *Op1 = Builder.CreateBitCast(II->getArgOperand(1),
3157 Mask->getType());
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003158 Value *Result = UndefValue::get(Op0->getType());
Jim Grosbach7815f562012-02-03 00:07:04 +00003159
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003160 // Only extract each element once.
3161 Value *ExtractedElts[32];
3162 memset(ExtractedElts, 0, sizeof(ExtractedElts));
Jim Grosbach7815f562012-02-03 00:07:04 +00003163
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003164 for (unsigned i = 0; i != 16; ++i) {
Chris Lattner0256be92012-01-27 03:08:05 +00003165 if (isa<UndefValue>(Mask->getAggregateElement(i)))
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003166 continue;
Jim Grosbach7815f562012-02-03 00:07:04 +00003167 unsigned Idx =
Chris Lattner0256be92012-01-27 03:08:05 +00003168 cast<ConstantInt>(Mask->getAggregateElement(i))->getZExtValue();
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003169 Idx &= 31; // Match the hardware behavior.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003170 if (DL.isLittleEndian())
Bill Schmidta1184632014-06-05 19:46:04 +00003171 Idx = 31 - Idx;
Jim Grosbach7815f562012-02-03 00:07:04 +00003172
Craig Topperf40110f2014-04-25 05:29:35 +00003173 if (!ExtractedElts[Idx]) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003174 Value *Op0ToUse = (DL.isLittleEndian()) ? Op1 : Op0;
3175 Value *Op1ToUse = (DL.isLittleEndian()) ? Op0 : Op1;
Jim Grosbach7815f562012-02-03 00:07:04 +00003176 ExtractedElts[Idx] =
Craig Topperbb4069e2017-07-07 23:16:26 +00003177 Builder.CreateExtractElement(Idx < 16 ? Op0ToUse : Op1ToUse,
3178 Builder.getInt32(Idx&15));
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003179 }
Jim Grosbach7815f562012-02-03 00:07:04 +00003180
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003181 // Insert this value into the result vector.
Craig Topperbb4069e2017-07-07 23:16:26 +00003182 Result = Builder.CreateInsertElement(Result, ExtractedElts[Idx],
3183 Builder.getInt32(i));
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003184 }
3185 return CastInst::Create(Instruction::BitCast, Result, CI.getType());
3186 }
3187 }
3188 break;
3189
Alexandros Lamprineas61f0ba12018-05-31 12:19:18 +00003190 case Intrinsic::arm_neon_vld1: {
3191 unsigned MemAlign = getKnownAlignment(II->getArgOperand(0),
3192 DL, II, &AC, &DT);
3193 if (Value *V = simplifyNeonVld1(*II, MemAlign, Builder))
3194 return replaceInstUsesWith(*II, V);
3195 break;
3196 }
3197
Bob Wilsona4e231c2010-10-22 21:41:48 +00003198 case Intrinsic::arm_neon_vld2:
3199 case Intrinsic::arm_neon_vld3:
3200 case Intrinsic::arm_neon_vld4:
3201 case Intrinsic::arm_neon_vld2lane:
3202 case Intrinsic::arm_neon_vld3lane:
3203 case Intrinsic::arm_neon_vld4lane:
3204 case Intrinsic::arm_neon_vst1:
3205 case Intrinsic::arm_neon_vst2:
3206 case Intrinsic::arm_neon_vst3:
3207 case Intrinsic::arm_neon_vst4:
3208 case Intrinsic::arm_neon_vst2lane:
3209 case Intrinsic::arm_neon_vst3lane:
3210 case Intrinsic::arm_neon_vst4lane: {
Justin Bogner99798402016-08-05 01:06:44 +00003211 unsigned MemAlign =
Daniel Jasperaec2fa32016-12-19 08:22:17 +00003212 getKnownAlignment(II->getArgOperand(0), DL, II, &AC, &DT);
Bob Wilsona4e231c2010-10-22 21:41:48 +00003213 unsigned AlignArg = II->getNumArgOperands() - 1;
3214 ConstantInt *IntrAlign = dyn_cast<ConstantInt>(II->getArgOperand(AlignArg));
3215 if (IntrAlign && IntrAlign->getZExtValue() < MemAlign) {
3216 II->setArgOperand(AlignArg,
3217 ConstantInt::get(Type::getInt32Ty(II->getContext()),
3218 MemAlign, false));
3219 return II;
3220 }
3221 break;
3222 }
3223
Alexandros Lamprineas52457d32018-05-30 14:38:50 +00003224 case Intrinsic::arm_neon_vtbl1:
3225 case Intrinsic::aarch64_neon_tbl1:
3226 if (Value *V = simplifyNeonTbl1(*II, Builder))
3227 return replaceInstUsesWith(*II, V);
3228 break;
3229
Lang Hames3a90fab2012-05-01 00:20:38 +00003230 case Intrinsic::arm_neon_vmulls:
Tim Northover00ed9962014-03-29 10:18:08 +00003231 case Intrinsic::arm_neon_vmullu:
Tim Northover3b0846e2014-05-24 12:50:23 +00003232 case Intrinsic::aarch64_neon_smull:
3233 case Intrinsic::aarch64_neon_umull: {
Lang Hames3a90fab2012-05-01 00:20:38 +00003234 Value *Arg0 = II->getArgOperand(0);
3235 Value *Arg1 = II->getArgOperand(1);
3236
3237 // Handle mul by zero first:
3238 if (isa<ConstantAggregateZero>(Arg0) || isa<ConstantAggregateZero>(Arg1)) {
Sanjay Patel4b198802016-02-01 22:23:39 +00003239 return replaceInstUsesWith(CI, ConstantAggregateZero::get(II->getType()));
Lang Hames3a90fab2012-05-01 00:20:38 +00003240 }
3241
3242 // Check for constant LHS & RHS - in this case we just simplify.
Tim Northover00ed9962014-03-29 10:18:08 +00003243 bool Zext = (II->getIntrinsicID() == Intrinsic::arm_neon_vmullu ||
Tim Northover3b0846e2014-05-24 12:50:23 +00003244 II->getIntrinsicID() == Intrinsic::aarch64_neon_umull);
Lang Hames3a90fab2012-05-01 00:20:38 +00003245 VectorType *NewVT = cast<VectorType>(II->getType());
Benjamin Kramer92040952014-02-13 18:23:24 +00003246 if (Constant *CV0 = dyn_cast<Constant>(Arg0)) {
3247 if (Constant *CV1 = dyn_cast<Constant>(Arg1)) {
3248 CV0 = ConstantExpr::getIntegerCast(CV0, NewVT, /*isSigned=*/!Zext);
3249 CV1 = ConstantExpr::getIntegerCast(CV1, NewVT, /*isSigned=*/!Zext);
3250
Sanjay Patel4b198802016-02-01 22:23:39 +00003251 return replaceInstUsesWith(CI, ConstantExpr::getMul(CV0, CV1));
Lang Hames3a90fab2012-05-01 00:20:38 +00003252 }
3253
Alp Tokercb402912014-01-24 17:20:08 +00003254 // Couldn't simplify - canonicalize constant to the RHS.
Lang Hames3a90fab2012-05-01 00:20:38 +00003255 std::swap(Arg0, Arg1);
3256 }
3257
3258 // Handle mul by one:
Benjamin Kramer92040952014-02-13 18:23:24 +00003259 if (Constant *CV1 = dyn_cast<Constant>(Arg1))
Lang Hames3a90fab2012-05-01 00:20:38 +00003260 if (ConstantInt *Splat =
Benjamin Kramer92040952014-02-13 18:23:24 +00003261 dyn_cast_or_null<ConstantInt>(CV1->getSplatValue()))
3262 if (Splat->isOne())
3263 return CastInst::CreateIntegerCast(Arg0, II->getType(),
3264 /*isSigned=*/!Zext);
Lang Hames3a90fab2012-05-01 00:20:38 +00003265
3266 break;
3267 }
Chad Rosier274d72f2018-05-24 15:26:42 +00003268 case Intrinsic::arm_neon_aesd:
3269 case Intrinsic::arm_neon_aese:
3270 case Intrinsic::aarch64_crypto_aesd:
3271 case Intrinsic::aarch64_crypto_aese: {
3272 Value *DataArg = II->getArgOperand(0);
3273 Value *KeyArg = II->getArgOperand(1);
3274
3275 // Try to use the builtin XOR in AESE and AESD to eliminate a prior XOR
3276 Value *Data, *Key;
3277 if (match(KeyArg, m_ZeroInt()) &&
3278 match(DataArg, m_Xor(m_Value(Data), m_Value(Key)))) {
3279 II->setArgOperand(0, Data);
3280 II->setArgOperand(1, Key);
3281 return II;
3282 }
3283 break;
3284 }
Matt Arsenaultbef34e22016-01-22 21:30:34 +00003285 case Intrinsic::amdgcn_rcp: {
Matt Arsenault4c7795d2017-03-24 19:04:57 +00003286 Value *Src = II->getArgOperand(0);
3287
3288 // TODO: Move to ConstantFolding/InstSimplify?
3289 if (isa<UndefValue>(Src))
3290 return replaceInstUsesWith(CI, Src);
3291
3292 if (const ConstantFP *C = dyn_cast<ConstantFP>(Src)) {
Matt Arsenaulta0050b02014-06-19 01:19:19 +00003293 const APFloat &ArgVal = C->getValueAPF();
3294 APFloat Val(ArgVal.getSemantics(), 1.0);
3295 APFloat::opStatus Status = Val.divide(ArgVal,
3296 APFloat::rmNearestTiesToEven);
3297 // Only do this if it was exact and therefore not dependent on the
3298 // rounding mode.
3299 if (Status == APFloat::opOK)
Sanjay Patel4b198802016-02-01 22:23:39 +00003300 return replaceInstUsesWith(CI, ConstantFP::get(II->getContext(), Val));
Matt Arsenaulta0050b02014-06-19 01:19:19 +00003301 }
3302
3303 break;
3304 }
Matt Arsenault4c7795d2017-03-24 19:04:57 +00003305 case Intrinsic::amdgcn_rsq: {
3306 Value *Src = II->getArgOperand(0);
3307
3308 // TODO: Move to ConstantFolding/InstSimplify?
3309 if (isa<UndefValue>(Src))
3310 return replaceInstUsesWith(CI, Src);
3311 break;
3312 }
Matt Arsenault2fe4fbc2016-03-30 22:28:52 +00003313 case Intrinsic::amdgcn_frexp_mant:
3314 case Intrinsic::amdgcn_frexp_exp: {
Matt Arsenault5cd4f8f2016-03-30 22:28:26 +00003315 Value *Src = II->getArgOperand(0);
3316 if (const ConstantFP *C = dyn_cast<ConstantFP>(Src)) {
3317 int Exp;
3318 APFloat Significand = frexp(C->getValueAPF(), Exp,
3319 APFloat::rmNearestTiesToEven);
3320
Matt Arsenault2fe4fbc2016-03-30 22:28:52 +00003321 if (II->getIntrinsicID() == Intrinsic::amdgcn_frexp_mant) {
3322 return replaceInstUsesWith(CI, ConstantFP::get(II->getContext(),
3323 Significand));
3324 }
3325
3326 // Match instruction special case behavior.
3327 if (Exp == APFloat::IEK_NaN || Exp == APFloat::IEK_Inf)
3328 Exp = 0;
3329
3330 return replaceInstUsesWith(CI, ConstantInt::get(II->getType(), Exp));
3331 }
3332
3333 if (isa<UndefValue>(Src))
3334 return replaceInstUsesWith(CI, UndefValue::get(II->getType()));
Matt Arsenault5cd4f8f2016-03-30 22:28:26 +00003335
3336 break;
3337 }
Matt Arsenault46a03822016-09-03 07:06:58 +00003338 case Intrinsic::amdgcn_class: {
3339 enum {
3340 S_NAN = 1 << 0, // Signaling NaN
3341 Q_NAN = 1 << 1, // Quiet NaN
3342 N_INFINITY = 1 << 2, // Negative infinity
3343 N_NORMAL = 1 << 3, // Negative normal
3344 N_SUBNORMAL = 1 << 4, // Negative subnormal
3345 N_ZERO = 1 << 5, // Negative zero
3346 P_ZERO = 1 << 6, // Positive zero
3347 P_SUBNORMAL = 1 << 7, // Positive subnormal
3348 P_NORMAL = 1 << 8, // Positive normal
3349 P_INFINITY = 1 << 9 // Positive infinity
3350 };
3351
3352 const uint32_t FullMask = S_NAN | Q_NAN | N_INFINITY | N_NORMAL |
3353 N_SUBNORMAL | N_ZERO | P_ZERO | P_SUBNORMAL | P_NORMAL | P_INFINITY;
3354
3355 Value *Src0 = II->getArgOperand(0);
3356 Value *Src1 = II->getArgOperand(1);
3357 const ConstantInt *CMask = dyn_cast<ConstantInt>(Src1);
3358 if (!CMask) {
3359 if (isa<UndefValue>(Src0))
3360 return replaceInstUsesWith(*II, UndefValue::get(II->getType()));
3361
3362 if (isa<UndefValue>(Src1))
3363 return replaceInstUsesWith(*II, ConstantInt::get(II->getType(), false));
3364 break;
3365 }
3366
3367 uint32_t Mask = CMask->getZExtValue();
3368
3369 // If all tests are made, it doesn't matter what the value is.
3370 if ((Mask & FullMask) == FullMask)
3371 return replaceInstUsesWith(*II, ConstantInt::get(II->getType(), true));
3372
3373 if ((Mask & FullMask) == 0)
3374 return replaceInstUsesWith(*II, ConstantInt::get(II->getType(), false));
3375
3376 if (Mask == (S_NAN | Q_NAN)) {
3377 // Equivalent of isnan. Replace with standard fcmp.
Craig Topperbb4069e2017-07-07 23:16:26 +00003378 Value *FCmp = Builder.CreateFCmpUNO(Src0, Src0);
Matt Arsenault46a03822016-09-03 07:06:58 +00003379 FCmp->takeName(II);
3380 return replaceInstUsesWith(*II, FCmp);
3381 }
3382
Matt Arsenaultd35f46c2018-08-10 18:58:49 +00003383 if (Mask == (N_ZERO | P_ZERO)) {
3384 // Equivalent of == 0.
3385 Value *FCmp = Builder.CreateFCmpOEQ(
3386 Src0, ConstantFP::get(Src0->getType(), 0.0));
3387
3388 FCmp->takeName(II);
3389 return replaceInstUsesWith(*II, FCmp);
3390 }
3391
Matt Arsenault10de2772018-08-28 18:10:02 +00003392 // fp_class (nnan x), qnan|snan|other -> fp_class (nnan x), other
3393 if (((Mask & S_NAN) || (Mask & Q_NAN)) && isKnownNeverNaN(Src0, &TLI)) {
3394 II->setArgOperand(1, ConstantInt::get(Src1->getType(),
3395 Mask & ~(S_NAN | Q_NAN)));
3396 return II;
3397 }
3398
Matt Arsenault46a03822016-09-03 07:06:58 +00003399 const ConstantFP *CVal = dyn_cast<ConstantFP>(Src0);
3400 if (!CVal) {
3401 if (isa<UndefValue>(Src0))
3402 return replaceInstUsesWith(*II, UndefValue::get(II->getType()));
3403
3404 // Clamp mask to used bits
3405 if ((Mask & FullMask) != Mask) {
Craig Topperbb4069e2017-07-07 23:16:26 +00003406 CallInst *NewCall = Builder.CreateCall(II->getCalledFunction(),
Matt Arsenault46a03822016-09-03 07:06:58 +00003407 { Src0, ConstantInt::get(Src1->getType(), Mask & FullMask) }
3408 );
3409
3410 NewCall->takeName(II);
3411 return replaceInstUsesWith(*II, NewCall);
3412 }
3413
3414 break;
3415 }
3416
3417 const APFloat &Val = CVal->getValueAPF();
3418
3419 bool Result =
3420 ((Mask & S_NAN) && Val.isNaN() && Val.isSignaling()) ||
3421 ((Mask & Q_NAN) && Val.isNaN() && !Val.isSignaling()) ||
3422 ((Mask & N_INFINITY) && Val.isInfinity() && Val.isNegative()) ||
3423 ((Mask & N_NORMAL) && Val.isNormal() && Val.isNegative()) ||
3424 ((Mask & N_SUBNORMAL) && Val.isDenormal() && Val.isNegative()) ||
3425 ((Mask & N_ZERO) && Val.isZero() && Val.isNegative()) ||
3426 ((Mask & P_ZERO) && Val.isZero() && !Val.isNegative()) ||
3427 ((Mask & P_SUBNORMAL) && Val.isDenormal() && !Val.isNegative()) ||
3428 ((Mask & P_NORMAL) && Val.isNormal() && !Val.isNegative()) ||
3429 ((Mask & P_INFINITY) && Val.isInfinity() && !Val.isNegative());
3430
3431 return replaceInstUsesWith(*II, ConstantInt::get(II->getType(), Result));
3432 }
Matt Arsenault1f17c662017-02-22 00:27:34 +00003433 case Intrinsic::amdgcn_cvt_pkrtz: {
3434 Value *Src0 = II->getArgOperand(0);
3435 Value *Src1 = II->getArgOperand(1);
3436 if (const ConstantFP *C0 = dyn_cast<ConstantFP>(Src0)) {
3437 if (const ConstantFP *C1 = dyn_cast<ConstantFP>(Src1)) {
3438 const fltSemantics &HalfSem
3439 = II->getType()->getScalarType()->getFltSemantics();
3440 bool LosesInfo;
3441 APFloat Val0 = C0->getValueAPF();
3442 APFloat Val1 = C1->getValueAPF();
3443 Val0.convert(HalfSem, APFloat::rmTowardZero, &LosesInfo);
3444 Val1.convert(HalfSem, APFloat::rmTowardZero, &LosesInfo);
3445
3446 Constant *Folded = ConstantVector::get({
3447 ConstantFP::get(II->getContext(), Val0),
3448 ConstantFP::get(II->getContext(), Val1) });
3449 return replaceInstUsesWith(*II, Folded);
3450 }
3451 }
3452
3453 if (isa<UndefValue>(Src0) && isa<UndefValue>(Src1))
3454 return replaceInstUsesWith(*II, UndefValue::get(II->getType()));
3455
3456 break;
3457 }
Marek Olsak13e47412018-01-31 20:18:04 +00003458 case Intrinsic::amdgcn_cvt_pknorm_i16:
3459 case Intrinsic::amdgcn_cvt_pknorm_u16:
3460 case Intrinsic::amdgcn_cvt_pk_i16:
3461 case Intrinsic::amdgcn_cvt_pk_u16: {
3462 Value *Src0 = II->getArgOperand(0);
3463 Value *Src1 = II->getArgOperand(1);
3464
3465 if (isa<UndefValue>(Src0) && isa<UndefValue>(Src1))
3466 return replaceInstUsesWith(*II, UndefValue::get(II->getType()));
3467
3468 break;
3469 }
Matt Arsenaultf5262252017-02-22 23:04:58 +00003470 case Intrinsic::amdgcn_ubfe:
3471 case Intrinsic::amdgcn_sbfe: {
3472 // Decompose simple cases into standard shifts.
3473 Value *Src = II->getArgOperand(0);
3474 if (isa<UndefValue>(Src))
3475 return replaceInstUsesWith(*II, Src);
3476
3477 unsigned Width;
3478 Type *Ty = II->getType();
3479 unsigned IntSize = Ty->getIntegerBitWidth();
3480
3481 ConstantInt *CWidth = dyn_cast<ConstantInt>(II->getArgOperand(2));
3482 if (CWidth) {
3483 Width = CWidth->getZExtValue();
3484 if ((Width & (IntSize - 1)) == 0)
3485 return replaceInstUsesWith(*II, ConstantInt::getNullValue(Ty));
3486
3487 if (Width >= IntSize) {
3488 // Hardware ignores high bits, so remove those.
3489 II->setArgOperand(2, ConstantInt::get(CWidth->getType(),
3490 Width & (IntSize - 1)));
3491 return II;
3492 }
3493 }
3494
3495 unsigned Offset;
3496 ConstantInt *COffset = dyn_cast<ConstantInt>(II->getArgOperand(1));
3497 if (COffset) {
3498 Offset = COffset->getZExtValue();
3499 if (Offset >= IntSize) {
3500 II->setArgOperand(1, ConstantInt::get(COffset->getType(),
3501 Offset & (IntSize - 1)));
3502 return II;
3503 }
3504 }
3505
3506 bool Signed = II->getIntrinsicID() == Intrinsic::amdgcn_sbfe;
3507
Matt Arsenaultf5262252017-02-22 23:04:58 +00003508 if (!CWidth || !COffset)
3509 break;
3510
Tom Stellard28d66212018-11-08 17:57:57 +00003511 // The case of Width == 0 is handled above, which makes this tranformation
3512 // safe. If Width == 0, then the ashr and lshr instructions become poison
3513 // value since the shift amount would be equal to the bit size.
3514 assert(Width != 0);
3515
Matt Arsenaultf5262252017-02-22 23:04:58 +00003516 // TODO: This allows folding to undef when the hardware has specific
3517 // behavior?
3518 if (Offset + Width < IntSize) {
Craig Topperbb4069e2017-07-07 23:16:26 +00003519 Value *Shl = Builder.CreateShl(Src, IntSize - Offset - Width);
3520 Value *RightShift = Signed ? Builder.CreateAShr(Shl, IntSize - Width)
3521 : Builder.CreateLShr(Shl, IntSize - Width);
Matt Arsenaultf5262252017-02-22 23:04:58 +00003522 RightShift->takeName(II);
3523 return replaceInstUsesWith(*II, RightShift);
3524 }
3525
Craig Topperbb4069e2017-07-07 23:16:26 +00003526 Value *RightShift = Signed ? Builder.CreateAShr(Src, Offset)
3527 : Builder.CreateLShr(Src, Offset);
Matt Arsenaultf5262252017-02-22 23:04:58 +00003528
3529 RightShift->takeName(II);
3530 return replaceInstUsesWith(*II, RightShift);
3531 }
Matt Arsenaultd4bca1e2017-02-23 00:44:03 +00003532 case Intrinsic::amdgcn_exp:
3533 case Intrinsic::amdgcn_exp_compr: {
3534 ConstantInt *En = dyn_cast<ConstantInt>(II->getArgOperand(1));
3535 if (!En) // Illegal.
3536 break;
3537
3538 unsigned EnBits = En->getZExtValue();
3539 if (EnBits == 0xf)
3540 break; // All inputs enabled.
3541
3542 bool IsCompr = II->getIntrinsicID() == Intrinsic::amdgcn_exp_compr;
3543 bool Changed = false;
3544 for (int I = 0; I < (IsCompr ? 2 : 4); ++I) {
3545 if ((!IsCompr && (EnBits & (1 << I)) == 0) ||
3546 (IsCompr && ((EnBits & (0x3 << (2 * I))) == 0))) {
3547 Value *Src = II->getArgOperand(I + 2);
3548 if (!isa<UndefValue>(Src)) {
3549 II->setArgOperand(I + 2, UndefValue::get(Src->getType()));
3550 Changed = true;
3551 }
3552 }
3553 }
3554
3555 if (Changed)
3556 return II;
3557
3558 break;
Matt Arsenaultcdb468c2017-02-27 23:08:49 +00003559 }
3560 case Intrinsic::amdgcn_fmed3: {
3561 // Note this does not preserve proper sNaN behavior if IEEE-mode is enabled
3562 // for the shader.
3563
3564 Value *Src0 = II->getArgOperand(0);
3565 Value *Src1 = II->getArgOperand(1);
3566 Value *Src2 = II->getArgOperand(2);
3567
Matt Arsenault24ce89b2018-07-05 17:05:36 +00003568 // Checking for NaN before canonicalization provides better fidelity when
3569 // mapping other operations onto fmed3 since the order of operands is
3570 // unchanged.
3571 CallInst *NewCall = nullptr;
3572 if (match(Src0, m_NaN()) || isa<UndefValue>(Src0)) {
3573 NewCall = Builder.CreateMinNum(Src1, Src2);
3574 } else if (match(Src1, m_NaN()) || isa<UndefValue>(Src1)) {
3575 NewCall = Builder.CreateMinNum(Src0, Src2);
3576 } else if (match(Src2, m_NaN()) || isa<UndefValue>(Src2)) {
3577 NewCall = Builder.CreateMaxNum(Src0, Src1);
3578 }
3579
3580 if (NewCall) {
3581 NewCall->copyFastMathFlags(II);
3582 NewCall->takeName(II);
3583 return replaceInstUsesWith(*II, NewCall);
3584 }
3585
Matt Arsenaultcdb468c2017-02-27 23:08:49 +00003586 bool Swap = false;
3587 // Canonicalize constants to RHS operands.
3588 //
3589 // fmed3(c0, x, c1) -> fmed3(x, c0, c1)
3590 if (isa<Constant>(Src0) && !isa<Constant>(Src1)) {
3591 std::swap(Src0, Src1);
3592 Swap = true;
3593 }
3594
3595 if (isa<Constant>(Src1) && !isa<Constant>(Src2)) {
3596 std::swap(Src1, Src2);
3597 Swap = true;
3598 }
3599
3600 if (isa<Constant>(Src0) && !isa<Constant>(Src1)) {
3601 std::swap(Src0, Src1);
3602 Swap = true;
3603 }
3604
3605 if (Swap) {
3606 II->setArgOperand(0, Src0);
3607 II->setArgOperand(1, Src1);
3608 II->setArgOperand(2, Src2);
3609 return II;
3610 }
3611
Matt Arsenaultcdb468c2017-02-27 23:08:49 +00003612 if (const ConstantFP *C0 = dyn_cast<ConstantFP>(Src0)) {
3613 if (const ConstantFP *C1 = dyn_cast<ConstantFP>(Src1)) {
3614 if (const ConstantFP *C2 = dyn_cast<ConstantFP>(Src2)) {
3615 APFloat Result = fmed3AMDGCN(C0->getValueAPF(), C1->getValueAPF(),
3616 C2->getValueAPF());
3617 return replaceInstUsesWith(*II,
Craig Topperbb4069e2017-07-07 23:16:26 +00003618 ConstantFP::get(Builder.getContext(), Result));
Matt Arsenaultcdb468c2017-02-27 23:08:49 +00003619 }
3620 }
3621 }
3622
3623 break;
Matt Arsenaultd4bca1e2017-02-23 00:44:03 +00003624 }
Matt Arsenaultd81f5572017-03-13 18:14:02 +00003625 case Intrinsic::amdgcn_icmp:
3626 case Intrinsic::amdgcn_fcmp: {
3627 const ConstantInt *CC = dyn_cast<ConstantInt>(II->getArgOperand(2));
3628 if (!CC)
3629 break;
3630
3631 // Guard against invalid arguments.
3632 int64_t CCVal = CC->getZExtValue();
3633 bool IsInteger = II->getIntrinsicID() == Intrinsic::amdgcn_icmp;
3634 if ((IsInteger && (CCVal < CmpInst::FIRST_ICMP_PREDICATE ||
3635 CCVal > CmpInst::LAST_ICMP_PREDICATE)) ||
3636 (!IsInteger && (CCVal < CmpInst::FIRST_FCMP_PREDICATE ||
3637 CCVal > CmpInst::LAST_FCMP_PREDICATE)))
3638 break;
3639
3640 Value *Src0 = II->getArgOperand(0);
3641 Value *Src1 = II->getArgOperand(1);
3642
3643 if (auto *CSrc0 = dyn_cast<Constant>(Src0)) {
3644 if (auto *CSrc1 = dyn_cast<Constant>(Src1)) {
3645 Constant *CCmp = ConstantExpr::getCompare(CCVal, CSrc0, CSrc1);
Nicolai Haehnle9c661852017-04-24 17:08:43 +00003646 if (CCmp->isNullValue()) {
3647 return replaceInstUsesWith(
3648 *II, ConstantExpr::getSExt(CCmp, II->getType()));
3649 }
3650
3651 // The result of V_ICMP/V_FCMP assembly instructions (which this
3652 // intrinsic exposes) is one bit per thread, masked with the EXEC
3653 // register (which contains the bitmask of live threads). So a
3654 // comparison that always returns true is the same as a read of the
3655 // EXEC register.
3656 Value *NewF = Intrinsic::getDeclaration(
3657 II->getModule(), Intrinsic::read_register, II->getType());
3658 Metadata *MDArgs[] = {MDString::get(II->getContext(), "exec")};
3659 MDNode *MD = MDNode::get(II->getContext(), MDArgs);
3660 Value *Args[] = {MetadataAsValue::get(II->getContext(), MD)};
Craig Topperbb4069e2017-07-07 23:16:26 +00003661 CallInst *NewCall = Builder.CreateCall(NewF, Args);
Nicolai Haehnle9c661852017-04-24 17:08:43 +00003662 NewCall->addAttribute(AttributeList::FunctionIndex,
3663 Attribute::Convergent);
3664 NewCall->takeName(II);
3665 return replaceInstUsesWith(*II, NewCall);
Matt Arsenaultd81f5572017-03-13 18:14:02 +00003666 }
3667
3668 // Canonicalize constants to RHS.
3669 CmpInst::Predicate SwapPred
3670 = CmpInst::getSwappedPredicate(static_cast<CmpInst::Predicate>(CCVal));
3671 II->setArgOperand(0, Src1);
3672 II->setArgOperand(1, Src0);
3673 II->setArgOperand(2, ConstantInt::get(CC->getType(),
3674 static_cast<int>(SwapPred)));
3675 return II;
3676 }
3677
3678 if (CCVal != CmpInst::ICMP_EQ && CCVal != CmpInst::ICMP_NE)
3679 break;
3680
3681 // Canonicalize compare eq with true value to compare != 0
3682 // llvm.amdgcn.icmp(zext (i1 x), 1, eq)
3683 // -> llvm.amdgcn.icmp(zext (i1 x), 0, ne)
3684 // llvm.amdgcn.icmp(sext (i1 x), -1, eq)
3685 // -> llvm.amdgcn.icmp(sext (i1 x), 0, ne)
3686 Value *ExtSrc;
3687 if (CCVal == CmpInst::ICMP_EQ &&
3688 ((match(Src1, m_One()) && match(Src0, m_ZExt(m_Value(ExtSrc)))) ||
3689 (match(Src1, m_AllOnes()) && match(Src0, m_SExt(m_Value(ExtSrc))))) &&
3690 ExtSrc->getType()->isIntegerTy(1)) {
3691 II->setArgOperand(1, ConstantInt::getNullValue(Src1->getType()));
3692 II->setArgOperand(2, ConstantInt::get(CC->getType(), CmpInst::ICMP_NE));
3693 return II;
3694 }
3695
3696 CmpInst::Predicate SrcPred;
3697 Value *SrcLHS;
3698 Value *SrcRHS;
3699
3700 // Fold compare eq/ne with 0 from a compare result as the predicate to the
3701 // intrinsic. The typical use is a wave vote function in the library, which
3702 // will be fed from a user code condition compared with 0. Fold in the
3703 // redundant compare.
3704
3705 // llvm.amdgcn.icmp([sz]ext ([if]cmp pred a, b), 0, ne)
3706 // -> llvm.amdgcn.[if]cmp(a, b, pred)
3707 //
3708 // llvm.amdgcn.icmp([sz]ext ([if]cmp pred a, b), 0, eq)
3709 // -> llvm.amdgcn.[if]cmp(a, b, inv pred)
3710 if (match(Src1, m_Zero()) &&
3711 match(Src0,
3712 m_ZExtOrSExt(m_Cmp(SrcPred, m_Value(SrcLHS), m_Value(SrcRHS))))) {
3713 if (CCVal == CmpInst::ICMP_EQ)
3714 SrcPred = CmpInst::getInversePredicate(SrcPred);
3715
3716 Intrinsic::ID NewIID = CmpInst::isFPPredicate(SrcPred) ?
3717 Intrinsic::amdgcn_fcmp : Intrinsic::amdgcn_icmp;
3718
Matt Arsenault9a389fb2018-08-15 21:14:25 +00003719 Type *Ty = SrcLHS->getType();
3720 if (auto *CmpType = dyn_cast<IntegerType>(Ty)) {
3721 // Promote to next legal integer type.
3722 unsigned Width = CmpType->getBitWidth();
3723 unsigned NewWidth = Width;
Marek Olsak33eb4d92019-01-15 02:13:18 +00003724
3725 // Don't do anything for i1 comparisons.
3726 if (Width == 1)
3727 break;
3728
Matt Arsenault9a389fb2018-08-15 21:14:25 +00003729 if (Width <= 16)
3730 NewWidth = 16;
3731 else if (Width <= 32)
3732 NewWidth = 32;
3733 else if (Width <= 64)
3734 NewWidth = 64;
3735 else if (Width > 64)
3736 break; // Can't handle this.
3737
3738 if (Width != NewWidth) {
3739 IntegerType *CmpTy = Builder.getIntNTy(NewWidth);
3740 if (CmpInst::isSigned(SrcPred)) {
3741 SrcLHS = Builder.CreateSExt(SrcLHS, CmpTy);
3742 SrcRHS = Builder.CreateSExt(SrcRHS, CmpTy);
3743 } else {
3744 SrcLHS = Builder.CreateZExt(SrcLHS, CmpTy);
3745 SrcRHS = Builder.CreateZExt(SrcRHS, CmpTy);
3746 }
3747 }
3748 } else if (!Ty->isFloatTy() && !Ty->isDoubleTy() && !Ty->isHalfTy())
3749 break;
3750
Matt Arsenaultd81f5572017-03-13 18:14:02 +00003751 Value *NewF = Intrinsic::getDeclaration(II->getModule(), NewIID,
3752 SrcLHS->getType());
3753 Value *Args[] = { SrcLHS, SrcRHS,
3754 ConstantInt::get(CC->getType(), SrcPred) };
Craig Topperbb4069e2017-07-07 23:16:26 +00003755 CallInst *NewCall = Builder.CreateCall(NewF, Args);
Matt Arsenaultd81f5572017-03-13 18:14:02 +00003756 NewCall->takeName(II);
3757 return replaceInstUsesWith(*II, NewCall);
3758 }
3759
3760 break;
3761 }
Marek Olsak2114fc32017-10-24 10:26:59 +00003762 case Intrinsic::amdgcn_wqm_vote: {
3763 // wqm_vote is identity when the argument is constant.
3764 if (!isa<Constant>(II->getArgOperand(0)))
3765 break;
3766
3767 return replaceInstUsesWith(*II, II->getArgOperand(0));
3768 }
Marek Olsakce76ea02017-10-24 10:27:13 +00003769 case Intrinsic::amdgcn_kill: {
3770 const ConstantInt *C = dyn_cast<ConstantInt>(II->getArgOperand(0));
3771 if (!C || !C->getZExtValue())
3772 break;
3773
3774 // amdgcn.kill(i1 1) is a no-op
3775 return eraseInstFromFunction(CI);
3776 }
Stanislav Mekhanoshin0e132dc2018-05-22 08:04:33 +00003777 case Intrinsic::amdgcn_update_dpp: {
3778 Value *Old = II->getArgOperand(0);
3779
3780 auto BC = dyn_cast<ConstantInt>(II->getArgOperand(5));
3781 auto RM = dyn_cast<ConstantInt>(II->getArgOperand(3));
3782 auto BM = dyn_cast<ConstantInt>(II->getArgOperand(4));
3783 if (!BC || !RM || !BM ||
3784 BC->isZeroValue() ||
3785 RM->getZExtValue() != 0xF ||
3786 BM->getZExtValue() != 0xF ||
3787 isa<UndefValue>(Old))
3788 break;
3789
3790 // If bound_ctrl = 1, row mask = bank mask = 0xf we can omit old value.
3791 II->setOperand(0, UndefValue::get(Old->getType()));
3792 return II;
3793 }
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003794 case Intrinsic::stackrestore: {
3795 // If the save is right next to the restore, remove the restore. This can
3796 // happen when variable allocas are DCE'd.
Gabor Greif589a0b92010-06-24 12:58:35 +00003797 if (IntrinsicInst *SS = dyn_cast<IntrinsicInst>(II->getArgOperand(0))) {
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003798 if (SS->getIntrinsicID() == Intrinsic::stacksave) {
Vedant Kumarf01827f2018-06-19 23:42:17 +00003799 // Skip over debug info.
3800 if (SS->getNextNonDebugInstruction() == II) {
Sanjay Patel4b198802016-02-01 22:23:39 +00003801 return eraseInstFromFunction(CI);
Davide Italiano189c2cf2018-06-08 20:42:36 +00003802 }
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003803 }
3804 }
Jim Grosbach7815f562012-02-03 00:07:04 +00003805
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003806 // Scan down this block to see if there is another stack restore in the
3807 // same block without an intervening call/alloca.
Duncan P. N. Exon Smith9f8aaf22015-10-13 16:59:33 +00003808 BasicBlock::iterator BI(II);
Chandler Carruthedb12a82018-10-15 10:04:59 +00003809 Instruction *TI = II->getParent()->getTerminator();
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003810 bool CannotRemove = false;
3811 for (++BI; &*BI != TI; ++BI) {
Nuno Lopes55fff832012-06-21 15:45:28 +00003812 if (isa<AllocaInst>(BI)) {
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003813 CannotRemove = true;
3814 break;
3815 }
3816 if (CallInst *BCI = dyn_cast<CallInst>(BI)) {
3817 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(BCI)) {
3818 // If there is a stackrestore below this one, remove this one.
3819 if (II->getIntrinsicID() == Intrinsic::stackrestore)
Sanjay Patel4b198802016-02-01 22:23:39 +00003820 return eraseInstFromFunction(CI);
Reid Kleckner892ae2e2016-02-27 00:53:54 +00003821
3822 // Bail if we cross over an intrinsic with side effects, such as
3823 // llvm.stacksave, llvm.read_register, or llvm.setjmp.
3824 if (II->mayHaveSideEffects()) {
3825 CannotRemove = true;
3826 break;
3827 }
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003828 } else {
3829 // If we found a non-intrinsic call, we can't remove the stack
3830 // restore.
3831 CannotRemove = true;
3832 break;
3833 }
3834 }
3835 }
Jim Grosbach7815f562012-02-03 00:07:04 +00003836
Bill Wendlingf891bf82011-07-31 06:30:59 +00003837 // If the stack restore is in a return, resume, or unwind block and if there
3838 // are no allocas or calls between the restore and the return, nuke the
3839 // restore.
Bill Wendlingd5d95b02012-02-06 21:16:41 +00003840 if (!CannotRemove && (isa<ReturnInst>(TI) || isa<ResumeInst>(TI)))
Sanjay Patel4b198802016-02-01 22:23:39 +00003841 return eraseInstFromFunction(CI);
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003842 break;
3843 }
Vitaly Bukaf0500b62016-07-28 22:50:48 +00003844 case Intrinsic::lifetime_start:
Vitaly Buka0ab23cf2016-07-28 22:59:03 +00003845 // Asan needs to poison memory to detect invalid access which is possible
3846 // even for empty lifetime range.
Evgeniy Stepanovc667c1f2017-12-09 00:21:41 +00003847 if (II->getFunction()->hasFnAttribute(Attribute::SanitizeAddress) ||
3848 II->getFunction()->hasFnAttribute(Attribute::SanitizeHWAddress))
Vitaly Buka0ab23cf2016-07-28 22:59:03 +00003849 break;
3850
Arnaud A. de Grandmaison333ef382016-05-10 09:24:49 +00003851 if (removeTriviallyEmptyRange(*II, Intrinsic::lifetime_start,
3852 Intrinsic::lifetime_end, *this))
3853 return nullptr;
Arnaud A. de Grandmaison849f3bf2015-10-01 14:54:31 +00003854 break;
Hal Finkelf5867a72014-07-25 21:45:17 +00003855 case Intrinsic::assume: {
David Majnemerfcc58112016-04-08 16:37:12 +00003856 Value *IIOperand = II->getArgOperand(0);
Sanjay Patel825a4fa2018-06-20 13:22:26 +00003857 // Remove an assume if it is followed by an identical assume.
3858 // TODO: Do we need this? Unless there are conflicting assumptions, the
3859 // computeKnownBits(IIOperand) below here eliminates redundant assumes.
3860 Instruction *Next = II->getNextNonDebugInstruction();
3861 if (match(Next, m_Intrinsic<Intrinsic::assume>(m_Specific(IIOperand))))
David Majnemerfcc58112016-04-08 16:37:12 +00003862 return eraseInstFromFunction(CI);
3863
Hal Finkelf5867a72014-07-25 21:45:17 +00003864 // Canonicalize assume(a && b) -> assume(a); assume(b);
Hal Finkel74c2f352014-09-07 12:44:26 +00003865 // Note: New assumption intrinsics created here are registered by
3866 // the InstCombineIRInserter object.
David Majnemerfcc58112016-04-08 16:37:12 +00003867 Value *AssumeIntrinsic = II->getCalledValue(), *A, *B;
Hal Finkelf5867a72014-07-25 21:45:17 +00003868 if (match(IIOperand, m_And(m_Value(A), m_Value(B)))) {
Craig Topperbb4069e2017-07-07 23:16:26 +00003869 Builder.CreateCall(AssumeIntrinsic, A, II->getName());
3870 Builder.CreateCall(AssumeIntrinsic, B, II->getName());
Sanjay Patel4b198802016-02-01 22:23:39 +00003871 return eraseInstFromFunction(*II);
Hal Finkelf5867a72014-07-25 21:45:17 +00003872 }
3873 // assume(!(a || b)) -> assume(!a); assume(!b);
3874 if (match(IIOperand, m_Not(m_Or(m_Value(A), m_Value(B))))) {
Craig Topperbb4069e2017-07-07 23:16:26 +00003875 Builder.CreateCall(AssumeIntrinsic, Builder.CreateNot(A), II->getName());
3876 Builder.CreateCall(AssumeIntrinsic, Builder.CreateNot(B), II->getName());
Sanjay Patel4b198802016-02-01 22:23:39 +00003877 return eraseInstFromFunction(*II);
Hal Finkelf5867a72014-07-25 21:45:17 +00003878 }
Hal Finkel04a15612014-10-04 21:27:06 +00003879
Philip Reames66c6de62014-11-11 23:33:19 +00003880 // assume( (load addr) != null ) -> add 'nonnull' metadata to load
3881 // (if assume is valid at the load)
Sanjay Patelf0d1e7732017-01-03 22:25:31 +00003882 CmpInst::Predicate Pred;
3883 Instruction *LHS;
3884 if (match(IIOperand, m_ICmp(Pred, m_Instruction(LHS), m_Zero())) &&
3885 Pred == ICmpInst::ICMP_NE && LHS->getOpcode() == Instruction::Load &&
3886 LHS->getType()->isPointerTy() &&
3887 isValidAssumeForContext(II, LHS, &DT)) {
3888 MDNode *MD = MDNode::get(II->getContext(), None);
3889 LHS->setMetadata(LLVMContext::MD_nonnull, MD);
3890 return eraseInstFromFunction(*II);
3891
Chandler Carruth24969102015-02-10 08:07:32 +00003892 // TODO: apply nonnull return attributes to calls and invokes
Philip Reames66c6de62014-11-11 23:33:19 +00003893 // TODO: apply range metadata for range check patterns?
3894 }
Sanjay Patelf0d1e7732017-01-03 22:25:31 +00003895
Hal Finkel04a15612014-10-04 21:27:06 +00003896 // If there is a dominating assume with the same condition as this one,
3897 // then this one is redundant, and should be removed.
Craig Topperb45eabc2017-04-26 16:39:58 +00003898 KnownBits Known(1);
3899 computeKnownBits(IIOperand, Known, 0, II);
Craig Topperf0aeee02017-05-05 17:36:09 +00003900 if (Known.isAllOnes())
Sanjay Patel4b198802016-02-01 22:23:39 +00003901 return eraseInstFromFunction(*II);
Hal Finkel04a15612014-10-04 21:27:06 +00003902
Hal Finkel8a9a7832017-01-11 13:24:24 +00003903 // Update the cache of affected values for this assumption (we might be
3904 // here because we just simplified the condition).
3905 AC.updateAffectedValues(II);
Hal Finkelf5867a72014-07-25 21:45:17 +00003906 break;
3907 }
Philip Reames9db26ff2014-12-29 23:27:30 +00003908 case Intrinsic::experimental_gc_relocate: {
3909 // Translate facts known about a pointer before relocating into
3910 // facts about the relocate value, while being careful to
3911 // preserve relocation semantics.
Manuel Jacob83eefa62016-01-05 04:03:00 +00003912 Value *DerivedPtr = cast<GCRelocateInst>(II)->getDerivedPtr();
Philip Reames9db26ff2014-12-29 23:27:30 +00003913
3914 // Remove the relocation if unused, note that this check is required
3915 // to prevent the cases below from looping forever.
3916 if (II->use_empty())
Sanjay Patel4b198802016-02-01 22:23:39 +00003917 return eraseInstFromFunction(*II);
Philip Reames9db26ff2014-12-29 23:27:30 +00003918
3919 // Undef is undef, even after relocation.
3920 // TODO: provide a hook for this in GCStrategy. This is clearly legal for
3921 // most practical collectors, but there was discussion in the review thread
3922 // about whether it was legal for all possible collectors.
Philip Reamesea4d8e82016-02-09 21:09:22 +00003923 if (isa<UndefValue>(DerivedPtr))
3924 // Use undef of gc_relocate's type to replace it.
3925 return replaceInstUsesWith(*II, UndefValue::get(II->getType()));
Philip Reames9db26ff2014-12-29 23:27:30 +00003926
Philip Reamesea4d8e82016-02-09 21:09:22 +00003927 if (auto *PT = dyn_cast<PointerType>(II->getType())) {
3928 // The relocation of null will be null for most any collector.
3929 // TODO: provide a hook for this in GCStrategy. There might be some
3930 // weird collector this property does not hold for.
3931 if (isa<ConstantPointerNull>(DerivedPtr))
3932 // Use null-pointer of gc_relocate's type to replace it.
3933 return replaceInstUsesWith(*II, ConstantPointerNull::get(PT));
Simon Pilgrimc0c56e72016-04-24 17:00:34 +00003934
Philip Reamesea4d8e82016-02-09 21:09:22 +00003935 // isKnownNonNull -> nonnull attribute
Philip Reamesb8d8db32018-11-12 20:00:53 +00003936 if (!II->hasRetAttr(Attribute::NonNull) &&
3937 isKnownNonZero(DerivedPtr, DL, 0, &AC, II, &DT)) {
Reid Klecknerb5180542017-03-21 16:57:19 +00003938 II->addAttribute(AttributeList::ReturnIndex, Attribute::NonNull);
Philip Reamesb8d8db32018-11-12 20:00:53 +00003939 return II;
3940 }
Ramkumar Ramachandra8fcb4982015-02-14 19:37:54 +00003941 }
Philip Reames9db26ff2014-12-29 23:27:30 +00003942
3943 // TODO: bitcast(relocate(p)) -> relocate(bitcast(p))
3944 // Canonicalize on the type from the uses to the defs
Ramkumar Ramachandra8fcb4982015-02-14 19:37:54 +00003945
Philip Reames9db26ff2014-12-29 23:27:30 +00003946 // TODO: relocate((gep p, C, C2, ...)) -> gep(relocate(p), C, C2, ...)
Philip Reamesea4d8e82016-02-09 21:09:22 +00003947 break;
Philip Reames9db26ff2014-12-29 23:27:30 +00003948 }
Artur Pilipenkoe812ca02017-01-25 14:12:12 +00003949
3950 case Intrinsic::experimental_guard: {
Philip Reames79e917d2018-05-09 22:56:32 +00003951 // Is this guard followed by another guard? We scan forward over a small
3952 // fixed window of instructions to handle common cases with conditions
3953 // computed between guards.
Sanjoy Dase0e57952017-02-01 16:34:55 +00003954 Instruction *NextInst = II->getNextNode();
Philip Reames913a7792018-05-10 00:05:29 +00003955 for (unsigned i = 0; i < GuardWideningWindow; i++) {
Philip Reames79e917d2018-05-09 22:56:32 +00003956 // Note: Using context-free form to avoid compile time blow up
3957 if (!isSafeToSpeculativelyExecute(NextInst))
3958 break;
3959 NextInst = NextInst->getNextNode();
3960 }
Sanjoy Dase0e57952017-02-01 16:34:55 +00003961 Value *NextCond = nullptr;
3962 if (match(NextInst,
3963 m_Intrinsic<Intrinsic::experimental_guard>(m_Value(NextCond)))) {
3964 Value *CurrCond = II->getArgOperand(0);
Artur Pilipenkoe812ca02017-01-25 14:12:12 +00003965
Simon Pilgrim68168d12017-03-30 12:59:53 +00003966 // Remove a guard that it is immediately preceded by an identical guard.
Sanjoy Dase0e57952017-02-01 16:34:55 +00003967 if (CurrCond == NextCond)
3968 return eraseInstFromFunction(*NextInst);
3969
3970 // Otherwise canonicalize guard(a); guard(b) -> guard(a & b).
Philip Reames79e917d2018-05-09 22:56:32 +00003971 Instruction* MoveI = II->getNextNode();
3972 while (MoveI != NextInst) {
3973 auto *Temp = MoveI;
3974 MoveI = MoveI->getNextNode();
3975 Temp->moveBefore(II);
3976 }
Craig Topperbb4069e2017-07-07 23:16:26 +00003977 II->setArgOperand(0, Builder.CreateAnd(CurrCond, NextCond));
Sanjoy Dase0e57952017-02-01 16:34:55 +00003978 return eraseInstFromFunction(*NextInst);
3979 }
Artur Pilipenkoe812ca02017-01-25 14:12:12 +00003980 break;
3981 }
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003982 }
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003983 return visitCallSite(II);
3984}
3985
Davide Italianoaec46172017-01-31 18:09:05 +00003986// Fence instruction simplification
3987Instruction *InstCombiner::visitFenceInst(FenceInst &FI) {
3988 // Remove identical consecutive fences.
Vedant Kumarf01827f2018-06-19 23:42:17 +00003989 Instruction *Next = FI.getNextNonDebugInstruction();
Tim Northover9b800602018-06-06 12:46:02 +00003990 if (auto *NFI = dyn_cast<FenceInst>(Next))
Davide Italianoaec46172017-01-31 18:09:05 +00003991 if (FI.isIdenticalTo(NFI))
3992 return eraseInstFromFunction(FI);
3993 return nullptr;
3994}
3995
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003996// InvokeInst simplification
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003997Instruction *InstCombiner::visitInvokeInst(InvokeInst &II) {
3998 return visitCallSite(&II);
3999}
4000
Sanjay Patelcd4377c2016-01-20 22:24:38 +00004001/// If this cast does not affect the value passed through the varargs area, we
4002/// can eliminate the use of the cast.
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004003static bool isSafeToEliminateVarargsCast(const CallSite CS,
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004004 const DataLayout &DL,
4005 const CastInst *const CI,
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004006 const int ix) {
4007 if (!CI->isLosslessCast())
4008 return false;
4009
Philip Reames1a1bdb22014-12-02 18:50:36 +00004010 // If this is a GC intrinsic, avoid munging types. We need types for
4011 // statepoint reconstruction in SelectionDAG.
4012 // TODO: This is probably something which should be expanded to all
4013 // intrinsics since the entire point of intrinsics is that
4014 // they are understandable by the optimizer.
4015 if (isStatepoint(CS) || isGCRelocate(CS) || isGCResult(CS))
4016 return false;
4017
Reid Kleckner26af2ca2014-01-28 02:38:36 +00004018 // The size of ByVal or InAlloca arguments is derived from the type, so we
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004019 // can't change to a type with a different size. If the size were
4020 // passed explicitly we could avoid this check.
Reid Kleckner26af2ca2014-01-28 02:38:36 +00004021 if (!CS.isByValOrInAllocaArgument(ix))
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004022 return true;
4023
Jim Grosbach7815f562012-02-03 00:07:04 +00004024 Type* SrcTy =
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004025 cast<PointerType>(CI->getOperand(0)->getType())->getElementType();
Chris Lattner229907c2011-07-18 04:54:35 +00004026 Type* DstTy = cast<PointerType>(CI->getType())->getElementType();
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004027 if (!SrcTy->isSized() || !DstTy->isSized())
4028 return false;
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004029 if (DL.getTypeAllocSize(SrcTy) != DL.getTypeAllocSize(DstTy))
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004030 return false;
4031 return true;
4032}
4033
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004034Instruction *InstCombiner::tryOptimizeCall(CallInst *CI) {
Craig Topperf40110f2014-04-25 05:29:35 +00004035 if (!CI->getCalledFunction()) return nullptr;
Eric Christophera7fb58f2010-03-06 10:50:38 +00004036
Chandler Carruthba4c5172015-01-21 11:23:40 +00004037 auto InstCombineRAUW = [this](Instruction *From, Value *With) {
Sanjay Patel4b198802016-02-01 22:23:39 +00004038 replaceInstUsesWith(*From, With);
Chandler Carruthba4c5172015-01-21 11:23:40 +00004039 };
Amara Emerson54f60252018-10-11 14:51:11 +00004040 auto InstCombineErase = [this](Instruction *I) {
4041 eraseInstFromFunction(*I);
4042 };
4043 LibCallSimplifier Simplifier(DL, &TLI, ORE, InstCombineRAUW,
4044 InstCombineErase);
Chandler Carruthba4c5172015-01-21 11:23:40 +00004045 if (Value *With = Simplifier.optimizeCall(CI)) {
Meador Ingee3f2b262012-11-30 04:05:06 +00004046 ++NumSimplified;
Sanjay Patel4b198802016-02-01 22:23:39 +00004047 return CI->use_empty() ? CI : replaceInstUsesWith(*CI, With);
Meador Ingee3f2b262012-11-30 04:05:06 +00004048 }
Meador Ingedf796f82012-10-13 16:45:24 +00004049
Craig Topperf40110f2014-04-25 05:29:35 +00004050 return nullptr;
Eric Christophera7fb58f2010-03-06 10:50:38 +00004051}
4052
Sanjay Patel6038d3e2016-01-29 23:27:03 +00004053static IntrinsicInst *findInitTrampolineFromAlloca(Value *TrampMem) {
Duncan Sandsa0984362011-09-06 13:37:06 +00004054 // Strip off at most one level of pointer casts, looking for an alloca. This
4055 // is good enough in practice and simpler than handling any number of casts.
4056 Value *Underlying = TrampMem->stripPointerCasts();
4057 if (Underlying != TrampMem &&
Chandler Carruthcdf47882014-03-09 03:16:01 +00004058 (!Underlying->hasOneUse() || Underlying->user_back() != TrampMem))
Craig Topperf40110f2014-04-25 05:29:35 +00004059 return nullptr;
Duncan Sandsa0984362011-09-06 13:37:06 +00004060 if (!isa<AllocaInst>(Underlying))
Craig Topperf40110f2014-04-25 05:29:35 +00004061 return nullptr;
Duncan Sandsa0984362011-09-06 13:37:06 +00004062
Craig Topperf40110f2014-04-25 05:29:35 +00004063 IntrinsicInst *InitTrampoline = nullptr;
Chandler Carruthcdf47882014-03-09 03:16:01 +00004064 for (User *U : TrampMem->users()) {
4065 IntrinsicInst *II = dyn_cast<IntrinsicInst>(U);
Duncan Sandsa0984362011-09-06 13:37:06 +00004066 if (!II)
Craig Topperf40110f2014-04-25 05:29:35 +00004067 return nullptr;
Duncan Sandsa0984362011-09-06 13:37:06 +00004068 if (II->getIntrinsicID() == Intrinsic::init_trampoline) {
4069 if (InitTrampoline)
4070 // More than one init_trampoline writes to this value. Give up.
Craig Topperf40110f2014-04-25 05:29:35 +00004071 return nullptr;
Duncan Sandsa0984362011-09-06 13:37:06 +00004072 InitTrampoline = II;
4073 continue;
4074 }
4075 if (II->getIntrinsicID() == Intrinsic::adjust_trampoline)
4076 // Allow any number of calls to adjust.trampoline.
4077 continue;
Craig Topperf40110f2014-04-25 05:29:35 +00004078 return nullptr;
Duncan Sandsa0984362011-09-06 13:37:06 +00004079 }
4080
4081 // No call to init.trampoline found.
4082 if (!InitTrampoline)
Craig Topperf40110f2014-04-25 05:29:35 +00004083 return nullptr;
Duncan Sandsa0984362011-09-06 13:37:06 +00004084
4085 // Check that the alloca is being used in the expected way.
4086 if (InitTrampoline->getOperand(0) != TrampMem)
Craig Topperf40110f2014-04-25 05:29:35 +00004087 return nullptr;
Duncan Sandsa0984362011-09-06 13:37:06 +00004088
4089 return InitTrampoline;
4090}
4091
Sanjay Patel6038d3e2016-01-29 23:27:03 +00004092static IntrinsicInst *findInitTrampolineFromBB(IntrinsicInst *AdjustTramp,
Duncan Sandsa0984362011-09-06 13:37:06 +00004093 Value *TrampMem) {
4094 // Visit all the previous instructions in the basic block, and try to find a
4095 // init.trampoline which has a direct path to the adjust.trampoline.
Duncan P. N. Exon Smith9f8aaf22015-10-13 16:59:33 +00004096 for (BasicBlock::iterator I = AdjustTramp->getIterator(),
4097 E = AdjustTramp->getParent()->begin();
4098 I != E;) {
4099 Instruction *Inst = &*--I;
Duncan Sandsa0984362011-09-06 13:37:06 +00004100 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I))
4101 if (II->getIntrinsicID() == Intrinsic::init_trampoline &&
4102 II->getOperand(0) == TrampMem)
4103 return II;
4104 if (Inst->mayWriteToMemory())
Craig Topperf40110f2014-04-25 05:29:35 +00004105 return nullptr;
Duncan Sandsa0984362011-09-06 13:37:06 +00004106 }
Craig Topperf40110f2014-04-25 05:29:35 +00004107 return nullptr;
Duncan Sandsa0984362011-09-06 13:37:06 +00004108}
4109
4110// Given a call to llvm.adjust.trampoline, find and return the corresponding
4111// call to llvm.init.trampoline if the call to the trampoline can be optimized
4112// to a direct call to a function. Otherwise return NULL.
Sanjay Patel6038d3e2016-01-29 23:27:03 +00004113static IntrinsicInst *findInitTrampoline(Value *Callee) {
Duncan Sandsa0984362011-09-06 13:37:06 +00004114 Callee = Callee->stripPointerCasts();
4115 IntrinsicInst *AdjustTramp = dyn_cast<IntrinsicInst>(Callee);
4116 if (!AdjustTramp ||
4117 AdjustTramp->getIntrinsicID() != Intrinsic::adjust_trampoline)
Craig Topperf40110f2014-04-25 05:29:35 +00004118 return nullptr;
Duncan Sandsa0984362011-09-06 13:37:06 +00004119
4120 Value *TrampMem = AdjustTramp->getOperand(0);
4121
Sanjay Patel6038d3e2016-01-29 23:27:03 +00004122 if (IntrinsicInst *IT = findInitTrampolineFromAlloca(TrampMem))
Duncan Sandsa0984362011-09-06 13:37:06 +00004123 return IT;
Sanjay Patel6038d3e2016-01-29 23:27:03 +00004124 if (IntrinsicInst *IT = findInitTrampolineFromBB(AdjustTramp, TrampMem))
Duncan Sandsa0984362011-09-06 13:37:06 +00004125 return IT;
Craig Topperf40110f2014-04-25 05:29:35 +00004126 return nullptr;
Duncan Sandsa0984362011-09-06 13:37:06 +00004127}
4128
Sanjay Patelcd4377c2016-01-20 22:24:38 +00004129/// Improvements for call and invoke instructions.
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004130Instruction *InstCombiner::visitCallSite(CallSite CS) {
Justin Bogner99798402016-08-05 01:06:44 +00004131 if (isAllocLikeFn(CS.getInstruction(), &TLI))
Nuno Lopes95cc4f32012-07-09 18:38:20 +00004132 return visitAllocSite(*CS.getInstruction());
Nuno Lopesdc6085e2012-06-21 21:25:05 +00004133
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004134 bool Changed = false;
4135
Philip Reamesc25df112015-06-16 20:24:25 +00004136 // Mark any parameters that are known to be non-null with the nonnull
4137 // attribute. This is helpful for inlining calls to functions with null
4138 // checks on their arguments.
Reid Kleckner5fbdd172017-05-31 19:23:09 +00004139 SmallVector<unsigned, 4> ArgNos;
Philip Reamesc25df112015-06-16 20:24:25 +00004140 unsigned ArgNo = 0;
Akira Hatanaka237916b2015-12-02 06:58:49 +00004141
Philip Reamesc25df112015-06-16 20:24:25 +00004142 for (Value *V : CS.args()) {
Sanjay Patelf9f5d3c2016-01-29 23:14:58 +00004143 if (V->getType()->isPointerTy() &&
Reid Klecknerfb502d22017-04-14 20:19:02 +00004144 !CS.paramHasAttr(ArgNo, Attribute::NonNull) &&
Nuno Lopes404f1062017-09-09 18:23:11 +00004145 isKnownNonZero(V, DL, 0, &AC, CS.getInstruction(), &DT))
Reid Kleckner5fbdd172017-05-31 19:23:09 +00004146 ArgNos.push_back(ArgNo);
Philip Reamesc25df112015-06-16 20:24:25 +00004147 ArgNo++;
4148 }
Akira Hatanaka237916b2015-12-02 06:58:49 +00004149
Philip Reamesc25df112015-06-16 20:24:25 +00004150 assert(ArgNo == CS.arg_size() && "sanity check");
4151
Reid Kleckner5fbdd172017-05-31 19:23:09 +00004152 if (!ArgNos.empty()) {
Reid Klecknerb5180542017-03-21 16:57:19 +00004153 AttributeList AS = CS.getAttributes();
Akira Hatanaka237916b2015-12-02 06:58:49 +00004154 LLVMContext &Ctx = CS.getInstruction()->getContext();
Reid Kleckner5fbdd172017-05-31 19:23:09 +00004155 AS = AS.addParamAttribute(Ctx, ArgNos,
4156 Attribute::get(Ctx, Attribute::NonNull));
Akira Hatanaka237916b2015-12-02 06:58:49 +00004157 CS.setAttributes(AS);
4158 Changed = true;
4159 }
4160
Chris Lattner73989652010-12-20 08:25:06 +00004161 // If the callee is a pointer to a function, attempt to move any casts to the
4162 // arguments of the call/invoke.
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004163 Value *Callee = CS.getCalledValue();
Chris Lattner73989652010-12-20 08:25:06 +00004164 if (!isa<Function>(Callee) && transformConstExprCastCall(CS))
Craig Topperf40110f2014-04-25 05:29:35 +00004165 return nullptr;
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004166
Justin Lebar9d943972016-03-14 20:18:54 +00004167 if (Function *CalleeF = dyn_cast<Function>(Callee)) {
4168 // Remove the convergent attr on calls when the callee is not convergent.
Matt Arsenault802ebcb2016-06-20 19:04:44 +00004169 if (CS.isConvergent() && !CalleeF->isConvergent() &&
4170 !CalleeF->isIntrinsic()) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00004171 LLVM_DEBUG(dbgs() << "Removing convergent attr from instr "
4172 << CS.getInstruction() << "\n");
Justin Lebar9d943972016-03-14 20:18:54 +00004173 CS.setNotConvergent();
4174 return CS.getInstruction();
4175 }
4176
Chris Lattner846a52e2010-02-01 18:11:34 +00004177 // If the call and callee calling conventions don't match, this call must
4178 // be unreachable, as the call is undefined.
4179 if (CalleeF->getCallingConv() != CS.getCallingConv() &&
4180 // Only do this for calls to a function with a body. A prototype may
4181 // not actually end up matching the implementation's calling conv for a
4182 // variety of reasons (e.g. it may be written in assembly).
4183 !CalleeF->isDeclaration()) {
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004184 Instruction *OldCall = CS.getInstruction();
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004185 new StoreInst(ConstantInt::getTrue(Callee->getContext()),
Jim Grosbach7815f562012-02-03 00:07:04 +00004186 UndefValue::get(Type::getInt1PtrTy(Callee->getContext())),
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004187 OldCall);
Chad Rosiere28ae302012-12-13 00:18:46 +00004188 // If OldCall does not return void then replaceAllUsesWith undef.
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004189 // This allows ValueHandlers and custom metadata to adjust itself.
4190 if (!OldCall->getType()->isVoidTy())
Sanjay Patel4b198802016-02-01 22:23:39 +00004191 replaceInstUsesWith(*OldCall, UndefValue::get(OldCall->getType()));
Chris Lattner2cecedf2010-02-01 18:04:58 +00004192 if (isa<CallInst>(OldCall))
Sanjay Patel4b198802016-02-01 22:23:39 +00004193 return eraseInstFromFunction(*OldCall);
Jim Grosbach7815f562012-02-03 00:07:04 +00004194
Chris Lattner2cecedf2010-02-01 18:04:58 +00004195 // We cannot remove an invoke, because it would change the CFG, just
4196 // change the callee to a null pointer.
Gabor Greiffebf6ab2010-03-20 21:00:25 +00004197 cast<InvokeInst>(OldCall)->setCalledFunction(
Chris Lattner2cecedf2010-02-01 18:04:58 +00004198 Constant::getNullValue(CalleeF->getType()));
Craig Topperf40110f2014-04-25 05:29:35 +00004199 return nullptr;
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004200 }
Justin Lebar9d943972016-03-14 20:18:54 +00004201 }
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004202
Manoj Gupta77eeac32018-07-09 22:27:23 +00004203 if ((isa<ConstantPointerNull>(Callee) &&
4204 !NullPointerIsDefined(CS.getInstruction()->getFunction())) ||
4205 isa<UndefValue>(Callee)) {
Gabor Greif589a0b92010-06-24 12:58:35 +00004206 // If CS does not return void then replaceAllUsesWith undef.
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004207 // This allows ValueHandlers and custom metadata to adjust itself.
4208 if (!CS.getInstruction()->getType()->isVoidTy())
Sanjay Patel4b198802016-02-01 22:23:39 +00004209 replaceInstUsesWith(*CS.getInstruction(),
Eli Friedmanb9ed18f2011-05-18 00:32:01 +00004210 UndefValue::get(CS.getInstruction()->getType()));
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004211
Nuno Lopes771e7bd2012-06-21 23:52:14 +00004212 if (isa<InvokeInst>(CS.getInstruction())) {
4213 // Can't remove an invoke because we cannot change the CFG.
Craig Topperf40110f2014-04-25 05:29:35 +00004214 return nullptr;
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004215 }
Nuno Lopes771e7bd2012-06-21 23:52:14 +00004216
4217 // This instruction is not reachable, just remove it. We insert a store to
4218 // undef so that we know that this code is not reachable, despite the fact
4219 // that we can't modify the CFG here.
4220 new StoreInst(ConstantInt::getTrue(Callee->getContext()),
4221 UndefValue::get(Type::getInt1PtrTy(Callee->getContext())),
4222 CS.getInstruction());
4223
Sanjay Patel4b198802016-02-01 22:23:39 +00004224 return eraseInstFromFunction(*CS.getInstruction());
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004225 }
4226
Sanjay Patel6038d3e2016-01-29 23:27:03 +00004227 if (IntrinsicInst *II = findInitTrampoline(Callee))
Duncan Sandsa0984362011-09-06 13:37:06 +00004228 return transformCallThroughTrampoline(CS, II);
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004229
Chris Lattner229907c2011-07-18 04:54:35 +00004230 PointerType *PTy = cast<PointerType>(Callee->getType());
4231 FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004232 if (FTy->isVarArg()) {
Eli Friedman7534b4682011-11-29 01:18:23 +00004233 int ix = FTy->getNumParams();
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004234 // See if we can optimize any arguments passed through the varargs area of
4235 // the call.
Matt Arsenault5d2e85f2013-06-28 00:25:40 +00004236 for (CallSite::arg_iterator I = CS.arg_begin() + FTy->getNumParams(),
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004237 E = CS.arg_end(); I != E; ++I, ++ix) {
4238 CastInst *CI = dyn_cast<CastInst>(*I);
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004239 if (CI && isSafeToEliminateVarargsCast(CS, DL, CI, ix)) {
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004240 *I = CI->getOperand(0);
4241 Changed = true;
4242 }
4243 }
4244 }
4245
4246 if (isa<InlineAsm>(Callee) && !CS.doesNotThrow()) {
4247 // Inline asm calls cannot throw - mark them 'nounwind'.
4248 CS.setDoesNotThrow();
4249 Changed = true;
4250 }
4251
Micah Villmowcdfe20b2012-10-08 16:38:25 +00004252 // Try to optimize the call if possible, we require DataLayout for most of
Eric Christophera7fb58f2010-03-06 10:50:38 +00004253 // this. None of these calls are seen as possibly dead so go ahead and
4254 // delete the instruction now.
4255 if (CallInst *CI = dyn_cast<CallInst>(CS.getInstruction())) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004256 Instruction *I = tryOptimizeCall(CI);
Eric Christopher1810d772010-03-06 10:59:25 +00004257 // If we changed something return the result, etc. Otherwise let
4258 // the fallthrough check.
Sanjay Patel4b198802016-02-01 22:23:39 +00004259 if (I) return eraseInstFromFunction(*I);
Eric Christophera7fb58f2010-03-06 10:50:38 +00004260 }
4261
Craig Topperf40110f2014-04-25 05:29:35 +00004262 return Changed ? CS.getInstruction() : nullptr;
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004263}
4264
Sanjay Patelcd4377c2016-01-20 22:24:38 +00004265/// If the callee is a constexpr cast of a function, attempt to move the cast to
4266/// the arguments of the call/invoke.
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004267bool InstCombiner::transformConstExprCastCall(CallSite CS) {
Sanjay Patele3c335c2016-08-11 15:21:21 +00004268 auto *Callee = dyn_cast<Function>(CS.getCalledValue()->stripPointerCasts());
Craig Topperf40110f2014-04-25 05:29:35 +00004269 if (!Callee)
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004270 return false;
Sanjay Patel38ae83d2016-08-11 15:23:56 +00004271
Reid Kleckner298ffc62018-04-02 22:49:44 +00004272 // If this is a call to a thunk function, don't remove the cast. Thunks are
4273 // used to transparently forward all incoming parameters and outgoing return
4274 // values, so it's important to leave the cast in place.
David Majnemer4c0a6e92015-01-21 22:32:04 +00004275 if (Callee->hasFnAttribute("thunk"))
4276 return false;
Sanjay Patel38ae83d2016-08-11 15:23:56 +00004277
Reid Kleckner298ffc62018-04-02 22:49:44 +00004278 // If this is a musttail call, the callee's prototype must match the caller's
4279 // prototype with the exception of pointee types. The code below doesn't
4280 // implement that, so we can't do this transform.
4281 // TODO: Do the transform if it only requires adding pointer casts.
4282 if (CS.isMustTailCall())
4283 return false;
4284
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004285 Instruction *Caller = CS.getInstruction();
Reid Klecknerb5180542017-03-21 16:57:19 +00004286 const AttributeList &CallerPAL = CS.getAttributes();
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004287
4288 // Okay, this is a cast from a function to a different type. Unless doing so
4289 // would cause a type conversion of one of our arguments, change this call to
4290 // be a direct call with arguments casted to the appropriate types.
Chris Lattner229907c2011-07-18 04:54:35 +00004291 FunctionType *FT = Callee->getFunctionType();
4292 Type *OldRetTy = Caller->getType();
4293 Type *NewRetTy = FT->getReturnType();
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004294
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004295 // Check to see if we are changing the return type...
4296 if (OldRetTy != NewRetTy) {
Nick Lewyckya6a17d72014-01-18 22:47:12 +00004297
4298 if (NewRetTy->isStructTy())
4299 return false; // TODO: Handle multiple return values.
4300
David Majnemer9b6b8222015-01-06 08:41:31 +00004301 if (!CastInst::isBitOrNoopPointerCastable(NewRetTy, OldRetTy, DL)) {
Matt Arsenaulte6952f22013-09-17 21:10:14 +00004302 if (Callee->isDeclaration())
4303 return false; // Cannot transform this return value.
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004304
Matt Arsenaulte6952f22013-09-17 21:10:14 +00004305 if (!Caller->use_empty() &&
4306 // void -> non-void is handled specially
4307 !NewRetTy->isVoidTy())
Frederic Rissc1892e22014-10-23 04:08:42 +00004308 return false; // Cannot transform this return value.
Matt Arsenaulte6952f22013-09-17 21:10:14 +00004309 }
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004310
4311 if (!CallerPAL.isEmpty() && !Caller->use_empty()) {
Reid Klecknerb5180542017-03-21 16:57:19 +00004312 AttrBuilder RAttrs(CallerPAL, AttributeList::ReturnIndex);
Pete Cooper2777d8872015-05-06 23:19:56 +00004313 if (RAttrs.overlaps(AttributeFuncs::typeIncompatible(NewRetTy)))
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004314 return false; // Attribute not compatible with transformed value.
4315 }
4316
4317 // If the callsite is an invoke instruction, and the return value is used by
4318 // a PHI node in a successor, we cannot change the return type of the call
4319 // because there is no place to put the cast instruction (without breaking
4320 // the critical edge). Bail out in this case.
4321 if (!Caller->use_empty())
4322 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller))
Chandler Carruthcdf47882014-03-09 03:16:01 +00004323 for (User *U : II->users())
4324 if (PHINode *PN = dyn_cast<PHINode>(U))
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004325 if (PN->getParent() == II->getNormalDest() ||
4326 PN->getParent() == II->getUnwindDest())
4327 return false;
4328 }
4329
Matt Arsenault5d2e85f2013-06-28 00:25:40 +00004330 unsigned NumActualArgs = CS.arg_size();
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004331 unsigned NumCommonArgs = std::min(FT->getNumParams(), NumActualArgs);
4332
David Majnemer9b6b8222015-01-06 08:41:31 +00004333 // Prevent us turning:
4334 // declare void @takes_i32_inalloca(i32* inalloca)
4335 // call void bitcast (void (i32*)* @takes_i32_inalloca to void (i32)*)(i32 0)
4336 //
4337 // into:
4338 // call void @takes_i32_inalloca(i32* null)
David Majnemerd61a6fd2015-03-11 18:03:05 +00004339 //
4340 // Similarly, avoid folding away bitcasts of byval calls.
4341 if (Callee->getAttributes().hasAttrSomewhere(Attribute::InAlloca) ||
4342 Callee->getAttributes().hasAttrSomewhere(Attribute::ByVal))
David Majnemer9b6b8222015-01-06 08:41:31 +00004343 return false;
4344
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004345 CallSite::arg_iterator AI = CS.arg_begin();
4346 for (unsigned i = 0, e = NumCommonArgs; i != e; ++i, ++AI) {
Chris Lattner229907c2011-07-18 04:54:35 +00004347 Type *ParamTy = FT->getParamType(i);
4348 Type *ActTy = (*AI)->getType();
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004349
David Majnemer9b6b8222015-01-06 08:41:31 +00004350 if (!CastInst::isBitOrNoopPointerCastable(ActTy, ParamTy, DL))
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004351 return false; // Cannot transform this parameter value.
4352
Reid Klecknerf021fab2017-04-13 23:12:13 +00004353 if (AttrBuilder(CallerPAL.getParamAttributes(i))
4354 .overlaps(AttributeFuncs::typeIncompatible(ParamTy)))
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004355 return false; // Attribute not compatible with transformed value.
Jim Grosbach7815f562012-02-03 00:07:04 +00004356
Reid Kleckner26af2ca2014-01-28 02:38:36 +00004357 if (CS.isInAllocaArgument(i))
4358 return false; // Cannot transform to and from inalloca.
4359
Chris Lattner27ca8eb2010-12-20 08:36:38 +00004360 // If the parameter is passed as a byval argument, then we have to have a
4361 // sized type and the sized type has to have the same size as the old type.
Reid Klecknerf021fab2017-04-13 23:12:13 +00004362 if (ParamTy != ActTy && CallerPAL.hasParamAttribute(i, Attribute::ByVal)) {
Chris Lattner229907c2011-07-18 04:54:35 +00004363 PointerType *ParamPTy = dyn_cast<PointerType>(ParamTy);
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004364 if (!ParamPTy || !ParamPTy->getElementType()->isSized())
Chris Lattner27ca8eb2010-12-20 08:36:38 +00004365 return false;
Jim Grosbach7815f562012-02-03 00:07:04 +00004366
Matt Arsenaultfa252722013-09-27 22:18:51 +00004367 Type *CurElTy = ActTy->getPointerElementType();
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004368 if (DL.getTypeAllocSize(CurElTy) !=
4369 DL.getTypeAllocSize(ParamPTy->getElementType()))
Chris Lattner27ca8eb2010-12-20 08:36:38 +00004370 return false;
4371 }
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004372 }
4373
Chris Lattneradf38b32011-02-24 05:10:56 +00004374 if (Callee->isDeclaration()) {
4375 // Do not delete arguments unless we have a function body.
4376 if (FT->getNumParams() < NumActualArgs && !FT->isVarArg())
4377 return false;
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004378
Chris Lattneradf38b32011-02-24 05:10:56 +00004379 // If the callee is just a declaration, don't change the varargsness of the
4380 // call. We don't want to introduce a varargs call where one doesn't
4381 // already exist.
Chris Lattner229907c2011-07-18 04:54:35 +00004382 PointerType *APTy = cast<PointerType>(CS.getCalledValue()->getType());
Chris Lattneradf38b32011-02-24 05:10:56 +00004383 if (FT->isVarArg()!=cast<FunctionType>(APTy->getElementType())->isVarArg())
4384 return false;
Jim Grosbache84ae7b2012-02-03 00:00:55 +00004385
4386 // If both the callee and the cast type are varargs, we still have to make
4387 // sure the number of fixed parameters are the same or we have the same
4388 // ABI issues as if we introduce a varargs call.
Jim Grosbach1df8cdc2012-02-03 00:26:07 +00004389 if (FT->isVarArg() &&
4390 cast<FunctionType>(APTy->getElementType())->isVarArg() &&
4391 FT->getNumParams() !=
Jim Grosbache84ae7b2012-02-03 00:00:55 +00004392 cast<FunctionType>(APTy->getElementType())->getNumParams())
4393 return false;
Chris Lattneradf38b32011-02-24 05:10:56 +00004394 }
Jim Grosbach7815f562012-02-03 00:07:04 +00004395
Jim Grosbach0ab54182012-02-03 00:00:50 +00004396 if (FT->getNumParams() < NumActualArgs && FT->isVarArg() &&
Reid Kleckneraa0cec72017-04-19 23:17:47 +00004397 !CallerPAL.isEmpty()) {
Jim Grosbach0ab54182012-02-03 00:00:50 +00004398 // In this case we have more arguments than the new function type, but we
4399 // won't be dropping them. Check that these extra arguments have attributes
4400 // that are compatible with being a vararg call argument.
Reid Kleckneraa0cec72017-04-19 23:17:47 +00004401 unsigned SRetIdx;
4402 if (CallerPAL.hasAttrSomewhere(Attribute::StructRet, &SRetIdx) &&
4403 SRetIdx > FT->getNumParams())
4404 return false;
4405 }
Jim Grosbach7815f562012-02-03 00:07:04 +00004406
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004407 // Okay, we decided that this is a safe thing to do: go ahead and start
Chris Lattneradf38b32011-02-24 05:10:56 +00004408 // inserting cast instructions as necessary.
Reid Klecknerc3fae792017-04-13 18:11:03 +00004409 SmallVector<Value *, 8> Args;
4410 SmallVector<AttributeSet, 8> ArgAttrs;
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004411 Args.reserve(NumActualArgs);
Reid Klecknerc3fae792017-04-13 18:11:03 +00004412 ArgAttrs.reserve(NumActualArgs);
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004413
4414 // Get any return attributes.
Reid Klecknerb5180542017-03-21 16:57:19 +00004415 AttrBuilder RAttrs(CallerPAL, AttributeList::ReturnIndex);
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004416
4417 // If the return value is not being used, the type may not be compatible
4418 // with the existing attributes. Wipe out any problematic attributes.
Pete Cooper2777d8872015-05-06 23:19:56 +00004419 RAttrs.remove(AttributeFuncs::typeIncompatible(NewRetTy));
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004420
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004421 AI = CS.arg_begin();
4422 for (unsigned i = 0; i != NumCommonArgs; ++i, ++AI) {
Chris Lattner229907c2011-07-18 04:54:35 +00004423 Type *ParamTy = FT->getParamType(i);
Matt Arsenaultcacbb232013-07-30 20:45:05 +00004424
Reid Klecknerc3fae792017-04-13 18:11:03 +00004425 Value *NewArg = *AI;
4426 if ((*AI)->getType() != ParamTy)
Craig Topperbb4069e2017-07-07 23:16:26 +00004427 NewArg = Builder.CreateBitOrPointerCast(*AI, ParamTy);
Reid Klecknerc3fae792017-04-13 18:11:03 +00004428 Args.push_back(NewArg);
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004429
4430 // Add any parameter attributes.
Reid Klecknerf021fab2017-04-13 23:12:13 +00004431 ArgAttrs.push_back(CallerPAL.getParamAttributes(i));
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004432 }
4433
4434 // If the function takes more arguments than the call was taking, add them
4435 // now.
Reid Klecknerc3fae792017-04-13 18:11:03 +00004436 for (unsigned i = NumCommonArgs; i != FT->getNumParams(); ++i) {
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004437 Args.push_back(Constant::getNullValue(FT->getParamType(i)));
Reid Klecknerc3fae792017-04-13 18:11:03 +00004438 ArgAttrs.push_back(AttributeSet());
4439 }
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004440
4441 // If we are removing arguments to the function, emit an obnoxious warning.
4442 if (FT->getNumParams() < NumActualArgs) {
Nick Lewycky90053a12012-12-26 22:00:35 +00004443 // TODO: if (!FT->isVarArg()) this call may be unreachable. PR14722
4444 if (FT->isVarArg()) {
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004445 // Add all of the arguments in their promoted form to the arg list.
4446 for (unsigned i = FT->getNumParams(); i != NumActualArgs; ++i, ++AI) {
Chris Lattner229907c2011-07-18 04:54:35 +00004447 Type *PTy = getPromotedType((*AI)->getType());
Reid Klecknerc3fae792017-04-13 18:11:03 +00004448 Value *NewArg = *AI;
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004449 if (PTy != (*AI)->getType()) {
4450 // Must promote to pass through va_arg area!
4451 Instruction::CastOps opcode =
4452 CastInst::getCastOpcode(*AI, false, PTy, false);
Craig Topperbb4069e2017-07-07 23:16:26 +00004453 NewArg = Builder.CreateCast(opcode, *AI, PTy);
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004454 }
Reid Klecknerc3fae792017-04-13 18:11:03 +00004455 Args.push_back(NewArg);
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004456
4457 // Add any parameter attributes.
Reid Klecknerf021fab2017-04-13 23:12:13 +00004458 ArgAttrs.push_back(CallerPAL.getParamAttributes(i));
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004459 }
4460 }
4461 }
4462
Reid Klecknerc2cb5602017-04-12 00:38:00 +00004463 AttributeSet FnAttrs = CallerPAL.getFnAttributes();
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004464
4465 if (NewRetTy->isVoidTy())
4466 Caller->setName(""); // Void type should not have a name.
4467
Reid Klecknerc3fae792017-04-13 18:11:03 +00004468 assert((ArgAttrs.size() == FT->getNumParams() || FT->isVarArg()) &&
4469 "missing argument attributes");
4470 LLVMContext &Ctx = Callee->getContext();
4471 AttributeList NewCallerPAL = AttributeList::get(
4472 Ctx, FnAttrs, AttributeSet::get(Ctx, RAttrs), ArgAttrs);
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004473
Sanjoy Das76293462015-11-25 00:42:19 +00004474 SmallVector<OperandBundleDef, 1> OpBundles;
Sanjoy Dasc521c7b2015-11-25 00:42:24 +00004475 CS.getOperandBundlesAsDefs(OpBundles);
Sanjoy Das76293462015-11-25 00:42:19 +00004476
Reid Kleckner257cb4e2017-04-13 20:26:38 +00004477 CallSite NewCS;
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004478 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Craig Topperbb4069e2017-07-07 23:16:26 +00004479 NewCS = Builder.CreateInvoke(Callee, II->getNormalDest(),
4480 II->getUnwindDest(), Args, OpBundles);
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004481 } else {
Craig Topperbb4069e2017-07-07 23:16:26 +00004482 NewCS = Builder.CreateCall(Callee, Args, OpBundles);
Reid Kleckner257cb4e2017-04-13 20:26:38 +00004483 cast<CallInst>(NewCS.getInstruction())
4484 ->setTailCallKind(cast<CallInst>(Caller)->getTailCallKind());
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004485 }
Reid Kleckner257cb4e2017-04-13 20:26:38 +00004486 NewCS->takeName(Caller);
4487 NewCS.setCallingConv(CS.getCallingConv());
4488 NewCS.setAttributes(NewCallerPAL);
4489
4490 // Preserve the weight metadata for the new call instruction. The metadata
4491 // is used by SamplePGO to check callsite's hotness.
4492 uint64_t W;
4493 if (Caller->extractProfTotalWeight(W))
4494 NewCS->setProfWeight(W);
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004495
4496 // Insert a cast of the return type as necessary.
Reid Kleckner257cb4e2017-04-13 20:26:38 +00004497 Instruction *NC = NewCS.getInstruction();
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004498 Value *NV = NC;
4499 if (OldRetTy != NV->getType() && !Caller->use_empty()) {
4500 if (!NV->getType()->isVoidTy()) {
David Majnemer9b6b8222015-01-06 08:41:31 +00004501 NV = NC = CastInst::CreateBitOrPointerCast(NC, OldRetTy);
Eli Friedman35211c62011-05-27 00:19:40 +00004502 NC->setDebugLoc(Caller->getDebugLoc());
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004503
4504 // If this is an invoke instruction, we should insert it after the first
4505 // non-phi, instruction in the normal successor block.
4506 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Bill Wendling07efd6f2011-08-25 01:08:34 +00004507 BasicBlock::iterator I = II->getNormalDest()->getFirstInsertionPt();
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004508 InsertNewInstBefore(NC, *I);
4509 } else {
Chris Lattner73989652010-12-20 08:25:06 +00004510 // Otherwise, it's a call, just insert cast right after the call.
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004511 InsertNewInstBefore(NC, *Caller);
4512 }
4513 Worklist.AddUsersToWorkList(*Caller);
4514 } else {
4515 NV = UndefValue::get(Caller->getType());
4516 }
4517 }
4518
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004519 if (!Caller->use_empty())
Sanjay Patel4b198802016-02-01 22:23:39 +00004520 replaceInstUsesWith(*Caller, NV);
Frederic Rissc1892e22014-10-23 04:08:42 +00004521 else if (Caller->hasValueHandle()) {
4522 if (OldRetTy == NV->getType())
4523 ValueHandleBase::ValueIsRAUWd(Caller, NV);
4524 else
4525 // We cannot call ValueIsRAUWd with a different type, and the
4526 // actual tracked value will disappear.
4527 ValueHandleBase::ValueIsDeleted(Caller);
4528 }
Eli Friedmanb9ed18f2011-05-18 00:32:01 +00004529
Sanjay Patel4b198802016-02-01 22:23:39 +00004530 eraseInstFromFunction(*Caller);
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004531 return true;
4532}
4533
Sanjay Patelcd4377c2016-01-20 22:24:38 +00004534/// Turn a call to a function created by init_trampoline / adjust_trampoline
4535/// intrinsic pair into a direct call to the underlying function.
Duncan Sandsa0984362011-09-06 13:37:06 +00004536Instruction *
4537InstCombiner::transformCallThroughTrampoline(CallSite CS,
4538 IntrinsicInst *Tramp) {
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004539 Value *Callee = CS.getCalledValue();
Chris Lattner229907c2011-07-18 04:54:35 +00004540 PointerType *PTy = cast<PointerType>(Callee->getType());
4541 FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
Reid Klecknereb9dd5b2017-04-10 23:31:05 +00004542 AttributeList Attrs = CS.getAttributes();
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004543
4544 // If the call already has the 'nest' attribute somewhere then give up -
4545 // otherwise 'nest' would occur twice after splicing in the chain.
Bill Wendling6e95ae82012-12-31 00:49:59 +00004546 if (Attrs.hasAttrSomewhere(Attribute::Nest))
Craig Topperf40110f2014-04-25 05:29:35 +00004547 return nullptr;
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004548
Duncan Sandsa0984362011-09-06 13:37:06 +00004549 assert(Tramp &&
4550 "transformCallThroughTrampoline called with incorrect CallSite.");
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004551
Gabor Greif3e44ea12010-07-22 10:37:47 +00004552 Function *NestF =cast<Function>(Tramp->getArgOperand(1)->stripPointerCasts());
Manuel Jacob5f6eaac2016-01-16 20:30:46 +00004553 FunctionType *NestFTy = cast<FunctionType>(NestF->getValueType());
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004554
Reid Klecknereb9dd5b2017-04-10 23:31:05 +00004555 AttributeList NestAttrs = NestF->getAttributes();
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004556 if (!NestAttrs.isEmpty()) {
Reid Klecknerf021fab2017-04-13 23:12:13 +00004557 unsigned NestArgNo = 0;
Craig Topperf40110f2014-04-25 05:29:35 +00004558 Type *NestTy = nullptr;
Reid Klecknerc2cb5602017-04-12 00:38:00 +00004559 AttributeSet NestAttr;
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004560
4561 // Look for a parameter marked with the 'nest' attribute.
4562 for (FunctionType::param_iterator I = NestFTy->param_begin(),
Reid Klecknerf021fab2017-04-13 23:12:13 +00004563 E = NestFTy->param_end();
4564 I != E; ++NestArgNo, ++I) {
4565 AttributeSet AS = NestAttrs.getParamAttributes(NestArgNo);
4566 if (AS.hasAttribute(Attribute::Nest)) {
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004567 // Record the parameter type and any other attributes.
4568 NestTy = *I;
Reid Klecknerf021fab2017-04-13 23:12:13 +00004569 NestAttr = AS;
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004570 break;
4571 }
Reid Klecknerf021fab2017-04-13 23:12:13 +00004572 }
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004573
4574 if (NestTy) {
4575 Instruction *Caller = CS.getInstruction();
4576 std::vector<Value*> NewArgs;
Reid Kleckner7f720332017-04-13 00:58:09 +00004577 std::vector<AttributeSet> NewArgAttrs;
Matt Arsenault5d2e85f2013-06-28 00:25:40 +00004578 NewArgs.reserve(CS.arg_size() + 1);
Reid Kleckner7f720332017-04-13 00:58:09 +00004579 NewArgAttrs.reserve(CS.arg_size());
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004580
4581 // Insert the nest argument into the call argument list, which may
4582 // mean appending it. Likewise for attributes.
4583
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004584 {
Reid Klecknerf021fab2017-04-13 23:12:13 +00004585 unsigned ArgNo = 0;
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004586 CallSite::arg_iterator I = CS.arg_begin(), E = CS.arg_end();
4587 do {
Reid Klecknerf021fab2017-04-13 23:12:13 +00004588 if (ArgNo == NestArgNo) {
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004589 // Add the chain argument and attributes.
Gabor Greif589a0b92010-06-24 12:58:35 +00004590 Value *NestVal = Tramp->getArgOperand(2);
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004591 if (NestVal->getType() != NestTy)
Craig Topperbb4069e2017-07-07 23:16:26 +00004592 NestVal = Builder.CreateBitCast(NestVal, NestTy, "nest");
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004593 NewArgs.push_back(NestVal);
Reid Kleckner7f720332017-04-13 00:58:09 +00004594 NewArgAttrs.push_back(NestAttr);
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004595 }
4596
4597 if (I == E)
4598 break;
4599
4600 // Add the original argument and attributes.
4601 NewArgs.push_back(*I);
Reid Klecknerf021fab2017-04-13 23:12:13 +00004602 NewArgAttrs.push_back(Attrs.getParamAttributes(ArgNo));
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004603
Reid Klecknerf021fab2017-04-13 23:12:13 +00004604 ++ArgNo;
Richard Trieu7a083812016-02-18 22:09:30 +00004605 ++I;
Eugene Zelenkocdc71612016-08-11 17:20:18 +00004606 } while (true);
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004607 }
4608
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004609 // The trampoline may have been bitcast to a bogus type (FTy).
4610 // Handle this by synthesizing a new function type, equal to FTy
4611 // with the chain parameter inserted.
4612
Jay Foadb804a2b2011-07-12 14:06:48 +00004613 std::vector<Type*> NewTypes;
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004614 NewTypes.reserve(FTy->getNumParams()+1);
4615
4616 // Insert the chain's type into the list of parameter types, which may
4617 // mean appending it.
4618 {
Reid Klecknerf021fab2017-04-13 23:12:13 +00004619 unsigned ArgNo = 0;
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004620 FunctionType::param_iterator I = FTy->param_begin(),
4621 E = FTy->param_end();
4622
4623 do {
Reid Klecknerf021fab2017-04-13 23:12:13 +00004624 if (ArgNo == NestArgNo)
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004625 // Add the chain's type.
4626 NewTypes.push_back(NestTy);
4627
4628 if (I == E)
4629 break;
4630
4631 // Add the original type.
4632 NewTypes.push_back(*I);
4633
Reid Klecknerf021fab2017-04-13 23:12:13 +00004634 ++ArgNo;
Richard Trieu7a083812016-02-18 22:09:30 +00004635 ++I;
Eugene Zelenkocdc71612016-08-11 17:20:18 +00004636 } while (true);
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004637 }
4638
4639 // Replace the trampoline call with a direct call. Let the generic
4640 // code sort out any function type mismatches.
Jim Grosbach7815f562012-02-03 00:07:04 +00004641 FunctionType *NewFTy = FunctionType::get(FTy->getReturnType(), NewTypes,
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004642 FTy->isVarArg());
4643 Constant *NewCallee =
4644 NestF->getType() == PointerType::getUnqual(NewFTy) ?
Jim Grosbach7815f562012-02-03 00:07:04 +00004645 NestF : ConstantExpr::getBitCast(NestF,
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004646 PointerType::getUnqual(NewFTy));
Reid Kleckner7f720332017-04-13 00:58:09 +00004647 AttributeList NewPAL =
4648 AttributeList::get(FTy->getContext(), Attrs.getFnAttributes(),
4649 Attrs.getRetAttributes(), NewArgAttrs);
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004650
David Majnemer231a68c2016-04-29 08:07:20 +00004651 SmallVector<OperandBundleDef, 1> OpBundles;
4652 CS.getOperandBundlesAsDefs(OpBundles);
4653
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004654 Instruction *NewCaller;
4655 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
4656 NewCaller = InvokeInst::Create(NewCallee,
4657 II->getNormalDest(), II->getUnwindDest(),
David Majnemer231a68c2016-04-29 08:07:20 +00004658 NewArgs, OpBundles);
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004659 cast<InvokeInst>(NewCaller)->setCallingConv(II->getCallingConv());
4660 cast<InvokeInst>(NewCaller)->setAttributes(NewPAL);
4661 } else {
David Majnemer231a68c2016-04-29 08:07:20 +00004662 NewCaller = CallInst::Create(NewCallee, NewArgs, OpBundles);
David Majnemerd5648c72016-11-25 22:35:09 +00004663 cast<CallInst>(NewCaller)->setTailCallKind(
4664 cast<CallInst>(Caller)->getTailCallKind());
4665 cast<CallInst>(NewCaller)->setCallingConv(
4666 cast<CallInst>(Caller)->getCallingConv());
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004667 cast<CallInst>(NewCaller)->setAttributes(NewPAL);
4668 }
Florian Hahn012c8f92017-12-20 17:16:59 +00004669 NewCaller->setDebugLoc(Caller->getDebugLoc());
Eli Friedman49346012011-05-18 19:57:14 +00004670
4671 return NewCaller;
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004672 }
4673 }
4674
4675 // Replace the trampoline call with a direct call. Since there is no 'nest'
4676 // parameter, there is no need to adjust the argument list. Let the generic
4677 // code sort out any function type mismatches.
4678 Constant *NewCallee =
Jim Grosbach7815f562012-02-03 00:07:04 +00004679 NestF->getType() == PTy ? NestF :
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004680 ConstantExpr::getBitCast(NestF, PTy);
4681 CS.setCalledFunction(NewCallee);
4682 return CS.getInstruction();
4683}