blob: df8022181ead8b30e6a341429eec1c3131c1b837 [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"
16#include "llvm/ADT/ArrayRef.h"
17#include "llvm/ADT/None.h"
Eugene Zelenko7f0f9bc2017-10-24 21:24:53 +000018#include "llvm/ADT/Optional.h"
Eugene Zelenkocdc71612016-08-11 17:20:18 +000019#include "llvm/ADT/STLExtras.h"
20#include "llvm/ADT/SmallVector.h"
Chandler Carruth6bda14b2017-06-06 11:49:48 +000021#include "llvm/ADT/Statistic.h"
Eugene Zelenkocdc71612016-08-11 17:20:18 +000022#include "llvm/ADT/Twine.h"
Eugene Zelenko7f0f9bc2017-10-24 21:24:53 +000023#include "llvm/Analysis/AssumptionCache.h"
David Majnemer15032582015-05-22 03:56:46 +000024#include "llvm/Analysis/InstructionSimplify.h"
Chris Lattner7a9e47a2010-01-05 07:32:13 +000025#include "llvm/Analysis/MemoryBuiltins.h"
David Blaikie31b98d22018-06-04 21:23:21 +000026#include "llvm/Transforms/Utils/Local.h"
Eugene Zelenkocdc71612016-08-11 17:20:18 +000027#include "llvm/Analysis/ValueTracking.h"
Eugene Zelenko7f0f9bc2017-10-24 21:24:53 +000028#include "llvm/IR/Attributes.h"
Eugene Zelenkocdc71612016-08-11 17:20:18 +000029#include "llvm/IR/BasicBlock.h"
Eugene Zelenkocdc71612016-08-11 17:20:18 +000030#include "llvm/IR/Constant.h"
Eugene Zelenko7f0f9bc2017-10-24 21:24:53 +000031#include "llvm/IR/Constants.h"
Eugene Zelenkocdc71612016-08-11 17:20:18 +000032#include "llvm/IR/DataLayout.h"
33#include "llvm/IR/DerivedTypes.h"
34#include "llvm/IR/Function.h"
35#include "llvm/IR/GlobalVariable.h"
36#include "llvm/IR/InstrTypes.h"
37#include "llvm/IR/Instruction.h"
38#include "llvm/IR/Instructions.h"
39#include "llvm/IR/IntrinsicInst.h"
40#include "llvm/IR/Intrinsics.h"
41#include "llvm/IR/LLVMContext.h"
42#include "llvm/IR/Metadata.h"
Chandler Carruth820a9082014-03-04 11:08:18 +000043#include "llvm/IR/PatternMatch.h"
Philip Reames1a1bdb22014-12-02 18:50:36 +000044#include "llvm/IR/Statepoint.h"
Eugene Zelenkocdc71612016-08-11 17:20:18 +000045#include "llvm/IR/Type.h"
Eugene Zelenko7f0f9bc2017-10-24 21:24:53 +000046#include "llvm/IR/User.h"
Eugene Zelenkocdc71612016-08-11 17:20:18 +000047#include "llvm/IR/Value.h"
48#include "llvm/IR/ValueHandle.h"
Eugene Zelenko7f0f9bc2017-10-24 21:24:53 +000049#include "llvm/Support/AtomicOrdering.h"
Eugene Zelenkocdc71612016-08-11 17:20:18 +000050#include "llvm/Support/Casting.h"
Eugene Zelenko7f0f9bc2017-10-24 21:24:53 +000051#include "llvm/Support/CommandLine.h"
52#include "llvm/Support/Compiler.h"
Eugene Zelenkocdc71612016-08-11 17:20:18 +000053#include "llvm/Support/Debug.h"
Eugene Zelenko7f0f9bc2017-10-24 21:24:53 +000054#include "llvm/Support/ErrorHandling.h"
Craig Topperb45eabc2017-04-26 16:39:58 +000055#include "llvm/Support/KnownBits.h"
Eugene Zelenkocdc71612016-08-11 17:20:18 +000056#include "llvm/Support/MathExtras.h"
Eugene Zelenko7f0f9bc2017-10-24 21:24:53 +000057#include "llvm/Support/raw_ostream.h"
58#include "llvm/Transforms/InstCombine/InstCombineWorklist.h"
Chandler Carruthba4c5172015-01-21 11:23:40 +000059#include "llvm/Transforms/Utils/SimplifyLibCalls.h"
Eugene Zelenkocdc71612016-08-11 17:20:18 +000060#include <algorithm>
61#include <cassert>
62#include <cstdint>
63#include <cstring>
Eugene Zelenko7f0f9bc2017-10-24 21:24:53 +000064#include <utility>
Eugene Zelenkocdc71612016-08-11 17:20:18 +000065#include <vector>
66
Chris Lattner7a9e47a2010-01-05 07:32:13 +000067using namespace llvm;
Michael Ilseman536cc322012-12-13 03:13:36 +000068using namespace PatternMatch;
Chris Lattner7a9e47a2010-01-05 07:32:13 +000069
Chandler Carruth964daaa2014-04-22 02:55:47 +000070#define DEBUG_TYPE "instcombine"
71
Meador Ingee3f2b262012-11-30 04:05:06 +000072STATISTIC(NumSimplified, "Number of library calls simplified");
73
Philip Reames79e917d2018-05-09 22:56:32 +000074static cl::opt<unsigned> GuardWideningWindow(
75 "instcombine-guard-widening-window",
76 cl::init(3),
77 cl::desc("How wide an instruction window to bypass looking for "
78 "another guard"));
79
Sanjay Patelcd4377c2016-01-20 22:24:38 +000080/// Return the specified type promoted as it would be to pass though a va_arg
81/// area.
Chris Lattner229907c2011-07-18 04:54:35 +000082static Type *getPromotedType(Type *Ty) {
83 if (IntegerType* ITy = dyn_cast<IntegerType>(Ty)) {
Chris Lattner7a9e47a2010-01-05 07:32:13 +000084 if (ITy->getBitWidth() < 32)
85 return Type::getInt32Ty(Ty->getContext());
86 }
87 return Ty;
88}
89
Sanjay Patel368ac5d2016-02-21 17:29:33 +000090/// Return a constant boolean vector that has true elements in all positions
Sanjay Patel24401302016-02-21 17:33:31 +000091/// where the input constant data vector has an element with the sign bit set.
Sanjay Patel368ac5d2016-02-21 17:29:33 +000092static Constant *getNegativeIsTrueBoolVec(ConstantDataVector *V) {
93 SmallVector<Constant *, 32> BoolVec;
94 IntegerType *BoolTy = Type::getInt1Ty(V->getContext());
95 for (unsigned I = 0, E = V->getNumElements(); I != E; ++I) {
96 Constant *Elt = V->getElementAsConstant(I);
97 assert((isa<ConstantInt>(Elt) || isa<ConstantFP>(Elt)) &&
98 "Unexpected constant data vector element type");
99 bool Sign = V->getElementType()->isIntegerTy()
100 ? cast<ConstantInt>(Elt)->isNegative()
101 : cast<ConstantFP>(Elt)->isNegative();
102 BoolVec.push_back(ConstantInt::get(BoolTy, Sign));
103 }
104 return ConstantVector::get(BoolVec);
105}
106
Daniel Neilson8f30ec62018-05-11 14:30:02 +0000107Instruction *InstCombiner::SimplifyAnyMemTransfer(AnyMemTransferInst *MI) {
Daniel Neilson2363da92018-02-12 23:06:55 +0000108 unsigned DstAlign = getKnownAlignment(MI->getRawDest(), DL, MI, &AC, &DT);
109 unsigned CopyDstAlign = MI->getDestAlignment();
110 if (CopyDstAlign < DstAlign){
111 MI->setDestAlignment(DstAlign);
112 return MI;
113 }
Chris Lattner7a9e47a2010-01-05 07:32:13 +0000114
Daniel Neilson8f30ec62018-05-11 14:30:02 +0000115 unsigned SrcAlign = getKnownAlignment(MI->getRawSource(), DL, MI, &AC, &DT);
116 unsigned CopySrcAlign = MI->getSourceAlignment();
Daniel Neilson2363da92018-02-12 23:06:55 +0000117 if (CopySrcAlign < SrcAlign) {
Daniel Neilson8f30ec62018-05-11 14:30:02 +0000118 MI->setSourceAlignment(SrcAlign);
Chris Lattner7a9e47a2010-01-05 07:32:13 +0000119 return MI;
120 }
Jim Grosbach7815f562012-02-03 00:07:04 +0000121
Chris Lattner7a9e47a2010-01-05 07:32:13 +0000122 // If MemCpyInst length is 1/2/4/8 bytes then replace memcpy with
123 // load/store.
Daniel Neilson8f30ec62018-05-11 14:30:02 +0000124 ConstantInt *MemOpLength = dyn_cast<ConstantInt>(MI->getLength());
Craig Topperf40110f2014-04-25 05:29:35 +0000125 if (!MemOpLength) return nullptr;
Jim Grosbach7815f562012-02-03 00:07:04 +0000126
Chris Lattner7a9e47a2010-01-05 07:32:13 +0000127 // Source and destination pointer types are always "i8*" for intrinsic. See
128 // if the size is something we can handle with a single primitive load/store.
129 // A single load+store correctly handles overlapping memory in the memmove
130 // case.
Michael Liao69e172a2012-08-15 03:49:59 +0000131 uint64_t Size = MemOpLength->getLimitedValue();
Alp Tokercb402912014-01-24 17:20:08 +0000132 assert(Size && "0-sized memory transferring should be removed already.");
Jim Grosbach7815f562012-02-03 00:07:04 +0000133
Chris Lattner7a9e47a2010-01-05 07:32:13 +0000134 if (Size > 8 || (Size&(Size-1)))
Craig Topperf40110f2014-04-25 05:29:35 +0000135 return nullptr; // If not 1/2/4/8 bytes, exit.
Jim Grosbach7815f562012-02-03 00:07:04 +0000136
Serguei Katkova5b0e552019-01-16 04:36:26 +0000137 // If it is an atomic and alignment is less than the size then we will
138 // introduce the unaligned memory access which will be later transformed
139 // into libcall in CodeGen. This is not evident performance gain so disable
140 // it now.
141 if (isa<AtomicMemTransferInst>(MI))
142 if (CopyDstAlign < Size || CopySrcAlign < Size)
143 return nullptr;
144
Chris Lattner7a9e47a2010-01-05 07:32:13 +0000145 // Use an integer load+store unless we can find something better.
Mon P Wangc576ee92010-04-04 03:10:48 +0000146 unsigned SrcAddrSp =
Gabor Greif0a136c92010-06-24 13:54:33 +0000147 cast<PointerType>(MI->getArgOperand(1)->getType())->getAddressSpace();
Gabor Greiff3755202010-04-16 15:33:14 +0000148 unsigned DstAddrSp =
Gabor Greif0a136c92010-06-24 13:54:33 +0000149 cast<PointerType>(MI->getArgOperand(0)->getType())->getAddressSpace();
Mon P Wangc576ee92010-04-04 03:10:48 +0000150
Chris Lattner229907c2011-07-18 04:54:35 +0000151 IntegerType* IntType = IntegerType::get(MI->getContext(), Size<<3);
Mon P Wangc576ee92010-04-04 03:10:48 +0000152 Type *NewSrcPtrTy = PointerType::get(IntType, SrcAddrSp);
153 Type *NewDstPtrTy = PointerType::get(IntType, DstAddrSp);
Jim Grosbach7815f562012-02-03 00:07:04 +0000154
Mikael Holmen760dc9a2017-03-01 06:45:20 +0000155 // If the memcpy has metadata describing the members, see if we can get the
156 // TBAA tag describing our copy.
Craig Topperf40110f2014-04-25 05:29:35 +0000157 MDNode *CopyMD = nullptr;
Ivan A. Kosarevf03f5792018-02-19 12:10:20 +0000158 if (MDNode *M = MI->getMetadata(LLVMContext::MD_tbaa)) {
159 CopyMD = M;
160 } else if (MDNode *M = MI->getMetadata(LLVMContext::MD_tbaa_struct)) {
Mikael Holmen760dc9a2017-03-01 06:45:20 +0000161 if (M->getNumOperands() == 3 && M->getOperand(0) &&
162 mdconst::hasa<ConstantInt>(M->getOperand(0)) &&
Craig Topper79ab6432017-07-06 18:39:47 +0000163 mdconst::extract<ConstantInt>(M->getOperand(0))->isZero() &&
Mikael Holmen760dc9a2017-03-01 06:45:20 +0000164 M->getOperand(1) &&
165 mdconst::hasa<ConstantInt>(M->getOperand(1)) &&
166 mdconst::extract<ConstantInt>(M->getOperand(1))->getValue() ==
167 Size &&
168 M->getOperand(2) && isa<MDNode>(M->getOperand(2)))
169 CopyMD = cast<MDNode>(M->getOperand(2));
Chris Lattner7a9e47a2010-01-05 07:32:13 +0000170 }
Jim Grosbach7815f562012-02-03 00:07:04 +0000171
Craig Topperbb4069e2017-07-07 23:16:26 +0000172 Value *Src = Builder.CreateBitCast(MI->getArgOperand(1), NewSrcPtrTy);
173 Value *Dest = Builder.CreateBitCast(MI->getArgOperand(0), NewDstPtrTy);
James Y Knight14359ef2019-02-01 20:44:24 +0000174 LoadInst *L = Builder.CreateLoad(IntType, Src);
Daniel Neilson2363da92018-02-12 23:06:55 +0000175 // Alignment from the mem intrinsic will be better, so use it.
176 L->setAlignment(CopySrcAlign);
Dan Gohman3f553c22012-09-13 21:51:01 +0000177 if (CopyMD)
178 L->setMetadata(LLVMContext::MD_tbaa, CopyMD);
Dorit Nuzmanabd15f62016-09-04 07:49:39 +0000179 MDNode *LoopMemParallelMD =
180 MI->getMetadata(LLVMContext::MD_mem_parallel_loop_access);
181 if (LoopMemParallelMD)
182 L->setMetadata(LLVMContext::MD_mem_parallel_loop_access, LoopMemParallelMD);
Michael Kruse978ba612018-12-20 04:58:07 +0000183 MDNode *AccessGroupMD = MI->getMetadata(LLVMContext::MD_access_group);
184 if (AccessGroupMD)
185 L->setMetadata(LLVMContext::MD_access_group, AccessGroupMD);
Dorit Nuzman7673ba72016-09-04 07:06:00 +0000186
Daniel Neilson8f30ec62018-05-11 14:30:02 +0000187 StoreInst *S = Builder.CreateStore(L, Dest);
Daniel Neilson2363da92018-02-12 23:06:55 +0000188 // Alignment from the mem intrinsic will be better, so use it.
189 S->setAlignment(CopyDstAlign);
Dan Gohman3f553c22012-09-13 21:51:01 +0000190 if (CopyMD)
191 S->setMetadata(LLVMContext::MD_tbaa, CopyMD);
Dorit Nuzmanabd15f62016-09-04 07:49:39 +0000192 if (LoopMemParallelMD)
193 S->setMetadata(LLVMContext::MD_mem_parallel_loop_access, LoopMemParallelMD);
Michael Kruse978ba612018-12-20 04:58:07 +0000194 if (AccessGroupMD)
195 S->setMetadata(LLVMContext::MD_access_group, AccessGroupMD);
Chris Lattner7a9e47a2010-01-05 07:32:13 +0000196
Daniel Neilson8f30ec62018-05-11 14:30:02 +0000197 if (auto *MT = dyn_cast<MemTransferInst>(MI)) {
198 // non-atomics can be volatile
199 L->setVolatile(MT->isVolatile());
200 S->setVolatile(MT->isVolatile());
201 }
202 if (isa<AtomicMemTransferInst>(MI)) {
203 // atomics have to be unordered
204 L->setOrdering(AtomicOrdering::Unordered);
205 S->setOrdering(AtomicOrdering::Unordered);
206 }
207
Chris Lattner7a9e47a2010-01-05 07:32:13 +0000208 // Set the size of the copy to 0, it will be deleted on the next iteration.
Daniel Neilson8f30ec62018-05-11 14:30:02 +0000209 MI->setLength(Constant::getNullValue(MemOpLength->getType()));
Chris Lattner7a9e47a2010-01-05 07:32:13 +0000210 return MI;
211}
212
Daniel Neilsonf6651d42018-05-11 20:04:50 +0000213Instruction *InstCombiner::SimplifyAnyMemSet(AnyMemSetInst *MI) {
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000214 unsigned Alignment = getKnownAlignment(MI->getDest(), DL, MI, &AC, &DT);
Daniel Neilson38af2ee2018-02-02 22:03:03 +0000215 if (MI->getDestAlignment() < Alignment) {
216 MI->setDestAlignment(Alignment);
Chris Lattner7a9e47a2010-01-05 07:32:13 +0000217 return MI;
218 }
Jim Grosbach7815f562012-02-03 00:07:04 +0000219
Chris Lattner7a9e47a2010-01-05 07:32:13 +0000220 // Extract the length and alignment and fill if they are constant.
221 ConstantInt *LenC = dyn_cast<ConstantInt>(MI->getLength());
222 ConstantInt *FillC = dyn_cast<ConstantInt>(MI->getValue());
Duncan Sands9dff9be2010-02-15 16:12:20 +0000223 if (!LenC || !FillC || !FillC->getType()->isIntegerTy(8))
Craig Topperf40110f2014-04-25 05:29:35 +0000224 return nullptr;
Michael Liao69e172a2012-08-15 03:49:59 +0000225 uint64_t Len = LenC->getLimitedValue();
Daniel Neilson710d7b92018-03-22 18:36:15 +0000226 Alignment = MI->getDestAlignment();
Michael Liao69e172a2012-08-15 03:49:59 +0000227 assert(Len && "0-sized memory setting should be removed already.");
Jim Grosbach7815f562012-02-03 00:07:04 +0000228
Serguei Katkova5b0e552019-01-16 04:36:26 +0000229 // Alignment 0 is identity for alignment 1 for memset, but not store.
230 if (Alignment == 0)
231 Alignment = 1;
232
233 // If it is an atomic and alignment is less than the size then we will
234 // introduce the unaligned memory access which will be later transformed
235 // into libcall in CodeGen. This is not evident performance gain so disable
236 // it now.
237 if (isa<AtomicMemSetInst>(MI))
238 if (Alignment < Len)
239 return nullptr;
240
Chris Lattner7a9e47a2010-01-05 07:32:13 +0000241 // memset(s,c,n) -> store s, c (for n=1,2,4,8)
242 if (Len <= 8 && isPowerOf2_32((uint32_t)Len)) {
Chris Lattner229907c2011-07-18 04:54:35 +0000243 Type *ITy = IntegerType::get(MI->getContext(), Len*8); // n=1 -> i8.
Jim Grosbach7815f562012-02-03 00:07:04 +0000244
Chris Lattner7a9e47a2010-01-05 07:32:13 +0000245 Value *Dest = MI->getDest();
Mon P Wang1991c472010-12-20 01:05:30 +0000246 unsigned DstAddrSp = cast<PointerType>(Dest->getType())->getAddressSpace();
247 Type *NewDstPtrTy = PointerType::get(ITy, DstAddrSp);
Craig Topperbb4069e2017-07-07 23:16:26 +0000248 Dest = Builder.CreateBitCast(Dest, NewDstPtrTy);
Chris Lattner7a9e47a2010-01-05 07:32:13 +0000249
Chris Lattner7a9e47a2010-01-05 07:32:13 +0000250 // Extract the fill value and store.
251 uint64_t Fill = FillC->getZExtValue()*0x0101010101010101ULL;
Craig Topperbb4069e2017-07-07 23:16:26 +0000252 StoreInst *S = Builder.CreateStore(ConstantInt::get(ITy, Fill), Dest,
253 MI->isVolatile());
Eli Friedman49346012011-05-18 19:57:14 +0000254 S->setAlignment(Alignment);
Daniel Neilsonf6651d42018-05-11 20:04:50 +0000255 if (isa<AtomicMemSetInst>(MI))
256 S->setOrdering(AtomicOrdering::Unordered);
Jim Grosbach7815f562012-02-03 00:07:04 +0000257
Chris Lattner7a9e47a2010-01-05 07:32:13 +0000258 // Set the size of the copy to 0, it will be deleted on the next iteration.
259 MI->setLength(Constant::getNullValue(LenC->getType()));
260 return MI;
261 }
262
Simon Pilgrim18617d12015-08-05 08:18:00 +0000263 return nullptr;
264}
265
Sanjay Patel6038d3e2016-01-29 23:27:03 +0000266static Value *simplifyX86immShift(const IntrinsicInst &II,
Simon Pilgrimbecd5e82015-08-13 07:39:03 +0000267 InstCombiner::BuilderTy &Builder) {
268 bool LogicalShift = false;
269 bool ShiftLeft = false;
270
271 switch (II.getIntrinsicID()) {
Craig Topperb4173a52016-11-13 07:26:19 +0000272 default: llvm_unreachable("Unexpected intrinsic!");
Simon Pilgrimbecd5e82015-08-13 07:39:03 +0000273 case Intrinsic::x86_sse2_psra_d:
274 case Intrinsic::x86_sse2_psra_w:
275 case Intrinsic::x86_sse2_psrai_d:
276 case Intrinsic::x86_sse2_psrai_w:
277 case Intrinsic::x86_avx2_psra_d:
278 case Intrinsic::x86_avx2_psra_w:
279 case Intrinsic::x86_avx2_psrai_d:
280 case Intrinsic::x86_avx2_psrai_w:
Craig Topper8b831cb2016-11-13 01:51:55 +0000281 case Intrinsic::x86_avx512_psra_q_128:
282 case Intrinsic::x86_avx512_psrai_q_128:
283 case Intrinsic::x86_avx512_psra_q_256:
284 case Intrinsic::x86_avx512_psrai_q_256:
285 case Intrinsic::x86_avx512_psra_d_512:
286 case Intrinsic::x86_avx512_psra_q_512:
287 case Intrinsic::x86_avx512_psra_w_512:
288 case Intrinsic::x86_avx512_psrai_d_512:
289 case Intrinsic::x86_avx512_psrai_q_512:
290 case Intrinsic::x86_avx512_psrai_w_512:
Simon Pilgrimbecd5e82015-08-13 07:39:03 +0000291 LogicalShift = false; ShiftLeft = false;
292 break;
293 case Intrinsic::x86_sse2_psrl_d:
294 case Intrinsic::x86_sse2_psrl_q:
295 case Intrinsic::x86_sse2_psrl_w:
296 case Intrinsic::x86_sse2_psrli_d:
297 case Intrinsic::x86_sse2_psrli_q:
298 case Intrinsic::x86_sse2_psrli_w:
299 case Intrinsic::x86_avx2_psrl_d:
300 case Intrinsic::x86_avx2_psrl_q:
301 case Intrinsic::x86_avx2_psrl_w:
302 case Intrinsic::x86_avx2_psrli_d:
303 case Intrinsic::x86_avx2_psrli_q:
304 case Intrinsic::x86_avx2_psrli_w:
Craig Topper8b831cb2016-11-13 01:51:55 +0000305 case Intrinsic::x86_avx512_psrl_d_512:
306 case Intrinsic::x86_avx512_psrl_q_512:
307 case Intrinsic::x86_avx512_psrl_w_512:
308 case Intrinsic::x86_avx512_psrli_d_512:
309 case Intrinsic::x86_avx512_psrli_q_512:
310 case Intrinsic::x86_avx512_psrli_w_512:
Simon Pilgrimbecd5e82015-08-13 07:39:03 +0000311 LogicalShift = true; ShiftLeft = false;
312 break;
313 case Intrinsic::x86_sse2_psll_d:
314 case Intrinsic::x86_sse2_psll_q:
315 case Intrinsic::x86_sse2_psll_w:
316 case Intrinsic::x86_sse2_pslli_d:
317 case Intrinsic::x86_sse2_pslli_q:
318 case Intrinsic::x86_sse2_pslli_w:
319 case Intrinsic::x86_avx2_psll_d:
320 case Intrinsic::x86_avx2_psll_q:
321 case Intrinsic::x86_avx2_psll_w:
322 case Intrinsic::x86_avx2_pslli_d:
323 case Intrinsic::x86_avx2_pslli_q:
324 case Intrinsic::x86_avx2_pslli_w:
Craig Topper8b831cb2016-11-13 01:51:55 +0000325 case Intrinsic::x86_avx512_psll_d_512:
326 case Intrinsic::x86_avx512_psll_q_512:
327 case Intrinsic::x86_avx512_psll_w_512:
328 case Intrinsic::x86_avx512_pslli_d_512:
329 case Intrinsic::x86_avx512_pslli_q_512:
330 case Intrinsic::x86_avx512_pslli_w_512:
Simon Pilgrimbecd5e82015-08-13 07:39:03 +0000331 LogicalShift = true; ShiftLeft = true;
332 break;
333 }
Simon Pilgrima3a72b42015-08-10 20:21:15 +0000334 assert((LogicalShift || !ShiftLeft) && "Only logical shifts can shift left");
335
Simon Pilgrim3815c162015-08-07 18:22:50 +0000336 // Simplify if count is constant.
337 auto Arg1 = II.getArgOperand(1);
338 auto CAZ = dyn_cast<ConstantAggregateZero>(Arg1);
339 auto CDV = dyn_cast<ConstantDataVector>(Arg1);
340 auto CInt = dyn_cast<ConstantInt>(Arg1);
341 if (!CAZ && !CDV && !CInt)
Simon Pilgrim18617d12015-08-05 08:18:00 +0000342 return nullptr;
Simon Pilgrim3815c162015-08-07 18:22:50 +0000343
344 APInt Count(64, 0);
345 if (CDV) {
346 // SSE2/AVX2 uses all the first 64-bits of the 128-bit vector
347 // operand to compute the shift amount.
348 auto VT = cast<VectorType>(CDV->getType());
349 unsigned BitWidth = VT->getElementType()->getPrimitiveSizeInBits();
350 assert((64 % BitWidth) == 0 && "Unexpected packed shift size");
351 unsigned NumSubElts = 64 / BitWidth;
352
353 // Concatenate the sub-elements to create the 64-bit value.
354 for (unsigned i = 0; i != NumSubElts; ++i) {
355 unsigned SubEltIdx = (NumSubElts - 1) - i;
356 auto SubElt = cast<ConstantInt>(CDV->getElementAsConstant(SubEltIdx));
Craig Topper24e71012017-04-28 03:36:24 +0000357 Count <<= BitWidth;
Simon Pilgrim3815c162015-08-07 18:22:50 +0000358 Count |= SubElt->getValue().zextOrTrunc(64);
359 }
360 }
361 else if (CInt)
362 Count = CInt->getValue();
Simon Pilgrim18617d12015-08-05 08:18:00 +0000363
364 auto Vec = II.getArgOperand(0);
365 auto VT = cast<VectorType>(Vec->getType());
366 auto SVT = VT->getElementType();
Simon Pilgrim3815c162015-08-07 18:22:50 +0000367 unsigned VWidth = VT->getNumElements();
368 unsigned BitWidth = SVT->getPrimitiveSizeInBits();
369
370 // If shift-by-zero then just return the original value.
Craig Topper73ba1c82017-06-07 07:40:37 +0000371 if (Count.isNullValue())
Simon Pilgrim3815c162015-08-07 18:22:50 +0000372 return Vec;
373
Simon Pilgrima3a72b42015-08-10 20:21:15 +0000374 // Handle cases when Shift >= BitWidth.
375 if (Count.uge(BitWidth)) {
376 // If LogicalShift - just return zero.
377 if (LogicalShift)
378 return ConstantAggregateZero::get(VT);
379
380 // If ArithmeticShift - clamp Shift to (BitWidth - 1).
381 Count = APInt(64, BitWidth - 1);
382 }
Simon Pilgrim18617d12015-08-05 08:18:00 +0000383
Simon Pilgrim18617d12015-08-05 08:18:00 +0000384 // Get a constant vector of the same type as the first operand.
Simon Pilgrim3815c162015-08-07 18:22:50 +0000385 auto ShiftAmt = ConstantInt::get(SVT, Count.zextOrTrunc(BitWidth));
386 auto ShiftVec = Builder.CreateVectorSplat(VWidth, ShiftAmt);
Simon Pilgrim18617d12015-08-05 08:18:00 +0000387
388 if (ShiftLeft)
Simon Pilgrim3815c162015-08-07 18:22:50 +0000389 return Builder.CreateShl(Vec, ShiftVec);
Simon Pilgrim18617d12015-08-05 08:18:00 +0000390
Simon Pilgrima3a72b42015-08-10 20:21:15 +0000391 if (LogicalShift)
392 return Builder.CreateLShr(Vec, ShiftVec);
393
394 return Builder.CreateAShr(Vec, ShiftVec);
Simon Pilgrim18617d12015-08-05 08:18:00 +0000395}
396
Simon Pilgrimdb9893f2016-06-07 10:27:15 +0000397// Attempt to simplify AVX2 per-element shift intrinsics to a generic IR shift.
398// Unlike the generic IR shifts, the intrinsics have defined behaviour for out
399// of range shift amounts (logical - set to zero, arithmetic - splat sign bit).
400static Value *simplifyX86varShift(const IntrinsicInst &II,
401 InstCombiner::BuilderTy &Builder) {
402 bool LogicalShift = false;
403 bool ShiftLeft = false;
404
405 switch (II.getIntrinsicID()) {
Craig Topperb4173a52016-11-13 07:26:19 +0000406 default: llvm_unreachable("Unexpected intrinsic!");
Simon Pilgrimdb9893f2016-06-07 10:27:15 +0000407 case Intrinsic::x86_avx2_psrav_d:
408 case Intrinsic::x86_avx2_psrav_d_256:
Craig Topperb4173a52016-11-13 07:26:19 +0000409 case Intrinsic::x86_avx512_psrav_q_128:
410 case Intrinsic::x86_avx512_psrav_q_256:
411 case Intrinsic::x86_avx512_psrav_d_512:
412 case Intrinsic::x86_avx512_psrav_q_512:
Craig Topper1de753f2016-11-18 06:04:33 +0000413 case Intrinsic::x86_avx512_psrav_w_128:
414 case Intrinsic::x86_avx512_psrav_w_256:
415 case Intrinsic::x86_avx512_psrav_w_512:
Simon Pilgrimdb9893f2016-06-07 10:27:15 +0000416 LogicalShift = false;
417 ShiftLeft = false;
418 break;
419 case Intrinsic::x86_avx2_psrlv_d:
420 case Intrinsic::x86_avx2_psrlv_d_256:
421 case Intrinsic::x86_avx2_psrlv_q:
422 case Intrinsic::x86_avx2_psrlv_q_256:
Craig Topperb4173a52016-11-13 07:26:19 +0000423 case Intrinsic::x86_avx512_psrlv_d_512:
424 case Intrinsic::x86_avx512_psrlv_q_512:
Craig Topper1de753f2016-11-18 06:04:33 +0000425 case Intrinsic::x86_avx512_psrlv_w_128:
426 case Intrinsic::x86_avx512_psrlv_w_256:
427 case Intrinsic::x86_avx512_psrlv_w_512:
Simon Pilgrimdb9893f2016-06-07 10:27:15 +0000428 LogicalShift = true;
429 ShiftLeft = false;
430 break;
431 case Intrinsic::x86_avx2_psllv_d:
432 case Intrinsic::x86_avx2_psllv_d_256:
433 case Intrinsic::x86_avx2_psllv_q:
434 case Intrinsic::x86_avx2_psllv_q_256:
Craig Topperb4173a52016-11-13 07:26:19 +0000435 case Intrinsic::x86_avx512_psllv_d_512:
436 case Intrinsic::x86_avx512_psllv_q_512:
Craig Topper1de753f2016-11-18 06:04:33 +0000437 case Intrinsic::x86_avx512_psllv_w_128:
438 case Intrinsic::x86_avx512_psllv_w_256:
439 case Intrinsic::x86_avx512_psllv_w_512:
Simon Pilgrimdb9893f2016-06-07 10:27:15 +0000440 LogicalShift = true;
441 ShiftLeft = true;
442 break;
443 }
444 assert((LogicalShift || !ShiftLeft) && "Only logical shifts can shift left");
445
446 // Simplify if all shift amounts are constant/undef.
447 auto *CShift = dyn_cast<Constant>(II.getArgOperand(1));
448 if (!CShift)
449 return nullptr;
450
451 auto Vec = II.getArgOperand(0);
452 auto VT = cast<VectorType>(II.getType());
453 auto SVT = VT->getVectorElementType();
454 int NumElts = VT->getNumElements();
455 int BitWidth = SVT->getIntegerBitWidth();
456
457 // Collect each element's shift amount.
458 // We also collect special cases: UNDEF = -1, OUT-OF-RANGE = BitWidth.
459 bool AnyOutOfRange = false;
460 SmallVector<int, 8> ShiftAmts;
461 for (int I = 0; I < NumElts; ++I) {
462 auto *CElt = CShift->getAggregateElement(I);
463 if (CElt && isa<UndefValue>(CElt)) {
464 ShiftAmts.push_back(-1);
465 continue;
466 }
467
468 auto *COp = dyn_cast_or_null<ConstantInt>(CElt);
469 if (!COp)
470 return nullptr;
471
472 // Handle out of range shifts.
473 // If LogicalShift - set to BitWidth (special case).
474 // If ArithmeticShift - set to (BitWidth - 1) (sign splat).
475 APInt ShiftVal = COp->getValue();
476 if (ShiftVal.uge(BitWidth)) {
477 AnyOutOfRange = LogicalShift;
478 ShiftAmts.push_back(LogicalShift ? BitWidth : BitWidth - 1);
479 continue;
480 }
481
482 ShiftAmts.push_back((int)ShiftVal.getZExtValue());
483 }
484
485 // If all elements out of range or UNDEF, return vector of zeros/undefs.
486 // ArithmeticShift should only hit this if they are all UNDEF.
487 auto OutOfRange = [&](int Idx) { return (Idx < 0) || (BitWidth <= Idx); };
Eugene Zelenko7f0f9bc2017-10-24 21:24:53 +0000488 if (llvm::all_of(ShiftAmts, OutOfRange)) {
Simon Pilgrimdb9893f2016-06-07 10:27:15 +0000489 SmallVector<Constant *, 8> ConstantVec;
490 for (int Idx : ShiftAmts) {
491 if (Idx < 0) {
492 ConstantVec.push_back(UndefValue::get(SVT));
493 } else {
494 assert(LogicalShift && "Logical shift expected");
495 ConstantVec.push_back(ConstantInt::getNullValue(SVT));
496 }
497 }
498 return ConstantVector::get(ConstantVec);
499 }
500
501 // We can't handle only some out of range values with generic logical shifts.
502 if (AnyOutOfRange)
503 return nullptr;
504
505 // Build the shift amount constant vector.
506 SmallVector<Constant *, 8> ShiftVecAmts;
507 for (int Idx : ShiftAmts) {
508 if (Idx < 0)
509 ShiftVecAmts.push_back(UndefValue::get(SVT));
510 else
511 ShiftVecAmts.push_back(ConstantInt::get(SVT, Idx));
512 }
513 auto ShiftVec = ConstantVector::get(ShiftVecAmts);
514
515 if (ShiftLeft)
516 return Builder.CreateShl(Vec, ShiftVec);
517
518 if (LogicalShift)
519 return Builder.CreateLShr(Vec, ShiftVec);
520
521 return Builder.CreateAShr(Vec, ShiftVec);
522}
523
Craig Topper4853c432017-07-06 23:18:42 +0000524static Value *simplifyX86pack(IntrinsicInst &II, bool IsSigned) {
Simon Pilgrim6f6b2792017-01-25 14:37:24 +0000525 Value *Arg0 = II.getArgOperand(0);
526 Value *Arg1 = II.getArgOperand(1);
527 Type *ResTy = II.getType();
528
529 // Fast all undef handling.
530 if (isa<UndefValue>(Arg0) && isa<UndefValue>(Arg1))
531 return UndefValue::get(ResTy);
532
533 Type *ArgTy = Arg0->getType();
534 unsigned NumLanes = ResTy->getPrimitiveSizeInBits() / 128;
535 unsigned NumDstElts = ResTy->getVectorNumElements();
536 unsigned NumSrcElts = ArgTy->getVectorNumElements();
537 assert(NumDstElts == (2 * NumSrcElts) && "Unexpected packing types");
538
539 unsigned NumDstEltsPerLane = NumDstElts / NumLanes;
540 unsigned NumSrcEltsPerLane = NumSrcElts / NumLanes;
541 unsigned DstScalarSizeInBits = ResTy->getScalarSizeInBits();
542 assert(ArgTy->getScalarSizeInBits() == (2 * DstScalarSizeInBits) &&
543 "Unexpected packing types");
544
545 // Constant folding.
546 auto *Cst0 = dyn_cast<Constant>(Arg0);
547 auto *Cst1 = dyn_cast<Constant>(Arg1);
548 if (!Cst0 || !Cst1)
549 return nullptr;
550
551 SmallVector<Constant *, 32> Vals;
552 for (unsigned Lane = 0; Lane != NumLanes; ++Lane) {
553 for (unsigned Elt = 0; Elt != NumDstEltsPerLane; ++Elt) {
554 unsigned SrcIdx = Lane * NumSrcEltsPerLane + Elt % NumSrcEltsPerLane;
555 auto *Cst = (Elt >= NumSrcEltsPerLane) ? Cst1 : Cst0;
556 auto *COp = Cst->getAggregateElement(SrcIdx);
557 if (COp && isa<UndefValue>(COp)) {
558 Vals.push_back(UndefValue::get(ResTy->getScalarType()));
559 continue;
560 }
561
562 auto *CInt = dyn_cast_or_null<ConstantInt>(COp);
563 if (!CInt)
564 return nullptr;
565
566 APInt Val = CInt->getValue();
567 assert(Val.getBitWidth() == ArgTy->getScalarSizeInBits() &&
568 "Unexpected constant bitwidth");
569
570 if (IsSigned) {
571 // PACKSS: Truncate signed value with signed saturation.
572 // Source values less than dst minint are saturated to minint.
573 // Source values greater than dst maxint are saturated to maxint.
574 if (Val.isSignedIntN(DstScalarSizeInBits))
575 Val = Val.trunc(DstScalarSizeInBits);
576 else if (Val.isNegative())
577 Val = APInt::getSignedMinValue(DstScalarSizeInBits);
578 else
579 Val = APInt::getSignedMaxValue(DstScalarSizeInBits);
580 } else {
581 // PACKUS: Truncate signed value with unsigned saturation.
582 // Source values less than zero are saturated to zero.
583 // Source values greater than dst maxuint are saturated to maxuint.
584 if (Val.isIntN(DstScalarSizeInBits))
585 Val = Val.trunc(DstScalarSizeInBits);
586 else if (Val.isNegative())
587 Val = APInt::getNullValue(DstScalarSizeInBits);
588 else
589 Val = APInt::getAllOnesValue(DstScalarSizeInBits);
590 }
591
592 Vals.push_back(ConstantInt::get(ResTy->getScalarType(), Val));
593 }
594 }
595
596 return ConstantVector::get(Vals);
597}
598
Mikhail Dvoretckii8393f902018-06-19 10:49:12 +0000599// Replace X86-specific intrinsics with generic floor-ceil where applicable.
600static Value *simplifyX86round(IntrinsicInst &II,
601 InstCombiner::BuilderTy &Builder) {
602 ConstantInt *Arg = nullptr;
603 Intrinsic::ID IntrinsicID = II.getIntrinsicID();
604
605 if (IntrinsicID == Intrinsic::x86_sse41_round_ss ||
606 IntrinsicID == Intrinsic::x86_sse41_round_sd)
607 Arg = dyn_cast<ConstantInt>(II.getArgOperand(2));
608 else if (IntrinsicID == Intrinsic::x86_avx512_mask_rndscale_ss ||
609 IntrinsicID == Intrinsic::x86_avx512_mask_rndscale_sd)
610 Arg = dyn_cast<ConstantInt>(II.getArgOperand(4));
611 else
612 Arg = dyn_cast<ConstantInt>(II.getArgOperand(1));
613 if (!Arg)
614 return nullptr;
615 unsigned RoundControl = Arg->getZExtValue();
616
617 Arg = nullptr;
618 unsigned SAE = 0;
619 if (IntrinsicID == Intrinsic::x86_avx512_mask_rndscale_ps_512 ||
620 IntrinsicID == Intrinsic::x86_avx512_mask_rndscale_pd_512)
621 Arg = dyn_cast<ConstantInt>(II.getArgOperand(4));
622 else if (IntrinsicID == Intrinsic::x86_avx512_mask_rndscale_ss ||
623 IntrinsicID == Intrinsic::x86_avx512_mask_rndscale_sd)
624 Arg = dyn_cast<ConstantInt>(II.getArgOperand(5));
625 else
626 SAE = 4;
627 if (!SAE) {
628 if (!Arg)
629 return nullptr;
630 SAE = Arg->getZExtValue();
631 }
632
633 if (SAE != 4 || (RoundControl != 2 /*ceil*/ && RoundControl != 1 /*floor*/))
634 return nullptr;
635
636 Value *Src, *Dst, *Mask;
637 bool IsScalar = false;
638 if (IntrinsicID == Intrinsic::x86_sse41_round_ss ||
639 IntrinsicID == Intrinsic::x86_sse41_round_sd ||
640 IntrinsicID == Intrinsic::x86_avx512_mask_rndscale_ss ||
641 IntrinsicID == Intrinsic::x86_avx512_mask_rndscale_sd) {
642 IsScalar = true;
643 if (IntrinsicID == Intrinsic::x86_avx512_mask_rndscale_ss ||
644 IntrinsicID == Intrinsic::x86_avx512_mask_rndscale_sd) {
645 Mask = II.getArgOperand(3);
646 Value *Zero = Constant::getNullValue(Mask->getType());
647 Mask = Builder.CreateAnd(Mask, 1);
648 Mask = Builder.CreateICmp(ICmpInst::ICMP_NE, Mask, Zero);
649 Dst = II.getArgOperand(2);
650 } else
651 Dst = II.getArgOperand(0);
652 Src = Builder.CreateExtractElement(II.getArgOperand(1), (uint64_t)0);
653 } else {
654 Src = II.getArgOperand(0);
655 if (IntrinsicID == Intrinsic::x86_avx512_mask_rndscale_ps_128 ||
656 IntrinsicID == Intrinsic::x86_avx512_mask_rndscale_ps_256 ||
657 IntrinsicID == Intrinsic::x86_avx512_mask_rndscale_ps_512 ||
658 IntrinsicID == Intrinsic::x86_avx512_mask_rndscale_pd_128 ||
659 IntrinsicID == Intrinsic::x86_avx512_mask_rndscale_pd_256 ||
660 IntrinsicID == Intrinsic::x86_avx512_mask_rndscale_pd_512) {
661 Dst = II.getArgOperand(2);
662 Mask = II.getArgOperand(3);
663 } else {
664 Dst = Src;
665 Mask = ConstantInt::getAllOnesValue(
666 Builder.getIntNTy(Src->getType()->getVectorNumElements()));
667 }
668 }
669
670 Intrinsic::ID ID = (RoundControl == 2) ? Intrinsic::ceil : Intrinsic::floor;
Neil Henning57f5d0a2018-10-08 10:32:33 +0000671 Value *Res = Builder.CreateUnaryIntrinsic(ID, Src, &II);
Mikhail Dvoretckii8393f902018-06-19 10:49:12 +0000672 if (!IsScalar) {
673 if (auto *C = dyn_cast<Constant>(Mask))
674 if (C->isAllOnesValue())
675 return Res;
676 auto *MaskTy = VectorType::get(
677 Builder.getInt1Ty(), cast<IntegerType>(Mask->getType())->getBitWidth());
678 Mask = Builder.CreateBitCast(Mask, MaskTy);
679 unsigned Width = Src->getType()->getVectorNumElements();
680 if (MaskTy->getVectorNumElements() > Width) {
681 uint32_t Indices[4];
682 for (unsigned i = 0; i != Width; ++i)
683 Indices[i] = i;
684 Mask = Builder.CreateShuffleVector(Mask, Mask,
685 makeArrayRef(Indices, Width));
686 }
687 return Builder.CreateSelect(Mask, Res, Dst);
688 }
689 if (IntrinsicID == Intrinsic::x86_avx512_mask_rndscale_ss ||
690 IntrinsicID == Intrinsic::x86_avx512_mask_rndscale_sd) {
691 Dst = Builder.CreateExtractElement(Dst, (uint64_t)0);
692 Res = Builder.CreateSelect(Mask, Res, Dst);
693 Dst = II.getArgOperand(0);
694 }
695 return Builder.CreateInsertElement(Dst, Res, (uint64_t)0);
696}
697
Sanjay Patel2aa2dc72018-12-11 16:38:03 +0000698static Value *simplifyX86movmsk(const IntrinsicInst &II,
699 InstCombiner::BuilderTy &Builder) {
Simon Pilgrim91e3ac82016-06-07 08:18:35 +0000700 Value *Arg = II.getArgOperand(0);
701 Type *ResTy = II.getType();
702 Type *ArgTy = Arg->getType();
703
704 // movmsk(undef) -> zero as we must ensure the upper bits are zero.
705 if (isa<UndefValue>(Arg))
706 return Constant::getNullValue(ResTy);
707
708 // We can't easily peek through x86_mmx types.
709 if (!ArgTy->isVectorTy())
710 return nullptr;
711
Sanjay Patel2aa2dc72018-12-11 16:38:03 +0000712 if (auto *C = dyn_cast<Constant>(Arg)) {
713 // Extract signbits of the vector input and pack into integer result.
714 APInt Result(ResTy->getPrimitiveSizeInBits(), 0);
715 for (unsigned I = 0, E = ArgTy->getVectorNumElements(); I != E; ++I) {
716 auto *COp = C->getAggregateElement(I);
717 if (!COp)
718 return nullptr;
719 if (isa<UndefValue>(COp))
720 continue;
Simon Pilgrim91e3ac82016-06-07 08:18:35 +0000721
Sanjay Patel2aa2dc72018-12-11 16:38:03 +0000722 auto *CInt = dyn_cast<ConstantInt>(COp);
723 auto *CFp = dyn_cast<ConstantFP>(COp);
724 if (!CInt && !CFp)
725 return nullptr;
Simon Pilgrim91e3ac82016-06-07 08:18:35 +0000726
Sanjay Patel2aa2dc72018-12-11 16:38:03 +0000727 if ((CInt && CInt->isNegative()) || (CFp && CFp->isNegative()))
728 Result.setBit(I);
729 }
730 return Constant::getIntegerValue(ResTy, Result);
Simon Pilgrim91e3ac82016-06-07 08:18:35 +0000731 }
732
Sanjay Patel2aa2dc72018-12-11 16:38:03 +0000733 // Look for a sign-extended boolean source vector as the argument to this
734 // movmsk. If the argument is bitcast, look through that, but make sure the
735 // source of that bitcast is still a vector with the same number of elements.
736 // TODO: We can also convert a bitcast with wider elements, but that requires
737 // duplicating the bool source sign bits to match the number of elements
738 // expected by the movmsk call.
739 Arg = peekThroughBitcast(Arg);
740 Value *X;
741 if (Arg->getType()->isVectorTy() &&
742 Arg->getType()->getVectorNumElements() == ArgTy->getVectorNumElements() &&
743 match(Arg, m_SExt(m_Value(X))) && X->getType()->isIntOrIntVectorTy(1)) {
744 // call iM movmsk(sext <N x i1> X) --> zext (bitcast <N x i1> X to iN) to iM
745 unsigned NumElts = X->getType()->getVectorNumElements();
746 Type *ScalarTy = Type::getIntNTy(Arg->getContext(), NumElts);
747 Value *BC = Builder.CreateBitCast(X, ScalarTy);
748 return Builder.CreateZExtOrTrunc(BC, ResTy);
749 }
750
751 return nullptr;
Simon Pilgrim91e3ac82016-06-07 08:18:35 +0000752}
753
Sanjay Patelbe23a912019-02-01 14:14:47 +0000754static Value *simplifyX86addcarry(const IntrinsicInst &II,
755 InstCombiner::BuilderTy &Builder) {
756 Value *CarryIn = II.getArgOperand(0);
757 Value *Op1 = II.getArgOperand(1);
758 Value *Op2 = II.getArgOperand(2);
759 Type *RetTy = II.getType();
760 Type *OpTy = Op1->getType();
761 assert(RetTy->getStructElementType(0)->isIntegerTy(8) &&
762 RetTy->getStructElementType(1) == OpTy && OpTy == Op2->getType() &&
763 "Unexpected types for x86 addcarry");
764
765 // If carry-in is zero, this is just an unsigned add with overflow.
766 if (match(CarryIn, m_ZeroInt())) {
767 Value *UAdd = Builder.CreateIntrinsic(Intrinsic::uadd_with_overflow, OpTy,
768 { Op1, Op2 });
769 // The types have to be adjusted to match the x86 call types.
770 Value *UAddResult = Builder.CreateExtractValue(UAdd, 0);
771 Value *UAddOV = Builder.CreateZExt(Builder.CreateExtractValue(UAdd, 1),
772 Builder.getInt8Ty());
Sanjay Patelfbcbac72019-02-01 14:37:49 +0000773 Value *Res = UndefValue::get(RetTy);
Sanjay Patelbe23a912019-02-01 14:14:47 +0000774 Res = Builder.CreateInsertValue(Res, UAddOV, 0);
775 return Builder.CreateInsertValue(Res, UAddResult, 1);
776 }
777
778 return nullptr;
779}
780
Sanjay Patel6038d3e2016-01-29 23:27:03 +0000781static Value *simplifyX86insertps(const IntrinsicInst &II,
Sanjay Patelc86867c2015-04-16 17:52:13 +0000782 InstCombiner::BuilderTy &Builder) {
Sanjay Patel03c03f52016-01-28 00:03:16 +0000783 auto *CInt = dyn_cast<ConstantInt>(II.getArgOperand(2));
784 if (!CInt)
785 return nullptr;
Simon Pilgrim54fcd622015-07-25 20:41:00 +0000786
Sanjay Patel03c03f52016-01-28 00:03:16 +0000787 VectorType *VecTy = cast<VectorType>(II.getType());
788 assert(VecTy->getNumElements() == 4 && "insertps with wrong vector type");
Sanjay Patelc86867c2015-04-16 17:52:13 +0000789
Sanjay Patel03c03f52016-01-28 00:03:16 +0000790 // The immediate permute control byte looks like this:
791 // [3:0] - zero mask for each 32-bit lane
792 // [5:4] - select one 32-bit destination lane
793 // [7:6] - select one 32-bit source lane
Sanjay Patelc86867c2015-04-16 17:52:13 +0000794
Sanjay Patel03c03f52016-01-28 00:03:16 +0000795 uint8_t Imm = CInt->getZExtValue();
796 uint8_t ZMask = Imm & 0xf;
797 uint8_t DestLane = (Imm >> 4) & 0x3;
798 uint8_t SourceLane = (Imm >> 6) & 0x3;
Sanjay Patelc1d20a32015-04-25 20:55:25 +0000799
Sanjay Patel03c03f52016-01-28 00:03:16 +0000800 ConstantAggregateZero *ZeroVector = ConstantAggregateZero::get(VecTy);
Sanjay Patelc86867c2015-04-16 17:52:13 +0000801
Sanjay Patel03c03f52016-01-28 00:03:16 +0000802 // If all zero mask bits are set, this was just a weird way to
803 // generate a zero vector.
804 if (ZMask == 0xf)
805 return ZeroVector;
Sanjay Patelc1d20a32015-04-25 20:55:25 +0000806
Sanjay Patel03c03f52016-01-28 00:03:16 +0000807 // Initialize by passing all of the first source bits through.
Craig Topper99d1eab2016-06-12 00:41:19 +0000808 uint32_t ShuffleMask[4] = { 0, 1, 2, 3 };
Sanjay Patelc1d20a32015-04-25 20:55:25 +0000809
Sanjay Patel03c03f52016-01-28 00:03:16 +0000810 // We may replace the second operand with the zero vector.
811 Value *V1 = II.getArgOperand(1);
812
813 if (ZMask) {
814 // If the zero mask is being used with a single input or the zero mask
815 // overrides the destination lane, this is a shuffle with the zero vector.
816 if ((II.getArgOperand(0) == II.getArgOperand(1)) ||
817 (ZMask & (1 << DestLane))) {
818 V1 = ZeroVector;
819 // We may still move 32-bits of the first source vector from one lane
820 // to another.
821 ShuffleMask[DestLane] = SourceLane;
822 // The zero mask may override the previous insert operation.
823 for (unsigned i = 0; i < 4; ++i)
824 if ((ZMask >> i) & 0x1)
825 ShuffleMask[i] = i + 4;
Sanjay Patelc1d20a32015-04-25 20:55:25 +0000826 } else {
Sanjay Patel03c03f52016-01-28 00:03:16 +0000827 // TODO: Model this case as 2 shuffles or a 'logical and' plus shuffle?
828 return nullptr;
Sanjay Patelc1d20a32015-04-25 20:55:25 +0000829 }
Sanjay Patel03c03f52016-01-28 00:03:16 +0000830 } else {
831 // Replace the selected destination lane with the selected source lane.
832 ShuffleMask[DestLane] = SourceLane + 4;
Sanjay Patelc86867c2015-04-16 17:52:13 +0000833 }
Sanjay Patel03c03f52016-01-28 00:03:16 +0000834
835 return Builder.CreateShuffleVector(II.getArgOperand(0), V1, ShuffleMask);
Sanjay Patelc86867c2015-04-16 17:52:13 +0000836}
837
Simon Pilgrim216b1bf2015-10-17 11:40:05 +0000838/// Attempt to simplify SSE4A EXTRQ/EXTRQI instructions using constant folding
839/// or conversion to a shuffle vector.
Sanjay Patel6038d3e2016-01-29 23:27:03 +0000840static Value *simplifyX86extrq(IntrinsicInst &II, Value *Op0,
Simon Pilgrim216b1bf2015-10-17 11:40:05 +0000841 ConstantInt *CILength, ConstantInt *CIIndex,
842 InstCombiner::BuilderTy &Builder) {
843 auto LowConstantHighUndef = [&](uint64_t Val) {
844 Type *IntTy64 = Type::getInt64Ty(II.getContext());
845 Constant *Args[] = {ConstantInt::get(IntTy64, Val),
846 UndefValue::get(IntTy64)};
847 return ConstantVector::get(Args);
848 };
849
850 // See if we're dealing with constant values.
851 Constant *C0 = dyn_cast<Constant>(Op0);
852 ConstantInt *CI0 =
Andrea Di Biagio8df5b9c2016-09-07 12:03:03 +0000853 C0 ? dyn_cast_or_null<ConstantInt>(C0->getAggregateElement((unsigned)0))
Simon Pilgrim216b1bf2015-10-17 11:40:05 +0000854 : nullptr;
855
856 // Attempt to constant fold.
857 if (CILength && CIIndex) {
858 // From AMD documentation: "The bit index and field length are each six
859 // bits in length other bits of the field are ignored."
860 APInt APIndex = CIIndex->getValue().zextOrTrunc(6);
861 APInt APLength = CILength->getValue().zextOrTrunc(6);
862
863 unsigned Index = APIndex.getZExtValue();
864
865 // From AMD documentation: "a value of zero in the field length is
866 // defined as length of 64".
867 unsigned Length = APLength == 0 ? 64 : APLength.getZExtValue();
868
869 // From AMD documentation: "If the sum of the bit index + length field
870 // is greater than 64, the results are undefined".
871 unsigned End = Index + Length;
872
873 // Note that both field index and field length are 8-bit quantities.
874 // Since variables 'Index' and 'Length' are unsigned values
875 // obtained from zero-extending field index and field length
876 // respectively, their sum should never wrap around.
877 if (End > 64)
878 return UndefValue::get(II.getType());
879
880 // If we are inserting whole bytes, we can convert this to a shuffle.
881 // Lowering can recognize EXTRQI shuffle masks.
882 if ((Length % 8) == 0 && (Index % 8) == 0) {
883 // Convert bit indices to byte indices.
884 Length /= 8;
885 Index /= 8;
886
887 Type *IntTy8 = Type::getInt8Ty(II.getContext());
888 Type *IntTy32 = Type::getInt32Ty(II.getContext());
889 VectorType *ShufTy = VectorType::get(IntTy8, 16);
890
891 SmallVector<Constant *, 16> ShuffleMask;
892 for (int i = 0; i != (int)Length; ++i)
893 ShuffleMask.push_back(
894 Constant::getIntegerValue(IntTy32, APInt(32, i + Index)));
895 for (int i = Length; i != 8; ++i)
896 ShuffleMask.push_back(
897 Constant::getIntegerValue(IntTy32, APInt(32, i + 16)));
898 for (int i = 8; i != 16; ++i)
899 ShuffleMask.push_back(UndefValue::get(IntTy32));
900
901 Value *SV = Builder.CreateShuffleVector(
902 Builder.CreateBitCast(Op0, ShufTy),
903 ConstantAggregateZero::get(ShufTy), ConstantVector::get(ShuffleMask));
904 return Builder.CreateBitCast(SV, II.getType());
905 }
906
907 // Constant Fold - shift Index'th bit to lowest position and mask off
908 // Length bits.
909 if (CI0) {
910 APInt Elt = CI0->getValue();
Craig Topperfc947bc2017-04-18 17:14:21 +0000911 Elt.lshrInPlace(Index);
912 Elt = Elt.zextOrTrunc(Length);
Simon Pilgrim216b1bf2015-10-17 11:40:05 +0000913 return LowConstantHighUndef(Elt.getZExtValue());
914 }
915
916 // If we were an EXTRQ call, we'll save registers if we convert to EXTRQI.
917 if (II.getIntrinsicID() == Intrinsic::x86_sse4a_extrq) {
918 Value *Args[] = {Op0, CILength, CIIndex};
Sanjay Patelaf674fb2015-12-14 17:24:23 +0000919 Module *M = II.getModule();
James Y Knight7976eb52019-02-01 20:43:25 +0000920 Function *F = Intrinsic::getDeclaration(M, Intrinsic::x86_sse4a_extrqi);
Simon Pilgrim216b1bf2015-10-17 11:40:05 +0000921 return Builder.CreateCall(F, Args);
922 }
923 }
924
925 // Constant Fold - extraction from zero is always {zero, undef}.
Craig Topperca2c8762017-07-06 18:39:49 +0000926 if (CI0 && CI0->isZero())
Simon Pilgrim216b1bf2015-10-17 11:40:05 +0000927 return LowConstantHighUndef(0);
928
929 return nullptr;
930}
931
932/// Attempt to simplify SSE4A INSERTQ/INSERTQI instructions using constant
933/// folding or conversion to a shuffle vector.
Sanjay Patel6038d3e2016-01-29 23:27:03 +0000934static Value *simplifyX86insertq(IntrinsicInst &II, Value *Op0, Value *Op1,
Simon Pilgrim216b1bf2015-10-17 11:40:05 +0000935 APInt APLength, APInt APIndex,
936 InstCombiner::BuilderTy &Builder) {
Simon Pilgrim216b1bf2015-10-17 11:40:05 +0000937 // From AMD documentation: "The bit index and field length are each six bits
938 // in length other bits of the field are ignored."
939 APIndex = APIndex.zextOrTrunc(6);
940 APLength = APLength.zextOrTrunc(6);
941
942 // Attempt to constant fold.
943 unsigned Index = APIndex.getZExtValue();
944
945 // From AMD documentation: "a value of zero in the field length is
946 // defined as length of 64".
947 unsigned Length = APLength == 0 ? 64 : APLength.getZExtValue();
948
949 // From AMD documentation: "If the sum of the bit index + length field
950 // is greater than 64, the results are undefined".
951 unsigned End = Index + Length;
952
953 // Note that both field index and field length are 8-bit quantities.
954 // Since variables 'Index' and 'Length' are unsigned values
955 // obtained from zero-extending field index and field length
956 // respectively, their sum should never wrap around.
957 if (End > 64)
958 return UndefValue::get(II.getType());
959
960 // If we are inserting whole bytes, we can convert this to a shuffle.
961 // Lowering can recognize INSERTQI shuffle masks.
962 if ((Length % 8) == 0 && (Index % 8) == 0) {
963 // Convert bit indices to byte indices.
964 Length /= 8;
965 Index /= 8;
966
967 Type *IntTy8 = Type::getInt8Ty(II.getContext());
968 Type *IntTy32 = Type::getInt32Ty(II.getContext());
969 VectorType *ShufTy = VectorType::get(IntTy8, 16);
970
971 SmallVector<Constant *, 16> ShuffleMask;
972 for (int i = 0; i != (int)Index; ++i)
973 ShuffleMask.push_back(Constant::getIntegerValue(IntTy32, APInt(32, i)));
974 for (int i = 0; i != (int)Length; ++i)
975 ShuffleMask.push_back(
976 Constant::getIntegerValue(IntTy32, APInt(32, i + 16)));
977 for (int i = Index + Length; i != 8; ++i)
978 ShuffleMask.push_back(Constant::getIntegerValue(IntTy32, APInt(32, i)));
979 for (int i = 8; i != 16; ++i)
980 ShuffleMask.push_back(UndefValue::get(IntTy32));
981
982 Value *SV = Builder.CreateShuffleVector(Builder.CreateBitCast(Op0, ShufTy),
983 Builder.CreateBitCast(Op1, ShufTy),
984 ConstantVector::get(ShuffleMask));
985 return Builder.CreateBitCast(SV, II.getType());
986 }
987
988 // See if we're dealing with constant values.
989 Constant *C0 = dyn_cast<Constant>(Op0);
990 Constant *C1 = dyn_cast<Constant>(Op1);
991 ConstantInt *CI00 =
Andrea Di Biagiof3fd3162016-09-07 12:47:53 +0000992 C0 ? dyn_cast_or_null<ConstantInt>(C0->getAggregateElement((unsigned)0))
Simon Pilgrim216b1bf2015-10-17 11:40:05 +0000993 : nullptr;
994 ConstantInt *CI10 =
Andrea Di Biagiof3fd3162016-09-07 12:47:53 +0000995 C1 ? dyn_cast_or_null<ConstantInt>(C1->getAggregateElement((unsigned)0))
Simon Pilgrim216b1bf2015-10-17 11:40:05 +0000996 : nullptr;
997
998 // Constant Fold - insert bottom Length bits starting at the Index'th bit.
999 if (CI00 && CI10) {
1000 APInt V00 = CI00->getValue();
1001 APInt V10 = CI10->getValue();
1002 APInt Mask = APInt::getLowBitsSet(64, Length).shl(Index);
1003 V00 = V00 & ~Mask;
1004 V10 = V10.zextOrTrunc(Length).zextOrTrunc(64).shl(Index);
1005 APInt Val = V00 | V10;
1006 Type *IntTy64 = Type::getInt64Ty(II.getContext());
1007 Constant *Args[] = {ConstantInt::get(IntTy64, Val.getZExtValue()),
1008 UndefValue::get(IntTy64)};
1009 return ConstantVector::get(Args);
1010 }
1011
1012 // If we were an INSERTQ call, we'll save demanded elements if we convert to
1013 // INSERTQI.
1014 if (II.getIntrinsicID() == Intrinsic::x86_sse4a_insertq) {
1015 Type *IntTy8 = Type::getInt8Ty(II.getContext());
1016 Constant *CILength = ConstantInt::get(IntTy8, Length, false);
1017 Constant *CIIndex = ConstantInt::get(IntTy8, Index, false);
1018
1019 Value *Args[] = {Op0, Op1, CILength, CIIndex};
Sanjay Patelaf674fb2015-12-14 17:24:23 +00001020 Module *M = II.getModule();
James Y Knight7976eb52019-02-01 20:43:25 +00001021 Function *F = Intrinsic::getDeclaration(M, Intrinsic::x86_sse4a_insertqi);
Simon Pilgrim216b1bf2015-10-17 11:40:05 +00001022 return Builder.CreateCall(F, Args);
1023 }
1024
1025 return nullptr;
1026}
1027
Simon Pilgrimc0c56e72016-04-24 17:00:34 +00001028/// Attempt to convert pshufb* to shufflevector if the mask is constant.
1029static Value *simplifyX86pshufb(const IntrinsicInst &II,
1030 InstCombiner::BuilderTy &Builder) {
Simon Pilgrimbf60cc42016-04-29 21:34:54 +00001031 Constant *V = dyn_cast<Constant>(II.getArgOperand(1));
1032 if (!V)
1033 return nullptr;
1034
Simon Pilgrime5e8c2f2016-05-01 19:26:21 +00001035 auto *VecTy = cast<VectorType>(II.getType());
1036 auto *MaskEltTy = Type::getInt32Ty(II.getContext());
1037 unsigned NumElts = VecTy->getNumElements();
Craig Topper9a63d7a2016-12-11 00:23:50 +00001038 assert((NumElts == 16 || NumElts == 32 || NumElts == 64) &&
Simon Pilgrimc0c56e72016-04-24 17:00:34 +00001039 "Unexpected number of elements in shuffle mask!");
Simon Pilgrimbf60cc42016-04-29 21:34:54 +00001040
Simon Pilgrime5e8c2f2016-05-01 19:26:21 +00001041 // Construct a shuffle mask from constant integers or UNDEFs.
Craig Topper9a63d7a2016-12-11 00:23:50 +00001042 Constant *Indexes[64] = {nullptr};
Simon Pilgrimc0c56e72016-04-24 17:00:34 +00001043
Simon Pilgrimbf60cc42016-04-29 21:34:54 +00001044 // Each byte in the shuffle control mask forms an index to permute the
1045 // corresponding byte in the destination operand.
1046 for (unsigned I = 0; I < NumElts; ++I) {
1047 Constant *COp = V->getAggregateElement(I);
Simon Pilgrime5e8c2f2016-05-01 19:26:21 +00001048 if (!COp || (!isa<UndefValue>(COp) && !isa<ConstantInt>(COp)))
Simon Pilgrimbf60cc42016-04-29 21:34:54 +00001049 return nullptr;
Simon Pilgrimc0c56e72016-04-24 17:00:34 +00001050
Simon Pilgrime5e8c2f2016-05-01 19:26:21 +00001051 if (isa<UndefValue>(COp)) {
1052 Indexes[I] = UndefValue::get(MaskEltTy);
1053 continue;
1054 }
1055
Simon Pilgrimbf60cc42016-04-29 21:34:54 +00001056 int8_t Index = cast<ConstantInt>(COp)->getValue().getZExtValue();
1057
1058 // If the most significant bit (bit[7]) of each byte of the shuffle
1059 // control mask is set, then zero is written in the result byte.
1060 // The zero vector is in the right-hand side of the resulting
1061 // shufflevector.
1062
Simon Pilgrime5e8c2f2016-05-01 19:26:21 +00001063 // The value of each index for the high 128-bit lane is the least
1064 // significant 4 bits of the respective shuffle control byte.
1065 Index = ((Index < 0) ? NumElts : Index & 0x0F) + (I & 0xF0);
1066 Indexes[I] = ConstantInt::get(MaskEltTy, Index);
Simon Pilgrimbf60cc42016-04-29 21:34:54 +00001067 }
Simon Pilgrimc0c56e72016-04-24 17:00:34 +00001068
Simon Pilgrime5e8c2f2016-05-01 19:26:21 +00001069 auto ShuffleMask = ConstantVector::get(makeArrayRef(Indexes, NumElts));
Simon Pilgrimc0c56e72016-04-24 17:00:34 +00001070 auto V1 = II.getArgOperand(0);
Simon Pilgrime5e8c2f2016-05-01 19:26:21 +00001071 auto V2 = Constant::getNullValue(VecTy);
Simon Pilgrimc0c56e72016-04-24 17:00:34 +00001072 return Builder.CreateShuffleVector(V1, V2, ShuffleMask);
1073}
1074
Simon Pilgrim2f6097d2016-04-24 17:23:46 +00001075/// Attempt to convert vpermilvar* to shufflevector if the mask is constant.
1076static Value *simplifyX86vpermilvar(const IntrinsicInst &II,
1077 InstCombiner::BuilderTy &Builder) {
Simon Pilgrim640f9962016-04-30 07:23:30 +00001078 Constant *V = dyn_cast<Constant>(II.getArgOperand(1));
1079 if (!V)
1080 return nullptr;
Simon Pilgrim2f6097d2016-04-24 17:23:46 +00001081
Craig Topper58917f32016-12-11 01:59:36 +00001082 auto *VecTy = cast<VectorType>(II.getType());
Simon Pilgrimeeacc402016-05-01 20:22:42 +00001083 auto *MaskEltTy = Type::getInt32Ty(II.getContext());
Craig Topper58917f32016-12-11 01:59:36 +00001084 unsigned NumElts = VecTy->getVectorNumElements();
1085 bool IsPD = VecTy->getScalarType()->isDoubleTy();
1086 unsigned NumLaneElts = IsPD ? 2 : 4;
1087 assert(NumElts == 16 || NumElts == 8 || NumElts == 4 || NumElts == 2);
Simon Pilgrim2f6097d2016-04-24 17:23:46 +00001088
Simon Pilgrimeeacc402016-05-01 20:22:42 +00001089 // Construct a shuffle mask from constant integers or UNDEFs.
Craig Topper58917f32016-12-11 01:59:36 +00001090 Constant *Indexes[16] = {nullptr};
Simon Pilgrim640f9962016-04-30 07:23:30 +00001091
1092 // The intrinsics only read one or two bits, clear the rest.
Simon Pilgrimeeacc402016-05-01 20:22:42 +00001093 for (unsigned I = 0; I < NumElts; ++I) {
Simon Pilgrim640f9962016-04-30 07:23:30 +00001094 Constant *COp = V->getAggregateElement(I);
Simon Pilgrimeeacc402016-05-01 20:22:42 +00001095 if (!COp || (!isa<UndefValue>(COp) && !isa<ConstantInt>(COp)))
Simon Pilgrim640f9962016-04-30 07:23:30 +00001096 return nullptr;
1097
Simon Pilgrimeeacc402016-05-01 20:22:42 +00001098 if (isa<UndefValue>(COp)) {
1099 Indexes[I] = UndefValue::get(MaskEltTy);
1100 continue;
1101 }
1102
1103 APInt Index = cast<ConstantInt>(COp)->getValue();
1104 Index = Index.zextOrTrunc(32).getLoBits(2);
Simon Pilgrim640f9962016-04-30 07:23:30 +00001105
1106 // The PD variants uses bit 1 to select per-lane element index, so
1107 // shift down to convert to generic shuffle mask index.
Craig Topper58917f32016-12-11 01:59:36 +00001108 if (IsPD)
Craig Topperfc947bc2017-04-18 17:14:21 +00001109 Index.lshrInPlace(1);
Simon Pilgrimeeacc402016-05-01 20:22:42 +00001110
1111 // The _256 variants are a bit trickier since the mask bits always index
1112 // into the corresponding 128 half. In order to convert to a generic
1113 // shuffle, we have to make that explicit.
Craig Topper58917f32016-12-11 01:59:36 +00001114 Index += APInt(32, (I / NumLaneElts) * NumLaneElts);
Simon Pilgrimeeacc402016-05-01 20:22:42 +00001115
1116 Indexes[I] = ConstantInt::get(MaskEltTy, Index);
Simon Pilgrim2f6097d2016-04-24 17:23:46 +00001117 }
1118
Simon Pilgrimeeacc402016-05-01 20:22:42 +00001119 auto ShuffleMask = ConstantVector::get(makeArrayRef(Indexes, NumElts));
Simon Pilgrim2f6097d2016-04-24 17:23:46 +00001120 auto V1 = II.getArgOperand(0);
1121 auto V2 = UndefValue::get(V1->getType());
1122 return Builder.CreateShuffleVector(V1, V2, ShuffleMask);
1123}
1124
Simon Pilgrim8cddf8b2016-05-01 16:41:22 +00001125/// Attempt to convert vpermd/vpermps to shufflevector if the mask is constant.
1126static Value *simplifyX86vpermv(const IntrinsicInst &II,
1127 InstCombiner::BuilderTy &Builder) {
1128 auto *V = dyn_cast<Constant>(II.getArgOperand(1));
1129 if (!V)
1130 return nullptr;
1131
Simon Pilgrimca140b12016-05-01 20:43:02 +00001132 auto *VecTy = cast<VectorType>(II.getType());
1133 auto *MaskEltTy = Type::getInt32Ty(II.getContext());
Simon Pilgrim8cddf8b2016-05-01 16:41:22 +00001134 unsigned Size = VecTy->getNumElements();
Craig Toppere3280452016-12-25 23:58:57 +00001135 assert((Size == 4 || Size == 8 || Size == 16 || Size == 32 || Size == 64) &&
1136 "Unexpected shuffle mask size");
Simon Pilgrim8cddf8b2016-05-01 16:41:22 +00001137
Simon Pilgrimca140b12016-05-01 20:43:02 +00001138 // Construct a shuffle mask from constant integers or UNDEFs.
Craig Toppere3280452016-12-25 23:58:57 +00001139 Constant *Indexes[64] = {nullptr};
Simon Pilgrim8cddf8b2016-05-01 16:41:22 +00001140
1141 for (unsigned I = 0; I < Size; ++I) {
1142 Constant *COp = V->getAggregateElement(I);
Simon Pilgrimca140b12016-05-01 20:43:02 +00001143 if (!COp || (!isa<UndefValue>(COp) && !isa<ConstantInt>(COp)))
Simon Pilgrim8cddf8b2016-05-01 16:41:22 +00001144 return nullptr;
1145
Simon Pilgrimca140b12016-05-01 20:43:02 +00001146 if (isa<UndefValue>(COp)) {
1147 Indexes[I] = UndefValue::get(MaskEltTy);
1148 continue;
1149 }
1150
Craig Toppere3280452016-12-25 23:58:57 +00001151 uint32_t Index = cast<ConstantInt>(COp)->getZExtValue();
1152 Index &= Size - 1;
Simon Pilgrimca140b12016-05-01 20:43:02 +00001153 Indexes[I] = ConstantInt::get(MaskEltTy, Index);
Simon Pilgrim8cddf8b2016-05-01 16:41:22 +00001154 }
1155
Simon Pilgrimca140b12016-05-01 20:43:02 +00001156 auto ShuffleMask = ConstantVector::get(makeArrayRef(Indexes, Size));
Simon Pilgrim8cddf8b2016-05-01 16:41:22 +00001157 auto V1 = II.getArgOperand(0);
1158 auto V2 = UndefValue::get(VecTy);
1159 return Builder.CreateShuffleVector(V1, V2, ShuffleMask);
1160}
1161
David Majnemer666aa942016-07-14 06:58:42 +00001162static bool maskIsAllOneOrUndef(Value *Mask) {
1163 auto *ConstMask = dyn_cast<Constant>(Mask);
1164 if (!ConstMask)
1165 return false;
1166 if (ConstMask->isAllOnesValue() || isa<UndefValue>(ConstMask))
1167 return true;
1168 for (unsigned I = 0, E = ConstMask->getType()->getVectorNumElements(); I != E;
1169 ++I) {
1170 if (auto *MaskElt = ConstMask->getAggregateElement(I))
1171 if (MaskElt->isAllOnesValue() || isa<UndefValue>(MaskElt))
1172 continue;
1173 return false;
1174 }
1175 return true;
1176}
1177
Philip Reames484d07c2019-03-20 03:36:05 +00001178// TODO, Obvious Missing Transforms:
1179// * Dereferenceable address -> speculative load/select
1180// * Narrow width by halfs excluding zero/undef lanes
Sanjay Patelb695c552016-02-01 17:00:10 +00001181static Value *simplifyMaskedLoad(const IntrinsicInst &II,
1182 InstCombiner::BuilderTy &Builder) {
David Majnemer666aa942016-07-14 06:58:42 +00001183 // If the mask is all ones or undefs, this is a plain vector load of the 1st
1184 // argument.
1185 if (maskIsAllOneOrUndef(II.getArgOperand(2))) {
Sanjay Patelb695c552016-02-01 17:00:10 +00001186 Value *LoadPtr = II.getArgOperand(0);
1187 unsigned Alignment = cast<ConstantInt>(II.getArgOperand(1))->getZExtValue();
James Y Knight14359ef2019-02-01 20:44:24 +00001188 return Builder.CreateAlignedLoad(II.getType(), LoadPtr, Alignment,
1189 "unmaskedload");
Sanjay Patelb695c552016-02-01 17:00:10 +00001190 }
1191
1192 return nullptr;
1193}
1194
Philip Reames484d07c2019-03-20 03:36:05 +00001195// TODO, Obvious Missing Transforms:
1196// * SimplifyDemandedVectorElts
1197// * Single constant active lane -> store
1198// * Narrow width by halfs excluding zero/undef lanes
Sanjay Patel04f792b2016-02-01 19:39:52 +00001199static Instruction *simplifyMaskedStore(IntrinsicInst &II, InstCombiner &IC) {
1200 auto *ConstMask = dyn_cast<Constant>(II.getArgOperand(3));
1201 if (!ConstMask)
1202 return nullptr;
1203
1204 // If the mask is all zeros, this instruction does nothing.
1205 if (ConstMask->isNullValue())
Sanjay Patel4b198802016-02-01 22:23:39 +00001206 return IC.eraseInstFromFunction(II);
Sanjay Patel04f792b2016-02-01 19:39:52 +00001207
1208 // If the mask is all ones, this is a plain vector store of the 1st argument.
1209 if (ConstMask->isAllOnesValue()) {
1210 Value *StorePtr = II.getArgOperand(1);
1211 unsigned Alignment = cast<ConstantInt>(II.getArgOperand(2))->getZExtValue();
1212 return new StoreInst(II.getArgOperand(0), StorePtr, false, Alignment);
1213 }
1214
1215 return nullptr;
1216}
1217
Philip Reames484d07c2019-03-20 03:36:05 +00001218// TODO, Obvious Missing Transforms:
1219// * Single constant active lane load -> load
1220// * Dereferenceable address & few lanes -> scalarize speculative load/selects
1221// * Adjacent vector addresses -> masked.load
1222// * Narrow width by halfs excluding zero/undef lanes
Sanjay Patel103ab7d2016-02-01 22:10:26 +00001223static Instruction *simplifyMaskedGather(IntrinsicInst &II, InstCombiner &IC) {
1224 // If the mask is all zeros, return the "passthru" argument of the gather.
1225 auto *ConstMask = dyn_cast<Constant>(II.getArgOperand(2));
1226 if (ConstMask && ConstMask->isNullValue())
Sanjay Patel4b198802016-02-01 22:23:39 +00001227 return IC.replaceInstUsesWith(II, II.getArgOperand(3));
Sanjay Patel103ab7d2016-02-01 22:10:26 +00001228
1229 return nullptr;
1230}
1231
Piotr Padlewskic63b4922018-07-12 23:55:20 +00001232/// This function transforms launder.invariant.group and strip.invariant.group
1233/// like:
1234/// launder(launder(%x)) -> launder(%x) (the result is not the argument)
1235/// launder(strip(%x)) -> launder(%x)
1236/// strip(strip(%x)) -> strip(%x) (the result is not the argument)
1237/// strip(launder(%x)) -> strip(%x)
1238/// This is legal because it preserves the most recent information about
1239/// the presence or absence of invariant.group.
1240static Instruction *simplifyInvariantGroupIntrinsic(IntrinsicInst &II,
1241 InstCombiner &IC) {
1242 auto *Arg = II.getArgOperand(0);
1243 auto *StrippedArg = Arg->stripPointerCasts();
1244 auto *StrippedInvariantGroupsArg = Arg->stripPointerCastsAndInvariantGroups();
1245 if (StrippedArg == StrippedInvariantGroupsArg)
1246 return nullptr; // No launders/strips to remove.
1247
1248 Value *Result = nullptr;
1249
1250 if (II.getIntrinsicID() == Intrinsic::launder_invariant_group)
1251 Result = IC.Builder.CreateLaunderInvariantGroup(StrippedInvariantGroupsArg);
1252 else if (II.getIntrinsicID() == Intrinsic::strip_invariant_group)
1253 Result = IC.Builder.CreateStripInvariantGroup(StrippedInvariantGroupsArg);
1254 else
1255 llvm_unreachable(
1256 "simplifyInvariantGroupIntrinsic only handles launder and strip");
1257 if (Result->getType()->getPointerAddressSpace() !=
1258 II.getType()->getPointerAddressSpace())
1259 Result = IC.Builder.CreateAddrSpaceCast(Result, II.getType());
1260 if (Result->getType() != II.getType())
1261 Result = IC.Builder.CreateBitCast(Result, II.getType());
1262
1263 return cast<Instruction>(Result);
1264}
1265
Philip Reames484d07c2019-03-20 03:36:05 +00001266// TODO, Obvious Missing Transforms:
1267// * SimplifyDemandedVectorElts
1268// * Single constant active lane -> store
1269// * Adjacent vector addresses -> masked.store
1270// * Narrow store width by halfs excluding zero/undef lanes
Sanjay Patel103ab7d2016-02-01 22:10:26 +00001271static Instruction *simplifyMaskedScatter(IntrinsicInst &II, InstCombiner &IC) {
1272 // If the mask is all zeros, a scatter does nothing.
1273 auto *ConstMask = dyn_cast<Constant>(II.getArgOperand(3));
1274 if (ConstMask && ConstMask->isNullValue())
Sanjay Patel4b198802016-02-01 22:23:39 +00001275 return IC.eraseInstFromFunction(II);
Sanjay Patel103ab7d2016-02-01 22:10:26 +00001276
1277 return nullptr;
1278}
1279
Amaury Sechet763c59d2016-08-18 20:43:50 +00001280static Instruction *foldCttzCtlz(IntrinsicInst &II, InstCombiner &IC) {
1281 assert((II.getIntrinsicID() == Intrinsic::cttz ||
1282 II.getIntrinsicID() == Intrinsic::ctlz) &&
1283 "Expected cttz or ctlz intrinsic");
Sanjay Patel8e3ab172016-08-05 22:42:46 +00001284 Value *Op0 = II.getArgOperand(0);
Sanjay Patel8e3ab172016-08-05 22:42:46 +00001285
Craig Topper8205a1a2017-05-24 16:53:07 +00001286 KnownBits Known = IC.computeKnownBits(Op0, 0, &II);
Sanjay Patel8e3ab172016-08-05 22:42:46 +00001287
1288 // Create a mask for bits above (ctlz) or below (cttz) the first known one.
1289 bool IsTZ = II.getIntrinsicID() == Intrinsic::cttz;
Craig Topper8df66c62017-05-12 17:20:30 +00001290 unsigned PossibleZeros = IsTZ ? Known.countMaxTrailingZeros()
1291 : Known.countMaxLeadingZeros();
1292 unsigned DefiniteZeros = IsTZ ? Known.countMinTrailingZeros()
1293 : Known.countMinLeadingZeros();
Sanjay Patel8e3ab172016-08-05 22:42:46 +00001294
1295 // If all bits above (ctlz) or below (cttz) the first known one are known
1296 // zero, this value is constant.
1297 // FIXME: This should be in InstSimplify because we're replacing an
1298 // instruction with a constant.
Craig Topper9474e9b2017-04-27 04:51:25 +00001299 if (PossibleZeros == DefiniteZeros) {
Craig Topper0799ff92017-06-03 18:50:32 +00001300 auto *C = ConstantInt::get(Op0->getType(), DefiniteZeros);
Amaury Sechet763c59d2016-08-18 20:43:50 +00001301 return IC.replaceInstUsesWith(II, C);
1302 }
1303
1304 // If the input to cttz/ctlz is known to be non-zero,
1305 // then change the 'ZeroIsUndef' parameter to 'true'
1306 // because we know the zero behavior can't affect the result.
Craig Topper73ba1c82017-06-07 07:40:37 +00001307 if (!Known.One.isNullValue() ||
Craig Topperd45185f2017-05-26 18:23:57 +00001308 isKnownNonZero(Op0, IC.getDataLayout(), 0, &IC.getAssumptionCache(), &II,
1309 &IC.getDominatorTree())) {
Amaury Sechet763c59d2016-08-18 20:43:50 +00001310 if (!match(II.getArgOperand(1), m_One())) {
Craig Topperbb4069e2017-07-07 23:16:26 +00001311 II.setOperand(1, IC.Builder.getTrue());
Amaury Sechet763c59d2016-08-18 20:43:50 +00001312 return &II;
1313 }
1314 }
Sanjay Patel8e3ab172016-08-05 22:42:46 +00001315
Craig Topper5b173f22017-06-21 16:32:35 +00001316 // Add range metadata since known bits can't completely reflect what we know.
1317 // TODO: Handle splat vectors.
1318 auto *IT = dyn_cast<IntegerType>(Op0->getType());
1319 if (IT && IT->getBitWidth() != 1 && !II.getMetadata(LLVMContext::MD_range)) {
1320 Metadata *LowAndHigh[] = {
1321 ConstantAsMetadata::get(ConstantInt::get(IT, DefiniteZeros)),
1322 ConstantAsMetadata::get(ConstantInt::get(IT, PossibleZeros + 1))};
1323 II.setMetadata(LLVMContext::MD_range,
1324 MDNode::get(II.getContext(), LowAndHigh));
1325 return &II;
1326 }
1327
1328 return nullptr;
1329}
1330
1331static Instruction *foldCtpop(IntrinsicInst &II, InstCombiner &IC) {
1332 assert(II.getIntrinsicID() == Intrinsic::ctpop &&
1333 "Expected ctpop intrinsic");
1334 Value *Op0 = II.getArgOperand(0);
1335 // FIXME: Try to simplify vectors of integers.
1336 auto *IT = dyn_cast<IntegerType>(Op0->getType());
1337 if (!IT)
1338 return nullptr;
1339
1340 unsigned BitWidth = IT->getBitWidth();
1341 KnownBits Known(BitWidth);
1342 IC.computeKnownBits(Op0, Known, 0, &II);
1343
1344 unsigned MinCount = Known.countMinPopulation();
1345 unsigned MaxCount = Known.countMaxPopulation();
1346
1347 // Add range metadata since known bits can't completely reflect what we know.
1348 if (IT->getBitWidth() != 1 && !II.getMetadata(LLVMContext::MD_range)) {
1349 Metadata *LowAndHigh[] = {
1350 ConstantAsMetadata::get(ConstantInt::get(IT, MinCount)),
1351 ConstantAsMetadata::get(ConstantInt::get(IT, MaxCount + 1))};
1352 II.setMetadata(LLVMContext::MD_range,
1353 MDNode::get(II.getContext(), LowAndHigh));
1354 return &II;
1355 }
1356
Sanjay Patel8e3ab172016-08-05 22:42:46 +00001357 return nullptr;
1358}
1359
Sanjay Patel1ace9932016-02-26 21:04:14 +00001360// TODO: If the x86 backend knew how to convert a bool vector mask back to an
1361// XMM register mask efficiently, we could transform all x86 masked intrinsics
1362// to LLVM masked intrinsics and remove the x86 masked intrinsic defs.
Sanjay Patel98a71502016-02-29 23:16:48 +00001363static Instruction *simplifyX86MaskedLoad(IntrinsicInst &II, InstCombiner &IC) {
1364 Value *Ptr = II.getOperand(0);
1365 Value *Mask = II.getOperand(1);
Sanjay Patel5e5056d2016-04-12 23:16:23 +00001366 Constant *ZeroVec = Constant::getNullValue(II.getType());
Sanjay Patel98a71502016-02-29 23:16:48 +00001367
1368 // Special case a zero mask since that's not a ConstantDataVector.
Sanjay Patel5e5056d2016-04-12 23:16:23 +00001369 // This masked load instruction creates a zero vector.
Sanjay Patel98a71502016-02-29 23:16:48 +00001370 if (isa<ConstantAggregateZero>(Mask))
Sanjay Patel5e5056d2016-04-12 23:16:23 +00001371 return IC.replaceInstUsesWith(II, ZeroVec);
Sanjay Patel98a71502016-02-29 23:16:48 +00001372
1373 auto *ConstMask = dyn_cast<ConstantDataVector>(Mask);
1374 if (!ConstMask)
1375 return nullptr;
1376
1377 // The mask is constant. Convert this x86 intrinsic to the LLVM instrinsic
1378 // to allow target-independent optimizations.
1379
1380 // First, cast the x86 intrinsic scalar pointer to a vector pointer to match
1381 // the LLVM intrinsic definition for the pointer argument.
1382 unsigned AddrSpace = cast<PointerType>(Ptr->getType())->getAddressSpace();
1383 PointerType *VecPtrTy = PointerType::get(II.getType(), AddrSpace);
Craig Topperbb4069e2017-07-07 23:16:26 +00001384 Value *PtrCast = IC.Builder.CreateBitCast(Ptr, VecPtrTy, "castvec");
Sanjay Patel98a71502016-02-29 23:16:48 +00001385
1386 // Second, convert the x86 XMM integer vector mask to a vector of bools based
1387 // on each element's most significant bit (the sign bit).
1388 Constant *BoolMask = getNegativeIsTrueBoolVec(ConstMask);
1389
Sanjay Patel5e5056d2016-04-12 23:16:23 +00001390 // The pass-through vector for an x86 masked load is a zero vector.
1391 CallInst *NewMaskedLoad =
Craig Topperbb4069e2017-07-07 23:16:26 +00001392 IC.Builder.CreateMaskedLoad(PtrCast, 1, BoolMask, ZeroVec);
Sanjay Patel98a71502016-02-29 23:16:48 +00001393 return IC.replaceInstUsesWith(II, NewMaskedLoad);
1394}
1395
1396// TODO: If the x86 backend knew how to convert a bool vector mask back to an
1397// XMM register mask efficiently, we could transform all x86 masked intrinsics
1398// to LLVM masked intrinsics and remove the x86 masked intrinsic defs.
Sanjay Patel1ace9932016-02-26 21:04:14 +00001399static bool simplifyX86MaskedStore(IntrinsicInst &II, InstCombiner &IC) {
1400 Value *Ptr = II.getOperand(0);
1401 Value *Mask = II.getOperand(1);
1402 Value *Vec = II.getOperand(2);
1403
1404 // Special case a zero mask since that's not a ConstantDataVector:
1405 // this masked store instruction does nothing.
1406 if (isa<ConstantAggregateZero>(Mask)) {
1407 IC.eraseInstFromFunction(II);
1408 return true;
1409 }
1410
Sanjay Patelc4acbae2016-03-12 15:16:59 +00001411 // The SSE2 version is too weird (eg, unaligned but non-temporal) to do
1412 // anything else at this level.
1413 if (II.getIntrinsicID() == Intrinsic::x86_sse2_maskmov_dqu)
1414 return false;
1415
Sanjay Patel1ace9932016-02-26 21:04:14 +00001416 auto *ConstMask = dyn_cast<ConstantDataVector>(Mask);
1417 if (!ConstMask)
1418 return false;
1419
1420 // The mask is constant. Convert this x86 intrinsic to the LLVM instrinsic
1421 // to allow target-independent optimizations.
1422
1423 // First, cast the x86 intrinsic scalar pointer to a vector pointer to match
1424 // the LLVM intrinsic definition for the pointer argument.
1425 unsigned AddrSpace = cast<PointerType>(Ptr->getType())->getAddressSpace();
1426 PointerType *VecPtrTy = PointerType::get(Vec->getType(), AddrSpace);
Craig Topperbb4069e2017-07-07 23:16:26 +00001427 Value *PtrCast = IC.Builder.CreateBitCast(Ptr, VecPtrTy, "castvec");
Sanjay Patel1ace9932016-02-26 21:04:14 +00001428
1429 // Second, convert the x86 XMM integer vector mask to a vector of bools based
1430 // on each element's most significant bit (the sign bit).
1431 Constant *BoolMask = getNegativeIsTrueBoolVec(ConstMask);
1432
Craig Topperbb4069e2017-07-07 23:16:26 +00001433 IC.Builder.CreateMaskedStore(Vec, PtrCast, 1, BoolMask);
Sanjay Patel1ace9932016-02-26 21:04:14 +00001434
1435 // 'Replace uses' doesn't work for stores. Erase the original masked store.
1436 IC.eraseInstFromFunction(II);
1437 return true;
1438}
1439
Matt Arsenaultcdb468c2017-02-27 23:08:49 +00001440// Constant fold llvm.amdgcn.fmed3 intrinsics for standard inputs.
1441//
1442// A single NaN input is folded to minnum, so we rely on that folding for
1443// handling NaNs.
1444static APFloat fmed3AMDGCN(const APFloat &Src0, const APFloat &Src1,
1445 const APFloat &Src2) {
1446 APFloat Max3 = maxnum(maxnum(Src0, Src1), Src2);
1447
1448 APFloat::cmpResult Cmp0 = Max3.compare(Src0);
1449 assert(Cmp0 != APFloat::cmpUnordered && "nans handled separately");
1450 if (Cmp0 == APFloat::cmpEqual)
1451 return maxnum(Src1, Src2);
1452
1453 APFloat::cmpResult Cmp1 = Max3.compare(Src1);
1454 assert(Cmp1 != APFloat::cmpUnordered && "nans handled separately");
1455 if (Cmp1 == APFloat::cmpEqual)
1456 return maxnum(Src0, Src2);
1457
1458 return maxnum(Src0, Src1);
1459}
1460
Alexandros Lamprineas52457d32018-05-30 14:38:50 +00001461/// Convert a table lookup to shufflevector if the mask is constant.
1462/// This could benefit tbl1 if the mask is { 7,6,5,4,3,2,1,0 }, in
1463/// which case we could lower the shufflevector with rev64 instructions
1464/// as it's actually a byte reverse.
1465static Value *simplifyNeonTbl1(const IntrinsicInst &II,
1466 InstCombiner::BuilderTy &Builder) {
1467 // Bail out if the mask is not a constant.
1468 auto *C = dyn_cast<Constant>(II.getArgOperand(1));
1469 if (!C)
1470 return nullptr;
1471
1472 auto *VecTy = cast<VectorType>(II.getType());
1473 unsigned NumElts = VecTy->getNumElements();
1474
1475 // Only perform this transformation for <8 x i8> vector types.
1476 if (!VecTy->getElementType()->isIntegerTy(8) || NumElts != 8)
1477 return nullptr;
1478
1479 uint32_t Indexes[8];
1480
1481 for (unsigned I = 0; I < NumElts; ++I) {
1482 Constant *COp = C->getAggregateElement(I);
1483
1484 if (!COp || !isa<ConstantInt>(COp))
1485 return nullptr;
1486
1487 Indexes[I] = cast<ConstantInt>(COp)->getLimitedValue();
1488
1489 // Make sure the mask indices are in range.
1490 if (Indexes[I] >= NumElts)
1491 return nullptr;
1492 }
1493
1494 auto *ShuffleMask = ConstantDataVector::get(II.getContext(),
1495 makeArrayRef(Indexes));
1496 auto *V1 = II.getArgOperand(0);
1497 auto *V2 = Constant::getNullValue(V1->getType());
1498 return Builder.CreateShuffleVector(V1, V2, ShuffleMask);
1499}
1500
Alexandros Lamprineas61f0ba12018-05-31 12:19:18 +00001501/// Convert a vector load intrinsic into a simple llvm load instruction.
1502/// This is beneficial when the underlying object being addressed comes
1503/// from a constant, since we get constant-folding for free.
1504static Value *simplifyNeonVld1(const IntrinsicInst &II,
1505 unsigned MemAlign,
1506 InstCombiner::BuilderTy &Builder) {
1507 auto *IntrAlign = dyn_cast<ConstantInt>(II.getArgOperand(1));
1508
1509 if (!IntrAlign)
1510 return nullptr;
1511
1512 unsigned Alignment = IntrAlign->getLimitedValue() < MemAlign ?
1513 MemAlign : IntrAlign->getLimitedValue();
1514
1515 if (!isPowerOf2_32(Alignment))
1516 return nullptr;
1517
1518 auto *BCastInst = Builder.CreateBitCast(II.getArgOperand(0),
1519 PointerType::get(II.getType(), 0));
James Y Knight14359ef2019-02-01 20:44:24 +00001520 return Builder.CreateAlignedLoad(II.getType(), BCastInst, Alignment);
Alexandros Lamprineas61f0ba12018-05-31 12:19:18 +00001521}
1522
Arnaud A. de Grandmaison333ef382016-05-10 09:24:49 +00001523// Returns true iff the 2 intrinsics have the same operands, limiting the
1524// comparison to the first NumOperands.
1525static bool haveSameOperands(const IntrinsicInst &I, const IntrinsicInst &E,
1526 unsigned NumOperands) {
1527 assert(I.getNumArgOperands() >= NumOperands && "Not enough operands");
1528 assert(E.getNumArgOperands() >= NumOperands && "Not enough operands");
1529 for (unsigned i = 0; i < NumOperands; i++)
1530 if (I.getArgOperand(i) != E.getArgOperand(i))
1531 return false;
1532 return true;
1533}
1534
1535// Remove trivially empty start/end intrinsic ranges, i.e. a start
1536// immediately followed by an end (ignoring debuginfo or other
1537// start/end intrinsics in between). As this handles only the most trivial
1538// cases, tracking the nesting level is not needed:
1539//
1540// call @llvm.foo.start(i1 0) ; &I
1541// call @llvm.foo.start(i1 0)
1542// call @llvm.foo.end(i1 0) ; This one will not be skipped: it will be removed
1543// call @llvm.foo.end(i1 0)
1544static bool removeTriviallyEmptyRange(IntrinsicInst &I, unsigned StartID,
1545 unsigned EndID, InstCombiner &IC) {
1546 assert(I.getIntrinsicID() == StartID &&
1547 "Start intrinsic does not have expected ID");
1548 BasicBlock::iterator BI(I), BE(I.getParent()->end());
1549 for (++BI; BI != BE; ++BI) {
1550 if (auto *E = dyn_cast<IntrinsicInst>(BI)) {
1551 if (isa<DbgInfoIntrinsic>(E) || E->getIntrinsicID() == StartID)
1552 continue;
1553 if (E->getIntrinsicID() == EndID &&
1554 haveSameOperands(I, *E, E->getNumArgOperands())) {
1555 IC.eraseInstFromFunction(*E);
1556 IC.eraseInstFromFunction(I);
1557 return true;
1558 }
1559 }
1560 break;
1561 }
1562
1563 return false;
1564}
1565
Justin Lebar698c31b2017-01-27 00:58:58 +00001566// Convert NVVM intrinsics to target-generic LLVM code where possible.
1567static Instruction *SimplifyNVVMIntrinsic(IntrinsicInst *II, InstCombiner &IC) {
1568 // Each NVVM intrinsic we can simplify can be replaced with one of:
1569 //
1570 // * an LLVM intrinsic,
1571 // * an LLVM cast operation,
1572 // * an LLVM binary operation, or
1573 // * ad-hoc LLVM IR for the particular operation.
1574
1575 // Some transformations are only valid when the module's
1576 // flush-denormals-to-zero (ftz) setting is true/false, whereas other
1577 // transformations are valid regardless of the module's ftz setting.
1578 enum FtzRequirementTy {
1579 FTZ_Any, // Any ftz setting is ok.
1580 FTZ_MustBeOn, // Transformation is valid only if ftz is on.
1581 FTZ_MustBeOff, // Transformation is valid only if ftz is off.
1582 };
1583 // Classes of NVVM intrinsics that can't be replaced one-to-one with a
1584 // target-generic intrinsic, cast op, or binary op but that we can nonetheless
1585 // simplify.
1586 enum SpecialCase {
1587 SPC_Reciprocal,
1588 };
1589
1590 // SimplifyAction is a poor-man's variant (plus an additional flag) that
1591 // represents how to replace an NVVM intrinsic with target-generic LLVM IR.
1592 struct SimplifyAction {
1593 // Invariant: At most one of these Optionals has a value.
1594 Optional<Intrinsic::ID> IID;
1595 Optional<Instruction::CastOps> CastOp;
1596 Optional<Instruction::BinaryOps> BinaryOp;
1597 Optional<SpecialCase> Special;
1598
1599 FtzRequirementTy FtzRequirement = FTZ_Any;
1600
1601 SimplifyAction() = default;
1602
1603 SimplifyAction(Intrinsic::ID IID, FtzRequirementTy FtzReq)
1604 : IID(IID), FtzRequirement(FtzReq) {}
1605
1606 // Cast operations don't have anything to do with FTZ, so we skip that
1607 // argument.
1608 SimplifyAction(Instruction::CastOps CastOp) : CastOp(CastOp) {}
1609
1610 SimplifyAction(Instruction::BinaryOps BinaryOp, FtzRequirementTy FtzReq)
1611 : BinaryOp(BinaryOp), FtzRequirement(FtzReq) {}
1612
1613 SimplifyAction(SpecialCase Special, FtzRequirementTy FtzReq)
1614 : Special(Special), FtzRequirement(FtzReq) {}
1615 };
1616
1617 // Try to generate a SimplifyAction describing how to replace our
1618 // IntrinsicInstr with target-generic LLVM IR.
1619 const SimplifyAction Action = [II]() -> SimplifyAction {
1620 switch (II->getIntrinsicID()) {
Justin Lebar698c31b2017-01-27 00:58:58 +00001621 // NVVM intrinsics that map directly to LLVM intrinsics.
1622 case Intrinsic::nvvm_ceil_d:
1623 return {Intrinsic::ceil, FTZ_Any};
1624 case Intrinsic::nvvm_ceil_f:
1625 return {Intrinsic::ceil, FTZ_MustBeOff};
1626 case Intrinsic::nvvm_ceil_ftz_f:
1627 return {Intrinsic::ceil, FTZ_MustBeOn};
1628 case Intrinsic::nvvm_fabs_d:
1629 return {Intrinsic::fabs, FTZ_Any};
1630 case Intrinsic::nvvm_fabs_f:
1631 return {Intrinsic::fabs, FTZ_MustBeOff};
1632 case Intrinsic::nvvm_fabs_ftz_f:
1633 return {Intrinsic::fabs, FTZ_MustBeOn};
1634 case Intrinsic::nvvm_floor_d:
1635 return {Intrinsic::floor, FTZ_Any};
1636 case Intrinsic::nvvm_floor_f:
1637 return {Intrinsic::floor, FTZ_MustBeOff};
1638 case Intrinsic::nvvm_floor_ftz_f:
1639 return {Intrinsic::floor, FTZ_MustBeOn};
1640 case Intrinsic::nvvm_fma_rn_d:
1641 return {Intrinsic::fma, FTZ_Any};
1642 case Intrinsic::nvvm_fma_rn_f:
1643 return {Intrinsic::fma, FTZ_MustBeOff};
1644 case Intrinsic::nvvm_fma_rn_ftz_f:
1645 return {Intrinsic::fma, FTZ_MustBeOn};
1646 case Intrinsic::nvvm_fmax_d:
1647 return {Intrinsic::maxnum, FTZ_Any};
1648 case Intrinsic::nvvm_fmax_f:
1649 return {Intrinsic::maxnum, FTZ_MustBeOff};
1650 case Intrinsic::nvvm_fmax_ftz_f:
1651 return {Intrinsic::maxnum, FTZ_MustBeOn};
1652 case Intrinsic::nvvm_fmin_d:
1653 return {Intrinsic::minnum, FTZ_Any};
1654 case Intrinsic::nvvm_fmin_f:
1655 return {Intrinsic::minnum, FTZ_MustBeOff};
1656 case Intrinsic::nvvm_fmin_ftz_f:
1657 return {Intrinsic::minnum, FTZ_MustBeOn};
1658 case Intrinsic::nvvm_round_d:
1659 return {Intrinsic::round, FTZ_Any};
1660 case Intrinsic::nvvm_round_f:
1661 return {Intrinsic::round, FTZ_MustBeOff};
1662 case Intrinsic::nvvm_round_ftz_f:
1663 return {Intrinsic::round, FTZ_MustBeOn};
1664 case Intrinsic::nvvm_sqrt_rn_d:
1665 return {Intrinsic::sqrt, FTZ_Any};
1666 case Intrinsic::nvvm_sqrt_f:
1667 // nvvm_sqrt_f is a special case. For most intrinsics, foo_ftz_f is the
1668 // ftz version, and foo_f is the non-ftz version. But nvvm_sqrt_f adopts
1669 // the ftz-ness of the surrounding code. sqrt_rn_f and sqrt_rn_ftz_f are
1670 // the versions with explicit ftz-ness.
1671 return {Intrinsic::sqrt, FTZ_Any};
1672 case Intrinsic::nvvm_sqrt_rn_f:
1673 return {Intrinsic::sqrt, FTZ_MustBeOff};
1674 case Intrinsic::nvvm_sqrt_rn_ftz_f:
1675 return {Intrinsic::sqrt, FTZ_MustBeOn};
1676 case Intrinsic::nvvm_trunc_d:
1677 return {Intrinsic::trunc, FTZ_Any};
1678 case Intrinsic::nvvm_trunc_f:
1679 return {Intrinsic::trunc, FTZ_MustBeOff};
1680 case Intrinsic::nvvm_trunc_ftz_f:
1681 return {Intrinsic::trunc, FTZ_MustBeOn};
1682
1683 // NVVM intrinsics that map to LLVM cast operations.
1684 //
1685 // Note that llvm's target-generic conversion operators correspond to the rz
1686 // (round to zero) versions of the nvvm conversion intrinsics, even though
1687 // most everything else here uses the rn (round to nearest even) nvvm ops.
1688 case Intrinsic::nvvm_d2i_rz:
1689 case Intrinsic::nvvm_f2i_rz:
1690 case Intrinsic::nvvm_d2ll_rz:
1691 case Intrinsic::nvvm_f2ll_rz:
1692 return {Instruction::FPToSI};
1693 case Intrinsic::nvvm_d2ui_rz:
1694 case Intrinsic::nvvm_f2ui_rz:
1695 case Intrinsic::nvvm_d2ull_rz:
1696 case Intrinsic::nvvm_f2ull_rz:
1697 return {Instruction::FPToUI};
1698 case Intrinsic::nvvm_i2d_rz:
1699 case Intrinsic::nvvm_i2f_rz:
1700 case Intrinsic::nvvm_ll2d_rz:
1701 case Intrinsic::nvvm_ll2f_rz:
1702 return {Instruction::SIToFP};
1703 case Intrinsic::nvvm_ui2d_rz:
1704 case Intrinsic::nvvm_ui2f_rz:
1705 case Intrinsic::nvvm_ull2d_rz:
1706 case Intrinsic::nvvm_ull2f_rz:
1707 return {Instruction::UIToFP};
1708
1709 // NVVM intrinsics that map to LLVM binary ops.
1710 case Intrinsic::nvvm_add_rn_d:
1711 return {Instruction::FAdd, FTZ_Any};
1712 case Intrinsic::nvvm_add_rn_f:
1713 return {Instruction::FAdd, FTZ_MustBeOff};
1714 case Intrinsic::nvvm_add_rn_ftz_f:
1715 return {Instruction::FAdd, FTZ_MustBeOn};
1716 case Intrinsic::nvvm_mul_rn_d:
1717 return {Instruction::FMul, FTZ_Any};
1718 case Intrinsic::nvvm_mul_rn_f:
1719 return {Instruction::FMul, FTZ_MustBeOff};
1720 case Intrinsic::nvvm_mul_rn_ftz_f:
1721 return {Instruction::FMul, FTZ_MustBeOn};
1722 case Intrinsic::nvvm_div_rn_d:
1723 return {Instruction::FDiv, FTZ_Any};
1724 case Intrinsic::nvvm_div_rn_f:
1725 return {Instruction::FDiv, FTZ_MustBeOff};
1726 case Intrinsic::nvvm_div_rn_ftz_f:
1727 return {Instruction::FDiv, FTZ_MustBeOn};
1728
1729 // The remainder of cases are NVVM intrinsics that map to LLVM idioms, but
1730 // need special handling.
1731 //
Hiroshi Inoue0ca79dc2017-07-11 06:04:59 +00001732 // We seem to be missing intrinsics for rcp.approx.{ftz.}f32, which is just
Justin Lebar698c31b2017-01-27 00:58:58 +00001733 // as well.
1734 case Intrinsic::nvvm_rcp_rn_d:
1735 return {SPC_Reciprocal, FTZ_Any};
1736 case Intrinsic::nvvm_rcp_rn_f:
1737 return {SPC_Reciprocal, FTZ_MustBeOff};
1738 case Intrinsic::nvvm_rcp_rn_ftz_f:
1739 return {SPC_Reciprocal, FTZ_MustBeOn};
1740
1741 // We do not currently simplify intrinsics that give an approximate answer.
1742 // These include:
1743 //
1744 // - nvvm_cos_approx_{f,ftz_f}
1745 // - nvvm_ex2_approx_{d,f,ftz_f}
1746 // - nvvm_lg2_approx_{d,f,ftz_f}
1747 // - nvvm_sin_approx_{f,ftz_f}
1748 // - nvvm_sqrt_approx_{f,ftz_f}
1749 // - nvvm_rsqrt_approx_{d,f,ftz_f}
1750 // - nvvm_div_approx_{ftz_d,ftz_f,f}
1751 // - nvvm_rcp_approx_ftz_d
1752 //
1753 // Ideally we'd encode them as e.g. "fast call @llvm.cos", where "fast"
1754 // means that fastmath is enabled in the intrinsic. Unfortunately only
1755 // binary operators (currently) have a fastmath bit in SelectionDAG, so this
1756 // information gets lost and we can't select on it.
1757 //
1758 // TODO: div and rcp are lowered to a binary op, so these we could in theory
1759 // lower them to "fast fdiv".
1760
1761 default:
1762 return {};
1763 }
1764 }();
1765
1766 // If Action.FtzRequirementTy is not satisfied by the module's ftz state, we
1767 // can bail out now. (Notice that in the case that IID is not an NVVM
1768 // intrinsic, we don't have to look up any module metadata, as
1769 // FtzRequirementTy will be FTZ_Any.)
1770 if (Action.FtzRequirement != FTZ_Any) {
1771 bool FtzEnabled =
1772 II->getFunction()->getFnAttribute("nvptx-f32ftz").getValueAsString() ==
1773 "true";
1774
1775 if (FtzEnabled != (Action.FtzRequirement == FTZ_MustBeOn))
1776 return nullptr;
1777 }
1778
1779 // Simplify to target-generic intrinsic.
1780 if (Action.IID) {
1781 SmallVector<Value *, 4> Args(II->arg_operands());
1782 // All the target-generic intrinsics currently of interest to us have one
1783 // type argument, equal to that of the nvvm intrinsic's argument.
Justin Lebare3ac0fb2017-01-27 01:49:39 +00001784 Type *Tys[] = {II->getArgOperand(0)->getType()};
Justin Lebar698c31b2017-01-27 00:58:58 +00001785 return CallInst::Create(
1786 Intrinsic::getDeclaration(II->getModule(), *Action.IID, Tys), Args);
1787 }
1788
1789 // Simplify to target-generic binary op.
1790 if (Action.BinaryOp)
1791 return BinaryOperator::Create(*Action.BinaryOp, II->getArgOperand(0),
1792 II->getArgOperand(1), II->getName());
1793
1794 // Simplify to target-generic cast op.
1795 if (Action.CastOp)
1796 return CastInst::Create(*Action.CastOp, II->getArgOperand(0), II->getType(),
1797 II->getName());
1798
1799 // All that's left are the special cases.
1800 if (!Action.Special)
1801 return nullptr;
1802
1803 switch (*Action.Special) {
1804 case SPC_Reciprocal:
1805 // Simplify reciprocal.
1806 return BinaryOperator::Create(
1807 Instruction::FDiv, ConstantFP::get(II->getArgOperand(0)->getType(), 1),
1808 II->getArgOperand(0), II->getName());
1809 }
Justin Lebar25ebe2d2017-01-27 02:04:07 +00001810 llvm_unreachable("All SpecialCase enumerators should be handled in switch.");
Justin Lebar698c31b2017-01-27 00:58:58 +00001811}
1812
Arnaud A. de Grandmaison333ef382016-05-10 09:24:49 +00001813Instruction *InstCombiner::visitVAStartInst(VAStartInst &I) {
1814 removeTriviallyEmptyRange(I, Intrinsic::vastart, Intrinsic::vaend, *this);
1815 return nullptr;
1816}
1817
1818Instruction *InstCombiner::visitVACopyInst(VACopyInst &I) {
1819 removeTriviallyEmptyRange(I, Intrinsic::vacopy, Intrinsic::vaend, *this);
1820 return nullptr;
1821}
1822
Sanjay Patel790af912018-11-26 22:00:41 +00001823static Instruction *canonicalizeConstantArg0ToArg1(CallInst &Call) {
1824 assert(Call.getNumArgOperands() > 1 && "Need at least 2 args to swap");
1825 Value *Arg0 = Call.getArgOperand(0), *Arg1 = Call.getArgOperand(1);
1826 if (isa<Constant>(Arg0) && !isa<Constant>(Arg1)) {
1827 Call.setArgOperand(0, Arg1);
1828 Call.setArgOperand(1, Arg0);
1829 return &Call;
1830 }
1831 return nullptr;
1832}
1833
Nikita Popov884feb12019-03-06 18:30:00 +00001834Instruction *InstCombiner::foldIntrinsicWithOverflowCommon(IntrinsicInst *II) {
1835 OverflowCheckFlavor OCF =
1836 IntrinsicIDToOverflowCheckFlavor(II->getIntrinsicID());
1837 assert(OCF != OCF_INVALID && "unexpected!");
1838
1839 Value *OperationResult = nullptr;
1840 Constant *OverflowResult = nullptr;
1841 if (OptimizeOverflowCheck(OCF, II->getArgOperand(0), II->getArgOperand(1),
1842 *II, OperationResult, OverflowResult))
1843 return CreateOverflowTuple(II, OperationResult, OverflowResult);
1844 return nullptr;
1845}
1846
Sanjay Patelcd4377c2016-01-20 22:24:38 +00001847/// CallInst simplification. This mostly only handles folding of intrinsic
Craig Topperc1892ec2019-01-31 17:23:29 +00001848/// instructions. For normal calls, it allows visitCallBase to do the heavy
Sanjay Patelcd4377c2016-01-20 22:24:38 +00001849/// lifting.
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001850Instruction *InstCombiner::visitCallInst(CallInst &CI) {
Philip Reames7a6db4f2017-12-27 00:16:12 +00001851 if (Value *V = SimplifyCall(&CI, SQ.getWithInstruction(&CI)))
Sanjay Patel4b198802016-02-01 22:23:39 +00001852 return replaceInstUsesWith(CI, V);
David Majnemer15032582015-05-22 03:56:46 +00001853
Justin Bogner99798402016-08-05 01:06:44 +00001854 if (isFreeCall(&CI, &TLI))
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001855 return visitFree(CI);
1856
1857 // If the caller function is nounwind, mark the call as nounwind, even if the
1858 // callee isn't.
Sanjay Patel5a470952016-08-11 15:16:06 +00001859 if (CI.getFunction()->doesNotThrow() && !CI.doesNotThrow()) {
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001860 CI.setDoesNotThrow();
1861 return &CI;
1862 }
Jim Grosbach7815f562012-02-03 00:07:04 +00001863
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001864 IntrinsicInst *II = dyn_cast<IntrinsicInst>(&CI);
Craig Topperc1892ec2019-01-31 17:23:29 +00001865 if (!II) return visitCallBase(CI);
Gabor Greif589a0b92010-06-24 12:58:35 +00001866
Craig Topper784929d2019-02-08 20:48:56 +00001867 // Intrinsics cannot occur in an invoke or a callbr, so handle them here
1868 // instead of in visitCallBase.
Daniel Neilson8f30ec62018-05-11 14:30:02 +00001869 if (auto *MI = dyn_cast<AnyMemIntrinsic>(II)) {
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001870 bool Changed = false;
1871
1872 // memmove/cpy/set of zero bytes is a noop.
1873 if (Constant *NumBytes = dyn_cast<Constant>(MI->getLength())) {
Chris Lattnerc663a672010-10-01 05:51:02 +00001874 if (NumBytes->isNullValue())
Sanjay Patel4b198802016-02-01 22:23:39 +00001875 return eraseInstFromFunction(CI);
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001876
1877 if (ConstantInt *CI = dyn_cast<ConstantInt>(NumBytes))
1878 if (CI->getZExtValue() == 1) {
1879 // Replace the instruction with just byte operations. We would
1880 // transform other cases to loads/stores, but we don't know if
1881 // alignment is sufficient.
1882 }
1883 }
Jim Grosbach7815f562012-02-03 00:07:04 +00001884
Chris Lattnerc663a672010-10-01 05:51:02 +00001885 // No other transformations apply to volatile transfers.
Daniel Neilson8f30ec62018-05-11 14:30:02 +00001886 if (auto *M = dyn_cast<MemIntrinsic>(MI))
1887 if (M->isVolatile())
1888 return nullptr;
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001889
1890 // If we have a memmove and the source operation is a constant global,
1891 // then the source and dest pointers can't alias, so we can change this
1892 // into a call to memcpy.
Daniel Neilson8f30ec62018-05-11 14:30:02 +00001893 if (auto *MMI = dyn_cast<AnyMemMoveInst>(MI)) {
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001894 if (GlobalVariable *GVSrc = dyn_cast<GlobalVariable>(MMI->getSource()))
1895 if (GVSrc->isConstant()) {
Sanjay Patelaf674fb2015-12-14 17:24:23 +00001896 Module *M = CI.getModule();
Daniel Neilson8f30ec62018-05-11 14:30:02 +00001897 Intrinsic::ID MemCpyID =
1898 isa<AtomicMemMoveInst>(MMI)
1899 ? Intrinsic::memcpy_element_unordered_atomic
1900 : Intrinsic::memcpy;
Jay Foadb804a2b2011-07-12 14:06:48 +00001901 Type *Tys[3] = { CI.getArgOperand(0)->getType(),
1902 CI.getArgOperand(1)->getType(),
1903 CI.getArgOperand(2)->getType() };
Benjamin Kramere6e19332011-07-14 17:45:39 +00001904 CI.setCalledFunction(Intrinsic::getDeclaration(M, MemCpyID, Tys));
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001905 Changed = true;
1906 }
1907 }
1908
Daniel Neilson8f30ec62018-05-11 14:30:02 +00001909 if (AnyMemTransferInst *MTI = dyn_cast<AnyMemTransferInst>(MI)) {
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001910 // memmove(x,x,size) -> noop.
1911 if (MTI->getSource() == MTI->getDest())
Sanjay Patel4b198802016-02-01 22:23:39 +00001912 return eraseInstFromFunction(CI);
Eric Christopher7258dcd2010-04-16 23:37:20 +00001913 }
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001914
Eric Christopher7258dcd2010-04-16 23:37:20 +00001915 // If we can determine a pointer alignment that is bigger than currently
1916 // set, update the alignment.
Daniel Neilson8f30ec62018-05-11 14:30:02 +00001917 if (auto *MTI = dyn_cast<AnyMemTransferInst>(MI)) {
1918 if (Instruction *I = SimplifyAnyMemTransfer(MTI))
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001919 return I;
Daniel Neilsonf6651d42018-05-11 20:04:50 +00001920 } else if (auto *MSI = dyn_cast<AnyMemSetInst>(MI)) {
1921 if (Instruction *I = SimplifyAnyMemSet(MSI))
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001922 return I;
1923 }
Gabor Greif590d95e2010-06-24 13:42:49 +00001924
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001925 if (Changed) return II;
1926 }
Jim Grosbach7815f562012-02-03 00:07:04 +00001927
Philip Reames68a2e4d2019-03-15 19:54:06 +00001928 // For vector result intrinsics, use the generic demanded vector support.
Philip Reamesc71e9962019-01-30 19:21:11 +00001929 if (II->getType()->isVectorTy()) {
1930 auto VWidth = II->getType()->getVectorNumElements();
1931 APInt UndefElts(VWidth, 0);
1932 APInt AllOnesEltMask(APInt::getAllOnesValue(VWidth));
1933 if (Value *V = SimplifyDemandedVectorElts(II, AllOnesEltMask, UndefElts)) {
1934 if (V != II)
1935 return replaceInstUsesWith(*II, V);
1936 return II;
1937 }
1938 }
1939
Justin Lebar698c31b2017-01-27 00:58:58 +00001940 if (Instruction *I = SimplifyNVVMIntrinsic(II, *this))
1941 return I;
1942
Sanjay Patel1c600c62016-01-20 16:41:43 +00001943 auto SimplifyDemandedVectorEltsLow = [this](Value *Op, unsigned Width,
1944 unsigned DemandedWidth) {
Simon Pilgrim61116dd2015-09-17 20:32:45 +00001945 APInt UndefElts(Width, 0);
1946 APInt DemandedElts = APInt::getLowBitsSet(Width, DemandedWidth);
1947 return SimplifyDemandedVectorElts(Op, DemandedElts, UndefElts);
1948 };
1949
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001950 switch (II->getIntrinsicID()) {
1951 default: break;
George Burgess IV3f089142016-12-20 23:46:36 +00001952 case Intrinsic::objectsize:
Erik Pilkington600e9de2019-01-30 20:34:35 +00001953 if (Value *V = lowerObjectSizeCall(II, DL, &TLI, /*MustSucceed=*/false))
1954 return replaceInstUsesWith(CI, V);
Craig Topperf40110f2014-04-25 05:29:35 +00001955 return nullptr;
Michael Ilseman536cc322012-12-13 03:13:36 +00001956 case Intrinsic::bswap: {
1957 Value *IIOperand = II->getArgOperand(0);
Craig Topperf40110f2014-04-25 05:29:35 +00001958 Value *X = nullptr;
Michael Ilseman536cc322012-12-13 03:13:36 +00001959
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001960 // bswap(trunc(bswap(x))) -> trunc(lshr(x, c))
Michael Ilseman536cc322012-12-13 03:13:36 +00001961 if (match(IIOperand, m_Trunc(m_BSwap(m_Value(X))))) {
1962 unsigned C = X->getType()->getPrimitiveSizeInBits() -
1963 IIOperand->getType()->getPrimitiveSizeInBits();
1964 Value *CV = ConstantInt::get(X->getType(), C);
Craig Topperbb4069e2017-07-07 23:16:26 +00001965 Value *V = Builder.CreateLShr(X, CV);
Michael Ilseman536cc322012-12-13 03:13:36 +00001966 return new TruncInst(V, IIOperand->getType());
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001967 }
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001968 break;
Michael Ilseman536cc322012-12-13 03:13:36 +00001969 }
Sanjay Patelb695c552016-02-01 17:00:10 +00001970 case Intrinsic::masked_load:
Craig Topperbb4069e2017-07-07 23:16:26 +00001971 if (Value *SimplifiedMaskedOp = simplifyMaskedLoad(*II, Builder))
Sanjay Patel4b198802016-02-01 22:23:39 +00001972 return replaceInstUsesWith(CI, SimplifiedMaskedOp);
Sanjay Patelb695c552016-02-01 17:00:10 +00001973 break;
Sanjay Patel04f792b2016-02-01 19:39:52 +00001974 case Intrinsic::masked_store:
1975 return simplifyMaskedStore(*II, *this);
Sanjay Patel103ab7d2016-02-01 22:10:26 +00001976 case Intrinsic::masked_gather:
1977 return simplifyMaskedGather(*II, *this);
1978 case Intrinsic::masked_scatter:
1979 return simplifyMaskedScatter(*II, *this);
Piotr Padlewskic63b4922018-07-12 23:55:20 +00001980 case Intrinsic::launder_invariant_group:
1981 case Intrinsic::strip_invariant_group:
1982 if (auto *SkippedBarrier = simplifyInvariantGroupIntrinsic(*II, *this))
1983 return replaceInstUsesWith(*II, SkippedBarrier);
1984 break;
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001985 case Intrinsic::powi:
Gabor Greif589a0b92010-06-24 12:58:35 +00001986 if (ConstantInt *Power = dyn_cast<ConstantInt>(II->getArgOperand(1))) {
Philip Reames5000ba62017-12-27 01:14:30 +00001987 // 0 and 1 are handled in instsimplify
1988
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001989 // powi(x, -1) -> 1/x
Craig Topper79ab6432017-07-06 18:39:47 +00001990 if (Power->isMinusOne())
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001991 return BinaryOperator::CreateFDiv(ConstantFP::get(CI.getType(), 1.0),
Gabor Greif589a0b92010-06-24 12:58:35 +00001992 II->getArgOperand(0));
Philip Reamescd13a662017-12-27 01:30:12 +00001993 // powi(x, 2) -> x*x
1994 if (Power->equalsInt(2))
1995 return BinaryOperator::CreateFMul(II->getArgOperand(0),
1996 II->getArgOperand(0));
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001997 }
1998 break;
Jim Grosbach7815f562012-02-03 00:07:04 +00001999
Sanjay Patel8e3ab172016-08-05 22:42:46 +00002000 case Intrinsic::cttz:
2001 case Intrinsic::ctlz:
Amaury Sechet763c59d2016-08-18 20:43:50 +00002002 if (auto *I = foldCttzCtlz(*II, *this))
2003 return I;
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002004 break;
Sanjoy Dasb0984472015-04-08 04:27:22 +00002005
Craig Topper5b173f22017-06-21 16:32:35 +00002006 case Intrinsic::ctpop:
2007 if (auto *I = foldCtpop(*II, *this))
2008 return I;
2009 break;
2010
Sanjay Patela1395642018-11-13 23:27:23 +00002011 case Intrinsic::fshl:
2012 case Intrinsic::fshr: {
Sanjay Patelb3bcd952019-03-17 19:08:00 +00002013 Value *Op0 = II->getArgOperand(0), *Op1 = II->getArgOperand(1);
2014 Type *Ty = II->getType();
2015 unsigned BitWidth = Ty->getScalarSizeInBits();
Sanjay Patelde1d5d32019-03-14 19:22:08 +00002016 Constant *ShAmtC;
2017 if (match(II->getArgOperand(2), m_Constant(ShAmtC)) &&
2018 !isa<ConstantExpr>(ShAmtC) && !ShAmtC->containsConstantExpression()) {
Sanjay Patelb3bcd952019-03-17 19:08:00 +00002019 // Canonicalize a shift amount constant operand to modulo the bit-width.
2020 Constant *WidthC = ConstantInt::get(Ty, BitWidth);
Sanjay Patelde1d5d32019-03-14 19:22:08 +00002021 Constant *ModuloC = ConstantExpr::getURem(ShAmtC, WidthC);
2022 if (ModuloC != ShAmtC) {
2023 II->setArgOperand(2, ModuloC);
2024 return II;
2025 }
Sanjay Patel60633932019-03-18 14:27:51 +00002026 assert(ConstantExpr::getICmp(ICmpInst::ICMP_UGT, WidthC, ShAmtC) ==
2027 ConstantInt::getTrue(CmpInst::makeCmpResultType(Ty)) &&
2028 "Shift amount expected to be modulo bitwidth");
2029
Sanjay Patel84de8a32019-03-18 14:10:11 +00002030 // Canonicalize funnel shift right by constant to funnel shift left. This
2031 // is not entirely arbitrary. For historical reasons, the backend may
2032 // recognize rotate left patterns but miss rotate right patterns.
2033 if (II->getIntrinsicID() == Intrinsic::fshr) {
2034 // fshr X, Y, C --> fshl X, Y, (BitWidth - C)
Sanjay Patelb3bcd952019-03-17 19:08:00 +00002035 Constant *LeftShiftC = ConstantExpr::getSub(WidthC, ShAmtC);
2036 Module *Mod = II->getModule();
2037 Function *Fshl = Intrinsic::getDeclaration(Mod, Intrinsic::fshl, Ty);
Sanjay Patel84de8a32019-03-18 14:10:11 +00002038 return CallInst::Create(Fshl, { Op0, Op1, LeftShiftC });
Sanjay Patelb3bcd952019-03-17 19:08:00 +00002039 }
Sanjay Patel84de8a32019-03-18 14:10:11 +00002040 assert(II->getIntrinsicID() == Intrinsic::fshl &&
2041 "All funnel shifts by simple constants should go left");
Nikita Popov6e81d422018-11-23 22:45:08 +00002042
Sanjay Patel60633932019-03-18 14:27:51 +00002043 // fshl(X, 0, C) --> shl X, C
2044 // fshl(X, undef, C) --> shl X, C
2045 if (match(Op1, m_ZeroInt()) || match(Op1, m_Undef()))
2046 return BinaryOperator::CreateShl(Op0, ShAmtC);
Nikita Popov6e81d422018-11-23 22:45:08 +00002047
Sanjay Patel60633932019-03-18 14:27:51 +00002048 // fshl(0, X, C) --> lshr X, (BW-C)
2049 // fshl(undef, X, C) --> lshr X, (BW-C)
2050 if (match(Op0, m_ZeroInt()) || match(Op0, m_Undef()))
2051 return BinaryOperator::CreateLShr(Op1,
2052 ConstantExpr::getSub(WidthC, ShAmtC));
Nikita Popov6e81d422018-11-23 22:45:08 +00002053 }
2054
Sanjay Patela1395642018-11-13 23:27:23 +00002055 // The shift amount (operand 2) of a funnel shift is modulo the bitwidth,
2056 // so only the low bits of the shift amount are demanded if the bitwidth is
2057 // a power-of-2.
Sanjay Patela1395642018-11-13 23:27:23 +00002058 if (!isPowerOf2_32(BitWidth))
2059 break;
2060 APInt Op2Demanded = APInt::getLowBitsSet(BitWidth, Log2_32_Ceil(BitWidth));
2061 KnownBits Op2Known(BitWidth);
2062 if (SimplifyDemandedBits(II, 2, Op2Demanded, Op2Known))
2063 return &CI;
2064 break;
2065 }
Nikita Popov884feb12019-03-06 18:30:00 +00002066 case Intrinsic::sadd_with_overflow: {
2067 if (Instruction *I = canonicalizeConstantArg0ToArg1(CI))
2068 return I;
2069 if (Instruction *I = foldIntrinsicWithOverflowCommon(II))
2070 return I;
2071
2072 // Given 2 constant operands whose sum does not overflow:
2073 // saddo (X +nsw C0), C1 -> saddo X, C0 + C1
2074 Value *X;
2075 const APInt *C0, *C1;
2076 Value *Arg0 = II->getArgOperand(0);
2077 Value *Arg1 = II->getArgOperand(1);
2078 if (match(Arg0, m_NSWAdd(m_Value(X), m_APInt(C0))) &&
2079 match(Arg1, m_APInt(C1))) {
2080 bool Overflow;
2081 APInt NewC = C1->sadd_ov(*C0, Overflow);
2082 if (!Overflow)
2083 return replaceInstUsesWith(
2084 *II, Builder.CreateBinaryIntrinsic(
2085 Intrinsic::sadd_with_overflow, X,
2086 ConstantInt::get(Arg1->getType(), NewC)));
2087 }
2088
2089 break;
2090 }
Nick Lewyckyabe2cc12015-04-13 19:17:37 +00002091 case Intrinsic::uadd_with_overflow:
Nick Lewyckyabe2cc12015-04-13 19:17:37 +00002092 case Intrinsic::umul_with_overflow:
2093 case Intrinsic::smul_with_overflow:
Sanjay Patel790af912018-11-26 22:00:41 +00002094 if (Instruction *I = canonicalizeConstantArg0ToArg1(CI))
2095 return I;
Justin Bognercd1d5aa2016-08-17 20:30:52 +00002096 LLVM_FALLTHROUGH;
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002097
Nick Lewyckyabe2cc12015-04-13 19:17:37 +00002098 case Intrinsic::usub_with_overflow:
2099 case Intrinsic::ssub_with_overflow: {
Nikita Popov884feb12019-03-06 18:30:00 +00002100 if (Instruction *I = foldIntrinsicWithOverflowCommon(II))
2101 return I;
Benjamin Kramera420df22014-07-04 10:22:21 +00002102
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002103 break;
Erik Eckstein096ff7d2014-12-11 08:02:30 +00002104 }
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002105
Nikita Popov085d24a2018-11-28 16:36:52 +00002106 case Intrinsic::uadd_sat:
2107 case Intrinsic::sadd_sat:
2108 if (Instruction *I = canonicalizeConstantArg0ToArg1(CI))
2109 return I;
Nikita Popov78a92952018-11-28 16:36:59 +00002110 LLVM_FALLTHROUGH;
2111 case Intrinsic::usub_sat:
2112 case Intrinsic::ssub_sat: {
2113 Value *Arg0 = II->getArgOperand(0);
2114 Value *Arg1 = II->getArgOperand(1);
2115 Intrinsic::ID IID = II->getIntrinsicID();
2116
2117 // Make use of known overflow information.
2118 OverflowResult OR;
2119 switch (IID) {
2120 default:
2121 llvm_unreachable("Unexpected intrinsic!");
2122 case Intrinsic::uadd_sat:
2123 OR = computeOverflowForUnsignedAdd(Arg0, Arg1, II);
2124 if (OR == OverflowResult::NeverOverflows)
2125 return BinaryOperator::CreateNUWAdd(Arg0, Arg1);
2126 if (OR == OverflowResult::AlwaysOverflows)
2127 return replaceInstUsesWith(*II,
2128 ConstantInt::getAllOnesValue(II->getType()));
2129 break;
2130 case Intrinsic::usub_sat:
2131 OR = computeOverflowForUnsignedSub(Arg0, Arg1, II);
2132 if (OR == OverflowResult::NeverOverflows)
2133 return BinaryOperator::CreateNUWSub(Arg0, Arg1);
2134 if (OR == OverflowResult::AlwaysOverflows)
2135 return replaceInstUsesWith(*II,
2136 ConstantInt::getNullValue(II->getType()));
2137 break;
2138 case Intrinsic::sadd_sat:
2139 if (willNotOverflowSignedAdd(Arg0, Arg1, *II))
2140 return BinaryOperator::CreateNSWAdd(Arg0, Arg1);
2141 break;
2142 case Intrinsic::ssub_sat:
2143 if (willNotOverflowSignedSub(Arg0, Arg1, *II))
2144 return BinaryOperator::CreateNSWSub(Arg0, Arg1);
2145 break;
2146 }
Nikita Popov42f89982018-11-28 16:37:09 +00002147
2148 // ssub.sat(X, C) -> sadd.sat(X, -C) if C != MIN
Nikita Popov0c5d6cc2018-12-01 10:58:34 +00002149 Constant *C;
2150 if (IID == Intrinsic::ssub_sat && match(Arg1, m_Constant(C)) &&
2151 C->isNotMinSignedValue()) {
2152 Value *NegVal = ConstantExpr::getNeg(C);
Nikita Popov42f89982018-11-28 16:37:09 +00002153 return replaceInstUsesWith(
2154 *II, Builder.CreateBinaryIntrinsic(
2155 Intrinsic::sadd_sat, Arg0, NegVal));
2156 }
Nikita Popov8d63aed2018-11-28 16:37:15 +00002157
2158 // sat(sat(X + Val2) + Val) -> sat(X + (Val+Val2))
2159 // sat(sat(X - Val2) - Val) -> sat(X - (Val+Val2))
2160 // if Val and Val2 have the same sign
2161 if (auto *Other = dyn_cast<IntrinsicInst>(Arg0)) {
2162 Value *X;
2163 const APInt *Val, *Val2;
2164 APInt NewVal;
2165 bool IsUnsigned =
2166 IID == Intrinsic::uadd_sat || IID == Intrinsic::usub_sat;
2167 if (Other->getIntrinsicID() == II->getIntrinsicID() &&
2168 match(Arg1, m_APInt(Val)) &&
2169 match(Other->getArgOperand(0), m_Value(X)) &&
2170 match(Other->getArgOperand(1), m_APInt(Val2))) {
2171 if (IsUnsigned)
2172 NewVal = Val->uadd_sat(*Val2);
2173 else if (Val->isNonNegative() == Val2->isNonNegative()) {
2174 bool Overflow;
2175 NewVal = Val->sadd_ov(*Val2, Overflow);
2176 if (Overflow) {
2177 // Both adds together may add more than SignedMaxValue
2178 // without saturating the final result.
2179 break;
2180 }
2181 } else {
2182 // Cannot fold saturated addition with different signs.
2183 break;
2184 }
2185
2186 return replaceInstUsesWith(
2187 *II, Builder.CreateBinaryIntrinsic(
2188 IID, X, ConstantInt::get(II->getType(), NewVal)));
2189 }
2190 }
Nikita Popov085d24a2018-11-28 16:36:52 +00002191 break;
Nikita Popov78a92952018-11-28 16:36:59 +00002192 }
Nikita Popov085d24a2018-11-28 16:36:52 +00002193
Matt Arsenaultd6511b42014-10-21 23:00:20 +00002194 case Intrinsic::minnum:
Thomas Livelyc3392502018-10-19 19:01:26 +00002195 case Intrinsic::maxnum:
2196 case Intrinsic::minimum:
2197 case Intrinsic::maximum: {
Sanjay Patel790af912018-11-26 22:00:41 +00002198 if (Instruction *I = canonicalizeConstantArg0ToArg1(CI))
2199 return I;
Matt Arsenaultd6511b42014-10-21 23:00:20 +00002200 Value *Arg0 = II->getArgOperand(0);
2201 Value *Arg1 = II->getArgOperand(1);
Volkan Keles3ca146d2018-10-31 17:50:52 +00002202 Intrinsic::ID IID = II->getIntrinsicID();
Sanjay Patelc7bb1432018-05-10 20:03:13 +00002203 Value *X, *Y;
2204 if (match(Arg0, m_FNeg(m_Value(X))) && match(Arg1, m_FNeg(m_Value(Y))) &&
2205 (Arg0->hasOneUse() || Arg1->hasOneUse())) {
2206 // If both operands are negated, invert the call and negate the result:
Thomas Livelyc3392502018-10-19 19:01:26 +00002207 // min(-X, -Y) --> -(max(X, Y))
2208 // max(-X, -Y) --> -(min(X, Y))
2209 Intrinsic::ID NewIID;
Volkan Keles3ca146d2018-10-31 17:50:52 +00002210 switch (IID) {
Thomas Livelyc3392502018-10-19 19:01:26 +00002211 case Intrinsic::maxnum:
2212 NewIID = Intrinsic::minnum;
2213 break;
2214 case Intrinsic::minnum:
2215 NewIID = Intrinsic::maxnum;
2216 break;
2217 case Intrinsic::maximum:
2218 NewIID = Intrinsic::minimum;
2219 break;
2220 case Intrinsic::minimum:
2221 NewIID = Intrinsic::maximum;
2222 break;
2223 default:
2224 llvm_unreachable("unexpected intrinsic ID");
2225 }
Neil Henning57f5d0a2018-10-08 10:32:33 +00002226 Value *NewCall = Builder.CreateBinaryIntrinsic(NewIID, X, Y, II);
Sanjay Patelc7bb1432018-05-10 20:03:13 +00002227 Instruction *FNeg = BinaryOperator::CreateFNeg(NewCall);
2228 FNeg->copyIRFlags(II);
2229 return FNeg;
2230 }
Volkan Keles3ca146d2018-10-31 17:50:52 +00002231
2232 // m(m(X, C2), C1) -> m(X, C)
2233 const APFloat *C1, *C2;
2234 if (auto *M = dyn_cast<IntrinsicInst>(Arg0)) {
2235 if (M->getIntrinsicID() == IID && match(Arg1, m_APFloat(C1)) &&
2236 ((match(M->getArgOperand(0), m_Value(X)) &&
2237 match(M->getArgOperand(1), m_APFloat(C2))) ||
2238 (match(M->getArgOperand(1), m_Value(X)) &&
2239 match(M->getArgOperand(0), m_APFloat(C2))))) {
2240 APFloat Res(0.0);
2241 switch (IID) {
2242 case Intrinsic::maxnum:
2243 Res = maxnum(*C1, *C2);
2244 break;
2245 case Intrinsic::minnum:
2246 Res = minnum(*C1, *C2);
2247 break;
2248 case Intrinsic::maximum:
2249 Res = maximum(*C1, *C2);
2250 break;
2251 case Intrinsic::minimum:
2252 Res = minimum(*C1, *C2);
2253 break;
2254 default:
2255 llvm_unreachable("unexpected intrinsic ID");
2256 }
2257 Instruction *NewCall = Builder.CreateBinaryIntrinsic(
2258 IID, X, ConstantFP::get(Arg0->getType(), Res));
2259 NewCall->copyIRFlags(II);
2260 return replaceInstUsesWith(*II, NewCall);
2261 }
2262 }
2263
Matt Arsenaultd6511b42014-10-21 23:00:20 +00002264 break;
2265 }
Matt Arsenault1cc294c2017-01-03 04:32:31 +00002266 case Intrinsic::fmuladd: {
Matt Arsenault92057602017-02-16 18:46:24 +00002267 // Canonicalize fast fmuladd to the separate fmul + fadd.
Sanjay Patel629c4112017-11-06 16:27:15 +00002268 if (II->isFast()) {
Craig Topperbb4069e2017-07-07 23:16:26 +00002269 BuilderTy::FastMathFlagGuard Guard(Builder);
2270 Builder.setFastMathFlags(II->getFastMathFlags());
2271 Value *Mul = Builder.CreateFMul(II->getArgOperand(0),
2272 II->getArgOperand(1));
2273 Value *Add = Builder.CreateFAdd(Mul, II->getArgOperand(2));
Matt Arsenault92057602017-02-16 18:46:24 +00002274 Add->takeName(II);
2275 return replaceInstUsesWith(*II, Add);
2276 }
2277
2278 LLVM_FALLTHROUGH;
2279 }
2280 case Intrinsic::fma: {
Sanjay Patel790af912018-11-26 22:00:41 +00002281 if (Instruction *I = canonicalizeConstantArg0ToArg1(CI))
2282 return I;
Matt Arsenaultb264c942017-01-03 04:32:35 +00002283
Matt Arsenault1cc294c2017-01-03 04:32:31 +00002284 // fma fneg(x), fneg(y), z -> fma x, y, z
Sanjay Patel790af912018-11-26 22:00:41 +00002285 Value *Src0 = II->getArgOperand(0);
2286 Value *Src1 = II->getArgOperand(1);
Sanjay Patel236442e2018-04-05 13:24:26 +00002287 Value *X, *Y;
2288 if (match(Src0, m_FNeg(m_Value(X))) && match(Src1, m_FNeg(m_Value(Y)))) {
2289 II->setArgOperand(0, X);
2290 II->setArgOperand(1, Y);
Matt Arsenault3f509042017-01-10 23:17:52 +00002291 return II;
Matt Arsenault1cc294c2017-01-03 04:32:31 +00002292 }
2293
2294 // fma fabs(x), fabs(x), z -> fma x, x, z
Matt Arsenaultd1496502018-07-27 09:04:35 +00002295 if (match(Src0, m_FAbs(m_Value(X))) &&
2296 match(Src1, m_FAbs(m_Specific(X)))) {
Sanjay Patel236442e2018-04-05 13:24:26 +00002297 II->setArgOperand(0, X);
2298 II->setArgOperand(1, X);
Matt Arsenault3f509042017-01-10 23:17:52 +00002299 return II;
Matt Arsenault1cc294c2017-01-03 04:32:31 +00002300 }
2301
Matt Arsenaultb264c942017-01-03 04:32:35 +00002302 // fma x, 1, z -> fadd x, z
2303 if (match(Src1, m_FPOne())) {
Sanjay Patel236442e2018-04-05 13:24:26 +00002304 auto *FAdd = BinaryOperator::CreateFAdd(Src0, II->getArgOperand(2));
2305 FAdd->copyFastMathFlags(II);
2306 return FAdd;
Matt Arsenaultb264c942017-01-03 04:32:35 +00002307 }
2308
Matt Arsenault1cc294c2017-01-03 04:32:31 +00002309 break;
2310 }
Matt Arsenault56ff4832017-01-03 22:40:34 +00002311 case Intrinsic::fabs: {
2312 Value *Cond;
2313 Constant *LHS, *RHS;
2314 if (match(II->getArgOperand(0),
2315 m_Select(m_Value(Cond), m_Constant(LHS), m_Constant(RHS)))) {
Craig Topperbb4069e2017-07-07 23:16:26 +00002316 CallInst *Call0 = Builder.CreateCall(II->getCalledFunction(), {LHS});
2317 CallInst *Call1 = Builder.CreateCall(II->getCalledFunction(), {RHS});
Matt Arsenault56ff4832017-01-03 22:40:34 +00002318 return SelectInst::Create(Cond, Call0, Call1);
2319 }
2320
Matt Arsenault954a6242017-01-23 23:55:08 +00002321 LLVM_FALLTHROUGH;
2322 }
2323 case Intrinsic::ceil:
2324 case Intrinsic::floor:
2325 case Intrinsic::round:
2326 case Intrinsic::nearbyint:
Joerg Sonnenberger28bed102017-03-31 19:58:07 +00002327 case Intrinsic::rint:
Matt Arsenault954a6242017-01-23 23:55:08 +00002328 case Intrinsic::trunc: {
Matt Arsenault72333442017-01-17 00:10:40 +00002329 Value *ExtSrc;
Sanjay Patel32381d72018-03-23 21:18:12 +00002330 if (match(II->getArgOperand(0), m_OneUse(m_FPExt(m_Value(ExtSrc))))) {
2331 // Narrow the call: intrinsic (fpext x) -> fpext (intrinsic x)
Neil Henning57f5d0a2018-10-08 10:32:33 +00002332 Value *NarrowII =
2333 Builder.CreateUnaryIntrinsic(II->getIntrinsicID(), ExtSrc, II);
Sanjay Patel32381d72018-03-23 21:18:12 +00002334 return new FPExtInst(NarrowII, II->getType());
Matt Arsenault72333442017-01-17 00:10:40 +00002335 }
Matt Arsenault56ff4832017-01-03 22:40:34 +00002336 break;
2337 }
Matt Arsenault3bdd75d2017-01-04 22:49:03 +00002338 case Intrinsic::cos:
2339 case Intrinsic::amdgcn_cos: {
Sanjay Patel0f29e952018-08-29 18:27:49 +00002340 Value *X;
Matt Arsenault3bdd75d2017-01-04 22:49:03 +00002341 Value *Src = II->getArgOperand(0);
Sanjay Patel0f29e952018-08-29 18:27:49 +00002342 if (match(Src, m_FNeg(m_Value(X))) || match(Src, m_FAbs(m_Value(X)))) {
Matt Arsenault3bdd75d2017-01-04 22:49:03 +00002343 // cos(-x) -> cos(x)
2344 // cos(fabs(x)) -> cos(x)
Sanjay Patel0f29e952018-08-29 18:27:49 +00002345 II->setArgOperand(0, X);
Matt Arsenault3bdd75d2017-01-04 22:49:03 +00002346 return II;
2347 }
Sanjay Patel0f29e952018-08-29 18:27:49 +00002348 break;
2349 }
2350 case Intrinsic::sin: {
2351 Value *X;
2352 if (match(II->getArgOperand(0), m_OneUse(m_FNeg(m_Value(X))))) {
2353 // sin(-x) --> -sin(x)
Neil Henning57f5d0a2018-10-08 10:32:33 +00002354 Value *NewSin = Builder.CreateUnaryIntrinsic(Intrinsic::sin, X, II);
Sanjay Patel0f29e952018-08-29 18:27:49 +00002355 Instruction *FNeg = BinaryOperator::CreateFNeg(NewSin);
2356 FNeg->copyFastMathFlags(II);
2357 return FNeg;
2358 }
Matt Arsenault3bdd75d2017-01-04 22:49:03 +00002359 break;
2360 }
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002361 case Intrinsic::ppc_altivec_lvx:
2362 case Intrinsic::ppc_altivec_lvxl:
Bill Wendlingb902f1d2011-04-13 00:36:11 +00002363 // Turn PPC lvx -> load if the pointer is known aligned.
Daniel Jasperaec2fa32016-12-19 08:22:17 +00002364 if (getOrEnforceKnownAlignment(II->getArgOperand(0), 16, DL, II, &AC,
Justin Bogner99798402016-08-05 01:06:44 +00002365 &DT) >= 16) {
Craig Topperbb4069e2017-07-07 23:16:26 +00002366 Value *Ptr = Builder.CreateBitCast(II->getArgOperand(0),
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002367 PointerType::getUnqual(II->getType()));
James Y Knight14359ef2019-02-01 20:44:24 +00002368 return new LoadInst(II->getType(), Ptr);
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002369 }
2370 break;
Bill Schmidt72954782014-11-12 04:19:40 +00002371 case Intrinsic::ppc_vsx_lxvw4x:
2372 case Intrinsic::ppc_vsx_lxvd2x: {
2373 // Turn PPC VSX loads into normal loads.
Craig Topperbb4069e2017-07-07 23:16:26 +00002374 Value *Ptr = Builder.CreateBitCast(II->getArgOperand(0),
2375 PointerType::getUnqual(II->getType()));
James Y Knight14359ef2019-02-01 20:44:24 +00002376 return new LoadInst(II->getType(), Ptr, Twine(""), false, 1);
Bill Schmidt72954782014-11-12 04:19:40 +00002377 }
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002378 case Intrinsic::ppc_altivec_stvx:
2379 case Intrinsic::ppc_altivec_stvxl:
2380 // Turn stvx -> store if the pointer is known aligned.
Daniel Jasperaec2fa32016-12-19 08:22:17 +00002381 if (getOrEnforceKnownAlignment(II->getArgOperand(1), 16, DL, II, &AC,
Justin Bogner99798402016-08-05 01:06:44 +00002382 &DT) >= 16) {
Jim Grosbach7815f562012-02-03 00:07:04 +00002383 Type *OpPtrTy =
Gabor Greifa6d75e22010-06-24 15:51:11 +00002384 PointerType::getUnqual(II->getArgOperand(0)->getType());
Craig Topperbb4069e2017-07-07 23:16:26 +00002385 Value *Ptr = Builder.CreateBitCast(II->getArgOperand(1), OpPtrTy);
Gabor Greifa6d75e22010-06-24 15:51:11 +00002386 return new StoreInst(II->getArgOperand(0), Ptr);
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002387 }
2388 break;
Bill Schmidt72954782014-11-12 04:19:40 +00002389 case Intrinsic::ppc_vsx_stxvw4x:
2390 case Intrinsic::ppc_vsx_stxvd2x: {
2391 // Turn PPC VSX stores into normal stores.
2392 Type *OpPtrTy = PointerType::getUnqual(II->getArgOperand(0)->getType());
Craig Topperbb4069e2017-07-07 23:16:26 +00002393 Value *Ptr = Builder.CreateBitCast(II->getArgOperand(1), OpPtrTy);
Bill Schmidt72954782014-11-12 04:19:40 +00002394 return new StoreInst(II->getArgOperand(0), Ptr, false, 1);
2395 }
Hal Finkel221f4672015-02-26 18:56:03 +00002396 case Intrinsic::ppc_qpx_qvlfs:
2397 // Turn PPC QPX qvlfs -> load if the pointer is known aligned.
Daniel Jasperaec2fa32016-12-19 08:22:17 +00002398 if (getOrEnforceKnownAlignment(II->getArgOperand(0), 16, DL, II, &AC,
Justin Bogner99798402016-08-05 01:06:44 +00002399 &DT) >= 16) {
Craig Topperbb4069e2017-07-07 23:16:26 +00002400 Type *VTy = VectorType::get(Builder.getFloatTy(),
Hal Finkelf0d68d72015-05-11 06:37:03 +00002401 II->getType()->getVectorNumElements());
Craig Topperbb4069e2017-07-07 23:16:26 +00002402 Value *Ptr = Builder.CreateBitCast(II->getArgOperand(0),
Hal Finkelf0d68d72015-05-11 06:37:03 +00002403 PointerType::getUnqual(VTy));
James Y Knight14359ef2019-02-01 20:44:24 +00002404 Value *Load = Builder.CreateLoad(VTy, Ptr);
Hal Finkelf0d68d72015-05-11 06:37:03 +00002405 return new FPExtInst(Load, II->getType());
Hal Finkel221f4672015-02-26 18:56:03 +00002406 }
2407 break;
2408 case Intrinsic::ppc_qpx_qvlfd:
2409 // Turn PPC QPX qvlfd -> load if the pointer is known aligned.
Daniel Jasperaec2fa32016-12-19 08:22:17 +00002410 if (getOrEnforceKnownAlignment(II->getArgOperand(0), 32, DL, II, &AC,
Justin Bogner99798402016-08-05 01:06:44 +00002411 &DT) >= 32) {
Craig Topperbb4069e2017-07-07 23:16:26 +00002412 Value *Ptr = Builder.CreateBitCast(II->getArgOperand(0),
Hal Finkel221f4672015-02-26 18:56:03 +00002413 PointerType::getUnqual(II->getType()));
James Y Knight14359ef2019-02-01 20:44:24 +00002414 return new LoadInst(II->getType(), Ptr);
Hal Finkel221f4672015-02-26 18:56:03 +00002415 }
2416 break;
2417 case Intrinsic::ppc_qpx_qvstfs:
2418 // Turn PPC QPX qvstfs -> store if the pointer is known aligned.
Daniel Jasperaec2fa32016-12-19 08:22:17 +00002419 if (getOrEnforceKnownAlignment(II->getArgOperand(1), 16, DL, II, &AC,
Justin Bogner99798402016-08-05 01:06:44 +00002420 &DT) >= 16) {
Craig Topperbb4069e2017-07-07 23:16:26 +00002421 Type *VTy = VectorType::get(Builder.getFloatTy(),
Hal Finkelf0d68d72015-05-11 06:37:03 +00002422 II->getArgOperand(0)->getType()->getVectorNumElements());
Craig Topperbb4069e2017-07-07 23:16:26 +00002423 Value *TOp = Builder.CreateFPTrunc(II->getArgOperand(0), VTy);
Hal Finkelf0d68d72015-05-11 06:37:03 +00002424 Type *OpPtrTy = PointerType::getUnqual(VTy);
Craig Topperbb4069e2017-07-07 23:16:26 +00002425 Value *Ptr = Builder.CreateBitCast(II->getArgOperand(1), OpPtrTy);
Hal Finkelf0d68d72015-05-11 06:37:03 +00002426 return new StoreInst(TOp, Ptr);
Hal Finkel221f4672015-02-26 18:56:03 +00002427 }
2428 break;
2429 case Intrinsic::ppc_qpx_qvstfd:
2430 // Turn PPC QPX qvstfd -> store if the pointer is known aligned.
Daniel Jasperaec2fa32016-12-19 08:22:17 +00002431 if (getOrEnforceKnownAlignment(II->getArgOperand(1), 32, DL, II, &AC,
Justin Bogner99798402016-08-05 01:06:44 +00002432 &DT) >= 32) {
Hal Finkel221f4672015-02-26 18:56:03 +00002433 Type *OpPtrTy =
2434 PointerType::getUnqual(II->getArgOperand(0)->getType());
Craig Topperbb4069e2017-07-07 23:16:26 +00002435 Value *Ptr = Builder.CreateBitCast(II->getArgOperand(1), OpPtrTy);
Hal Finkel221f4672015-02-26 18:56:03 +00002436 return new StoreInst(II->getArgOperand(0), Ptr);
2437 }
2438 break;
Simon Pilgrim20c607b2015-09-12 13:39:53 +00002439
Craig Topper83240032017-07-31 18:52:13 +00002440 case Intrinsic::x86_bmi_bextr_32:
2441 case Intrinsic::x86_bmi_bextr_64:
2442 case Intrinsic::x86_tbm_bextri_u32:
2443 case Intrinsic::x86_tbm_bextri_u64:
2444 // If the RHS is a constant we can try some simplifications.
2445 if (auto *C = dyn_cast<ConstantInt>(II->getArgOperand(1))) {
2446 uint64_t Shift = C->getZExtValue();
2447 uint64_t Length = (Shift >> 8) & 0xff;
2448 Shift &= 0xff;
2449 unsigned BitWidth = II->getType()->getIntegerBitWidth();
2450 // If the length is 0 or the shift is out of range, replace with zero.
2451 if (Length == 0 || Shift >= BitWidth)
2452 return replaceInstUsesWith(CI, ConstantInt::get(II->getType(), 0));
2453 // If the LHS is also a constant, we can completely constant fold this.
2454 if (auto *InC = dyn_cast<ConstantInt>(II->getArgOperand(0))) {
2455 uint64_t Result = InC->getZExtValue() >> Shift;
2456 if (Length > BitWidth)
2457 Length = BitWidth;
2458 Result &= maskTrailingOnes<uint64_t>(Length);
2459 return replaceInstUsesWith(CI, ConstantInt::get(II->getType(), Result));
2460 }
2461 // TODO should we turn this into 'and' if shift is 0? Or 'shl' if we
2462 // are only masking bits that a shift already cleared?
2463 }
2464 break;
2465
Craig Topper317a51e2017-07-31 18:52:15 +00002466 case Intrinsic::x86_bmi_bzhi_32:
2467 case Intrinsic::x86_bmi_bzhi_64:
2468 // If the RHS is a constant we can try some simplifications.
2469 if (auto *C = dyn_cast<ConstantInt>(II->getArgOperand(1))) {
2470 uint64_t Index = C->getZExtValue() & 0xff;
2471 unsigned BitWidth = II->getType()->getIntegerBitWidth();
2472 if (Index >= BitWidth)
2473 return replaceInstUsesWith(CI, II->getArgOperand(0));
2474 if (Index == 0)
2475 return replaceInstUsesWith(CI, ConstantInt::get(II->getType(), 0));
2476 // If the LHS is also a constant, we can completely constant fold this.
2477 if (auto *InC = dyn_cast<ConstantInt>(II->getArgOperand(0))) {
2478 uint64_t Result = InC->getZExtValue();
2479 Result &= maskTrailingOnes<uint64_t>(Index);
2480 return replaceInstUsesWith(CI, ConstantInt::get(II->getType(), Result));
2481 }
2482 // TODO should we convert this to an AND if the RHS is constant?
2483 }
2484 break;
2485
Simon Pilgrim20c607b2015-09-12 13:39:53 +00002486 case Intrinsic::x86_vcvtph2ps_128:
2487 case Intrinsic::x86_vcvtph2ps_256: {
2488 auto Arg = II->getArgOperand(0);
2489 auto ArgType = cast<VectorType>(Arg->getType());
2490 auto RetType = cast<VectorType>(II->getType());
2491 unsigned ArgWidth = ArgType->getNumElements();
2492 unsigned RetWidth = RetType->getNumElements();
2493 assert(RetWidth <= ArgWidth && "Unexpected input/return vector widths");
2494 assert(ArgType->isIntOrIntVectorTy() &&
2495 ArgType->getScalarSizeInBits() == 16 &&
2496 "CVTPH2PS input type should be 16-bit integer vector");
2497 assert(RetType->getScalarType()->isFloatTy() &&
2498 "CVTPH2PS output type should be 32-bit float vector");
2499
2500 // Constant folding: Convert to generic half to single conversion.
Simon Pilgrim48ffca02015-09-12 14:00:17 +00002501 if (isa<ConstantAggregateZero>(Arg))
Sanjay Patel4b198802016-02-01 22:23:39 +00002502 return replaceInstUsesWith(*II, ConstantAggregateZero::get(RetType));
Simon Pilgrim20c607b2015-09-12 13:39:53 +00002503
Simon Pilgrim48ffca02015-09-12 14:00:17 +00002504 if (isa<ConstantDataVector>(Arg)) {
Simon Pilgrim20c607b2015-09-12 13:39:53 +00002505 auto VectorHalfAsShorts = Arg;
2506 if (RetWidth < ArgWidth) {
Craig Topper99d1eab2016-06-12 00:41:19 +00002507 SmallVector<uint32_t, 8> SubVecMask;
Simon Pilgrim20c607b2015-09-12 13:39:53 +00002508 for (unsigned i = 0; i != RetWidth; ++i)
2509 SubVecMask.push_back((int)i);
Craig Topperbb4069e2017-07-07 23:16:26 +00002510 VectorHalfAsShorts = Builder.CreateShuffleVector(
Simon Pilgrim20c607b2015-09-12 13:39:53 +00002511 Arg, UndefValue::get(ArgType), SubVecMask);
2512 }
2513
2514 auto VectorHalfType =
2515 VectorType::get(Type::getHalfTy(II->getContext()), RetWidth);
2516 auto VectorHalfs =
Craig Topperbb4069e2017-07-07 23:16:26 +00002517 Builder.CreateBitCast(VectorHalfAsShorts, VectorHalfType);
2518 auto VectorFloats = Builder.CreateFPExt(VectorHalfs, RetType);
Sanjay Patel4b198802016-02-01 22:23:39 +00002519 return replaceInstUsesWith(*II, VectorFloats);
Simon Pilgrim20c607b2015-09-12 13:39:53 +00002520 }
2521
2522 // We only use the lowest lanes of the argument.
Simon Pilgrim996725e2015-09-19 11:41:53 +00002523 if (Value *V = SimplifyDemandedVectorEltsLow(Arg, ArgWidth, RetWidth)) {
Simon Pilgrim20c607b2015-09-12 13:39:53 +00002524 II->setArgOperand(0, V);
2525 return II;
2526 }
2527 break;
2528 }
2529
Chandler Carruthcf414cf2011-01-10 07:19:37 +00002530 case Intrinsic::x86_sse_cvtss2si:
2531 case Intrinsic::x86_sse_cvtss2si64:
2532 case Intrinsic::x86_sse_cvttss2si:
2533 case Intrinsic::x86_sse_cvttss2si64:
2534 case Intrinsic::x86_sse2_cvtsd2si:
2535 case Intrinsic::x86_sse2_cvtsd2si64:
2536 case Intrinsic::x86_sse2_cvttsd2si:
Craig Topperaeaa52c2016-12-14 07:46:12 +00002537 case Intrinsic::x86_sse2_cvttsd2si64:
2538 case Intrinsic::x86_avx512_vcvtss2si32:
2539 case Intrinsic::x86_avx512_vcvtss2si64:
2540 case Intrinsic::x86_avx512_vcvtss2usi32:
2541 case Intrinsic::x86_avx512_vcvtss2usi64:
2542 case Intrinsic::x86_avx512_vcvtsd2si32:
2543 case Intrinsic::x86_avx512_vcvtsd2si64:
2544 case Intrinsic::x86_avx512_vcvtsd2usi32:
2545 case Intrinsic::x86_avx512_vcvtsd2usi64:
2546 case Intrinsic::x86_avx512_cvttss2si:
2547 case Intrinsic::x86_avx512_cvttss2si64:
2548 case Intrinsic::x86_avx512_cvttss2usi:
2549 case Intrinsic::x86_avx512_cvttss2usi64:
2550 case Intrinsic::x86_avx512_cvttsd2si:
2551 case Intrinsic::x86_avx512_cvttsd2si64:
2552 case Intrinsic::x86_avx512_cvttsd2usi:
2553 case Intrinsic::x86_avx512_cvttsd2usi64: {
Chandler Carruthcf414cf2011-01-10 07:19:37 +00002554 // These intrinsics only demand the 0th element of their input vectors. If
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002555 // we can simplify the input based on that, do so now.
Simon Pilgrim996725e2015-09-19 11:41:53 +00002556 Value *Arg = II->getArgOperand(0);
2557 unsigned VWidth = Arg->getType()->getVectorNumElements();
2558 if (Value *V = SimplifyDemandedVectorEltsLow(Arg, VWidth, 1)) {
Gabor Greif5b1370e2010-06-28 16:50:57 +00002559 II->setArgOperand(0, V);
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002560 return II;
2561 }
Simon Pilgrim18617d12015-08-05 08:18:00 +00002562 break;
2563 }
2564
Mikhail Dvoretckii8393f902018-06-19 10:49:12 +00002565 case Intrinsic::x86_sse41_round_ps:
2566 case Intrinsic::x86_sse41_round_pd:
2567 case Intrinsic::x86_avx_round_ps_256:
2568 case Intrinsic::x86_avx_round_pd_256:
2569 case Intrinsic::x86_avx512_mask_rndscale_ps_128:
2570 case Intrinsic::x86_avx512_mask_rndscale_ps_256:
2571 case Intrinsic::x86_avx512_mask_rndscale_ps_512:
2572 case Intrinsic::x86_avx512_mask_rndscale_pd_128:
2573 case Intrinsic::x86_avx512_mask_rndscale_pd_256:
2574 case Intrinsic::x86_avx512_mask_rndscale_pd_512:
2575 case Intrinsic::x86_avx512_mask_rndscale_ss:
2576 case Intrinsic::x86_avx512_mask_rndscale_sd:
2577 if (Value *V = simplifyX86round(*II, Builder))
2578 return replaceInstUsesWith(*II, V);
2579 break;
2580
Simon Pilgrim91e3ac82016-06-07 08:18:35 +00002581 case Intrinsic::x86_mmx_pmovmskb:
2582 case Intrinsic::x86_sse_movmsk_ps:
2583 case Intrinsic::x86_sse2_movmsk_pd:
2584 case Intrinsic::x86_sse2_pmovmskb_128:
2585 case Intrinsic::x86_avx_movmsk_pd_256:
2586 case Intrinsic::x86_avx_movmsk_ps_256:
Eugene Zelenko7f0f9bc2017-10-24 21:24:53 +00002587 case Intrinsic::x86_avx2_pmovmskb:
Sanjay Patel2aa2dc72018-12-11 16:38:03 +00002588 if (Value *V = simplifyX86movmsk(*II, Builder))
Simon Pilgrim91e3ac82016-06-07 08:18:35 +00002589 return replaceInstUsesWith(*II, V);
2590 break;
Simon Pilgrim91e3ac82016-06-07 08:18:35 +00002591
Simon Pilgrim471efd22016-02-20 23:17:35 +00002592 case Intrinsic::x86_sse_comieq_ss:
2593 case Intrinsic::x86_sse_comige_ss:
2594 case Intrinsic::x86_sse_comigt_ss:
2595 case Intrinsic::x86_sse_comile_ss:
2596 case Intrinsic::x86_sse_comilt_ss:
2597 case Intrinsic::x86_sse_comineq_ss:
2598 case Intrinsic::x86_sse_ucomieq_ss:
2599 case Intrinsic::x86_sse_ucomige_ss:
2600 case Intrinsic::x86_sse_ucomigt_ss:
2601 case Intrinsic::x86_sse_ucomile_ss:
2602 case Intrinsic::x86_sse_ucomilt_ss:
2603 case Intrinsic::x86_sse_ucomineq_ss:
2604 case Intrinsic::x86_sse2_comieq_sd:
2605 case Intrinsic::x86_sse2_comige_sd:
2606 case Intrinsic::x86_sse2_comigt_sd:
2607 case Intrinsic::x86_sse2_comile_sd:
2608 case Intrinsic::x86_sse2_comilt_sd:
2609 case Intrinsic::x86_sse2_comineq_sd:
2610 case Intrinsic::x86_sse2_ucomieq_sd:
2611 case Intrinsic::x86_sse2_ucomige_sd:
2612 case Intrinsic::x86_sse2_ucomigt_sd:
2613 case Intrinsic::x86_sse2_ucomile_sd:
2614 case Intrinsic::x86_sse2_ucomilt_sd:
Craig Topperd9639532016-12-11 07:42:04 +00002615 case Intrinsic::x86_sse2_ucomineq_sd:
Craig Topperd00db692016-12-31 00:45:06 +00002616 case Intrinsic::x86_avx512_vcomi_ss:
2617 case Intrinsic::x86_avx512_vcomi_sd:
Craig Topperd9639532016-12-11 07:42:04 +00002618 case Intrinsic::x86_avx512_mask_cmp_ss:
2619 case Intrinsic::x86_avx512_mask_cmp_sd: {
Simon Pilgrim471efd22016-02-20 23:17:35 +00002620 // These intrinsics only demand the 0th element of their input vectors. If
2621 // we can simplify the input based on that, do so now.
Simon Pilgrim1c9a9f22016-04-24 17:57:27 +00002622 bool MadeChange = false;
Simon Pilgrim471efd22016-02-20 23:17:35 +00002623 Value *Arg0 = II->getArgOperand(0);
2624 Value *Arg1 = II->getArgOperand(1);
2625 unsigned VWidth = Arg0->getType()->getVectorNumElements();
2626 if (Value *V = SimplifyDemandedVectorEltsLow(Arg0, VWidth, 1)) {
2627 II->setArgOperand(0, V);
Simon Pilgrim1c9a9f22016-04-24 17:57:27 +00002628 MadeChange = true;
Simon Pilgrim471efd22016-02-20 23:17:35 +00002629 }
2630 if (Value *V = SimplifyDemandedVectorEltsLow(Arg1, VWidth, 1)) {
2631 II->setArgOperand(1, V);
Simon Pilgrim1c9a9f22016-04-24 17:57:27 +00002632 MadeChange = true;
Simon Pilgrim471efd22016-02-20 23:17:35 +00002633 }
Simon Pilgrim1c9a9f22016-04-24 17:57:27 +00002634 if (MadeChange)
2635 return II;
Simon Pilgrim471efd22016-02-20 23:17:35 +00002636 break;
2637 }
Craig Topper31cbe752018-06-27 15:57:53 +00002638 case Intrinsic::x86_avx512_cmp_pd_128:
2639 case Intrinsic::x86_avx512_cmp_pd_256:
2640 case Intrinsic::x86_avx512_cmp_pd_512:
2641 case Intrinsic::x86_avx512_cmp_ps_128:
2642 case Intrinsic::x86_avx512_cmp_ps_256:
2643 case Intrinsic::x86_avx512_cmp_ps_512: {
Michael Zuckerman16b20d22017-04-16 13:26:08 +00002644 // Folding cmp(sub(a,b),0) -> cmp(a,b) and cmp(0,sub(a,b)) -> cmp(b,a)
2645 Value *Arg0 = II->getArgOperand(0);
2646 Value *Arg1 = II->getArgOperand(1);
Sanjay Patel93e64dd2018-03-25 21:16:33 +00002647 bool Arg0IsZero = match(Arg0, m_PosZeroFP());
Michael Zuckerman16b20d22017-04-16 13:26:08 +00002648 if (Arg0IsZero)
2649 std::swap(Arg0, Arg1);
2650 Value *A, *B;
2651 // This fold requires only the NINF(not +/- inf) since inf minus
2652 // inf is nan.
2653 // NSZ(No Signed Zeros) is not needed because zeros of any sign are
2654 // equal for both compares.
2655 // NNAN is not needed because nans compare the same for both compares.
2656 // The compare intrinsic uses the above assumptions and therefore
2657 // doesn't require additional flags.
2658 if ((match(Arg0, m_OneUse(m_FSub(m_Value(A), m_Value(B)))) &&
Sanjay Patel93e64dd2018-03-25 21:16:33 +00002659 match(Arg1, m_PosZeroFP()) && isa<Instruction>(Arg0) &&
Michael Zuckerman16b20d22017-04-16 13:26:08 +00002660 cast<Instruction>(Arg0)->getFastMathFlags().noInfs())) {
2661 if (Arg0IsZero)
2662 std::swap(A, B);
2663 II->setArgOperand(0, A);
2664 II->setArgOperand(1, B);
2665 return II;
2666 }
2667 break;
2668 }
Simon Pilgrim471efd22016-02-20 23:17:35 +00002669
Craig Topper98a79932018-06-10 06:01:36 +00002670 case Intrinsic::x86_avx512_add_ps_512:
2671 case Intrinsic::x86_avx512_div_ps_512:
2672 case Intrinsic::x86_avx512_mul_ps_512:
2673 case Intrinsic::x86_avx512_sub_ps_512:
2674 case Intrinsic::x86_avx512_add_pd_512:
2675 case Intrinsic::x86_avx512_div_pd_512:
2676 case Intrinsic::x86_avx512_mul_pd_512:
2677 case Intrinsic::x86_avx512_sub_pd_512:
Craig Topper020b2282016-12-27 00:23:16 +00002678 // If the rounding mode is CUR_DIRECTION(4) we can turn these into regular
2679 // IR operations.
Craig Topper98a79932018-06-10 06:01:36 +00002680 if (auto *R = dyn_cast<ConstantInt>(II->getArgOperand(2))) {
Craig Topper020b2282016-12-27 00:23:16 +00002681 if (R->getValue() == 4) {
2682 Value *Arg0 = II->getArgOperand(0);
2683 Value *Arg1 = II->getArgOperand(1);
2684
2685 Value *V;
2686 switch (II->getIntrinsicID()) {
2687 default: llvm_unreachable("Case stmts out of sync!");
Craig Topper98a79932018-06-10 06:01:36 +00002688 case Intrinsic::x86_avx512_add_ps_512:
2689 case Intrinsic::x86_avx512_add_pd_512:
Craig Topperbb4069e2017-07-07 23:16:26 +00002690 V = Builder.CreateFAdd(Arg0, Arg1);
Craig Topper020b2282016-12-27 00:23:16 +00002691 break;
Craig Topper98a79932018-06-10 06:01:36 +00002692 case Intrinsic::x86_avx512_sub_ps_512:
2693 case Intrinsic::x86_avx512_sub_pd_512:
Craig Topperbb4069e2017-07-07 23:16:26 +00002694 V = Builder.CreateFSub(Arg0, Arg1);
Craig Topper020b2282016-12-27 00:23:16 +00002695 break;
Craig Topper98a79932018-06-10 06:01:36 +00002696 case Intrinsic::x86_avx512_mul_ps_512:
2697 case Intrinsic::x86_avx512_mul_pd_512:
Craig Topperbb4069e2017-07-07 23:16:26 +00002698 V = Builder.CreateFMul(Arg0, Arg1);
Craig Topper020b2282016-12-27 00:23:16 +00002699 break;
Craig Topper98a79932018-06-10 06:01:36 +00002700 case Intrinsic::x86_avx512_div_ps_512:
2701 case Intrinsic::x86_avx512_div_pd_512:
Craig Topperbb4069e2017-07-07 23:16:26 +00002702 V = Builder.CreateFDiv(Arg0, Arg1);
Craig Topper020b2282016-12-27 00:23:16 +00002703 break;
2704 }
2705
Craig Topper020b2282016-12-27 00:23:16 +00002706 return replaceInstUsesWith(*II, V);
2707 }
2708 }
2709 break;
2710
Craig Topper790d0fa2016-12-11 07:42:01 +00002711 case Intrinsic::x86_avx512_mask_add_ss_round:
2712 case Intrinsic::x86_avx512_mask_div_ss_round:
2713 case Intrinsic::x86_avx512_mask_mul_ss_round:
2714 case Intrinsic::x86_avx512_mask_sub_ss_round:
Craig Topper790d0fa2016-12-11 07:42:01 +00002715 case Intrinsic::x86_avx512_mask_add_sd_round:
2716 case Intrinsic::x86_avx512_mask_div_sd_round:
2717 case Intrinsic::x86_avx512_mask_mul_sd_round:
2718 case Intrinsic::x86_avx512_mask_sub_sd_round:
Craig Topper7b788ada2016-12-26 06:33:19 +00002719 // If the rounding mode is CUR_DIRECTION(4) we can turn these into regular
2720 // IR operations.
2721 if (auto *R = dyn_cast<ConstantInt>(II->getArgOperand(4))) {
2722 if (R->getValue() == 4) {
Craig Topper7f8540b2016-12-27 01:56:30 +00002723 // Extract the element as scalars.
2724 Value *Arg0 = II->getArgOperand(0);
2725 Value *Arg1 = II->getArgOperand(1);
Craig Topperbb4069e2017-07-07 23:16:26 +00002726 Value *LHS = Builder.CreateExtractElement(Arg0, (uint64_t)0);
2727 Value *RHS = Builder.CreateExtractElement(Arg1, (uint64_t)0);
Craig Topper7b788ada2016-12-26 06:33:19 +00002728
Craig Topper7f8540b2016-12-27 01:56:30 +00002729 Value *V;
2730 switch (II->getIntrinsicID()) {
2731 default: llvm_unreachable("Case stmts out of sync!");
2732 case Intrinsic::x86_avx512_mask_add_ss_round:
2733 case Intrinsic::x86_avx512_mask_add_sd_round:
Craig Topperbb4069e2017-07-07 23:16:26 +00002734 V = Builder.CreateFAdd(LHS, RHS);
Craig Topper7f8540b2016-12-27 01:56:30 +00002735 break;
2736 case Intrinsic::x86_avx512_mask_sub_ss_round:
2737 case Intrinsic::x86_avx512_mask_sub_sd_round:
Craig Topperbb4069e2017-07-07 23:16:26 +00002738 V = Builder.CreateFSub(LHS, RHS);
Craig Topper7f8540b2016-12-27 01:56:30 +00002739 break;
2740 case Intrinsic::x86_avx512_mask_mul_ss_round:
2741 case Intrinsic::x86_avx512_mask_mul_sd_round:
Craig Topperbb4069e2017-07-07 23:16:26 +00002742 V = Builder.CreateFMul(LHS, RHS);
Craig Topper7f8540b2016-12-27 01:56:30 +00002743 break;
2744 case Intrinsic::x86_avx512_mask_div_ss_round:
2745 case Intrinsic::x86_avx512_mask_div_sd_round:
Craig Topperbb4069e2017-07-07 23:16:26 +00002746 V = Builder.CreateFDiv(LHS, RHS);
Craig Topper7f8540b2016-12-27 01:56:30 +00002747 break;
Craig Topper7b788ada2016-12-26 06:33:19 +00002748 }
Craig Topper7f8540b2016-12-27 01:56:30 +00002749
2750 // Handle the masking aspect of the intrinsic.
Craig Topper7f8540b2016-12-27 01:56:30 +00002751 Value *Mask = II->getArgOperand(3);
Craig Topper99163632016-12-30 23:06:28 +00002752 auto *C = dyn_cast<ConstantInt>(Mask);
2753 // We don't need a select if we know the mask bit is a 1.
2754 if (!C || !C->getValue()[0]) {
2755 // Cast the mask to an i1 vector and then extract the lowest element.
Craig Topperbb4069e2017-07-07 23:16:26 +00002756 auto *MaskTy = VectorType::get(Builder.getInt1Ty(),
Craig Topper7f8540b2016-12-27 01:56:30 +00002757 cast<IntegerType>(Mask->getType())->getBitWidth());
Craig Topperbb4069e2017-07-07 23:16:26 +00002758 Mask = Builder.CreateBitCast(Mask, MaskTy);
2759 Mask = Builder.CreateExtractElement(Mask, (uint64_t)0);
Craig Topper99163632016-12-30 23:06:28 +00002760 // Extract the lowest element from the passthru operand.
Craig Topperbb4069e2017-07-07 23:16:26 +00002761 Value *Passthru = Builder.CreateExtractElement(II->getArgOperand(2),
Craig Topper99163632016-12-30 23:06:28 +00002762 (uint64_t)0);
Craig Topperbb4069e2017-07-07 23:16:26 +00002763 V = Builder.CreateSelect(Mask, V, Passthru);
Craig Topper99163632016-12-30 23:06:28 +00002764 }
Craig Topper7f8540b2016-12-27 01:56:30 +00002765
2766 // Insert the result back into the original argument 0.
Craig Topperbb4069e2017-07-07 23:16:26 +00002767 V = Builder.CreateInsertElement(Arg0, V, (uint64_t)0);
Craig Topper7f8540b2016-12-27 01:56:30 +00002768
2769 return replaceInstUsesWith(*II, V);
Craig Topper7b788ada2016-12-26 06:33:19 +00002770 }
2771 }
Philip Reamesc71e9962019-01-30 19:21:11 +00002772 break;
Craig Topper7b788ada2016-12-26 06:33:19 +00002773
Mikhail Dvoretckii8393f902018-06-19 10:49:12 +00002774 case Intrinsic::x86_sse41_round_ss:
2775 case Intrinsic::x86_sse41_round_sd: {
Philip Reamesc71e9962019-01-30 19:21:11 +00002776 if (Value *V = simplifyX86round(*II, Builder))
Mikhail Dvoretckii8393f902018-06-19 10:49:12 +00002777 return replaceInstUsesWith(*II, V);
2778 break;
2779 }
Craig Topperac75bca2016-12-13 07:45:45 +00002780
Simon Pilgrima3a72b42015-08-10 20:21:15 +00002781 // Constant fold ashr( <A x Bi>, Ci ).
Simon Pilgrimbecd5e82015-08-13 07:39:03 +00002782 // Constant fold lshr( <A x Bi>, Ci ).
2783 // Constant fold shl( <A x Bi>, Ci ).
Simon Pilgrima3a72b42015-08-10 20:21:15 +00002784 case Intrinsic::x86_sse2_psrai_d:
2785 case Intrinsic::x86_sse2_psrai_w:
Simon Pilgrima3a72b42015-08-10 20:21:15 +00002786 case Intrinsic::x86_avx2_psrai_d:
2787 case Intrinsic::x86_avx2_psrai_w:
Craig Topper8b831cb2016-11-13 01:51:55 +00002788 case Intrinsic::x86_avx512_psrai_q_128:
2789 case Intrinsic::x86_avx512_psrai_q_256:
2790 case Intrinsic::x86_avx512_psrai_d_512:
2791 case Intrinsic::x86_avx512_psrai_q_512:
2792 case Intrinsic::x86_avx512_psrai_w_512:
Simon Pilgrim18617d12015-08-05 08:18:00 +00002793 case Intrinsic::x86_sse2_psrli_d:
2794 case Intrinsic::x86_sse2_psrli_q:
2795 case Intrinsic::x86_sse2_psrli_w:
Simon Pilgrim18617d12015-08-05 08:18:00 +00002796 case Intrinsic::x86_avx2_psrli_d:
2797 case Intrinsic::x86_avx2_psrli_q:
2798 case Intrinsic::x86_avx2_psrli_w:
Craig Topper8b831cb2016-11-13 01:51:55 +00002799 case Intrinsic::x86_avx512_psrli_d_512:
2800 case Intrinsic::x86_avx512_psrli_q_512:
2801 case Intrinsic::x86_avx512_psrli_w_512:
Michael J. Spencerdee4b2c2014-04-24 00:58:18 +00002802 case Intrinsic::x86_sse2_pslli_d:
2803 case Intrinsic::x86_sse2_pslli_q:
2804 case Intrinsic::x86_sse2_pslli_w:
Simon Pilgrim18617d12015-08-05 08:18:00 +00002805 case Intrinsic::x86_avx2_pslli_d:
2806 case Intrinsic::x86_avx2_pslli_q:
2807 case Intrinsic::x86_avx2_pslli_w:
Craig Topper8b831cb2016-11-13 01:51:55 +00002808 case Intrinsic::x86_avx512_pslli_d_512:
2809 case Intrinsic::x86_avx512_pslli_q_512:
2810 case Intrinsic::x86_avx512_pslli_w_512:
Craig Topperbb4069e2017-07-07 23:16:26 +00002811 if (Value *V = simplifyX86immShift(*II, Builder))
Sanjay Patel4b198802016-02-01 22:23:39 +00002812 return replaceInstUsesWith(*II, V);
Simon Pilgrim18617d12015-08-05 08:18:00 +00002813 break;
2814
Simon Pilgrimbecd5e82015-08-13 07:39:03 +00002815 case Intrinsic::x86_sse2_psra_d:
2816 case Intrinsic::x86_sse2_psra_w:
2817 case Intrinsic::x86_avx2_psra_d:
2818 case Intrinsic::x86_avx2_psra_w:
Craig Topper8b831cb2016-11-13 01:51:55 +00002819 case Intrinsic::x86_avx512_psra_q_128:
2820 case Intrinsic::x86_avx512_psra_q_256:
2821 case Intrinsic::x86_avx512_psra_d_512:
2822 case Intrinsic::x86_avx512_psra_q_512:
2823 case Intrinsic::x86_avx512_psra_w_512:
Simon Pilgrimbecd5e82015-08-13 07:39:03 +00002824 case Intrinsic::x86_sse2_psrl_d:
2825 case Intrinsic::x86_sse2_psrl_q:
2826 case Intrinsic::x86_sse2_psrl_w:
2827 case Intrinsic::x86_avx2_psrl_d:
2828 case Intrinsic::x86_avx2_psrl_q:
2829 case Intrinsic::x86_avx2_psrl_w:
Craig Topper8b831cb2016-11-13 01:51:55 +00002830 case Intrinsic::x86_avx512_psrl_d_512:
2831 case Intrinsic::x86_avx512_psrl_q_512:
2832 case Intrinsic::x86_avx512_psrl_w_512:
Simon Pilgrimbecd5e82015-08-13 07:39:03 +00002833 case Intrinsic::x86_sse2_psll_d:
2834 case Intrinsic::x86_sse2_psll_q:
2835 case Intrinsic::x86_sse2_psll_w:
2836 case Intrinsic::x86_avx2_psll_d:
2837 case Intrinsic::x86_avx2_psll_q:
Craig Topper8b831cb2016-11-13 01:51:55 +00002838 case Intrinsic::x86_avx2_psll_w:
2839 case Intrinsic::x86_avx512_psll_d_512:
2840 case Intrinsic::x86_avx512_psll_q_512:
2841 case Intrinsic::x86_avx512_psll_w_512: {
Craig Topperbb4069e2017-07-07 23:16:26 +00002842 if (Value *V = simplifyX86immShift(*II, Builder))
Sanjay Patel4b198802016-02-01 22:23:39 +00002843 return replaceInstUsesWith(*II, V);
Simon Pilgrimbecd5e82015-08-13 07:39:03 +00002844
2845 // SSE2/AVX2 uses only the first 64-bits of the 128-bit vector
2846 // operand to compute the shift amount.
Simon Pilgrim996725e2015-09-19 11:41:53 +00002847 Value *Arg1 = II->getArgOperand(1);
2848 assert(Arg1->getType()->getPrimitiveSizeInBits() == 128 &&
Simon Pilgrimbecd5e82015-08-13 07:39:03 +00002849 "Unexpected packed shift size");
Simon Pilgrim996725e2015-09-19 11:41:53 +00002850 unsigned VWidth = Arg1->getType()->getVectorNumElements();
Simon Pilgrimbecd5e82015-08-13 07:39:03 +00002851
Simon Pilgrim996725e2015-09-19 11:41:53 +00002852 if (Value *V = SimplifyDemandedVectorEltsLow(Arg1, VWidth, VWidth / 2)) {
Simon Pilgrimbecd5e82015-08-13 07:39:03 +00002853 II->setArgOperand(1, V);
2854 return II;
2855 }
2856 break;
2857 }
2858
Simon Pilgrimdb9893f2016-06-07 10:27:15 +00002859 case Intrinsic::x86_avx2_psllv_d:
2860 case Intrinsic::x86_avx2_psllv_d_256:
2861 case Intrinsic::x86_avx2_psllv_q:
2862 case Intrinsic::x86_avx2_psllv_q_256:
Craig Topperb4173a52016-11-13 07:26:19 +00002863 case Intrinsic::x86_avx512_psllv_d_512:
2864 case Intrinsic::x86_avx512_psllv_q_512:
Craig Topper1de753f2016-11-18 06:04:33 +00002865 case Intrinsic::x86_avx512_psllv_w_128:
2866 case Intrinsic::x86_avx512_psllv_w_256:
2867 case Intrinsic::x86_avx512_psllv_w_512:
Simon Pilgrimdb9893f2016-06-07 10:27:15 +00002868 case Intrinsic::x86_avx2_psrav_d:
2869 case Intrinsic::x86_avx2_psrav_d_256:
Craig Topperb4173a52016-11-13 07:26:19 +00002870 case Intrinsic::x86_avx512_psrav_q_128:
2871 case Intrinsic::x86_avx512_psrav_q_256:
2872 case Intrinsic::x86_avx512_psrav_d_512:
2873 case Intrinsic::x86_avx512_psrav_q_512:
Craig Topper1de753f2016-11-18 06:04:33 +00002874 case Intrinsic::x86_avx512_psrav_w_128:
2875 case Intrinsic::x86_avx512_psrav_w_256:
2876 case Intrinsic::x86_avx512_psrav_w_512:
Simon Pilgrimdb9893f2016-06-07 10:27:15 +00002877 case Intrinsic::x86_avx2_psrlv_d:
2878 case Intrinsic::x86_avx2_psrlv_d_256:
2879 case Intrinsic::x86_avx2_psrlv_q:
2880 case Intrinsic::x86_avx2_psrlv_q_256:
Craig Topperb4173a52016-11-13 07:26:19 +00002881 case Intrinsic::x86_avx512_psrlv_d_512:
2882 case Intrinsic::x86_avx512_psrlv_q_512:
Craig Topper1de753f2016-11-18 06:04:33 +00002883 case Intrinsic::x86_avx512_psrlv_w_128:
2884 case Intrinsic::x86_avx512_psrlv_w_256:
2885 case Intrinsic::x86_avx512_psrlv_w_512:
Craig Topperbb4069e2017-07-07 23:16:26 +00002886 if (Value *V = simplifyX86varShift(*II, Builder))
Simon Pilgrimdb9893f2016-06-07 10:27:15 +00002887 return replaceInstUsesWith(*II, V);
2888 break;
2889
Simon Pilgrim6f6b2792017-01-25 14:37:24 +00002890 case Intrinsic::x86_sse2_packssdw_128:
2891 case Intrinsic::x86_sse2_packsswb_128:
2892 case Intrinsic::x86_avx2_packssdw:
2893 case Intrinsic::x86_avx2_packsswb:
Craig Topper3731f4d2017-02-16 07:35:23 +00002894 case Intrinsic::x86_avx512_packssdw_512:
2895 case Intrinsic::x86_avx512_packsswb_512:
Craig Topper4853c432017-07-06 23:18:42 +00002896 if (Value *V = simplifyX86pack(*II, true))
Simon Pilgrim6f6b2792017-01-25 14:37:24 +00002897 return replaceInstUsesWith(*II, V);
2898 break;
2899
2900 case Intrinsic::x86_sse2_packuswb_128:
2901 case Intrinsic::x86_sse41_packusdw:
2902 case Intrinsic::x86_avx2_packusdw:
2903 case Intrinsic::x86_avx2_packuswb:
Craig Topper3731f4d2017-02-16 07:35:23 +00002904 case Intrinsic::x86_avx512_packusdw_512:
2905 case Intrinsic::x86_avx512_packuswb_512:
Craig Topper4853c432017-07-06 23:18:42 +00002906 if (Value *V = simplifyX86pack(*II, false))
Simon Pilgrim6f6b2792017-01-25 14:37:24 +00002907 return replaceInstUsesWith(*II, V);
2908 break;
2909
Craig Topper911025b2018-05-13 21:56:32 +00002910 case Intrinsic::x86_pclmulqdq:
2911 case Intrinsic::x86_pclmulqdq_256:
2912 case Intrinsic::x86_pclmulqdq_512: {
Craig Topperb6122122017-01-26 05:17:13 +00002913 if (auto *C = dyn_cast<ConstantInt>(II->getArgOperand(2))) {
2914 unsigned Imm = C->getZExtValue();
2915
2916 bool MadeChange = false;
2917 Value *Arg0 = II->getArgOperand(0);
2918 Value *Arg1 = II->getArgOperand(1);
2919 unsigned VWidth = Arg0->getType()->getVectorNumElements();
Craig Topperb6122122017-01-26 05:17:13 +00002920
2921 APInt UndefElts1(VWidth, 0);
Craig Topper911025b2018-05-13 21:56:32 +00002922 APInt DemandedElts1 = APInt::getSplat(VWidth,
2923 APInt(2, (Imm & 0x01) ? 2 : 1));
2924 if (Value *V = SimplifyDemandedVectorElts(Arg0, DemandedElts1,
Craig Topperb6122122017-01-26 05:17:13 +00002925 UndefElts1)) {
2926 II->setArgOperand(0, V);
2927 MadeChange = true;
2928 }
2929
2930 APInt UndefElts2(VWidth, 0);
Craig Topper911025b2018-05-13 21:56:32 +00002931 APInt DemandedElts2 = APInt::getSplat(VWidth,
2932 APInt(2, (Imm & 0x10) ? 2 : 1));
2933 if (Value *V = SimplifyDemandedVectorElts(Arg1, DemandedElts2,
Craig Topperb6122122017-01-26 05:17:13 +00002934 UndefElts2)) {
2935 II->setArgOperand(1, V);
2936 MadeChange = true;
2937 }
2938
Craig Topper911025b2018-05-13 21:56:32 +00002939 // If either input elements are undef, the result is zero.
2940 if (DemandedElts1.isSubsetOf(UndefElts1) ||
2941 DemandedElts2.isSubsetOf(UndefElts2))
Craig Topperb6122122017-01-26 05:17:13 +00002942 return replaceInstUsesWith(*II,
2943 ConstantAggregateZero::get(II->getType()));
2944
2945 if (MadeChange)
2946 return II;
2947 }
2948 break;
2949 }
2950
Sanjay Patelc86867c2015-04-16 17:52:13 +00002951 case Intrinsic::x86_sse41_insertps:
Craig Topperbb4069e2017-07-07 23:16:26 +00002952 if (Value *V = simplifyX86insertps(*II, Builder))
Sanjay Patel4b198802016-02-01 22:23:39 +00002953 return replaceInstUsesWith(*II, V);
Sanjay Patelc86867c2015-04-16 17:52:13 +00002954 break;
Simon Pilgrim54fcd622015-07-25 20:41:00 +00002955
Simon Pilgrim61116dd2015-09-17 20:32:45 +00002956 case Intrinsic::x86_sse4a_extrq: {
Simon Pilgrim61116dd2015-09-17 20:32:45 +00002957 Value *Op0 = II->getArgOperand(0);
2958 Value *Op1 = II->getArgOperand(1);
2959 unsigned VWidth0 = Op0->getType()->getVectorNumElements();
2960 unsigned VWidth1 = Op1->getType()->getVectorNumElements();
Simon Pilgrim216b1bf2015-10-17 11:40:05 +00002961 assert(Op0->getType()->getPrimitiveSizeInBits() == 128 &&
2962 Op1->getType()->getPrimitiveSizeInBits() == 128 && VWidth0 == 2 &&
2963 VWidth1 == 16 && "Unexpected operand sizes");
Simon Pilgrim61116dd2015-09-17 20:32:45 +00002964
Simon Pilgrim216b1bf2015-10-17 11:40:05 +00002965 // See if we're dealing with constant values.
2966 Constant *C1 = dyn_cast<Constant>(Op1);
2967 ConstantInt *CILength =
Andrea Di Biagio8df5b9c2016-09-07 12:03:03 +00002968 C1 ? dyn_cast_or_null<ConstantInt>(C1->getAggregateElement((unsigned)0))
Simon Pilgrim216b1bf2015-10-17 11:40:05 +00002969 : nullptr;
2970 ConstantInt *CIIndex =
Andrea Di Biagio8df5b9c2016-09-07 12:03:03 +00002971 C1 ? dyn_cast_or_null<ConstantInt>(C1->getAggregateElement((unsigned)1))
Simon Pilgrim216b1bf2015-10-17 11:40:05 +00002972 : nullptr;
2973
2974 // Attempt to simplify to a constant, shuffle vector or EXTRQI call.
Craig Topperbb4069e2017-07-07 23:16:26 +00002975 if (Value *V = simplifyX86extrq(*II, Op0, CILength, CIIndex, Builder))
Sanjay Patel4b198802016-02-01 22:23:39 +00002976 return replaceInstUsesWith(*II, V);
Simon Pilgrim216b1bf2015-10-17 11:40:05 +00002977
2978 // EXTRQ only uses the lowest 64-bits of the first 128-bit vector
2979 // operands and the lowest 16-bits of the second.
Simon Pilgrim1c9a9f22016-04-24 17:57:27 +00002980 bool MadeChange = false;
Simon Pilgrim61116dd2015-09-17 20:32:45 +00002981 if (Value *V = SimplifyDemandedVectorEltsLow(Op0, VWidth0, 1)) {
2982 II->setArgOperand(0, V);
Simon Pilgrim1c9a9f22016-04-24 17:57:27 +00002983 MadeChange = true;
Simon Pilgrim61116dd2015-09-17 20:32:45 +00002984 }
2985 if (Value *V = SimplifyDemandedVectorEltsLow(Op1, VWidth1, 2)) {
2986 II->setArgOperand(1, V);
Simon Pilgrim1c9a9f22016-04-24 17:57:27 +00002987 MadeChange = true;
Simon Pilgrim61116dd2015-09-17 20:32:45 +00002988 }
Simon Pilgrim1c9a9f22016-04-24 17:57:27 +00002989 if (MadeChange)
2990 return II;
Simon Pilgrim61116dd2015-09-17 20:32:45 +00002991 break;
2992 }
2993
2994 case Intrinsic::x86_sse4a_extrqi: {
Simon Pilgrim216b1bf2015-10-17 11:40:05 +00002995 // EXTRQI: Extract Length bits starting from Index. Zero pad the remaining
2996 // bits of the lower 64-bits. The upper 64-bits are undefined.
2997 Value *Op0 = II->getArgOperand(0);
2998 unsigned VWidth = Op0->getType()->getVectorNumElements();
2999 assert(Op0->getType()->getPrimitiveSizeInBits() == 128 && VWidth == 2 &&
3000 "Unexpected operand size");
Simon Pilgrim61116dd2015-09-17 20:32:45 +00003001
Simon Pilgrim216b1bf2015-10-17 11:40:05 +00003002 // See if we're dealing with constant values.
3003 ConstantInt *CILength = dyn_cast<ConstantInt>(II->getArgOperand(1));
3004 ConstantInt *CIIndex = dyn_cast<ConstantInt>(II->getArgOperand(2));
3005
3006 // Attempt to simplify to a constant or shuffle vector.
Craig Topperbb4069e2017-07-07 23:16:26 +00003007 if (Value *V = simplifyX86extrq(*II, Op0, CILength, CIIndex, Builder))
Sanjay Patel4b198802016-02-01 22:23:39 +00003008 return replaceInstUsesWith(*II, V);
Simon Pilgrim216b1bf2015-10-17 11:40:05 +00003009
3010 // EXTRQI only uses the lowest 64-bits of the first 128-bit vector
3011 // operand.
3012 if (Value *V = SimplifyDemandedVectorEltsLow(Op0, VWidth, 1)) {
Simon Pilgrim61116dd2015-09-17 20:32:45 +00003013 II->setArgOperand(0, V);
3014 return II;
3015 }
3016 break;
3017 }
3018
3019 case Intrinsic::x86_sse4a_insertq: {
Simon Pilgrim216b1bf2015-10-17 11:40:05 +00003020 Value *Op0 = II->getArgOperand(0);
3021 Value *Op1 = II->getArgOperand(1);
3022 unsigned VWidth = Op0->getType()->getVectorNumElements();
3023 assert(Op0->getType()->getPrimitiveSizeInBits() == 128 &&
3024 Op1->getType()->getPrimitiveSizeInBits() == 128 && VWidth == 2 &&
3025 Op1->getType()->getVectorNumElements() == 2 &&
3026 "Unexpected operand size");
Simon Pilgrim61116dd2015-09-17 20:32:45 +00003027
Simon Pilgrim216b1bf2015-10-17 11:40:05 +00003028 // See if we're dealing with constant values.
3029 Constant *C1 = dyn_cast<Constant>(Op1);
3030 ConstantInt *CI11 =
Andrea Di Biagiof3fd3162016-09-07 12:47:53 +00003031 C1 ? dyn_cast_or_null<ConstantInt>(C1->getAggregateElement((unsigned)1))
Simon Pilgrim216b1bf2015-10-17 11:40:05 +00003032 : nullptr;
3033
3034 // Attempt to simplify to a constant, shuffle vector or INSERTQI call.
3035 if (CI11) {
Benjamin Kramer46e38f32016-06-08 10:01:20 +00003036 const APInt &V11 = CI11->getValue();
Simon Pilgrim216b1bf2015-10-17 11:40:05 +00003037 APInt Len = V11.zextOrTrunc(6);
3038 APInt Idx = V11.lshr(8).zextOrTrunc(6);
Craig Topperbb4069e2017-07-07 23:16:26 +00003039 if (Value *V = simplifyX86insertq(*II, Op0, Op1, Len, Idx, Builder))
Sanjay Patel4b198802016-02-01 22:23:39 +00003040 return replaceInstUsesWith(*II, V);
Simon Pilgrim216b1bf2015-10-17 11:40:05 +00003041 }
3042
3043 // INSERTQ only uses the lowest 64-bits of the first 128-bit vector
3044 // operand.
3045 if (Value *V = SimplifyDemandedVectorEltsLow(Op0, VWidth, 1)) {
Simon Pilgrim61116dd2015-09-17 20:32:45 +00003046 II->setArgOperand(0, V);
3047 return II;
3048 }
3049 break;
3050 }
3051
Filipe Cabecinhas1a805952014-04-24 00:38:14 +00003052 case Intrinsic::x86_sse4a_insertqi: {
Simon Pilgrim216b1bf2015-10-17 11:40:05 +00003053 // INSERTQI: Extract lowest Length bits from lower half of second source and
3054 // insert over first source starting at Index bit. The upper 64-bits are
3055 // undefined.
Simon Pilgrim61116dd2015-09-17 20:32:45 +00003056 Value *Op0 = II->getArgOperand(0);
3057 Value *Op1 = II->getArgOperand(1);
3058 unsigned VWidth0 = Op0->getType()->getVectorNumElements();
3059 unsigned VWidth1 = Op1->getType()->getVectorNumElements();
Simon Pilgrim216b1bf2015-10-17 11:40:05 +00003060 assert(Op0->getType()->getPrimitiveSizeInBits() == 128 &&
3061 Op1->getType()->getPrimitiveSizeInBits() == 128 && VWidth0 == 2 &&
3062 VWidth1 == 2 && "Unexpected operand sizes");
Simon Pilgrim61116dd2015-09-17 20:32:45 +00003063
Simon Pilgrim216b1bf2015-10-17 11:40:05 +00003064 // See if we're dealing with constant values.
3065 ConstantInt *CILength = dyn_cast<ConstantInt>(II->getArgOperand(2));
3066 ConstantInt *CIIndex = dyn_cast<ConstantInt>(II->getArgOperand(3));
3067
3068 // Attempt to simplify to a constant or shuffle vector.
3069 if (CILength && CIIndex) {
3070 APInt Len = CILength->getValue().zextOrTrunc(6);
3071 APInt Idx = CIIndex->getValue().zextOrTrunc(6);
Craig Topperbb4069e2017-07-07 23:16:26 +00003072 if (Value *V = simplifyX86insertq(*II, Op0, Op1, Len, Idx, Builder))
Sanjay Patel4b198802016-02-01 22:23:39 +00003073 return replaceInstUsesWith(*II, V);
Simon Pilgrim216b1bf2015-10-17 11:40:05 +00003074 }
3075
3076 // INSERTQI only uses the lowest 64-bits of the first two 128-bit vector
3077 // operands.
Simon Pilgrim1c9a9f22016-04-24 17:57:27 +00003078 bool MadeChange = false;
Simon Pilgrim61116dd2015-09-17 20:32:45 +00003079 if (Value *V = SimplifyDemandedVectorEltsLow(Op0, VWidth0, 1)) {
3080 II->setArgOperand(0, V);
Simon Pilgrim1c9a9f22016-04-24 17:57:27 +00003081 MadeChange = true;
Simon Pilgrim61116dd2015-09-17 20:32:45 +00003082 }
Simon Pilgrim61116dd2015-09-17 20:32:45 +00003083 if (Value *V = SimplifyDemandedVectorEltsLow(Op1, VWidth1, 1)) {
3084 II->setArgOperand(1, V);
Simon Pilgrim1c9a9f22016-04-24 17:57:27 +00003085 MadeChange = true;
Simon Pilgrim61116dd2015-09-17 20:32:45 +00003086 }
Simon Pilgrim1c9a9f22016-04-24 17:57:27 +00003087 if (MadeChange)
3088 return II;
Filipe Cabecinhas1a805952014-04-24 00:38:14 +00003089 break;
3090 }
3091
Filipe Cabecinhas82ac07c2014-05-27 03:42:20 +00003092 case Intrinsic::x86_sse41_pblendvb:
3093 case Intrinsic::x86_sse41_blendvps:
3094 case Intrinsic::x86_sse41_blendvpd:
3095 case Intrinsic::x86_avx_blendv_ps_256:
3096 case Intrinsic::x86_avx_blendv_pd_256:
3097 case Intrinsic::x86_avx2_pblendvb: {
Sanjay Patel296d35a2018-09-15 14:25:44 +00003098 // fold (blend A, A, Mask) -> A
Simon Pilgrim8c049d52015-08-12 08:08:56 +00003099 Value *Op0 = II->getArgOperand(0);
3100 Value *Op1 = II->getArgOperand(1);
Filipe Cabecinhas82ac07c2014-05-27 03:42:20 +00003101 Value *Mask = II->getArgOperand(2);
Simon Pilgrim8c049d52015-08-12 08:08:56 +00003102 if (Op0 == Op1)
Sanjay Patel4b198802016-02-01 22:23:39 +00003103 return replaceInstUsesWith(CI, Op0);
Simon Pilgrim8c049d52015-08-12 08:08:56 +00003104
3105 // Zero Mask - select 1st argument.
Simon Pilgrim93f59f52015-08-12 08:23:36 +00003106 if (isa<ConstantAggregateZero>(Mask))
Sanjay Patel4b198802016-02-01 22:23:39 +00003107 return replaceInstUsesWith(CI, Op0);
Simon Pilgrim8c049d52015-08-12 08:08:56 +00003108
3109 // Constant Mask - select 1st/2nd argument lane based on top bit of mask.
Sanjay Patel368ac5d2016-02-21 17:29:33 +00003110 if (auto *ConstantMask = dyn_cast<ConstantDataVector>(Mask)) {
3111 Constant *NewSelector = getNegativeIsTrueBoolVec(ConstantMask);
Simon Pilgrim8c049d52015-08-12 08:08:56 +00003112 return SelectInst::Create(NewSelector, Op1, Op0, "blendv");
Filipe Cabecinhas82ac07c2014-05-27 03:42:20 +00003113 }
Sanjay Patel296d35a2018-09-15 14:25:44 +00003114
3115 // Convert to a vector select if we can bypass casts and find a boolean
3116 // vector condition value.
3117 Value *BoolVec;
Sanjay Patel09e02fb2018-09-22 14:43:55 +00003118 Mask = peekThroughBitcast(Mask);
3119 if (match(Mask, m_SExt(m_Value(BoolVec))) &&
3120 BoolVec->getType()->isVectorTy() &&
3121 BoolVec->getType()->getScalarSizeInBits() == 1) {
3122 assert(Mask->getType()->getPrimitiveSizeInBits() ==
3123 II->getType()->getPrimitiveSizeInBits() &&
3124 "Not expecting mask and operands with different sizes");
3125
3126 unsigned NumMaskElts = Mask->getType()->getVectorNumElements();
3127 unsigned NumOperandElts = II->getType()->getVectorNumElements();
3128 if (NumMaskElts == NumOperandElts)
Sanjay Patel296d35a2018-09-15 14:25:44 +00003129 return SelectInst::Create(BoolVec, Op1, Op0);
Sanjay Patel09e02fb2018-09-22 14:43:55 +00003130
3131 // If the mask has less elements than the operands, each mask bit maps to
3132 // multiple elements of the operands. Bitcast back and forth.
3133 if (NumMaskElts < NumOperandElts) {
3134 Value *CastOp0 = Builder.CreateBitCast(Op0, Mask->getType());
3135 Value *CastOp1 = Builder.CreateBitCast(Op1, Mask->getType());
3136 Value *Sel = Builder.CreateSelect(BoolVec, CastOp1, CastOp0);
3137 return new BitCastInst(Sel, II->getType());
3138 }
Sanjay Patel296d35a2018-09-15 14:25:44 +00003139 }
3140
Simon Pilgrim8c049d52015-08-12 08:08:56 +00003141 break;
Filipe Cabecinhas82ac07c2014-05-27 03:42:20 +00003142 }
3143
Andrea Di Biagio0594e2a2015-09-30 16:44:39 +00003144 case Intrinsic::x86_ssse3_pshuf_b_128:
Simon Pilgrimc0c56e72016-04-24 17:00:34 +00003145 case Intrinsic::x86_avx2_pshuf_b:
Simon Pilgrima22c3a12017-01-18 13:44:04 +00003146 case Intrinsic::x86_avx512_pshuf_b_512:
Craig Topperbb4069e2017-07-07 23:16:26 +00003147 if (Value *V = simplifyX86pshufb(*II, Builder))
Simon Pilgrimc0c56e72016-04-24 17:00:34 +00003148 return replaceInstUsesWith(*II, V);
3149 break;
Andrea Di Biagio0594e2a2015-09-30 16:44:39 +00003150
Rafael Espindolabad3f772014-04-21 22:06:04 +00003151 case Intrinsic::x86_avx_vpermilvar_ps:
3152 case Intrinsic::x86_avx_vpermilvar_ps_256:
Craig Topper58917f32016-12-11 01:59:36 +00003153 case Intrinsic::x86_avx512_vpermilvar_ps_512:
Rafael Espindolabad3f772014-04-21 22:06:04 +00003154 case Intrinsic::x86_avx_vpermilvar_pd:
Simon Pilgrim2f6097d2016-04-24 17:23:46 +00003155 case Intrinsic::x86_avx_vpermilvar_pd_256:
Simon Pilgrima22c3a12017-01-18 13:44:04 +00003156 case Intrinsic::x86_avx512_vpermilvar_pd_512:
Craig Topperbb4069e2017-07-07 23:16:26 +00003157 if (Value *V = simplifyX86vpermilvar(*II, Builder))
Simon Pilgrim2f6097d2016-04-24 17:23:46 +00003158 return replaceInstUsesWith(*II, V);
3159 break;
Rafael Espindolabad3f772014-04-21 22:06:04 +00003160
Simon Pilgrim8cddf8b2016-05-01 16:41:22 +00003161 case Intrinsic::x86_avx2_permd:
3162 case Intrinsic::x86_avx2_permps:
Craig Toppere4c045b2018-05-20 23:34:04 +00003163 case Intrinsic::x86_avx512_permvar_df_256:
3164 case Intrinsic::x86_avx512_permvar_df_512:
3165 case Intrinsic::x86_avx512_permvar_di_256:
3166 case Intrinsic::x86_avx512_permvar_di_512:
3167 case Intrinsic::x86_avx512_permvar_hi_128:
3168 case Intrinsic::x86_avx512_permvar_hi_256:
3169 case Intrinsic::x86_avx512_permvar_hi_512:
3170 case Intrinsic::x86_avx512_permvar_qi_128:
3171 case Intrinsic::x86_avx512_permvar_qi_256:
3172 case Intrinsic::x86_avx512_permvar_qi_512:
3173 case Intrinsic::x86_avx512_permvar_sf_512:
3174 case Intrinsic::x86_avx512_permvar_si_512:
Craig Topperbb4069e2017-07-07 23:16:26 +00003175 if (Value *V = simplifyX86vpermv(*II, Builder))
Simon Pilgrim8cddf8b2016-05-01 16:41:22 +00003176 return replaceInstUsesWith(*II, V);
3177 break;
3178
Sanjay Patel98a71502016-02-29 23:16:48 +00003179 case Intrinsic::x86_avx_maskload_ps:
Sanjay Patel6f2c01f2016-02-29 23:59:00 +00003180 case Intrinsic::x86_avx_maskload_pd:
3181 case Intrinsic::x86_avx_maskload_ps_256:
3182 case Intrinsic::x86_avx_maskload_pd_256:
3183 case Intrinsic::x86_avx2_maskload_d:
3184 case Intrinsic::x86_avx2_maskload_q:
3185 case Intrinsic::x86_avx2_maskload_d_256:
3186 case Intrinsic::x86_avx2_maskload_q_256:
Sanjay Patel98a71502016-02-29 23:16:48 +00003187 if (Instruction *I = simplifyX86MaskedLoad(*II, *this))
3188 return I;
3189 break;
3190
Sanjay Patelc4acbae2016-03-12 15:16:59 +00003191 case Intrinsic::x86_sse2_maskmov_dqu:
Sanjay Patel1ace9932016-02-26 21:04:14 +00003192 case Intrinsic::x86_avx_maskstore_ps:
3193 case Intrinsic::x86_avx_maskstore_pd:
3194 case Intrinsic::x86_avx_maskstore_ps_256:
3195 case Intrinsic::x86_avx_maskstore_pd_256:
Sanjay Patelfc7e7eb2016-02-26 21:51:44 +00003196 case Intrinsic::x86_avx2_maskstore_d:
3197 case Intrinsic::x86_avx2_maskstore_q:
3198 case Intrinsic::x86_avx2_maskstore_d_256:
3199 case Intrinsic::x86_avx2_maskstore_q_256:
Sanjay Patel1ace9932016-02-26 21:04:14 +00003200 if (simplifyX86MaskedStore(*II, *this))
3201 return nullptr;
3202 break;
3203
Sanjay Patelbe23a912019-02-01 14:14:47 +00003204 case Intrinsic::x86_addcarry_32:
3205 case Intrinsic::x86_addcarry_64:
3206 if (Value *V = simplifyX86addcarry(*II, Builder))
3207 return replaceInstUsesWith(*II, V);
3208 break;
3209
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003210 case Intrinsic::ppc_altivec_vperm:
3211 // Turn vperm(V1,V2,mask) -> shuffle(V1,V2,mask) if mask is a constant.
Bill Schmidta1184632014-06-05 19:46:04 +00003212 // Note that ppc_altivec_vperm has a big-endian bias, so when creating
3213 // a vectorshuffle for little endian, we must undo the transformation
3214 // performed on vec_perm in altivec.h. That is, we must complement
3215 // the permutation mask with respect to 31 and reverse the order of
3216 // V1 and V2.
Chris Lattner0256be92012-01-27 03:08:05 +00003217 if (Constant *Mask = dyn_cast<Constant>(II->getArgOperand(2))) {
3218 assert(Mask->getType()->getVectorNumElements() == 16 &&
3219 "Bad type for intrinsic!");
Jim Grosbach7815f562012-02-03 00:07:04 +00003220
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003221 // Check that all of the elements are integer constants or undefs.
3222 bool AllEltsOk = true;
3223 for (unsigned i = 0; i != 16; ++i) {
Chris Lattner0256be92012-01-27 03:08:05 +00003224 Constant *Elt = Mask->getAggregateElement(i);
Craig Topperf40110f2014-04-25 05:29:35 +00003225 if (!Elt || !(isa<ConstantInt>(Elt) || isa<UndefValue>(Elt))) {
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003226 AllEltsOk = false;
3227 break;
3228 }
3229 }
Jim Grosbach7815f562012-02-03 00:07:04 +00003230
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003231 if (AllEltsOk) {
3232 // Cast the input vectors to byte vectors.
Craig Topperbb4069e2017-07-07 23:16:26 +00003233 Value *Op0 = Builder.CreateBitCast(II->getArgOperand(0),
3234 Mask->getType());
3235 Value *Op1 = Builder.CreateBitCast(II->getArgOperand(1),
3236 Mask->getType());
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003237 Value *Result = UndefValue::get(Op0->getType());
Jim Grosbach7815f562012-02-03 00:07:04 +00003238
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003239 // Only extract each element once.
3240 Value *ExtractedElts[32];
3241 memset(ExtractedElts, 0, sizeof(ExtractedElts));
Jim Grosbach7815f562012-02-03 00:07:04 +00003242
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003243 for (unsigned i = 0; i != 16; ++i) {
Chris Lattner0256be92012-01-27 03:08:05 +00003244 if (isa<UndefValue>(Mask->getAggregateElement(i)))
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003245 continue;
Jim Grosbach7815f562012-02-03 00:07:04 +00003246 unsigned Idx =
Chris Lattner0256be92012-01-27 03:08:05 +00003247 cast<ConstantInt>(Mask->getAggregateElement(i))->getZExtValue();
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003248 Idx &= 31; // Match the hardware behavior.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003249 if (DL.isLittleEndian())
Bill Schmidta1184632014-06-05 19:46:04 +00003250 Idx = 31 - Idx;
Jim Grosbach7815f562012-02-03 00:07:04 +00003251
Craig Topperf40110f2014-04-25 05:29:35 +00003252 if (!ExtractedElts[Idx]) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003253 Value *Op0ToUse = (DL.isLittleEndian()) ? Op1 : Op0;
3254 Value *Op1ToUse = (DL.isLittleEndian()) ? Op0 : Op1;
Jim Grosbach7815f562012-02-03 00:07:04 +00003255 ExtractedElts[Idx] =
Craig Topperbb4069e2017-07-07 23:16:26 +00003256 Builder.CreateExtractElement(Idx < 16 ? Op0ToUse : Op1ToUse,
3257 Builder.getInt32(Idx&15));
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003258 }
Jim Grosbach7815f562012-02-03 00:07:04 +00003259
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003260 // Insert this value into the result vector.
Craig Topperbb4069e2017-07-07 23:16:26 +00003261 Result = Builder.CreateInsertElement(Result, ExtractedElts[Idx],
3262 Builder.getInt32(i));
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003263 }
3264 return CastInst::Create(Instruction::BitCast, Result, CI.getType());
3265 }
3266 }
3267 break;
3268
Alexandros Lamprineas61f0ba12018-05-31 12:19:18 +00003269 case Intrinsic::arm_neon_vld1: {
3270 unsigned MemAlign = getKnownAlignment(II->getArgOperand(0),
3271 DL, II, &AC, &DT);
3272 if (Value *V = simplifyNeonVld1(*II, MemAlign, Builder))
3273 return replaceInstUsesWith(*II, V);
3274 break;
3275 }
3276
Bob Wilsona4e231c2010-10-22 21:41:48 +00003277 case Intrinsic::arm_neon_vld2:
3278 case Intrinsic::arm_neon_vld3:
3279 case Intrinsic::arm_neon_vld4:
3280 case Intrinsic::arm_neon_vld2lane:
3281 case Intrinsic::arm_neon_vld3lane:
3282 case Intrinsic::arm_neon_vld4lane:
3283 case Intrinsic::arm_neon_vst1:
3284 case Intrinsic::arm_neon_vst2:
3285 case Intrinsic::arm_neon_vst3:
3286 case Intrinsic::arm_neon_vst4:
3287 case Intrinsic::arm_neon_vst2lane:
3288 case Intrinsic::arm_neon_vst3lane:
3289 case Intrinsic::arm_neon_vst4lane: {
Justin Bogner99798402016-08-05 01:06:44 +00003290 unsigned MemAlign =
Daniel Jasperaec2fa32016-12-19 08:22:17 +00003291 getKnownAlignment(II->getArgOperand(0), DL, II, &AC, &DT);
Bob Wilsona4e231c2010-10-22 21:41:48 +00003292 unsigned AlignArg = II->getNumArgOperands() - 1;
3293 ConstantInt *IntrAlign = dyn_cast<ConstantInt>(II->getArgOperand(AlignArg));
3294 if (IntrAlign && IntrAlign->getZExtValue() < MemAlign) {
3295 II->setArgOperand(AlignArg,
3296 ConstantInt::get(Type::getInt32Ty(II->getContext()),
3297 MemAlign, false));
3298 return II;
3299 }
3300 break;
3301 }
3302
Alexandros Lamprineas52457d32018-05-30 14:38:50 +00003303 case Intrinsic::arm_neon_vtbl1:
3304 case Intrinsic::aarch64_neon_tbl1:
3305 if (Value *V = simplifyNeonTbl1(*II, Builder))
3306 return replaceInstUsesWith(*II, V);
3307 break;
3308
Lang Hames3a90fab2012-05-01 00:20:38 +00003309 case Intrinsic::arm_neon_vmulls:
Tim Northover00ed9962014-03-29 10:18:08 +00003310 case Intrinsic::arm_neon_vmullu:
Tim Northover3b0846e2014-05-24 12:50:23 +00003311 case Intrinsic::aarch64_neon_smull:
3312 case Intrinsic::aarch64_neon_umull: {
Lang Hames3a90fab2012-05-01 00:20:38 +00003313 Value *Arg0 = II->getArgOperand(0);
3314 Value *Arg1 = II->getArgOperand(1);
3315
3316 // Handle mul by zero first:
3317 if (isa<ConstantAggregateZero>(Arg0) || isa<ConstantAggregateZero>(Arg1)) {
Sanjay Patel4b198802016-02-01 22:23:39 +00003318 return replaceInstUsesWith(CI, ConstantAggregateZero::get(II->getType()));
Lang Hames3a90fab2012-05-01 00:20:38 +00003319 }
3320
3321 // Check for constant LHS & RHS - in this case we just simplify.
Tim Northover00ed9962014-03-29 10:18:08 +00003322 bool Zext = (II->getIntrinsicID() == Intrinsic::arm_neon_vmullu ||
Tim Northover3b0846e2014-05-24 12:50:23 +00003323 II->getIntrinsicID() == Intrinsic::aarch64_neon_umull);
Lang Hames3a90fab2012-05-01 00:20:38 +00003324 VectorType *NewVT = cast<VectorType>(II->getType());
Benjamin Kramer92040952014-02-13 18:23:24 +00003325 if (Constant *CV0 = dyn_cast<Constant>(Arg0)) {
3326 if (Constant *CV1 = dyn_cast<Constant>(Arg1)) {
3327 CV0 = ConstantExpr::getIntegerCast(CV0, NewVT, /*isSigned=*/!Zext);
3328 CV1 = ConstantExpr::getIntegerCast(CV1, NewVT, /*isSigned=*/!Zext);
3329
Sanjay Patel4b198802016-02-01 22:23:39 +00003330 return replaceInstUsesWith(CI, ConstantExpr::getMul(CV0, CV1));
Lang Hames3a90fab2012-05-01 00:20:38 +00003331 }
3332
Alp Tokercb402912014-01-24 17:20:08 +00003333 // Couldn't simplify - canonicalize constant to the RHS.
Lang Hames3a90fab2012-05-01 00:20:38 +00003334 std::swap(Arg0, Arg1);
3335 }
3336
3337 // Handle mul by one:
Benjamin Kramer92040952014-02-13 18:23:24 +00003338 if (Constant *CV1 = dyn_cast<Constant>(Arg1))
Lang Hames3a90fab2012-05-01 00:20:38 +00003339 if (ConstantInt *Splat =
Benjamin Kramer92040952014-02-13 18:23:24 +00003340 dyn_cast_or_null<ConstantInt>(CV1->getSplatValue()))
3341 if (Splat->isOne())
3342 return CastInst::CreateIntegerCast(Arg0, II->getType(),
3343 /*isSigned=*/!Zext);
Lang Hames3a90fab2012-05-01 00:20:38 +00003344
3345 break;
3346 }
Chad Rosier274d72f2018-05-24 15:26:42 +00003347 case Intrinsic::arm_neon_aesd:
3348 case Intrinsic::arm_neon_aese:
3349 case Intrinsic::aarch64_crypto_aesd:
3350 case Intrinsic::aarch64_crypto_aese: {
3351 Value *DataArg = II->getArgOperand(0);
3352 Value *KeyArg = II->getArgOperand(1);
3353
3354 // Try to use the builtin XOR in AESE and AESD to eliminate a prior XOR
3355 Value *Data, *Key;
3356 if (match(KeyArg, m_ZeroInt()) &&
3357 match(DataArg, m_Xor(m_Value(Data), m_Value(Key)))) {
3358 II->setArgOperand(0, Data);
3359 II->setArgOperand(1, Key);
3360 return II;
3361 }
3362 break;
3363 }
Matt Arsenaultbef34e22016-01-22 21:30:34 +00003364 case Intrinsic::amdgcn_rcp: {
Matt Arsenault4c7795d2017-03-24 19:04:57 +00003365 Value *Src = II->getArgOperand(0);
3366
3367 // TODO: Move to ConstantFolding/InstSimplify?
3368 if (isa<UndefValue>(Src))
3369 return replaceInstUsesWith(CI, Src);
3370
3371 if (const ConstantFP *C = dyn_cast<ConstantFP>(Src)) {
Matt Arsenaulta0050b02014-06-19 01:19:19 +00003372 const APFloat &ArgVal = C->getValueAPF();
3373 APFloat Val(ArgVal.getSemantics(), 1.0);
3374 APFloat::opStatus Status = Val.divide(ArgVal,
3375 APFloat::rmNearestTiesToEven);
3376 // Only do this if it was exact and therefore not dependent on the
3377 // rounding mode.
3378 if (Status == APFloat::opOK)
Sanjay Patel4b198802016-02-01 22:23:39 +00003379 return replaceInstUsesWith(CI, ConstantFP::get(II->getContext(), Val));
Matt Arsenaulta0050b02014-06-19 01:19:19 +00003380 }
3381
3382 break;
3383 }
Matt Arsenault4c7795d2017-03-24 19:04:57 +00003384 case Intrinsic::amdgcn_rsq: {
3385 Value *Src = II->getArgOperand(0);
3386
3387 // TODO: Move to ConstantFolding/InstSimplify?
3388 if (isa<UndefValue>(Src))
3389 return replaceInstUsesWith(CI, Src);
3390 break;
3391 }
Matt Arsenault2fe4fbc2016-03-30 22:28:52 +00003392 case Intrinsic::amdgcn_frexp_mant:
3393 case Intrinsic::amdgcn_frexp_exp: {
Matt Arsenault5cd4f8f2016-03-30 22:28:26 +00003394 Value *Src = II->getArgOperand(0);
3395 if (const ConstantFP *C = dyn_cast<ConstantFP>(Src)) {
3396 int Exp;
3397 APFloat Significand = frexp(C->getValueAPF(), Exp,
3398 APFloat::rmNearestTiesToEven);
3399
Matt Arsenault2fe4fbc2016-03-30 22:28:52 +00003400 if (II->getIntrinsicID() == Intrinsic::amdgcn_frexp_mant) {
3401 return replaceInstUsesWith(CI, ConstantFP::get(II->getContext(),
3402 Significand));
3403 }
3404
3405 // Match instruction special case behavior.
3406 if (Exp == APFloat::IEK_NaN || Exp == APFloat::IEK_Inf)
3407 Exp = 0;
3408
3409 return replaceInstUsesWith(CI, ConstantInt::get(II->getType(), Exp));
3410 }
3411
3412 if (isa<UndefValue>(Src))
3413 return replaceInstUsesWith(CI, UndefValue::get(II->getType()));
Matt Arsenault5cd4f8f2016-03-30 22:28:26 +00003414
3415 break;
3416 }
Matt Arsenault46a03822016-09-03 07:06:58 +00003417 case Intrinsic::amdgcn_class: {
3418 enum {
3419 S_NAN = 1 << 0, // Signaling NaN
3420 Q_NAN = 1 << 1, // Quiet NaN
3421 N_INFINITY = 1 << 2, // Negative infinity
3422 N_NORMAL = 1 << 3, // Negative normal
3423 N_SUBNORMAL = 1 << 4, // Negative subnormal
3424 N_ZERO = 1 << 5, // Negative zero
3425 P_ZERO = 1 << 6, // Positive zero
3426 P_SUBNORMAL = 1 << 7, // Positive subnormal
3427 P_NORMAL = 1 << 8, // Positive normal
3428 P_INFINITY = 1 << 9 // Positive infinity
3429 };
3430
3431 const uint32_t FullMask = S_NAN | Q_NAN | N_INFINITY | N_NORMAL |
3432 N_SUBNORMAL | N_ZERO | P_ZERO | P_SUBNORMAL | P_NORMAL | P_INFINITY;
3433
3434 Value *Src0 = II->getArgOperand(0);
3435 Value *Src1 = II->getArgOperand(1);
3436 const ConstantInt *CMask = dyn_cast<ConstantInt>(Src1);
3437 if (!CMask) {
3438 if (isa<UndefValue>(Src0))
3439 return replaceInstUsesWith(*II, UndefValue::get(II->getType()));
3440
3441 if (isa<UndefValue>(Src1))
3442 return replaceInstUsesWith(*II, ConstantInt::get(II->getType(), false));
3443 break;
3444 }
3445
3446 uint32_t Mask = CMask->getZExtValue();
3447
3448 // If all tests are made, it doesn't matter what the value is.
3449 if ((Mask & FullMask) == FullMask)
3450 return replaceInstUsesWith(*II, ConstantInt::get(II->getType(), true));
3451
3452 if ((Mask & FullMask) == 0)
3453 return replaceInstUsesWith(*II, ConstantInt::get(II->getType(), false));
3454
3455 if (Mask == (S_NAN | Q_NAN)) {
3456 // Equivalent of isnan. Replace with standard fcmp.
Craig Topperbb4069e2017-07-07 23:16:26 +00003457 Value *FCmp = Builder.CreateFCmpUNO(Src0, Src0);
Matt Arsenault46a03822016-09-03 07:06:58 +00003458 FCmp->takeName(II);
3459 return replaceInstUsesWith(*II, FCmp);
3460 }
3461
Matt Arsenaultd35f46c2018-08-10 18:58:49 +00003462 if (Mask == (N_ZERO | P_ZERO)) {
3463 // Equivalent of == 0.
3464 Value *FCmp = Builder.CreateFCmpOEQ(
3465 Src0, ConstantFP::get(Src0->getType(), 0.0));
3466
3467 FCmp->takeName(II);
3468 return replaceInstUsesWith(*II, FCmp);
3469 }
3470
Matt Arsenault10de2772018-08-28 18:10:02 +00003471 // fp_class (nnan x), qnan|snan|other -> fp_class (nnan x), other
3472 if (((Mask & S_NAN) || (Mask & Q_NAN)) && isKnownNeverNaN(Src0, &TLI)) {
3473 II->setArgOperand(1, ConstantInt::get(Src1->getType(),
3474 Mask & ~(S_NAN | Q_NAN)));
3475 return II;
3476 }
3477
Matt Arsenault46a03822016-09-03 07:06:58 +00003478 const ConstantFP *CVal = dyn_cast<ConstantFP>(Src0);
3479 if (!CVal) {
3480 if (isa<UndefValue>(Src0))
3481 return replaceInstUsesWith(*II, UndefValue::get(II->getType()));
3482
3483 // Clamp mask to used bits
3484 if ((Mask & FullMask) != Mask) {
Craig Topperbb4069e2017-07-07 23:16:26 +00003485 CallInst *NewCall = Builder.CreateCall(II->getCalledFunction(),
Matt Arsenault46a03822016-09-03 07:06:58 +00003486 { Src0, ConstantInt::get(Src1->getType(), Mask & FullMask) }
3487 );
3488
3489 NewCall->takeName(II);
3490 return replaceInstUsesWith(*II, NewCall);
3491 }
3492
3493 break;
3494 }
3495
3496 const APFloat &Val = CVal->getValueAPF();
3497
3498 bool Result =
3499 ((Mask & S_NAN) && Val.isNaN() && Val.isSignaling()) ||
3500 ((Mask & Q_NAN) && Val.isNaN() && !Val.isSignaling()) ||
3501 ((Mask & N_INFINITY) && Val.isInfinity() && Val.isNegative()) ||
3502 ((Mask & N_NORMAL) && Val.isNormal() && Val.isNegative()) ||
3503 ((Mask & N_SUBNORMAL) && Val.isDenormal() && Val.isNegative()) ||
3504 ((Mask & N_ZERO) && Val.isZero() && Val.isNegative()) ||
3505 ((Mask & P_ZERO) && Val.isZero() && !Val.isNegative()) ||
3506 ((Mask & P_SUBNORMAL) && Val.isDenormal() && !Val.isNegative()) ||
3507 ((Mask & P_NORMAL) && Val.isNormal() && !Val.isNegative()) ||
3508 ((Mask & P_INFINITY) && Val.isInfinity() && !Val.isNegative());
3509
3510 return replaceInstUsesWith(*II, ConstantInt::get(II->getType(), Result));
3511 }
Matt Arsenault1f17c662017-02-22 00:27:34 +00003512 case Intrinsic::amdgcn_cvt_pkrtz: {
3513 Value *Src0 = II->getArgOperand(0);
3514 Value *Src1 = II->getArgOperand(1);
3515 if (const ConstantFP *C0 = dyn_cast<ConstantFP>(Src0)) {
3516 if (const ConstantFP *C1 = dyn_cast<ConstantFP>(Src1)) {
3517 const fltSemantics &HalfSem
3518 = II->getType()->getScalarType()->getFltSemantics();
3519 bool LosesInfo;
3520 APFloat Val0 = C0->getValueAPF();
3521 APFloat Val1 = C1->getValueAPF();
3522 Val0.convert(HalfSem, APFloat::rmTowardZero, &LosesInfo);
3523 Val1.convert(HalfSem, APFloat::rmTowardZero, &LosesInfo);
3524
3525 Constant *Folded = ConstantVector::get({
3526 ConstantFP::get(II->getContext(), Val0),
3527 ConstantFP::get(II->getContext(), Val1) });
3528 return replaceInstUsesWith(*II, Folded);
3529 }
3530 }
3531
3532 if (isa<UndefValue>(Src0) && isa<UndefValue>(Src1))
3533 return replaceInstUsesWith(*II, UndefValue::get(II->getType()));
3534
3535 break;
3536 }
Marek Olsak13e47412018-01-31 20:18:04 +00003537 case Intrinsic::amdgcn_cvt_pknorm_i16:
3538 case Intrinsic::amdgcn_cvt_pknorm_u16:
3539 case Intrinsic::amdgcn_cvt_pk_i16:
3540 case Intrinsic::amdgcn_cvt_pk_u16: {
3541 Value *Src0 = II->getArgOperand(0);
3542 Value *Src1 = II->getArgOperand(1);
3543
3544 if (isa<UndefValue>(Src0) && isa<UndefValue>(Src1))
3545 return replaceInstUsesWith(*II, UndefValue::get(II->getType()));
3546
3547 break;
3548 }
Matt Arsenaultf5262252017-02-22 23:04:58 +00003549 case Intrinsic::amdgcn_ubfe:
3550 case Intrinsic::amdgcn_sbfe: {
3551 // Decompose simple cases into standard shifts.
3552 Value *Src = II->getArgOperand(0);
3553 if (isa<UndefValue>(Src))
3554 return replaceInstUsesWith(*II, Src);
3555
3556 unsigned Width;
3557 Type *Ty = II->getType();
3558 unsigned IntSize = Ty->getIntegerBitWidth();
3559
3560 ConstantInt *CWidth = dyn_cast<ConstantInt>(II->getArgOperand(2));
3561 if (CWidth) {
3562 Width = CWidth->getZExtValue();
3563 if ((Width & (IntSize - 1)) == 0)
3564 return replaceInstUsesWith(*II, ConstantInt::getNullValue(Ty));
3565
3566 if (Width >= IntSize) {
3567 // Hardware ignores high bits, so remove those.
3568 II->setArgOperand(2, ConstantInt::get(CWidth->getType(),
3569 Width & (IntSize - 1)));
3570 return II;
3571 }
3572 }
3573
3574 unsigned Offset;
3575 ConstantInt *COffset = dyn_cast<ConstantInt>(II->getArgOperand(1));
3576 if (COffset) {
3577 Offset = COffset->getZExtValue();
3578 if (Offset >= IntSize) {
3579 II->setArgOperand(1, ConstantInt::get(COffset->getType(),
3580 Offset & (IntSize - 1)));
3581 return II;
3582 }
3583 }
3584
3585 bool Signed = II->getIntrinsicID() == Intrinsic::amdgcn_sbfe;
3586
Matt Arsenaultf5262252017-02-22 23:04:58 +00003587 if (!CWidth || !COffset)
3588 break;
3589
Tom Stellard28d66212018-11-08 17:57:57 +00003590 // The case of Width == 0 is handled above, which makes this tranformation
3591 // safe. If Width == 0, then the ashr and lshr instructions become poison
3592 // value since the shift amount would be equal to the bit size.
3593 assert(Width != 0);
3594
Matt Arsenaultf5262252017-02-22 23:04:58 +00003595 // TODO: This allows folding to undef when the hardware has specific
3596 // behavior?
3597 if (Offset + Width < IntSize) {
Craig Topperbb4069e2017-07-07 23:16:26 +00003598 Value *Shl = Builder.CreateShl(Src, IntSize - Offset - Width);
3599 Value *RightShift = Signed ? Builder.CreateAShr(Shl, IntSize - Width)
3600 : Builder.CreateLShr(Shl, IntSize - Width);
Matt Arsenaultf5262252017-02-22 23:04:58 +00003601 RightShift->takeName(II);
3602 return replaceInstUsesWith(*II, RightShift);
3603 }
3604
Craig Topperbb4069e2017-07-07 23:16:26 +00003605 Value *RightShift = Signed ? Builder.CreateAShr(Src, Offset)
3606 : Builder.CreateLShr(Src, Offset);
Matt Arsenaultf5262252017-02-22 23:04:58 +00003607
3608 RightShift->takeName(II);
3609 return replaceInstUsesWith(*II, RightShift);
3610 }
Matt Arsenaultd4bca1e2017-02-23 00:44:03 +00003611 case Intrinsic::amdgcn_exp:
3612 case Intrinsic::amdgcn_exp_compr: {
Matt Arsenaultcaf13162019-03-12 21:02:54 +00003613 ConstantInt *En = cast<ConstantInt>(II->getArgOperand(1));
Matt Arsenaultd4bca1e2017-02-23 00:44:03 +00003614 unsigned EnBits = En->getZExtValue();
3615 if (EnBits == 0xf)
3616 break; // All inputs enabled.
3617
3618 bool IsCompr = II->getIntrinsicID() == Intrinsic::amdgcn_exp_compr;
3619 bool Changed = false;
3620 for (int I = 0; I < (IsCompr ? 2 : 4); ++I) {
3621 if ((!IsCompr && (EnBits & (1 << I)) == 0) ||
3622 (IsCompr && ((EnBits & (0x3 << (2 * I))) == 0))) {
3623 Value *Src = II->getArgOperand(I + 2);
3624 if (!isa<UndefValue>(Src)) {
3625 II->setArgOperand(I + 2, UndefValue::get(Src->getType()));
3626 Changed = true;
3627 }
3628 }
3629 }
3630
3631 if (Changed)
3632 return II;
3633
3634 break;
Matt Arsenaultcdb468c2017-02-27 23:08:49 +00003635 }
3636 case Intrinsic::amdgcn_fmed3: {
3637 // Note this does not preserve proper sNaN behavior if IEEE-mode is enabled
3638 // for the shader.
3639
3640 Value *Src0 = II->getArgOperand(0);
3641 Value *Src1 = II->getArgOperand(1);
3642 Value *Src2 = II->getArgOperand(2);
3643
Matt Arsenault24ce89b2018-07-05 17:05:36 +00003644 // Checking for NaN before canonicalization provides better fidelity when
3645 // mapping other operations onto fmed3 since the order of operands is
3646 // unchanged.
3647 CallInst *NewCall = nullptr;
3648 if (match(Src0, m_NaN()) || isa<UndefValue>(Src0)) {
3649 NewCall = Builder.CreateMinNum(Src1, Src2);
3650 } else if (match(Src1, m_NaN()) || isa<UndefValue>(Src1)) {
3651 NewCall = Builder.CreateMinNum(Src0, Src2);
3652 } else if (match(Src2, m_NaN()) || isa<UndefValue>(Src2)) {
3653 NewCall = Builder.CreateMaxNum(Src0, Src1);
3654 }
3655
3656 if (NewCall) {
3657 NewCall->copyFastMathFlags(II);
3658 NewCall->takeName(II);
3659 return replaceInstUsesWith(*II, NewCall);
3660 }
3661
Matt Arsenaultcdb468c2017-02-27 23:08:49 +00003662 bool Swap = false;
3663 // Canonicalize constants to RHS operands.
3664 //
3665 // fmed3(c0, x, c1) -> fmed3(x, c0, c1)
3666 if (isa<Constant>(Src0) && !isa<Constant>(Src1)) {
3667 std::swap(Src0, Src1);
3668 Swap = true;
3669 }
3670
3671 if (isa<Constant>(Src1) && !isa<Constant>(Src2)) {
3672 std::swap(Src1, Src2);
3673 Swap = true;
3674 }
3675
3676 if (isa<Constant>(Src0) && !isa<Constant>(Src1)) {
3677 std::swap(Src0, Src1);
3678 Swap = true;
3679 }
3680
3681 if (Swap) {
3682 II->setArgOperand(0, Src0);
3683 II->setArgOperand(1, Src1);
3684 II->setArgOperand(2, Src2);
3685 return II;
3686 }
3687
Matt Arsenaultcdb468c2017-02-27 23:08:49 +00003688 if (const ConstantFP *C0 = dyn_cast<ConstantFP>(Src0)) {
3689 if (const ConstantFP *C1 = dyn_cast<ConstantFP>(Src1)) {
3690 if (const ConstantFP *C2 = dyn_cast<ConstantFP>(Src2)) {
3691 APFloat Result = fmed3AMDGCN(C0->getValueAPF(), C1->getValueAPF(),
3692 C2->getValueAPF());
3693 return replaceInstUsesWith(*II,
Craig Topperbb4069e2017-07-07 23:16:26 +00003694 ConstantFP::get(Builder.getContext(), Result));
Matt Arsenaultcdb468c2017-02-27 23:08:49 +00003695 }
3696 }
3697 }
3698
3699 break;
Matt Arsenaultd4bca1e2017-02-23 00:44:03 +00003700 }
Matt Arsenaultd81f5572017-03-13 18:14:02 +00003701 case Intrinsic::amdgcn_icmp:
3702 case Intrinsic::amdgcn_fcmp: {
Matt Arsenaultcaf13162019-03-12 21:02:54 +00003703 const ConstantInt *CC = cast<ConstantInt>(II->getArgOperand(2));
Matt Arsenaultd81f5572017-03-13 18:14:02 +00003704 // Guard against invalid arguments.
3705 int64_t CCVal = CC->getZExtValue();
3706 bool IsInteger = II->getIntrinsicID() == Intrinsic::amdgcn_icmp;
3707 if ((IsInteger && (CCVal < CmpInst::FIRST_ICMP_PREDICATE ||
3708 CCVal > CmpInst::LAST_ICMP_PREDICATE)) ||
3709 (!IsInteger && (CCVal < CmpInst::FIRST_FCMP_PREDICATE ||
3710 CCVal > CmpInst::LAST_FCMP_PREDICATE)))
3711 break;
3712
3713 Value *Src0 = II->getArgOperand(0);
3714 Value *Src1 = II->getArgOperand(1);
3715
3716 if (auto *CSrc0 = dyn_cast<Constant>(Src0)) {
3717 if (auto *CSrc1 = dyn_cast<Constant>(Src1)) {
3718 Constant *CCmp = ConstantExpr::getCompare(CCVal, CSrc0, CSrc1);
Nicolai Haehnle9c661852017-04-24 17:08:43 +00003719 if (CCmp->isNullValue()) {
3720 return replaceInstUsesWith(
3721 *II, ConstantExpr::getSExt(CCmp, II->getType()));
3722 }
3723
3724 // The result of V_ICMP/V_FCMP assembly instructions (which this
3725 // intrinsic exposes) is one bit per thread, masked with the EXEC
3726 // register (which contains the bitmask of live threads). So a
3727 // comparison that always returns true is the same as a read of the
3728 // EXEC register.
James Y Knight7976eb52019-02-01 20:43:25 +00003729 Function *NewF = Intrinsic::getDeclaration(
Nicolai Haehnle9c661852017-04-24 17:08:43 +00003730 II->getModule(), Intrinsic::read_register, II->getType());
3731 Metadata *MDArgs[] = {MDString::get(II->getContext(), "exec")};
3732 MDNode *MD = MDNode::get(II->getContext(), MDArgs);
3733 Value *Args[] = {MetadataAsValue::get(II->getContext(), MD)};
Craig Topperbb4069e2017-07-07 23:16:26 +00003734 CallInst *NewCall = Builder.CreateCall(NewF, Args);
Nicolai Haehnle9c661852017-04-24 17:08:43 +00003735 NewCall->addAttribute(AttributeList::FunctionIndex,
3736 Attribute::Convergent);
3737 NewCall->takeName(II);
3738 return replaceInstUsesWith(*II, NewCall);
Matt Arsenaultd81f5572017-03-13 18:14:02 +00003739 }
3740
3741 // Canonicalize constants to RHS.
3742 CmpInst::Predicate SwapPred
3743 = CmpInst::getSwappedPredicate(static_cast<CmpInst::Predicate>(CCVal));
3744 II->setArgOperand(0, Src1);
3745 II->setArgOperand(1, Src0);
3746 II->setArgOperand(2, ConstantInt::get(CC->getType(),
3747 static_cast<int>(SwapPred)));
3748 return II;
3749 }
3750
3751 if (CCVal != CmpInst::ICMP_EQ && CCVal != CmpInst::ICMP_NE)
3752 break;
3753
3754 // Canonicalize compare eq with true value to compare != 0
3755 // llvm.amdgcn.icmp(zext (i1 x), 1, eq)
3756 // -> llvm.amdgcn.icmp(zext (i1 x), 0, ne)
3757 // llvm.amdgcn.icmp(sext (i1 x), -1, eq)
3758 // -> llvm.amdgcn.icmp(sext (i1 x), 0, ne)
3759 Value *ExtSrc;
3760 if (CCVal == CmpInst::ICMP_EQ &&
3761 ((match(Src1, m_One()) && match(Src0, m_ZExt(m_Value(ExtSrc)))) ||
3762 (match(Src1, m_AllOnes()) && match(Src0, m_SExt(m_Value(ExtSrc))))) &&
3763 ExtSrc->getType()->isIntegerTy(1)) {
3764 II->setArgOperand(1, ConstantInt::getNullValue(Src1->getType()));
3765 II->setArgOperand(2, ConstantInt::get(CC->getType(), CmpInst::ICMP_NE));
3766 return II;
3767 }
3768
3769 CmpInst::Predicate SrcPred;
3770 Value *SrcLHS;
3771 Value *SrcRHS;
3772
3773 // Fold compare eq/ne with 0 from a compare result as the predicate to the
3774 // intrinsic. The typical use is a wave vote function in the library, which
3775 // will be fed from a user code condition compared with 0. Fold in the
3776 // redundant compare.
3777
3778 // llvm.amdgcn.icmp([sz]ext ([if]cmp pred a, b), 0, ne)
3779 // -> llvm.amdgcn.[if]cmp(a, b, pred)
3780 //
3781 // llvm.amdgcn.icmp([sz]ext ([if]cmp pred a, b), 0, eq)
3782 // -> llvm.amdgcn.[if]cmp(a, b, inv pred)
3783 if (match(Src1, m_Zero()) &&
3784 match(Src0,
3785 m_ZExtOrSExt(m_Cmp(SrcPred, m_Value(SrcLHS), m_Value(SrcRHS))))) {
3786 if (CCVal == CmpInst::ICMP_EQ)
3787 SrcPred = CmpInst::getInversePredicate(SrcPred);
3788
3789 Intrinsic::ID NewIID = CmpInst::isFPPredicate(SrcPred) ?
3790 Intrinsic::amdgcn_fcmp : Intrinsic::amdgcn_icmp;
3791
Matt Arsenault9a389fb2018-08-15 21:14:25 +00003792 Type *Ty = SrcLHS->getType();
3793 if (auto *CmpType = dyn_cast<IntegerType>(Ty)) {
3794 // Promote to next legal integer type.
3795 unsigned Width = CmpType->getBitWidth();
3796 unsigned NewWidth = Width;
Marek Olsak33eb4d92019-01-15 02:13:18 +00003797
3798 // Don't do anything for i1 comparisons.
3799 if (Width == 1)
3800 break;
3801
Matt Arsenault9a389fb2018-08-15 21:14:25 +00003802 if (Width <= 16)
3803 NewWidth = 16;
3804 else if (Width <= 32)
3805 NewWidth = 32;
3806 else if (Width <= 64)
3807 NewWidth = 64;
3808 else if (Width > 64)
3809 break; // Can't handle this.
3810
3811 if (Width != NewWidth) {
3812 IntegerType *CmpTy = Builder.getIntNTy(NewWidth);
3813 if (CmpInst::isSigned(SrcPred)) {
3814 SrcLHS = Builder.CreateSExt(SrcLHS, CmpTy);
3815 SrcRHS = Builder.CreateSExt(SrcRHS, CmpTy);
3816 } else {
3817 SrcLHS = Builder.CreateZExt(SrcLHS, CmpTy);
3818 SrcRHS = Builder.CreateZExt(SrcRHS, CmpTy);
3819 }
3820 }
3821 } else if (!Ty->isFloatTy() && !Ty->isDoubleTy() && !Ty->isHalfTy())
3822 break;
3823
James Y Knight7976eb52019-02-01 20:43:25 +00003824 Function *NewF =
3825 Intrinsic::getDeclaration(II->getModule(), NewIID, SrcLHS->getType());
Matt Arsenaultd81f5572017-03-13 18:14:02 +00003826 Value *Args[] = { SrcLHS, SrcRHS,
3827 ConstantInt::get(CC->getType(), SrcPred) };
Craig Topperbb4069e2017-07-07 23:16:26 +00003828 CallInst *NewCall = Builder.CreateCall(NewF, Args);
Matt Arsenaultd81f5572017-03-13 18:14:02 +00003829 NewCall->takeName(II);
3830 return replaceInstUsesWith(*II, NewCall);
3831 }
3832
3833 break;
3834 }
Marek Olsak2114fc32017-10-24 10:26:59 +00003835 case Intrinsic::amdgcn_wqm_vote: {
3836 // wqm_vote is identity when the argument is constant.
3837 if (!isa<Constant>(II->getArgOperand(0)))
3838 break;
3839
3840 return replaceInstUsesWith(*II, II->getArgOperand(0));
3841 }
Marek Olsakce76ea02017-10-24 10:27:13 +00003842 case Intrinsic::amdgcn_kill: {
3843 const ConstantInt *C = dyn_cast<ConstantInt>(II->getArgOperand(0));
3844 if (!C || !C->getZExtValue())
3845 break;
3846
3847 // amdgcn.kill(i1 1) is a no-op
3848 return eraseInstFromFunction(CI);
3849 }
Stanislav Mekhanoshin0e132dc2018-05-22 08:04:33 +00003850 case Intrinsic::amdgcn_update_dpp: {
3851 Value *Old = II->getArgOperand(0);
3852
Matt Arsenaultcaf13162019-03-12 21:02:54 +00003853 auto BC = cast<ConstantInt>(II->getArgOperand(5));
3854 auto RM = cast<ConstantInt>(II->getArgOperand(3));
3855 auto BM = cast<ConstantInt>(II->getArgOperand(4));
3856 if (BC->isZeroValue() ||
Stanislav Mekhanoshin0e132dc2018-05-22 08:04:33 +00003857 RM->getZExtValue() != 0xF ||
3858 BM->getZExtValue() != 0xF ||
3859 isa<UndefValue>(Old))
3860 break;
3861
3862 // If bound_ctrl = 1, row mask = bank mask = 0xf we can omit old value.
3863 II->setOperand(0, UndefValue::get(Old->getType()));
3864 return II;
3865 }
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003866 case Intrinsic::stackrestore: {
3867 // If the save is right next to the restore, remove the restore. This can
3868 // happen when variable allocas are DCE'd.
Gabor Greif589a0b92010-06-24 12:58:35 +00003869 if (IntrinsicInst *SS = dyn_cast<IntrinsicInst>(II->getArgOperand(0))) {
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003870 if (SS->getIntrinsicID() == Intrinsic::stacksave) {
Vedant Kumarf01827f2018-06-19 23:42:17 +00003871 // Skip over debug info.
3872 if (SS->getNextNonDebugInstruction() == II) {
Sanjay Patel4b198802016-02-01 22:23:39 +00003873 return eraseInstFromFunction(CI);
Davide Italiano189c2cf2018-06-08 20:42:36 +00003874 }
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003875 }
3876 }
Jim Grosbach7815f562012-02-03 00:07:04 +00003877
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003878 // Scan down this block to see if there is another stack restore in the
3879 // same block without an intervening call/alloca.
Duncan P. N. Exon Smith9f8aaf22015-10-13 16:59:33 +00003880 BasicBlock::iterator BI(II);
Chandler Carruthedb12a82018-10-15 10:04:59 +00003881 Instruction *TI = II->getParent()->getTerminator();
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003882 bool CannotRemove = false;
3883 for (++BI; &*BI != TI; ++BI) {
Nuno Lopes55fff832012-06-21 15:45:28 +00003884 if (isa<AllocaInst>(BI)) {
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003885 CannotRemove = true;
3886 break;
3887 }
3888 if (CallInst *BCI = dyn_cast<CallInst>(BI)) {
3889 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(BCI)) {
3890 // If there is a stackrestore below this one, remove this one.
3891 if (II->getIntrinsicID() == Intrinsic::stackrestore)
Sanjay Patel4b198802016-02-01 22:23:39 +00003892 return eraseInstFromFunction(CI);
Reid Kleckner892ae2e2016-02-27 00:53:54 +00003893
3894 // Bail if we cross over an intrinsic with side effects, such as
3895 // llvm.stacksave, llvm.read_register, or llvm.setjmp.
3896 if (II->mayHaveSideEffects()) {
3897 CannotRemove = true;
3898 break;
3899 }
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003900 } else {
3901 // If we found a non-intrinsic call, we can't remove the stack
3902 // restore.
3903 CannotRemove = true;
3904 break;
3905 }
3906 }
3907 }
Jim Grosbach7815f562012-02-03 00:07:04 +00003908
Bill Wendlingf891bf82011-07-31 06:30:59 +00003909 // If the stack restore is in a return, resume, or unwind block and if there
3910 // are no allocas or calls between the restore and the return, nuke the
3911 // restore.
Bill Wendlingd5d95b02012-02-06 21:16:41 +00003912 if (!CannotRemove && (isa<ReturnInst>(TI) || isa<ResumeInst>(TI)))
Sanjay Patel4b198802016-02-01 22:23:39 +00003913 return eraseInstFromFunction(CI);
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003914 break;
3915 }
Vitaly Bukaf0500b62016-07-28 22:50:48 +00003916 case Intrinsic::lifetime_start:
Vitaly Buka0ab23cf2016-07-28 22:59:03 +00003917 // Asan needs to poison memory to detect invalid access which is possible
3918 // even for empty lifetime range.
Evgeniy Stepanovc667c1f2017-12-09 00:21:41 +00003919 if (II->getFunction()->hasFnAttribute(Attribute::SanitizeAddress) ||
3920 II->getFunction()->hasFnAttribute(Attribute::SanitizeHWAddress))
Vitaly Buka0ab23cf2016-07-28 22:59:03 +00003921 break;
3922
Arnaud A. de Grandmaison333ef382016-05-10 09:24:49 +00003923 if (removeTriviallyEmptyRange(*II, Intrinsic::lifetime_start,
3924 Intrinsic::lifetime_end, *this))
3925 return nullptr;
Arnaud A. de Grandmaison849f3bf2015-10-01 14:54:31 +00003926 break;
Hal Finkelf5867a72014-07-25 21:45:17 +00003927 case Intrinsic::assume: {
David Majnemerfcc58112016-04-08 16:37:12 +00003928 Value *IIOperand = II->getArgOperand(0);
Sanjay Patel825a4fa2018-06-20 13:22:26 +00003929 // Remove an assume if it is followed by an identical assume.
3930 // TODO: Do we need this? Unless there are conflicting assumptions, the
3931 // computeKnownBits(IIOperand) below here eliminates redundant assumes.
3932 Instruction *Next = II->getNextNonDebugInstruction();
3933 if (match(Next, m_Intrinsic<Intrinsic::assume>(m_Specific(IIOperand))))
David Majnemerfcc58112016-04-08 16:37:12 +00003934 return eraseInstFromFunction(CI);
3935
Hal Finkelf5867a72014-07-25 21:45:17 +00003936 // Canonicalize assume(a && b) -> assume(a); assume(b);
Hal Finkel74c2f352014-09-07 12:44:26 +00003937 // Note: New assumption intrinsics created here are registered by
3938 // the InstCombineIRInserter object.
James Y Knight7976eb52019-02-01 20:43:25 +00003939 FunctionType *AssumeIntrinsicTy = II->getFunctionType();
3940 Value *AssumeIntrinsic = II->getCalledValue();
3941 Value *A, *B;
Hal Finkelf5867a72014-07-25 21:45:17 +00003942 if (match(IIOperand, m_And(m_Value(A), m_Value(B)))) {
James Y Knight7976eb52019-02-01 20:43:25 +00003943 Builder.CreateCall(AssumeIntrinsicTy, AssumeIntrinsic, A, II->getName());
3944 Builder.CreateCall(AssumeIntrinsicTy, AssumeIntrinsic, B, II->getName());
Sanjay Patel4b198802016-02-01 22:23:39 +00003945 return eraseInstFromFunction(*II);
Hal Finkelf5867a72014-07-25 21:45:17 +00003946 }
3947 // assume(!(a || b)) -> assume(!a); assume(!b);
3948 if (match(IIOperand, m_Not(m_Or(m_Value(A), m_Value(B))))) {
James Y Knight7976eb52019-02-01 20:43:25 +00003949 Builder.CreateCall(AssumeIntrinsicTy, AssumeIntrinsic,
3950 Builder.CreateNot(A), II->getName());
3951 Builder.CreateCall(AssumeIntrinsicTy, AssumeIntrinsic,
3952 Builder.CreateNot(B), II->getName());
Sanjay Patel4b198802016-02-01 22:23:39 +00003953 return eraseInstFromFunction(*II);
Hal Finkelf5867a72014-07-25 21:45:17 +00003954 }
Hal Finkel04a15612014-10-04 21:27:06 +00003955
Philip Reames66c6de62014-11-11 23:33:19 +00003956 // assume( (load addr) != null ) -> add 'nonnull' metadata to load
3957 // (if assume is valid at the load)
Sanjay Patelf0d1e7732017-01-03 22:25:31 +00003958 CmpInst::Predicate Pred;
3959 Instruction *LHS;
3960 if (match(IIOperand, m_ICmp(Pred, m_Instruction(LHS), m_Zero())) &&
3961 Pred == ICmpInst::ICMP_NE && LHS->getOpcode() == Instruction::Load &&
3962 LHS->getType()->isPointerTy() &&
3963 isValidAssumeForContext(II, LHS, &DT)) {
3964 MDNode *MD = MDNode::get(II->getContext(), None);
3965 LHS->setMetadata(LLVMContext::MD_nonnull, MD);
3966 return eraseInstFromFunction(*II);
3967
Chandler Carruth24969102015-02-10 08:07:32 +00003968 // TODO: apply nonnull return attributes to calls and invokes
Philip Reames66c6de62014-11-11 23:33:19 +00003969 // TODO: apply range metadata for range check patterns?
3970 }
Sanjay Patelf0d1e7732017-01-03 22:25:31 +00003971
Hal Finkel04a15612014-10-04 21:27:06 +00003972 // If there is a dominating assume with the same condition as this one,
3973 // then this one is redundant, and should be removed.
Craig Topperb45eabc2017-04-26 16:39:58 +00003974 KnownBits Known(1);
3975 computeKnownBits(IIOperand, Known, 0, II);
Craig Topperf0aeee02017-05-05 17:36:09 +00003976 if (Known.isAllOnes())
Sanjay Patel4b198802016-02-01 22:23:39 +00003977 return eraseInstFromFunction(*II);
Hal Finkel04a15612014-10-04 21:27:06 +00003978
Hal Finkel8a9a7832017-01-11 13:24:24 +00003979 // Update the cache of affected values for this assumption (we might be
3980 // here because we just simplified the condition).
3981 AC.updateAffectedValues(II);
Hal Finkelf5867a72014-07-25 21:45:17 +00003982 break;
3983 }
Philip Reames9db26ff2014-12-29 23:27:30 +00003984 case Intrinsic::experimental_gc_relocate: {
3985 // Translate facts known about a pointer before relocating into
3986 // facts about the relocate value, while being careful to
3987 // preserve relocation semantics.
Manuel Jacob83eefa62016-01-05 04:03:00 +00003988 Value *DerivedPtr = cast<GCRelocateInst>(II)->getDerivedPtr();
Philip Reames9db26ff2014-12-29 23:27:30 +00003989
3990 // Remove the relocation if unused, note that this check is required
3991 // to prevent the cases below from looping forever.
3992 if (II->use_empty())
Sanjay Patel4b198802016-02-01 22:23:39 +00003993 return eraseInstFromFunction(*II);
Philip Reames9db26ff2014-12-29 23:27:30 +00003994
3995 // Undef is undef, even after relocation.
3996 // TODO: provide a hook for this in GCStrategy. This is clearly legal for
3997 // most practical collectors, but there was discussion in the review thread
3998 // about whether it was legal for all possible collectors.
Philip Reamesea4d8e82016-02-09 21:09:22 +00003999 if (isa<UndefValue>(DerivedPtr))
4000 // Use undef of gc_relocate's type to replace it.
4001 return replaceInstUsesWith(*II, UndefValue::get(II->getType()));
Philip Reames9db26ff2014-12-29 23:27:30 +00004002
Philip Reamesea4d8e82016-02-09 21:09:22 +00004003 if (auto *PT = dyn_cast<PointerType>(II->getType())) {
4004 // The relocation of null will be null for most any collector.
4005 // TODO: provide a hook for this in GCStrategy. There might be some
4006 // weird collector this property does not hold for.
4007 if (isa<ConstantPointerNull>(DerivedPtr))
4008 // Use null-pointer of gc_relocate's type to replace it.
4009 return replaceInstUsesWith(*II, ConstantPointerNull::get(PT));
Simon Pilgrimc0c56e72016-04-24 17:00:34 +00004010
Philip Reamesea4d8e82016-02-09 21:09:22 +00004011 // isKnownNonNull -> nonnull attribute
Philip Reamesb8d8db32018-11-12 20:00:53 +00004012 if (!II->hasRetAttr(Attribute::NonNull) &&
4013 isKnownNonZero(DerivedPtr, DL, 0, &AC, II, &DT)) {
Reid Klecknerb5180542017-03-21 16:57:19 +00004014 II->addAttribute(AttributeList::ReturnIndex, Attribute::NonNull);
Philip Reamesb8d8db32018-11-12 20:00:53 +00004015 return II;
4016 }
Ramkumar Ramachandra8fcb4982015-02-14 19:37:54 +00004017 }
Philip Reames9db26ff2014-12-29 23:27:30 +00004018
4019 // TODO: bitcast(relocate(p)) -> relocate(bitcast(p))
4020 // Canonicalize on the type from the uses to the defs
Ramkumar Ramachandra8fcb4982015-02-14 19:37:54 +00004021
Philip Reames9db26ff2014-12-29 23:27:30 +00004022 // TODO: relocate((gep p, C, C2, ...)) -> gep(relocate(p), C, C2, ...)
Philip Reamesea4d8e82016-02-09 21:09:22 +00004023 break;
Philip Reames9db26ff2014-12-29 23:27:30 +00004024 }
Artur Pilipenkoe812ca02017-01-25 14:12:12 +00004025
4026 case Intrinsic::experimental_guard: {
Philip Reames79e917d2018-05-09 22:56:32 +00004027 // Is this guard followed by another guard? We scan forward over a small
4028 // fixed window of instructions to handle common cases with conditions
4029 // computed between guards.
Sanjoy Dase0e57952017-02-01 16:34:55 +00004030 Instruction *NextInst = II->getNextNode();
Philip Reames913a7792018-05-10 00:05:29 +00004031 for (unsigned i = 0; i < GuardWideningWindow; i++) {
Philip Reames79e917d2018-05-09 22:56:32 +00004032 // Note: Using context-free form to avoid compile time blow up
4033 if (!isSafeToSpeculativelyExecute(NextInst))
4034 break;
4035 NextInst = NextInst->getNextNode();
4036 }
Sanjoy Dase0e57952017-02-01 16:34:55 +00004037 Value *NextCond = nullptr;
4038 if (match(NextInst,
4039 m_Intrinsic<Intrinsic::experimental_guard>(m_Value(NextCond)))) {
4040 Value *CurrCond = II->getArgOperand(0);
Artur Pilipenkoe812ca02017-01-25 14:12:12 +00004041
Simon Pilgrim68168d12017-03-30 12:59:53 +00004042 // Remove a guard that it is immediately preceded by an identical guard.
Sanjoy Dase0e57952017-02-01 16:34:55 +00004043 if (CurrCond == NextCond)
4044 return eraseInstFromFunction(*NextInst);
4045
4046 // Otherwise canonicalize guard(a); guard(b) -> guard(a & b).
Philip Reames79e917d2018-05-09 22:56:32 +00004047 Instruction* MoveI = II->getNextNode();
4048 while (MoveI != NextInst) {
4049 auto *Temp = MoveI;
4050 MoveI = MoveI->getNextNode();
4051 Temp->moveBefore(II);
4052 }
Craig Topperbb4069e2017-07-07 23:16:26 +00004053 II->setArgOperand(0, Builder.CreateAnd(CurrCond, NextCond));
Sanjoy Dase0e57952017-02-01 16:34:55 +00004054 return eraseInstFromFunction(*NextInst);
4055 }
Artur Pilipenkoe812ca02017-01-25 14:12:12 +00004056 break;
4057 }
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004058 }
Craig Topperc1892ec2019-01-31 17:23:29 +00004059 return visitCallBase(*II);
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004060}
4061
Davide Italianoaec46172017-01-31 18:09:05 +00004062// Fence instruction simplification
4063Instruction *InstCombiner::visitFenceInst(FenceInst &FI) {
4064 // Remove identical consecutive fences.
Vedant Kumarf01827f2018-06-19 23:42:17 +00004065 Instruction *Next = FI.getNextNonDebugInstruction();
Tim Northover9b800602018-06-06 12:46:02 +00004066 if (auto *NFI = dyn_cast<FenceInst>(Next))
Davide Italianoaec46172017-01-31 18:09:05 +00004067 if (FI.isIdenticalTo(NFI))
4068 return eraseInstFromFunction(FI);
4069 return nullptr;
4070}
4071
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004072// InvokeInst simplification
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004073Instruction *InstCombiner::visitInvokeInst(InvokeInst &II) {
Craig Topperc1892ec2019-01-31 17:23:29 +00004074 return visitCallBase(II);
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004075}
4076
Craig Topper784929d2019-02-08 20:48:56 +00004077// CallBrInst simplification
4078Instruction *InstCombiner::visitCallBrInst(CallBrInst &CBI) {
4079 return visitCallBase(CBI);
4080}
4081
Sanjay Patelcd4377c2016-01-20 22:24:38 +00004082/// If this cast does not affect the value passed through the varargs area, we
4083/// can eliminate the use of the cast.
Craig Topperc1892ec2019-01-31 17:23:29 +00004084static bool isSafeToEliminateVarargsCast(const CallBase &Call,
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004085 const DataLayout &DL,
4086 const CastInst *const CI,
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004087 const int ix) {
4088 if (!CI->isLosslessCast())
4089 return false;
4090
Philip Reames1a1bdb22014-12-02 18:50:36 +00004091 // If this is a GC intrinsic, avoid munging types. We need types for
4092 // statepoint reconstruction in SelectionDAG.
4093 // TODO: This is probably something which should be expanded to all
4094 // intrinsics since the entire point of intrinsics is that
4095 // they are understandable by the optimizer.
Craig Topperc1892ec2019-01-31 17:23:29 +00004096 if (isStatepoint(&Call) || isGCRelocate(&Call) || isGCResult(&Call))
Philip Reames1a1bdb22014-12-02 18:50:36 +00004097 return false;
4098
Reid Kleckner26af2ca2014-01-28 02:38:36 +00004099 // The size of ByVal or InAlloca arguments is derived from the type, so we
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004100 // can't change to a type with a different size. If the size were
4101 // passed explicitly we could avoid this check.
Craig Topperc1892ec2019-01-31 17:23:29 +00004102 if (!Call.isByValOrInAllocaArgument(ix))
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004103 return true;
4104
Jim Grosbach7815f562012-02-03 00:07:04 +00004105 Type* SrcTy =
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004106 cast<PointerType>(CI->getOperand(0)->getType())->getElementType();
Chris Lattner229907c2011-07-18 04:54:35 +00004107 Type* DstTy = cast<PointerType>(CI->getType())->getElementType();
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004108 if (!SrcTy->isSized() || !DstTy->isSized())
4109 return false;
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004110 if (DL.getTypeAllocSize(SrcTy) != DL.getTypeAllocSize(DstTy))
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004111 return false;
4112 return true;
4113}
4114
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004115Instruction *InstCombiner::tryOptimizeCall(CallInst *CI) {
Craig Topperf40110f2014-04-25 05:29:35 +00004116 if (!CI->getCalledFunction()) return nullptr;
Eric Christophera7fb58f2010-03-06 10:50:38 +00004117
Chandler Carruthba4c5172015-01-21 11:23:40 +00004118 auto InstCombineRAUW = [this](Instruction *From, Value *With) {
Sanjay Patel4b198802016-02-01 22:23:39 +00004119 replaceInstUsesWith(*From, With);
Chandler Carruthba4c5172015-01-21 11:23:40 +00004120 };
Amara Emerson54f60252018-10-11 14:51:11 +00004121 auto InstCombineErase = [this](Instruction *I) {
4122 eraseInstFromFunction(*I);
4123 };
4124 LibCallSimplifier Simplifier(DL, &TLI, ORE, InstCombineRAUW,
4125 InstCombineErase);
Chandler Carruthba4c5172015-01-21 11:23:40 +00004126 if (Value *With = Simplifier.optimizeCall(CI)) {
Meador Ingee3f2b262012-11-30 04:05:06 +00004127 ++NumSimplified;
Sanjay Patel4b198802016-02-01 22:23:39 +00004128 return CI->use_empty() ? CI : replaceInstUsesWith(*CI, With);
Meador Ingee3f2b262012-11-30 04:05:06 +00004129 }
Meador Ingedf796f82012-10-13 16:45:24 +00004130
Craig Topperf40110f2014-04-25 05:29:35 +00004131 return nullptr;
Eric Christophera7fb58f2010-03-06 10:50:38 +00004132}
4133
Sanjay Patel6038d3e2016-01-29 23:27:03 +00004134static IntrinsicInst *findInitTrampolineFromAlloca(Value *TrampMem) {
Duncan Sandsa0984362011-09-06 13:37:06 +00004135 // Strip off at most one level of pointer casts, looking for an alloca. This
4136 // is good enough in practice and simpler than handling any number of casts.
4137 Value *Underlying = TrampMem->stripPointerCasts();
4138 if (Underlying != TrampMem &&
Chandler Carruthcdf47882014-03-09 03:16:01 +00004139 (!Underlying->hasOneUse() || Underlying->user_back() != TrampMem))
Craig Topperf40110f2014-04-25 05:29:35 +00004140 return nullptr;
Duncan Sandsa0984362011-09-06 13:37:06 +00004141 if (!isa<AllocaInst>(Underlying))
Craig Topperf40110f2014-04-25 05:29:35 +00004142 return nullptr;
Duncan Sandsa0984362011-09-06 13:37:06 +00004143
Craig Topperf40110f2014-04-25 05:29:35 +00004144 IntrinsicInst *InitTrampoline = nullptr;
Chandler Carruthcdf47882014-03-09 03:16:01 +00004145 for (User *U : TrampMem->users()) {
4146 IntrinsicInst *II = dyn_cast<IntrinsicInst>(U);
Duncan Sandsa0984362011-09-06 13:37:06 +00004147 if (!II)
Craig Topperf40110f2014-04-25 05:29:35 +00004148 return nullptr;
Duncan Sandsa0984362011-09-06 13:37:06 +00004149 if (II->getIntrinsicID() == Intrinsic::init_trampoline) {
4150 if (InitTrampoline)
4151 // More than one init_trampoline writes to this value. Give up.
Craig Topperf40110f2014-04-25 05:29:35 +00004152 return nullptr;
Duncan Sandsa0984362011-09-06 13:37:06 +00004153 InitTrampoline = II;
4154 continue;
4155 }
4156 if (II->getIntrinsicID() == Intrinsic::adjust_trampoline)
4157 // Allow any number of calls to adjust.trampoline.
4158 continue;
Craig Topperf40110f2014-04-25 05:29:35 +00004159 return nullptr;
Duncan Sandsa0984362011-09-06 13:37:06 +00004160 }
4161
4162 // No call to init.trampoline found.
4163 if (!InitTrampoline)
Craig Topperf40110f2014-04-25 05:29:35 +00004164 return nullptr;
Duncan Sandsa0984362011-09-06 13:37:06 +00004165
4166 // Check that the alloca is being used in the expected way.
4167 if (InitTrampoline->getOperand(0) != TrampMem)
Craig Topperf40110f2014-04-25 05:29:35 +00004168 return nullptr;
Duncan Sandsa0984362011-09-06 13:37:06 +00004169
4170 return InitTrampoline;
4171}
4172
Sanjay Patel6038d3e2016-01-29 23:27:03 +00004173static IntrinsicInst *findInitTrampolineFromBB(IntrinsicInst *AdjustTramp,
Duncan Sandsa0984362011-09-06 13:37:06 +00004174 Value *TrampMem) {
4175 // Visit all the previous instructions in the basic block, and try to find a
4176 // init.trampoline which has a direct path to the adjust.trampoline.
Duncan P. N. Exon Smith9f8aaf22015-10-13 16:59:33 +00004177 for (BasicBlock::iterator I = AdjustTramp->getIterator(),
4178 E = AdjustTramp->getParent()->begin();
4179 I != E;) {
4180 Instruction *Inst = &*--I;
Duncan Sandsa0984362011-09-06 13:37:06 +00004181 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I))
4182 if (II->getIntrinsicID() == Intrinsic::init_trampoline &&
4183 II->getOperand(0) == TrampMem)
4184 return II;
4185 if (Inst->mayWriteToMemory())
Craig Topperf40110f2014-04-25 05:29:35 +00004186 return nullptr;
Duncan Sandsa0984362011-09-06 13:37:06 +00004187 }
Craig Topperf40110f2014-04-25 05:29:35 +00004188 return nullptr;
Duncan Sandsa0984362011-09-06 13:37:06 +00004189}
4190
4191// Given a call to llvm.adjust.trampoline, find and return the corresponding
4192// call to llvm.init.trampoline if the call to the trampoline can be optimized
4193// to a direct call to a function. Otherwise return NULL.
Sanjay Patel6038d3e2016-01-29 23:27:03 +00004194static IntrinsicInst *findInitTrampoline(Value *Callee) {
Duncan Sandsa0984362011-09-06 13:37:06 +00004195 Callee = Callee->stripPointerCasts();
4196 IntrinsicInst *AdjustTramp = dyn_cast<IntrinsicInst>(Callee);
4197 if (!AdjustTramp ||
4198 AdjustTramp->getIntrinsicID() != Intrinsic::adjust_trampoline)
Craig Topperf40110f2014-04-25 05:29:35 +00004199 return nullptr;
Duncan Sandsa0984362011-09-06 13:37:06 +00004200
4201 Value *TrampMem = AdjustTramp->getOperand(0);
4202
Sanjay Patel6038d3e2016-01-29 23:27:03 +00004203 if (IntrinsicInst *IT = findInitTrampolineFromAlloca(TrampMem))
Duncan Sandsa0984362011-09-06 13:37:06 +00004204 return IT;
Sanjay Patel6038d3e2016-01-29 23:27:03 +00004205 if (IntrinsicInst *IT = findInitTrampolineFromBB(AdjustTramp, TrampMem))
Duncan Sandsa0984362011-09-06 13:37:06 +00004206 return IT;
Craig Topperf40110f2014-04-25 05:29:35 +00004207 return nullptr;
Duncan Sandsa0984362011-09-06 13:37:06 +00004208}
4209
Craig Topper784929d2019-02-08 20:48:56 +00004210/// Improvements for call, callbr and invoke instructions.
Craig Topperc1892ec2019-01-31 17:23:29 +00004211Instruction *InstCombiner::visitCallBase(CallBase &Call) {
4212 if (isAllocLikeFn(&Call, &TLI))
4213 return visitAllocSite(Call);
Nuno Lopesdc6085e2012-06-21 21:25:05 +00004214
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004215 bool Changed = false;
4216
Philip Reamesc25df112015-06-16 20:24:25 +00004217 // Mark any parameters that are known to be non-null with the nonnull
4218 // attribute. This is helpful for inlining calls to functions with null
4219 // checks on their arguments.
Reid Kleckner5fbdd172017-05-31 19:23:09 +00004220 SmallVector<unsigned, 4> ArgNos;
Philip Reamesc25df112015-06-16 20:24:25 +00004221 unsigned ArgNo = 0;
Akira Hatanaka237916b2015-12-02 06:58:49 +00004222
Craig Topperc1892ec2019-01-31 17:23:29 +00004223 for (Value *V : Call.args()) {
Sanjay Patelf9f5d3c2016-01-29 23:14:58 +00004224 if (V->getType()->isPointerTy() &&
Craig Topperc1892ec2019-01-31 17:23:29 +00004225 !Call.paramHasAttr(ArgNo, Attribute::NonNull) &&
4226 isKnownNonZero(V, DL, 0, &AC, &Call, &DT))
Reid Kleckner5fbdd172017-05-31 19:23:09 +00004227 ArgNos.push_back(ArgNo);
Philip Reamesc25df112015-06-16 20:24:25 +00004228 ArgNo++;
4229 }
Akira Hatanaka237916b2015-12-02 06:58:49 +00004230
Craig Topperc1892ec2019-01-31 17:23:29 +00004231 assert(ArgNo == Call.arg_size() && "sanity check");
Philip Reamesc25df112015-06-16 20:24:25 +00004232
Reid Kleckner5fbdd172017-05-31 19:23:09 +00004233 if (!ArgNos.empty()) {
Craig Topperc1892ec2019-01-31 17:23:29 +00004234 AttributeList AS = Call.getAttributes();
4235 LLVMContext &Ctx = Call.getContext();
Reid Kleckner5fbdd172017-05-31 19:23:09 +00004236 AS = AS.addParamAttribute(Ctx, ArgNos,
4237 Attribute::get(Ctx, Attribute::NonNull));
Craig Topperc1892ec2019-01-31 17:23:29 +00004238 Call.setAttributes(AS);
Akira Hatanaka237916b2015-12-02 06:58:49 +00004239 Changed = true;
4240 }
4241
Chris Lattner73989652010-12-20 08:25:06 +00004242 // If the callee is a pointer to a function, attempt to move any casts to the
Craig Topper784929d2019-02-08 20:48:56 +00004243 // arguments of the call/callbr/invoke.
Craig Topperc1892ec2019-01-31 17:23:29 +00004244 Value *Callee = Call.getCalledValue();
4245 if (!isa<Function>(Callee) && transformConstExprCastCall(Call))
Craig Topperf40110f2014-04-25 05:29:35 +00004246 return nullptr;
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004247
Justin Lebar9d943972016-03-14 20:18:54 +00004248 if (Function *CalleeF = dyn_cast<Function>(Callee)) {
4249 // Remove the convergent attr on calls when the callee is not convergent.
Craig Topperc1892ec2019-01-31 17:23:29 +00004250 if (Call.isConvergent() && !CalleeF->isConvergent() &&
Matt Arsenault802ebcb2016-06-20 19:04:44 +00004251 !CalleeF->isIntrinsic()) {
Craig Topperc1892ec2019-01-31 17:23:29 +00004252 LLVM_DEBUG(dbgs() << "Removing convergent attr from instr " << Call
4253 << "\n");
4254 Call.setNotConvergent();
4255 return &Call;
Justin Lebar9d943972016-03-14 20:18:54 +00004256 }
4257
Chris Lattner846a52e2010-02-01 18:11:34 +00004258 // If the call and callee calling conventions don't match, this call must
4259 // be unreachable, as the call is undefined.
Craig Topperc1892ec2019-01-31 17:23:29 +00004260 if (CalleeF->getCallingConv() != Call.getCallingConv() &&
Chris Lattner846a52e2010-02-01 18:11:34 +00004261 // Only do this for calls to a function with a body. A prototype may
4262 // not actually end up matching the implementation's calling conv for a
4263 // variety of reasons (e.g. it may be written in assembly).
4264 !CalleeF->isDeclaration()) {
Craig Topperc1892ec2019-01-31 17:23:29 +00004265 Instruction *OldCall = &Call;
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004266 new StoreInst(ConstantInt::getTrue(Callee->getContext()),
Jim Grosbach7815f562012-02-03 00:07:04 +00004267 UndefValue::get(Type::getInt1PtrTy(Callee->getContext())),
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004268 OldCall);
Chad Rosiere28ae302012-12-13 00:18:46 +00004269 // If OldCall does not return void then replaceAllUsesWith undef.
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004270 // This allows ValueHandlers and custom metadata to adjust itself.
4271 if (!OldCall->getType()->isVoidTy())
Sanjay Patel4b198802016-02-01 22:23:39 +00004272 replaceInstUsesWith(*OldCall, UndefValue::get(OldCall->getType()));
Chris Lattner2cecedf2010-02-01 18:04:58 +00004273 if (isa<CallInst>(OldCall))
Sanjay Patel4b198802016-02-01 22:23:39 +00004274 return eraseInstFromFunction(*OldCall);
Jim Grosbach7815f562012-02-03 00:07:04 +00004275
Craig Topper784929d2019-02-08 20:48:56 +00004276 // We cannot remove an invoke or a callbr, because it would change thexi
4277 // CFG, just change the callee to a null pointer.
4278 cast<CallBase>(OldCall)->setCalledFunction(
James Y Knight291f7912019-02-01 20:44:54 +00004279 CalleeF->getFunctionType(),
4280 Constant::getNullValue(CalleeF->getType()));
Craig Topperf40110f2014-04-25 05:29:35 +00004281 return nullptr;
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004282 }
Justin Lebar9d943972016-03-14 20:18:54 +00004283 }
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004284
Manoj Gupta77eeac32018-07-09 22:27:23 +00004285 if ((isa<ConstantPointerNull>(Callee) &&
Craig Topperc1892ec2019-01-31 17:23:29 +00004286 !NullPointerIsDefined(Call.getFunction())) ||
Manoj Gupta77eeac32018-07-09 22:27:23 +00004287 isa<UndefValue>(Callee)) {
Craig Topperc1892ec2019-01-31 17:23:29 +00004288 // If Call does not return void then replaceAllUsesWith undef.
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004289 // This allows ValueHandlers and custom metadata to adjust itself.
Craig Topperc1892ec2019-01-31 17:23:29 +00004290 if (!Call.getType()->isVoidTy())
4291 replaceInstUsesWith(Call, UndefValue::get(Call.getType()));
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004292
Craig Topper784929d2019-02-08 20:48:56 +00004293 if (Call.isTerminator()) {
4294 // Can't remove an invoke or callbr because we cannot change the CFG.
Craig Topperf40110f2014-04-25 05:29:35 +00004295 return nullptr;
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004296 }
Nuno Lopes771e7bd2012-06-21 23:52:14 +00004297
4298 // This instruction is not reachable, just remove it. We insert a store to
4299 // undef so that we know that this code is not reachable, despite the fact
4300 // that we can't modify the CFG here.
4301 new StoreInst(ConstantInt::getTrue(Callee->getContext()),
4302 UndefValue::get(Type::getInt1PtrTy(Callee->getContext())),
Craig Topperc1892ec2019-01-31 17:23:29 +00004303 &Call);
Nuno Lopes771e7bd2012-06-21 23:52:14 +00004304
Craig Topperc1892ec2019-01-31 17:23:29 +00004305 return eraseInstFromFunction(Call);
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004306 }
4307
Sanjay Patel6038d3e2016-01-29 23:27:03 +00004308 if (IntrinsicInst *II = findInitTrampoline(Callee))
Craig Topperc1892ec2019-01-31 17:23:29 +00004309 return transformCallThroughTrampoline(Call, *II);
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004310
Chris Lattner229907c2011-07-18 04:54:35 +00004311 PointerType *PTy = cast<PointerType>(Callee->getType());
4312 FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004313 if (FTy->isVarArg()) {
Eli Friedman7534b4682011-11-29 01:18:23 +00004314 int ix = FTy->getNumParams();
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004315 // See if we can optimize any arguments passed through the varargs area of
4316 // the call.
Craig Topperc1892ec2019-01-31 17:23:29 +00004317 for (auto I = Call.arg_begin() + FTy->getNumParams(), E = Call.arg_end();
4318 I != E; ++I, ++ix) {
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004319 CastInst *CI = dyn_cast<CastInst>(*I);
Craig Topperc1892ec2019-01-31 17:23:29 +00004320 if (CI && isSafeToEliminateVarargsCast(Call, DL, CI, ix)) {
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004321 *I = CI->getOperand(0);
4322 Changed = true;
4323 }
4324 }
4325 }
4326
Craig Topperc1892ec2019-01-31 17:23:29 +00004327 if (isa<InlineAsm>(Callee) && !Call.doesNotThrow()) {
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004328 // Inline asm calls cannot throw - mark them 'nounwind'.
Craig Topperc1892ec2019-01-31 17:23:29 +00004329 Call.setDoesNotThrow();
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004330 Changed = true;
4331 }
4332
Micah Villmowcdfe20b2012-10-08 16:38:25 +00004333 // Try to optimize the call if possible, we require DataLayout for most of
Eric Christophera7fb58f2010-03-06 10:50:38 +00004334 // this. None of these calls are seen as possibly dead so go ahead and
4335 // delete the instruction now.
Craig Topperc1892ec2019-01-31 17:23:29 +00004336 if (CallInst *CI = dyn_cast<CallInst>(&Call)) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004337 Instruction *I = tryOptimizeCall(CI);
Eric Christopher1810d772010-03-06 10:59:25 +00004338 // If we changed something return the result, etc. Otherwise let
4339 // the fallthrough check.
Sanjay Patel4b198802016-02-01 22:23:39 +00004340 if (I) return eraseInstFromFunction(*I);
Eric Christophera7fb58f2010-03-06 10:50:38 +00004341 }
4342
Craig Topperc1892ec2019-01-31 17:23:29 +00004343 return Changed ? &Call : nullptr;
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004344}
4345
Sanjay Patelcd4377c2016-01-20 22:24:38 +00004346/// If the callee is a constexpr cast of a function, attempt to move the cast to
Craig Topper784929d2019-02-08 20:48:56 +00004347/// the arguments of the call/callbr/invoke.
Craig Topperc1892ec2019-01-31 17:23:29 +00004348bool InstCombiner::transformConstExprCastCall(CallBase &Call) {
4349 auto *Callee = dyn_cast<Function>(Call.getCalledValue()->stripPointerCasts());
Craig Topperf40110f2014-04-25 05:29:35 +00004350 if (!Callee)
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004351 return false;
Sanjay Patel38ae83d2016-08-11 15:23:56 +00004352
Reid Kleckner298ffc62018-04-02 22:49:44 +00004353 // If this is a call to a thunk function, don't remove the cast. Thunks are
4354 // used to transparently forward all incoming parameters and outgoing return
4355 // values, so it's important to leave the cast in place.
David Majnemer4c0a6e92015-01-21 22:32:04 +00004356 if (Callee->hasFnAttribute("thunk"))
4357 return false;
Sanjay Patel38ae83d2016-08-11 15:23:56 +00004358
Reid Kleckner298ffc62018-04-02 22:49:44 +00004359 // If this is a musttail call, the callee's prototype must match the caller's
4360 // prototype with the exception of pointee types. The code below doesn't
4361 // implement that, so we can't do this transform.
4362 // TODO: Do the transform if it only requires adding pointer casts.
Craig Topperc1892ec2019-01-31 17:23:29 +00004363 if (Call.isMustTailCall())
Reid Kleckner298ffc62018-04-02 22:49:44 +00004364 return false;
4365
Craig Topperc1892ec2019-01-31 17:23:29 +00004366 Instruction *Caller = &Call;
4367 const AttributeList &CallerPAL = Call.getAttributes();
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004368
4369 // Okay, this is a cast from a function to a different type. Unless doing so
4370 // would cause a type conversion of one of our arguments, change this call to
4371 // be a direct call with arguments casted to the appropriate types.
Chris Lattner229907c2011-07-18 04:54:35 +00004372 FunctionType *FT = Callee->getFunctionType();
4373 Type *OldRetTy = Caller->getType();
4374 Type *NewRetTy = FT->getReturnType();
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004375
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004376 // Check to see if we are changing the return type...
4377 if (OldRetTy != NewRetTy) {
Nick Lewyckya6a17d72014-01-18 22:47:12 +00004378
4379 if (NewRetTy->isStructTy())
4380 return false; // TODO: Handle multiple return values.
4381
David Majnemer9b6b8222015-01-06 08:41:31 +00004382 if (!CastInst::isBitOrNoopPointerCastable(NewRetTy, OldRetTy, DL)) {
Matt Arsenaulte6952f22013-09-17 21:10:14 +00004383 if (Callee->isDeclaration())
4384 return false; // Cannot transform this return value.
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004385
Matt Arsenaulte6952f22013-09-17 21:10:14 +00004386 if (!Caller->use_empty() &&
4387 // void -> non-void is handled specially
4388 !NewRetTy->isVoidTy())
Frederic Rissc1892e22014-10-23 04:08:42 +00004389 return false; // Cannot transform this return value.
Matt Arsenaulte6952f22013-09-17 21:10:14 +00004390 }
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004391
4392 if (!CallerPAL.isEmpty() && !Caller->use_empty()) {
Reid Klecknerb5180542017-03-21 16:57:19 +00004393 AttrBuilder RAttrs(CallerPAL, AttributeList::ReturnIndex);
Pete Cooper2777d8872015-05-06 23:19:56 +00004394 if (RAttrs.overlaps(AttributeFuncs::typeIncompatible(NewRetTy)))
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004395 return false; // Attribute not compatible with transformed value.
4396 }
4397
Craig Topper784929d2019-02-08 20:48:56 +00004398 // If the callbase is an invoke/callbr instruction, and the return value is
4399 // used by a PHI node in a successor, we cannot change the return type of
4400 // the call because there is no place to put the cast instruction (without
4401 // breaking the critical edge). Bail out in this case.
4402 if (!Caller->use_empty()) {
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004403 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller))
Chandler Carruthcdf47882014-03-09 03:16:01 +00004404 for (User *U : II->users())
4405 if (PHINode *PN = dyn_cast<PHINode>(U))
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004406 if (PN->getParent() == II->getNormalDest() ||
4407 PN->getParent() == II->getUnwindDest())
4408 return false;
Craig Topper784929d2019-02-08 20:48:56 +00004409 // FIXME: Be conservative for callbr to avoid a quadratic search.
Craig Toppera97857b2019-02-10 02:21:29 +00004410 if (isa<CallBrInst>(Caller))
Craig Topper784929d2019-02-08 20:48:56 +00004411 return false;
4412 }
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004413 }
4414
Craig Topperc1892ec2019-01-31 17:23:29 +00004415 unsigned NumActualArgs = Call.arg_size();
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004416 unsigned NumCommonArgs = std::min(FT->getNumParams(), NumActualArgs);
4417
David Majnemer9b6b8222015-01-06 08:41:31 +00004418 // Prevent us turning:
4419 // declare void @takes_i32_inalloca(i32* inalloca)
4420 // call void bitcast (void (i32*)* @takes_i32_inalloca to void (i32)*)(i32 0)
4421 //
4422 // into:
4423 // call void @takes_i32_inalloca(i32* null)
David Majnemerd61a6fd2015-03-11 18:03:05 +00004424 //
4425 // Similarly, avoid folding away bitcasts of byval calls.
4426 if (Callee->getAttributes().hasAttrSomewhere(Attribute::InAlloca) ||
4427 Callee->getAttributes().hasAttrSomewhere(Attribute::ByVal))
David Majnemer9b6b8222015-01-06 08:41:31 +00004428 return false;
4429
Craig Topperc1892ec2019-01-31 17:23:29 +00004430 auto AI = Call.arg_begin();
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004431 for (unsigned i = 0, e = NumCommonArgs; i != e; ++i, ++AI) {
Chris Lattner229907c2011-07-18 04:54:35 +00004432 Type *ParamTy = FT->getParamType(i);
4433 Type *ActTy = (*AI)->getType();
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004434
David Majnemer9b6b8222015-01-06 08:41:31 +00004435 if (!CastInst::isBitOrNoopPointerCastable(ActTy, ParamTy, DL))
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004436 return false; // Cannot transform this parameter value.
4437
Reid Klecknerf021fab2017-04-13 23:12:13 +00004438 if (AttrBuilder(CallerPAL.getParamAttributes(i))
4439 .overlaps(AttributeFuncs::typeIncompatible(ParamTy)))
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004440 return false; // Attribute not compatible with transformed value.
Jim Grosbach7815f562012-02-03 00:07:04 +00004441
Craig Topperc1892ec2019-01-31 17:23:29 +00004442 if (Call.isInAllocaArgument(i))
Reid Kleckner26af2ca2014-01-28 02:38:36 +00004443 return false; // Cannot transform to and from inalloca.
4444
Chris Lattner27ca8eb2010-12-20 08:36:38 +00004445 // If the parameter is passed as a byval argument, then we have to have a
4446 // sized type and the sized type has to have the same size as the old type.
Reid Klecknerf021fab2017-04-13 23:12:13 +00004447 if (ParamTy != ActTy && CallerPAL.hasParamAttribute(i, Attribute::ByVal)) {
Chris Lattner229907c2011-07-18 04:54:35 +00004448 PointerType *ParamPTy = dyn_cast<PointerType>(ParamTy);
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004449 if (!ParamPTy || !ParamPTy->getElementType()->isSized())
Chris Lattner27ca8eb2010-12-20 08:36:38 +00004450 return false;
Jim Grosbach7815f562012-02-03 00:07:04 +00004451
Matt Arsenaultfa252722013-09-27 22:18:51 +00004452 Type *CurElTy = ActTy->getPointerElementType();
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004453 if (DL.getTypeAllocSize(CurElTy) !=
4454 DL.getTypeAllocSize(ParamPTy->getElementType()))
Chris Lattner27ca8eb2010-12-20 08:36:38 +00004455 return false;
4456 }
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004457 }
4458
Chris Lattneradf38b32011-02-24 05:10:56 +00004459 if (Callee->isDeclaration()) {
4460 // Do not delete arguments unless we have a function body.
4461 if (FT->getNumParams() < NumActualArgs && !FT->isVarArg())
4462 return false;
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004463
Chris Lattneradf38b32011-02-24 05:10:56 +00004464 // If the callee is just a declaration, don't change the varargsness of the
4465 // call. We don't want to introduce a varargs call where one doesn't
4466 // already exist.
Craig Topperc1892ec2019-01-31 17:23:29 +00004467 PointerType *APTy = cast<PointerType>(Call.getCalledValue()->getType());
Chris Lattneradf38b32011-02-24 05:10:56 +00004468 if (FT->isVarArg()!=cast<FunctionType>(APTy->getElementType())->isVarArg())
4469 return false;
Jim Grosbache84ae7b2012-02-03 00:00:55 +00004470
4471 // If both the callee and the cast type are varargs, we still have to make
4472 // sure the number of fixed parameters are the same or we have the same
4473 // ABI issues as if we introduce a varargs call.
Jim Grosbach1df8cdc2012-02-03 00:26:07 +00004474 if (FT->isVarArg() &&
4475 cast<FunctionType>(APTy->getElementType())->isVarArg() &&
4476 FT->getNumParams() !=
Jim Grosbache84ae7b2012-02-03 00:00:55 +00004477 cast<FunctionType>(APTy->getElementType())->getNumParams())
4478 return false;
Chris Lattneradf38b32011-02-24 05:10:56 +00004479 }
Jim Grosbach7815f562012-02-03 00:07:04 +00004480
Jim Grosbach0ab54182012-02-03 00:00:50 +00004481 if (FT->getNumParams() < NumActualArgs && FT->isVarArg() &&
Reid Kleckneraa0cec72017-04-19 23:17:47 +00004482 !CallerPAL.isEmpty()) {
Jim Grosbach0ab54182012-02-03 00:00:50 +00004483 // In this case we have more arguments than the new function type, but we
4484 // won't be dropping them. Check that these extra arguments have attributes
4485 // that are compatible with being a vararg call argument.
Reid Kleckneraa0cec72017-04-19 23:17:47 +00004486 unsigned SRetIdx;
4487 if (CallerPAL.hasAttrSomewhere(Attribute::StructRet, &SRetIdx) &&
4488 SRetIdx > FT->getNumParams())
4489 return false;
4490 }
Jim Grosbach7815f562012-02-03 00:07:04 +00004491
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004492 // Okay, we decided that this is a safe thing to do: go ahead and start
Chris Lattneradf38b32011-02-24 05:10:56 +00004493 // inserting cast instructions as necessary.
Reid Klecknerc3fae792017-04-13 18:11:03 +00004494 SmallVector<Value *, 8> Args;
4495 SmallVector<AttributeSet, 8> ArgAttrs;
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004496 Args.reserve(NumActualArgs);
Reid Klecknerc3fae792017-04-13 18:11:03 +00004497 ArgAttrs.reserve(NumActualArgs);
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004498
4499 // Get any return attributes.
Reid Klecknerb5180542017-03-21 16:57:19 +00004500 AttrBuilder RAttrs(CallerPAL, AttributeList::ReturnIndex);
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004501
4502 // If the return value is not being used, the type may not be compatible
4503 // with the existing attributes. Wipe out any problematic attributes.
Pete Cooper2777d8872015-05-06 23:19:56 +00004504 RAttrs.remove(AttributeFuncs::typeIncompatible(NewRetTy));
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004505
Craig Topperc1892ec2019-01-31 17:23:29 +00004506 AI = Call.arg_begin();
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004507 for (unsigned i = 0; i != NumCommonArgs; ++i, ++AI) {
Chris Lattner229907c2011-07-18 04:54:35 +00004508 Type *ParamTy = FT->getParamType(i);
Matt Arsenaultcacbb232013-07-30 20:45:05 +00004509
Reid Klecknerc3fae792017-04-13 18:11:03 +00004510 Value *NewArg = *AI;
4511 if ((*AI)->getType() != ParamTy)
Craig Topperbb4069e2017-07-07 23:16:26 +00004512 NewArg = Builder.CreateBitOrPointerCast(*AI, ParamTy);
Reid Klecknerc3fae792017-04-13 18:11:03 +00004513 Args.push_back(NewArg);
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004514
4515 // Add any parameter attributes.
Reid Klecknerf021fab2017-04-13 23:12:13 +00004516 ArgAttrs.push_back(CallerPAL.getParamAttributes(i));
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004517 }
4518
4519 // If the function takes more arguments than the call was taking, add them
4520 // now.
Reid Klecknerc3fae792017-04-13 18:11:03 +00004521 for (unsigned i = NumCommonArgs; i != FT->getNumParams(); ++i) {
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004522 Args.push_back(Constant::getNullValue(FT->getParamType(i)));
Reid Klecknerc3fae792017-04-13 18:11:03 +00004523 ArgAttrs.push_back(AttributeSet());
4524 }
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004525
4526 // If we are removing arguments to the function, emit an obnoxious warning.
4527 if (FT->getNumParams() < NumActualArgs) {
Nick Lewycky90053a12012-12-26 22:00:35 +00004528 // TODO: if (!FT->isVarArg()) this call may be unreachable. PR14722
4529 if (FT->isVarArg()) {
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004530 // Add all of the arguments in their promoted form to the arg list.
4531 for (unsigned i = FT->getNumParams(); i != NumActualArgs; ++i, ++AI) {
Chris Lattner229907c2011-07-18 04:54:35 +00004532 Type *PTy = getPromotedType((*AI)->getType());
Reid Klecknerc3fae792017-04-13 18:11:03 +00004533 Value *NewArg = *AI;
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004534 if (PTy != (*AI)->getType()) {
4535 // Must promote to pass through va_arg area!
4536 Instruction::CastOps opcode =
4537 CastInst::getCastOpcode(*AI, false, PTy, false);
Craig Topperbb4069e2017-07-07 23:16:26 +00004538 NewArg = Builder.CreateCast(opcode, *AI, PTy);
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004539 }
Reid Klecknerc3fae792017-04-13 18:11:03 +00004540 Args.push_back(NewArg);
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004541
4542 // Add any parameter attributes.
Reid Klecknerf021fab2017-04-13 23:12:13 +00004543 ArgAttrs.push_back(CallerPAL.getParamAttributes(i));
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004544 }
4545 }
4546 }
4547
Reid Klecknerc2cb5602017-04-12 00:38:00 +00004548 AttributeSet FnAttrs = CallerPAL.getFnAttributes();
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004549
4550 if (NewRetTy->isVoidTy())
4551 Caller->setName(""); // Void type should not have a name.
4552
Reid Klecknerc3fae792017-04-13 18:11:03 +00004553 assert((ArgAttrs.size() == FT->getNumParams() || FT->isVarArg()) &&
4554 "missing argument attributes");
4555 LLVMContext &Ctx = Callee->getContext();
4556 AttributeList NewCallerPAL = AttributeList::get(
4557 Ctx, FnAttrs, AttributeSet::get(Ctx, RAttrs), ArgAttrs);
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004558
Sanjoy Das76293462015-11-25 00:42:19 +00004559 SmallVector<OperandBundleDef, 1> OpBundles;
Craig Topperc1892ec2019-01-31 17:23:29 +00004560 Call.getOperandBundlesAsDefs(OpBundles);
Sanjoy Das76293462015-11-25 00:42:19 +00004561
Craig Topperc1892ec2019-01-31 17:23:29 +00004562 CallBase *NewCall;
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004563 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Craig Topperc1892ec2019-01-31 17:23:29 +00004564 NewCall = Builder.CreateInvoke(Callee, II->getNormalDest(),
4565 II->getUnwindDest(), Args, OpBundles);
Craig Topper784929d2019-02-08 20:48:56 +00004566 } else if (CallBrInst *CBI = dyn_cast<CallBrInst>(Caller)) {
4567 NewCall = Builder.CreateCallBr(Callee, CBI->getDefaultDest(),
4568 CBI->getIndirectDests(), Args, OpBundles);
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004569 } else {
Craig Topperc1892ec2019-01-31 17:23:29 +00004570 NewCall = Builder.CreateCall(Callee, Args, OpBundles);
4571 cast<CallInst>(NewCall)->setTailCallKind(
4572 cast<CallInst>(Caller)->getTailCallKind());
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004573 }
Craig Topperc1892ec2019-01-31 17:23:29 +00004574 NewCall->takeName(Caller);
4575 NewCall->setCallingConv(Call.getCallingConv());
4576 NewCall->setAttributes(NewCallerPAL);
Reid Kleckner257cb4e2017-04-13 20:26:38 +00004577
4578 // Preserve the weight metadata for the new call instruction. The metadata
4579 // is used by SamplePGO to check callsite's hotness.
4580 uint64_t W;
4581 if (Caller->extractProfTotalWeight(W))
Craig Topperc1892ec2019-01-31 17:23:29 +00004582 NewCall->setProfWeight(W);
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004583
4584 // Insert a cast of the return type as necessary.
Craig Topperc1892ec2019-01-31 17:23:29 +00004585 Instruction *NC = NewCall;
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004586 Value *NV = NC;
4587 if (OldRetTy != NV->getType() && !Caller->use_empty()) {
4588 if (!NV->getType()->isVoidTy()) {
David Majnemer9b6b8222015-01-06 08:41:31 +00004589 NV = NC = CastInst::CreateBitOrPointerCast(NC, OldRetTy);
Eli Friedman35211c62011-05-27 00:19:40 +00004590 NC->setDebugLoc(Caller->getDebugLoc());
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004591
Craig Topper784929d2019-02-08 20:48:56 +00004592 // If this is an invoke/callbr instruction, we should insert it after the
4593 // first non-phi instruction in the normal successor block.
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004594 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Bill Wendling07efd6f2011-08-25 01:08:34 +00004595 BasicBlock::iterator I = II->getNormalDest()->getFirstInsertionPt();
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004596 InsertNewInstBefore(NC, *I);
Craig Topper784929d2019-02-08 20:48:56 +00004597 } else if (CallBrInst *CBI = dyn_cast<CallBrInst>(Caller)) {
4598 BasicBlock::iterator I = CBI->getDefaultDest()->getFirstInsertionPt();
4599 InsertNewInstBefore(NC, *I);
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004600 } else {
Chris Lattner73989652010-12-20 08:25:06 +00004601 // Otherwise, it's a call, just insert cast right after the call.
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004602 InsertNewInstBefore(NC, *Caller);
4603 }
4604 Worklist.AddUsersToWorkList(*Caller);
4605 } else {
4606 NV = UndefValue::get(Caller->getType());
4607 }
4608 }
4609
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004610 if (!Caller->use_empty())
Sanjay Patel4b198802016-02-01 22:23:39 +00004611 replaceInstUsesWith(*Caller, NV);
Frederic Rissc1892e22014-10-23 04:08:42 +00004612 else if (Caller->hasValueHandle()) {
4613 if (OldRetTy == NV->getType())
4614 ValueHandleBase::ValueIsRAUWd(Caller, NV);
4615 else
4616 // We cannot call ValueIsRAUWd with a different type, and the
4617 // actual tracked value will disappear.
4618 ValueHandleBase::ValueIsDeleted(Caller);
4619 }
Eli Friedmanb9ed18f2011-05-18 00:32:01 +00004620
Sanjay Patel4b198802016-02-01 22:23:39 +00004621 eraseInstFromFunction(*Caller);
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004622 return true;
4623}
4624
Sanjay Patelcd4377c2016-01-20 22:24:38 +00004625/// Turn a call to a function created by init_trampoline / adjust_trampoline
4626/// intrinsic pair into a direct call to the underlying function.
Duncan Sandsa0984362011-09-06 13:37:06 +00004627Instruction *
Craig Topperc1892ec2019-01-31 17:23:29 +00004628InstCombiner::transformCallThroughTrampoline(CallBase &Call,
4629 IntrinsicInst &Tramp) {
4630 Value *Callee = Call.getCalledValue();
James Y Knight291f7912019-02-01 20:44:54 +00004631 Type *CalleeTy = Callee->getType();
4632 FunctionType *FTy = Call.getFunctionType();
Craig Topperc1892ec2019-01-31 17:23:29 +00004633 AttributeList Attrs = Call.getAttributes();
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004634
4635 // If the call already has the 'nest' attribute somewhere then give up -
4636 // otherwise 'nest' would occur twice after splicing in the chain.
Bill Wendling6e95ae82012-12-31 00:49:59 +00004637 if (Attrs.hasAttrSomewhere(Attribute::Nest))
Craig Topperf40110f2014-04-25 05:29:35 +00004638 return nullptr;
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004639
Craig Topperc1892ec2019-01-31 17:23:29 +00004640 Function *NestF = cast<Function>(Tramp.getArgOperand(1)->stripPointerCasts());
James Y Knight291f7912019-02-01 20:44:54 +00004641 FunctionType *NestFTy = NestF->getFunctionType();
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004642
Reid Klecknereb9dd5b2017-04-10 23:31:05 +00004643 AttributeList NestAttrs = NestF->getAttributes();
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004644 if (!NestAttrs.isEmpty()) {
Reid Klecknerf021fab2017-04-13 23:12:13 +00004645 unsigned NestArgNo = 0;
Craig Topperf40110f2014-04-25 05:29:35 +00004646 Type *NestTy = nullptr;
Reid Klecknerc2cb5602017-04-12 00:38:00 +00004647 AttributeSet NestAttr;
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004648
4649 // Look for a parameter marked with the 'nest' attribute.
4650 for (FunctionType::param_iterator I = NestFTy->param_begin(),
Reid Klecknerf021fab2017-04-13 23:12:13 +00004651 E = NestFTy->param_end();
4652 I != E; ++NestArgNo, ++I) {
4653 AttributeSet AS = NestAttrs.getParamAttributes(NestArgNo);
4654 if (AS.hasAttribute(Attribute::Nest)) {
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004655 // Record the parameter type and any other attributes.
4656 NestTy = *I;
Reid Klecknerf021fab2017-04-13 23:12:13 +00004657 NestAttr = AS;
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004658 break;
4659 }
Reid Klecknerf021fab2017-04-13 23:12:13 +00004660 }
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004661
4662 if (NestTy) {
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004663 std::vector<Value*> NewArgs;
Reid Kleckner7f720332017-04-13 00:58:09 +00004664 std::vector<AttributeSet> NewArgAttrs;
Craig Topperc1892ec2019-01-31 17:23:29 +00004665 NewArgs.reserve(Call.arg_size() + 1);
4666 NewArgAttrs.reserve(Call.arg_size());
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004667
4668 // Insert the nest argument into the call argument list, which may
4669 // mean appending it. Likewise for attributes.
4670
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004671 {
Reid Klecknerf021fab2017-04-13 23:12:13 +00004672 unsigned ArgNo = 0;
Craig Topperc1892ec2019-01-31 17:23:29 +00004673 auto I = Call.arg_begin(), E = Call.arg_end();
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004674 do {
Reid Klecknerf021fab2017-04-13 23:12:13 +00004675 if (ArgNo == NestArgNo) {
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004676 // Add the chain argument and attributes.
Craig Topperc1892ec2019-01-31 17:23:29 +00004677 Value *NestVal = Tramp.getArgOperand(2);
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004678 if (NestVal->getType() != NestTy)
Craig Topperbb4069e2017-07-07 23:16:26 +00004679 NestVal = Builder.CreateBitCast(NestVal, NestTy, "nest");
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004680 NewArgs.push_back(NestVal);
Reid Kleckner7f720332017-04-13 00:58:09 +00004681 NewArgAttrs.push_back(NestAttr);
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004682 }
4683
4684 if (I == E)
4685 break;
4686
4687 // Add the original argument and attributes.
4688 NewArgs.push_back(*I);
Reid Klecknerf021fab2017-04-13 23:12:13 +00004689 NewArgAttrs.push_back(Attrs.getParamAttributes(ArgNo));
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004690
Reid Klecknerf021fab2017-04-13 23:12:13 +00004691 ++ArgNo;
Richard Trieu7a083812016-02-18 22:09:30 +00004692 ++I;
Eugene Zelenkocdc71612016-08-11 17:20:18 +00004693 } while (true);
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004694 }
4695
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004696 // The trampoline may have been bitcast to a bogus type (FTy).
4697 // Handle this by synthesizing a new function type, equal to FTy
4698 // with the chain parameter inserted.
4699
Jay Foadb804a2b2011-07-12 14:06:48 +00004700 std::vector<Type*> NewTypes;
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004701 NewTypes.reserve(FTy->getNumParams()+1);
4702
4703 // Insert the chain's type into the list of parameter types, which may
4704 // mean appending it.
4705 {
Reid Klecknerf021fab2017-04-13 23:12:13 +00004706 unsigned ArgNo = 0;
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004707 FunctionType::param_iterator I = FTy->param_begin(),
4708 E = FTy->param_end();
4709
4710 do {
Reid Klecknerf021fab2017-04-13 23:12:13 +00004711 if (ArgNo == NestArgNo)
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004712 // Add the chain's type.
4713 NewTypes.push_back(NestTy);
4714
4715 if (I == E)
4716 break;
4717
4718 // Add the original type.
4719 NewTypes.push_back(*I);
4720
Reid Klecknerf021fab2017-04-13 23:12:13 +00004721 ++ArgNo;
Richard Trieu7a083812016-02-18 22:09:30 +00004722 ++I;
Eugene Zelenkocdc71612016-08-11 17:20:18 +00004723 } while (true);
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004724 }
4725
4726 // Replace the trampoline call with a direct call. Let the generic
4727 // code sort out any function type mismatches.
Jim Grosbach7815f562012-02-03 00:07:04 +00004728 FunctionType *NewFTy = FunctionType::get(FTy->getReturnType(), NewTypes,
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004729 FTy->isVarArg());
4730 Constant *NewCallee =
4731 NestF->getType() == PointerType::getUnqual(NewFTy) ?
Jim Grosbach7815f562012-02-03 00:07:04 +00004732 NestF : ConstantExpr::getBitCast(NestF,
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004733 PointerType::getUnqual(NewFTy));
Reid Kleckner7f720332017-04-13 00:58:09 +00004734 AttributeList NewPAL =
4735 AttributeList::get(FTy->getContext(), Attrs.getFnAttributes(),
4736 Attrs.getRetAttributes(), NewArgAttrs);
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004737
David Majnemer231a68c2016-04-29 08:07:20 +00004738 SmallVector<OperandBundleDef, 1> OpBundles;
Craig Topperc1892ec2019-01-31 17:23:29 +00004739 Call.getOperandBundlesAsDefs(OpBundles);
David Majnemer231a68c2016-04-29 08:07:20 +00004740
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004741 Instruction *NewCaller;
Craig Topperc1892ec2019-01-31 17:23:29 +00004742 if (InvokeInst *II = dyn_cast<InvokeInst>(&Call)) {
James Y Knight7976eb52019-02-01 20:43:25 +00004743 NewCaller = InvokeInst::Create(NewFTy, NewCallee,
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004744 II->getNormalDest(), II->getUnwindDest(),
David Majnemer231a68c2016-04-29 08:07:20 +00004745 NewArgs, OpBundles);
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004746 cast<InvokeInst>(NewCaller)->setCallingConv(II->getCallingConv());
4747 cast<InvokeInst>(NewCaller)->setAttributes(NewPAL);
Craig Topper784929d2019-02-08 20:48:56 +00004748 } else if (CallBrInst *CBI = dyn_cast<CallBrInst>(&Call)) {
4749 NewCaller =
4750 CallBrInst::Create(NewFTy, NewCallee, CBI->getDefaultDest(),
4751 CBI->getIndirectDests(), NewArgs, OpBundles);
4752 cast<CallBrInst>(NewCaller)->setCallingConv(CBI->getCallingConv());
4753 cast<CallBrInst>(NewCaller)->setAttributes(NewPAL);
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004754 } else {
James Y Knight7976eb52019-02-01 20:43:25 +00004755 NewCaller = CallInst::Create(NewFTy, NewCallee, NewArgs, OpBundles);
David Majnemerd5648c72016-11-25 22:35:09 +00004756 cast<CallInst>(NewCaller)->setTailCallKind(
Craig Topperc1892ec2019-01-31 17:23:29 +00004757 cast<CallInst>(Call).getTailCallKind());
David Majnemerd5648c72016-11-25 22:35:09 +00004758 cast<CallInst>(NewCaller)->setCallingConv(
Craig Topperc1892ec2019-01-31 17:23:29 +00004759 cast<CallInst>(Call).getCallingConv());
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004760 cast<CallInst>(NewCaller)->setAttributes(NewPAL);
4761 }
Craig Topperc1892ec2019-01-31 17:23:29 +00004762 NewCaller->setDebugLoc(Call.getDebugLoc());
Eli Friedman49346012011-05-18 19:57:14 +00004763
4764 return NewCaller;
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004765 }
4766 }
4767
4768 // Replace the trampoline call with a direct call. Since there is no 'nest'
4769 // parameter, there is no need to adjust the argument list. Let the generic
4770 // code sort out any function type mismatches.
James Y Knight291f7912019-02-01 20:44:54 +00004771 Constant *NewCallee = ConstantExpr::getBitCast(NestF, CalleeTy);
4772 Call.setCalledFunction(FTy, NewCallee);
Craig Topperc1892ec2019-01-31 17:23:29 +00004773 return &Call;
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004774}