blob: c15fb27a4c7af06eda7453a0562de878e64be5bf [file] [log] [blame]
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001//===- InstCombineCalls.cpp -----------------------------------------------===//
2//
Chandler Carruth2946cd72019-01-19 08:50:56 +00003// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
Chris Lattner7a9e47a2010-01-05 07:32:13 +00006//
7//===----------------------------------------------------------------------===//
8//
Craig Topper784929d2019-02-08 20:48:56 +00009// This file implements the visitCall, visitInvoke, and visitCallBr functions.
Chris Lattner7a9e47a2010-01-05 07:32:13 +000010//
11//===----------------------------------------------------------------------===//
12
Chandler Carrutha9174582015-01-22 05:25:13 +000013#include "InstCombineInternal.h"
Eugene Zelenkocdc71612016-08-11 17:20:18 +000014#include "llvm/ADT/APFloat.h"
15#include "llvm/ADT/APInt.h"
Nikita Popov53828032019-05-29 18:37:13 +000016#include "llvm/ADT/APSInt.h"
Eugene Zelenkocdc71612016-08-11 17:20:18 +000017#include "llvm/ADT/ArrayRef.h"
18#include "llvm/ADT/None.h"
Eugene Zelenko7f0f9bc2017-10-24 21:24:53 +000019#include "llvm/ADT/Optional.h"
Eugene Zelenkocdc71612016-08-11 17:20:18 +000020#include "llvm/ADT/STLExtras.h"
21#include "llvm/ADT/SmallVector.h"
Chandler Carruth6bda14b2017-06-06 11:49:48 +000022#include "llvm/ADT/Statistic.h"
Eugene Zelenkocdc71612016-08-11 17:20:18 +000023#include "llvm/ADT/Twine.h"
Eugene Zelenko7f0f9bc2017-10-24 21:24:53 +000024#include "llvm/Analysis/AssumptionCache.h"
David Majnemer15032582015-05-22 03:56:46 +000025#include "llvm/Analysis/InstructionSimplify.h"
Simon Pilgrim4b7d3c42019-04-25 09:49:37 +000026#include "llvm/Analysis/Loads.h"
Chris Lattner7a9e47a2010-01-05 07:32:13 +000027#include "llvm/Analysis/MemoryBuiltins.h"
Eugene Zelenkocdc71612016-08-11 17:20:18 +000028#include "llvm/Analysis/ValueTracking.h"
Philip Reamese4588bb2019-03-20 18:44:58 +000029#include "llvm/Analysis/VectorUtils.h"
Eugene Zelenko7f0f9bc2017-10-24 21:24:53 +000030#include "llvm/IR/Attributes.h"
Eugene Zelenkocdc71612016-08-11 17:20:18 +000031#include "llvm/IR/BasicBlock.h"
Eugene Zelenkocdc71612016-08-11 17:20:18 +000032#include "llvm/IR/Constant.h"
Eugene Zelenko7f0f9bc2017-10-24 21:24:53 +000033#include "llvm/IR/Constants.h"
Eugene Zelenkocdc71612016-08-11 17:20:18 +000034#include "llvm/IR/DataLayout.h"
35#include "llvm/IR/DerivedTypes.h"
36#include "llvm/IR/Function.h"
37#include "llvm/IR/GlobalVariable.h"
38#include "llvm/IR/InstrTypes.h"
39#include "llvm/IR/Instruction.h"
40#include "llvm/IR/Instructions.h"
41#include "llvm/IR/IntrinsicInst.h"
42#include "llvm/IR/Intrinsics.h"
43#include "llvm/IR/LLVMContext.h"
44#include "llvm/IR/Metadata.h"
Chandler Carruth820a9082014-03-04 11:08:18 +000045#include "llvm/IR/PatternMatch.h"
Philip Reames1a1bdb22014-12-02 18:50:36 +000046#include "llvm/IR/Statepoint.h"
Eugene Zelenkocdc71612016-08-11 17:20:18 +000047#include "llvm/IR/Type.h"
Eugene Zelenko7f0f9bc2017-10-24 21:24:53 +000048#include "llvm/IR/User.h"
Eugene Zelenkocdc71612016-08-11 17:20:18 +000049#include "llvm/IR/Value.h"
50#include "llvm/IR/ValueHandle.h"
Eugene Zelenko7f0f9bc2017-10-24 21:24:53 +000051#include "llvm/Support/AtomicOrdering.h"
Eugene Zelenkocdc71612016-08-11 17:20:18 +000052#include "llvm/Support/Casting.h"
Eugene Zelenko7f0f9bc2017-10-24 21:24:53 +000053#include "llvm/Support/CommandLine.h"
54#include "llvm/Support/Compiler.h"
Eugene Zelenkocdc71612016-08-11 17:20:18 +000055#include "llvm/Support/Debug.h"
Eugene Zelenko7f0f9bc2017-10-24 21:24:53 +000056#include "llvm/Support/ErrorHandling.h"
Craig Topperb45eabc2017-04-26 16:39:58 +000057#include "llvm/Support/KnownBits.h"
Eugene Zelenkocdc71612016-08-11 17:20:18 +000058#include "llvm/Support/MathExtras.h"
Eugene Zelenko7f0f9bc2017-10-24 21:24:53 +000059#include "llvm/Support/raw_ostream.h"
60#include "llvm/Transforms/InstCombine/InstCombineWorklist.h"
Philip Reames88cd69b2019-04-25 02:30:17 +000061#include "llvm/Transforms/Utils/Local.h"
Chandler Carruthba4c5172015-01-21 11:23:40 +000062#include "llvm/Transforms/Utils/SimplifyLibCalls.h"
Eugene Zelenkocdc71612016-08-11 17:20:18 +000063#include <algorithm>
64#include <cassert>
65#include <cstdint>
66#include <cstring>
Eugene Zelenko7f0f9bc2017-10-24 21:24:53 +000067#include <utility>
Eugene Zelenkocdc71612016-08-11 17:20:18 +000068#include <vector>
69
Chris Lattner7a9e47a2010-01-05 07:32:13 +000070using namespace llvm;
Michael Ilseman536cc322012-12-13 03:13:36 +000071using namespace PatternMatch;
Chris Lattner7a9e47a2010-01-05 07:32:13 +000072
Chandler Carruth964daaa2014-04-22 02:55:47 +000073#define DEBUG_TYPE "instcombine"
74
Meador Ingee3f2b262012-11-30 04:05:06 +000075STATISTIC(NumSimplified, "Number of library calls simplified");
76
Philip Reames79e917d2018-05-09 22:56:32 +000077static cl::opt<unsigned> GuardWideningWindow(
78 "instcombine-guard-widening-window",
79 cl::init(3),
80 cl::desc("How wide an instruction window to bypass looking for "
81 "another guard"));
82
Sanjay Patelcd4377c2016-01-20 22:24:38 +000083/// Return the specified type promoted as it would be to pass though a va_arg
84/// area.
Chris Lattner229907c2011-07-18 04:54:35 +000085static Type *getPromotedType(Type *Ty) {
86 if (IntegerType* ITy = dyn_cast<IntegerType>(Ty)) {
Chris Lattner7a9e47a2010-01-05 07:32:13 +000087 if (ITy->getBitWidth() < 32)
88 return Type::getInt32Ty(Ty->getContext());
89 }
90 return Ty;
91}
92
Sanjay Patel368ac5d2016-02-21 17:29:33 +000093/// Return a constant boolean vector that has true elements in all positions
Sanjay Patel24401302016-02-21 17:33:31 +000094/// where the input constant data vector has an element with the sign bit set.
Sanjay Patel368ac5d2016-02-21 17:29:33 +000095static Constant *getNegativeIsTrueBoolVec(ConstantDataVector *V) {
96 SmallVector<Constant *, 32> BoolVec;
97 IntegerType *BoolTy = Type::getInt1Ty(V->getContext());
98 for (unsigned I = 0, E = V->getNumElements(); I != E; ++I) {
99 Constant *Elt = V->getElementAsConstant(I);
100 assert((isa<ConstantInt>(Elt) || isa<ConstantFP>(Elt)) &&
101 "Unexpected constant data vector element type");
102 bool Sign = V->getElementType()->isIntegerTy()
103 ? cast<ConstantInt>(Elt)->isNegative()
104 : cast<ConstantFP>(Elt)->isNegative();
105 BoolVec.push_back(ConstantInt::get(BoolTy, Sign));
106 }
107 return ConstantVector::get(BoolVec);
108}
109
Daniel Neilson8f30ec62018-05-11 14:30:02 +0000110Instruction *InstCombiner::SimplifyAnyMemTransfer(AnyMemTransferInst *MI) {
Daniel Neilson2363da92018-02-12 23:06:55 +0000111 unsigned DstAlign = getKnownAlignment(MI->getRawDest(), DL, MI, &AC, &DT);
112 unsigned CopyDstAlign = MI->getDestAlignment();
113 if (CopyDstAlign < DstAlign){
114 MI->setDestAlignment(DstAlign);
115 return MI;
116 }
Chris Lattner7a9e47a2010-01-05 07:32:13 +0000117
Daniel Neilson8f30ec62018-05-11 14:30:02 +0000118 unsigned SrcAlign = getKnownAlignment(MI->getRawSource(), DL, MI, &AC, &DT);
119 unsigned CopySrcAlign = MI->getSourceAlignment();
Daniel Neilson2363da92018-02-12 23:06:55 +0000120 if (CopySrcAlign < SrcAlign) {
Daniel Neilson8f30ec62018-05-11 14:30:02 +0000121 MI->setSourceAlignment(SrcAlign);
Chris Lattner7a9e47a2010-01-05 07:32:13 +0000122 return MI;
123 }
Jim Grosbach7815f562012-02-03 00:07:04 +0000124
Philip Reamesd7486892019-04-22 20:28:19 +0000125 // If we have a store to a location which is known constant, we can conclude
126 // that the store must be storing the constant value (else the memory
127 // wouldn't be constant), and this must be a noop.
128 if (AA->pointsToConstantMemory(MI->getDest())) {
129 // Set the size of the copy to 0, it will be deleted on the next iteration.
130 MI->setLength(Constant::getNullValue(MI->getLength()->getType()));
131 return MI;
132 }
133
Chris Lattner7a9e47a2010-01-05 07:32:13 +0000134 // If MemCpyInst length is 1/2/4/8 bytes then replace memcpy with
135 // load/store.
Daniel Neilson8f30ec62018-05-11 14:30:02 +0000136 ConstantInt *MemOpLength = dyn_cast<ConstantInt>(MI->getLength());
Craig Topperf40110f2014-04-25 05:29:35 +0000137 if (!MemOpLength) return nullptr;
Jim Grosbach7815f562012-02-03 00:07:04 +0000138
Chris Lattner7a9e47a2010-01-05 07:32:13 +0000139 // Source and destination pointer types are always "i8*" for intrinsic. See
140 // if the size is something we can handle with a single primitive load/store.
141 // A single load+store correctly handles overlapping memory in the memmove
142 // case.
Michael Liao69e172a2012-08-15 03:49:59 +0000143 uint64_t Size = MemOpLength->getLimitedValue();
Alp Tokercb402912014-01-24 17:20:08 +0000144 assert(Size && "0-sized memory transferring should be removed already.");
Jim Grosbach7815f562012-02-03 00:07:04 +0000145
Chris Lattner7a9e47a2010-01-05 07:32:13 +0000146 if (Size > 8 || (Size&(Size-1)))
Craig Topperf40110f2014-04-25 05:29:35 +0000147 return nullptr; // If not 1/2/4/8 bytes, exit.
Jim Grosbach7815f562012-02-03 00:07:04 +0000148
Serguei Katkova5b0e552019-01-16 04:36:26 +0000149 // If it is an atomic and alignment is less than the size then we will
150 // introduce the unaligned memory access which will be later transformed
151 // into libcall in CodeGen. This is not evident performance gain so disable
152 // it now.
153 if (isa<AtomicMemTransferInst>(MI))
154 if (CopyDstAlign < Size || CopySrcAlign < Size)
155 return nullptr;
156
Chris Lattner7a9e47a2010-01-05 07:32:13 +0000157 // Use an integer load+store unless we can find something better.
Mon P Wangc576ee92010-04-04 03:10:48 +0000158 unsigned SrcAddrSp =
Gabor Greif0a136c92010-06-24 13:54:33 +0000159 cast<PointerType>(MI->getArgOperand(1)->getType())->getAddressSpace();
Gabor Greiff3755202010-04-16 15:33:14 +0000160 unsigned DstAddrSp =
Gabor Greif0a136c92010-06-24 13:54:33 +0000161 cast<PointerType>(MI->getArgOperand(0)->getType())->getAddressSpace();
Mon P Wangc576ee92010-04-04 03:10:48 +0000162
Chris Lattner229907c2011-07-18 04:54:35 +0000163 IntegerType* IntType = IntegerType::get(MI->getContext(), Size<<3);
Mon P Wangc576ee92010-04-04 03:10:48 +0000164 Type *NewSrcPtrTy = PointerType::get(IntType, SrcAddrSp);
165 Type *NewDstPtrTy = PointerType::get(IntType, DstAddrSp);
Jim Grosbach7815f562012-02-03 00:07:04 +0000166
Mikael Holmen760dc9a2017-03-01 06:45:20 +0000167 // If the memcpy has metadata describing the members, see if we can get the
168 // TBAA tag describing our copy.
Craig Topperf40110f2014-04-25 05:29:35 +0000169 MDNode *CopyMD = nullptr;
Ivan A. Kosarevf03f5792018-02-19 12:10:20 +0000170 if (MDNode *M = MI->getMetadata(LLVMContext::MD_tbaa)) {
171 CopyMD = M;
172 } else if (MDNode *M = MI->getMetadata(LLVMContext::MD_tbaa_struct)) {
Mikael Holmen760dc9a2017-03-01 06:45:20 +0000173 if (M->getNumOperands() == 3 && M->getOperand(0) &&
174 mdconst::hasa<ConstantInt>(M->getOperand(0)) &&
Craig Topper79ab6432017-07-06 18:39:47 +0000175 mdconst::extract<ConstantInt>(M->getOperand(0))->isZero() &&
Mikael Holmen760dc9a2017-03-01 06:45:20 +0000176 M->getOperand(1) &&
177 mdconst::hasa<ConstantInt>(M->getOperand(1)) &&
178 mdconst::extract<ConstantInt>(M->getOperand(1))->getValue() ==
179 Size &&
180 M->getOperand(2) && isa<MDNode>(M->getOperand(2)))
181 CopyMD = cast<MDNode>(M->getOperand(2));
Chris Lattner7a9e47a2010-01-05 07:32:13 +0000182 }
Jim Grosbach7815f562012-02-03 00:07:04 +0000183
Craig Topperbb4069e2017-07-07 23:16:26 +0000184 Value *Src = Builder.CreateBitCast(MI->getArgOperand(1), NewSrcPtrTy);
185 Value *Dest = Builder.CreateBitCast(MI->getArgOperand(0), NewDstPtrTy);
James Y Knight14359ef2019-02-01 20:44:24 +0000186 LoadInst *L = Builder.CreateLoad(IntType, Src);
Daniel Neilson2363da92018-02-12 23:06:55 +0000187 // Alignment from the mem intrinsic will be better, so use it.
Guillaume Chateletd400d452019-10-03 13:17:21 +0000188 L->setAlignment(
189 MaybeAlign(CopySrcAlign)); // FIXME: Check if we can use Align instead.
Dan Gohman3f553c22012-09-13 21:51:01 +0000190 if (CopyMD)
191 L->setMetadata(LLVMContext::MD_tbaa, CopyMD);
Dorit Nuzmanabd15f62016-09-04 07:49:39 +0000192 MDNode *LoopMemParallelMD =
193 MI->getMetadata(LLVMContext::MD_mem_parallel_loop_access);
194 if (LoopMemParallelMD)
195 L->setMetadata(LLVMContext::MD_mem_parallel_loop_access, LoopMemParallelMD);
Michael Kruse978ba612018-12-20 04:58:07 +0000196 MDNode *AccessGroupMD = MI->getMetadata(LLVMContext::MD_access_group);
197 if (AccessGroupMD)
198 L->setMetadata(LLVMContext::MD_access_group, AccessGroupMD);
Dorit Nuzman7673ba72016-09-04 07:06:00 +0000199
Daniel Neilson8f30ec62018-05-11 14:30:02 +0000200 StoreInst *S = Builder.CreateStore(L, Dest);
Daniel Neilson2363da92018-02-12 23:06:55 +0000201 // Alignment from the mem intrinsic will be better, so use it.
Guillaume Chateletd400d452019-10-03 13:17:21 +0000202 S->setAlignment(
203 MaybeAlign(CopyDstAlign)); // FIXME: Check if we can use Align instead.
Dan Gohman3f553c22012-09-13 21:51:01 +0000204 if (CopyMD)
205 S->setMetadata(LLVMContext::MD_tbaa, CopyMD);
Dorit Nuzmanabd15f62016-09-04 07:49:39 +0000206 if (LoopMemParallelMD)
207 S->setMetadata(LLVMContext::MD_mem_parallel_loop_access, LoopMemParallelMD);
Michael Kruse978ba612018-12-20 04:58:07 +0000208 if (AccessGroupMD)
209 S->setMetadata(LLVMContext::MD_access_group, AccessGroupMD);
Chris Lattner7a9e47a2010-01-05 07:32:13 +0000210
Daniel Neilson8f30ec62018-05-11 14:30:02 +0000211 if (auto *MT = dyn_cast<MemTransferInst>(MI)) {
212 // non-atomics can be volatile
213 L->setVolatile(MT->isVolatile());
214 S->setVolatile(MT->isVolatile());
215 }
216 if (isa<AtomicMemTransferInst>(MI)) {
217 // atomics have to be unordered
218 L->setOrdering(AtomicOrdering::Unordered);
219 S->setOrdering(AtomicOrdering::Unordered);
220 }
221
Chris Lattner7a9e47a2010-01-05 07:32:13 +0000222 // Set the size of the copy to 0, it will be deleted on the next iteration.
Daniel Neilson8f30ec62018-05-11 14:30:02 +0000223 MI->setLength(Constant::getNullValue(MemOpLength->getType()));
Chris Lattner7a9e47a2010-01-05 07:32:13 +0000224 return MI;
225}
226
Daniel Neilsonf6651d42018-05-11 20:04:50 +0000227Instruction *InstCombiner::SimplifyAnyMemSet(AnyMemSetInst *MI) {
Guillaume Chateletd400d452019-10-03 13:17:21 +0000228 const unsigned KnownAlignment =
229 getKnownAlignment(MI->getDest(), DL, MI, &AC, &DT);
230 if (MI->getDestAlignment() < KnownAlignment) {
231 MI->setDestAlignment(KnownAlignment);
Chris Lattner7a9e47a2010-01-05 07:32:13 +0000232 return MI;
233 }
Jim Grosbach7815f562012-02-03 00:07:04 +0000234
Philip Reamesd7486892019-04-22 20:28:19 +0000235 // If we have a store to a location which is known constant, we can conclude
236 // that the store must be storing the constant value (else the memory
237 // wouldn't be constant), and this must be a noop.
238 if (AA->pointsToConstantMemory(MI->getDest())) {
239 // Set the size of the copy to 0, it will be deleted on the next iteration.
240 MI->setLength(Constant::getNullValue(MI->getLength()->getType()));
241 return MI;
242 }
243
Chris Lattner7a9e47a2010-01-05 07:32:13 +0000244 // Extract the length and alignment and fill if they are constant.
245 ConstantInt *LenC = dyn_cast<ConstantInt>(MI->getLength());
246 ConstantInt *FillC = dyn_cast<ConstantInt>(MI->getValue());
Duncan Sands9dff9be2010-02-15 16:12:20 +0000247 if (!LenC || !FillC || !FillC->getType()->isIntegerTy(8))
Craig Topperf40110f2014-04-25 05:29:35 +0000248 return nullptr;
Guillaume Chateletd400d452019-10-03 13:17:21 +0000249 const uint64_t Len = LenC->getLimitedValue();
Michael Liao69e172a2012-08-15 03:49:59 +0000250 assert(Len && "0-sized memory setting should be removed already.");
Guillaume Chateletd400d452019-10-03 13:17:21 +0000251 const Align Alignment = assumeAligned(MI->getDestAlignment());
Serguei Katkova5b0e552019-01-16 04:36:26 +0000252
253 // If it is an atomic and alignment is less than the size then we will
254 // introduce the unaligned memory access which will be later transformed
255 // into libcall in CodeGen. This is not evident performance gain so disable
256 // it now.
257 if (isa<AtomicMemSetInst>(MI))
258 if (Alignment < Len)
259 return nullptr;
260
Chris Lattner7a9e47a2010-01-05 07:32:13 +0000261 // memset(s,c,n) -> store s, c (for n=1,2,4,8)
262 if (Len <= 8 && isPowerOf2_32((uint32_t)Len)) {
Chris Lattner229907c2011-07-18 04:54:35 +0000263 Type *ITy = IntegerType::get(MI->getContext(), Len*8); // n=1 -> i8.
Jim Grosbach7815f562012-02-03 00:07:04 +0000264
Chris Lattner7a9e47a2010-01-05 07:32:13 +0000265 Value *Dest = MI->getDest();
Mon P Wang1991c472010-12-20 01:05:30 +0000266 unsigned DstAddrSp = cast<PointerType>(Dest->getType())->getAddressSpace();
267 Type *NewDstPtrTy = PointerType::get(ITy, DstAddrSp);
Craig Topperbb4069e2017-07-07 23:16:26 +0000268 Dest = Builder.CreateBitCast(Dest, NewDstPtrTy);
Chris Lattner7a9e47a2010-01-05 07:32:13 +0000269
Chris Lattner7a9e47a2010-01-05 07:32:13 +0000270 // Extract the fill value and store.
271 uint64_t Fill = FillC->getZExtValue()*0x0101010101010101ULL;
Craig Topperbb4069e2017-07-07 23:16:26 +0000272 StoreInst *S = Builder.CreateStore(ConstantInt::get(ITy, Fill), Dest,
273 MI->isVolatile());
Eli Friedman49346012011-05-18 19:57:14 +0000274 S->setAlignment(Alignment);
Daniel Neilsonf6651d42018-05-11 20:04:50 +0000275 if (isa<AtomicMemSetInst>(MI))
276 S->setOrdering(AtomicOrdering::Unordered);
Jim Grosbach7815f562012-02-03 00:07:04 +0000277
Chris Lattner7a9e47a2010-01-05 07:32:13 +0000278 // Set the size of the copy to 0, it will be deleted on the next iteration.
279 MI->setLength(Constant::getNullValue(LenC->getType()));
280 return MI;
281 }
282
Simon Pilgrim18617d12015-08-05 08:18:00 +0000283 return nullptr;
284}
285
Sanjay Patel6038d3e2016-01-29 23:27:03 +0000286static Value *simplifyX86immShift(const IntrinsicInst &II,
Simon Pilgrimbecd5e82015-08-13 07:39:03 +0000287 InstCombiner::BuilderTy &Builder) {
288 bool LogicalShift = false;
289 bool ShiftLeft = false;
290
291 switch (II.getIntrinsicID()) {
Craig Topperb4173a52016-11-13 07:26:19 +0000292 default: llvm_unreachable("Unexpected intrinsic!");
Simon Pilgrimbecd5e82015-08-13 07:39:03 +0000293 case Intrinsic::x86_sse2_psra_d:
294 case Intrinsic::x86_sse2_psra_w:
295 case Intrinsic::x86_sse2_psrai_d:
296 case Intrinsic::x86_sse2_psrai_w:
297 case Intrinsic::x86_avx2_psra_d:
298 case Intrinsic::x86_avx2_psra_w:
299 case Intrinsic::x86_avx2_psrai_d:
300 case Intrinsic::x86_avx2_psrai_w:
Craig Topper8b831cb2016-11-13 01:51:55 +0000301 case Intrinsic::x86_avx512_psra_q_128:
302 case Intrinsic::x86_avx512_psrai_q_128:
303 case Intrinsic::x86_avx512_psra_q_256:
304 case Intrinsic::x86_avx512_psrai_q_256:
305 case Intrinsic::x86_avx512_psra_d_512:
306 case Intrinsic::x86_avx512_psra_q_512:
307 case Intrinsic::x86_avx512_psra_w_512:
308 case Intrinsic::x86_avx512_psrai_d_512:
309 case Intrinsic::x86_avx512_psrai_q_512:
310 case Intrinsic::x86_avx512_psrai_w_512:
Simon Pilgrimbecd5e82015-08-13 07:39:03 +0000311 LogicalShift = false; ShiftLeft = false;
312 break;
313 case Intrinsic::x86_sse2_psrl_d:
314 case Intrinsic::x86_sse2_psrl_q:
315 case Intrinsic::x86_sse2_psrl_w:
316 case Intrinsic::x86_sse2_psrli_d:
317 case Intrinsic::x86_sse2_psrli_q:
318 case Intrinsic::x86_sse2_psrli_w:
319 case Intrinsic::x86_avx2_psrl_d:
320 case Intrinsic::x86_avx2_psrl_q:
321 case Intrinsic::x86_avx2_psrl_w:
322 case Intrinsic::x86_avx2_psrli_d:
323 case Intrinsic::x86_avx2_psrli_q:
324 case Intrinsic::x86_avx2_psrli_w:
Craig Topper8b831cb2016-11-13 01:51:55 +0000325 case Intrinsic::x86_avx512_psrl_d_512:
326 case Intrinsic::x86_avx512_psrl_q_512:
327 case Intrinsic::x86_avx512_psrl_w_512:
328 case Intrinsic::x86_avx512_psrli_d_512:
329 case Intrinsic::x86_avx512_psrli_q_512:
330 case Intrinsic::x86_avx512_psrli_w_512:
Simon Pilgrimbecd5e82015-08-13 07:39:03 +0000331 LogicalShift = true; ShiftLeft = false;
332 break;
333 case Intrinsic::x86_sse2_psll_d:
334 case Intrinsic::x86_sse2_psll_q:
335 case Intrinsic::x86_sse2_psll_w:
336 case Intrinsic::x86_sse2_pslli_d:
337 case Intrinsic::x86_sse2_pslli_q:
338 case Intrinsic::x86_sse2_pslli_w:
339 case Intrinsic::x86_avx2_psll_d:
340 case Intrinsic::x86_avx2_psll_q:
341 case Intrinsic::x86_avx2_psll_w:
342 case Intrinsic::x86_avx2_pslli_d:
343 case Intrinsic::x86_avx2_pslli_q:
344 case Intrinsic::x86_avx2_pslli_w:
Craig Topper8b831cb2016-11-13 01:51:55 +0000345 case Intrinsic::x86_avx512_psll_d_512:
346 case Intrinsic::x86_avx512_psll_q_512:
347 case Intrinsic::x86_avx512_psll_w_512:
348 case Intrinsic::x86_avx512_pslli_d_512:
349 case Intrinsic::x86_avx512_pslli_q_512:
350 case Intrinsic::x86_avx512_pslli_w_512:
Simon Pilgrimbecd5e82015-08-13 07:39:03 +0000351 LogicalShift = true; ShiftLeft = true;
352 break;
353 }
Simon Pilgrima3a72b42015-08-10 20:21:15 +0000354 assert((LogicalShift || !ShiftLeft) && "Only logical shifts can shift left");
355
Simon Pilgrim3815c162015-08-07 18:22:50 +0000356 // Simplify if count is constant.
357 auto Arg1 = II.getArgOperand(1);
358 auto CAZ = dyn_cast<ConstantAggregateZero>(Arg1);
359 auto CDV = dyn_cast<ConstantDataVector>(Arg1);
360 auto CInt = dyn_cast<ConstantInt>(Arg1);
361 if (!CAZ && !CDV && !CInt)
Simon Pilgrim18617d12015-08-05 08:18:00 +0000362 return nullptr;
Simon Pilgrim3815c162015-08-07 18:22:50 +0000363
364 APInt Count(64, 0);
365 if (CDV) {
366 // SSE2/AVX2 uses all the first 64-bits of the 128-bit vector
367 // operand to compute the shift amount.
368 auto VT = cast<VectorType>(CDV->getType());
369 unsigned BitWidth = VT->getElementType()->getPrimitiveSizeInBits();
370 assert((64 % BitWidth) == 0 && "Unexpected packed shift size");
371 unsigned NumSubElts = 64 / BitWidth;
372
373 // Concatenate the sub-elements to create the 64-bit value.
374 for (unsigned i = 0; i != NumSubElts; ++i) {
375 unsigned SubEltIdx = (NumSubElts - 1) - i;
376 auto SubElt = cast<ConstantInt>(CDV->getElementAsConstant(SubEltIdx));
Craig Topper24e71012017-04-28 03:36:24 +0000377 Count <<= BitWidth;
Simon Pilgrim3815c162015-08-07 18:22:50 +0000378 Count |= SubElt->getValue().zextOrTrunc(64);
379 }
380 }
381 else if (CInt)
382 Count = CInt->getValue();
Simon Pilgrim18617d12015-08-05 08:18:00 +0000383
384 auto Vec = II.getArgOperand(0);
385 auto VT = cast<VectorType>(Vec->getType());
386 auto SVT = VT->getElementType();
Simon Pilgrim3815c162015-08-07 18:22:50 +0000387 unsigned VWidth = VT->getNumElements();
388 unsigned BitWidth = SVT->getPrimitiveSizeInBits();
389
390 // If shift-by-zero then just return the original value.
Craig Topper73ba1c82017-06-07 07:40:37 +0000391 if (Count.isNullValue())
Simon Pilgrim3815c162015-08-07 18:22:50 +0000392 return Vec;
393
Simon Pilgrima3a72b42015-08-10 20:21:15 +0000394 // Handle cases when Shift >= BitWidth.
395 if (Count.uge(BitWidth)) {
396 // If LogicalShift - just return zero.
397 if (LogicalShift)
398 return ConstantAggregateZero::get(VT);
399
400 // If ArithmeticShift - clamp Shift to (BitWidth - 1).
401 Count = APInt(64, BitWidth - 1);
402 }
Simon Pilgrim18617d12015-08-05 08:18:00 +0000403
Simon Pilgrim18617d12015-08-05 08:18:00 +0000404 // Get a constant vector of the same type as the first operand.
Simon Pilgrim3815c162015-08-07 18:22:50 +0000405 auto ShiftAmt = ConstantInt::get(SVT, Count.zextOrTrunc(BitWidth));
406 auto ShiftVec = Builder.CreateVectorSplat(VWidth, ShiftAmt);
Simon Pilgrim18617d12015-08-05 08:18:00 +0000407
408 if (ShiftLeft)
Simon Pilgrim3815c162015-08-07 18:22:50 +0000409 return Builder.CreateShl(Vec, ShiftVec);
Simon Pilgrim18617d12015-08-05 08:18:00 +0000410
Simon Pilgrima3a72b42015-08-10 20:21:15 +0000411 if (LogicalShift)
412 return Builder.CreateLShr(Vec, ShiftVec);
413
414 return Builder.CreateAShr(Vec, ShiftVec);
Simon Pilgrim18617d12015-08-05 08:18:00 +0000415}
416
Simon Pilgrimdb9893f2016-06-07 10:27:15 +0000417// Attempt to simplify AVX2 per-element shift intrinsics to a generic IR shift.
418// Unlike the generic IR shifts, the intrinsics have defined behaviour for out
419// of range shift amounts (logical - set to zero, arithmetic - splat sign bit).
420static Value *simplifyX86varShift(const IntrinsicInst &II,
421 InstCombiner::BuilderTy &Builder) {
422 bool LogicalShift = false;
423 bool ShiftLeft = false;
424
425 switch (II.getIntrinsicID()) {
Craig Topperb4173a52016-11-13 07:26:19 +0000426 default: llvm_unreachable("Unexpected intrinsic!");
Simon Pilgrimdb9893f2016-06-07 10:27:15 +0000427 case Intrinsic::x86_avx2_psrav_d:
428 case Intrinsic::x86_avx2_psrav_d_256:
Craig Topperb4173a52016-11-13 07:26:19 +0000429 case Intrinsic::x86_avx512_psrav_q_128:
430 case Intrinsic::x86_avx512_psrav_q_256:
431 case Intrinsic::x86_avx512_psrav_d_512:
432 case Intrinsic::x86_avx512_psrav_q_512:
Craig Topper1de753f2016-11-18 06:04:33 +0000433 case Intrinsic::x86_avx512_psrav_w_128:
434 case Intrinsic::x86_avx512_psrav_w_256:
435 case Intrinsic::x86_avx512_psrav_w_512:
Simon Pilgrimdb9893f2016-06-07 10:27:15 +0000436 LogicalShift = false;
437 ShiftLeft = false;
438 break;
439 case Intrinsic::x86_avx2_psrlv_d:
440 case Intrinsic::x86_avx2_psrlv_d_256:
441 case Intrinsic::x86_avx2_psrlv_q:
442 case Intrinsic::x86_avx2_psrlv_q_256:
Craig Topperb4173a52016-11-13 07:26:19 +0000443 case Intrinsic::x86_avx512_psrlv_d_512:
444 case Intrinsic::x86_avx512_psrlv_q_512:
Craig Topper1de753f2016-11-18 06:04:33 +0000445 case Intrinsic::x86_avx512_psrlv_w_128:
446 case Intrinsic::x86_avx512_psrlv_w_256:
447 case Intrinsic::x86_avx512_psrlv_w_512:
Simon Pilgrimdb9893f2016-06-07 10:27:15 +0000448 LogicalShift = true;
449 ShiftLeft = false;
450 break;
451 case Intrinsic::x86_avx2_psllv_d:
452 case Intrinsic::x86_avx2_psllv_d_256:
453 case Intrinsic::x86_avx2_psllv_q:
454 case Intrinsic::x86_avx2_psllv_q_256:
Craig Topperb4173a52016-11-13 07:26:19 +0000455 case Intrinsic::x86_avx512_psllv_d_512:
456 case Intrinsic::x86_avx512_psllv_q_512:
Craig Topper1de753f2016-11-18 06:04:33 +0000457 case Intrinsic::x86_avx512_psllv_w_128:
458 case Intrinsic::x86_avx512_psllv_w_256:
459 case Intrinsic::x86_avx512_psllv_w_512:
Simon Pilgrimdb9893f2016-06-07 10:27:15 +0000460 LogicalShift = true;
461 ShiftLeft = true;
462 break;
463 }
464 assert((LogicalShift || !ShiftLeft) && "Only logical shifts can shift left");
465
466 // Simplify if all shift amounts are constant/undef.
467 auto *CShift = dyn_cast<Constant>(II.getArgOperand(1));
468 if (!CShift)
469 return nullptr;
470
471 auto Vec = II.getArgOperand(0);
472 auto VT = cast<VectorType>(II.getType());
473 auto SVT = VT->getVectorElementType();
474 int NumElts = VT->getNumElements();
475 int BitWidth = SVT->getIntegerBitWidth();
476
477 // Collect each element's shift amount.
478 // We also collect special cases: UNDEF = -1, OUT-OF-RANGE = BitWidth.
479 bool AnyOutOfRange = false;
480 SmallVector<int, 8> ShiftAmts;
481 for (int I = 0; I < NumElts; ++I) {
482 auto *CElt = CShift->getAggregateElement(I);
483 if (CElt && isa<UndefValue>(CElt)) {
484 ShiftAmts.push_back(-1);
485 continue;
486 }
487
488 auto *COp = dyn_cast_or_null<ConstantInt>(CElt);
489 if (!COp)
490 return nullptr;
491
492 // Handle out of range shifts.
493 // If LogicalShift - set to BitWidth (special case).
494 // If ArithmeticShift - set to (BitWidth - 1) (sign splat).
495 APInt ShiftVal = COp->getValue();
496 if (ShiftVal.uge(BitWidth)) {
497 AnyOutOfRange = LogicalShift;
498 ShiftAmts.push_back(LogicalShift ? BitWidth : BitWidth - 1);
499 continue;
500 }
501
502 ShiftAmts.push_back((int)ShiftVal.getZExtValue());
503 }
504
505 // If all elements out of range or UNDEF, return vector of zeros/undefs.
506 // ArithmeticShift should only hit this if they are all UNDEF.
507 auto OutOfRange = [&](int Idx) { return (Idx < 0) || (BitWidth <= Idx); };
Eugene Zelenko7f0f9bc2017-10-24 21:24:53 +0000508 if (llvm::all_of(ShiftAmts, OutOfRange)) {
Simon Pilgrimdb9893f2016-06-07 10:27:15 +0000509 SmallVector<Constant *, 8> ConstantVec;
510 for (int Idx : ShiftAmts) {
511 if (Idx < 0) {
512 ConstantVec.push_back(UndefValue::get(SVT));
513 } else {
514 assert(LogicalShift && "Logical shift expected");
515 ConstantVec.push_back(ConstantInt::getNullValue(SVT));
516 }
517 }
518 return ConstantVector::get(ConstantVec);
519 }
520
521 // We can't handle only some out of range values with generic logical shifts.
522 if (AnyOutOfRange)
523 return nullptr;
524
525 // Build the shift amount constant vector.
526 SmallVector<Constant *, 8> ShiftVecAmts;
527 for (int Idx : ShiftAmts) {
528 if (Idx < 0)
529 ShiftVecAmts.push_back(UndefValue::get(SVT));
530 else
531 ShiftVecAmts.push_back(ConstantInt::get(SVT, Idx));
532 }
533 auto ShiftVec = ConstantVector::get(ShiftVecAmts);
534
535 if (ShiftLeft)
536 return Builder.CreateShl(Vec, ShiftVec);
537
538 if (LogicalShift)
539 return Builder.CreateLShr(Vec, ShiftVec);
540
541 return Builder.CreateAShr(Vec, ShiftVec);
542}
543
Simon Pilgrim55f14da2019-04-24 16:53:17 +0000544static Value *simplifyX86pack(IntrinsicInst &II,
545 InstCombiner::BuilderTy &Builder, bool IsSigned) {
Simon Pilgrim6f6b2792017-01-25 14:37:24 +0000546 Value *Arg0 = II.getArgOperand(0);
547 Value *Arg1 = II.getArgOperand(1);
548 Type *ResTy = II.getType();
549
550 // Fast all undef handling.
551 if (isa<UndefValue>(Arg0) && isa<UndefValue>(Arg1))
552 return UndefValue::get(ResTy);
553
554 Type *ArgTy = Arg0->getType();
555 unsigned NumLanes = ResTy->getPrimitiveSizeInBits() / 128;
Simon Pilgrim6f6b2792017-01-25 14:37:24 +0000556 unsigned NumSrcElts = ArgTy->getVectorNumElements();
Simon Pilgrim55f14da2019-04-24 16:53:17 +0000557 assert(ResTy->getVectorNumElements() == (2 * NumSrcElts) &&
558 "Unexpected packing types");
Simon Pilgrim6f6b2792017-01-25 14:37:24 +0000559
Simon Pilgrim6f6b2792017-01-25 14:37:24 +0000560 unsigned NumSrcEltsPerLane = NumSrcElts / NumLanes;
561 unsigned DstScalarSizeInBits = ResTy->getScalarSizeInBits();
Simon Pilgrim55f14da2019-04-24 16:53:17 +0000562 unsigned SrcScalarSizeInBits = ArgTy->getScalarSizeInBits();
563 assert(SrcScalarSizeInBits == (2 * DstScalarSizeInBits) &&
Simon Pilgrim6f6b2792017-01-25 14:37:24 +0000564 "Unexpected packing types");
565
566 // Constant folding.
Simon Pilgrim55f14da2019-04-24 16:53:17 +0000567 if (!isa<Constant>(Arg0) || !isa<Constant>(Arg1))
Simon Pilgrim6f6b2792017-01-25 14:37:24 +0000568 return nullptr;
569
Simon Pilgrim55f14da2019-04-24 16:53:17 +0000570 // Clamp Values - signed/unsigned both use signed clamp values, but they
571 // differ on the min/max values.
572 APInt MinValue, MaxValue;
573 if (IsSigned) {
574 // PACKSS: Truncate signed value with signed saturation.
575 // Source values less than dst minint are saturated to minint.
576 // Source values greater than dst maxint are saturated to maxint.
577 MinValue =
578 APInt::getSignedMinValue(DstScalarSizeInBits).sext(SrcScalarSizeInBits);
579 MaxValue =
580 APInt::getSignedMaxValue(DstScalarSizeInBits).sext(SrcScalarSizeInBits);
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 MinValue = APInt::getNullValue(SrcScalarSizeInBits);
586 MaxValue = APInt::getLowBitsSet(SrcScalarSizeInBits, DstScalarSizeInBits);
Simon Pilgrim6f6b2792017-01-25 14:37:24 +0000587 }
588
Simon Pilgrim55f14da2019-04-24 16:53:17 +0000589 auto *MinC = Constant::getIntegerValue(ArgTy, MinValue);
590 auto *MaxC = Constant::getIntegerValue(ArgTy, MaxValue);
591 Arg0 = Builder.CreateSelect(Builder.CreateICmpSLT(Arg0, MinC), MinC, Arg0);
592 Arg1 = Builder.CreateSelect(Builder.CreateICmpSLT(Arg1, MinC), MinC, Arg1);
593 Arg0 = Builder.CreateSelect(Builder.CreateICmpSGT(Arg0, MaxC), MaxC, Arg0);
594 Arg1 = Builder.CreateSelect(Builder.CreateICmpSGT(Arg1, MaxC), MaxC, Arg1);
595
Simon Pilgrim48a3b542019-04-25 13:51:57 +0000596 // Shuffle clamped args together at the lane level.
Simon Pilgrim55f14da2019-04-24 16:53:17 +0000597 SmallVector<unsigned, 32> PackMask;
598 for (unsigned Lane = 0; Lane != NumLanes; ++Lane) {
599 for (unsigned Elt = 0; Elt != NumSrcEltsPerLane; ++Elt)
600 PackMask.push_back(Elt + (Lane * NumSrcEltsPerLane));
601 for (unsigned Elt = 0; Elt != NumSrcEltsPerLane; ++Elt)
602 PackMask.push_back(Elt + (Lane * NumSrcEltsPerLane) + NumSrcElts);
603 }
Simon Pilgrim48a3b542019-04-25 13:51:57 +0000604 auto *Shuffle = Builder.CreateShuffleVector(Arg0, Arg1, PackMask);
Simon Pilgrim55f14da2019-04-24 16:53:17 +0000605
Simon Pilgrim48a3b542019-04-25 13:51:57 +0000606 // Truncate to dst size.
607 return Builder.CreateTrunc(Shuffle, ResTy);
Simon Pilgrim6f6b2792017-01-25 14:37:24 +0000608}
609
Sanjay Patel2aa2dc72018-12-11 16:38:03 +0000610static Value *simplifyX86movmsk(const IntrinsicInst &II,
611 InstCombiner::BuilderTy &Builder) {
Simon Pilgrim91e3ac82016-06-07 08:18:35 +0000612 Value *Arg = II.getArgOperand(0);
613 Type *ResTy = II.getType();
614 Type *ArgTy = Arg->getType();
615
616 // movmsk(undef) -> zero as we must ensure the upper bits are zero.
617 if (isa<UndefValue>(Arg))
618 return Constant::getNullValue(ResTy);
619
620 // We can't easily peek through x86_mmx types.
621 if (!ArgTy->isVectorTy())
622 return nullptr;
623
Simon Pilgrimb4f1bfa2019-04-08 13:17:51 +0000624 // Expand MOVMSK to compare/bitcast/zext:
625 // e.g. PMOVMSKB(v16i8 x):
626 // %cmp = icmp slt <16 x i8> %x, zeroinitializer
627 // %int = bitcast <16 x i1> %cmp to i16
628 // %res = zext i16 %int to i32
629 unsigned NumElts = ArgTy->getVectorNumElements();
630 Type *IntegerVecTy = VectorType::getInteger(cast<VectorType>(ArgTy));
631 Type *IntegerTy = Builder.getIntNTy(NumElts);
Simon Pilgrim91e3ac82016-06-07 08:18:35 +0000632
Simon Pilgrimb4f1bfa2019-04-08 13:17:51 +0000633 Value *Res = Builder.CreateBitCast(Arg, IntegerVecTy);
634 Res = Builder.CreateICmpSLT(Res, Constant::getNullValue(IntegerVecTy));
635 Res = Builder.CreateBitCast(Res, IntegerTy);
636 Res = Builder.CreateZExtOrTrunc(Res, ResTy);
637 return Res;
Simon Pilgrim91e3ac82016-06-07 08:18:35 +0000638}
639
Sanjay Patelbe23a912019-02-01 14:14:47 +0000640static Value *simplifyX86addcarry(const IntrinsicInst &II,
641 InstCombiner::BuilderTy &Builder) {
642 Value *CarryIn = II.getArgOperand(0);
643 Value *Op1 = II.getArgOperand(1);
644 Value *Op2 = II.getArgOperand(2);
645 Type *RetTy = II.getType();
646 Type *OpTy = Op1->getType();
647 assert(RetTy->getStructElementType(0)->isIntegerTy(8) &&
648 RetTy->getStructElementType(1) == OpTy && OpTy == Op2->getType() &&
649 "Unexpected types for x86 addcarry");
650
651 // If carry-in is zero, this is just an unsigned add with overflow.
652 if (match(CarryIn, m_ZeroInt())) {
653 Value *UAdd = Builder.CreateIntrinsic(Intrinsic::uadd_with_overflow, OpTy,
654 { Op1, Op2 });
655 // The types have to be adjusted to match the x86 call types.
656 Value *UAddResult = Builder.CreateExtractValue(UAdd, 0);
657 Value *UAddOV = Builder.CreateZExt(Builder.CreateExtractValue(UAdd, 1),
658 Builder.getInt8Ty());
Sanjay Patelfbcbac72019-02-01 14:37:49 +0000659 Value *Res = UndefValue::get(RetTy);
Sanjay Patelbe23a912019-02-01 14:14:47 +0000660 Res = Builder.CreateInsertValue(Res, UAddOV, 0);
661 return Builder.CreateInsertValue(Res, UAddResult, 1);
662 }
663
664 return nullptr;
665}
666
Sanjay Patel6038d3e2016-01-29 23:27:03 +0000667static Value *simplifyX86insertps(const IntrinsicInst &II,
Sanjay Patelc86867c2015-04-16 17:52:13 +0000668 InstCombiner::BuilderTy &Builder) {
Sanjay Patel03c03f52016-01-28 00:03:16 +0000669 auto *CInt = dyn_cast<ConstantInt>(II.getArgOperand(2));
670 if (!CInt)
671 return nullptr;
Simon Pilgrim54fcd622015-07-25 20:41:00 +0000672
Sanjay Patel03c03f52016-01-28 00:03:16 +0000673 VectorType *VecTy = cast<VectorType>(II.getType());
674 assert(VecTy->getNumElements() == 4 && "insertps with wrong vector type");
Sanjay Patelc86867c2015-04-16 17:52:13 +0000675
Sanjay Patel03c03f52016-01-28 00:03:16 +0000676 // The immediate permute control byte looks like this:
677 // [3:0] - zero mask for each 32-bit lane
678 // [5:4] - select one 32-bit destination lane
679 // [7:6] - select one 32-bit source lane
Sanjay Patelc86867c2015-04-16 17:52:13 +0000680
Sanjay Patel03c03f52016-01-28 00:03:16 +0000681 uint8_t Imm = CInt->getZExtValue();
682 uint8_t ZMask = Imm & 0xf;
683 uint8_t DestLane = (Imm >> 4) & 0x3;
684 uint8_t SourceLane = (Imm >> 6) & 0x3;
Sanjay Patelc1d20a32015-04-25 20:55:25 +0000685
Sanjay Patel03c03f52016-01-28 00:03:16 +0000686 ConstantAggregateZero *ZeroVector = ConstantAggregateZero::get(VecTy);
Sanjay Patelc86867c2015-04-16 17:52:13 +0000687
Sanjay Patel03c03f52016-01-28 00:03:16 +0000688 // If all zero mask bits are set, this was just a weird way to
689 // generate a zero vector.
690 if (ZMask == 0xf)
691 return ZeroVector;
Sanjay Patelc1d20a32015-04-25 20:55:25 +0000692
Sanjay Patel03c03f52016-01-28 00:03:16 +0000693 // Initialize by passing all of the first source bits through.
Craig Topper99d1eab2016-06-12 00:41:19 +0000694 uint32_t ShuffleMask[4] = { 0, 1, 2, 3 };
Sanjay Patelc1d20a32015-04-25 20:55:25 +0000695
Sanjay Patel03c03f52016-01-28 00:03:16 +0000696 // We may replace the second operand with the zero vector.
697 Value *V1 = II.getArgOperand(1);
698
699 if (ZMask) {
700 // If the zero mask is being used with a single input or the zero mask
701 // overrides the destination lane, this is a shuffle with the zero vector.
702 if ((II.getArgOperand(0) == II.getArgOperand(1)) ||
703 (ZMask & (1 << DestLane))) {
704 V1 = ZeroVector;
705 // We may still move 32-bits of the first source vector from one lane
706 // to another.
707 ShuffleMask[DestLane] = SourceLane;
708 // The zero mask may override the previous insert operation.
709 for (unsigned i = 0; i < 4; ++i)
710 if ((ZMask >> i) & 0x1)
711 ShuffleMask[i] = i + 4;
Sanjay Patelc1d20a32015-04-25 20:55:25 +0000712 } else {
Sanjay Patel03c03f52016-01-28 00:03:16 +0000713 // TODO: Model this case as 2 shuffles or a 'logical and' plus shuffle?
714 return nullptr;
Sanjay Patelc1d20a32015-04-25 20:55:25 +0000715 }
Sanjay Patel03c03f52016-01-28 00:03:16 +0000716 } else {
717 // Replace the selected destination lane with the selected source lane.
718 ShuffleMask[DestLane] = SourceLane + 4;
Sanjay Patelc86867c2015-04-16 17:52:13 +0000719 }
Sanjay Patel03c03f52016-01-28 00:03:16 +0000720
721 return Builder.CreateShuffleVector(II.getArgOperand(0), V1, ShuffleMask);
Sanjay Patelc86867c2015-04-16 17:52:13 +0000722}
723
Simon Pilgrim216b1bf2015-10-17 11:40:05 +0000724/// Attempt to simplify SSE4A EXTRQ/EXTRQI instructions using constant folding
725/// or conversion to a shuffle vector.
Sanjay Patel6038d3e2016-01-29 23:27:03 +0000726static Value *simplifyX86extrq(IntrinsicInst &II, Value *Op0,
Simon Pilgrim216b1bf2015-10-17 11:40:05 +0000727 ConstantInt *CILength, ConstantInt *CIIndex,
728 InstCombiner::BuilderTy &Builder) {
729 auto LowConstantHighUndef = [&](uint64_t Val) {
730 Type *IntTy64 = Type::getInt64Ty(II.getContext());
731 Constant *Args[] = {ConstantInt::get(IntTy64, Val),
732 UndefValue::get(IntTy64)};
733 return ConstantVector::get(Args);
734 };
735
736 // See if we're dealing with constant values.
737 Constant *C0 = dyn_cast<Constant>(Op0);
738 ConstantInt *CI0 =
Andrea Di Biagio8df5b9c2016-09-07 12:03:03 +0000739 C0 ? dyn_cast_or_null<ConstantInt>(C0->getAggregateElement((unsigned)0))
Simon Pilgrim216b1bf2015-10-17 11:40:05 +0000740 : nullptr;
741
742 // Attempt to constant fold.
743 if (CILength && CIIndex) {
744 // From AMD documentation: "The bit index and field length are each six
745 // bits in length other bits of the field are ignored."
746 APInt APIndex = CIIndex->getValue().zextOrTrunc(6);
747 APInt APLength = CILength->getValue().zextOrTrunc(6);
748
749 unsigned Index = APIndex.getZExtValue();
750
751 // From AMD documentation: "a value of zero in the field length is
752 // defined as length of 64".
753 unsigned Length = APLength == 0 ? 64 : APLength.getZExtValue();
754
755 // From AMD documentation: "If the sum of the bit index + length field
756 // is greater than 64, the results are undefined".
757 unsigned End = Index + Length;
758
759 // Note that both field index and field length are 8-bit quantities.
760 // Since variables 'Index' and 'Length' are unsigned values
761 // obtained from zero-extending field index and field length
762 // respectively, their sum should never wrap around.
763 if (End > 64)
764 return UndefValue::get(II.getType());
765
766 // If we are inserting whole bytes, we can convert this to a shuffle.
767 // Lowering can recognize EXTRQI shuffle masks.
768 if ((Length % 8) == 0 && (Index % 8) == 0) {
769 // Convert bit indices to byte indices.
770 Length /= 8;
771 Index /= 8;
772
773 Type *IntTy8 = Type::getInt8Ty(II.getContext());
774 Type *IntTy32 = Type::getInt32Ty(II.getContext());
775 VectorType *ShufTy = VectorType::get(IntTy8, 16);
776
777 SmallVector<Constant *, 16> ShuffleMask;
778 for (int i = 0; i != (int)Length; ++i)
779 ShuffleMask.push_back(
780 Constant::getIntegerValue(IntTy32, APInt(32, i + Index)));
781 for (int i = Length; i != 8; ++i)
782 ShuffleMask.push_back(
783 Constant::getIntegerValue(IntTy32, APInt(32, i + 16)));
784 for (int i = 8; i != 16; ++i)
785 ShuffleMask.push_back(UndefValue::get(IntTy32));
786
787 Value *SV = Builder.CreateShuffleVector(
788 Builder.CreateBitCast(Op0, ShufTy),
789 ConstantAggregateZero::get(ShufTy), ConstantVector::get(ShuffleMask));
790 return Builder.CreateBitCast(SV, II.getType());
791 }
792
793 // Constant Fold - shift Index'th bit to lowest position and mask off
794 // Length bits.
795 if (CI0) {
796 APInt Elt = CI0->getValue();
Craig Topperfc947bc2017-04-18 17:14:21 +0000797 Elt.lshrInPlace(Index);
798 Elt = Elt.zextOrTrunc(Length);
Simon Pilgrim216b1bf2015-10-17 11:40:05 +0000799 return LowConstantHighUndef(Elt.getZExtValue());
800 }
801
802 // If we were an EXTRQ call, we'll save registers if we convert to EXTRQI.
803 if (II.getIntrinsicID() == Intrinsic::x86_sse4a_extrq) {
804 Value *Args[] = {Op0, CILength, CIIndex};
Sanjay Patelaf674fb2015-12-14 17:24:23 +0000805 Module *M = II.getModule();
James Y Knight7976eb52019-02-01 20:43:25 +0000806 Function *F = Intrinsic::getDeclaration(M, Intrinsic::x86_sse4a_extrqi);
Simon Pilgrim216b1bf2015-10-17 11:40:05 +0000807 return Builder.CreateCall(F, Args);
808 }
809 }
810
811 // Constant Fold - extraction from zero is always {zero, undef}.
Craig Topperca2c8762017-07-06 18:39:49 +0000812 if (CI0 && CI0->isZero())
Simon Pilgrim216b1bf2015-10-17 11:40:05 +0000813 return LowConstantHighUndef(0);
814
815 return nullptr;
816}
817
818/// Attempt to simplify SSE4A INSERTQ/INSERTQI instructions using constant
819/// folding or conversion to a shuffle vector.
Sanjay Patel6038d3e2016-01-29 23:27:03 +0000820static Value *simplifyX86insertq(IntrinsicInst &II, Value *Op0, Value *Op1,
Simon Pilgrim216b1bf2015-10-17 11:40:05 +0000821 APInt APLength, APInt APIndex,
822 InstCombiner::BuilderTy &Builder) {
Simon Pilgrim216b1bf2015-10-17 11:40:05 +0000823 // From AMD documentation: "The bit index and field length are each six bits
824 // in length other bits of the field are ignored."
825 APIndex = APIndex.zextOrTrunc(6);
826 APLength = APLength.zextOrTrunc(6);
827
828 // Attempt to constant fold.
829 unsigned Index = APIndex.getZExtValue();
830
831 // From AMD documentation: "a value of zero in the field length is
832 // defined as length of 64".
833 unsigned Length = APLength == 0 ? 64 : APLength.getZExtValue();
834
835 // From AMD documentation: "If the sum of the bit index + length field
836 // is greater than 64, the results are undefined".
837 unsigned End = Index + Length;
838
839 // Note that both field index and field length are 8-bit quantities.
840 // Since variables 'Index' and 'Length' are unsigned values
841 // obtained from zero-extending field index and field length
842 // respectively, their sum should never wrap around.
843 if (End > 64)
844 return UndefValue::get(II.getType());
845
846 // If we are inserting whole bytes, we can convert this to a shuffle.
847 // Lowering can recognize INSERTQI shuffle masks.
848 if ((Length % 8) == 0 && (Index % 8) == 0) {
849 // Convert bit indices to byte indices.
850 Length /= 8;
851 Index /= 8;
852
853 Type *IntTy8 = Type::getInt8Ty(II.getContext());
854 Type *IntTy32 = Type::getInt32Ty(II.getContext());
855 VectorType *ShufTy = VectorType::get(IntTy8, 16);
856
857 SmallVector<Constant *, 16> ShuffleMask;
858 for (int i = 0; i != (int)Index; ++i)
859 ShuffleMask.push_back(Constant::getIntegerValue(IntTy32, APInt(32, i)));
860 for (int i = 0; i != (int)Length; ++i)
861 ShuffleMask.push_back(
862 Constant::getIntegerValue(IntTy32, APInt(32, i + 16)));
863 for (int i = Index + Length; i != 8; ++i)
864 ShuffleMask.push_back(Constant::getIntegerValue(IntTy32, APInt(32, i)));
865 for (int i = 8; i != 16; ++i)
866 ShuffleMask.push_back(UndefValue::get(IntTy32));
867
868 Value *SV = Builder.CreateShuffleVector(Builder.CreateBitCast(Op0, ShufTy),
869 Builder.CreateBitCast(Op1, ShufTy),
870 ConstantVector::get(ShuffleMask));
871 return Builder.CreateBitCast(SV, II.getType());
872 }
873
874 // See if we're dealing with constant values.
875 Constant *C0 = dyn_cast<Constant>(Op0);
876 Constant *C1 = dyn_cast<Constant>(Op1);
877 ConstantInt *CI00 =
Andrea Di Biagiof3fd3162016-09-07 12:47:53 +0000878 C0 ? dyn_cast_or_null<ConstantInt>(C0->getAggregateElement((unsigned)0))
Simon Pilgrim216b1bf2015-10-17 11:40:05 +0000879 : nullptr;
880 ConstantInt *CI10 =
Andrea Di Biagiof3fd3162016-09-07 12:47:53 +0000881 C1 ? dyn_cast_or_null<ConstantInt>(C1->getAggregateElement((unsigned)0))
Simon Pilgrim216b1bf2015-10-17 11:40:05 +0000882 : nullptr;
883
884 // Constant Fold - insert bottom Length bits starting at the Index'th bit.
885 if (CI00 && CI10) {
886 APInt V00 = CI00->getValue();
887 APInt V10 = CI10->getValue();
888 APInt Mask = APInt::getLowBitsSet(64, Length).shl(Index);
889 V00 = V00 & ~Mask;
890 V10 = V10.zextOrTrunc(Length).zextOrTrunc(64).shl(Index);
891 APInt Val = V00 | V10;
892 Type *IntTy64 = Type::getInt64Ty(II.getContext());
893 Constant *Args[] = {ConstantInt::get(IntTy64, Val.getZExtValue()),
894 UndefValue::get(IntTy64)};
895 return ConstantVector::get(Args);
896 }
897
898 // If we were an INSERTQ call, we'll save demanded elements if we convert to
899 // INSERTQI.
900 if (II.getIntrinsicID() == Intrinsic::x86_sse4a_insertq) {
901 Type *IntTy8 = Type::getInt8Ty(II.getContext());
902 Constant *CILength = ConstantInt::get(IntTy8, Length, false);
903 Constant *CIIndex = ConstantInt::get(IntTy8, Index, false);
904
905 Value *Args[] = {Op0, Op1, CILength, CIIndex};
Sanjay Patelaf674fb2015-12-14 17:24:23 +0000906 Module *M = II.getModule();
James Y Knight7976eb52019-02-01 20:43:25 +0000907 Function *F = Intrinsic::getDeclaration(M, Intrinsic::x86_sse4a_insertqi);
Simon Pilgrim216b1bf2015-10-17 11:40:05 +0000908 return Builder.CreateCall(F, Args);
909 }
910
911 return nullptr;
912}
913
Simon Pilgrimc0c56e72016-04-24 17:00:34 +0000914/// Attempt to convert pshufb* to shufflevector if the mask is constant.
915static Value *simplifyX86pshufb(const IntrinsicInst &II,
916 InstCombiner::BuilderTy &Builder) {
Simon Pilgrimbf60cc42016-04-29 21:34:54 +0000917 Constant *V = dyn_cast<Constant>(II.getArgOperand(1));
918 if (!V)
919 return nullptr;
920
Simon Pilgrime5e8c2f2016-05-01 19:26:21 +0000921 auto *VecTy = cast<VectorType>(II.getType());
922 auto *MaskEltTy = Type::getInt32Ty(II.getContext());
923 unsigned NumElts = VecTy->getNumElements();
Craig Topper9a63d7a2016-12-11 00:23:50 +0000924 assert((NumElts == 16 || NumElts == 32 || NumElts == 64) &&
Simon Pilgrimc0c56e72016-04-24 17:00:34 +0000925 "Unexpected number of elements in shuffle mask!");
Simon Pilgrimbf60cc42016-04-29 21:34:54 +0000926
Simon Pilgrime5e8c2f2016-05-01 19:26:21 +0000927 // Construct a shuffle mask from constant integers or UNDEFs.
Craig Topper9a63d7a2016-12-11 00:23:50 +0000928 Constant *Indexes[64] = {nullptr};
Simon Pilgrimc0c56e72016-04-24 17:00:34 +0000929
Simon Pilgrimbf60cc42016-04-29 21:34:54 +0000930 // Each byte in the shuffle control mask forms an index to permute the
931 // corresponding byte in the destination operand.
932 for (unsigned I = 0; I < NumElts; ++I) {
933 Constant *COp = V->getAggregateElement(I);
Simon Pilgrime5e8c2f2016-05-01 19:26:21 +0000934 if (!COp || (!isa<UndefValue>(COp) && !isa<ConstantInt>(COp)))
Simon Pilgrimbf60cc42016-04-29 21:34:54 +0000935 return nullptr;
Simon Pilgrimc0c56e72016-04-24 17:00:34 +0000936
Simon Pilgrime5e8c2f2016-05-01 19:26:21 +0000937 if (isa<UndefValue>(COp)) {
938 Indexes[I] = UndefValue::get(MaskEltTy);
939 continue;
940 }
941
Simon Pilgrimbf60cc42016-04-29 21:34:54 +0000942 int8_t Index = cast<ConstantInt>(COp)->getValue().getZExtValue();
943
944 // If the most significant bit (bit[7]) of each byte of the shuffle
945 // control mask is set, then zero is written in the result byte.
946 // The zero vector is in the right-hand side of the resulting
947 // shufflevector.
948
Simon Pilgrime5e8c2f2016-05-01 19:26:21 +0000949 // The value of each index for the high 128-bit lane is the least
950 // significant 4 bits of the respective shuffle control byte.
951 Index = ((Index < 0) ? NumElts : Index & 0x0F) + (I & 0xF0);
952 Indexes[I] = ConstantInt::get(MaskEltTy, Index);
Simon Pilgrimbf60cc42016-04-29 21:34:54 +0000953 }
Simon Pilgrimc0c56e72016-04-24 17:00:34 +0000954
Simon Pilgrime5e8c2f2016-05-01 19:26:21 +0000955 auto ShuffleMask = ConstantVector::get(makeArrayRef(Indexes, NumElts));
Simon Pilgrimc0c56e72016-04-24 17:00:34 +0000956 auto V1 = II.getArgOperand(0);
Simon Pilgrime5e8c2f2016-05-01 19:26:21 +0000957 auto V2 = Constant::getNullValue(VecTy);
Simon Pilgrimc0c56e72016-04-24 17:00:34 +0000958 return Builder.CreateShuffleVector(V1, V2, ShuffleMask);
959}
960
Simon Pilgrim2f6097d2016-04-24 17:23:46 +0000961/// Attempt to convert vpermilvar* to shufflevector if the mask is constant.
962static Value *simplifyX86vpermilvar(const IntrinsicInst &II,
963 InstCombiner::BuilderTy &Builder) {
Simon Pilgrim640f9962016-04-30 07:23:30 +0000964 Constant *V = dyn_cast<Constant>(II.getArgOperand(1));
965 if (!V)
966 return nullptr;
Simon Pilgrim2f6097d2016-04-24 17:23:46 +0000967
Craig Topper58917f32016-12-11 01:59:36 +0000968 auto *VecTy = cast<VectorType>(II.getType());
Simon Pilgrimeeacc402016-05-01 20:22:42 +0000969 auto *MaskEltTy = Type::getInt32Ty(II.getContext());
Craig Topper58917f32016-12-11 01:59:36 +0000970 unsigned NumElts = VecTy->getVectorNumElements();
971 bool IsPD = VecTy->getScalarType()->isDoubleTy();
972 unsigned NumLaneElts = IsPD ? 2 : 4;
973 assert(NumElts == 16 || NumElts == 8 || NumElts == 4 || NumElts == 2);
Simon Pilgrim2f6097d2016-04-24 17:23:46 +0000974
Simon Pilgrimeeacc402016-05-01 20:22:42 +0000975 // Construct a shuffle mask from constant integers or UNDEFs.
Craig Topper58917f32016-12-11 01:59:36 +0000976 Constant *Indexes[16] = {nullptr};
Simon Pilgrim640f9962016-04-30 07:23:30 +0000977
978 // The intrinsics only read one or two bits, clear the rest.
Simon Pilgrimeeacc402016-05-01 20:22:42 +0000979 for (unsigned I = 0; I < NumElts; ++I) {
Simon Pilgrim640f9962016-04-30 07:23:30 +0000980 Constant *COp = V->getAggregateElement(I);
Simon Pilgrimeeacc402016-05-01 20:22:42 +0000981 if (!COp || (!isa<UndefValue>(COp) && !isa<ConstantInt>(COp)))
Simon Pilgrim640f9962016-04-30 07:23:30 +0000982 return nullptr;
983
Simon Pilgrimeeacc402016-05-01 20:22:42 +0000984 if (isa<UndefValue>(COp)) {
985 Indexes[I] = UndefValue::get(MaskEltTy);
986 continue;
987 }
988
989 APInt Index = cast<ConstantInt>(COp)->getValue();
990 Index = Index.zextOrTrunc(32).getLoBits(2);
Simon Pilgrim640f9962016-04-30 07:23:30 +0000991
992 // The PD variants uses bit 1 to select per-lane element index, so
993 // shift down to convert to generic shuffle mask index.
Craig Topper58917f32016-12-11 01:59:36 +0000994 if (IsPD)
Craig Topperfc947bc2017-04-18 17:14:21 +0000995 Index.lshrInPlace(1);
Simon Pilgrimeeacc402016-05-01 20:22:42 +0000996
997 // The _256 variants are a bit trickier since the mask bits always index
998 // into the corresponding 128 half. In order to convert to a generic
999 // shuffle, we have to make that explicit.
Craig Topper58917f32016-12-11 01:59:36 +00001000 Index += APInt(32, (I / NumLaneElts) * NumLaneElts);
Simon Pilgrimeeacc402016-05-01 20:22:42 +00001001
1002 Indexes[I] = ConstantInt::get(MaskEltTy, Index);
Simon Pilgrim2f6097d2016-04-24 17:23:46 +00001003 }
1004
Simon Pilgrimeeacc402016-05-01 20:22:42 +00001005 auto ShuffleMask = ConstantVector::get(makeArrayRef(Indexes, NumElts));
Simon Pilgrim2f6097d2016-04-24 17:23:46 +00001006 auto V1 = II.getArgOperand(0);
1007 auto V2 = UndefValue::get(V1->getType());
1008 return Builder.CreateShuffleVector(V1, V2, ShuffleMask);
1009}
1010
Simon Pilgrim8cddf8b2016-05-01 16:41:22 +00001011/// Attempt to convert vpermd/vpermps to shufflevector if the mask is constant.
1012static Value *simplifyX86vpermv(const IntrinsicInst &II,
1013 InstCombiner::BuilderTy &Builder) {
1014 auto *V = dyn_cast<Constant>(II.getArgOperand(1));
1015 if (!V)
1016 return nullptr;
1017
Simon Pilgrimca140b12016-05-01 20:43:02 +00001018 auto *VecTy = cast<VectorType>(II.getType());
1019 auto *MaskEltTy = Type::getInt32Ty(II.getContext());
Simon Pilgrim8cddf8b2016-05-01 16:41:22 +00001020 unsigned Size = VecTy->getNumElements();
Craig Toppere3280452016-12-25 23:58:57 +00001021 assert((Size == 4 || Size == 8 || Size == 16 || Size == 32 || Size == 64) &&
1022 "Unexpected shuffle mask size");
Simon Pilgrim8cddf8b2016-05-01 16:41:22 +00001023
Simon Pilgrimca140b12016-05-01 20:43:02 +00001024 // Construct a shuffle mask from constant integers or UNDEFs.
Craig Toppere3280452016-12-25 23:58:57 +00001025 Constant *Indexes[64] = {nullptr};
Simon Pilgrim8cddf8b2016-05-01 16:41:22 +00001026
1027 for (unsigned I = 0; I < Size; ++I) {
1028 Constant *COp = V->getAggregateElement(I);
Simon Pilgrimca140b12016-05-01 20:43:02 +00001029 if (!COp || (!isa<UndefValue>(COp) && !isa<ConstantInt>(COp)))
Simon Pilgrim8cddf8b2016-05-01 16:41:22 +00001030 return nullptr;
1031
Simon Pilgrimca140b12016-05-01 20:43:02 +00001032 if (isa<UndefValue>(COp)) {
1033 Indexes[I] = UndefValue::get(MaskEltTy);
1034 continue;
1035 }
1036
Craig Toppere3280452016-12-25 23:58:57 +00001037 uint32_t Index = cast<ConstantInt>(COp)->getZExtValue();
1038 Index &= Size - 1;
Simon Pilgrimca140b12016-05-01 20:43:02 +00001039 Indexes[I] = ConstantInt::get(MaskEltTy, Index);
Simon Pilgrim8cddf8b2016-05-01 16:41:22 +00001040 }
1041
Simon Pilgrimca140b12016-05-01 20:43:02 +00001042 auto ShuffleMask = ConstantVector::get(makeArrayRef(Indexes, Size));
Simon Pilgrim8cddf8b2016-05-01 16:41:22 +00001043 auto V1 = II.getArgOperand(0);
1044 auto V2 = UndefValue::get(VecTy);
1045 return Builder.CreateShuffleVector(V1, V2, ShuffleMask);
1046}
1047
Philip Reames484d07c2019-03-20 03:36:05 +00001048// TODO, Obvious Missing Transforms:
Philip Reames484d07c2019-03-20 03:36:05 +00001049// * Narrow width by halfs excluding zero/undef lanes
Philip Reames7c8647b2019-04-25 01:18:56 +00001050Value *InstCombiner::simplifyMaskedLoad(IntrinsicInst &II) {
Philip Reames2ce01702019-04-23 15:25:14 +00001051 Value *LoadPtr = II.getArgOperand(0);
1052 unsigned Alignment = cast<ConstantInt>(II.getArgOperand(1))->getZExtValue();
1053
David Majnemer666aa942016-07-14 06:58:42 +00001054 // If the mask is all ones or undefs, this is a plain vector load of the 1st
1055 // argument.
Philip Reames2ce01702019-04-23 15:25:14 +00001056 if (maskIsAllOneOrUndef(II.getArgOperand(2)))
James Y Knight14359ef2019-02-01 20:44:24 +00001057 return Builder.CreateAlignedLoad(II.getType(), LoadPtr, Alignment,
1058 "unmaskedload");
Philip Reames2ce01702019-04-23 15:25:14 +00001059
1060 // If we can unconditionally load from this address, replace with a
1061 // load/select idiom. TODO: use DT for context sensitive query
Guillaume Chatelet301b4122019-10-21 15:10:26 +00001062 if (isDereferenceableAndAlignedPointer(
1063 LoadPtr, II.getType(), MaybeAlign(Alignment),
1064 II.getModule()->getDataLayout(), &II, nullptr)) {
Philip Reames2ce01702019-04-23 15:25:14 +00001065 Value *LI = Builder.CreateAlignedLoad(II.getType(), LoadPtr, Alignment,
1066 "unmaskedload");
1067 return Builder.CreateSelect(II.getArgOperand(2), LI, II.getArgOperand(3));
Sanjay Patelb695c552016-02-01 17:00:10 +00001068 }
1069
1070 return nullptr;
1071}
1072
Philip Reames484d07c2019-03-20 03:36:05 +00001073// TODO, Obvious Missing Transforms:
Philip Reames484d07c2019-03-20 03:36:05 +00001074// * Single constant active lane -> store
1075// * Narrow width by halfs excluding zero/undef lanes
Philip Reamese4588bb2019-03-20 18:44:58 +00001076Instruction *InstCombiner::simplifyMaskedStore(IntrinsicInst &II) {
Sanjay Patel04f792b2016-02-01 19:39:52 +00001077 auto *ConstMask = dyn_cast<Constant>(II.getArgOperand(3));
1078 if (!ConstMask)
1079 return nullptr;
1080
1081 // If the mask is all zeros, this instruction does nothing.
1082 if (ConstMask->isNullValue())
Philip Reamese4588bb2019-03-20 18:44:58 +00001083 return eraseInstFromFunction(II);
Sanjay Patel04f792b2016-02-01 19:39:52 +00001084
1085 // If the mask is all ones, this is a plain vector store of the 1st argument.
1086 if (ConstMask->isAllOnesValue()) {
1087 Value *StorePtr = II.getArgOperand(1);
1088 unsigned Alignment = cast<ConstantInt>(II.getArgOperand(2))->getZExtValue();
1089 return new StoreInst(II.getArgOperand(0), StorePtr, false, Alignment);
1090 }
1091
Philip Reamese4588bb2019-03-20 18:44:58 +00001092 // Use masked off lanes to simplify operands via SimplifyDemandedVectorElts
1093 APInt DemandedElts = possiblyDemandedEltsInMask(ConstMask);
1094 APInt UndefElts(DemandedElts.getBitWidth(), 0);
1095 if (Value *V = SimplifyDemandedVectorElts(II.getOperand(0),
1096 DemandedElts, UndefElts)) {
1097 II.setOperand(0, V);
1098 return &II;
1099 }
1100
Sanjay Patel04f792b2016-02-01 19:39:52 +00001101 return nullptr;
1102}
1103
Philip Reames484d07c2019-03-20 03:36:05 +00001104// TODO, Obvious Missing Transforms:
1105// * Single constant active lane load -> load
1106// * Dereferenceable address & few lanes -> scalarize speculative load/selects
1107// * Adjacent vector addresses -> masked.load
1108// * Narrow width by halfs excluding zero/undef lanes
Philip Reames60212be2019-03-21 03:23:40 +00001109// * Vector splat address w/known mask -> scalar load
1110// * Vector incrementing address -> vector masked load
Philip Reames7c8647b2019-04-25 01:18:56 +00001111Instruction *InstCombiner::simplifyMaskedGather(IntrinsicInst &II) {
Sanjay Patel103ab7d2016-02-01 22:10:26 +00001112 return nullptr;
1113}
1114
Philip Reames60212be2019-03-21 03:23:40 +00001115// TODO, Obvious Missing Transforms:
1116// * Single constant active lane -> store
1117// * Adjacent vector addresses -> masked.store
1118// * Narrow store width by halfs excluding zero/undef lanes
1119// * Vector splat address w/known mask -> scalar store
1120// * Vector incrementing address -> vector masked store
1121Instruction *InstCombiner::simplifyMaskedScatter(IntrinsicInst &II) {
1122 auto *ConstMask = dyn_cast<Constant>(II.getArgOperand(3));
1123 if (!ConstMask)
1124 return nullptr;
1125
1126 // If the mask is all zeros, a scatter does nothing.
1127 if (ConstMask->isNullValue())
1128 return eraseInstFromFunction(II);
1129
1130 // Use masked off lanes to simplify operands via SimplifyDemandedVectorElts
1131 APInt DemandedElts = possiblyDemandedEltsInMask(ConstMask);
1132 APInt UndefElts(DemandedElts.getBitWidth(), 0);
1133 if (Value *V = SimplifyDemandedVectorElts(II.getOperand(0),
1134 DemandedElts, UndefElts)) {
1135 II.setOperand(0, V);
1136 return &II;
1137 }
1138 if (Value *V = SimplifyDemandedVectorElts(II.getOperand(1),
1139 DemandedElts, UndefElts)) {
1140 II.setOperand(1, V);
1141 return &II;
1142 }
1143
1144 return nullptr;
1145}
1146
Piotr Padlewskic63b4922018-07-12 23:55:20 +00001147/// This function transforms launder.invariant.group and strip.invariant.group
1148/// like:
1149/// launder(launder(%x)) -> launder(%x) (the result is not the argument)
1150/// launder(strip(%x)) -> launder(%x)
1151/// strip(strip(%x)) -> strip(%x) (the result is not the argument)
1152/// strip(launder(%x)) -> strip(%x)
1153/// This is legal because it preserves the most recent information about
1154/// the presence or absence of invariant.group.
1155static Instruction *simplifyInvariantGroupIntrinsic(IntrinsicInst &II,
1156 InstCombiner &IC) {
1157 auto *Arg = II.getArgOperand(0);
1158 auto *StrippedArg = Arg->stripPointerCasts();
1159 auto *StrippedInvariantGroupsArg = Arg->stripPointerCastsAndInvariantGroups();
1160 if (StrippedArg == StrippedInvariantGroupsArg)
1161 return nullptr; // No launders/strips to remove.
1162
1163 Value *Result = nullptr;
1164
1165 if (II.getIntrinsicID() == Intrinsic::launder_invariant_group)
1166 Result = IC.Builder.CreateLaunderInvariantGroup(StrippedInvariantGroupsArg);
1167 else if (II.getIntrinsicID() == Intrinsic::strip_invariant_group)
1168 Result = IC.Builder.CreateStripInvariantGroup(StrippedInvariantGroupsArg);
1169 else
1170 llvm_unreachable(
1171 "simplifyInvariantGroupIntrinsic only handles launder and strip");
1172 if (Result->getType()->getPointerAddressSpace() !=
1173 II.getType()->getPointerAddressSpace())
1174 Result = IC.Builder.CreateAddrSpaceCast(Result, II.getType());
1175 if (Result->getType() != II.getType())
1176 Result = IC.Builder.CreateBitCast(Result, II.getType());
1177
1178 return cast<Instruction>(Result);
1179}
1180
Amaury Sechet763c59d2016-08-18 20:43:50 +00001181static Instruction *foldCttzCtlz(IntrinsicInst &II, InstCombiner &IC) {
1182 assert((II.getIntrinsicID() == Intrinsic::cttz ||
1183 II.getIntrinsicID() == Intrinsic::ctlz) &&
1184 "Expected cttz or ctlz intrinsic");
David Bolvansky5ba60b22019-04-02 20:13:28 +00001185 bool IsTZ = II.getIntrinsicID() == Intrinsic::cttz;
Sanjay Patel8e3ab172016-08-05 22:42:46 +00001186 Value *Op0 = II.getArgOperand(0);
David Bolvansky5ba60b22019-04-02 20:13:28 +00001187 Value *X;
1188 // ctlz(bitreverse(x)) -> cttz(x)
1189 // cttz(bitreverse(x)) -> ctlz(x)
1190 if (match(Op0, m_BitReverse(m_Value(X)))) {
1191 Intrinsic::ID ID = IsTZ ? Intrinsic::ctlz : Intrinsic::cttz;
1192 Function *F = Intrinsic::getDeclaration(II.getModule(), ID, II.getType());
1193 return CallInst::Create(F, {X, II.getArgOperand(1)});
1194 }
Sanjay Patel8e3ab172016-08-05 22:42:46 +00001195
David Bolvansky4b284782019-06-21 15:26:22 +00001196 if (IsTZ) {
1197 // cttz(-x) -> cttz(x)
1198 if (match(Op0, m_Neg(m_Value(X)))) {
1199 II.setOperand(0, X);
1200 return &II;
1201 }
1202
1203 // cttz(abs(x)) -> cttz(x)
1204 // cttz(nabs(x)) -> cttz(x)
1205 Value *Y;
1206 SelectPatternFlavor SPF = matchSelectPattern(Op0, X, Y).Flavor;
1207 if (SPF == SPF_ABS || SPF == SPF_NABS) {
1208 II.setOperand(0, X);
1209 return &II;
1210 }
David Bolvansky01511192019-06-20 17:04:14 +00001211 }
1212
Craig Topper8205a1a2017-05-24 16:53:07 +00001213 KnownBits Known = IC.computeKnownBits(Op0, 0, &II);
Sanjay Patel8e3ab172016-08-05 22:42:46 +00001214
1215 // Create a mask for bits above (ctlz) or below (cttz) the first known one.
Craig Topper8df66c62017-05-12 17:20:30 +00001216 unsigned PossibleZeros = IsTZ ? Known.countMaxTrailingZeros()
1217 : Known.countMaxLeadingZeros();
1218 unsigned DefiniteZeros = IsTZ ? Known.countMinTrailingZeros()
1219 : Known.countMinLeadingZeros();
Sanjay Patel8e3ab172016-08-05 22:42:46 +00001220
1221 // If all bits above (ctlz) or below (cttz) the first known one are known
1222 // zero, this value is constant.
1223 // FIXME: This should be in InstSimplify because we're replacing an
1224 // instruction with a constant.
Craig Topper9474e9b2017-04-27 04:51:25 +00001225 if (PossibleZeros == DefiniteZeros) {
Craig Topper0799ff92017-06-03 18:50:32 +00001226 auto *C = ConstantInt::get(Op0->getType(), DefiniteZeros);
Amaury Sechet763c59d2016-08-18 20:43:50 +00001227 return IC.replaceInstUsesWith(II, C);
1228 }
1229
1230 // If the input to cttz/ctlz is known to be non-zero,
1231 // then change the 'ZeroIsUndef' parameter to 'true'
1232 // because we know the zero behavior can't affect the result.
Craig Topper73ba1c82017-06-07 07:40:37 +00001233 if (!Known.One.isNullValue() ||
Craig Topperd45185f2017-05-26 18:23:57 +00001234 isKnownNonZero(Op0, IC.getDataLayout(), 0, &IC.getAssumptionCache(), &II,
1235 &IC.getDominatorTree())) {
Amaury Sechet763c59d2016-08-18 20:43:50 +00001236 if (!match(II.getArgOperand(1), m_One())) {
Craig Topperbb4069e2017-07-07 23:16:26 +00001237 II.setOperand(1, IC.Builder.getTrue());
Amaury Sechet763c59d2016-08-18 20:43:50 +00001238 return &II;
1239 }
1240 }
Sanjay Patel8e3ab172016-08-05 22:42:46 +00001241
Craig Topper5b173f22017-06-21 16:32:35 +00001242 // Add range metadata since known bits can't completely reflect what we know.
1243 // TODO: Handle splat vectors.
1244 auto *IT = dyn_cast<IntegerType>(Op0->getType());
1245 if (IT && IT->getBitWidth() != 1 && !II.getMetadata(LLVMContext::MD_range)) {
1246 Metadata *LowAndHigh[] = {
1247 ConstantAsMetadata::get(ConstantInt::get(IT, DefiniteZeros)),
1248 ConstantAsMetadata::get(ConstantInt::get(IT, PossibleZeros + 1))};
1249 II.setMetadata(LLVMContext::MD_range,
1250 MDNode::get(II.getContext(), LowAndHigh));
1251 return &II;
1252 }
1253
1254 return nullptr;
1255}
1256
1257static Instruction *foldCtpop(IntrinsicInst &II, InstCombiner &IC) {
1258 assert(II.getIntrinsicID() == Intrinsic::ctpop &&
1259 "Expected ctpop intrinsic");
1260 Value *Op0 = II.getArgOperand(0);
David Bolvansky937720e2019-04-03 08:08:44 +00001261 Value *X;
1262 // ctpop(bitreverse(x)) -> ctpop(x)
1263 // ctpop(bswap(x)) -> ctpop(x)
1264 if (match(Op0, m_BitReverse(m_Value(X))) || match(Op0, m_BSwap(m_Value(X)))) {
1265 II.setOperand(0, X);
1266 return &II;
1267 }
1268
Craig Topper5b173f22017-06-21 16:32:35 +00001269 // FIXME: Try to simplify vectors of integers.
1270 auto *IT = dyn_cast<IntegerType>(Op0->getType());
1271 if (!IT)
1272 return nullptr;
1273
1274 unsigned BitWidth = IT->getBitWidth();
1275 KnownBits Known(BitWidth);
1276 IC.computeKnownBits(Op0, Known, 0, &II);
1277
1278 unsigned MinCount = Known.countMinPopulation();
1279 unsigned MaxCount = Known.countMaxPopulation();
1280
1281 // Add range metadata since known bits can't completely reflect what we know.
1282 if (IT->getBitWidth() != 1 && !II.getMetadata(LLVMContext::MD_range)) {
1283 Metadata *LowAndHigh[] = {
1284 ConstantAsMetadata::get(ConstantInt::get(IT, MinCount)),
1285 ConstantAsMetadata::get(ConstantInt::get(IT, MaxCount + 1))};
1286 II.setMetadata(LLVMContext::MD_range,
1287 MDNode::get(II.getContext(), LowAndHigh));
1288 return &II;
1289 }
1290
Sanjay Patel8e3ab172016-08-05 22:42:46 +00001291 return nullptr;
1292}
1293
Sanjay Patel1ace9932016-02-26 21:04:14 +00001294// TODO: If the x86 backend knew how to convert a bool vector mask back to an
1295// XMM register mask efficiently, we could transform all x86 masked intrinsics
1296// to LLVM masked intrinsics and remove the x86 masked intrinsic defs.
Sanjay Patel98a71502016-02-29 23:16:48 +00001297static Instruction *simplifyX86MaskedLoad(IntrinsicInst &II, InstCombiner &IC) {
1298 Value *Ptr = II.getOperand(0);
1299 Value *Mask = II.getOperand(1);
Sanjay Patel5e5056d2016-04-12 23:16:23 +00001300 Constant *ZeroVec = Constant::getNullValue(II.getType());
Sanjay Patel98a71502016-02-29 23:16:48 +00001301
1302 // Special case a zero mask since that's not a ConstantDataVector.
Sanjay Patel5e5056d2016-04-12 23:16:23 +00001303 // This masked load instruction creates a zero vector.
Sanjay Patel98a71502016-02-29 23:16:48 +00001304 if (isa<ConstantAggregateZero>(Mask))
Sanjay Patel5e5056d2016-04-12 23:16:23 +00001305 return IC.replaceInstUsesWith(II, ZeroVec);
Sanjay Patel98a71502016-02-29 23:16:48 +00001306
1307 auto *ConstMask = dyn_cast<ConstantDataVector>(Mask);
1308 if (!ConstMask)
1309 return nullptr;
1310
1311 // The mask is constant. Convert this x86 intrinsic to the LLVM instrinsic
1312 // to allow target-independent optimizations.
1313
1314 // First, cast the x86 intrinsic scalar pointer to a vector pointer to match
1315 // the LLVM intrinsic definition for the pointer argument.
1316 unsigned AddrSpace = cast<PointerType>(Ptr->getType())->getAddressSpace();
1317 PointerType *VecPtrTy = PointerType::get(II.getType(), AddrSpace);
Craig Topperbb4069e2017-07-07 23:16:26 +00001318 Value *PtrCast = IC.Builder.CreateBitCast(Ptr, VecPtrTy, "castvec");
Sanjay Patel98a71502016-02-29 23:16:48 +00001319
1320 // Second, convert the x86 XMM integer vector mask to a vector of bools based
1321 // on each element's most significant bit (the sign bit).
1322 Constant *BoolMask = getNegativeIsTrueBoolVec(ConstMask);
1323
Sanjay Patel5e5056d2016-04-12 23:16:23 +00001324 // The pass-through vector for an x86 masked load is a zero vector.
1325 CallInst *NewMaskedLoad =
Craig Topperbb4069e2017-07-07 23:16:26 +00001326 IC.Builder.CreateMaskedLoad(PtrCast, 1, BoolMask, ZeroVec);
Sanjay Patel98a71502016-02-29 23:16:48 +00001327 return IC.replaceInstUsesWith(II, NewMaskedLoad);
1328}
1329
1330// TODO: If the x86 backend knew how to convert a bool vector mask back to an
1331// XMM register mask efficiently, we could transform all x86 masked intrinsics
1332// to LLVM masked intrinsics and remove the x86 masked intrinsic defs.
Sanjay Patel1ace9932016-02-26 21:04:14 +00001333static bool simplifyX86MaskedStore(IntrinsicInst &II, InstCombiner &IC) {
1334 Value *Ptr = II.getOperand(0);
1335 Value *Mask = II.getOperand(1);
1336 Value *Vec = II.getOperand(2);
1337
1338 // Special case a zero mask since that's not a ConstantDataVector:
1339 // this masked store instruction does nothing.
1340 if (isa<ConstantAggregateZero>(Mask)) {
1341 IC.eraseInstFromFunction(II);
1342 return true;
1343 }
1344
Sanjay Patelc4acbae2016-03-12 15:16:59 +00001345 // The SSE2 version is too weird (eg, unaligned but non-temporal) to do
1346 // anything else at this level.
1347 if (II.getIntrinsicID() == Intrinsic::x86_sse2_maskmov_dqu)
1348 return false;
1349
Sanjay Patel1ace9932016-02-26 21:04:14 +00001350 auto *ConstMask = dyn_cast<ConstantDataVector>(Mask);
1351 if (!ConstMask)
1352 return false;
1353
1354 // The mask is constant. Convert this x86 intrinsic to the LLVM instrinsic
1355 // to allow target-independent optimizations.
1356
1357 // First, cast the x86 intrinsic scalar pointer to a vector pointer to match
1358 // the LLVM intrinsic definition for the pointer argument.
1359 unsigned AddrSpace = cast<PointerType>(Ptr->getType())->getAddressSpace();
1360 PointerType *VecPtrTy = PointerType::get(Vec->getType(), AddrSpace);
Craig Topperbb4069e2017-07-07 23:16:26 +00001361 Value *PtrCast = IC.Builder.CreateBitCast(Ptr, VecPtrTy, "castvec");
Sanjay Patel1ace9932016-02-26 21:04:14 +00001362
1363 // Second, convert the x86 XMM integer vector mask to a vector of bools based
1364 // on each element's most significant bit (the sign bit).
1365 Constant *BoolMask = getNegativeIsTrueBoolVec(ConstMask);
1366
Craig Topperbb4069e2017-07-07 23:16:26 +00001367 IC.Builder.CreateMaskedStore(Vec, PtrCast, 1, BoolMask);
Sanjay Patel1ace9932016-02-26 21:04:14 +00001368
1369 // 'Replace uses' doesn't work for stores. Erase the original masked store.
1370 IC.eraseInstFromFunction(II);
1371 return true;
1372}
1373
Matt Arsenaultcdb468c2017-02-27 23:08:49 +00001374// Constant fold llvm.amdgcn.fmed3 intrinsics for standard inputs.
1375//
1376// A single NaN input is folded to minnum, so we rely on that folding for
1377// handling NaNs.
1378static APFloat fmed3AMDGCN(const APFloat &Src0, const APFloat &Src1,
1379 const APFloat &Src2) {
1380 APFloat Max3 = maxnum(maxnum(Src0, Src1), Src2);
1381
1382 APFloat::cmpResult Cmp0 = Max3.compare(Src0);
1383 assert(Cmp0 != APFloat::cmpUnordered && "nans handled separately");
1384 if (Cmp0 == APFloat::cmpEqual)
1385 return maxnum(Src1, Src2);
1386
1387 APFloat::cmpResult Cmp1 = Max3.compare(Src1);
1388 assert(Cmp1 != APFloat::cmpUnordered && "nans handled separately");
1389 if (Cmp1 == APFloat::cmpEqual)
1390 return maxnum(Src0, Src2);
1391
1392 return maxnum(Src0, Src1);
1393}
1394
Alexandros Lamprineas52457d32018-05-30 14:38:50 +00001395/// Convert a table lookup to shufflevector if the mask is constant.
1396/// This could benefit tbl1 if the mask is { 7,6,5,4,3,2,1,0 }, in
1397/// which case we could lower the shufflevector with rev64 instructions
1398/// as it's actually a byte reverse.
1399static Value *simplifyNeonTbl1(const IntrinsicInst &II,
1400 InstCombiner::BuilderTy &Builder) {
1401 // Bail out if the mask is not a constant.
1402 auto *C = dyn_cast<Constant>(II.getArgOperand(1));
1403 if (!C)
1404 return nullptr;
1405
1406 auto *VecTy = cast<VectorType>(II.getType());
1407 unsigned NumElts = VecTy->getNumElements();
1408
1409 // Only perform this transformation for <8 x i8> vector types.
1410 if (!VecTy->getElementType()->isIntegerTy(8) || NumElts != 8)
1411 return nullptr;
1412
1413 uint32_t Indexes[8];
1414
1415 for (unsigned I = 0; I < NumElts; ++I) {
1416 Constant *COp = C->getAggregateElement(I);
1417
1418 if (!COp || !isa<ConstantInt>(COp))
1419 return nullptr;
1420
1421 Indexes[I] = cast<ConstantInt>(COp)->getLimitedValue();
1422
1423 // Make sure the mask indices are in range.
1424 if (Indexes[I] >= NumElts)
1425 return nullptr;
1426 }
1427
1428 auto *ShuffleMask = ConstantDataVector::get(II.getContext(),
1429 makeArrayRef(Indexes));
1430 auto *V1 = II.getArgOperand(0);
1431 auto *V2 = Constant::getNullValue(V1->getType());
1432 return Builder.CreateShuffleVector(V1, V2, ShuffleMask);
1433}
1434
Alexandros Lamprineas61f0ba12018-05-31 12:19:18 +00001435/// Convert a vector load intrinsic into a simple llvm load instruction.
1436/// This is beneficial when the underlying object being addressed comes
1437/// from a constant, since we get constant-folding for free.
1438static Value *simplifyNeonVld1(const IntrinsicInst &II,
1439 unsigned MemAlign,
1440 InstCombiner::BuilderTy &Builder) {
1441 auto *IntrAlign = dyn_cast<ConstantInt>(II.getArgOperand(1));
1442
1443 if (!IntrAlign)
1444 return nullptr;
1445
1446 unsigned Alignment = IntrAlign->getLimitedValue() < MemAlign ?
1447 MemAlign : IntrAlign->getLimitedValue();
1448
1449 if (!isPowerOf2_32(Alignment))
1450 return nullptr;
1451
1452 auto *BCastInst = Builder.CreateBitCast(II.getArgOperand(0),
1453 PointerType::get(II.getType(), 0));
James Y Knight14359ef2019-02-01 20:44:24 +00001454 return Builder.CreateAlignedLoad(II.getType(), BCastInst, Alignment);
Alexandros Lamprineas61f0ba12018-05-31 12:19:18 +00001455}
1456
Arnaud A. de Grandmaison333ef382016-05-10 09:24:49 +00001457// Returns true iff the 2 intrinsics have the same operands, limiting the
1458// comparison to the first NumOperands.
1459static bool haveSameOperands(const IntrinsicInst &I, const IntrinsicInst &E,
1460 unsigned NumOperands) {
1461 assert(I.getNumArgOperands() >= NumOperands && "Not enough operands");
1462 assert(E.getNumArgOperands() >= NumOperands && "Not enough operands");
1463 for (unsigned i = 0; i < NumOperands; i++)
1464 if (I.getArgOperand(i) != E.getArgOperand(i))
1465 return false;
1466 return true;
1467}
1468
1469// Remove trivially empty start/end intrinsic ranges, i.e. a start
1470// immediately followed by an end (ignoring debuginfo or other
1471// start/end intrinsics in between). As this handles only the most trivial
1472// cases, tracking the nesting level is not needed:
1473//
1474// call @llvm.foo.start(i1 0) ; &I
1475// call @llvm.foo.start(i1 0)
1476// call @llvm.foo.end(i1 0) ; This one will not be skipped: it will be removed
1477// call @llvm.foo.end(i1 0)
1478static bool removeTriviallyEmptyRange(IntrinsicInst &I, unsigned StartID,
1479 unsigned EndID, InstCombiner &IC) {
1480 assert(I.getIntrinsicID() == StartID &&
1481 "Start intrinsic does not have expected ID");
1482 BasicBlock::iterator BI(I), BE(I.getParent()->end());
1483 for (++BI; BI != BE; ++BI) {
1484 if (auto *E = dyn_cast<IntrinsicInst>(BI)) {
1485 if (isa<DbgInfoIntrinsic>(E) || E->getIntrinsicID() == StartID)
1486 continue;
1487 if (E->getIntrinsicID() == EndID &&
1488 haveSameOperands(I, *E, E->getNumArgOperands())) {
1489 IC.eraseInstFromFunction(*E);
1490 IC.eraseInstFromFunction(I);
1491 return true;
1492 }
1493 }
1494 break;
1495 }
1496
1497 return false;
1498}
1499
Justin Lebar698c31b2017-01-27 00:58:58 +00001500// Convert NVVM intrinsics to target-generic LLVM code where possible.
1501static Instruction *SimplifyNVVMIntrinsic(IntrinsicInst *II, InstCombiner &IC) {
1502 // Each NVVM intrinsic we can simplify can be replaced with one of:
1503 //
1504 // * an LLVM intrinsic,
1505 // * an LLVM cast operation,
1506 // * an LLVM binary operation, or
1507 // * ad-hoc LLVM IR for the particular operation.
1508
1509 // Some transformations are only valid when the module's
1510 // flush-denormals-to-zero (ftz) setting is true/false, whereas other
1511 // transformations are valid regardless of the module's ftz setting.
1512 enum FtzRequirementTy {
1513 FTZ_Any, // Any ftz setting is ok.
1514 FTZ_MustBeOn, // Transformation is valid only if ftz is on.
1515 FTZ_MustBeOff, // Transformation is valid only if ftz is off.
1516 };
1517 // Classes of NVVM intrinsics that can't be replaced one-to-one with a
1518 // target-generic intrinsic, cast op, or binary op but that we can nonetheless
1519 // simplify.
1520 enum SpecialCase {
1521 SPC_Reciprocal,
1522 };
1523
1524 // SimplifyAction is a poor-man's variant (plus an additional flag) that
1525 // represents how to replace an NVVM intrinsic with target-generic LLVM IR.
1526 struct SimplifyAction {
1527 // Invariant: At most one of these Optionals has a value.
1528 Optional<Intrinsic::ID> IID;
1529 Optional<Instruction::CastOps> CastOp;
1530 Optional<Instruction::BinaryOps> BinaryOp;
1531 Optional<SpecialCase> Special;
1532
1533 FtzRequirementTy FtzRequirement = FTZ_Any;
1534
1535 SimplifyAction() = default;
1536
1537 SimplifyAction(Intrinsic::ID IID, FtzRequirementTy FtzReq)
1538 : IID(IID), FtzRequirement(FtzReq) {}
1539
1540 // Cast operations don't have anything to do with FTZ, so we skip that
1541 // argument.
1542 SimplifyAction(Instruction::CastOps CastOp) : CastOp(CastOp) {}
1543
1544 SimplifyAction(Instruction::BinaryOps BinaryOp, FtzRequirementTy FtzReq)
1545 : BinaryOp(BinaryOp), FtzRequirement(FtzReq) {}
1546
1547 SimplifyAction(SpecialCase Special, FtzRequirementTy FtzReq)
1548 : Special(Special), FtzRequirement(FtzReq) {}
1549 };
1550
1551 // Try to generate a SimplifyAction describing how to replace our
1552 // IntrinsicInstr with target-generic LLVM IR.
1553 const SimplifyAction Action = [II]() -> SimplifyAction {
1554 switch (II->getIntrinsicID()) {
Justin Lebar698c31b2017-01-27 00:58:58 +00001555 // NVVM intrinsics that map directly to LLVM intrinsics.
1556 case Intrinsic::nvvm_ceil_d:
1557 return {Intrinsic::ceil, FTZ_Any};
1558 case Intrinsic::nvvm_ceil_f:
1559 return {Intrinsic::ceil, FTZ_MustBeOff};
1560 case Intrinsic::nvvm_ceil_ftz_f:
1561 return {Intrinsic::ceil, FTZ_MustBeOn};
1562 case Intrinsic::nvvm_fabs_d:
1563 return {Intrinsic::fabs, FTZ_Any};
1564 case Intrinsic::nvvm_fabs_f:
1565 return {Intrinsic::fabs, FTZ_MustBeOff};
1566 case Intrinsic::nvvm_fabs_ftz_f:
1567 return {Intrinsic::fabs, FTZ_MustBeOn};
1568 case Intrinsic::nvvm_floor_d:
1569 return {Intrinsic::floor, FTZ_Any};
1570 case Intrinsic::nvvm_floor_f:
1571 return {Intrinsic::floor, FTZ_MustBeOff};
1572 case Intrinsic::nvvm_floor_ftz_f:
1573 return {Intrinsic::floor, FTZ_MustBeOn};
1574 case Intrinsic::nvvm_fma_rn_d:
1575 return {Intrinsic::fma, FTZ_Any};
1576 case Intrinsic::nvvm_fma_rn_f:
1577 return {Intrinsic::fma, FTZ_MustBeOff};
1578 case Intrinsic::nvvm_fma_rn_ftz_f:
1579 return {Intrinsic::fma, FTZ_MustBeOn};
1580 case Intrinsic::nvvm_fmax_d:
1581 return {Intrinsic::maxnum, FTZ_Any};
1582 case Intrinsic::nvvm_fmax_f:
1583 return {Intrinsic::maxnum, FTZ_MustBeOff};
1584 case Intrinsic::nvvm_fmax_ftz_f:
1585 return {Intrinsic::maxnum, FTZ_MustBeOn};
1586 case Intrinsic::nvvm_fmin_d:
1587 return {Intrinsic::minnum, FTZ_Any};
1588 case Intrinsic::nvvm_fmin_f:
1589 return {Intrinsic::minnum, FTZ_MustBeOff};
1590 case Intrinsic::nvvm_fmin_ftz_f:
1591 return {Intrinsic::minnum, FTZ_MustBeOn};
1592 case Intrinsic::nvvm_round_d:
1593 return {Intrinsic::round, FTZ_Any};
1594 case Intrinsic::nvvm_round_f:
1595 return {Intrinsic::round, FTZ_MustBeOff};
1596 case Intrinsic::nvvm_round_ftz_f:
1597 return {Intrinsic::round, FTZ_MustBeOn};
1598 case Intrinsic::nvvm_sqrt_rn_d:
1599 return {Intrinsic::sqrt, FTZ_Any};
1600 case Intrinsic::nvvm_sqrt_f:
1601 // nvvm_sqrt_f is a special case. For most intrinsics, foo_ftz_f is the
1602 // ftz version, and foo_f is the non-ftz version. But nvvm_sqrt_f adopts
1603 // the ftz-ness of the surrounding code. sqrt_rn_f and sqrt_rn_ftz_f are
1604 // the versions with explicit ftz-ness.
1605 return {Intrinsic::sqrt, FTZ_Any};
1606 case Intrinsic::nvvm_sqrt_rn_f:
1607 return {Intrinsic::sqrt, FTZ_MustBeOff};
1608 case Intrinsic::nvvm_sqrt_rn_ftz_f:
1609 return {Intrinsic::sqrt, FTZ_MustBeOn};
1610 case Intrinsic::nvvm_trunc_d:
1611 return {Intrinsic::trunc, FTZ_Any};
1612 case Intrinsic::nvvm_trunc_f:
1613 return {Intrinsic::trunc, FTZ_MustBeOff};
1614 case Intrinsic::nvvm_trunc_ftz_f:
1615 return {Intrinsic::trunc, FTZ_MustBeOn};
1616
1617 // NVVM intrinsics that map to LLVM cast operations.
1618 //
1619 // Note that llvm's target-generic conversion operators correspond to the rz
1620 // (round to zero) versions of the nvvm conversion intrinsics, even though
1621 // most everything else here uses the rn (round to nearest even) nvvm ops.
1622 case Intrinsic::nvvm_d2i_rz:
1623 case Intrinsic::nvvm_f2i_rz:
1624 case Intrinsic::nvvm_d2ll_rz:
1625 case Intrinsic::nvvm_f2ll_rz:
1626 return {Instruction::FPToSI};
1627 case Intrinsic::nvvm_d2ui_rz:
1628 case Intrinsic::nvvm_f2ui_rz:
1629 case Intrinsic::nvvm_d2ull_rz:
1630 case Intrinsic::nvvm_f2ull_rz:
1631 return {Instruction::FPToUI};
1632 case Intrinsic::nvvm_i2d_rz:
1633 case Intrinsic::nvvm_i2f_rz:
1634 case Intrinsic::nvvm_ll2d_rz:
1635 case Intrinsic::nvvm_ll2f_rz:
1636 return {Instruction::SIToFP};
1637 case Intrinsic::nvvm_ui2d_rz:
1638 case Intrinsic::nvvm_ui2f_rz:
1639 case Intrinsic::nvvm_ull2d_rz:
1640 case Intrinsic::nvvm_ull2f_rz:
1641 return {Instruction::UIToFP};
1642
1643 // NVVM intrinsics that map to LLVM binary ops.
1644 case Intrinsic::nvvm_add_rn_d:
1645 return {Instruction::FAdd, FTZ_Any};
1646 case Intrinsic::nvvm_add_rn_f:
1647 return {Instruction::FAdd, FTZ_MustBeOff};
1648 case Intrinsic::nvvm_add_rn_ftz_f:
1649 return {Instruction::FAdd, FTZ_MustBeOn};
1650 case Intrinsic::nvvm_mul_rn_d:
1651 return {Instruction::FMul, FTZ_Any};
1652 case Intrinsic::nvvm_mul_rn_f:
1653 return {Instruction::FMul, FTZ_MustBeOff};
1654 case Intrinsic::nvvm_mul_rn_ftz_f:
1655 return {Instruction::FMul, FTZ_MustBeOn};
1656 case Intrinsic::nvvm_div_rn_d:
1657 return {Instruction::FDiv, FTZ_Any};
1658 case Intrinsic::nvvm_div_rn_f:
1659 return {Instruction::FDiv, FTZ_MustBeOff};
1660 case Intrinsic::nvvm_div_rn_ftz_f:
1661 return {Instruction::FDiv, FTZ_MustBeOn};
1662
1663 // The remainder of cases are NVVM intrinsics that map to LLVM idioms, but
1664 // need special handling.
1665 //
Hiroshi Inoue0ca79dc2017-07-11 06:04:59 +00001666 // We seem to be missing intrinsics for rcp.approx.{ftz.}f32, which is just
Justin Lebar698c31b2017-01-27 00:58:58 +00001667 // as well.
1668 case Intrinsic::nvvm_rcp_rn_d:
1669 return {SPC_Reciprocal, FTZ_Any};
1670 case Intrinsic::nvvm_rcp_rn_f:
1671 return {SPC_Reciprocal, FTZ_MustBeOff};
1672 case Intrinsic::nvvm_rcp_rn_ftz_f:
1673 return {SPC_Reciprocal, FTZ_MustBeOn};
1674
1675 // We do not currently simplify intrinsics that give an approximate answer.
1676 // These include:
1677 //
1678 // - nvvm_cos_approx_{f,ftz_f}
1679 // - nvvm_ex2_approx_{d,f,ftz_f}
1680 // - nvvm_lg2_approx_{d,f,ftz_f}
1681 // - nvvm_sin_approx_{f,ftz_f}
1682 // - nvvm_sqrt_approx_{f,ftz_f}
1683 // - nvvm_rsqrt_approx_{d,f,ftz_f}
1684 // - nvvm_div_approx_{ftz_d,ftz_f,f}
1685 // - nvvm_rcp_approx_ftz_d
1686 //
1687 // Ideally we'd encode them as e.g. "fast call @llvm.cos", where "fast"
1688 // means that fastmath is enabled in the intrinsic. Unfortunately only
1689 // binary operators (currently) have a fastmath bit in SelectionDAG, so this
1690 // information gets lost and we can't select on it.
1691 //
1692 // TODO: div and rcp are lowered to a binary op, so these we could in theory
1693 // lower them to "fast fdiv".
1694
1695 default:
1696 return {};
1697 }
1698 }();
1699
1700 // If Action.FtzRequirementTy is not satisfied by the module's ftz state, we
1701 // can bail out now. (Notice that in the case that IID is not an NVVM
1702 // intrinsic, we don't have to look up any module metadata, as
1703 // FtzRequirementTy will be FTZ_Any.)
1704 if (Action.FtzRequirement != FTZ_Any) {
1705 bool FtzEnabled =
1706 II->getFunction()->getFnAttribute("nvptx-f32ftz").getValueAsString() ==
1707 "true";
1708
1709 if (FtzEnabled != (Action.FtzRequirement == FTZ_MustBeOn))
1710 return nullptr;
1711 }
1712
1713 // Simplify to target-generic intrinsic.
1714 if (Action.IID) {
1715 SmallVector<Value *, 4> Args(II->arg_operands());
1716 // All the target-generic intrinsics currently of interest to us have one
1717 // type argument, equal to that of the nvvm intrinsic's argument.
Justin Lebare3ac0fb2017-01-27 01:49:39 +00001718 Type *Tys[] = {II->getArgOperand(0)->getType()};
Justin Lebar698c31b2017-01-27 00:58:58 +00001719 return CallInst::Create(
1720 Intrinsic::getDeclaration(II->getModule(), *Action.IID, Tys), Args);
1721 }
1722
1723 // Simplify to target-generic binary op.
1724 if (Action.BinaryOp)
1725 return BinaryOperator::Create(*Action.BinaryOp, II->getArgOperand(0),
1726 II->getArgOperand(1), II->getName());
1727
1728 // Simplify to target-generic cast op.
1729 if (Action.CastOp)
1730 return CastInst::Create(*Action.CastOp, II->getArgOperand(0), II->getType(),
1731 II->getName());
1732
1733 // All that's left are the special cases.
1734 if (!Action.Special)
1735 return nullptr;
1736
1737 switch (*Action.Special) {
1738 case SPC_Reciprocal:
1739 // Simplify reciprocal.
1740 return BinaryOperator::Create(
1741 Instruction::FDiv, ConstantFP::get(II->getArgOperand(0)->getType(), 1),
1742 II->getArgOperand(0), II->getName());
1743 }
Justin Lebar25ebe2d2017-01-27 02:04:07 +00001744 llvm_unreachable("All SpecialCase enumerators should be handled in switch.");
Justin Lebar698c31b2017-01-27 00:58:58 +00001745}
1746
Arnaud A. de Grandmaison333ef382016-05-10 09:24:49 +00001747Instruction *InstCombiner::visitVAStartInst(VAStartInst &I) {
1748 removeTriviallyEmptyRange(I, Intrinsic::vastart, Intrinsic::vaend, *this);
1749 return nullptr;
1750}
1751
1752Instruction *InstCombiner::visitVACopyInst(VACopyInst &I) {
1753 removeTriviallyEmptyRange(I, Intrinsic::vacopy, Intrinsic::vaend, *this);
1754 return nullptr;
1755}
1756
Sanjay Patel790af912018-11-26 22:00:41 +00001757static Instruction *canonicalizeConstantArg0ToArg1(CallInst &Call) {
1758 assert(Call.getNumArgOperands() > 1 && "Need at least 2 args to swap");
1759 Value *Arg0 = Call.getArgOperand(0), *Arg1 = Call.getArgOperand(1);
1760 if (isa<Constant>(Arg0) && !isa<Constant>(Arg1)) {
1761 Call.setArgOperand(0, Arg1);
1762 Call.setArgOperand(1, Arg0);
1763 return &Call;
1764 }
1765 return nullptr;
1766}
1767
Nikita Popov884feb12019-03-06 18:30:00 +00001768Instruction *InstCombiner::foldIntrinsicWithOverflowCommon(IntrinsicInst *II) {
Nikita Popov352f5982019-05-26 11:43:31 +00001769 WithOverflowInst *WO = cast<WithOverflowInst>(II);
Nikita Popov884feb12019-03-06 18:30:00 +00001770 Value *OperationResult = nullptr;
1771 Constant *OverflowResult = nullptr;
Nikita Popov352f5982019-05-26 11:43:31 +00001772 if (OptimizeOverflowCheck(WO->getBinaryOp(), WO->isSigned(), WO->getLHS(),
1773 WO->getRHS(), *WO, OperationResult, OverflowResult))
1774 return CreateOverflowTuple(WO, OperationResult, OverflowResult);
Nikita Popov884feb12019-03-06 18:30:00 +00001775 return nullptr;
1776}
1777
Sanjay Patelcd4377c2016-01-20 22:24:38 +00001778/// CallInst simplification. This mostly only handles folding of intrinsic
Craig Topperc1892ec2019-01-31 17:23:29 +00001779/// instructions. For normal calls, it allows visitCallBase to do the heavy
Sanjay Patelcd4377c2016-01-20 22:24:38 +00001780/// lifting.
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001781Instruction *InstCombiner::visitCallInst(CallInst &CI) {
Philip Reames7a6db4f2017-12-27 00:16:12 +00001782 if (Value *V = SimplifyCall(&CI, SQ.getWithInstruction(&CI)))
Sanjay Patel4b198802016-02-01 22:23:39 +00001783 return replaceInstUsesWith(CI, V);
David Majnemer15032582015-05-22 03:56:46 +00001784
Justin Bogner99798402016-08-05 01:06:44 +00001785 if (isFreeCall(&CI, &TLI))
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001786 return visitFree(CI);
1787
1788 // If the caller function is nounwind, mark the call as nounwind, even if the
1789 // callee isn't.
Sanjay Patel5a470952016-08-11 15:16:06 +00001790 if (CI.getFunction()->doesNotThrow() && !CI.doesNotThrow()) {
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001791 CI.setDoesNotThrow();
1792 return &CI;
1793 }
Jim Grosbach7815f562012-02-03 00:07:04 +00001794
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001795 IntrinsicInst *II = dyn_cast<IntrinsicInst>(&CI);
Craig Topperc1892ec2019-01-31 17:23:29 +00001796 if (!II) return visitCallBase(CI);
Gabor Greif589a0b92010-06-24 12:58:35 +00001797
Craig Topper784929d2019-02-08 20:48:56 +00001798 // Intrinsics cannot occur in an invoke or a callbr, so handle them here
1799 // instead of in visitCallBase.
Daniel Neilson8f30ec62018-05-11 14:30:02 +00001800 if (auto *MI = dyn_cast<AnyMemIntrinsic>(II)) {
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001801 bool Changed = false;
1802
1803 // memmove/cpy/set of zero bytes is a noop.
1804 if (Constant *NumBytes = dyn_cast<Constant>(MI->getLength())) {
Chris Lattnerc663a672010-10-01 05:51:02 +00001805 if (NumBytes->isNullValue())
Sanjay Patel4b198802016-02-01 22:23:39 +00001806 return eraseInstFromFunction(CI);
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001807
1808 if (ConstantInt *CI = dyn_cast<ConstantInt>(NumBytes))
1809 if (CI->getZExtValue() == 1) {
1810 // Replace the instruction with just byte operations. We would
1811 // transform other cases to loads/stores, but we don't know if
1812 // alignment is sufficient.
1813 }
1814 }
Jim Grosbach7815f562012-02-03 00:07:04 +00001815
Chris Lattnerc663a672010-10-01 05:51:02 +00001816 // No other transformations apply to volatile transfers.
Daniel Neilson8f30ec62018-05-11 14:30:02 +00001817 if (auto *M = dyn_cast<MemIntrinsic>(MI))
1818 if (M->isVolatile())
1819 return nullptr;
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001820
1821 // If we have a memmove and the source operation is a constant global,
1822 // then the source and dest pointers can't alias, so we can change this
1823 // into a call to memcpy.
Daniel Neilson8f30ec62018-05-11 14:30:02 +00001824 if (auto *MMI = dyn_cast<AnyMemMoveInst>(MI)) {
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001825 if (GlobalVariable *GVSrc = dyn_cast<GlobalVariable>(MMI->getSource()))
1826 if (GVSrc->isConstant()) {
Sanjay Patelaf674fb2015-12-14 17:24:23 +00001827 Module *M = CI.getModule();
Daniel Neilson8f30ec62018-05-11 14:30:02 +00001828 Intrinsic::ID MemCpyID =
1829 isa<AtomicMemMoveInst>(MMI)
1830 ? Intrinsic::memcpy_element_unordered_atomic
1831 : Intrinsic::memcpy;
Jay Foadb804a2b2011-07-12 14:06:48 +00001832 Type *Tys[3] = { CI.getArgOperand(0)->getType(),
1833 CI.getArgOperand(1)->getType(),
1834 CI.getArgOperand(2)->getType() };
Benjamin Kramere6e19332011-07-14 17:45:39 +00001835 CI.setCalledFunction(Intrinsic::getDeclaration(M, MemCpyID, Tys));
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001836 Changed = true;
1837 }
1838 }
1839
Daniel Neilson8f30ec62018-05-11 14:30:02 +00001840 if (AnyMemTransferInst *MTI = dyn_cast<AnyMemTransferInst>(MI)) {
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001841 // memmove(x,x,size) -> noop.
1842 if (MTI->getSource() == MTI->getDest())
Sanjay Patel4b198802016-02-01 22:23:39 +00001843 return eraseInstFromFunction(CI);
Eric Christopher7258dcd2010-04-16 23:37:20 +00001844 }
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001845
Eric Christopher7258dcd2010-04-16 23:37:20 +00001846 // If we can determine a pointer alignment that is bigger than currently
1847 // set, update the alignment.
Daniel Neilson8f30ec62018-05-11 14:30:02 +00001848 if (auto *MTI = dyn_cast<AnyMemTransferInst>(MI)) {
1849 if (Instruction *I = SimplifyAnyMemTransfer(MTI))
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001850 return I;
Daniel Neilsonf6651d42018-05-11 20:04:50 +00001851 } else if (auto *MSI = dyn_cast<AnyMemSetInst>(MI)) {
1852 if (Instruction *I = SimplifyAnyMemSet(MSI))
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001853 return I;
1854 }
Gabor Greif590d95e2010-06-24 13:42:49 +00001855
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001856 if (Changed) return II;
1857 }
Jim Grosbach7815f562012-02-03 00:07:04 +00001858
Philip Reames68a2e4d2019-03-15 19:54:06 +00001859 // For vector result intrinsics, use the generic demanded vector support.
Philip Reamesc71e9962019-01-30 19:21:11 +00001860 if (II->getType()->isVectorTy()) {
1861 auto VWidth = II->getType()->getVectorNumElements();
1862 APInt UndefElts(VWidth, 0);
1863 APInt AllOnesEltMask(APInt::getAllOnesValue(VWidth));
1864 if (Value *V = SimplifyDemandedVectorElts(II, AllOnesEltMask, UndefElts)) {
1865 if (V != II)
1866 return replaceInstUsesWith(*II, V);
1867 return II;
1868 }
1869 }
1870
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
Sanjay Patel62f457b2019-05-06 15:35:02 +00001881 Intrinsic::ID IID = II->getIntrinsicID();
1882 switch (IID) {
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001883 default: break;
George Burgess IV3f089142016-12-20 23:46:36 +00001884 case Intrinsic::objectsize:
Erik Pilkington600e9de2019-01-30 20:34:35 +00001885 if (Value *V = lowerObjectSizeCall(II, DL, &TLI, /*MustSucceed=*/false))
1886 return replaceInstUsesWith(CI, V);
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:
Philip Reames7c8647b2019-04-25 01:18:56 +00001903 if (Value *SimplifiedMaskedOp = simplifyMaskedLoad(*II))
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:
Philip Reamese4588bb2019-03-20 18:44:58 +00001907 return simplifyMaskedStore(*II);
Sanjay Patel103ab7d2016-02-01 22:10:26 +00001908 case Intrinsic::masked_gather:
Philip Reames7c8647b2019-04-25 01:18:56 +00001909 return simplifyMaskedGather(*II);
Sanjay Patel103ab7d2016-02-01 22:10:26 +00001910 case Intrinsic::masked_scatter:
Philip Reamese4588bb2019-03-20 18:44:58 +00001911 return simplifyMaskedScatter(*II);
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: {
Sanjay Patelb3bcd952019-03-17 19:08:00 +00001945 Value *Op0 = II->getArgOperand(0), *Op1 = II->getArgOperand(1);
1946 Type *Ty = II->getType();
1947 unsigned BitWidth = Ty->getScalarSizeInBits();
Sanjay Patelde1d5d32019-03-14 19:22:08 +00001948 Constant *ShAmtC;
1949 if (match(II->getArgOperand(2), m_Constant(ShAmtC)) &&
1950 !isa<ConstantExpr>(ShAmtC) && !ShAmtC->containsConstantExpression()) {
Sanjay Patelb3bcd952019-03-17 19:08:00 +00001951 // Canonicalize a shift amount constant operand to modulo the bit-width.
1952 Constant *WidthC = ConstantInt::get(Ty, BitWidth);
Sanjay Patelde1d5d32019-03-14 19:22:08 +00001953 Constant *ModuloC = ConstantExpr::getURem(ShAmtC, WidthC);
1954 if (ModuloC != ShAmtC) {
1955 II->setArgOperand(2, ModuloC);
1956 return II;
1957 }
Sanjay Patel60633932019-03-18 14:27:51 +00001958 assert(ConstantExpr::getICmp(ICmpInst::ICMP_UGT, WidthC, ShAmtC) ==
1959 ConstantInt::getTrue(CmpInst::makeCmpResultType(Ty)) &&
1960 "Shift amount expected to be modulo bitwidth");
1961
Sanjay Patel84de8a32019-03-18 14:10:11 +00001962 // Canonicalize funnel shift right by constant to funnel shift left. This
1963 // is not entirely arbitrary. For historical reasons, the backend may
1964 // recognize rotate left patterns but miss rotate right patterns.
Sanjay Patel62f457b2019-05-06 15:35:02 +00001965 if (IID == Intrinsic::fshr) {
Sanjay Patel84de8a32019-03-18 14:10:11 +00001966 // fshr X, Y, C --> fshl X, Y, (BitWidth - C)
Sanjay Patelb3bcd952019-03-17 19:08:00 +00001967 Constant *LeftShiftC = ConstantExpr::getSub(WidthC, ShAmtC);
1968 Module *Mod = II->getModule();
1969 Function *Fshl = Intrinsic::getDeclaration(Mod, Intrinsic::fshl, Ty);
Sanjay Patel84de8a32019-03-18 14:10:11 +00001970 return CallInst::Create(Fshl, { Op0, Op1, LeftShiftC });
Sanjay Patelb3bcd952019-03-17 19:08:00 +00001971 }
Sanjay Patel62f457b2019-05-06 15:35:02 +00001972 assert(IID == Intrinsic::fshl &&
Sanjay Patel84de8a32019-03-18 14:10:11 +00001973 "All funnel shifts by simple constants should go left");
Nikita Popov6e81d422018-11-23 22:45:08 +00001974
Sanjay Patel60633932019-03-18 14:27:51 +00001975 // fshl(X, 0, C) --> shl X, C
1976 // fshl(X, undef, C) --> shl X, C
1977 if (match(Op1, m_ZeroInt()) || match(Op1, m_Undef()))
1978 return BinaryOperator::CreateShl(Op0, ShAmtC);
Nikita Popov6e81d422018-11-23 22:45:08 +00001979
Sanjay Patel60633932019-03-18 14:27:51 +00001980 // fshl(0, X, C) --> lshr X, (BW-C)
1981 // fshl(undef, X, C) --> lshr X, (BW-C)
1982 if (match(Op0, m_ZeroInt()) || match(Op0, m_Undef()))
1983 return BinaryOperator::CreateLShr(Op1,
1984 ConstantExpr::getSub(WidthC, ShAmtC));
Sanjay Patel89efefb2019-06-24 15:20:49 +00001985
1986 // fshl i16 X, X, 8 --> bswap i16 X (reduce to more-specific form)
1987 if (Op0 == Op1 && BitWidth == 16 && match(ShAmtC, m_SpecificInt(8))) {
1988 Module *Mod = II->getModule();
1989 Function *Bswap = Intrinsic::getDeclaration(Mod, Intrinsic::bswap, Ty);
1990 return CallInst::Create(Bswap, { Op0 });
1991 }
Nikita Popov6e81d422018-11-23 22:45:08 +00001992 }
1993
Nikita Popov5ecd6a42019-04-16 19:05:49 +00001994 // Left or right might be masked.
1995 if (SimplifyDemandedInstructionBits(*II))
1996 return &CI;
1997
Sanjay Patela1395642018-11-13 23:27:23 +00001998 // The shift amount (operand 2) of a funnel shift is modulo the bitwidth,
1999 // so only the low bits of the shift amount are demanded if the bitwidth is
2000 // a power-of-2.
Sanjay Patela1395642018-11-13 23:27:23 +00002001 if (!isPowerOf2_32(BitWidth))
2002 break;
2003 APInt Op2Demanded = APInt::getLowBitsSet(BitWidth, Log2_32_Ceil(BitWidth));
2004 KnownBits Op2Known(BitWidth);
2005 if (SimplifyDemandedBits(II, 2, Op2Demanded, Op2Known))
2006 return &CI;
2007 break;
2008 }
Nikita Popov37cf25c2019-03-20 18:00:27 +00002009 case Intrinsic::uadd_with_overflow:
Nikita Popov884feb12019-03-06 18:30:00 +00002010 case Intrinsic::sadd_with_overflow: {
2011 if (Instruction *I = canonicalizeConstantArg0ToArg1(CI))
2012 return I;
2013 if (Instruction *I = foldIntrinsicWithOverflowCommon(II))
2014 return I;
2015
2016 // Given 2 constant operands whose sum does not overflow:
Nikita Popov37cf25c2019-03-20 18:00:27 +00002017 // uaddo (X +nuw C0), C1 -> uaddo X, C0 + C1
Nikita Popov884feb12019-03-06 18:30:00 +00002018 // saddo (X +nsw C0), C1 -> saddo X, C0 + C1
2019 Value *X;
2020 const APInt *C0, *C1;
2021 Value *Arg0 = II->getArgOperand(0);
2022 Value *Arg1 = II->getArgOperand(1);
Sanjay Patel62f457b2019-05-06 15:35:02 +00002023 bool IsSigned = IID == Intrinsic::sadd_with_overflow;
Nikita Popov37cf25c2019-03-20 18:00:27 +00002024 bool HasNWAdd = IsSigned ? match(Arg0, m_NSWAdd(m_Value(X), m_APInt(C0)))
2025 : match(Arg0, m_NUWAdd(m_Value(X), m_APInt(C0)));
2026 if (HasNWAdd && match(Arg1, m_APInt(C1))) {
Nikita Popov884feb12019-03-06 18:30:00 +00002027 bool Overflow;
Nikita Popov37cf25c2019-03-20 18:00:27 +00002028 APInt NewC =
2029 IsSigned ? C1->sadd_ov(*C0, Overflow) : C1->uadd_ov(*C0, Overflow);
Nikita Popov884feb12019-03-06 18:30:00 +00002030 if (!Overflow)
2031 return replaceInstUsesWith(
2032 *II, Builder.CreateBinaryIntrinsic(
Sanjay Patel62f457b2019-05-06 15:35:02 +00002033 IID, X, ConstantInt::get(Arg1->getType(), NewC)));
Nikita Popov884feb12019-03-06 18:30:00 +00002034 }
Nikita Popov884feb12019-03-06 18:30:00 +00002035 break;
2036 }
Nikita Popov7a543c32019-04-10 16:27:36 +00002037
Nick Lewyckyabe2cc12015-04-13 19:17:37 +00002038 case Intrinsic::umul_with_overflow:
2039 case Intrinsic::smul_with_overflow:
Sanjay Patel790af912018-11-26 22:00:41 +00002040 if (Instruction *I = canonicalizeConstantArg0ToArg1(CI))
2041 return I;
Justin Bognercd1d5aa2016-08-17 20:30:52 +00002042 LLVM_FALLTHROUGH;
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002043
Nick Lewyckyabe2cc12015-04-13 19:17:37 +00002044 case Intrinsic::usub_with_overflow:
Nikita Popov7a543c32019-04-10 16:27:36 +00002045 if (Instruction *I = foldIntrinsicWithOverflowCommon(II))
2046 return I;
2047 break;
2048
Nick Lewyckyabe2cc12015-04-13 19:17:37 +00002049 case Intrinsic::ssub_with_overflow: {
Nikita Popov884feb12019-03-06 18:30:00 +00002050 if (Instruction *I = foldIntrinsicWithOverflowCommon(II))
2051 return I;
Benjamin Kramera420df22014-07-04 10:22:21 +00002052
Nikita Popov7a543c32019-04-10 16:27:36 +00002053 Constant *C;
2054 Value *Arg0 = II->getArgOperand(0);
2055 Value *Arg1 = II->getArgOperand(1);
2056 // Given a constant C that is not the minimum signed value
2057 // for an integer of a given bit width:
2058 //
2059 // ssubo X, C -> saddo X, -C
2060 if (match(Arg1, m_Constant(C)) && C->isNotMinSignedValue()) {
2061 Value *NegVal = ConstantExpr::getNeg(C);
2062 // Build a saddo call that is equivalent to the discovered
2063 // ssubo call.
2064 return replaceInstUsesWith(
2065 *II, Builder.CreateBinaryIntrinsic(Intrinsic::sadd_with_overflow,
2066 Arg0, NegVal));
2067 }
2068
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002069 break;
Erik Eckstein096ff7d2014-12-11 08:02:30 +00002070 }
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002071
Nikita Popov085d24a2018-11-28 16:36:52 +00002072 case Intrinsic::uadd_sat:
2073 case Intrinsic::sadd_sat:
2074 if (Instruction *I = canonicalizeConstantArg0ToArg1(CI))
2075 return I;
Nikita Popov78a92952018-11-28 16:36:59 +00002076 LLVM_FALLTHROUGH;
2077 case Intrinsic::usub_sat:
2078 case Intrinsic::ssub_sat: {
Nikita Popovc51cdac2019-05-28 18:59:21 +00002079 SaturatingInst *SI = cast<SaturatingInst>(II);
Nikita Popov53828032019-05-29 18:37:13 +00002080 Type *Ty = SI->getType();
Nikita Popovc51cdac2019-05-28 18:59:21 +00002081 Value *Arg0 = SI->getLHS();
2082 Value *Arg1 = SI->getRHS();
Nikita Popov78a92952018-11-28 16:36:59 +00002083
2084 // Make use of known overflow information.
Nikita Popovc51cdac2019-05-28 18:59:21 +00002085 OverflowResult OR = computeOverflow(SI->getBinaryOp(), SI->isSigned(),
2086 Arg0, Arg1, SI);
2087 switch (OR) {
2088 case OverflowResult::MayOverflow:
2089 break;
2090 case OverflowResult::NeverOverflows:
2091 if (SI->isSigned())
2092 return BinaryOperator::CreateNSW(SI->getBinaryOp(), Arg0, Arg1);
2093 else
2094 return BinaryOperator::CreateNUW(SI->getBinaryOp(), Arg0, Arg1);
Nikita Popov53828032019-05-29 18:37:13 +00002095 case OverflowResult::AlwaysOverflowsLow: {
2096 unsigned BitWidth = Ty->getScalarSizeInBits();
2097 APInt Min = APSInt::getMinValue(BitWidth, !SI->isSigned());
2098 return replaceInstUsesWith(*SI, ConstantInt::get(Ty, Min));
2099 }
2100 case OverflowResult::AlwaysOverflowsHigh: {
2101 unsigned BitWidth = Ty->getScalarSizeInBits();
2102 APInt Max = APSInt::getMaxValue(BitWidth, !SI->isSigned());
2103 return replaceInstUsesWith(*SI, ConstantInt::get(Ty, Max));
2104 }
Nikita Popov78a92952018-11-28 16:36:59 +00002105 }
Nikita Popov42f89982018-11-28 16:37:09 +00002106
2107 // ssub.sat(X, C) -> sadd.sat(X, -C) if C != MIN
Nikita Popov0c5d6cc2018-12-01 10:58:34 +00002108 Constant *C;
2109 if (IID == Intrinsic::ssub_sat && match(Arg1, m_Constant(C)) &&
2110 C->isNotMinSignedValue()) {
2111 Value *NegVal = ConstantExpr::getNeg(C);
Nikita Popov42f89982018-11-28 16:37:09 +00002112 return replaceInstUsesWith(
2113 *II, Builder.CreateBinaryIntrinsic(
2114 Intrinsic::sadd_sat, Arg0, NegVal));
2115 }
Nikita Popov8d63aed2018-11-28 16:37:15 +00002116
2117 // sat(sat(X + Val2) + Val) -> sat(X + (Val+Val2))
2118 // sat(sat(X - Val2) - Val) -> sat(X - (Val+Val2))
2119 // if Val and Val2 have the same sign
2120 if (auto *Other = dyn_cast<IntrinsicInst>(Arg0)) {
2121 Value *X;
2122 const APInt *Val, *Val2;
2123 APInt NewVal;
2124 bool IsUnsigned =
2125 IID == Intrinsic::uadd_sat || IID == Intrinsic::usub_sat;
Sanjay Patel62f457b2019-05-06 15:35:02 +00002126 if (Other->getIntrinsicID() == IID &&
Nikita Popov8d63aed2018-11-28 16:37:15 +00002127 match(Arg1, m_APInt(Val)) &&
2128 match(Other->getArgOperand(0), m_Value(X)) &&
2129 match(Other->getArgOperand(1), m_APInt(Val2))) {
2130 if (IsUnsigned)
2131 NewVal = Val->uadd_sat(*Val2);
2132 else if (Val->isNonNegative() == Val2->isNonNegative()) {
2133 bool Overflow;
2134 NewVal = Val->sadd_ov(*Val2, Overflow);
2135 if (Overflow) {
2136 // Both adds together may add more than SignedMaxValue
2137 // without saturating the final result.
2138 break;
2139 }
2140 } else {
2141 // Cannot fold saturated addition with different signs.
2142 break;
2143 }
2144
2145 return replaceInstUsesWith(
2146 *II, Builder.CreateBinaryIntrinsic(
2147 IID, X, ConstantInt::get(II->getType(), NewVal)));
2148 }
2149 }
Nikita Popov085d24a2018-11-28 16:36:52 +00002150 break;
Nikita Popov78a92952018-11-28 16:36:59 +00002151 }
Nikita Popov085d24a2018-11-28 16:36:52 +00002152
Matt Arsenaultd6511b42014-10-21 23:00:20 +00002153 case Intrinsic::minnum:
Thomas Livelyc3392502018-10-19 19:01:26 +00002154 case Intrinsic::maxnum:
2155 case Intrinsic::minimum:
2156 case Intrinsic::maximum: {
Sanjay Patel790af912018-11-26 22:00:41 +00002157 if (Instruction *I = canonicalizeConstantArg0ToArg1(CI))
2158 return I;
Matt Arsenaultd6511b42014-10-21 23:00:20 +00002159 Value *Arg0 = II->getArgOperand(0);
2160 Value *Arg1 = II->getArgOperand(1);
Sanjay Patelc7bb1432018-05-10 20:03:13 +00002161 Value *X, *Y;
2162 if (match(Arg0, m_FNeg(m_Value(X))) && match(Arg1, m_FNeg(m_Value(Y))) &&
2163 (Arg0->hasOneUse() || Arg1->hasOneUse())) {
2164 // If both operands are negated, invert the call and negate the result:
Thomas Livelyc3392502018-10-19 19:01:26 +00002165 // min(-X, -Y) --> -(max(X, Y))
2166 // max(-X, -Y) --> -(min(X, Y))
2167 Intrinsic::ID NewIID;
Volkan Keles3ca146d2018-10-31 17:50:52 +00002168 switch (IID) {
Thomas Livelyc3392502018-10-19 19:01:26 +00002169 case Intrinsic::maxnum:
2170 NewIID = Intrinsic::minnum;
2171 break;
2172 case Intrinsic::minnum:
2173 NewIID = Intrinsic::maxnum;
2174 break;
2175 case Intrinsic::maximum:
2176 NewIID = Intrinsic::minimum;
2177 break;
2178 case Intrinsic::minimum:
2179 NewIID = Intrinsic::maximum;
2180 break;
2181 default:
2182 llvm_unreachable("unexpected intrinsic ID");
2183 }
Neil Henning57f5d0a2018-10-08 10:32:33 +00002184 Value *NewCall = Builder.CreateBinaryIntrinsic(NewIID, X, Y, II);
Sanjay Patelc7bb1432018-05-10 20:03:13 +00002185 Instruction *FNeg = BinaryOperator::CreateFNeg(NewCall);
2186 FNeg->copyIRFlags(II);
2187 return FNeg;
2188 }
Volkan Keles3ca146d2018-10-31 17:50:52 +00002189
2190 // m(m(X, C2), C1) -> m(X, C)
2191 const APFloat *C1, *C2;
2192 if (auto *M = dyn_cast<IntrinsicInst>(Arg0)) {
2193 if (M->getIntrinsicID() == IID && match(Arg1, m_APFloat(C1)) &&
2194 ((match(M->getArgOperand(0), m_Value(X)) &&
2195 match(M->getArgOperand(1), m_APFloat(C2))) ||
2196 (match(M->getArgOperand(1), m_Value(X)) &&
2197 match(M->getArgOperand(0), m_APFloat(C2))))) {
2198 APFloat Res(0.0);
2199 switch (IID) {
2200 case Intrinsic::maxnum:
2201 Res = maxnum(*C1, *C2);
2202 break;
2203 case Intrinsic::minnum:
2204 Res = minnum(*C1, *C2);
2205 break;
2206 case Intrinsic::maximum:
2207 Res = maximum(*C1, *C2);
2208 break;
2209 case Intrinsic::minimum:
2210 Res = minimum(*C1, *C2);
2211 break;
2212 default:
2213 llvm_unreachable("unexpected intrinsic ID");
2214 }
2215 Instruction *NewCall = Builder.CreateBinaryIntrinsic(
2216 IID, X, ConstantFP::get(Arg0->getType(), Res));
2217 NewCall->copyIRFlags(II);
2218 return replaceInstUsesWith(*II, NewCall);
2219 }
2220 }
2221
Matt Arsenaultd6511b42014-10-21 23:00:20 +00002222 break;
2223 }
Matt Arsenault1cc294c2017-01-03 04:32:31 +00002224 case Intrinsic::fmuladd: {
Matt Arsenault92057602017-02-16 18:46:24 +00002225 // Canonicalize fast fmuladd to the separate fmul + fadd.
Sanjay Patel629c4112017-11-06 16:27:15 +00002226 if (II->isFast()) {
Craig Topperbb4069e2017-07-07 23:16:26 +00002227 BuilderTy::FastMathFlagGuard Guard(Builder);
2228 Builder.setFastMathFlags(II->getFastMathFlags());
2229 Value *Mul = Builder.CreateFMul(II->getArgOperand(0),
2230 II->getArgOperand(1));
2231 Value *Add = Builder.CreateFAdd(Mul, II->getArgOperand(2));
Matt Arsenault92057602017-02-16 18:46:24 +00002232 Add->takeName(II);
2233 return replaceInstUsesWith(*II, Add);
2234 }
2235
Florian Hahnf3ab99d2019-09-25 17:03:20 +00002236 // Try to simplify the underlying FMul.
2237 if (Value *V = SimplifyFMulInst(II->getArgOperand(0), II->getArgOperand(1),
2238 II->getFastMathFlags(),
2239 SQ.getWithInstruction(II))) {
2240 auto *FAdd = BinaryOperator::CreateFAdd(V, II->getArgOperand(2));
2241 FAdd->copyFastMathFlags(II);
2242 return FAdd;
2243 }
2244
Matt Arsenault92057602017-02-16 18:46:24 +00002245 LLVM_FALLTHROUGH;
2246 }
2247 case Intrinsic::fma: {
Sanjay Patel790af912018-11-26 22:00:41 +00002248 if (Instruction *I = canonicalizeConstantArg0ToArg1(CI))
2249 return I;
Matt Arsenaultb264c942017-01-03 04:32:35 +00002250
Matt Arsenault1cc294c2017-01-03 04:32:31 +00002251 // fma fneg(x), fneg(y), z -> fma x, y, z
Sanjay Patel790af912018-11-26 22:00:41 +00002252 Value *Src0 = II->getArgOperand(0);
2253 Value *Src1 = II->getArgOperand(1);
Sanjay Patel236442e2018-04-05 13:24:26 +00002254 Value *X, *Y;
2255 if (match(Src0, m_FNeg(m_Value(X))) && match(Src1, m_FNeg(m_Value(Y)))) {
2256 II->setArgOperand(0, X);
2257 II->setArgOperand(1, Y);
Matt Arsenault3f509042017-01-10 23:17:52 +00002258 return II;
Matt Arsenault1cc294c2017-01-03 04:32:31 +00002259 }
2260
2261 // fma fabs(x), fabs(x), z -> fma x, x, z
Matt Arsenaultd1496502018-07-27 09:04:35 +00002262 if (match(Src0, m_FAbs(m_Value(X))) &&
2263 match(Src1, m_FAbs(m_Specific(X)))) {
Sanjay Patel236442e2018-04-05 13:24:26 +00002264 II->setArgOperand(0, X);
2265 II->setArgOperand(1, X);
Matt Arsenault3f509042017-01-10 23:17:52 +00002266 return II;
Matt Arsenault1cc294c2017-01-03 04:32:31 +00002267 }
2268
Florian Hahnf3ab99d2019-09-25 17:03:20 +00002269 // Try to simplify the underlying FMul. We can only apply simplifications
2270 // that do not require rounding.
2271 if (Value *V = SimplifyFMAFMul(II->getArgOperand(0), II->getArgOperand(1),
2272 II->getFastMathFlags(),
2273 SQ.getWithInstruction(II))) {
2274 auto *FAdd = BinaryOperator::CreateFAdd(V, II->getArgOperand(2));
Sanjay Patel236442e2018-04-05 13:24:26 +00002275 FAdd->copyFastMathFlags(II);
2276 return FAdd;
Matt Arsenaultb264c942017-01-03 04:32:35 +00002277 }
2278
Matt Arsenault1cc294c2017-01-03 04:32:31 +00002279 break;
2280 }
Matt Arsenault56ff4832017-01-03 22:40:34 +00002281 case Intrinsic::fabs: {
2282 Value *Cond;
2283 Constant *LHS, *RHS;
2284 if (match(II->getArgOperand(0),
2285 m_Select(m_Value(Cond), m_Constant(LHS), m_Constant(RHS)))) {
Craig Topperbb4069e2017-07-07 23:16:26 +00002286 CallInst *Call0 = Builder.CreateCall(II->getCalledFunction(), {LHS});
2287 CallInst *Call1 = Builder.CreateCall(II->getCalledFunction(), {RHS});
Matt Arsenault56ff4832017-01-03 22:40:34 +00002288 return SelectInst::Create(Cond, Call0, Call1);
2289 }
2290
Matt Arsenault954a6242017-01-23 23:55:08 +00002291 LLVM_FALLTHROUGH;
2292 }
2293 case Intrinsic::ceil:
2294 case Intrinsic::floor:
2295 case Intrinsic::round:
2296 case Intrinsic::nearbyint:
Joerg Sonnenberger28bed102017-03-31 19:58:07 +00002297 case Intrinsic::rint:
Matt Arsenault954a6242017-01-23 23:55:08 +00002298 case Intrinsic::trunc: {
Matt Arsenault72333442017-01-17 00:10:40 +00002299 Value *ExtSrc;
Sanjay Patel32381d72018-03-23 21:18:12 +00002300 if (match(II->getArgOperand(0), m_OneUse(m_FPExt(m_Value(ExtSrc))))) {
2301 // Narrow the call: intrinsic (fpext x) -> fpext (intrinsic x)
Sanjay Patel62f457b2019-05-06 15:35:02 +00002302 Value *NarrowII = Builder.CreateUnaryIntrinsic(IID, ExtSrc, II);
Sanjay Patel32381d72018-03-23 21:18:12 +00002303 return new FPExtInst(NarrowII, II->getType());
Matt Arsenault72333442017-01-17 00:10:40 +00002304 }
Matt Arsenault56ff4832017-01-03 22:40:34 +00002305 break;
2306 }
Matt Arsenault3bdd75d2017-01-04 22:49:03 +00002307 case Intrinsic::cos:
2308 case Intrinsic::amdgcn_cos: {
Sanjay Patel0f29e952018-08-29 18:27:49 +00002309 Value *X;
Matt Arsenault3bdd75d2017-01-04 22:49:03 +00002310 Value *Src = II->getArgOperand(0);
Sanjay Patel0f29e952018-08-29 18:27:49 +00002311 if (match(Src, m_FNeg(m_Value(X))) || match(Src, m_FAbs(m_Value(X)))) {
Matt Arsenault3bdd75d2017-01-04 22:49:03 +00002312 // cos(-x) -> cos(x)
2313 // cos(fabs(x)) -> cos(x)
Sanjay Patel0f29e952018-08-29 18:27:49 +00002314 II->setArgOperand(0, X);
Matt Arsenault3bdd75d2017-01-04 22:49:03 +00002315 return II;
2316 }
Sanjay Patel0f29e952018-08-29 18:27:49 +00002317 break;
2318 }
2319 case Intrinsic::sin: {
2320 Value *X;
2321 if (match(II->getArgOperand(0), m_OneUse(m_FNeg(m_Value(X))))) {
2322 // sin(-x) --> -sin(x)
Neil Henning57f5d0a2018-10-08 10:32:33 +00002323 Value *NewSin = Builder.CreateUnaryIntrinsic(Intrinsic::sin, X, II);
Sanjay Patel0f29e952018-08-29 18:27:49 +00002324 Instruction *FNeg = BinaryOperator::CreateFNeg(NewSin);
2325 FNeg->copyFastMathFlags(II);
2326 return FNeg;
2327 }
Matt Arsenault3bdd75d2017-01-04 22:49:03 +00002328 break;
2329 }
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002330 case Intrinsic::ppc_altivec_lvx:
2331 case Intrinsic::ppc_altivec_lvxl:
Bill Wendlingb902f1d2011-04-13 00:36:11 +00002332 // Turn PPC lvx -> load if the pointer is known aligned.
Daniel Jasperaec2fa32016-12-19 08:22:17 +00002333 if (getOrEnforceKnownAlignment(II->getArgOperand(0), 16, DL, II, &AC,
Justin Bogner99798402016-08-05 01:06:44 +00002334 &DT) >= 16) {
Craig Topperbb4069e2017-07-07 23:16:26 +00002335 Value *Ptr = Builder.CreateBitCast(II->getArgOperand(0),
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002336 PointerType::getUnqual(II->getType()));
James Y Knight14359ef2019-02-01 20:44:24 +00002337 return new LoadInst(II->getType(), Ptr);
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002338 }
2339 break;
Bill Schmidt72954782014-11-12 04:19:40 +00002340 case Intrinsic::ppc_vsx_lxvw4x:
2341 case Intrinsic::ppc_vsx_lxvd2x: {
2342 // Turn PPC VSX loads into normal loads.
Craig Topperbb4069e2017-07-07 23:16:26 +00002343 Value *Ptr = Builder.CreateBitCast(II->getArgOperand(0),
2344 PointerType::getUnqual(II->getType()));
James Y Knight14359ef2019-02-01 20:44:24 +00002345 return new LoadInst(II->getType(), Ptr, Twine(""), false, 1);
Bill Schmidt72954782014-11-12 04:19:40 +00002346 }
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002347 case Intrinsic::ppc_altivec_stvx:
2348 case Intrinsic::ppc_altivec_stvxl:
2349 // Turn stvx -> store if the pointer is known aligned.
Daniel Jasperaec2fa32016-12-19 08:22:17 +00002350 if (getOrEnforceKnownAlignment(II->getArgOperand(1), 16, DL, II, &AC,
Justin Bogner99798402016-08-05 01:06:44 +00002351 &DT) >= 16) {
Jim Grosbach7815f562012-02-03 00:07:04 +00002352 Type *OpPtrTy =
Gabor Greifa6d75e22010-06-24 15:51:11 +00002353 PointerType::getUnqual(II->getArgOperand(0)->getType());
Craig Topperbb4069e2017-07-07 23:16:26 +00002354 Value *Ptr = Builder.CreateBitCast(II->getArgOperand(1), OpPtrTy);
Gabor Greifa6d75e22010-06-24 15:51:11 +00002355 return new StoreInst(II->getArgOperand(0), Ptr);
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002356 }
2357 break;
Bill Schmidt72954782014-11-12 04:19:40 +00002358 case Intrinsic::ppc_vsx_stxvw4x:
2359 case Intrinsic::ppc_vsx_stxvd2x: {
2360 // Turn PPC VSX stores into normal stores.
2361 Type *OpPtrTy = PointerType::getUnqual(II->getArgOperand(0)->getType());
Craig Topperbb4069e2017-07-07 23:16:26 +00002362 Value *Ptr = Builder.CreateBitCast(II->getArgOperand(1), OpPtrTy);
Bill Schmidt72954782014-11-12 04:19:40 +00002363 return new StoreInst(II->getArgOperand(0), Ptr, false, 1);
2364 }
Hal Finkel221f4672015-02-26 18:56:03 +00002365 case Intrinsic::ppc_qpx_qvlfs:
2366 // Turn PPC QPX qvlfs -> load if the pointer is known aligned.
Daniel Jasperaec2fa32016-12-19 08:22:17 +00002367 if (getOrEnforceKnownAlignment(II->getArgOperand(0), 16, DL, II, &AC,
Justin Bogner99798402016-08-05 01:06:44 +00002368 &DT) >= 16) {
Craig Topperbb4069e2017-07-07 23:16:26 +00002369 Type *VTy = VectorType::get(Builder.getFloatTy(),
Hal Finkelf0d68d72015-05-11 06:37:03 +00002370 II->getType()->getVectorNumElements());
Craig Topperbb4069e2017-07-07 23:16:26 +00002371 Value *Ptr = Builder.CreateBitCast(II->getArgOperand(0),
Hal Finkelf0d68d72015-05-11 06:37:03 +00002372 PointerType::getUnqual(VTy));
James Y Knight14359ef2019-02-01 20:44:24 +00002373 Value *Load = Builder.CreateLoad(VTy, Ptr);
Hal Finkelf0d68d72015-05-11 06:37:03 +00002374 return new FPExtInst(Load, II->getType());
Hal Finkel221f4672015-02-26 18:56:03 +00002375 }
2376 break;
2377 case Intrinsic::ppc_qpx_qvlfd:
2378 // Turn PPC QPX qvlfd -> load if the pointer is known aligned.
Daniel Jasperaec2fa32016-12-19 08:22:17 +00002379 if (getOrEnforceKnownAlignment(II->getArgOperand(0), 32, DL, II, &AC,
Justin Bogner99798402016-08-05 01:06:44 +00002380 &DT) >= 32) {
Craig Topperbb4069e2017-07-07 23:16:26 +00002381 Value *Ptr = Builder.CreateBitCast(II->getArgOperand(0),
Hal Finkel221f4672015-02-26 18:56:03 +00002382 PointerType::getUnqual(II->getType()));
James Y Knight14359ef2019-02-01 20:44:24 +00002383 return new LoadInst(II->getType(), Ptr);
Hal Finkel221f4672015-02-26 18:56:03 +00002384 }
2385 break;
2386 case Intrinsic::ppc_qpx_qvstfs:
2387 // Turn PPC QPX qvstfs -> store if the pointer is known aligned.
Daniel Jasperaec2fa32016-12-19 08:22:17 +00002388 if (getOrEnforceKnownAlignment(II->getArgOperand(1), 16, DL, II, &AC,
Justin Bogner99798402016-08-05 01:06:44 +00002389 &DT) >= 16) {
Craig Topperbb4069e2017-07-07 23:16:26 +00002390 Type *VTy = VectorType::get(Builder.getFloatTy(),
Hal Finkelf0d68d72015-05-11 06:37:03 +00002391 II->getArgOperand(0)->getType()->getVectorNumElements());
Craig Topperbb4069e2017-07-07 23:16:26 +00002392 Value *TOp = Builder.CreateFPTrunc(II->getArgOperand(0), VTy);
Hal Finkelf0d68d72015-05-11 06:37:03 +00002393 Type *OpPtrTy = PointerType::getUnqual(VTy);
Craig Topperbb4069e2017-07-07 23:16:26 +00002394 Value *Ptr = Builder.CreateBitCast(II->getArgOperand(1), OpPtrTy);
Hal Finkelf0d68d72015-05-11 06:37:03 +00002395 return new StoreInst(TOp, Ptr);
Hal Finkel221f4672015-02-26 18:56:03 +00002396 }
2397 break;
2398 case Intrinsic::ppc_qpx_qvstfd:
2399 // Turn PPC QPX qvstfd -> store if the pointer is known aligned.
Daniel Jasperaec2fa32016-12-19 08:22:17 +00002400 if (getOrEnforceKnownAlignment(II->getArgOperand(1), 32, DL, II, &AC,
Justin Bogner99798402016-08-05 01:06:44 +00002401 &DT) >= 32) {
Hal Finkel221f4672015-02-26 18:56:03 +00002402 Type *OpPtrTy =
2403 PointerType::getUnqual(II->getArgOperand(0)->getType());
Craig Topperbb4069e2017-07-07 23:16:26 +00002404 Value *Ptr = Builder.CreateBitCast(II->getArgOperand(1), OpPtrTy);
Hal Finkel221f4672015-02-26 18:56:03 +00002405 return new StoreInst(II->getArgOperand(0), Ptr);
2406 }
2407 break;
Simon Pilgrim20c607b2015-09-12 13:39:53 +00002408
Craig Topper83240032017-07-31 18:52:13 +00002409 case Intrinsic::x86_bmi_bextr_32:
2410 case Intrinsic::x86_bmi_bextr_64:
2411 case Intrinsic::x86_tbm_bextri_u32:
2412 case Intrinsic::x86_tbm_bextri_u64:
2413 // If the RHS is a constant we can try some simplifications.
2414 if (auto *C = dyn_cast<ConstantInt>(II->getArgOperand(1))) {
2415 uint64_t Shift = C->getZExtValue();
2416 uint64_t Length = (Shift >> 8) & 0xff;
2417 Shift &= 0xff;
2418 unsigned BitWidth = II->getType()->getIntegerBitWidth();
2419 // If the length is 0 or the shift is out of range, replace with zero.
2420 if (Length == 0 || Shift >= BitWidth)
2421 return replaceInstUsesWith(CI, ConstantInt::get(II->getType(), 0));
2422 // If the LHS is also a constant, we can completely constant fold this.
2423 if (auto *InC = dyn_cast<ConstantInt>(II->getArgOperand(0))) {
2424 uint64_t Result = InC->getZExtValue() >> Shift;
2425 if (Length > BitWidth)
2426 Length = BitWidth;
2427 Result &= maskTrailingOnes<uint64_t>(Length);
2428 return replaceInstUsesWith(CI, ConstantInt::get(II->getType(), Result));
2429 }
2430 // TODO should we turn this into 'and' if shift is 0? Or 'shl' if we
2431 // are only masking bits that a shift already cleared?
2432 }
2433 break;
2434
Craig Topper317a51e2017-07-31 18:52:15 +00002435 case Intrinsic::x86_bmi_bzhi_32:
2436 case Intrinsic::x86_bmi_bzhi_64:
2437 // If the RHS is a constant we can try some simplifications.
2438 if (auto *C = dyn_cast<ConstantInt>(II->getArgOperand(1))) {
2439 uint64_t Index = C->getZExtValue() & 0xff;
2440 unsigned BitWidth = II->getType()->getIntegerBitWidth();
2441 if (Index >= BitWidth)
2442 return replaceInstUsesWith(CI, II->getArgOperand(0));
2443 if (Index == 0)
2444 return replaceInstUsesWith(CI, ConstantInt::get(II->getType(), 0));
2445 // If the LHS is also a constant, we can completely constant fold this.
2446 if (auto *InC = dyn_cast<ConstantInt>(II->getArgOperand(0))) {
2447 uint64_t Result = InC->getZExtValue();
2448 Result &= maskTrailingOnes<uint64_t>(Index);
2449 return replaceInstUsesWith(CI, ConstantInt::get(II->getType(), Result));
2450 }
2451 // TODO should we convert this to an AND if the RHS is constant?
2452 }
2453 break;
2454
Simon Pilgrim20c607b2015-09-12 13:39:53 +00002455 case Intrinsic::x86_vcvtph2ps_128:
2456 case Intrinsic::x86_vcvtph2ps_256: {
2457 auto Arg = II->getArgOperand(0);
2458 auto ArgType = cast<VectorType>(Arg->getType());
2459 auto RetType = cast<VectorType>(II->getType());
2460 unsigned ArgWidth = ArgType->getNumElements();
2461 unsigned RetWidth = RetType->getNumElements();
2462 assert(RetWidth <= ArgWidth && "Unexpected input/return vector widths");
2463 assert(ArgType->isIntOrIntVectorTy() &&
2464 ArgType->getScalarSizeInBits() == 16 &&
2465 "CVTPH2PS input type should be 16-bit integer vector");
2466 assert(RetType->getScalarType()->isFloatTy() &&
2467 "CVTPH2PS output type should be 32-bit float vector");
2468
2469 // Constant folding: Convert to generic half to single conversion.
Simon Pilgrim48ffca02015-09-12 14:00:17 +00002470 if (isa<ConstantAggregateZero>(Arg))
Sanjay Patel4b198802016-02-01 22:23:39 +00002471 return replaceInstUsesWith(*II, ConstantAggregateZero::get(RetType));
Simon Pilgrim20c607b2015-09-12 13:39:53 +00002472
Simon Pilgrim48ffca02015-09-12 14:00:17 +00002473 if (isa<ConstantDataVector>(Arg)) {
Simon Pilgrim20c607b2015-09-12 13:39:53 +00002474 auto VectorHalfAsShorts = Arg;
2475 if (RetWidth < ArgWidth) {
Craig Topper99d1eab2016-06-12 00:41:19 +00002476 SmallVector<uint32_t, 8> SubVecMask;
Simon Pilgrim20c607b2015-09-12 13:39:53 +00002477 for (unsigned i = 0; i != RetWidth; ++i)
2478 SubVecMask.push_back((int)i);
Craig Topperbb4069e2017-07-07 23:16:26 +00002479 VectorHalfAsShorts = Builder.CreateShuffleVector(
Simon Pilgrim20c607b2015-09-12 13:39:53 +00002480 Arg, UndefValue::get(ArgType), SubVecMask);
2481 }
2482
2483 auto VectorHalfType =
2484 VectorType::get(Type::getHalfTy(II->getContext()), RetWidth);
2485 auto VectorHalfs =
Craig Topperbb4069e2017-07-07 23:16:26 +00002486 Builder.CreateBitCast(VectorHalfAsShorts, VectorHalfType);
2487 auto VectorFloats = Builder.CreateFPExt(VectorHalfs, RetType);
Sanjay Patel4b198802016-02-01 22:23:39 +00002488 return replaceInstUsesWith(*II, VectorFloats);
Simon Pilgrim20c607b2015-09-12 13:39:53 +00002489 }
2490
2491 // We only use the lowest lanes of the argument.
Simon Pilgrim996725e2015-09-19 11:41:53 +00002492 if (Value *V = SimplifyDemandedVectorEltsLow(Arg, ArgWidth, RetWidth)) {
Simon Pilgrim20c607b2015-09-12 13:39:53 +00002493 II->setArgOperand(0, V);
2494 return II;
2495 }
2496 break;
2497 }
2498
Chandler Carruthcf414cf2011-01-10 07:19:37 +00002499 case Intrinsic::x86_sse_cvtss2si:
2500 case Intrinsic::x86_sse_cvtss2si64:
2501 case Intrinsic::x86_sse_cvttss2si:
2502 case Intrinsic::x86_sse_cvttss2si64:
2503 case Intrinsic::x86_sse2_cvtsd2si:
2504 case Intrinsic::x86_sse2_cvtsd2si64:
2505 case Intrinsic::x86_sse2_cvttsd2si:
Craig Topperaeaa52c2016-12-14 07:46:12 +00002506 case Intrinsic::x86_sse2_cvttsd2si64:
2507 case Intrinsic::x86_avx512_vcvtss2si32:
2508 case Intrinsic::x86_avx512_vcvtss2si64:
2509 case Intrinsic::x86_avx512_vcvtss2usi32:
2510 case Intrinsic::x86_avx512_vcvtss2usi64:
2511 case Intrinsic::x86_avx512_vcvtsd2si32:
2512 case Intrinsic::x86_avx512_vcvtsd2si64:
2513 case Intrinsic::x86_avx512_vcvtsd2usi32:
2514 case Intrinsic::x86_avx512_vcvtsd2usi64:
2515 case Intrinsic::x86_avx512_cvttss2si:
2516 case Intrinsic::x86_avx512_cvttss2si64:
2517 case Intrinsic::x86_avx512_cvttss2usi:
2518 case Intrinsic::x86_avx512_cvttss2usi64:
2519 case Intrinsic::x86_avx512_cvttsd2si:
2520 case Intrinsic::x86_avx512_cvttsd2si64:
2521 case Intrinsic::x86_avx512_cvttsd2usi:
2522 case Intrinsic::x86_avx512_cvttsd2usi64: {
Chandler Carruthcf414cf2011-01-10 07:19:37 +00002523 // These intrinsics only demand the 0th element of their input vectors. If
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002524 // we can simplify the input based on that, do so now.
Simon Pilgrim996725e2015-09-19 11:41:53 +00002525 Value *Arg = II->getArgOperand(0);
2526 unsigned VWidth = Arg->getType()->getVectorNumElements();
2527 if (Value *V = SimplifyDemandedVectorEltsLow(Arg, VWidth, 1)) {
Gabor Greif5b1370e2010-06-28 16:50:57 +00002528 II->setArgOperand(0, V);
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002529 return II;
2530 }
Simon Pilgrim18617d12015-08-05 08:18:00 +00002531 break;
2532 }
2533
Simon Pilgrim91e3ac82016-06-07 08:18:35 +00002534 case Intrinsic::x86_mmx_pmovmskb:
2535 case Intrinsic::x86_sse_movmsk_ps:
2536 case Intrinsic::x86_sse2_movmsk_pd:
2537 case Intrinsic::x86_sse2_pmovmskb_128:
2538 case Intrinsic::x86_avx_movmsk_pd_256:
2539 case Intrinsic::x86_avx_movmsk_ps_256:
Eugene Zelenko7f0f9bc2017-10-24 21:24:53 +00002540 case Intrinsic::x86_avx2_pmovmskb:
Sanjay Patel2aa2dc72018-12-11 16:38:03 +00002541 if (Value *V = simplifyX86movmsk(*II, Builder))
Simon Pilgrim91e3ac82016-06-07 08:18:35 +00002542 return replaceInstUsesWith(*II, V);
2543 break;
Simon Pilgrim91e3ac82016-06-07 08:18:35 +00002544
Simon Pilgrim471efd22016-02-20 23:17:35 +00002545 case Intrinsic::x86_sse_comieq_ss:
2546 case Intrinsic::x86_sse_comige_ss:
2547 case Intrinsic::x86_sse_comigt_ss:
2548 case Intrinsic::x86_sse_comile_ss:
2549 case Intrinsic::x86_sse_comilt_ss:
2550 case Intrinsic::x86_sse_comineq_ss:
2551 case Intrinsic::x86_sse_ucomieq_ss:
2552 case Intrinsic::x86_sse_ucomige_ss:
2553 case Intrinsic::x86_sse_ucomigt_ss:
2554 case Intrinsic::x86_sse_ucomile_ss:
2555 case Intrinsic::x86_sse_ucomilt_ss:
2556 case Intrinsic::x86_sse_ucomineq_ss:
2557 case Intrinsic::x86_sse2_comieq_sd:
2558 case Intrinsic::x86_sse2_comige_sd:
2559 case Intrinsic::x86_sse2_comigt_sd:
2560 case Intrinsic::x86_sse2_comile_sd:
2561 case Intrinsic::x86_sse2_comilt_sd:
2562 case Intrinsic::x86_sse2_comineq_sd:
2563 case Intrinsic::x86_sse2_ucomieq_sd:
2564 case Intrinsic::x86_sse2_ucomige_sd:
2565 case Intrinsic::x86_sse2_ucomigt_sd:
2566 case Intrinsic::x86_sse2_ucomile_sd:
2567 case Intrinsic::x86_sse2_ucomilt_sd:
Craig Topperd9639532016-12-11 07:42:04 +00002568 case Intrinsic::x86_sse2_ucomineq_sd:
Craig Topperd00db692016-12-31 00:45:06 +00002569 case Intrinsic::x86_avx512_vcomi_ss:
2570 case Intrinsic::x86_avx512_vcomi_sd:
Craig Topperd9639532016-12-11 07:42:04 +00002571 case Intrinsic::x86_avx512_mask_cmp_ss:
2572 case Intrinsic::x86_avx512_mask_cmp_sd: {
Simon Pilgrim471efd22016-02-20 23:17:35 +00002573 // These intrinsics only demand the 0th element of their input vectors. If
2574 // we can simplify the input based on that, do so now.
Simon Pilgrim1c9a9f22016-04-24 17:57:27 +00002575 bool MadeChange = false;
Simon Pilgrim471efd22016-02-20 23:17:35 +00002576 Value *Arg0 = II->getArgOperand(0);
2577 Value *Arg1 = II->getArgOperand(1);
2578 unsigned VWidth = Arg0->getType()->getVectorNumElements();
2579 if (Value *V = SimplifyDemandedVectorEltsLow(Arg0, VWidth, 1)) {
2580 II->setArgOperand(0, V);
Simon Pilgrim1c9a9f22016-04-24 17:57:27 +00002581 MadeChange = true;
Simon Pilgrim471efd22016-02-20 23:17:35 +00002582 }
2583 if (Value *V = SimplifyDemandedVectorEltsLow(Arg1, VWidth, 1)) {
2584 II->setArgOperand(1, V);
Simon Pilgrim1c9a9f22016-04-24 17:57:27 +00002585 MadeChange = true;
Simon Pilgrim471efd22016-02-20 23:17:35 +00002586 }
Simon Pilgrim1c9a9f22016-04-24 17:57:27 +00002587 if (MadeChange)
2588 return II;
Simon Pilgrim471efd22016-02-20 23:17:35 +00002589 break;
2590 }
Craig Topper31cbe752018-06-27 15:57:53 +00002591 case Intrinsic::x86_avx512_cmp_pd_128:
2592 case Intrinsic::x86_avx512_cmp_pd_256:
2593 case Intrinsic::x86_avx512_cmp_pd_512:
2594 case Intrinsic::x86_avx512_cmp_ps_128:
2595 case Intrinsic::x86_avx512_cmp_ps_256:
2596 case Intrinsic::x86_avx512_cmp_ps_512: {
Michael Zuckerman16b20d22017-04-16 13:26:08 +00002597 // Folding cmp(sub(a,b),0) -> cmp(a,b) and cmp(0,sub(a,b)) -> cmp(b,a)
2598 Value *Arg0 = II->getArgOperand(0);
2599 Value *Arg1 = II->getArgOperand(1);
Sanjay Patel93e64dd2018-03-25 21:16:33 +00002600 bool Arg0IsZero = match(Arg0, m_PosZeroFP());
Michael Zuckerman16b20d22017-04-16 13:26:08 +00002601 if (Arg0IsZero)
2602 std::swap(Arg0, Arg1);
2603 Value *A, *B;
2604 // This fold requires only the NINF(not +/- inf) since inf minus
2605 // inf is nan.
2606 // NSZ(No Signed Zeros) is not needed because zeros of any sign are
2607 // equal for both compares.
2608 // NNAN is not needed because nans compare the same for both compares.
2609 // The compare intrinsic uses the above assumptions and therefore
2610 // doesn't require additional flags.
2611 if ((match(Arg0, m_OneUse(m_FSub(m_Value(A), m_Value(B)))) &&
Sanjay Patel93e64dd2018-03-25 21:16:33 +00002612 match(Arg1, m_PosZeroFP()) && isa<Instruction>(Arg0) &&
Michael Zuckerman16b20d22017-04-16 13:26:08 +00002613 cast<Instruction>(Arg0)->getFastMathFlags().noInfs())) {
2614 if (Arg0IsZero)
2615 std::swap(A, B);
2616 II->setArgOperand(0, A);
2617 II->setArgOperand(1, B);
2618 return II;
2619 }
2620 break;
2621 }
Simon Pilgrim471efd22016-02-20 23:17:35 +00002622
Craig Topper98a79932018-06-10 06:01:36 +00002623 case Intrinsic::x86_avx512_add_ps_512:
2624 case Intrinsic::x86_avx512_div_ps_512:
2625 case Intrinsic::x86_avx512_mul_ps_512:
2626 case Intrinsic::x86_avx512_sub_ps_512:
2627 case Intrinsic::x86_avx512_add_pd_512:
2628 case Intrinsic::x86_avx512_div_pd_512:
2629 case Intrinsic::x86_avx512_mul_pd_512:
2630 case Intrinsic::x86_avx512_sub_pd_512:
Craig Topper020b2282016-12-27 00:23:16 +00002631 // If the rounding mode is CUR_DIRECTION(4) we can turn these into regular
2632 // IR operations.
Craig Topper98a79932018-06-10 06:01:36 +00002633 if (auto *R = dyn_cast<ConstantInt>(II->getArgOperand(2))) {
Craig Topper020b2282016-12-27 00:23:16 +00002634 if (R->getValue() == 4) {
2635 Value *Arg0 = II->getArgOperand(0);
2636 Value *Arg1 = II->getArgOperand(1);
2637
2638 Value *V;
Sanjay Patel62f457b2019-05-06 15:35:02 +00002639 switch (IID) {
Craig Topper020b2282016-12-27 00:23:16 +00002640 default: llvm_unreachable("Case stmts out of sync!");
Craig Topper98a79932018-06-10 06:01:36 +00002641 case Intrinsic::x86_avx512_add_ps_512:
2642 case Intrinsic::x86_avx512_add_pd_512:
Craig Topperbb4069e2017-07-07 23:16:26 +00002643 V = Builder.CreateFAdd(Arg0, Arg1);
Craig Topper020b2282016-12-27 00:23:16 +00002644 break;
Craig Topper98a79932018-06-10 06:01:36 +00002645 case Intrinsic::x86_avx512_sub_ps_512:
2646 case Intrinsic::x86_avx512_sub_pd_512:
Craig Topperbb4069e2017-07-07 23:16:26 +00002647 V = Builder.CreateFSub(Arg0, Arg1);
Craig Topper020b2282016-12-27 00:23:16 +00002648 break;
Craig Topper98a79932018-06-10 06:01:36 +00002649 case Intrinsic::x86_avx512_mul_ps_512:
2650 case Intrinsic::x86_avx512_mul_pd_512:
Craig Topperbb4069e2017-07-07 23:16:26 +00002651 V = Builder.CreateFMul(Arg0, Arg1);
Craig Topper020b2282016-12-27 00:23:16 +00002652 break;
Craig Topper98a79932018-06-10 06:01:36 +00002653 case Intrinsic::x86_avx512_div_ps_512:
2654 case Intrinsic::x86_avx512_div_pd_512:
Craig Topperbb4069e2017-07-07 23:16:26 +00002655 V = Builder.CreateFDiv(Arg0, Arg1);
Craig Topper020b2282016-12-27 00:23:16 +00002656 break;
2657 }
2658
Craig Topper020b2282016-12-27 00:23:16 +00002659 return replaceInstUsesWith(*II, V);
2660 }
2661 }
2662 break;
2663
Craig Topper790d0fa2016-12-11 07:42:01 +00002664 case Intrinsic::x86_avx512_mask_add_ss_round:
2665 case Intrinsic::x86_avx512_mask_div_ss_round:
2666 case Intrinsic::x86_avx512_mask_mul_ss_round:
2667 case Intrinsic::x86_avx512_mask_sub_ss_round:
Craig Topper790d0fa2016-12-11 07:42:01 +00002668 case Intrinsic::x86_avx512_mask_add_sd_round:
2669 case Intrinsic::x86_avx512_mask_div_sd_round:
2670 case Intrinsic::x86_avx512_mask_mul_sd_round:
2671 case Intrinsic::x86_avx512_mask_sub_sd_round:
Craig Topper7b788ada2016-12-26 06:33:19 +00002672 // If the rounding mode is CUR_DIRECTION(4) we can turn these into regular
2673 // IR operations.
2674 if (auto *R = dyn_cast<ConstantInt>(II->getArgOperand(4))) {
2675 if (R->getValue() == 4) {
Craig Topper7f8540b2016-12-27 01:56:30 +00002676 // Extract the element as scalars.
2677 Value *Arg0 = II->getArgOperand(0);
2678 Value *Arg1 = II->getArgOperand(1);
Craig Topperbb4069e2017-07-07 23:16:26 +00002679 Value *LHS = Builder.CreateExtractElement(Arg0, (uint64_t)0);
2680 Value *RHS = Builder.CreateExtractElement(Arg1, (uint64_t)0);
Craig Topper7b788ada2016-12-26 06:33:19 +00002681
Craig Topper7f8540b2016-12-27 01:56:30 +00002682 Value *V;
Sanjay Patel62f457b2019-05-06 15:35:02 +00002683 switch (IID) {
Craig Topper7f8540b2016-12-27 01:56:30 +00002684 default: llvm_unreachable("Case stmts out of sync!");
2685 case Intrinsic::x86_avx512_mask_add_ss_round:
2686 case Intrinsic::x86_avx512_mask_add_sd_round:
Craig Topperbb4069e2017-07-07 23:16:26 +00002687 V = Builder.CreateFAdd(LHS, RHS);
Craig Topper7f8540b2016-12-27 01:56:30 +00002688 break;
2689 case Intrinsic::x86_avx512_mask_sub_ss_round:
2690 case Intrinsic::x86_avx512_mask_sub_sd_round:
Craig Topperbb4069e2017-07-07 23:16:26 +00002691 V = Builder.CreateFSub(LHS, RHS);
Craig Topper7f8540b2016-12-27 01:56:30 +00002692 break;
2693 case Intrinsic::x86_avx512_mask_mul_ss_round:
2694 case Intrinsic::x86_avx512_mask_mul_sd_round:
Craig Topperbb4069e2017-07-07 23:16:26 +00002695 V = Builder.CreateFMul(LHS, RHS);
Craig Topper7f8540b2016-12-27 01:56:30 +00002696 break;
2697 case Intrinsic::x86_avx512_mask_div_ss_round:
2698 case Intrinsic::x86_avx512_mask_div_sd_round:
Craig Topperbb4069e2017-07-07 23:16:26 +00002699 V = Builder.CreateFDiv(LHS, RHS);
Craig Topper7f8540b2016-12-27 01:56:30 +00002700 break;
Craig Topper7b788ada2016-12-26 06:33:19 +00002701 }
Craig Topper7f8540b2016-12-27 01:56:30 +00002702
2703 // Handle the masking aspect of the intrinsic.
Craig Topper7f8540b2016-12-27 01:56:30 +00002704 Value *Mask = II->getArgOperand(3);
Craig Topper99163632016-12-30 23:06:28 +00002705 auto *C = dyn_cast<ConstantInt>(Mask);
2706 // We don't need a select if we know the mask bit is a 1.
2707 if (!C || !C->getValue()[0]) {
2708 // Cast the mask to an i1 vector and then extract the lowest element.
Craig Topperbb4069e2017-07-07 23:16:26 +00002709 auto *MaskTy = VectorType::get(Builder.getInt1Ty(),
Craig Topper7f8540b2016-12-27 01:56:30 +00002710 cast<IntegerType>(Mask->getType())->getBitWidth());
Craig Topperbb4069e2017-07-07 23:16:26 +00002711 Mask = Builder.CreateBitCast(Mask, MaskTy);
2712 Mask = Builder.CreateExtractElement(Mask, (uint64_t)0);
Craig Topper99163632016-12-30 23:06:28 +00002713 // Extract the lowest element from the passthru operand.
Craig Topperbb4069e2017-07-07 23:16:26 +00002714 Value *Passthru = Builder.CreateExtractElement(II->getArgOperand(2),
Craig Topper99163632016-12-30 23:06:28 +00002715 (uint64_t)0);
Craig Topperbb4069e2017-07-07 23:16:26 +00002716 V = Builder.CreateSelect(Mask, V, Passthru);
Craig Topper99163632016-12-30 23:06:28 +00002717 }
Craig Topper7f8540b2016-12-27 01:56:30 +00002718
2719 // Insert the result back into the original argument 0.
Craig Topperbb4069e2017-07-07 23:16:26 +00002720 V = Builder.CreateInsertElement(Arg0, V, (uint64_t)0);
Craig Topper7f8540b2016-12-27 01:56:30 +00002721
2722 return replaceInstUsesWith(*II, V);
Craig Topper7b788ada2016-12-26 06:33:19 +00002723 }
2724 }
Philip Reamesc71e9962019-01-30 19:21:11 +00002725 break;
Craig Topper7b788ada2016-12-26 06:33:19 +00002726
Simon Pilgrima3a72b42015-08-10 20:21:15 +00002727 // Constant fold ashr( <A x Bi>, Ci ).
Simon Pilgrimbecd5e82015-08-13 07:39:03 +00002728 // Constant fold lshr( <A x Bi>, Ci ).
2729 // Constant fold shl( <A x Bi>, Ci ).
Simon Pilgrima3a72b42015-08-10 20:21:15 +00002730 case Intrinsic::x86_sse2_psrai_d:
2731 case Intrinsic::x86_sse2_psrai_w:
Simon Pilgrima3a72b42015-08-10 20:21:15 +00002732 case Intrinsic::x86_avx2_psrai_d:
2733 case Intrinsic::x86_avx2_psrai_w:
Craig Topper8b831cb2016-11-13 01:51:55 +00002734 case Intrinsic::x86_avx512_psrai_q_128:
2735 case Intrinsic::x86_avx512_psrai_q_256:
2736 case Intrinsic::x86_avx512_psrai_d_512:
2737 case Intrinsic::x86_avx512_psrai_q_512:
2738 case Intrinsic::x86_avx512_psrai_w_512:
Simon Pilgrim18617d12015-08-05 08:18:00 +00002739 case Intrinsic::x86_sse2_psrli_d:
2740 case Intrinsic::x86_sse2_psrli_q:
2741 case Intrinsic::x86_sse2_psrli_w:
Simon Pilgrim18617d12015-08-05 08:18:00 +00002742 case Intrinsic::x86_avx2_psrli_d:
2743 case Intrinsic::x86_avx2_psrli_q:
2744 case Intrinsic::x86_avx2_psrli_w:
Craig Topper8b831cb2016-11-13 01:51:55 +00002745 case Intrinsic::x86_avx512_psrli_d_512:
2746 case Intrinsic::x86_avx512_psrli_q_512:
2747 case Intrinsic::x86_avx512_psrli_w_512:
Michael J. Spencerdee4b2c2014-04-24 00:58:18 +00002748 case Intrinsic::x86_sse2_pslli_d:
2749 case Intrinsic::x86_sse2_pslli_q:
2750 case Intrinsic::x86_sse2_pslli_w:
Simon Pilgrim18617d12015-08-05 08:18:00 +00002751 case Intrinsic::x86_avx2_pslli_d:
2752 case Intrinsic::x86_avx2_pslli_q:
2753 case Intrinsic::x86_avx2_pslli_w:
Craig Topper8b831cb2016-11-13 01:51:55 +00002754 case Intrinsic::x86_avx512_pslli_d_512:
2755 case Intrinsic::x86_avx512_pslli_q_512:
2756 case Intrinsic::x86_avx512_pslli_w_512:
Craig Topperbb4069e2017-07-07 23:16:26 +00002757 if (Value *V = simplifyX86immShift(*II, Builder))
Sanjay Patel4b198802016-02-01 22:23:39 +00002758 return replaceInstUsesWith(*II, V);
Simon Pilgrim18617d12015-08-05 08:18:00 +00002759 break;
2760
Simon Pilgrimbecd5e82015-08-13 07:39:03 +00002761 case Intrinsic::x86_sse2_psra_d:
2762 case Intrinsic::x86_sse2_psra_w:
2763 case Intrinsic::x86_avx2_psra_d:
2764 case Intrinsic::x86_avx2_psra_w:
Craig Topper8b831cb2016-11-13 01:51:55 +00002765 case Intrinsic::x86_avx512_psra_q_128:
2766 case Intrinsic::x86_avx512_psra_q_256:
2767 case Intrinsic::x86_avx512_psra_d_512:
2768 case Intrinsic::x86_avx512_psra_q_512:
2769 case Intrinsic::x86_avx512_psra_w_512:
Simon Pilgrimbecd5e82015-08-13 07:39:03 +00002770 case Intrinsic::x86_sse2_psrl_d:
2771 case Intrinsic::x86_sse2_psrl_q:
2772 case Intrinsic::x86_sse2_psrl_w:
2773 case Intrinsic::x86_avx2_psrl_d:
2774 case Intrinsic::x86_avx2_psrl_q:
2775 case Intrinsic::x86_avx2_psrl_w:
Craig Topper8b831cb2016-11-13 01:51:55 +00002776 case Intrinsic::x86_avx512_psrl_d_512:
2777 case Intrinsic::x86_avx512_psrl_q_512:
2778 case Intrinsic::x86_avx512_psrl_w_512:
Simon Pilgrimbecd5e82015-08-13 07:39:03 +00002779 case Intrinsic::x86_sse2_psll_d:
2780 case Intrinsic::x86_sse2_psll_q:
2781 case Intrinsic::x86_sse2_psll_w:
2782 case Intrinsic::x86_avx2_psll_d:
2783 case Intrinsic::x86_avx2_psll_q:
Craig Topper8b831cb2016-11-13 01:51:55 +00002784 case Intrinsic::x86_avx2_psll_w:
2785 case Intrinsic::x86_avx512_psll_d_512:
2786 case Intrinsic::x86_avx512_psll_q_512:
2787 case Intrinsic::x86_avx512_psll_w_512: {
Craig Topperbb4069e2017-07-07 23:16:26 +00002788 if (Value *V = simplifyX86immShift(*II, Builder))
Sanjay Patel4b198802016-02-01 22:23:39 +00002789 return replaceInstUsesWith(*II, V);
Simon Pilgrimbecd5e82015-08-13 07:39:03 +00002790
2791 // SSE2/AVX2 uses only the first 64-bits of the 128-bit vector
2792 // operand to compute the shift amount.
Simon Pilgrim996725e2015-09-19 11:41:53 +00002793 Value *Arg1 = II->getArgOperand(1);
2794 assert(Arg1->getType()->getPrimitiveSizeInBits() == 128 &&
Simon Pilgrimbecd5e82015-08-13 07:39:03 +00002795 "Unexpected packed shift size");
Simon Pilgrim996725e2015-09-19 11:41:53 +00002796 unsigned VWidth = Arg1->getType()->getVectorNumElements();
Simon Pilgrimbecd5e82015-08-13 07:39:03 +00002797
Simon Pilgrim996725e2015-09-19 11:41:53 +00002798 if (Value *V = SimplifyDemandedVectorEltsLow(Arg1, VWidth, VWidth / 2)) {
Simon Pilgrimbecd5e82015-08-13 07:39:03 +00002799 II->setArgOperand(1, V);
2800 return II;
2801 }
2802 break;
2803 }
2804
Simon Pilgrimdb9893f2016-06-07 10:27:15 +00002805 case Intrinsic::x86_avx2_psllv_d:
2806 case Intrinsic::x86_avx2_psllv_d_256:
2807 case Intrinsic::x86_avx2_psllv_q:
2808 case Intrinsic::x86_avx2_psllv_q_256:
Craig Topperb4173a52016-11-13 07:26:19 +00002809 case Intrinsic::x86_avx512_psllv_d_512:
2810 case Intrinsic::x86_avx512_psllv_q_512:
Craig Topper1de753f2016-11-18 06:04:33 +00002811 case Intrinsic::x86_avx512_psllv_w_128:
2812 case Intrinsic::x86_avx512_psllv_w_256:
2813 case Intrinsic::x86_avx512_psllv_w_512:
Simon Pilgrimdb9893f2016-06-07 10:27:15 +00002814 case Intrinsic::x86_avx2_psrav_d:
2815 case Intrinsic::x86_avx2_psrav_d_256:
Craig Topperb4173a52016-11-13 07:26:19 +00002816 case Intrinsic::x86_avx512_psrav_q_128:
2817 case Intrinsic::x86_avx512_psrav_q_256:
2818 case Intrinsic::x86_avx512_psrav_d_512:
2819 case Intrinsic::x86_avx512_psrav_q_512:
Craig Topper1de753f2016-11-18 06:04:33 +00002820 case Intrinsic::x86_avx512_psrav_w_128:
2821 case Intrinsic::x86_avx512_psrav_w_256:
2822 case Intrinsic::x86_avx512_psrav_w_512:
Simon Pilgrimdb9893f2016-06-07 10:27:15 +00002823 case Intrinsic::x86_avx2_psrlv_d:
2824 case Intrinsic::x86_avx2_psrlv_d_256:
2825 case Intrinsic::x86_avx2_psrlv_q:
2826 case Intrinsic::x86_avx2_psrlv_q_256:
Craig Topperb4173a52016-11-13 07:26:19 +00002827 case Intrinsic::x86_avx512_psrlv_d_512:
2828 case Intrinsic::x86_avx512_psrlv_q_512:
Craig Topper1de753f2016-11-18 06:04:33 +00002829 case Intrinsic::x86_avx512_psrlv_w_128:
2830 case Intrinsic::x86_avx512_psrlv_w_256:
2831 case Intrinsic::x86_avx512_psrlv_w_512:
Craig Topperbb4069e2017-07-07 23:16:26 +00002832 if (Value *V = simplifyX86varShift(*II, Builder))
Simon Pilgrimdb9893f2016-06-07 10:27:15 +00002833 return replaceInstUsesWith(*II, V);
2834 break;
2835
Simon Pilgrim6f6b2792017-01-25 14:37:24 +00002836 case Intrinsic::x86_sse2_packssdw_128:
2837 case Intrinsic::x86_sse2_packsswb_128:
2838 case Intrinsic::x86_avx2_packssdw:
2839 case Intrinsic::x86_avx2_packsswb:
Craig Topper3731f4d2017-02-16 07:35:23 +00002840 case Intrinsic::x86_avx512_packssdw_512:
2841 case Intrinsic::x86_avx512_packsswb_512:
Simon Pilgrim55f14da2019-04-24 16:53:17 +00002842 if (Value *V = simplifyX86pack(*II, Builder, true))
Simon Pilgrim6f6b2792017-01-25 14:37:24 +00002843 return replaceInstUsesWith(*II, V);
2844 break;
2845
2846 case Intrinsic::x86_sse2_packuswb_128:
2847 case Intrinsic::x86_sse41_packusdw:
2848 case Intrinsic::x86_avx2_packusdw:
2849 case Intrinsic::x86_avx2_packuswb:
Craig Topper3731f4d2017-02-16 07:35:23 +00002850 case Intrinsic::x86_avx512_packusdw_512:
2851 case Intrinsic::x86_avx512_packuswb_512:
Simon Pilgrim55f14da2019-04-24 16:53:17 +00002852 if (Value *V = simplifyX86pack(*II, Builder, false))
Simon Pilgrim6f6b2792017-01-25 14:37:24 +00002853 return replaceInstUsesWith(*II, V);
2854 break;
2855
Craig Topper911025b2018-05-13 21:56:32 +00002856 case Intrinsic::x86_pclmulqdq:
2857 case Intrinsic::x86_pclmulqdq_256:
2858 case Intrinsic::x86_pclmulqdq_512: {
Craig Topperb6122122017-01-26 05:17:13 +00002859 if (auto *C = dyn_cast<ConstantInt>(II->getArgOperand(2))) {
2860 unsigned Imm = C->getZExtValue();
2861
2862 bool MadeChange = false;
2863 Value *Arg0 = II->getArgOperand(0);
2864 Value *Arg1 = II->getArgOperand(1);
2865 unsigned VWidth = Arg0->getType()->getVectorNumElements();
Craig Topperb6122122017-01-26 05:17:13 +00002866
2867 APInt UndefElts1(VWidth, 0);
Craig Topper911025b2018-05-13 21:56:32 +00002868 APInt DemandedElts1 = APInt::getSplat(VWidth,
2869 APInt(2, (Imm & 0x01) ? 2 : 1));
2870 if (Value *V = SimplifyDemandedVectorElts(Arg0, DemandedElts1,
Craig Topperb6122122017-01-26 05:17:13 +00002871 UndefElts1)) {
2872 II->setArgOperand(0, V);
2873 MadeChange = true;
2874 }
2875
2876 APInt UndefElts2(VWidth, 0);
Craig Topper911025b2018-05-13 21:56:32 +00002877 APInt DemandedElts2 = APInt::getSplat(VWidth,
2878 APInt(2, (Imm & 0x10) ? 2 : 1));
2879 if (Value *V = SimplifyDemandedVectorElts(Arg1, DemandedElts2,
Craig Topperb6122122017-01-26 05:17:13 +00002880 UndefElts2)) {
2881 II->setArgOperand(1, V);
2882 MadeChange = true;
2883 }
2884
Craig Topper911025b2018-05-13 21:56:32 +00002885 // If either input elements are undef, the result is zero.
2886 if (DemandedElts1.isSubsetOf(UndefElts1) ||
2887 DemandedElts2.isSubsetOf(UndefElts2))
Craig Topperb6122122017-01-26 05:17:13 +00002888 return replaceInstUsesWith(*II,
2889 ConstantAggregateZero::get(II->getType()));
2890
2891 if (MadeChange)
2892 return II;
2893 }
2894 break;
2895 }
2896
Sanjay Patelc86867c2015-04-16 17:52:13 +00002897 case Intrinsic::x86_sse41_insertps:
Craig Topperbb4069e2017-07-07 23:16:26 +00002898 if (Value *V = simplifyX86insertps(*II, Builder))
Sanjay Patel4b198802016-02-01 22:23:39 +00002899 return replaceInstUsesWith(*II, V);
Sanjay Patelc86867c2015-04-16 17:52:13 +00002900 break;
Simon Pilgrim54fcd622015-07-25 20:41:00 +00002901
Simon Pilgrim61116dd2015-09-17 20:32:45 +00002902 case Intrinsic::x86_sse4a_extrq: {
Simon Pilgrim61116dd2015-09-17 20:32:45 +00002903 Value *Op0 = II->getArgOperand(0);
2904 Value *Op1 = II->getArgOperand(1);
2905 unsigned VWidth0 = Op0->getType()->getVectorNumElements();
2906 unsigned VWidth1 = Op1->getType()->getVectorNumElements();
Simon Pilgrim216b1bf2015-10-17 11:40:05 +00002907 assert(Op0->getType()->getPrimitiveSizeInBits() == 128 &&
2908 Op1->getType()->getPrimitiveSizeInBits() == 128 && VWidth0 == 2 &&
2909 VWidth1 == 16 && "Unexpected operand sizes");
Simon Pilgrim61116dd2015-09-17 20:32:45 +00002910
Simon Pilgrim216b1bf2015-10-17 11:40:05 +00002911 // See if we're dealing with constant values.
2912 Constant *C1 = dyn_cast<Constant>(Op1);
2913 ConstantInt *CILength =
Andrea Di Biagio8df5b9c2016-09-07 12:03:03 +00002914 C1 ? dyn_cast_or_null<ConstantInt>(C1->getAggregateElement((unsigned)0))
Simon Pilgrim216b1bf2015-10-17 11:40:05 +00002915 : nullptr;
2916 ConstantInt *CIIndex =
Andrea Di Biagio8df5b9c2016-09-07 12:03:03 +00002917 C1 ? dyn_cast_or_null<ConstantInt>(C1->getAggregateElement((unsigned)1))
Simon Pilgrim216b1bf2015-10-17 11:40:05 +00002918 : nullptr;
2919
2920 // Attempt to simplify to a constant, shuffle vector or EXTRQI call.
Craig Topperbb4069e2017-07-07 23:16:26 +00002921 if (Value *V = simplifyX86extrq(*II, Op0, CILength, CIIndex, Builder))
Sanjay Patel4b198802016-02-01 22:23:39 +00002922 return replaceInstUsesWith(*II, V);
Simon Pilgrim216b1bf2015-10-17 11:40:05 +00002923
2924 // EXTRQ only uses the lowest 64-bits of the first 128-bit vector
2925 // operands and the lowest 16-bits of the second.
Simon Pilgrim1c9a9f22016-04-24 17:57:27 +00002926 bool MadeChange = false;
Simon Pilgrim61116dd2015-09-17 20:32:45 +00002927 if (Value *V = SimplifyDemandedVectorEltsLow(Op0, VWidth0, 1)) {
2928 II->setArgOperand(0, V);
Simon Pilgrim1c9a9f22016-04-24 17:57:27 +00002929 MadeChange = true;
Simon Pilgrim61116dd2015-09-17 20:32:45 +00002930 }
2931 if (Value *V = SimplifyDemandedVectorEltsLow(Op1, VWidth1, 2)) {
2932 II->setArgOperand(1, V);
Simon Pilgrim1c9a9f22016-04-24 17:57:27 +00002933 MadeChange = true;
Simon Pilgrim61116dd2015-09-17 20:32:45 +00002934 }
Simon Pilgrim1c9a9f22016-04-24 17:57:27 +00002935 if (MadeChange)
2936 return II;
Simon Pilgrim61116dd2015-09-17 20:32:45 +00002937 break;
2938 }
2939
2940 case Intrinsic::x86_sse4a_extrqi: {
Simon Pilgrim216b1bf2015-10-17 11:40:05 +00002941 // EXTRQI: Extract Length bits starting from Index. Zero pad the remaining
2942 // bits of the lower 64-bits. The upper 64-bits are undefined.
2943 Value *Op0 = II->getArgOperand(0);
2944 unsigned VWidth = Op0->getType()->getVectorNumElements();
2945 assert(Op0->getType()->getPrimitiveSizeInBits() == 128 && VWidth == 2 &&
2946 "Unexpected operand size");
Simon Pilgrim61116dd2015-09-17 20:32:45 +00002947
Simon Pilgrim216b1bf2015-10-17 11:40:05 +00002948 // See if we're dealing with constant values.
2949 ConstantInt *CILength = dyn_cast<ConstantInt>(II->getArgOperand(1));
2950 ConstantInt *CIIndex = dyn_cast<ConstantInt>(II->getArgOperand(2));
2951
2952 // Attempt to simplify to a constant or shuffle vector.
Craig Topperbb4069e2017-07-07 23:16:26 +00002953 if (Value *V = simplifyX86extrq(*II, Op0, CILength, CIIndex, Builder))
Sanjay Patel4b198802016-02-01 22:23:39 +00002954 return replaceInstUsesWith(*II, V);
Simon Pilgrim216b1bf2015-10-17 11:40:05 +00002955
2956 // EXTRQI only uses the lowest 64-bits of the first 128-bit vector
2957 // operand.
2958 if (Value *V = SimplifyDemandedVectorEltsLow(Op0, VWidth, 1)) {
Simon Pilgrim61116dd2015-09-17 20:32:45 +00002959 II->setArgOperand(0, V);
2960 return II;
2961 }
2962 break;
2963 }
2964
2965 case Intrinsic::x86_sse4a_insertq: {
Simon Pilgrim216b1bf2015-10-17 11:40:05 +00002966 Value *Op0 = II->getArgOperand(0);
2967 Value *Op1 = II->getArgOperand(1);
2968 unsigned VWidth = Op0->getType()->getVectorNumElements();
2969 assert(Op0->getType()->getPrimitiveSizeInBits() == 128 &&
2970 Op1->getType()->getPrimitiveSizeInBits() == 128 && VWidth == 2 &&
2971 Op1->getType()->getVectorNumElements() == 2 &&
2972 "Unexpected operand size");
Simon Pilgrim61116dd2015-09-17 20:32:45 +00002973
Simon Pilgrim216b1bf2015-10-17 11:40:05 +00002974 // See if we're dealing with constant values.
2975 Constant *C1 = dyn_cast<Constant>(Op1);
2976 ConstantInt *CI11 =
Andrea Di Biagiof3fd3162016-09-07 12:47:53 +00002977 C1 ? dyn_cast_or_null<ConstantInt>(C1->getAggregateElement((unsigned)1))
Simon Pilgrim216b1bf2015-10-17 11:40:05 +00002978 : nullptr;
2979
2980 // Attempt to simplify to a constant, shuffle vector or INSERTQI call.
2981 if (CI11) {
Benjamin Kramer46e38f32016-06-08 10:01:20 +00002982 const APInt &V11 = CI11->getValue();
Simon Pilgrim216b1bf2015-10-17 11:40:05 +00002983 APInt Len = V11.zextOrTrunc(6);
2984 APInt Idx = V11.lshr(8).zextOrTrunc(6);
Craig Topperbb4069e2017-07-07 23:16:26 +00002985 if (Value *V = simplifyX86insertq(*II, Op0, Op1, Len, Idx, Builder))
Sanjay Patel4b198802016-02-01 22:23:39 +00002986 return replaceInstUsesWith(*II, V);
Simon Pilgrim216b1bf2015-10-17 11:40:05 +00002987 }
2988
2989 // INSERTQ only uses the lowest 64-bits of the first 128-bit vector
2990 // operand.
2991 if (Value *V = SimplifyDemandedVectorEltsLow(Op0, VWidth, 1)) {
Simon Pilgrim61116dd2015-09-17 20:32:45 +00002992 II->setArgOperand(0, V);
2993 return II;
2994 }
2995 break;
2996 }
2997
Filipe Cabecinhas1a805952014-04-24 00:38:14 +00002998 case Intrinsic::x86_sse4a_insertqi: {
Simon Pilgrim216b1bf2015-10-17 11:40:05 +00002999 // INSERTQI: Extract lowest Length bits from lower half of second source and
3000 // insert over first source starting at Index bit. The upper 64-bits are
3001 // undefined.
Simon Pilgrim61116dd2015-09-17 20:32:45 +00003002 Value *Op0 = II->getArgOperand(0);
3003 Value *Op1 = II->getArgOperand(1);
3004 unsigned VWidth0 = Op0->getType()->getVectorNumElements();
3005 unsigned VWidth1 = Op1->getType()->getVectorNumElements();
Simon Pilgrim216b1bf2015-10-17 11:40:05 +00003006 assert(Op0->getType()->getPrimitiveSizeInBits() == 128 &&
3007 Op1->getType()->getPrimitiveSizeInBits() == 128 && VWidth0 == 2 &&
3008 VWidth1 == 2 && "Unexpected operand sizes");
Simon Pilgrim61116dd2015-09-17 20:32:45 +00003009
Simon Pilgrim216b1bf2015-10-17 11:40:05 +00003010 // See if we're dealing with constant values.
3011 ConstantInt *CILength = dyn_cast<ConstantInt>(II->getArgOperand(2));
3012 ConstantInt *CIIndex = dyn_cast<ConstantInt>(II->getArgOperand(3));
3013
3014 // Attempt to simplify to a constant or shuffle vector.
3015 if (CILength && CIIndex) {
3016 APInt Len = CILength->getValue().zextOrTrunc(6);
3017 APInt Idx = CIIndex->getValue().zextOrTrunc(6);
Craig Topperbb4069e2017-07-07 23:16:26 +00003018 if (Value *V = simplifyX86insertq(*II, Op0, Op1, Len, Idx, Builder))
Sanjay Patel4b198802016-02-01 22:23:39 +00003019 return replaceInstUsesWith(*II, V);
Simon Pilgrim216b1bf2015-10-17 11:40:05 +00003020 }
3021
3022 // INSERTQI only uses the lowest 64-bits of the first two 128-bit vector
3023 // operands.
Simon Pilgrim1c9a9f22016-04-24 17:57:27 +00003024 bool MadeChange = false;
Simon Pilgrim61116dd2015-09-17 20:32:45 +00003025 if (Value *V = SimplifyDemandedVectorEltsLow(Op0, VWidth0, 1)) {
3026 II->setArgOperand(0, V);
Simon Pilgrim1c9a9f22016-04-24 17:57:27 +00003027 MadeChange = true;
Simon Pilgrim61116dd2015-09-17 20:32:45 +00003028 }
Simon Pilgrim61116dd2015-09-17 20:32:45 +00003029 if (Value *V = SimplifyDemandedVectorEltsLow(Op1, VWidth1, 1)) {
3030 II->setArgOperand(1, V);
Simon Pilgrim1c9a9f22016-04-24 17:57:27 +00003031 MadeChange = true;
Simon Pilgrim61116dd2015-09-17 20:32:45 +00003032 }
Simon Pilgrim1c9a9f22016-04-24 17:57:27 +00003033 if (MadeChange)
3034 return II;
Filipe Cabecinhas1a805952014-04-24 00:38:14 +00003035 break;
3036 }
3037
Filipe Cabecinhas82ac07c2014-05-27 03:42:20 +00003038 case Intrinsic::x86_sse41_pblendvb:
3039 case Intrinsic::x86_sse41_blendvps:
3040 case Intrinsic::x86_sse41_blendvpd:
3041 case Intrinsic::x86_avx_blendv_ps_256:
3042 case Intrinsic::x86_avx_blendv_pd_256:
3043 case Intrinsic::x86_avx2_pblendvb: {
Sanjay Patel296d35a2018-09-15 14:25:44 +00003044 // fold (blend A, A, Mask) -> A
Simon Pilgrim8c049d52015-08-12 08:08:56 +00003045 Value *Op0 = II->getArgOperand(0);
3046 Value *Op1 = II->getArgOperand(1);
Filipe Cabecinhas82ac07c2014-05-27 03:42:20 +00003047 Value *Mask = II->getArgOperand(2);
Simon Pilgrim8c049d52015-08-12 08:08:56 +00003048 if (Op0 == Op1)
Sanjay Patel4b198802016-02-01 22:23:39 +00003049 return replaceInstUsesWith(CI, Op0);
Simon Pilgrim8c049d52015-08-12 08:08:56 +00003050
3051 // Zero Mask - select 1st argument.
Simon Pilgrim93f59f52015-08-12 08:23:36 +00003052 if (isa<ConstantAggregateZero>(Mask))
Sanjay Patel4b198802016-02-01 22:23:39 +00003053 return replaceInstUsesWith(CI, Op0);
Simon Pilgrim8c049d52015-08-12 08:08:56 +00003054
3055 // Constant Mask - select 1st/2nd argument lane based on top bit of mask.
Sanjay Patel368ac5d2016-02-21 17:29:33 +00003056 if (auto *ConstantMask = dyn_cast<ConstantDataVector>(Mask)) {
3057 Constant *NewSelector = getNegativeIsTrueBoolVec(ConstantMask);
Simon Pilgrim8c049d52015-08-12 08:08:56 +00003058 return SelectInst::Create(NewSelector, Op1, Op0, "blendv");
Filipe Cabecinhas82ac07c2014-05-27 03:42:20 +00003059 }
Sanjay Patel296d35a2018-09-15 14:25:44 +00003060
3061 // Convert to a vector select if we can bypass casts and find a boolean
3062 // vector condition value.
3063 Value *BoolVec;
Sanjay Patel09e02fb2018-09-22 14:43:55 +00003064 Mask = peekThroughBitcast(Mask);
3065 if (match(Mask, m_SExt(m_Value(BoolVec))) &&
3066 BoolVec->getType()->isVectorTy() &&
3067 BoolVec->getType()->getScalarSizeInBits() == 1) {
3068 assert(Mask->getType()->getPrimitiveSizeInBits() ==
3069 II->getType()->getPrimitiveSizeInBits() &&
3070 "Not expecting mask and operands with different sizes");
3071
3072 unsigned NumMaskElts = Mask->getType()->getVectorNumElements();
3073 unsigned NumOperandElts = II->getType()->getVectorNumElements();
3074 if (NumMaskElts == NumOperandElts)
Sanjay Patel296d35a2018-09-15 14:25:44 +00003075 return SelectInst::Create(BoolVec, Op1, Op0);
Sanjay Patel09e02fb2018-09-22 14:43:55 +00003076
3077 // If the mask has less elements than the operands, each mask bit maps to
3078 // multiple elements of the operands. Bitcast back and forth.
3079 if (NumMaskElts < NumOperandElts) {
3080 Value *CastOp0 = Builder.CreateBitCast(Op0, Mask->getType());
3081 Value *CastOp1 = Builder.CreateBitCast(Op1, Mask->getType());
3082 Value *Sel = Builder.CreateSelect(BoolVec, CastOp1, CastOp0);
3083 return new BitCastInst(Sel, II->getType());
3084 }
Sanjay Patel296d35a2018-09-15 14:25:44 +00003085 }
3086
Simon Pilgrim8c049d52015-08-12 08:08:56 +00003087 break;
Filipe Cabecinhas82ac07c2014-05-27 03:42:20 +00003088 }
3089
Andrea Di Biagio0594e2a2015-09-30 16:44:39 +00003090 case Intrinsic::x86_ssse3_pshuf_b_128:
Simon Pilgrimc0c56e72016-04-24 17:00:34 +00003091 case Intrinsic::x86_avx2_pshuf_b:
Simon Pilgrima22c3a12017-01-18 13:44:04 +00003092 case Intrinsic::x86_avx512_pshuf_b_512:
Craig Topperbb4069e2017-07-07 23:16:26 +00003093 if (Value *V = simplifyX86pshufb(*II, Builder))
Simon Pilgrimc0c56e72016-04-24 17:00:34 +00003094 return replaceInstUsesWith(*II, V);
3095 break;
Andrea Di Biagio0594e2a2015-09-30 16:44:39 +00003096
Rafael Espindolabad3f772014-04-21 22:06:04 +00003097 case Intrinsic::x86_avx_vpermilvar_ps:
3098 case Intrinsic::x86_avx_vpermilvar_ps_256:
Craig Topper58917f32016-12-11 01:59:36 +00003099 case Intrinsic::x86_avx512_vpermilvar_ps_512:
Rafael Espindolabad3f772014-04-21 22:06:04 +00003100 case Intrinsic::x86_avx_vpermilvar_pd:
Simon Pilgrim2f6097d2016-04-24 17:23:46 +00003101 case Intrinsic::x86_avx_vpermilvar_pd_256:
Simon Pilgrima22c3a12017-01-18 13:44:04 +00003102 case Intrinsic::x86_avx512_vpermilvar_pd_512:
Craig Topperbb4069e2017-07-07 23:16:26 +00003103 if (Value *V = simplifyX86vpermilvar(*II, Builder))
Simon Pilgrim2f6097d2016-04-24 17:23:46 +00003104 return replaceInstUsesWith(*II, V);
3105 break;
Rafael Espindolabad3f772014-04-21 22:06:04 +00003106
Simon Pilgrim8cddf8b2016-05-01 16:41:22 +00003107 case Intrinsic::x86_avx2_permd:
3108 case Intrinsic::x86_avx2_permps:
Craig Toppere4c045b2018-05-20 23:34:04 +00003109 case Intrinsic::x86_avx512_permvar_df_256:
3110 case Intrinsic::x86_avx512_permvar_df_512:
3111 case Intrinsic::x86_avx512_permvar_di_256:
3112 case Intrinsic::x86_avx512_permvar_di_512:
3113 case Intrinsic::x86_avx512_permvar_hi_128:
3114 case Intrinsic::x86_avx512_permvar_hi_256:
3115 case Intrinsic::x86_avx512_permvar_hi_512:
3116 case Intrinsic::x86_avx512_permvar_qi_128:
3117 case Intrinsic::x86_avx512_permvar_qi_256:
3118 case Intrinsic::x86_avx512_permvar_qi_512:
3119 case Intrinsic::x86_avx512_permvar_sf_512:
3120 case Intrinsic::x86_avx512_permvar_si_512:
Craig Topperbb4069e2017-07-07 23:16:26 +00003121 if (Value *V = simplifyX86vpermv(*II, Builder))
Simon Pilgrim8cddf8b2016-05-01 16:41:22 +00003122 return replaceInstUsesWith(*II, V);
3123 break;
3124
Sanjay Patel98a71502016-02-29 23:16:48 +00003125 case Intrinsic::x86_avx_maskload_ps:
Sanjay Patel6f2c01f2016-02-29 23:59:00 +00003126 case Intrinsic::x86_avx_maskload_pd:
3127 case Intrinsic::x86_avx_maskload_ps_256:
3128 case Intrinsic::x86_avx_maskload_pd_256:
3129 case Intrinsic::x86_avx2_maskload_d:
3130 case Intrinsic::x86_avx2_maskload_q:
3131 case Intrinsic::x86_avx2_maskload_d_256:
3132 case Intrinsic::x86_avx2_maskload_q_256:
Sanjay Patel98a71502016-02-29 23:16:48 +00003133 if (Instruction *I = simplifyX86MaskedLoad(*II, *this))
3134 return I;
3135 break;
3136
Sanjay Patelc4acbae2016-03-12 15:16:59 +00003137 case Intrinsic::x86_sse2_maskmov_dqu:
Sanjay Patel1ace9932016-02-26 21:04:14 +00003138 case Intrinsic::x86_avx_maskstore_ps:
3139 case Intrinsic::x86_avx_maskstore_pd:
3140 case Intrinsic::x86_avx_maskstore_ps_256:
3141 case Intrinsic::x86_avx_maskstore_pd_256:
Sanjay Patelfc7e7eb2016-02-26 21:51:44 +00003142 case Intrinsic::x86_avx2_maskstore_d:
3143 case Intrinsic::x86_avx2_maskstore_q:
3144 case Intrinsic::x86_avx2_maskstore_d_256:
3145 case Intrinsic::x86_avx2_maskstore_q_256:
Sanjay Patel1ace9932016-02-26 21:04:14 +00003146 if (simplifyX86MaskedStore(*II, *this))
3147 return nullptr;
3148 break;
3149
Sanjay Patelbe23a912019-02-01 14:14:47 +00003150 case Intrinsic::x86_addcarry_32:
3151 case Intrinsic::x86_addcarry_64:
3152 if (Value *V = simplifyX86addcarry(*II, Builder))
3153 return replaceInstUsesWith(*II, V);
3154 break;
3155
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003156 case Intrinsic::ppc_altivec_vperm:
3157 // Turn vperm(V1,V2,mask) -> shuffle(V1,V2,mask) if mask is a constant.
Bill Schmidta1184632014-06-05 19:46:04 +00003158 // Note that ppc_altivec_vperm has a big-endian bias, so when creating
3159 // a vectorshuffle for little endian, we must undo the transformation
3160 // performed on vec_perm in altivec.h. That is, we must complement
3161 // the permutation mask with respect to 31 and reverse the order of
3162 // V1 and V2.
Chris Lattner0256be92012-01-27 03:08:05 +00003163 if (Constant *Mask = dyn_cast<Constant>(II->getArgOperand(2))) {
3164 assert(Mask->getType()->getVectorNumElements() == 16 &&
3165 "Bad type for intrinsic!");
Jim Grosbach7815f562012-02-03 00:07:04 +00003166
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003167 // Check that all of the elements are integer constants or undefs.
3168 bool AllEltsOk = true;
3169 for (unsigned i = 0; i != 16; ++i) {
Chris Lattner0256be92012-01-27 03:08:05 +00003170 Constant *Elt = Mask->getAggregateElement(i);
Craig Topperf40110f2014-04-25 05:29:35 +00003171 if (!Elt || !(isa<ConstantInt>(Elt) || isa<UndefValue>(Elt))) {
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003172 AllEltsOk = false;
3173 break;
3174 }
3175 }
Jim Grosbach7815f562012-02-03 00:07:04 +00003176
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003177 if (AllEltsOk) {
3178 // Cast the input vectors to byte vectors.
Craig Topperbb4069e2017-07-07 23:16:26 +00003179 Value *Op0 = Builder.CreateBitCast(II->getArgOperand(0),
3180 Mask->getType());
3181 Value *Op1 = Builder.CreateBitCast(II->getArgOperand(1),
3182 Mask->getType());
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003183 Value *Result = UndefValue::get(Op0->getType());
Jim Grosbach7815f562012-02-03 00:07:04 +00003184
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003185 // Only extract each element once.
3186 Value *ExtractedElts[32];
3187 memset(ExtractedElts, 0, sizeof(ExtractedElts));
Jim Grosbach7815f562012-02-03 00:07:04 +00003188
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003189 for (unsigned i = 0; i != 16; ++i) {
Chris Lattner0256be92012-01-27 03:08:05 +00003190 if (isa<UndefValue>(Mask->getAggregateElement(i)))
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003191 continue;
Jim Grosbach7815f562012-02-03 00:07:04 +00003192 unsigned Idx =
Chris Lattner0256be92012-01-27 03:08:05 +00003193 cast<ConstantInt>(Mask->getAggregateElement(i))->getZExtValue();
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003194 Idx &= 31; // Match the hardware behavior.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003195 if (DL.isLittleEndian())
Bill Schmidta1184632014-06-05 19:46:04 +00003196 Idx = 31 - Idx;
Jim Grosbach7815f562012-02-03 00:07:04 +00003197
Craig Topperf40110f2014-04-25 05:29:35 +00003198 if (!ExtractedElts[Idx]) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003199 Value *Op0ToUse = (DL.isLittleEndian()) ? Op1 : Op0;
3200 Value *Op1ToUse = (DL.isLittleEndian()) ? Op0 : Op1;
Jim Grosbach7815f562012-02-03 00:07:04 +00003201 ExtractedElts[Idx] =
Craig Topperbb4069e2017-07-07 23:16:26 +00003202 Builder.CreateExtractElement(Idx < 16 ? Op0ToUse : Op1ToUse,
3203 Builder.getInt32(Idx&15));
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003204 }
Jim Grosbach7815f562012-02-03 00:07:04 +00003205
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003206 // Insert this value into the result vector.
Craig Topperbb4069e2017-07-07 23:16:26 +00003207 Result = Builder.CreateInsertElement(Result, ExtractedElts[Idx],
3208 Builder.getInt32(i));
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003209 }
3210 return CastInst::Create(Instruction::BitCast, Result, CI.getType());
3211 }
3212 }
3213 break;
3214
Alexandros Lamprineas61f0ba12018-05-31 12:19:18 +00003215 case Intrinsic::arm_neon_vld1: {
3216 unsigned MemAlign = getKnownAlignment(II->getArgOperand(0),
3217 DL, II, &AC, &DT);
3218 if (Value *V = simplifyNeonVld1(*II, MemAlign, Builder))
3219 return replaceInstUsesWith(*II, V);
3220 break;
3221 }
3222
Bob Wilsona4e231c2010-10-22 21:41:48 +00003223 case Intrinsic::arm_neon_vld2:
3224 case Intrinsic::arm_neon_vld3:
3225 case Intrinsic::arm_neon_vld4:
3226 case Intrinsic::arm_neon_vld2lane:
3227 case Intrinsic::arm_neon_vld3lane:
3228 case Intrinsic::arm_neon_vld4lane:
3229 case Intrinsic::arm_neon_vst1:
3230 case Intrinsic::arm_neon_vst2:
3231 case Intrinsic::arm_neon_vst3:
3232 case Intrinsic::arm_neon_vst4:
3233 case Intrinsic::arm_neon_vst2lane:
3234 case Intrinsic::arm_neon_vst3lane:
3235 case Intrinsic::arm_neon_vst4lane: {
Justin Bogner99798402016-08-05 01:06:44 +00003236 unsigned MemAlign =
Daniel Jasperaec2fa32016-12-19 08:22:17 +00003237 getKnownAlignment(II->getArgOperand(0), DL, II, &AC, &DT);
Bob Wilsona4e231c2010-10-22 21:41:48 +00003238 unsigned AlignArg = II->getNumArgOperands() - 1;
3239 ConstantInt *IntrAlign = dyn_cast<ConstantInt>(II->getArgOperand(AlignArg));
3240 if (IntrAlign && IntrAlign->getZExtValue() < MemAlign) {
3241 II->setArgOperand(AlignArg,
3242 ConstantInt::get(Type::getInt32Ty(II->getContext()),
3243 MemAlign, false));
3244 return II;
3245 }
3246 break;
3247 }
3248
Alexandros Lamprineas52457d32018-05-30 14:38:50 +00003249 case Intrinsic::arm_neon_vtbl1:
3250 case Intrinsic::aarch64_neon_tbl1:
3251 if (Value *V = simplifyNeonTbl1(*II, Builder))
3252 return replaceInstUsesWith(*II, V);
3253 break;
3254
Lang Hames3a90fab2012-05-01 00:20:38 +00003255 case Intrinsic::arm_neon_vmulls:
Tim Northover00ed9962014-03-29 10:18:08 +00003256 case Intrinsic::arm_neon_vmullu:
Tim Northover3b0846e2014-05-24 12:50:23 +00003257 case Intrinsic::aarch64_neon_smull:
3258 case Intrinsic::aarch64_neon_umull: {
Lang Hames3a90fab2012-05-01 00:20:38 +00003259 Value *Arg0 = II->getArgOperand(0);
3260 Value *Arg1 = II->getArgOperand(1);
3261
3262 // Handle mul by zero first:
3263 if (isa<ConstantAggregateZero>(Arg0) || isa<ConstantAggregateZero>(Arg1)) {
Sanjay Patel4b198802016-02-01 22:23:39 +00003264 return replaceInstUsesWith(CI, ConstantAggregateZero::get(II->getType()));
Lang Hames3a90fab2012-05-01 00:20:38 +00003265 }
3266
3267 // Check for constant LHS & RHS - in this case we just simplify.
Sanjay Patel62f457b2019-05-06 15:35:02 +00003268 bool Zext = (IID == Intrinsic::arm_neon_vmullu ||
3269 IID == Intrinsic::aarch64_neon_umull);
Lang Hames3a90fab2012-05-01 00:20:38 +00003270 VectorType *NewVT = cast<VectorType>(II->getType());
Benjamin Kramer92040952014-02-13 18:23:24 +00003271 if (Constant *CV0 = dyn_cast<Constant>(Arg0)) {
3272 if (Constant *CV1 = dyn_cast<Constant>(Arg1)) {
3273 CV0 = ConstantExpr::getIntegerCast(CV0, NewVT, /*isSigned=*/!Zext);
3274 CV1 = ConstantExpr::getIntegerCast(CV1, NewVT, /*isSigned=*/!Zext);
3275
Sanjay Patel4b198802016-02-01 22:23:39 +00003276 return replaceInstUsesWith(CI, ConstantExpr::getMul(CV0, CV1));
Lang Hames3a90fab2012-05-01 00:20:38 +00003277 }
3278
Alp Tokercb402912014-01-24 17:20:08 +00003279 // Couldn't simplify - canonicalize constant to the RHS.
Lang Hames3a90fab2012-05-01 00:20:38 +00003280 std::swap(Arg0, Arg1);
3281 }
3282
3283 // Handle mul by one:
Benjamin Kramer92040952014-02-13 18:23:24 +00003284 if (Constant *CV1 = dyn_cast<Constant>(Arg1))
Lang Hames3a90fab2012-05-01 00:20:38 +00003285 if (ConstantInt *Splat =
Benjamin Kramer92040952014-02-13 18:23:24 +00003286 dyn_cast_or_null<ConstantInt>(CV1->getSplatValue()))
3287 if (Splat->isOne())
3288 return CastInst::CreateIntegerCast(Arg0, II->getType(),
3289 /*isSigned=*/!Zext);
Lang Hames3a90fab2012-05-01 00:20:38 +00003290
3291 break;
3292 }
Chad Rosier274d72f2018-05-24 15:26:42 +00003293 case Intrinsic::arm_neon_aesd:
3294 case Intrinsic::arm_neon_aese:
3295 case Intrinsic::aarch64_crypto_aesd:
3296 case Intrinsic::aarch64_crypto_aese: {
3297 Value *DataArg = II->getArgOperand(0);
3298 Value *KeyArg = II->getArgOperand(1);
3299
3300 // Try to use the builtin XOR in AESE and AESD to eliminate a prior XOR
3301 Value *Data, *Key;
3302 if (match(KeyArg, m_ZeroInt()) &&
3303 match(DataArg, m_Xor(m_Value(Data), m_Value(Key)))) {
3304 II->setArgOperand(0, Data);
3305 II->setArgOperand(1, Key);
3306 return II;
3307 }
3308 break;
3309 }
Matt Arsenaultbef34e22016-01-22 21:30:34 +00003310 case Intrinsic::amdgcn_rcp: {
Matt Arsenault4c7795d2017-03-24 19:04:57 +00003311 Value *Src = II->getArgOperand(0);
3312
3313 // TODO: Move to ConstantFolding/InstSimplify?
3314 if (isa<UndefValue>(Src))
3315 return replaceInstUsesWith(CI, Src);
3316
3317 if (const ConstantFP *C = dyn_cast<ConstantFP>(Src)) {
Matt Arsenaulta0050b02014-06-19 01:19:19 +00003318 const APFloat &ArgVal = C->getValueAPF();
3319 APFloat Val(ArgVal.getSemantics(), 1.0);
3320 APFloat::opStatus Status = Val.divide(ArgVal,
3321 APFloat::rmNearestTiesToEven);
3322 // Only do this if it was exact and therefore not dependent on the
3323 // rounding mode.
3324 if (Status == APFloat::opOK)
Sanjay Patel4b198802016-02-01 22:23:39 +00003325 return replaceInstUsesWith(CI, ConstantFP::get(II->getContext(), Val));
Matt Arsenaulta0050b02014-06-19 01:19:19 +00003326 }
3327
3328 break;
3329 }
Matt Arsenault4c7795d2017-03-24 19:04:57 +00003330 case Intrinsic::amdgcn_rsq: {
3331 Value *Src = II->getArgOperand(0);
3332
3333 // TODO: Move to ConstantFolding/InstSimplify?
3334 if (isa<UndefValue>(Src))
3335 return replaceInstUsesWith(CI, Src);
3336 break;
3337 }
Matt Arsenault2fe4fbc2016-03-30 22:28:52 +00003338 case Intrinsic::amdgcn_frexp_mant:
3339 case Intrinsic::amdgcn_frexp_exp: {
Matt Arsenault5cd4f8f2016-03-30 22:28:26 +00003340 Value *Src = II->getArgOperand(0);
3341 if (const ConstantFP *C = dyn_cast<ConstantFP>(Src)) {
3342 int Exp;
3343 APFloat Significand = frexp(C->getValueAPF(), Exp,
3344 APFloat::rmNearestTiesToEven);
3345
Sanjay Patel62f457b2019-05-06 15:35:02 +00003346 if (IID == Intrinsic::amdgcn_frexp_mant) {
Matt Arsenault2fe4fbc2016-03-30 22:28:52 +00003347 return replaceInstUsesWith(CI, ConstantFP::get(II->getContext(),
3348 Significand));
3349 }
3350
3351 // Match instruction special case behavior.
3352 if (Exp == APFloat::IEK_NaN || Exp == APFloat::IEK_Inf)
3353 Exp = 0;
3354
3355 return replaceInstUsesWith(CI, ConstantInt::get(II->getType(), Exp));
3356 }
3357
3358 if (isa<UndefValue>(Src))
3359 return replaceInstUsesWith(CI, UndefValue::get(II->getType()));
Matt Arsenault5cd4f8f2016-03-30 22:28:26 +00003360
3361 break;
3362 }
Matt Arsenault46a03822016-09-03 07:06:58 +00003363 case Intrinsic::amdgcn_class: {
3364 enum {
3365 S_NAN = 1 << 0, // Signaling NaN
3366 Q_NAN = 1 << 1, // Quiet NaN
3367 N_INFINITY = 1 << 2, // Negative infinity
3368 N_NORMAL = 1 << 3, // Negative normal
3369 N_SUBNORMAL = 1 << 4, // Negative subnormal
3370 N_ZERO = 1 << 5, // Negative zero
3371 P_ZERO = 1 << 6, // Positive zero
3372 P_SUBNORMAL = 1 << 7, // Positive subnormal
3373 P_NORMAL = 1 << 8, // Positive normal
3374 P_INFINITY = 1 << 9 // Positive infinity
3375 };
3376
3377 const uint32_t FullMask = S_NAN | Q_NAN | N_INFINITY | N_NORMAL |
3378 N_SUBNORMAL | N_ZERO | P_ZERO | P_SUBNORMAL | P_NORMAL | P_INFINITY;
3379
3380 Value *Src0 = II->getArgOperand(0);
3381 Value *Src1 = II->getArgOperand(1);
3382 const ConstantInt *CMask = dyn_cast<ConstantInt>(Src1);
3383 if (!CMask) {
3384 if (isa<UndefValue>(Src0))
3385 return replaceInstUsesWith(*II, UndefValue::get(II->getType()));
3386
3387 if (isa<UndefValue>(Src1))
3388 return replaceInstUsesWith(*II, ConstantInt::get(II->getType(), false));
3389 break;
3390 }
3391
3392 uint32_t Mask = CMask->getZExtValue();
3393
3394 // If all tests are made, it doesn't matter what the value is.
3395 if ((Mask & FullMask) == FullMask)
3396 return replaceInstUsesWith(*II, ConstantInt::get(II->getType(), true));
3397
3398 if ((Mask & FullMask) == 0)
3399 return replaceInstUsesWith(*II, ConstantInt::get(II->getType(), false));
3400
3401 if (Mask == (S_NAN | Q_NAN)) {
3402 // Equivalent of isnan. Replace with standard fcmp.
Craig Topperbb4069e2017-07-07 23:16:26 +00003403 Value *FCmp = Builder.CreateFCmpUNO(Src0, Src0);
Matt Arsenault46a03822016-09-03 07:06:58 +00003404 FCmp->takeName(II);
3405 return replaceInstUsesWith(*II, FCmp);
3406 }
3407
Matt Arsenaultd35f46c2018-08-10 18:58:49 +00003408 if (Mask == (N_ZERO | P_ZERO)) {
3409 // Equivalent of == 0.
3410 Value *FCmp = Builder.CreateFCmpOEQ(
3411 Src0, ConstantFP::get(Src0->getType(), 0.0));
3412
3413 FCmp->takeName(II);
3414 return replaceInstUsesWith(*II, FCmp);
3415 }
3416
Matt Arsenault10de2772018-08-28 18:10:02 +00003417 // fp_class (nnan x), qnan|snan|other -> fp_class (nnan x), other
3418 if (((Mask & S_NAN) || (Mask & Q_NAN)) && isKnownNeverNaN(Src0, &TLI)) {
3419 II->setArgOperand(1, ConstantInt::get(Src1->getType(),
3420 Mask & ~(S_NAN | Q_NAN)));
3421 return II;
3422 }
3423
Matt Arsenault46a03822016-09-03 07:06:58 +00003424 const ConstantFP *CVal = dyn_cast<ConstantFP>(Src0);
3425 if (!CVal) {
3426 if (isa<UndefValue>(Src0))
3427 return replaceInstUsesWith(*II, UndefValue::get(II->getType()));
3428
3429 // Clamp mask to used bits
3430 if ((Mask & FullMask) != Mask) {
Craig Topperbb4069e2017-07-07 23:16:26 +00003431 CallInst *NewCall = Builder.CreateCall(II->getCalledFunction(),
Matt Arsenault46a03822016-09-03 07:06:58 +00003432 { Src0, ConstantInt::get(Src1->getType(), Mask & FullMask) }
3433 );
3434
3435 NewCall->takeName(II);
3436 return replaceInstUsesWith(*II, NewCall);
3437 }
3438
3439 break;
3440 }
3441
3442 const APFloat &Val = CVal->getValueAPF();
3443
3444 bool Result =
3445 ((Mask & S_NAN) && Val.isNaN() && Val.isSignaling()) ||
3446 ((Mask & Q_NAN) && Val.isNaN() && !Val.isSignaling()) ||
3447 ((Mask & N_INFINITY) && Val.isInfinity() && Val.isNegative()) ||
3448 ((Mask & N_NORMAL) && Val.isNormal() && Val.isNegative()) ||
3449 ((Mask & N_SUBNORMAL) && Val.isDenormal() && Val.isNegative()) ||
3450 ((Mask & N_ZERO) && Val.isZero() && Val.isNegative()) ||
3451 ((Mask & P_ZERO) && Val.isZero() && !Val.isNegative()) ||
3452 ((Mask & P_SUBNORMAL) && Val.isDenormal() && !Val.isNegative()) ||
3453 ((Mask & P_NORMAL) && Val.isNormal() && !Val.isNegative()) ||
3454 ((Mask & P_INFINITY) && Val.isInfinity() && !Val.isNegative());
3455
3456 return replaceInstUsesWith(*II, ConstantInt::get(II->getType(), Result));
3457 }
Matt Arsenault1f17c662017-02-22 00:27:34 +00003458 case Intrinsic::amdgcn_cvt_pkrtz: {
3459 Value *Src0 = II->getArgOperand(0);
3460 Value *Src1 = II->getArgOperand(1);
3461 if (const ConstantFP *C0 = dyn_cast<ConstantFP>(Src0)) {
3462 if (const ConstantFP *C1 = dyn_cast<ConstantFP>(Src1)) {
3463 const fltSemantics &HalfSem
3464 = II->getType()->getScalarType()->getFltSemantics();
3465 bool LosesInfo;
3466 APFloat Val0 = C0->getValueAPF();
3467 APFloat Val1 = C1->getValueAPF();
3468 Val0.convert(HalfSem, APFloat::rmTowardZero, &LosesInfo);
3469 Val1.convert(HalfSem, APFloat::rmTowardZero, &LosesInfo);
3470
3471 Constant *Folded = ConstantVector::get({
3472 ConstantFP::get(II->getContext(), Val0),
3473 ConstantFP::get(II->getContext(), Val1) });
3474 return replaceInstUsesWith(*II, Folded);
3475 }
3476 }
3477
3478 if (isa<UndefValue>(Src0) && isa<UndefValue>(Src1))
3479 return replaceInstUsesWith(*II, UndefValue::get(II->getType()));
3480
3481 break;
3482 }
Marek Olsak13e47412018-01-31 20:18:04 +00003483 case Intrinsic::amdgcn_cvt_pknorm_i16:
3484 case Intrinsic::amdgcn_cvt_pknorm_u16:
3485 case Intrinsic::amdgcn_cvt_pk_i16:
3486 case Intrinsic::amdgcn_cvt_pk_u16: {
3487 Value *Src0 = II->getArgOperand(0);
3488 Value *Src1 = II->getArgOperand(1);
3489
3490 if (isa<UndefValue>(Src0) && isa<UndefValue>(Src1))
3491 return replaceInstUsesWith(*II, UndefValue::get(II->getType()));
3492
3493 break;
3494 }
Matt Arsenaultf5262252017-02-22 23:04:58 +00003495 case Intrinsic::amdgcn_ubfe:
3496 case Intrinsic::amdgcn_sbfe: {
3497 // Decompose simple cases into standard shifts.
3498 Value *Src = II->getArgOperand(0);
3499 if (isa<UndefValue>(Src))
3500 return replaceInstUsesWith(*II, Src);
3501
3502 unsigned Width;
3503 Type *Ty = II->getType();
3504 unsigned IntSize = Ty->getIntegerBitWidth();
3505
3506 ConstantInt *CWidth = dyn_cast<ConstantInt>(II->getArgOperand(2));
3507 if (CWidth) {
3508 Width = CWidth->getZExtValue();
3509 if ((Width & (IntSize - 1)) == 0)
3510 return replaceInstUsesWith(*II, ConstantInt::getNullValue(Ty));
3511
3512 if (Width >= IntSize) {
3513 // Hardware ignores high bits, so remove those.
3514 II->setArgOperand(2, ConstantInt::get(CWidth->getType(),
3515 Width & (IntSize - 1)));
3516 return II;
3517 }
3518 }
3519
3520 unsigned Offset;
3521 ConstantInt *COffset = dyn_cast<ConstantInt>(II->getArgOperand(1));
3522 if (COffset) {
3523 Offset = COffset->getZExtValue();
3524 if (Offset >= IntSize) {
3525 II->setArgOperand(1, ConstantInt::get(COffset->getType(),
3526 Offset & (IntSize - 1)));
3527 return II;
3528 }
3529 }
3530
Sanjay Patel62f457b2019-05-06 15:35:02 +00003531 bool Signed = IID == Intrinsic::amdgcn_sbfe;
Matt Arsenaultf5262252017-02-22 23:04:58 +00003532
Matt Arsenaultf5262252017-02-22 23:04:58 +00003533 if (!CWidth || !COffset)
3534 break;
3535
Tom Stellard28d66212018-11-08 17:57:57 +00003536 // The case of Width == 0 is handled above, which makes this tranformation
3537 // safe. If Width == 0, then the ashr and lshr instructions become poison
3538 // value since the shift amount would be equal to the bit size.
3539 assert(Width != 0);
3540
Matt Arsenaultf5262252017-02-22 23:04:58 +00003541 // TODO: This allows folding to undef when the hardware has specific
3542 // behavior?
3543 if (Offset + Width < IntSize) {
Craig Topperbb4069e2017-07-07 23:16:26 +00003544 Value *Shl = Builder.CreateShl(Src, IntSize - Offset - Width);
3545 Value *RightShift = Signed ? Builder.CreateAShr(Shl, IntSize - Width)
3546 : Builder.CreateLShr(Shl, IntSize - Width);
Matt Arsenaultf5262252017-02-22 23:04:58 +00003547 RightShift->takeName(II);
3548 return replaceInstUsesWith(*II, RightShift);
3549 }
3550
Craig Topperbb4069e2017-07-07 23:16:26 +00003551 Value *RightShift = Signed ? Builder.CreateAShr(Src, Offset)
3552 : Builder.CreateLShr(Src, Offset);
Matt Arsenaultf5262252017-02-22 23:04:58 +00003553
3554 RightShift->takeName(II);
3555 return replaceInstUsesWith(*II, RightShift);
3556 }
Matt Arsenaultd4bca1e2017-02-23 00:44:03 +00003557 case Intrinsic::amdgcn_exp:
3558 case Intrinsic::amdgcn_exp_compr: {
Matt Arsenaultcaf13162019-03-12 21:02:54 +00003559 ConstantInt *En = cast<ConstantInt>(II->getArgOperand(1));
Matt Arsenaultd4bca1e2017-02-23 00:44:03 +00003560 unsigned EnBits = En->getZExtValue();
3561 if (EnBits == 0xf)
3562 break; // All inputs enabled.
3563
Sanjay Patel62f457b2019-05-06 15:35:02 +00003564 bool IsCompr = IID == Intrinsic::amdgcn_exp_compr;
Matt Arsenaultd4bca1e2017-02-23 00:44:03 +00003565 bool Changed = false;
3566 for (int I = 0; I < (IsCompr ? 2 : 4); ++I) {
3567 if ((!IsCompr && (EnBits & (1 << I)) == 0) ||
3568 (IsCompr && ((EnBits & (0x3 << (2 * I))) == 0))) {
3569 Value *Src = II->getArgOperand(I + 2);
3570 if (!isa<UndefValue>(Src)) {
3571 II->setArgOperand(I + 2, UndefValue::get(Src->getType()));
3572 Changed = true;
3573 }
3574 }
3575 }
3576
3577 if (Changed)
3578 return II;
3579
3580 break;
Matt Arsenaultcdb468c2017-02-27 23:08:49 +00003581 }
3582 case Intrinsic::amdgcn_fmed3: {
3583 // Note this does not preserve proper sNaN behavior if IEEE-mode is enabled
3584 // for the shader.
3585
3586 Value *Src0 = II->getArgOperand(0);
3587 Value *Src1 = II->getArgOperand(1);
3588 Value *Src2 = II->getArgOperand(2);
3589
Matt Arsenault24ce89b2018-07-05 17:05:36 +00003590 // Checking for NaN before canonicalization provides better fidelity when
3591 // mapping other operations onto fmed3 since the order of operands is
3592 // unchanged.
3593 CallInst *NewCall = nullptr;
3594 if (match(Src0, m_NaN()) || isa<UndefValue>(Src0)) {
3595 NewCall = Builder.CreateMinNum(Src1, Src2);
3596 } else if (match(Src1, m_NaN()) || isa<UndefValue>(Src1)) {
3597 NewCall = Builder.CreateMinNum(Src0, Src2);
3598 } else if (match(Src2, m_NaN()) || isa<UndefValue>(Src2)) {
3599 NewCall = Builder.CreateMaxNum(Src0, Src1);
3600 }
3601
3602 if (NewCall) {
3603 NewCall->copyFastMathFlags(II);
3604 NewCall->takeName(II);
3605 return replaceInstUsesWith(*II, NewCall);
3606 }
3607
Matt Arsenaultcdb468c2017-02-27 23:08:49 +00003608 bool Swap = false;
3609 // Canonicalize constants to RHS operands.
3610 //
3611 // fmed3(c0, x, c1) -> fmed3(x, c0, c1)
3612 if (isa<Constant>(Src0) && !isa<Constant>(Src1)) {
3613 std::swap(Src0, Src1);
3614 Swap = true;
3615 }
3616
3617 if (isa<Constant>(Src1) && !isa<Constant>(Src2)) {
3618 std::swap(Src1, Src2);
3619 Swap = true;
3620 }
3621
3622 if (isa<Constant>(Src0) && !isa<Constant>(Src1)) {
3623 std::swap(Src0, Src1);
3624 Swap = true;
3625 }
3626
3627 if (Swap) {
3628 II->setArgOperand(0, Src0);
3629 II->setArgOperand(1, Src1);
3630 II->setArgOperand(2, Src2);
3631 return II;
3632 }
3633
Matt Arsenaultcdb468c2017-02-27 23:08:49 +00003634 if (const ConstantFP *C0 = dyn_cast<ConstantFP>(Src0)) {
3635 if (const ConstantFP *C1 = dyn_cast<ConstantFP>(Src1)) {
3636 if (const ConstantFP *C2 = dyn_cast<ConstantFP>(Src2)) {
3637 APFloat Result = fmed3AMDGCN(C0->getValueAPF(), C1->getValueAPF(),
3638 C2->getValueAPF());
3639 return replaceInstUsesWith(*II,
Craig Topperbb4069e2017-07-07 23:16:26 +00003640 ConstantFP::get(Builder.getContext(), Result));
Matt Arsenaultcdb468c2017-02-27 23:08:49 +00003641 }
3642 }
3643 }
3644
3645 break;
Matt Arsenaultd4bca1e2017-02-23 00:44:03 +00003646 }
Matt Arsenaultd81f5572017-03-13 18:14:02 +00003647 case Intrinsic::amdgcn_icmp:
3648 case Intrinsic::amdgcn_fcmp: {
Matt Arsenaultcaf13162019-03-12 21:02:54 +00003649 const ConstantInt *CC = cast<ConstantInt>(II->getArgOperand(2));
Matt Arsenaultd81f5572017-03-13 18:14:02 +00003650 // Guard against invalid arguments.
3651 int64_t CCVal = CC->getZExtValue();
Sanjay Patel62f457b2019-05-06 15:35:02 +00003652 bool IsInteger = IID == Intrinsic::amdgcn_icmp;
Matt Arsenaultd81f5572017-03-13 18:14:02 +00003653 if ((IsInteger && (CCVal < CmpInst::FIRST_ICMP_PREDICATE ||
3654 CCVal > CmpInst::LAST_ICMP_PREDICATE)) ||
3655 (!IsInteger && (CCVal < CmpInst::FIRST_FCMP_PREDICATE ||
3656 CCVal > CmpInst::LAST_FCMP_PREDICATE)))
3657 break;
3658
3659 Value *Src0 = II->getArgOperand(0);
3660 Value *Src1 = II->getArgOperand(1);
3661
3662 if (auto *CSrc0 = dyn_cast<Constant>(Src0)) {
3663 if (auto *CSrc1 = dyn_cast<Constant>(Src1)) {
3664 Constant *CCmp = ConstantExpr::getCompare(CCVal, CSrc0, CSrc1);
Nicolai Haehnle9c661852017-04-24 17:08:43 +00003665 if (CCmp->isNullValue()) {
3666 return replaceInstUsesWith(
3667 *II, ConstantExpr::getSExt(CCmp, II->getType()));
3668 }
3669
3670 // The result of V_ICMP/V_FCMP assembly instructions (which this
3671 // intrinsic exposes) is one bit per thread, masked with the EXEC
3672 // register (which contains the bitmask of live threads). So a
3673 // comparison that always returns true is the same as a read of the
3674 // EXEC register.
James Y Knight7976eb52019-02-01 20:43:25 +00003675 Function *NewF = Intrinsic::getDeclaration(
Nicolai Haehnle9c661852017-04-24 17:08:43 +00003676 II->getModule(), Intrinsic::read_register, II->getType());
3677 Metadata *MDArgs[] = {MDString::get(II->getContext(), "exec")};
3678 MDNode *MD = MDNode::get(II->getContext(), MDArgs);
3679 Value *Args[] = {MetadataAsValue::get(II->getContext(), MD)};
Craig Topperbb4069e2017-07-07 23:16:26 +00003680 CallInst *NewCall = Builder.CreateCall(NewF, Args);
Nicolai Haehnle9c661852017-04-24 17:08:43 +00003681 NewCall->addAttribute(AttributeList::FunctionIndex,
3682 Attribute::Convergent);
3683 NewCall->takeName(II);
3684 return replaceInstUsesWith(*II, NewCall);
Matt Arsenaultd81f5572017-03-13 18:14:02 +00003685 }
3686
3687 // Canonicalize constants to RHS.
3688 CmpInst::Predicate SwapPred
3689 = CmpInst::getSwappedPredicate(static_cast<CmpInst::Predicate>(CCVal));
3690 II->setArgOperand(0, Src1);
3691 II->setArgOperand(1, Src0);
3692 II->setArgOperand(2, ConstantInt::get(CC->getType(),
3693 static_cast<int>(SwapPred)));
3694 return II;
3695 }
3696
3697 if (CCVal != CmpInst::ICMP_EQ && CCVal != CmpInst::ICMP_NE)
3698 break;
3699
3700 // Canonicalize compare eq with true value to compare != 0
3701 // llvm.amdgcn.icmp(zext (i1 x), 1, eq)
3702 // -> llvm.amdgcn.icmp(zext (i1 x), 0, ne)
3703 // llvm.amdgcn.icmp(sext (i1 x), -1, eq)
3704 // -> llvm.amdgcn.icmp(sext (i1 x), 0, ne)
3705 Value *ExtSrc;
3706 if (CCVal == CmpInst::ICMP_EQ &&
3707 ((match(Src1, m_One()) && match(Src0, m_ZExt(m_Value(ExtSrc)))) ||
3708 (match(Src1, m_AllOnes()) && match(Src0, m_SExt(m_Value(ExtSrc))))) &&
3709 ExtSrc->getType()->isIntegerTy(1)) {
3710 II->setArgOperand(1, ConstantInt::getNullValue(Src1->getType()));
3711 II->setArgOperand(2, ConstantInt::get(CC->getType(), CmpInst::ICMP_NE));
3712 return II;
3713 }
3714
3715 CmpInst::Predicate SrcPred;
3716 Value *SrcLHS;
3717 Value *SrcRHS;
3718
3719 // Fold compare eq/ne with 0 from a compare result as the predicate to the
3720 // intrinsic. The typical use is a wave vote function in the library, which
3721 // will be fed from a user code condition compared with 0. Fold in the
3722 // redundant compare.
3723
3724 // llvm.amdgcn.icmp([sz]ext ([if]cmp pred a, b), 0, ne)
3725 // -> llvm.amdgcn.[if]cmp(a, b, pred)
3726 //
3727 // llvm.amdgcn.icmp([sz]ext ([if]cmp pred a, b), 0, eq)
3728 // -> llvm.amdgcn.[if]cmp(a, b, inv pred)
3729 if (match(Src1, m_Zero()) &&
3730 match(Src0,
3731 m_ZExtOrSExt(m_Cmp(SrcPred, m_Value(SrcLHS), m_Value(SrcRHS))))) {
3732 if (CCVal == CmpInst::ICMP_EQ)
3733 SrcPred = CmpInst::getInversePredicate(SrcPred);
3734
3735 Intrinsic::ID NewIID = CmpInst::isFPPredicate(SrcPred) ?
3736 Intrinsic::amdgcn_fcmp : Intrinsic::amdgcn_icmp;
3737
Matt Arsenault9a389fb2018-08-15 21:14:25 +00003738 Type *Ty = SrcLHS->getType();
3739 if (auto *CmpType = dyn_cast<IntegerType>(Ty)) {
3740 // Promote to next legal integer type.
3741 unsigned Width = CmpType->getBitWidth();
3742 unsigned NewWidth = Width;
Marek Olsak33eb4d92019-01-15 02:13:18 +00003743
3744 // Don't do anything for i1 comparisons.
3745 if (Width == 1)
3746 break;
3747
Matt Arsenault9a389fb2018-08-15 21:14:25 +00003748 if (Width <= 16)
3749 NewWidth = 16;
3750 else if (Width <= 32)
3751 NewWidth = 32;
3752 else if (Width <= 64)
3753 NewWidth = 64;
3754 else if (Width > 64)
3755 break; // Can't handle this.
3756
3757 if (Width != NewWidth) {
3758 IntegerType *CmpTy = Builder.getIntNTy(NewWidth);
3759 if (CmpInst::isSigned(SrcPred)) {
3760 SrcLHS = Builder.CreateSExt(SrcLHS, CmpTy);
3761 SrcRHS = Builder.CreateSExt(SrcRHS, CmpTy);
3762 } else {
3763 SrcLHS = Builder.CreateZExt(SrcLHS, CmpTy);
3764 SrcRHS = Builder.CreateZExt(SrcRHS, CmpTy);
3765 }
3766 }
3767 } else if (!Ty->isFloatTy() && !Ty->isDoubleTy() && !Ty->isHalfTy())
3768 break;
3769
James Y Knight7976eb52019-02-01 20:43:25 +00003770 Function *NewF =
Stanislav Mekhanoshin68a2fef2019-06-13 23:47:36 +00003771 Intrinsic::getDeclaration(II->getModule(), NewIID,
3772 { II->getType(),
3773 SrcLHS->getType() });
Matt Arsenaultd81f5572017-03-13 18:14:02 +00003774 Value *Args[] = { SrcLHS, SrcRHS,
3775 ConstantInt::get(CC->getType(), SrcPred) };
Craig Topperbb4069e2017-07-07 23:16:26 +00003776 CallInst *NewCall = Builder.CreateCall(NewF, Args);
Matt Arsenaultd81f5572017-03-13 18:14:02 +00003777 NewCall->takeName(II);
3778 return replaceInstUsesWith(*II, NewCall);
3779 }
3780
3781 break;
3782 }
Marek Olsak2114fc32017-10-24 10:26:59 +00003783 case Intrinsic::amdgcn_wqm_vote: {
3784 // wqm_vote is identity when the argument is constant.
3785 if (!isa<Constant>(II->getArgOperand(0)))
3786 break;
3787
3788 return replaceInstUsesWith(*II, II->getArgOperand(0));
3789 }
Marek Olsakce76ea02017-10-24 10:27:13 +00003790 case Intrinsic::amdgcn_kill: {
3791 const ConstantInt *C = dyn_cast<ConstantInt>(II->getArgOperand(0));
3792 if (!C || !C->getZExtValue())
3793 break;
3794
3795 // amdgcn.kill(i1 1) is a no-op
3796 return eraseInstFromFunction(CI);
3797 }
Stanislav Mekhanoshin0e132dc2018-05-22 08:04:33 +00003798 case Intrinsic::amdgcn_update_dpp: {
3799 Value *Old = II->getArgOperand(0);
3800
Matt Arsenaultcaf13162019-03-12 21:02:54 +00003801 auto BC = cast<ConstantInt>(II->getArgOperand(5));
3802 auto RM = cast<ConstantInt>(II->getArgOperand(3));
3803 auto BM = cast<ConstantInt>(II->getArgOperand(4));
3804 if (BC->isZeroValue() ||
Stanislav Mekhanoshin0e132dc2018-05-22 08:04:33 +00003805 RM->getZExtValue() != 0xF ||
3806 BM->getZExtValue() != 0xF ||
3807 isa<UndefValue>(Old))
3808 break;
3809
3810 // If bound_ctrl = 1, row mask = bank mask = 0xf we can omit old value.
3811 II->setOperand(0, UndefValue::get(Old->getType()));
3812 return II;
3813 }
Matt Arsenault492d71c2019-06-14 14:51:26 +00003814 case Intrinsic::amdgcn_readfirstlane:
3815 case Intrinsic::amdgcn_readlane: {
3816 // A constant value is trivially uniform.
3817 if (Constant *C = dyn_cast<Constant>(II->getArgOperand(0)))
3818 return replaceInstUsesWith(*II, C);
Matt Arsenault6d741f22019-06-17 17:52:35 +00003819
3820 // The rest of these may not be safe if the exec may not be the same between
3821 // the def and use.
3822 Value *Src = II->getArgOperand(0);
3823 Instruction *SrcInst = dyn_cast<Instruction>(Src);
3824 if (SrcInst && SrcInst->getParent() != II->getParent())
3825 break;
3826
3827 // readfirstlane (readfirstlane x) -> readfirstlane x
3828 // readlane (readfirstlane x), y -> readfirstlane x
3829 if (match(Src, m_Intrinsic<Intrinsic::amdgcn_readfirstlane>()))
3830 return replaceInstUsesWith(*II, Src);
3831
3832 if (IID == Intrinsic::amdgcn_readfirstlane) {
3833 // readfirstlane (readlane x, y) -> readlane x, y
3834 if (match(Src, m_Intrinsic<Intrinsic::amdgcn_readlane>()))
3835 return replaceInstUsesWith(*II, Src);
3836 } else {
3837 // readlane (readlane x, y), y -> readlane x, y
3838 if (match(Src, m_Intrinsic<Intrinsic::amdgcn_readlane>(
3839 m_Value(), m_Specific(II->getArgOperand(1)))))
3840 return replaceInstUsesWith(*II, Src);
3841 }
3842
Matt Arsenault492d71c2019-06-14 14:51:26 +00003843 break;
3844 }
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003845 case Intrinsic::stackrestore: {
3846 // If the save is right next to the restore, remove the restore. This can
3847 // happen when variable allocas are DCE'd.
Gabor Greif589a0b92010-06-24 12:58:35 +00003848 if (IntrinsicInst *SS = dyn_cast<IntrinsicInst>(II->getArgOperand(0))) {
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003849 if (SS->getIntrinsicID() == Intrinsic::stacksave) {
Vedant Kumarf01827f2018-06-19 23:42:17 +00003850 // Skip over debug info.
3851 if (SS->getNextNonDebugInstruction() == II) {
Sanjay Patel4b198802016-02-01 22:23:39 +00003852 return eraseInstFromFunction(CI);
Davide Italiano189c2cf2018-06-08 20:42:36 +00003853 }
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003854 }
3855 }
Jim Grosbach7815f562012-02-03 00:07:04 +00003856
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003857 // Scan down this block to see if there is another stack restore in the
3858 // same block without an intervening call/alloca.
Duncan P. N. Exon Smith9f8aaf22015-10-13 16:59:33 +00003859 BasicBlock::iterator BI(II);
Chandler Carruthedb12a82018-10-15 10:04:59 +00003860 Instruction *TI = II->getParent()->getTerminator();
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003861 bool CannotRemove = false;
3862 for (++BI; &*BI != TI; ++BI) {
Nuno Lopes55fff832012-06-21 15:45:28 +00003863 if (isa<AllocaInst>(BI)) {
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003864 CannotRemove = true;
3865 break;
3866 }
3867 if (CallInst *BCI = dyn_cast<CallInst>(BI)) {
Sanjay Patel62f457b2019-05-06 15:35:02 +00003868 if (auto *II2 = dyn_cast<IntrinsicInst>(BCI)) {
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003869 // If there is a stackrestore below this one, remove this one.
Sanjay Patel62f457b2019-05-06 15:35:02 +00003870 if (II2->getIntrinsicID() == Intrinsic::stackrestore)
Sanjay Patel4b198802016-02-01 22:23:39 +00003871 return eraseInstFromFunction(CI);
Reid Kleckner892ae2e2016-02-27 00:53:54 +00003872
3873 // Bail if we cross over an intrinsic with side effects, such as
3874 // llvm.stacksave, llvm.read_register, or llvm.setjmp.
Sanjay Patel62f457b2019-05-06 15:35:02 +00003875 if (II2->mayHaveSideEffects()) {
Reid Kleckner892ae2e2016-02-27 00:53:54 +00003876 CannotRemove = true;
3877 break;
3878 }
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003879 } else {
3880 // If we found a non-intrinsic call, we can't remove the stack
3881 // restore.
3882 CannotRemove = true;
3883 break;
3884 }
3885 }
3886 }
Jim Grosbach7815f562012-02-03 00:07:04 +00003887
Bill Wendlingf891bf82011-07-31 06:30:59 +00003888 // If the stack restore is in a return, resume, or unwind block and if there
3889 // are no allocas or calls between the restore and the return, nuke the
3890 // restore.
Bill Wendlingd5d95b02012-02-06 21:16:41 +00003891 if (!CannotRemove && (isa<ReturnInst>(TI) || isa<ResumeInst>(TI)))
Sanjay Patel4b198802016-02-01 22:23:39 +00003892 return eraseInstFromFunction(CI);
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003893 break;
3894 }
Vitaly Bukaf0500b62016-07-28 22:50:48 +00003895 case Intrinsic::lifetime_start:
Vitaly Buka0ab23cf2016-07-28 22:59:03 +00003896 // Asan needs to poison memory to detect invalid access which is possible
3897 // even for empty lifetime range.
Evgeniy Stepanovc667c1f2017-12-09 00:21:41 +00003898 if (II->getFunction()->hasFnAttribute(Attribute::SanitizeAddress) ||
Vitaly Bukaaeca5692019-08-26 22:15:50 +00003899 II->getFunction()->hasFnAttribute(Attribute::SanitizeMemory) ||
Evgeniy Stepanovc667c1f2017-12-09 00:21:41 +00003900 II->getFunction()->hasFnAttribute(Attribute::SanitizeHWAddress))
Vitaly Buka0ab23cf2016-07-28 22:59:03 +00003901 break;
3902
Arnaud A. de Grandmaison333ef382016-05-10 09:24:49 +00003903 if (removeTriviallyEmptyRange(*II, Intrinsic::lifetime_start,
3904 Intrinsic::lifetime_end, *this))
3905 return nullptr;
Arnaud A. de Grandmaison849f3bf2015-10-01 14:54:31 +00003906 break;
Hal Finkelf5867a72014-07-25 21:45:17 +00003907 case Intrinsic::assume: {
David Majnemerfcc58112016-04-08 16:37:12 +00003908 Value *IIOperand = II->getArgOperand(0);
Sanjay Patel825a4fa2018-06-20 13:22:26 +00003909 // Remove an assume if it is followed by an identical assume.
3910 // TODO: Do we need this? Unless there are conflicting assumptions, the
3911 // computeKnownBits(IIOperand) below here eliminates redundant assumes.
3912 Instruction *Next = II->getNextNonDebugInstruction();
3913 if (match(Next, m_Intrinsic<Intrinsic::assume>(m_Specific(IIOperand))))
David Majnemerfcc58112016-04-08 16:37:12 +00003914 return eraseInstFromFunction(CI);
3915
Hal Finkelf5867a72014-07-25 21:45:17 +00003916 // Canonicalize assume(a && b) -> assume(a); assume(b);
Hal Finkel74c2f352014-09-07 12:44:26 +00003917 // Note: New assumption intrinsics created here are registered by
3918 // the InstCombineIRInserter object.
James Y Knight7976eb52019-02-01 20:43:25 +00003919 FunctionType *AssumeIntrinsicTy = II->getFunctionType();
3920 Value *AssumeIntrinsic = II->getCalledValue();
3921 Value *A, *B;
Hal Finkelf5867a72014-07-25 21:45:17 +00003922 if (match(IIOperand, m_And(m_Value(A), m_Value(B)))) {
James Y Knight7976eb52019-02-01 20:43:25 +00003923 Builder.CreateCall(AssumeIntrinsicTy, AssumeIntrinsic, A, II->getName());
3924 Builder.CreateCall(AssumeIntrinsicTy, AssumeIntrinsic, B, II->getName());
Sanjay Patel4b198802016-02-01 22:23:39 +00003925 return eraseInstFromFunction(*II);
Hal Finkelf5867a72014-07-25 21:45:17 +00003926 }
3927 // assume(!(a || b)) -> assume(!a); assume(!b);
3928 if (match(IIOperand, m_Not(m_Or(m_Value(A), m_Value(B))))) {
James Y Knight7976eb52019-02-01 20:43:25 +00003929 Builder.CreateCall(AssumeIntrinsicTy, AssumeIntrinsic,
3930 Builder.CreateNot(A), II->getName());
3931 Builder.CreateCall(AssumeIntrinsicTy, AssumeIntrinsic,
3932 Builder.CreateNot(B), II->getName());
Sanjay Patel4b198802016-02-01 22:23:39 +00003933 return eraseInstFromFunction(*II);
Hal Finkelf5867a72014-07-25 21:45:17 +00003934 }
Hal Finkel04a15612014-10-04 21:27:06 +00003935
Philip Reames66c6de62014-11-11 23:33:19 +00003936 // assume( (load addr) != null ) -> add 'nonnull' metadata to load
3937 // (if assume is valid at the load)
Sanjay Patelf0d1e7732017-01-03 22:25:31 +00003938 CmpInst::Predicate Pred;
3939 Instruction *LHS;
3940 if (match(IIOperand, m_ICmp(Pred, m_Instruction(LHS), m_Zero())) &&
3941 Pred == ICmpInst::ICMP_NE && LHS->getOpcode() == Instruction::Load &&
3942 LHS->getType()->isPointerTy() &&
3943 isValidAssumeForContext(II, LHS, &DT)) {
3944 MDNode *MD = MDNode::get(II->getContext(), None);
3945 LHS->setMetadata(LLVMContext::MD_nonnull, MD);
3946 return eraseInstFromFunction(*II);
3947
Chandler Carruth24969102015-02-10 08:07:32 +00003948 // TODO: apply nonnull return attributes to calls and invokes
Philip Reames66c6de62014-11-11 23:33:19 +00003949 // TODO: apply range metadata for range check patterns?
3950 }
Sanjay Patelf0d1e7732017-01-03 22:25:31 +00003951
Hal Finkel04a15612014-10-04 21:27:06 +00003952 // If there is a dominating assume with the same condition as this one,
3953 // then this one is redundant, and should be removed.
Craig Topperb45eabc2017-04-26 16:39:58 +00003954 KnownBits Known(1);
3955 computeKnownBits(IIOperand, Known, 0, II);
Craig Topperf0aeee02017-05-05 17:36:09 +00003956 if (Known.isAllOnes())
Sanjay Patel4b198802016-02-01 22:23:39 +00003957 return eraseInstFromFunction(*II);
Hal Finkel04a15612014-10-04 21:27:06 +00003958
Hal Finkel8a9a7832017-01-11 13:24:24 +00003959 // Update the cache of affected values for this assumption (we might be
3960 // here because we just simplified the condition).
3961 AC.updateAffectedValues(II);
Hal Finkelf5867a72014-07-25 21:45:17 +00003962 break;
3963 }
Philip Reames9db26ff2014-12-29 23:27:30 +00003964 case Intrinsic::experimental_gc_relocate: {
Philip Reamesd9629b82019-09-24 17:24:16 +00003965 auto &GCR = *cast<GCRelocateInst>(II);
3966
3967 // If we have two copies of the same pointer in the statepoint argument
3968 // list, canonicalize to one. This may let us common gc.relocates.
3969 if (GCR.getBasePtr() == GCR.getDerivedPtr() &&
3970 GCR.getBasePtrIndex() != GCR.getDerivedPtrIndex()) {
3971 auto *OpIntTy = GCR.getOperand(2)->getType();
3972 II->setOperand(2, ConstantInt::get(OpIntTy, GCR.getBasePtrIndex()));
3973 return II;
3974 }
3975
Philip Reames9db26ff2014-12-29 23:27:30 +00003976 // Translate facts known about a pointer before relocating into
3977 // facts about the relocate value, while being careful to
3978 // preserve relocation semantics.
Philip Reamesd9629b82019-09-24 17:24:16 +00003979 Value *DerivedPtr = GCR.getDerivedPtr();
Philip Reames9db26ff2014-12-29 23:27:30 +00003980
3981 // Remove the relocation if unused, note that this check is required
3982 // to prevent the cases below from looping forever.
3983 if (II->use_empty())
Sanjay Patel4b198802016-02-01 22:23:39 +00003984 return eraseInstFromFunction(*II);
Philip Reames9db26ff2014-12-29 23:27:30 +00003985
3986 // Undef is undef, even after relocation.
3987 // TODO: provide a hook for this in GCStrategy. This is clearly legal for
3988 // most practical collectors, but there was discussion in the review thread
3989 // about whether it was legal for all possible collectors.
Philip Reamesea4d8e82016-02-09 21:09:22 +00003990 if (isa<UndefValue>(DerivedPtr))
3991 // Use undef of gc_relocate's type to replace it.
3992 return replaceInstUsesWith(*II, UndefValue::get(II->getType()));
Philip Reames9db26ff2014-12-29 23:27:30 +00003993
Philip Reamesea4d8e82016-02-09 21:09:22 +00003994 if (auto *PT = dyn_cast<PointerType>(II->getType())) {
3995 // The relocation of null will be null for most any collector.
3996 // TODO: provide a hook for this in GCStrategy. There might be some
3997 // weird collector this property does not hold for.
3998 if (isa<ConstantPointerNull>(DerivedPtr))
3999 // Use null-pointer of gc_relocate's type to replace it.
4000 return replaceInstUsesWith(*II, ConstantPointerNull::get(PT));
Simon Pilgrimc0c56e72016-04-24 17:00:34 +00004001
Philip Reamesea4d8e82016-02-09 21:09:22 +00004002 // isKnownNonNull -> nonnull attribute
Philip Reamesb8d8db32018-11-12 20:00:53 +00004003 if (!II->hasRetAttr(Attribute::NonNull) &&
4004 isKnownNonZero(DerivedPtr, DL, 0, &AC, II, &DT)) {
Reid Klecknerb5180542017-03-21 16:57:19 +00004005 II->addAttribute(AttributeList::ReturnIndex, Attribute::NonNull);
Philip Reamesb8d8db32018-11-12 20:00:53 +00004006 return II;
4007 }
Ramkumar Ramachandra8fcb4982015-02-14 19:37:54 +00004008 }
Philip Reames9db26ff2014-12-29 23:27:30 +00004009
4010 // TODO: bitcast(relocate(p)) -> relocate(bitcast(p))
4011 // Canonicalize on the type from the uses to the defs
Ramkumar Ramachandra8fcb4982015-02-14 19:37:54 +00004012
Philip Reames9db26ff2014-12-29 23:27:30 +00004013 // TODO: relocate((gep p, C, C2, ...)) -> gep(relocate(p), C, C2, ...)
Philip Reamesea4d8e82016-02-09 21:09:22 +00004014 break;
Philip Reames9db26ff2014-12-29 23:27:30 +00004015 }
Artur Pilipenkoe812ca02017-01-25 14:12:12 +00004016
4017 case Intrinsic::experimental_guard: {
Philip Reames79e917d2018-05-09 22:56:32 +00004018 // Is this guard followed by another guard? We scan forward over a small
4019 // fixed window of instructions to handle common cases with conditions
4020 // computed between guards.
Sanjoy Dase0e57952017-02-01 16:34:55 +00004021 Instruction *NextInst = II->getNextNode();
Philip Reames913a7792018-05-10 00:05:29 +00004022 for (unsigned i = 0; i < GuardWideningWindow; i++) {
Philip Reames79e917d2018-05-09 22:56:32 +00004023 // Note: Using context-free form to avoid compile time blow up
4024 if (!isSafeToSpeculativelyExecute(NextInst))
4025 break;
4026 NextInst = NextInst->getNextNode();
4027 }
Sanjoy Dase0e57952017-02-01 16:34:55 +00004028 Value *NextCond = nullptr;
4029 if (match(NextInst,
4030 m_Intrinsic<Intrinsic::experimental_guard>(m_Value(NextCond)))) {
4031 Value *CurrCond = II->getArgOperand(0);
Artur Pilipenkoe812ca02017-01-25 14:12:12 +00004032
Simon Pilgrim68168d12017-03-30 12:59:53 +00004033 // Remove a guard that it is immediately preceded by an identical guard.
Sanjoy Dase0e57952017-02-01 16:34:55 +00004034 if (CurrCond == NextCond)
4035 return eraseInstFromFunction(*NextInst);
4036
4037 // Otherwise canonicalize guard(a); guard(b) -> guard(a & b).
Philip Reames79e917d2018-05-09 22:56:32 +00004038 Instruction* MoveI = II->getNextNode();
4039 while (MoveI != NextInst) {
4040 auto *Temp = MoveI;
4041 MoveI = MoveI->getNextNode();
4042 Temp->moveBefore(II);
4043 }
Craig Topperbb4069e2017-07-07 23:16:26 +00004044 II->setArgOperand(0, Builder.CreateAnd(CurrCond, NextCond));
Sanjoy Dase0e57952017-02-01 16:34:55 +00004045 return eraseInstFromFunction(*NextInst);
4046 }
Artur Pilipenkoe812ca02017-01-25 14:12:12 +00004047 break;
4048 }
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004049 }
Craig Topperc1892ec2019-01-31 17:23:29 +00004050 return visitCallBase(*II);
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004051}
4052
Davide Italianoaec46172017-01-31 18:09:05 +00004053// Fence instruction simplification
4054Instruction *InstCombiner::visitFenceInst(FenceInst &FI) {
4055 // Remove identical consecutive fences.
Vedant Kumarf01827f2018-06-19 23:42:17 +00004056 Instruction *Next = FI.getNextNonDebugInstruction();
Tim Northover9b800602018-06-06 12:46:02 +00004057 if (auto *NFI = dyn_cast<FenceInst>(Next))
Davide Italianoaec46172017-01-31 18:09:05 +00004058 if (FI.isIdenticalTo(NFI))
4059 return eraseInstFromFunction(FI);
4060 return nullptr;
4061}
4062
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004063// InvokeInst simplification
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004064Instruction *InstCombiner::visitInvokeInst(InvokeInst &II) {
Craig Topperc1892ec2019-01-31 17:23:29 +00004065 return visitCallBase(II);
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004066}
4067
Craig Topper784929d2019-02-08 20:48:56 +00004068// CallBrInst simplification
4069Instruction *InstCombiner::visitCallBrInst(CallBrInst &CBI) {
4070 return visitCallBase(CBI);
4071}
4072
Sanjay Patelcd4377c2016-01-20 22:24:38 +00004073/// If this cast does not affect the value passed through the varargs area, we
4074/// can eliminate the use of the cast.
Craig Topperc1892ec2019-01-31 17:23:29 +00004075static bool isSafeToEliminateVarargsCast(const CallBase &Call,
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004076 const DataLayout &DL,
4077 const CastInst *const CI,
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004078 const int ix) {
4079 if (!CI->isLosslessCast())
4080 return false;
4081
Philip Reames1a1bdb22014-12-02 18:50:36 +00004082 // If this is a GC intrinsic, avoid munging types. We need types for
4083 // statepoint reconstruction in SelectionDAG.
4084 // TODO: This is probably something which should be expanded to all
4085 // intrinsics since the entire point of intrinsics is that
4086 // they are understandable by the optimizer.
Craig Topperc1892ec2019-01-31 17:23:29 +00004087 if (isStatepoint(&Call) || isGCRelocate(&Call) || isGCResult(&Call))
Philip Reames1a1bdb22014-12-02 18:50:36 +00004088 return false;
4089
Reid Kleckner26af2ca2014-01-28 02:38:36 +00004090 // The size of ByVal or InAlloca arguments is derived from the type, so we
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004091 // can't change to a type with a different size. If the size were
4092 // passed explicitly we could avoid this check.
Craig Topperc1892ec2019-01-31 17:23:29 +00004093 if (!Call.isByValOrInAllocaArgument(ix))
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004094 return true;
4095
Jim Grosbach7815f562012-02-03 00:07:04 +00004096 Type* SrcTy =
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004097 cast<PointerType>(CI->getOperand(0)->getType())->getElementType();
Tim Northover8d7f1182019-06-05 20:38:17 +00004098 Type *DstTy = Call.isByValArgument(ix)
4099 ? Call.getParamByValType(ix)
4100 : cast<PointerType>(CI->getType())->getElementType();
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004101 if (!SrcTy->isSized() || !DstTy->isSized())
4102 return false;
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004103 if (DL.getTypeAllocSize(SrcTy) != DL.getTypeAllocSize(DstTy))
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004104 return false;
4105 return true;
4106}
4107
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004108Instruction *InstCombiner::tryOptimizeCall(CallInst *CI) {
Craig Topperf40110f2014-04-25 05:29:35 +00004109 if (!CI->getCalledFunction()) return nullptr;
Eric Christophera7fb58f2010-03-06 10:50:38 +00004110
Chandler Carruthba4c5172015-01-21 11:23:40 +00004111 auto InstCombineRAUW = [this](Instruction *From, Value *With) {
Sanjay Patel4b198802016-02-01 22:23:39 +00004112 replaceInstUsesWith(*From, With);
Chandler Carruthba4c5172015-01-21 11:23:40 +00004113 };
Amara Emerson54f60252018-10-11 14:51:11 +00004114 auto InstCombineErase = [this](Instruction *I) {
4115 eraseInstFromFunction(*I);
4116 };
Hiroshi Yamauchi09e539f2019-04-15 16:49:00 +00004117 LibCallSimplifier Simplifier(DL, &TLI, ORE, BFI, PSI, InstCombineRAUW,
Amara Emerson54f60252018-10-11 14:51:11 +00004118 InstCombineErase);
Chandler Carruthba4c5172015-01-21 11:23:40 +00004119 if (Value *With = Simplifier.optimizeCall(CI)) {
Meador Ingee3f2b262012-11-30 04:05:06 +00004120 ++NumSimplified;
Sanjay Patel4b198802016-02-01 22:23:39 +00004121 return CI->use_empty() ? CI : replaceInstUsesWith(*CI, With);
Meador Ingee3f2b262012-11-30 04:05:06 +00004122 }
Meador Ingedf796f82012-10-13 16:45:24 +00004123
Craig Topperf40110f2014-04-25 05:29:35 +00004124 return nullptr;
Eric Christophera7fb58f2010-03-06 10:50:38 +00004125}
4126
Sanjay Patel6038d3e2016-01-29 23:27:03 +00004127static IntrinsicInst *findInitTrampolineFromAlloca(Value *TrampMem) {
Duncan Sandsa0984362011-09-06 13:37:06 +00004128 // Strip off at most one level of pointer casts, looking for an alloca. This
4129 // is good enough in practice and simpler than handling any number of casts.
4130 Value *Underlying = TrampMem->stripPointerCasts();
4131 if (Underlying != TrampMem &&
Chandler Carruthcdf47882014-03-09 03:16:01 +00004132 (!Underlying->hasOneUse() || Underlying->user_back() != TrampMem))
Craig Topperf40110f2014-04-25 05:29:35 +00004133 return nullptr;
Duncan Sandsa0984362011-09-06 13:37:06 +00004134 if (!isa<AllocaInst>(Underlying))
Craig Topperf40110f2014-04-25 05:29:35 +00004135 return nullptr;
Duncan Sandsa0984362011-09-06 13:37:06 +00004136
Craig Topperf40110f2014-04-25 05:29:35 +00004137 IntrinsicInst *InitTrampoline = nullptr;
Chandler Carruthcdf47882014-03-09 03:16:01 +00004138 for (User *U : TrampMem->users()) {
4139 IntrinsicInst *II = dyn_cast<IntrinsicInst>(U);
Duncan Sandsa0984362011-09-06 13:37:06 +00004140 if (!II)
Craig Topperf40110f2014-04-25 05:29:35 +00004141 return nullptr;
Duncan Sandsa0984362011-09-06 13:37:06 +00004142 if (II->getIntrinsicID() == Intrinsic::init_trampoline) {
4143 if (InitTrampoline)
4144 // More than one init_trampoline writes to this value. Give up.
Craig Topperf40110f2014-04-25 05:29:35 +00004145 return nullptr;
Duncan Sandsa0984362011-09-06 13:37:06 +00004146 InitTrampoline = II;
4147 continue;
4148 }
4149 if (II->getIntrinsicID() == Intrinsic::adjust_trampoline)
4150 // Allow any number of calls to adjust.trampoline.
4151 continue;
Craig Topperf40110f2014-04-25 05:29:35 +00004152 return nullptr;
Duncan Sandsa0984362011-09-06 13:37:06 +00004153 }
4154
4155 // No call to init.trampoline found.
4156 if (!InitTrampoline)
Craig Topperf40110f2014-04-25 05:29:35 +00004157 return nullptr;
Duncan Sandsa0984362011-09-06 13:37:06 +00004158
4159 // Check that the alloca is being used in the expected way.
4160 if (InitTrampoline->getOperand(0) != TrampMem)
Craig Topperf40110f2014-04-25 05:29:35 +00004161 return nullptr;
Duncan Sandsa0984362011-09-06 13:37:06 +00004162
4163 return InitTrampoline;
4164}
4165
Sanjay Patel6038d3e2016-01-29 23:27:03 +00004166static IntrinsicInst *findInitTrampolineFromBB(IntrinsicInst *AdjustTramp,
Duncan Sandsa0984362011-09-06 13:37:06 +00004167 Value *TrampMem) {
4168 // Visit all the previous instructions in the basic block, and try to find a
4169 // init.trampoline which has a direct path to the adjust.trampoline.
Duncan P. N. Exon Smith9f8aaf22015-10-13 16:59:33 +00004170 for (BasicBlock::iterator I = AdjustTramp->getIterator(),
4171 E = AdjustTramp->getParent()->begin();
4172 I != E;) {
4173 Instruction *Inst = &*--I;
Duncan Sandsa0984362011-09-06 13:37:06 +00004174 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I))
4175 if (II->getIntrinsicID() == Intrinsic::init_trampoline &&
4176 II->getOperand(0) == TrampMem)
4177 return II;
4178 if (Inst->mayWriteToMemory())
Craig Topperf40110f2014-04-25 05:29:35 +00004179 return nullptr;
Duncan Sandsa0984362011-09-06 13:37:06 +00004180 }
Craig Topperf40110f2014-04-25 05:29:35 +00004181 return nullptr;
Duncan Sandsa0984362011-09-06 13:37:06 +00004182}
4183
4184// Given a call to llvm.adjust.trampoline, find and return the corresponding
4185// call to llvm.init.trampoline if the call to the trampoline can be optimized
4186// to a direct call to a function. Otherwise return NULL.
Sanjay Patel6038d3e2016-01-29 23:27:03 +00004187static IntrinsicInst *findInitTrampoline(Value *Callee) {
Duncan Sandsa0984362011-09-06 13:37:06 +00004188 Callee = Callee->stripPointerCasts();
4189 IntrinsicInst *AdjustTramp = dyn_cast<IntrinsicInst>(Callee);
4190 if (!AdjustTramp ||
4191 AdjustTramp->getIntrinsicID() != Intrinsic::adjust_trampoline)
Craig Topperf40110f2014-04-25 05:29:35 +00004192 return nullptr;
Duncan Sandsa0984362011-09-06 13:37:06 +00004193
4194 Value *TrampMem = AdjustTramp->getOperand(0);
4195
Sanjay Patel6038d3e2016-01-29 23:27:03 +00004196 if (IntrinsicInst *IT = findInitTrampolineFromAlloca(TrampMem))
Duncan Sandsa0984362011-09-06 13:37:06 +00004197 return IT;
Sanjay Patel6038d3e2016-01-29 23:27:03 +00004198 if (IntrinsicInst *IT = findInitTrampolineFromBB(AdjustTramp, TrampMem))
Duncan Sandsa0984362011-09-06 13:37:06 +00004199 return IT;
Craig Topperf40110f2014-04-25 05:29:35 +00004200 return nullptr;
Duncan Sandsa0984362011-09-06 13:37:06 +00004201}
4202
David Bolvansky05bda8b2019-08-28 08:28:20 +00004203static void annotateAnyAllocSite(CallBase &Call, const TargetLibraryInfo *TLI) {
David Bolvansky48db0272019-09-23 19:55:45 +00004204 unsigned NumArgs = Call.getNumArgOperands();
David Bolvansky05bda8b2019-08-28 08:28:20 +00004205 ConstantInt *Op0C = dyn_cast<ConstantInt>(Call.getOperand(0));
David Bolvansky48db0272019-09-23 19:55:45 +00004206 ConstantInt *Op1C =
4207 (NumArgs == 1) ? nullptr : dyn_cast<ConstantInt>(Call.getOperand(1));
David Bolvanskyaf118bb2019-08-28 15:04:48 +00004208 // Bail out if the allocation size is zero.
David Bolvansky05bda8b2019-08-28 08:28:20 +00004209 if ((Op0C && Op0C->isNullValue()) || (Op1C && Op1C->isNullValue()))
4210 return;
David Bolvanskyaf118bb2019-08-28 15:04:48 +00004211
David Bolvansky05bda8b2019-08-28 08:28:20 +00004212 if (isMallocLikeFn(&Call, TLI) && Op0C) {
David Bolvansky4dae2832019-09-11 10:37:03 +00004213 if (isOpNewLikeFn(&Call, TLI))
4214 Call.addAttribute(AttributeList::ReturnIndex,
4215 Attribute::getWithDereferenceableBytes(
4216 Call.getContext(), Op0C->getZExtValue()));
4217 else
4218 Call.addAttribute(AttributeList::ReturnIndex,
4219 Attribute::getWithDereferenceableOrNullBytes(
4220 Call.getContext(), Op0C->getZExtValue()));
David Bolvansky05bda8b2019-08-28 08:28:20 +00004221 } else if (isReallocLikeFn(&Call, TLI) && Op1C) {
4222 Call.addAttribute(AttributeList::ReturnIndex,
4223 Attribute::getWithDereferenceableOrNullBytes(
4224 Call.getContext(), Op1C->getZExtValue()));
4225 } else if (isCallocLikeFn(&Call, TLI) && Op0C && Op1C) {
4226 bool Overflow;
4227 const APInt &N = Op0C->getValue();
4228 APInt Size = N.umul_ov(Op1C->getValue(), Overflow);
4229 if (!Overflow)
4230 Call.addAttribute(AttributeList::ReturnIndex,
4231 Attribute::getWithDereferenceableOrNullBytes(
4232 Call.getContext(), Size.getZExtValue()));
David Bolvansky48db0272019-09-23 19:55:45 +00004233 } else if (isStrdupLikeFn(&Call, TLI)) {
4234 uint64_t Len = GetStringLength(Call.getOperand(0));
4235 if (Len) {
4236 // strdup
4237 if (NumArgs == 1)
4238 Call.addAttribute(AttributeList::ReturnIndex,
4239 Attribute::getWithDereferenceableOrNullBytes(
4240 Call.getContext(), Len));
4241 // strndup
4242 else if (NumArgs == 2 && Op1C)
4243 Call.addAttribute(
4244 AttributeList::ReturnIndex,
4245 Attribute::getWithDereferenceableOrNullBytes(
4246 Call.getContext(), std::min(Len, Op1C->getZExtValue() + 1)));
4247 }
David Bolvansky05bda8b2019-08-28 08:28:20 +00004248 }
4249}
4250
Craig Topper784929d2019-02-08 20:48:56 +00004251/// Improvements for call, callbr and invoke instructions.
Craig Topperc1892ec2019-01-31 17:23:29 +00004252Instruction *InstCombiner::visitCallBase(CallBase &Call) {
David Bolvansky05bda8b2019-08-28 08:28:20 +00004253 if (isAllocationFn(&Call, &TLI))
4254 annotateAnyAllocSite(Call, &TLI);
4255
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004256 bool Changed = false;
4257
Philip Reamesc25df112015-06-16 20:24:25 +00004258 // Mark any parameters that are known to be non-null with the nonnull
4259 // attribute. This is helpful for inlining calls to functions with null
4260 // checks on their arguments.
Reid Kleckner5fbdd172017-05-31 19:23:09 +00004261 SmallVector<unsigned, 4> ArgNos;
Philip Reamesc25df112015-06-16 20:24:25 +00004262 unsigned ArgNo = 0;
Akira Hatanaka237916b2015-12-02 06:58:49 +00004263
Craig Topperc1892ec2019-01-31 17:23:29 +00004264 for (Value *V : Call.args()) {
Sanjay Patelf9f5d3c2016-01-29 23:14:58 +00004265 if (V->getType()->isPointerTy() &&
Craig Topperc1892ec2019-01-31 17:23:29 +00004266 !Call.paramHasAttr(ArgNo, Attribute::NonNull) &&
4267 isKnownNonZero(V, DL, 0, &AC, &Call, &DT))
Reid Kleckner5fbdd172017-05-31 19:23:09 +00004268 ArgNos.push_back(ArgNo);
Philip Reamesc25df112015-06-16 20:24:25 +00004269 ArgNo++;
4270 }
Akira Hatanaka237916b2015-12-02 06:58:49 +00004271
Craig Topperc1892ec2019-01-31 17:23:29 +00004272 assert(ArgNo == Call.arg_size() && "sanity check");
Philip Reamesc25df112015-06-16 20:24:25 +00004273
Reid Kleckner5fbdd172017-05-31 19:23:09 +00004274 if (!ArgNos.empty()) {
Craig Topperc1892ec2019-01-31 17:23:29 +00004275 AttributeList AS = Call.getAttributes();
4276 LLVMContext &Ctx = Call.getContext();
Reid Kleckner5fbdd172017-05-31 19:23:09 +00004277 AS = AS.addParamAttribute(Ctx, ArgNos,
4278 Attribute::get(Ctx, Attribute::NonNull));
Craig Topperc1892ec2019-01-31 17:23:29 +00004279 Call.setAttributes(AS);
Akira Hatanaka237916b2015-12-02 06:58:49 +00004280 Changed = true;
4281 }
4282
Chris Lattner73989652010-12-20 08:25:06 +00004283 // If the callee is a pointer to a function, attempt to move any casts to the
Craig Topper784929d2019-02-08 20:48:56 +00004284 // arguments of the call/callbr/invoke.
Craig Topperc1892ec2019-01-31 17:23:29 +00004285 Value *Callee = Call.getCalledValue();
4286 if (!isa<Function>(Callee) && transformConstExprCastCall(Call))
Craig Topperf40110f2014-04-25 05:29:35 +00004287 return nullptr;
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004288
Justin Lebar9d943972016-03-14 20:18:54 +00004289 if (Function *CalleeF = dyn_cast<Function>(Callee)) {
4290 // Remove the convergent attr on calls when the callee is not convergent.
Craig Topperc1892ec2019-01-31 17:23:29 +00004291 if (Call.isConvergent() && !CalleeF->isConvergent() &&
Matt Arsenault802ebcb2016-06-20 19:04:44 +00004292 !CalleeF->isIntrinsic()) {
Craig Topperc1892ec2019-01-31 17:23:29 +00004293 LLVM_DEBUG(dbgs() << "Removing convergent attr from instr " << Call
4294 << "\n");
4295 Call.setNotConvergent();
4296 return &Call;
Justin Lebar9d943972016-03-14 20:18:54 +00004297 }
4298
Chris Lattner846a52e2010-02-01 18:11:34 +00004299 // If the call and callee calling conventions don't match, this call must
4300 // be unreachable, as the call is undefined.
Craig Topperc1892ec2019-01-31 17:23:29 +00004301 if (CalleeF->getCallingConv() != Call.getCallingConv() &&
Chris Lattner846a52e2010-02-01 18:11:34 +00004302 // Only do this for calls to a function with a body. A prototype may
4303 // not actually end up matching the implementation's calling conv for a
4304 // variety of reasons (e.g. it may be written in assembly).
4305 !CalleeF->isDeclaration()) {
Craig Topperc1892ec2019-01-31 17:23:29 +00004306 Instruction *OldCall = &Call;
Philip Reames88679712019-04-17 17:37:58 +00004307 CreateNonTerminatorUnreachable(OldCall);
Chad Rosiere28ae302012-12-13 00:18:46 +00004308 // If OldCall does not return void then replaceAllUsesWith undef.
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004309 // This allows ValueHandlers and custom metadata to adjust itself.
4310 if (!OldCall->getType()->isVoidTy())
Sanjay Patel4b198802016-02-01 22:23:39 +00004311 replaceInstUsesWith(*OldCall, UndefValue::get(OldCall->getType()));
Chris Lattner2cecedf2010-02-01 18:04:58 +00004312 if (isa<CallInst>(OldCall))
Sanjay Patel4b198802016-02-01 22:23:39 +00004313 return eraseInstFromFunction(*OldCall);
Jim Grosbach7815f562012-02-03 00:07:04 +00004314
Craig Topper784929d2019-02-08 20:48:56 +00004315 // We cannot remove an invoke or a callbr, because it would change thexi
4316 // CFG, just change the callee to a null pointer.
4317 cast<CallBase>(OldCall)->setCalledFunction(
James Y Knight291f7912019-02-01 20:44:54 +00004318 CalleeF->getFunctionType(),
4319 Constant::getNullValue(CalleeF->getType()));
Craig Topperf40110f2014-04-25 05:29:35 +00004320 return nullptr;
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004321 }
Justin Lebar9d943972016-03-14 20:18:54 +00004322 }
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004323
Manoj Gupta77eeac32018-07-09 22:27:23 +00004324 if ((isa<ConstantPointerNull>(Callee) &&
Craig Topperc1892ec2019-01-31 17:23:29 +00004325 !NullPointerIsDefined(Call.getFunction())) ||
Manoj Gupta77eeac32018-07-09 22:27:23 +00004326 isa<UndefValue>(Callee)) {
Craig Topperc1892ec2019-01-31 17:23:29 +00004327 // If Call does not return void then replaceAllUsesWith undef.
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004328 // This allows ValueHandlers and custom metadata to adjust itself.
Craig Topperc1892ec2019-01-31 17:23:29 +00004329 if (!Call.getType()->isVoidTy())
4330 replaceInstUsesWith(Call, UndefValue::get(Call.getType()));
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004331
Craig Topper784929d2019-02-08 20:48:56 +00004332 if (Call.isTerminator()) {
4333 // Can't remove an invoke or callbr because we cannot change the CFG.
Craig Topperf40110f2014-04-25 05:29:35 +00004334 return nullptr;
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004335 }
Nuno Lopes771e7bd2012-06-21 23:52:14 +00004336
Philip Reames88679712019-04-17 17:37:58 +00004337 // This instruction is not reachable, just remove it.
4338 CreateNonTerminatorUnreachable(&Call);
Craig Topperc1892ec2019-01-31 17:23:29 +00004339 return eraseInstFromFunction(Call);
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004340 }
4341
Sanjay Patel6038d3e2016-01-29 23:27:03 +00004342 if (IntrinsicInst *II = findInitTrampoline(Callee))
Craig Topperc1892ec2019-01-31 17:23:29 +00004343 return transformCallThroughTrampoline(Call, *II);
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004344
Chris Lattner229907c2011-07-18 04:54:35 +00004345 PointerType *PTy = cast<PointerType>(Callee->getType());
4346 FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004347 if (FTy->isVarArg()) {
Eli Friedman7534b4682011-11-29 01:18:23 +00004348 int ix = FTy->getNumParams();
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004349 // See if we can optimize any arguments passed through the varargs area of
4350 // the call.
Craig Topperc1892ec2019-01-31 17:23:29 +00004351 for (auto I = Call.arg_begin() + FTy->getNumParams(), E = Call.arg_end();
4352 I != E; ++I, ++ix) {
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004353 CastInst *CI = dyn_cast<CastInst>(*I);
Craig Topperc1892ec2019-01-31 17:23:29 +00004354 if (CI && isSafeToEliminateVarargsCast(Call, DL, CI, ix)) {
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004355 *I = CI->getOperand(0);
Tim Northover8d7f1182019-06-05 20:38:17 +00004356
4357 // Update the byval type to match the argument type.
4358 if (Call.isByValArgument(ix)) {
4359 Call.removeParamAttr(ix, Attribute::ByVal);
4360 Call.addParamAttr(
4361 ix, Attribute::getWithByValType(
4362 Call.getContext(),
4363 CI->getOperand(0)->getType()->getPointerElementType()));
4364 }
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004365 Changed = true;
4366 }
4367 }
4368 }
4369
Craig Topperc1892ec2019-01-31 17:23:29 +00004370 if (isa<InlineAsm>(Callee) && !Call.doesNotThrow()) {
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004371 // Inline asm calls cannot throw - mark them 'nounwind'.
Craig Topperc1892ec2019-01-31 17:23:29 +00004372 Call.setDoesNotThrow();
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004373 Changed = true;
4374 }
4375
Micah Villmowcdfe20b2012-10-08 16:38:25 +00004376 // Try to optimize the call if possible, we require DataLayout for most of
Eric Christophera7fb58f2010-03-06 10:50:38 +00004377 // this. None of these calls are seen as possibly dead so go ahead and
4378 // delete the instruction now.
Craig Topperc1892ec2019-01-31 17:23:29 +00004379 if (CallInst *CI = dyn_cast<CallInst>(&Call)) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004380 Instruction *I = tryOptimizeCall(CI);
Eric Christopher1810d772010-03-06 10:59:25 +00004381 // If we changed something return the result, etc. Otherwise let
4382 // the fallthrough check.
Sanjay Patel4b198802016-02-01 22:23:39 +00004383 if (I) return eraseInstFromFunction(*I);
Eric Christophera7fb58f2010-03-06 10:50:38 +00004384 }
4385
David Bolvansky8d520162019-09-23 18:20:01 +00004386 if (isAllocLikeFn(&Call, &TLI))
4387 return visitAllocSite(Call);
4388
Craig Topperc1892ec2019-01-31 17:23:29 +00004389 return Changed ? &Call : nullptr;
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004390}
4391
Sanjay Patelcd4377c2016-01-20 22:24:38 +00004392/// If the callee is a constexpr cast of a function, attempt to move the cast to
Craig Topper784929d2019-02-08 20:48:56 +00004393/// the arguments of the call/callbr/invoke.
Craig Topperc1892ec2019-01-31 17:23:29 +00004394bool InstCombiner::transformConstExprCastCall(CallBase &Call) {
4395 auto *Callee = dyn_cast<Function>(Call.getCalledValue()->stripPointerCasts());
Craig Topperf40110f2014-04-25 05:29:35 +00004396 if (!Callee)
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004397 return false;
Sanjay Patel38ae83d2016-08-11 15:23:56 +00004398
Reid Kleckner298ffc62018-04-02 22:49:44 +00004399 // If this is a call to a thunk function, don't remove the cast. Thunks are
4400 // used to transparently forward all incoming parameters and outgoing return
4401 // values, so it's important to leave the cast in place.
David Majnemer4c0a6e92015-01-21 22:32:04 +00004402 if (Callee->hasFnAttribute("thunk"))
4403 return false;
Sanjay Patel38ae83d2016-08-11 15:23:56 +00004404
Reid Kleckner298ffc62018-04-02 22:49:44 +00004405 // If this is a musttail call, the callee's prototype must match the caller's
4406 // prototype with the exception of pointee types. The code below doesn't
4407 // implement that, so we can't do this transform.
4408 // TODO: Do the transform if it only requires adding pointer casts.
Craig Topperc1892ec2019-01-31 17:23:29 +00004409 if (Call.isMustTailCall())
Reid Kleckner298ffc62018-04-02 22:49:44 +00004410 return false;
4411
Craig Topperc1892ec2019-01-31 17:23:29 +00004412 Instruction *Caller = &Call;
4413 const AttributeList &CallerPAL = Call.getAttributes();
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004414
4415 // Okay, this is a cast from a function to a different type. Unless doing so
4416 // would cause a type conversion of one of our arguments, change this call to
4417 // be a direct call with arguments casted to the appropriate types.
Chris Lattner229907c2011-07-18 04:54:35 +00004418 FunctionType *FT = Callee->getFunctionType();
4419 Type *OldRetTy = Caller->getType();
4420 Type *NewRetTy = FT->getReturnType();
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004421
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004422 // Check to see if we are changing the return type...
4423 if (OldRetTy != NewRetTy) {
Nick Lewyckya6a17d72014-01-18 22:47:12 +00004424
4425 if (NewRetTy->isStructTy())
4426 return false; // TODO: Handle multiple return values.
4427
David Majnemer9b6b8222015-01-06 08:41:31 +00004428 if (!CastInst::isBitOrNoopPointerCastable(NewRetTy, OldRetTy, DL)) {
Matt Arsenaulte6952f22013-09-17 21:10:14 +00004429 if (Callee->isDeclaration())
4430 return false; // Cannot transform this return value.
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004431
Matt Arsenaulte6952f22013-09-17 21:10:14 +00004432 if (!Caller->use_empty() &&
4433 // void -> non-void is handled specially
4434 !NewRetTy->isVoidTy())
Frederic Rissc1892e22014-10-23 04:08:42 +00004435 return false; // Cannot transform this return value.
Matt Arsenaulte6952f22013-09-17 21:10:14 +00004436 }
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004437
4438 if (!CallerPAL.isEmpty() && !Caller->use_empty()) {
Reid Klecknerb5180542017-03-21 16:57:19 +00004439 AttrBuilder RAttrs(CallerPAL, AttributeList::ReturnIndex);
Pete Cooper2777d8872015-05-06 23:19:56 +00004440 if (RAttrs.overlaps(AttributeFuncs::typeIncompatible(NewRetTy)))
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004441 return false; // Attribute not compatible with transformed value.
4442 }
4443
Craig Topper784929d2019-02-08 20:48:56 +00004444 // If the callbase is an invoke/callbr instruction, and the return value is
4445 // used by a PHI node in a successor, we cannot change the return type of
4446 // the call because there is no place to put the cast instruction (without
4447 // breaking the critical edge). Bail out in this case.
4448 if (!Caller->use_empty()) {
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004449 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller))
Chandler Carruthcdf47882014-03-09 03:16:01 +00004450 for (User *U : II->users())
4451 if (PHINode *PN = dyn_cast<PHINode>(U))
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004452 if (PN->getParent() == II->getNormalDest() ||
4453 PN->getParent() == II->getUnwindDest())
4454 return false;
Craig Topper784929d2019-02-08 20:48:56 +00004455 // FIXME: Be conservative for callbr to avoid a quadratic search.
Craig Toppera97857b2019-02-10 02:21:29 +00004456 if (isa<CallBrInst>(Caller))
Craig Topper784929d2019-02-08 20:48:56 +00004457 return false;
4458 }
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004459 }
4460
Craig Topperc1892ec2019-01-31 17:23:29 +00004461 unsigned NumActualArgs = Call.arg_size();
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004462 unsigned NumCommonArgs = std::min(FT->getNumParams(), NumActualArgs);
4463
David Majnemer9b6b8222015-01-06 08:41:31 +00004464 // Prevent us turning:
4465 // declare void @takes_i32_inalloca(i32* inalloca)
4466 // call void bitcast (void (i32*)* @takes_i32_inalloca to void (i32)*)(i32 0)
4467 //
4468 // into:
4469 // call void @takes_i32_inalloca(i32* null)
David Majnemerd61a6fd2015-03-11 18:03:05 +00004470 //
4471 // Similarly, avoid folding away bitcasts of byval calls.
4472 if (Callee->getAttributes().hasAttrSomewhere(Attribute::InAlloca) ||
4473 Callee->getAttributes().hasAttrSomewhere(Attribute::ByVal))
David Majnemer9b6b8222015-01-06 08:41:31 +00004474 return false;
4475
Craig Topperc1892ec2019-01-31 17:23:29 +00004476 auto AI = Call.arg_begin();
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004477 for (unsigned i = 0, e = NumCommonArgs; i != e; ++i, ++AI) {
Chris Lattner229907c2011-07-18 04:54:35 +00004478 Type *ParamTy = FT->getParamType(i);
4479 Type *ActTy = (*AI)->getType();
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004480
David Majnemer9b6b8222015-01-06 08:41:31 +00004481 if (!CastInst::isBitOrNoopPointerCastable(ActTy, ParamTy, DL))
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004482 return false; // Cannot transform this parameter value.
4483
Reid Klecknerf021fab2017-04-13 23:12:13 +00004484 if (AttrBuilder(CallerPAL.getParamAttributes(i))
4485 .overlaps(AttributeFuncs::typeIncompatible(ParamTy)))
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004486 return false; // Attribute not compatible with transformed value.
Jim Grosbach7815f562012-02-03 00:07:04 +00004487
Craig Topperc1892ec2019-01-31 17:23:29 +00004488 if (Call.isInAllocaArgument(i))
Reid Kleckner26af2ca2014-01-28 02:38:36 +00004489 return false; // Cannot transform to and from inalloca.
4490
Chris Lattner27ca8eb2010-12-20 08:36:38 +00004491 // If the parameter is passed as a byval argument, then we have to have a
4492 // sized type and the sized type has to have the same size as the old type.
Reid Klecknerf021fab2017-04-13 23:12:13 +00004493 if (ParamTy != ActTy && CallerPAL.hasParamAttribute(i, Attribute::ByVal)) {
Chris Lattner229907c2011-07-18 04:54:35 +00004494 PointerType *ParamPTy = dyn_cast<PointerType>(ParamTy);
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004495 if (!ParamPTy || !ParamPTy->getElementType()->isSized())
Chris Lattner27ca8eb2010-12-20 08:36:38 +00004496 return false;
Jim Grosbach7815f562012-02-03 00:07:04 +00004497
Tim Northover8d7f1182019-06-05 20:38:17 +00004498 Type *CurElTy = Call.getParamByValType(i);
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004499 if (DL.getTypeAllocSize(CurElTy) !=
4500 DL.getTypeAllocSize(ParamPTy->getElementType()))
Chris Lattner27ca8eb2010-12-20 08:36:38 +00004501 return false;
4502 }
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004503 }
4504
Chris Lattneradf38b32011-02-24 05:10:56 +00004505 if (Callee->isDeclaration()) {
4506 // Do not delete arguments unless we have a function body.
4507 if (FT->getNumParams() < NumActualArgs && !FT->isVarArg())
4508 return false;
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004509
Chris Lattneradf38b32011-02-24 05:10:56 +00004510 // If the callee is just a declaration, don't change the varargsness of the
4511 // call. We don't want to introduce a varargs call where one doesn't
4512 // already exist.
Craig Topperc1892ec2019-01-31 17:23:29 +00004513 PointerType *APTy = cast<PointerType>(Call.getCalledValue()->getType());
Chris Lattneradf38b32011-02-24 05:10:56 +00004514 if (FT->isVarArg()!=cast<FunctionType>(APTy->getElementType())->isVarArg())
4515 return false;
Jim Grosbache84ae7b2012-02-03 00:00:55 +00004516
4517 // If both the callee and the cast type are varargs, we still have to make
4518 // sure the number of fixed parameters are the same or we have the same
4519 // ABI issues as if we introduce a varargs call.
Jim Grosbach1df8cdc2012-02-03 00:26:07 +00004520 if (FT->isVarArg() &&
4521 cast<FunctionType>(APTy->getElementType())->isVarArg() &&
4522 FT->getNumParams() !=
Jim Grosbache84ae7b2012-02-03 00:00:55 +00004523 cast<FunctionType>(APTy->getElementType())->getNumParams())
4524 return false;
Chris Lattneradf38b32011-02-24 05:10:56 +00004525 }
Jim Grosbach7815f562012-02-03 00:07:04 +00004526
Jim Grosbach0ab54182012-02-03 00:00:50 +00004527 if (FT->getNumParams() < NumActualArgs && FT->isVarArg() &&
Reid Kleckneraa0cec72017-04-19 23:17:47 +00004528 !CallerPAL.isEmpty()) {
Jim Grosbach0ab54182012-02-03 00:00:50 +00004529 // In this case we have more arguments than the new function type, but we
4530 // won't be dropping them. Check that these extra arguments have attributes
4531 // that are compatible with being a vararg call argument.
Reid Kleckneraa0cec72017-04-19 23:17:47 +00004532 unsigned SRetIdx;
4533 if (CallerPAL.hasAttrSomewhere(Attribute::StructRet, &SRetIdx) &&
4534 SRetIdx > FT->getNumParams())
4535 return false;
4536 }
Jim Grosbach7815f562012-02-03 00:07:04 +00004537
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004538 // Okay, we decided that this is a safe thing to do: go ahead and start
Chris Lattneradf38b32011-02-24 05:10:56 +00004539 // inserting cast instructions as necessary.
Reid Klecknerc3fae792017-04-13 18:11:03 +00004540 SmallVector<Value *, 8> Args;
4541 SmallVector<AttributeSet, 8> ArgAttrs;
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004542 Args.reserve(NumActualArgs);
Reid Klecknerc3fae792017-04-13 18:11:03 +00004543 ArgAttrs.reserve(NumActualArgs);
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004544
4545 // Get any return attributes.
Reid Klecknerb5180542017-03-21 16:57:19 +00004546 AttrBuilder RAttrs(CallerPAL, AttributeList::ReturnIndex);
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004547
4548 // If the return value is not being used, the type may not be compatible
4549 // with the existing attributes. Wipe out any problematic attributes.
Pete Cooper2777d8872015-05-06 23:19:56 +00004550 RAttrs.remove(AttributeFuncs::typeIncompatible(NewRetTy));
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004551
Tim Northover8d7f1182019-06-05 20:38:17 +00004552 LLVMContext &Ctx = Call.getContext();
Craig Topperc1892ec2019-01-31 17:23:29 +00004553 AI = Call.arg_begin();
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004554 for (unsigned i = 0; i != NumCommonArgs; ++i, ++AI) {
Chris Lattner229907c2011-07-18 04:54:35 +00004555 Type *ParamTy = FT->getParamType(i);
Matt Arsenaultcacbb232013-07-30 20:45:05 +00004556
Reid Klecknerc3fae792017-04-13 18:11:03 +00004557 Value *NewArg = *AI;
4558 if ((*AI)->getType() != ParamTy)
Craig Topperbb4069e2017-07-07 23:16:26 +00004559 NewArg = Builder.CreateBitOrPointerCast(*AI, ParamTy);
Reid Klecknerc3fae792017-04-13 18:11:03 +00004560 Args.push_back(NewArg);
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004561
4562 // Add any parameter attributes.
Tim Northover8d7f1182019-06-05 20:38:17 +00004563 if (CallerPAL.hasParamAttribute(i, Attribute::ByVal)) {
4564 AttrBuilder AB(CallerPAL.getParamAttributes(i));
4565 AB.addByValAttr(NewArg->getType()->getPointerElementType());
4566 ArgAttrs.push_back(AttributeSet::get(Ctx, AB));
4567 } else
4568 ArgAttrs.push_back(CallerPAL.getParamAttributes(i));
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004569 }
4570
4571 // If the function takes more arguments than the call was taking, add them
4572 // now.
Reid Klecknerc3fae792017-04-13 18:11:03 +00004573 for (unsigned i = NumCommonArgs; i != FT->getNumParams(); ++i) {
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004574 Args.push_back(Constant::getNullValue(FT->getParamType(i)));
Reid Klecknerc3fae792017-04-13 18:11:03 +00004575 ArgAttrs.push_back(AttributeSet());
4576 }
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004577
4578 // If we are removing arguments to the function, emit an obnoxious warning.
4579 if (FT->getNumParams() < NumActualArgs) {
Nick Lewycky90053a12012-12-26 22:00:35 +00004580 // TODO: if (!FT->isVarArg()) this call may be unreachable. PR14722
4581 if (FT->isVarArg()) {
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004582 // Add all of the arguments in their promoted form to the arg list.
4583 for (unsigned i = FT->getNumParams(); i != NumActualArgs; ++i, ++AI) {
Chris Lattner229907c2011-07-18 04:54:35 +00004584 Type *PTy = getPromotedType((*AI)->getType());
Reid Klecknerc3fae792017-04-13 18:11:03 +00004585 Value *NewArg = *AI;
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004586 if (PTy != (*AI)->getType()) {
4587 // Must promote to pass through va_arg area!
4588 Instruction::CastOps opcode =
4589 CastInst::getCastOpcode(*AI, false, PTy, false);
Craig Topperbb4069e2017-07-07 23:16:26 +00004590 NewArg = Builder.CreateCast(opcode, *AI, PTy);
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004591 }
Reid Klecknerc3fae792017-04-13 18:11:03 +00004592 Args.push_back(NewArg);
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004593
4594 // Add any parameter attributes.
Reid Klecknerf021fab2017-04-13 23:12:13 +00004595 ArgAttrs.push_back(CallerPAL.getParamAttributes(i));
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004596 }
4597 }
4598 }
4599
Reid Klecknerc2cb5602017-04-12 00:38:00 +00004600 AttributeSet FnAttrs = CallerPAL.getFnAttributes();
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004601
4602 if (NewRetTy->isVoidTy())
4603 Caller->setName(""); // Void type should not have a name.
4604
Reid Klecknerc3fae792017-04-13 18:11:03 +00004605 assert((ArgAttrs.size() == FT->getNumParams() || FT->isVarArg()) &&
4606 "missing argument attributes");
Reid Klecknerc3fae792017-04-13 18:11:03 +00004607 AttributeList NewCallerPAL = AttributeList::get(
4608 Ctx, FnAttrs, AttributeSet::get(Ctx, RAttrs), ArgAttrs);
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004609
Sanjoy Das76293462015-11-25 00:42:19 +00004610 SmallVector<OperandBundleDef, 1> OpBundles;
Craig Topperc1892ec2019-01-31 17:23:29 +00004611 Call.getOperandBundlesAsDefs(OpBundles);
Sanjoy Das76293462015-11-25 00:42:19 +00004612
Craig Topperc1892ec2019-01-31 17:23:29 +00004613 CallBase *NewCall;
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004614 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Craig Topperc1892ec2019-01-31 17:23:29 +00004615 NewCall = Builder.CreateInvoke(Callee, II->getNormalDest(),
4616 II->getUnwindDest(), Args, OpBundles);
Craig Topper784929d2019-02-08 20:48:56 +00004617 } else if (CallBrInst *CBI = dyn_cast<CallBrInst>(Caller)) {
4618 NewCall = Builder.CreateCallBr(Callee, CBI->getDefaultDest(),
4619 CBI->getIndirectDests(), Args, OpBundles);
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004620 } else {
Craig Topperc1892ec2019-01-31 17:23:29 +00004621 NewCall = Builder.CreateCall(Callee, Args, OpBundles);
4622 cast<CallInst>(NewCall)->setTailCallKind(
4623 cast<CallInst>(Caller)->getTailCallKind());
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004624 }
Craig Topperc1892ec2019-01-31 17:23:29 +00004625 NewCall->takeName(Caller);
4626 NewCall->setCallingConv(Call.getCallingConv());
4627 NewCall->setAttributes(NewCallerPAL);
Reid Kleckner257cb4e2017-04-13 20:26:38 +00004628
4629 // Preserve the weight metadata for the new call instruction. The metadata
4630 // is used by SamplePGO to check callsite's hotness.
4631 uint64_t W;
4632 if (Caller->extractProfTotalWeight(W))
Craig Topperc1892ec2019-01-31 17:23:29 +00004633 NewCall->setProfWeight(W);
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004634
4635 // Insert a cast of the return type as necessary.
Craig Topperc1892ec2019-01-31 17:23:29 +00004636 Instruction *NC = NewCall;
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004637 Value *NV = NC;
4638 if (OldRetTy != NV->getType() && !Caller->use_empty()) {
4639 if (!NV->getType()->isVoidTy()) {
David Majnemer9b6b8222015-01-06 08:41:31 +00004640 NV = NC = CastInst::CreateBitOrPointerCast(NC, OldRetTy);
Eli Friedman35211c62011-05-27 00:19:40 +00004641 NC->setDebugLoc(Caller->getDebugLoc());
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004642
Craig Topper784929d2019-02-08 20:48:56 +00004643 // If this is an invoke/callbr instruction, we should insert it after the
4644 // first non-phi instruction in the normal successor block.
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004645 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Bill Wendling07efd6f2011-08-25 01:08:34 +00004646 BasicBlock::iterator I = II->getNormalDest()->getFirstInsertionPt();
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004647 InsertNewInstBefore(NC, *I);
Craig Topper784929d2019-02-08 20:48:56 +00004648 } else if (CallBrInst *CBI = dyn_cast<CallBrInst>(Caller)) {
4649 BasicBlock::iterator I = CBI->getDefaultDest()->getFirstInsertionPt();
4650 InsertNewInstBefore(NC, *I);
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004651 } else {
Chris Lattner73989652010-12-20 08:25:06 +00004652 // Otherwise, it's a call, just insert cast right after the call.
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004653 InsertNewInstBefore(NC, *Caller);
4654 }
4655 Worklist.AddUsersToWorkList(*Caller);
4656 } else {
4657 NV = UndefValue::get(Caller->getType());
4658 }
4659 }
4660
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004661 if (!Caller->use_empty())
Sanjay Patel4b198802016-02-01 22:23:39 +00004662 replaceInstUsesWith(*Caller, NV);
Frederic Rissc1892e22014-10-23 04:08:42 +00004663 else if (Caller->hasValueHandle()) {
4664 if (OldRetTy == NV->getType())
4665 ValueHandleBase::ValueIsRAUWd(Caller, NV);
4666 else
4667 // We cannot call ValueIsRAUWd with a different type, and the
4668 // actual tracked value will disappear.
4669 ValueHandleBase::ValueIsDeleted(Caller);
4670 }
Eli Friedmanb9ed18f2011-05-18 00:32:01 +00004671
Sanjay Patel4b198802016-02-01 22:23:39 +00004672 eraseInstFromFunction(*Caller);
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004673 return true;
4674}
4675
Sanjay Patelcd4377c2016-01-20 22:24:38 +00004676/// Turn a call to a function created by init_trampoline / adjust_trampoline
4677/// intrinsic pair into a direct call to the underlying function.
Duncan Sandsa0984362011-09-06 13:37:06 +00004678Instruction *
Craig Topperc1892ec2019-01-31 17:23:29 +00004679InstCombiner::transformCallThroughTrampoline(CallBase &Call,
4680 IntrinsicInst &Tramp) {
4681 Value *Callee = Call.getCalledValue();
James Y Knight291f7912019-02-01 20:44:54 +00004682 Type *CalleeTy = Callee->getType();
4683 FunctionType *FTy = Call.getFunctionType();
Craig Topperc1892ec2019-01-31 17:23:29 +00004684 AttributeList Attrs = Call.getAttributes();
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004685
4686 // If the call already has the 'nest' attribute somewhere then give up -
4687 // otherwise 'nest' would occur twice after splicing in the chain.
Bill Wendling6e95ae82012-12-31 00:49:59 +00004688 if (Attrs.hasAttrSomewhere(Attribute::Nest))
Craig Topperf40110f2014-04-25 05:29:35 +00004689 return nullptr;
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004690
Craig Topperc1892ec2019-01-31 17:23:29 +00004691 Function *NestF = cast<Function>(Tramp.getArgOperand(1)->stripPointerCasts());
James Y Knight291f7912019-02-01 20:44:54 +00004692 FunctionType *NestFTy = NestF->getFunctionType();
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004693
Reid Klecknereb9dd5b2017-04-10 23:31:05 +00004694 AttributeList NestAttrs = NestF->getAttributes();
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004695 if (!NestAttrs.isEmpty()) {
Reid Klecknerf021fab2017-04-13 23:12:13 +00004696 unsigned NestArgNo = 0;
Craig Topperf40110f2014-04-25 05:29:35 +00004697 Type *NestTy = nullptr;
Reid Klecknerc2cb5602017-04-12 00:38:00 +00004698 AttributeSet NestAttr;
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004699
4700 // Look for a parameter marked with the 'nest' attribute.
4701 for (FunctionType::param_iterator I = NestFTy->param_begin(),
Reid Klecknerf021fab2017-04-13 23:12:13 +00004702 E = NestFTy->param_end();
4703 I != E; ++NestArgNo, ++I) {
4704 AttributeSet AS = NestAttrs.getParamAttributes(NestArgNo);
4705 if (AS.hasAttribute(Attribute::Nest)) {
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004706 // Record the parameter type and any other attributes.
4707 NestTy = *I;
Reid Klecknerf021fab2017-04-13 23:12:13 +00004708 NestAttr = AS;
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004709 break;
4710 }
Reid Klecknerf021fab2017-04-13 23:12:13 +00004711 }
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004712
4713 if (NestTy) {
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004714 std::vector<Value*> NewArgs;
Reid Kleckner7f720332017-04-13 00:58:09 +00004715 std::vector<AttributeSet> NewArgAttrs;
Craig Topperc1892ec2019-01-31 17:23:29 +00004716 NewArgs.reserve(Call.arg_size() + 1);
4717 NewArgAttrs.reserve(Call.arg_size());
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004718
4719 // Insert the nest argument into the call argument list, which may
4720 // mean appending it. Likewise for attributes.
4721
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004722 {
Reid Klecknerf021fab2017-04-13 23:12:13 +00004723 unsigned ArgNo = 0;
Craig Topperc1892ec2019-01-31 17:23:29 +00004724 auto I = Call.arg_begin(), E = Call.arg_end();
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004725 do {
Reid Klecknerf021fab2017-04-13 23:12:13 +00004726 if (ArgNo == NestArgNo) {
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004727 // Add the chain argument and attributes.
Craig Topperc1892ec2019-01-31 17:23:29 +00004728 Value *NestVal = Tramp.getArgOperand(2);
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004729 if (NestVal->getType() != NestTy)
Craig Topperbb4069e2017-07-07 23:16:26 +00004730 NestVal = Builder.CreateBitCast(NestVal, NestTy, "nest");
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004731 NewArgs.push_back(NestVal);
Reid Kleckner7f720332017-04-13 00:58:09 +00004732 NewArgAttrs.push_back(NestAttr);
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004733 }
4734
4735 if (I == E)
4736 break;
4737
4738 // Add the original argument and attributes.
4739 NewArgs.push_back(*I);
Reid Klecknerf021fab2017-04-13 23:12:13 +00004740 NewArgAttrs.push_back(Attrs.getParamAttributes(ArgNo));
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004741
Reid Klecknerf021fab2017-04-13 23:12:13 +00004742 ++ArgNo;
Richard Trieu7a083812016-02-18 22:09:30 +00004743 ++I;
Eugene Zelenkocdc71612016-08-11 17:20:18 +00004744 } while (true);
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004745 }
4746
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004747 // The trampoline may have been bitcast to a bogus type (FTy).
4748 // Handle this by synthesizing a new function type, equal to FTy
4749 // with the chain parameter inserted.
4750
Jay Foadb804a2b2011-07-12 14:06:48 +00004751 std::vector<Type*> NewTypes;
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004752 NewTypes.reserve(FTy->getNumParams()+1);
4753
4754 // Insert the chain's type into the list of parameter types, which may
4755 // mean appending it.
4756 {
Reid Klecknerf021fab2017-04-13 23:12:13 +00004757 unsigned ArgNo = 0;
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004758 FunctionType::param_iterator I = FTy->param_begin(),
4759 E = FTy->param_end();
4760
4761 do {
Reid Klecknerf021fab2017-04-13 23:12:13 +00004762 if (ArgNo == NestArgNo)
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004763 // Add the chain's type.
4764 NewTypes.push_back(NestTy);
4765
4766 if (I == E)
4767 break;
4768
4769 // Add the original type.
4770 NewTypes.push_back(*I);
4771
Reid Klecknerf021fab2017-04-13 23:12:13 +00004772 ++ArgNo;
Richard Trieu7a083812016-02-18 22:09:30 +00004773 ++I;
Eugene Zelenkocdc71612016-08-11 17:20:18 +00004774 } while (true);
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004775 }
4776
4777 // Replace the trampoline call with a direct call. Let the generic
4778 // code sort out any function type mismatches.
Jim Grosbach7815f562012-02-03 00:07:04 +00004779 FunctionType *NewFTy = FunctionType::get(FTy->getReturnType(), NewTypes,
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004780 FTy->isVarArg());
4781 Constant *NewCallee =
4782 NestF->getType() == PointerType::getUnqual(NewFTy) ?
Jim Grosbach7815f562012-02-03 00:07:04 +00004783 NestF : ConstantExpr::getBitCast(NestF,
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004784 PointerType::getUnqual(NewFTy));
Reid Kleckner7f720332017-04-13 00:58:09 +00004785 AttributeList NewPAL =
4786 AttributeList::get(FTy->getContext(), Attrs.getFnAttributes(),
4787 Attrs.getRetAttributes(), NewArgAttrs);
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004788
David Majnemer231a68c2016-04-29 08:07:20 +00004789 SmallVector<OperandBundleDef, 1> OpBundles;
Craig Topperc1892ec2019-01-31 17:23:29 +00004790 Call.getOperandBundlesAsDefs(OpBundles);
David Majnemer231a68c2016-04-29 08:07:20 +00004791
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004792 Instruction *NewCaller;
Craig Topperc1892ec2019-01-31 17:23:29 +00004793 if (InvokeInst *II = dyn_cast<InvokeInst>(&Call)) {
James Y Knight7976eb52019-02-01 20:43:25 +00004794 NewCaller = InvokeInst::Create(NewFTy, NewCallee,
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004795 II->getNormalDest(), II->getUnwindDest(),
David Majnemer231a68c2016-04-29 08:07:20 +00004796 NewArgs, OpBundles);
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004797 cast<InvokeInst>(NewCaller)->setCallingConv(II->getCallingConv());
4798 cast<InvokeInst>(NewCaller)->setAttributes(NewPAL);
Craig Topper784929d2019-02-08 20:48:56 +00004799 } else if (CallBrInst *CBI = dyn_cast<CallBrInst>(&Call)) {
4800 NewCaller =
4801 CallBrInst::Create(NewFTy, NewCallee, CBI->getDefaultDest(),
4802 CBI->getIndirectDests(), NewArgs, OpBundles);
4803 cast<CallBrInst>(NewCaller)->setCallingConv(CBI->getCallingConv());
4804 cast<CallBrInst>(NewCaller)->setAttributes(NewPAL);
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004805 } else {
James Y Knight7976eb52019-02-01 20:43:25 +00004806 NewCaller = CallInst::Create(NewFTy, NewCallee, NewArgs, OpBundles);
David Majnemerd5648c72016-11-25 22:35:09 +00004807 cast<CallInst>(NewCaller)->setTailCallKind(
Craig Topperc1892ec2019-01-31 17:23:29 +00004808 cast<CallInst>(Call).getTailCallKind());
David Majnemerd5648c72016-11-25 22:35:09 +00004809 cast<CallInst>(NewCaller)->setCallingConv(
Craig Topperc1892ec2019-01-31 17:23:29 +00004810 cast<CallInst>(Call).getCallingConv());
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004811 cast<CallInst>(NewCaller)->setAttributes(NewPAL);
4812 }
Craig Topperc1892ec2019-01-31 17:23:29 +00004813 NewCaller->setDebugLoc(Call.getDebugLoc());
Eli Friedman49346012011-05-18 19:57:14 +00004814
4815 return NewCaller;
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004816 }
4817 }
4818
4819 // Replace the trampoline call with a direct call. Since there is no 'nest'
4820 // parameter, there is no need to adjust the argument list. Let the generic
4821 // code sort out any function type mismatches.
James Y Knight291f7912019-02-01 20:44:54 +00004822 Constant *NewCallee = ConstantExpr::getBitCast(NestF, CalleeTy);
4823 Call.setCalledFunction(FTy, NewCallee);
Craig Topperc1892ec2019-01-31 17:23:29 +00004824 return &Call;
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004825}