blob: 9516bf24251a4e014353719c7d1929025261ae37 [file] [log] [blame]
Meador Ingedf796f82012-10-13 16:45:24 +00001//===------ SimplifyLibCalls.cpp - Library calls simplifier ---------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This is a utility pass used for testing the InstructionSimplify analysis.
11// The analysis is applied to every instruction, and if it simplifies then the
12// instruction is replaced by the simplification. If you are looking for a pass
13// that performs serious instruction folding, use the instcombine pass instead.
14//
15//===----------------------------------------------------------------------===//
16
17#include "llvm/Transforms/Utils/SimplifyLibCalls.h"
Meador Inge20255ef2013-03-12 00:08:29 +000018#include "llvm/ADT/SmallString.h"
Meador Ingedf796f82012-10-13 16:45:24 +000019#include "llvm/ADT/StringMap.h"
Bob Wilsond8d92d92013-11-03 06:48:38 +000020#include "llvm/ADT/Triple.h"
Sanjay Patel82ec8722017-08-21 19:13:14 +000021#include "llvm/Analysis/ConstantFolding.h"
Adam Nemet0965da22017-10-09 23:19:02 +000022#include "llvm/Analysis/OptimizationRemarkEmitter.h"
Weiming Zhao45d4cb92015-11-24 18:57:06 +000023#include "llvm/Analysis/TargetLibraryInfo.h"
Meador Ingedf796f82012-10-13 16:45:24 +000024#include "llvm/Analysis/ValueTracking.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000025#include "llvm/IR/DataLayout.h"
26#include "llvm/IR/Function.h"
27#include "llvm/IR/IRBuilder.h"
Meador Inge20255ef2013-03-12 00:08:29 +000028#include "llvm/IR/IntrinsicInst.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000029#include "llvm/IR/Intrinsics.h"
30#include "llvm/IR/LLVMContext.h"
31#include "llvm/IR/Module.h"
Sanjay Patelc699a612014-10-16 18:48:17 +000032#include "llvm/IR/PatternMatch.h"
Hal Finkel66cd3f12013-11-17 02:06:35 +000033#include "llvm/Support/CommandLine.h"
Craig Topperb45eabc2017-04-26 16:39:58 +000034#include "llvm/Support/KnownBits.h"
Meador Ingedf796f82012-10-13 16:45:24 +000035#include "llvm/Transforms/Utils/BuildLibCalls.h"
Chad Rosierdc655322015-08-28 18:30:18 +000036#include "llvm/Transforms/Utils/Local.h"
Meador Ingedf796f82012-10-13 16:45:24 +000037
38using namespace llvm;
Sanjay Patelc699a612014-10-16 18:48:17 +000039using namespace PatternMatch;
Meador Ingedf796f82012-10-13 16:45:24 +000040
Hal Finkel66cd3f12013-11-17 02:06:35 +000041static cl::opt<bool>
Sanjay Patela92fa442014-10-22 15:29:23 +000042 EnableUnsafeFPShrink("enable-double-float-shrink", cl::Hidden,
43 cl::init(false),
44 cl::desc("Enable unsafe double to float "
45 "shrinking for math lib calls"));
46
47
Meador Ingedf796f82012-10-13 16:45:24 +000048//===----------------------------------------------------------------------===//
Meador Inged589ac62012-10-31 03:33:06 +000049// Helper Functions
50//===----------------------------------------------------------------------===//
51
David L. Jonesd21529f2017-01-23 23:16:46 +000052static bool ignoreCallingConv(LibFunc Func) {
53 return Func == LibFunc_abs || Func == LibFunc_labs ||
54 Func == LibFunc_llabs || Func == LibFunc_strlen;
Chris Bienemanad070d02014-09-17 20:55:46 +000055}
56
Sam Parker214f7bf2016-09-13 12:10:14 +000057static bool isCallingConvCCompatible(CallInst *CI) {
58 switch(CI->getCallingConv()) {
59 default:
60 return false;
61 case llvm::CallingConv::C:
62 return true;
63 case llvm::CallingConv::ARM_APCS:
64 case llvm::CallingConv::ARM_AAPCS:
65 case llvm::CallingConv::ARM_AAPCS_VFP: {
66
67 // The iOS ABI diverges from the standard in some cases, so for now don't
68 // try to simplify those calls.
69 if (Triple(CI->getModule()->getTargetTriple()).isiOS())
70 return false;
71
72 auto *FuncTy = CI->getFunctionType();
73
74 if (!FuncTy->getReturnType()->isPointerTy() &&
75 !FuncTy->getReturnType()->isIntegerTy() &&
76 !FuncTy->getReturnType()->isVoidTy())
77 return false;
78
79 for (auto Param : FuncTy->params()) {
80 if (!Param->isPointerTy() && !Param->isIntegerTy())
81 return false;
82 }
83 return true;
84 }
85 }
86 return false;
87}
88
Sanjay Pateld707db92015-12-31 16:10:49 +000089/// Return true if it is only used in equality comparisons with With.
Meador Inge56edbc92012-11-11 03:51:48 +000090static bool isOnlyUsedInEqualityComparison(Value *V, Value *With) {
Chandler Carruthcdf47882014-03-09 03:16:01 +000091 for (User *U : V->users()) {
92 if (ICmpInst *IC = dyn_cast<ICmpInst>(U))
Meador Inge56edbc92012-11-11 03:51:48 +000093 if (IC->isEquality() && IC->getOperand(1) == With)
94 continue;
95 // Unknown instruction.
96 return false;
97 }
98 return true;
99}
100
Meador Inge08ca1152012-11-26 20:37:20 +0000101static bool callHasFloatingPointArgument(const CallInst *CI) {
David Majnemer0a16c222016-08-11 21:15:00 +0000102 return any_of(CI->operands(), [](const Use &OI) {
Davide Italianoda3beeb2015-11-28 22:27:48 +0000103 return OI->getType()->isFloatingPointTy();
104 });
Meador Inge08ca1152012-11-26 20:37:20 +0000105}
106
Benjamin Kramer2702caa2013-08-31 18:19:35 +0000107/// \brief Check whether the overloaded unary floating point function
Sanjay Patele24c60e2015-08-12 20:36:18 +0000108/// corresponding to \a Ty is available.
Benjamin Kramer2702caa2013-08-31 18:19:35 +0000109static bool hasUnaryFloatFn(const TargetLibraryInfo *TLI, Type *Ty,
David L. Jonesd21529f2017-01-23 23:16:46 +0000110 LibFunc DoubleFn, LibFunc FloatFn,
111 LibFunc LongDoubleFn) {
Benjamin Kramer2702caa2013-08-31 18:19:35 +0000112 switch (Ty->getTypeID()) {
113 case Type::FloatTyID:
114 return TLI->has(FloatFn);
115 case Type::DoubleTyID:
116 return TLI->has(DoubleFn);
117 default:
118 return TLI->has(LongDoubleFn);
119 }
120}
121
Meador Inged589ac62012-10-31 03:33:06 +0000122//===----------------------------------------------------------------------===//
Meador Inge7fb2f732012-10-13 16:45:32 +0000123// String and Memory Library Call Optimizations
124//===----------------------------------------------------------------------===//
125
Chris Bienemanad070d02014-09-17 20:55:46 +0000126Value *LibCallSimplifier::optimizeStrCat(CallInst *CI, IRBuilder<> &B) {
Chris Bienemanad070d02014-09-17 20:55:46 +0000127 // Extract some information from the instruction
128 Value *Dst = CI->getArgOperand(0);
129 Value *Src = CI->getArgOperand(1);
130
131 // See if we can get the length of the input string.
132 uint64_t Len = GetStringLength(Src);
133 if (Len == 0)
134 return nullptr;
135 --Len; // Unbias length.
136
137 // Handle the simple, do-nothing case: strcat(x, "") -> x
138 if (Len == 0)
139 return Dst;
140
Chris Bienemanad070d02014-09-17 20:55:46 +0000141 return emitStrLenMemCpy(Src, Dst, Len, B);
142}
143
144Value *LibCallSimplifier::emitStrLenMemCpy(Value *Src, Value *Dst, uint64_t Len,
145 IRBuilder<> &B) {
146 // We need to find the end of the destination string. That's where the
147 // memory is to be moved to. We just generate a call to strlen.
Sanjay Pateld3112a52016-01-19 19:46:10 +0000148 Value *DstLen = emitStrLen(Dst, B, DL, TLI);
Chris Bienemanad070d02014-09-17 20:55:46 +0000149 if (!DstLen)
150 return nullptr;
151
152 // Now that we have the destination's length, we must index into the
153 // destination's pointer to get the actual memcpy destination (end of
154 // the string .. we're concatenating).
David Blaikie3909da72015-03-30 20:42:56 +0000155 Value *CpyDst = B.CreateGEP(B.getInt8Ty(), Dst, DstLen, "endptr");
Chris Bienemanad070d02014-09-17 20:55:46 +0000156
157 // We have enough information to now generate the memcpy call to do the
158 // concatenation for us. Make a memcpy to copy the nul byte with align = 1.
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000159 B.CreateMemCpy(CpyDst, Src,
160 ConstantInt::get(DL.getIntPtrType(Src->getContext()), Len + 1),
Pete Cooper67cf9a72015-11-19 05:56:52 +0000161 1);
Chris Bienemanad070d02014-09-17 20:55:46 +0000162 return Dst;
163}
164
165Value *LibCallSimplifier::optimizeStrNCat(CallInst *CI, IRBuilder<> &B) {
Sanjay Pateld707db92015-12-31 16:10:49 +0000166 // Extract some information from the instruction.
Chris Bienemanad070d02014-09-17 20:55:46 +0000167 Value *Dst = CI->getArgOperand(0);
168 Value *Src = CI->getArgOperand(1);
169 uint64_t Len;
170
Sanjay Pateld707db92015-12-31 16:10:49 +0000171 // We don't do anything if length is not constant.
Chris Bienemanad070d02014-09-17 20:55:46 +0000172 if (ConstantInt *LengthArg = dyn_cast<ConstantInt>(CI->getArgOperand(2)))
173 Len = LengthArg->getZExtValue();
174 else
175 return nullptr;
176
177 // See if we can get the length of the input string.
178 uint64_t SrcLen = GetStringLength(Src);
179 if (SrcLen == 0)
180 return nullptr;
181 --SrcLen; // Unbias length.
182
183 // Handle the simple, do-nothing cases:
184 // strncat(x, "", c) -> x
185 // strncat(x, c, 0) -> x
186 if (SrcLen == 0 || Len == 0)
187 return Dst;
188
Sanjay Pateld707db92015-12-31 16:10:49 +0000189 // We don't optimize this case.
Chris Bienemanad070d02014-09-17 20:55:46 +0000190 if (Len < SrcLen)
191 return nullptr;
192
193 // strncat(x, s, c) -> strcat(x, s)
Sanjay Pateld707db92015-12-31 16:10:49 +0000194 // s is constant so the strcat can be optimized further.
Chris Bienemanad070d02014-09-17 20:55:46 +0000195 return emitStrLenMemCpy(Src, Dst, SrcLen, B);
196}
197
198Value *LibCallSimplifier::optimizeStrChr(CallInst *CI, IRBuilder<> &B) {
199 Function *Callee = CI->getCalledFunction();
Chris Bienemanad070d02014-09-17 20:55:46 +0000200 FunctionType *FT = Callee->getFunctionType();
Chris Bienemanad070d02014-09-17 20:55:46 +0000201 Value *SrcStr = CI->getArgOperand(0);
202
203 // If the second operand is non-constant, see if we can compute the length
204 // of the input string and turn this into memchr.
205 ConstantInt *CharC = dyn_cast<ConstantInt>(CI->getArgOperand(1));
206 if (!CharC) {
Chris Bienemanad070d02014-09-17 20:55:46 +0000207 uint64_t Len = GetStringLength(SrcStr);
208 if (Len == 0 || !FT->getParamType(1)->isIntegerTy(32)) // memchr needs i32.
209 return nullptr;
Meador Inge7fb2f732012-10-13 16:45:32 +0000210
Sanjay Pateld3112a52016-01-19 19:46:10 +0000211 return emitMemChr(SrcStr, CI->getArgOperand(1), // include nul.
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000212 ConstantInt::get(DL.getIntPtrType(CI->getContext()), Len),
213 B, DL, TLI);
Meador Inge7fb2f732012-10-13 16:45:32 +0000214 }
215
Chris Bienemanad070d02014-09-17 20:55:46 +0000216 // Otherwise, the character is a constant, see if the first argument is
217 // a string literal. If so, we can constant fold.
218 StringRef Str;
219 if (!getConstantStringInfo(SrcStr, Str)) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000220 if (CharC->isZero()) // strchr(p, 0) -> p + strlen(p)
Sanjay Pateld3112a52016-01-19 19:46:10 +0000221 return B.CreateGEP(B.getInt8Ty(), SrcStr, emitStrLen(SrcStr, B, DL, TLI),
Sanjay Pateld707db92015-12-31 16:10:49 +0000222 "strchr");
Chris Bienemanad070d02014-09-17 20:55:46 +0000223 return nullptr;
224 }
225
226 // Compute the offset, make sure to handle the case when we're searching for
227 // zero (a weird way to spell strlen).
228 size_t I = (0xFF & CharC->getSExtValue()) == 0
229 ? Str.size()
230 : Str.find(CharC->getSExtValue());
231 if (I == StringRef::npos) // Didn't find the char. strchr returns null.
232 return Constant::getNullValue(CI->getType());
233
234 // strchr(s+n,c) -> gep(s+n+i,c)
David Blaikie3909da72015-03-30 20:42:56 +0000235 return B.CreateGEP(B.getInt8Ty(), SrcStr, B.getInt64(I), "strchr");
Chris Bienemanad070d02014-09-17 20:55:46 +0000236}
237
238Value *LibCallSimplifier::optimizeStrRChr(CallInst *CI, IRBuilder<> &B) {
Chris Bienemanad070d02014-09-17 20:55:46 +0000239 Value *SrcStr = CI->getArgOperand(0);
240 ConstantInt *CharC = dyn_cast<ConstantInt>(CI->getArgOperand(1));
241
242 // Cannot fold anything if we're not looking for a constant.
243 if (!CharC)
244 return nullptr;
245
246 StringRef Str;
247 if (!getConstantStringInfo(SrcStr, Str)) {
248 // strrchr(s, 0) -> strchr(s, 0)
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000249 if (CharC->isZero())
Sanjay Pateld3112a52016-01-19 19:46:10 +0000250 return emitStrChr(SrcStr, '\0', B, TLI);
Chris Bienemanad070d02014-09-17 20:55:46 +0000251 return nullptr;
252 }
253
254 // Compute the offset.
255 size_t I = (0xFF & CharC->getSExtValue()) == 0
256 ? Str.size()
257 : Str.rfind(CharC->getSExtValue());
258 if (I == StringRef::npos) // Didn't find the char. Return null.
259 return Constant::getNullValue(CI->getType());
260
261 // strrchr(s+n,c) -> gep(s+n+i,c)
David Blaikie3909da72015-03-30 20:42:56 +0000262 return B.CreateGEP(B.getInt8Ty(), SrcStr, B.getInt64(I), "strrchr");
Chris Bienemanad070d02014-09-17 20:55:46 +0000263}
264
265Value *LibCallSimplifier::optimizeStrCmp(CallInst *CI, IRBuilder<> &B) {
Chris Bienemanad070d02014-09-17 20:55:46 +0000266 Value *Str1P = CI->getArgOperand(0), *Str2P = CI->getArgOperand(1);
267 if (Str1P == Str2P) // strcmp(x,x) -> 0
268 return ConstantInt::get(CI->getType(), 0);
269
270 StringRef Str1, Str2;
271 bool HasStr1 = getConstantStringInfo(Str1P, Str1);
272 bool HasStr2 = getConstantStringInfo(Str2P, Str2);
273
274 // strcmp(x, y) -> cnst (if both x and y are constant strings)
275 if (HasStr1 && HasStr2)
276 return ConstantInt::get(CI->getType(), Str1.compare(Str2));
277
278 if (HasStr1 && Str1.empty()) // strcmp("", x) -> -*x
279 return B.CreateNeg(
280 B.CreateZExt(B.CreateLoad(Str2P, "strcmpload"), CI->getType()));
281
282 if (HasStr2 && Str2.empty()) // strcmp(x,"") -> *x
283 return B.CreateZExt(B.CreateLoad(Str1P, "strcmpload"), CI->getType());
284
285 // strcmp(P, "x") -> memcmp(P, "x", 2)
286 uint64_t Len1 = GetStringLength(Str1P);
287 uint64_t Len2 = GetStringLength(Str2P);
288 if (Len1 && Len2) {
Sanjay Pateld3112a52016-01-19 19:46:10 +0000289 return emitMemCmp(Str1P, Str2P,
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000290 ConstantInt::get(DL.getIntPtrType(CI->getContext()),
Chris Bienemanad070d02014-09-17 20:55:46 +0000291 std::min(Len1, Len2)),
292 B, DL, TLI);
293 }
Meador Inge7fb2f732012-10-13 16:45:32 +0000294
Chris Bienemanad070d02014-09-17 20:55:46 +0000295 return nullptr;
296}
297
298Value *LibCallSimplifier::optimizeStrNCmp(CallInst *CI, IRBuilder<> &B) {
Chris Bienemanad070d02014-09-17 20:55:46 +0000299 Value *Str1P = CI->getArgOperand(0), *Str2P = CI->getArgOperand(1);
300 if (Str1P == Str2P) // strncmp(x,x,n) -> 0
301 return ConstantInt::get(CI->getType(), 0);
302
303 // Get the length argument if it is constant.
304 uint64_t Length;
305 if (ConstantInt *LengthArg = dyn_cast<ConstantInt>(CI->getArgOperand(2)))
306 Length = LengthArg->getZExtValue();
307 else
308 return nullptr;
309
310 if (Length == 0) // strncmp(x,y,0) -> 0
311 return ConstantInt::get(CI->getType(), 0);
312
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000313 if (Length == 1) // strncmp(x,y,1) -> memcmp(x,y,1)
Sanjay Pateld3112a52016-01-19 19:46:10 +0000314 return emitMemCmp(Str1P, Str2P, CI->getArgOperand(2), B, DL, TLI);
Chris Bienemanad070d02014-09-17 20:55:46 +0000315
316 StringRef Str1, Str2;
317 bool HasStr1 = getConstantStringInfo(Str1P, Str1);
318 bool HasStr2 = getConstantStringInfo(Str2P, Str2);
319
320 // strncmp(x, y) -> cnst (if both x and y are constant strings)
321 if (HasStr1 && HasStr2) {
322 StringRef SubStr1 = Str1.substr(0, Length);
323 StringRef SubStr2 = Str2.substr(0, Length);
324 return ConstantInt::get(CI->getType(), SubStr1.compare(SubStr2));
325 }
326
327 if (HasStr1 && Str1.empty()) // strncmp("", x, n) -> -*x
328 return B.CreateNeg(
329 B.CreateZExt(B.CreateLoad(Str2P, "strcmpload"), CI->getType()));
330
331 if (HasStr2 && Str2.empty()) // strncmp(x, "", n) -> *x
332 return B.CreateZExt(B.CreateLoad(Str1P, "strcmpload"), CI->getType());
333
334 return nullptr;
335}
336
337Value *LibCallSimplifier::optimizeStrCpy(CallInst *CI, IRBuilder<> &B) {
Chris Bienemanad070d02014-09-17 20:55:46 +0000338 Value *Dst = CI->getArgOperand(0), *Src = CI->getArgOperand(1);
339 if (Dst == Src) // strcpy(x,x) -> x
340 return Src;
341
Chris Bienemanad070d02014-09-17 20:55:46 +0000342 // See if we can get the length of the input string.
343 uint64_t Len = GetStringLength(Src);
344 if (Len == 0)
345 return nullptr;
346
347 // We have enough information to now generate the memcpy call to do the
348 // copy for us. Make a memcpy to copy the nul byte with align = 1.
349 B.CreateMemCpy(Dst, Src,
Pete Cooper67cf9a72015-11-19 05:56:52 +0000350 ConstantInt::get(DL.getIntPtrType(CI->getContext()), Len), 1);
Chris Bienemanad070d02014-09-17 20:55:46 +0000351 return Dst;
352}
353
354Value *LibCallSimplifier::optimizeStpCpy(CallInst *CI, IRBuilder<> &B) {
355 Function *Callee = CI->getCalledFunction();
Chris Bienemanad070d02014-09-17 20:55:46 +0000356 Value *Dst = CI->getArgOperand(0), *Src = CI->getArgOperand(1);
357 if (Dst == Src) { // stpcpy(x,x) -> x+strlen(x)
Sanjay Pateld3112a52016-01-19 19:46:10 +0000358 Value *StrLen = emitStrLen(Src, B, DL, TLI);
David Blaikieaa41cd52015-04-03 21:33:42 +0000359 return StrLen ? B.CreateInBoundsGEP(B.getInt8Ty(), Dst, StrLen) : nullptr;
Chris Bienemanad070d02014-09-17 20:55:46 +0000360 }
361
362 // See if we can get the length of the input string.
363 uint64_t Len = GetStringLength(Src);
364 if (Len == 0)
365 return nullptr;
366
Davide Italianob7487e62015-11-02 23:07:14 +0000367 Type *PT = Callee->getFunctionType()->getParamType(0);
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000368 Value *LenV = ConstantInt::get(DL.getIntPtrType(PT), Len);
Sanjay Pateld707db92015-12-31 16:10:49 +0000369 Value *DstEnd = B.CreateGEP(B.getInt8Ty(), Dst,
370 ConstantInt::get(DL.getIntPtrType(PT), Len - 1));
Chris Bienemanad070d02014-09-17 20:55:46 +0000371
372 // We have enough information to now generate the memcpy call to do the
373 // copy for us. Make a memcpy to copy the nul byte with align = 1.
Pete Cooper67cf9a72015-11-19 05:56:52 +0000374 B.CreateMemCpy(Dst, Src, LenV, 1);
Chris Bienemanad070d02014-09-17 20:55:46 +0000375 return DstEnd;
376}
377
378Value *LibCallSimplifier::optimizeStrNCpy(CallInst *CI, IRBuilder<> &B) {
379 Function *Callee = CI->getCalledFunction();
Chris Bienemanad070d02014-09-17 20:55:46 +0000380 Value *Dst = CI->getArgOperand(0);
381 Value *Src = CI->getArgOperand(1);
382 Value *LenOp = CI->getArgOperand(2);
383
384 // See if we can get the length of the input string.
385 uint64_t SrcLen = GetStringLength(Src);
386 if (SrcLen == 0)
387 return nullptr;
388 --SrcLen;
389
390 if (SrcLen == 0) {
391 // strncpy(x, "", y) -> memset(x, '\0', y, 1)
392 B.CreateMemSet(Dst, B.getInt8('\0'), LenOp, 1);
Meador Inge7fb2f732012-10-13 16:45:32 +0000393 return Dst;
394 }
Meador Inge7fb2f732012-10-13 16:45:32 +0000395
Chris Bienemanad070d02014-09-17 20:55:46 +0000396 uint64_t Len;
397 if (ConstantInt *LengthArg = dyn_cast<ConstantInt>(LenOp))
398 Len = LengthArg->getZExtValue();
399 else
400 return nullptr;
Meador Inge7fb2f732012-10-13 16:45:32 +0000401
Chris Bienemanad070d02014-09-17 20:55:46 +0000402 if (Len == 0)
403 return Dst; // strncpy(x, y, 0) -> x
Meador Inge7fb2f732012-10-13 16:45:32 +0000404
Chris Bienemanad070d02014-09-17 20:55:46 +0000405 // Let strncpy handle the zero padding
406 if (Len > SrcLen + 1)
407 return nullptr;
Meador Inge7fb2f732012-10-13 16:45:32 +0000408
Davide Italianob7487e62015-11-02 23:07:14 +0000409 Type *PT = Callee->getFunctionType()->getParamType(0);
Chris Bienemanad070d02014-09-17 20:55:46 +0000410 // strncpy(x, s, c) -> memcpy(x, s, c, 1) [s and c are constant]
Pete Cooper67cf9a72015-11-19 05:56:52 +0000411 B.CreateMemCpy(Dst, Src, ConstantInt::get(DL.getIntPtrType(PT), Len), 1);
Meador Inge7fb2f732012-10-13 16:45:32 +0000412
Chris Bienemanad070d02014-09-17 20:55:46 +0000413 return Dst;
414}
Meador Inge7fb2f732012-10-13 16:45:32 +0000415
Matthias Braun50ec0b52017-05-19 22:37:09 +0000416Value *LibCallSimplifier::optimizeStringLength(CallInst *CI, IRBuilder<> &B,
417 unsigned CharSize) {
Chris Bienemanad070d02014-09-17 20:55:46 +0000418 Value *Src = CI->getArgOperand(0);
419
420 // Constant folding: strlen("xyz") -> 3
Matthias Braun50ec0b52017-05-19 22:37:09 +0000421 if (uint64_t Len = GetStringLength(Src, CharSize))
Chris Bienemanad070d02014-09-17 20:55:46 +0000422 return ConstantInt::get(CI->getType(), Len - 1);
423
David L Kreitzer752c1442016-04-13 14:31:06 +0000424 // If s is a constant pointer pointing to a string literal, we can fold
Matthias Braun50ec0b52017-05-19 22:37:09 +0000425 // strlen(s + x) to strlen(s) - x, when x is known to be in the range
David L Kreitzer752c1442016-04-13 14:31:06 +0000426 // [0, strlen(s)] or the string has a single null terminator '\0' at the end.
Matthias Braun50ec0b52017-05-19 22:37:09 +0000427 // We only try to simplify strlen when the pointer s points to an array
David L Kreitzer752c1442016-04-13 14:31:06 +0000428 // of i8. Otherwise, we would need to scale the offset x before doing the
Matthias Braun50ec0b52017-05-19 22:37:09 +0000429 // subtraction. This will make the optimization more complex, and it's not
430 // very useful because calling strlen for a pointer of other types is
David L Kreitzer752c1442016-04-13 14:31:06 +0000431 // very uncommon.
432 if (GEPOperator *GEP = dyn_cast<GEPOperator>(Src)) {
Matthias Braun50ec0b52017-05-19 22:37:09 +0000433 if (!isGEPBasedOnPointerToString(GEP, CharSize))
David L Kreitzer752c1442016-04-13 14:31:06 +0000434 return nullptr;
435
Matthias Braun50ec0b52017-05-19 22:37:09 +0000436 ConstantDataArraySlice Slice;
437 if (getConstantDataArrayInfo(GEP->getOperand(0), Slice, CharSize)) {
438 uint64_t NullTermIdx;
439 if (Slice.Array == nullptr) {
440 NullTermIdx = 0;
441 } else {
442 NullTermIdx = ~((uint64_t)0);
443 for (uint64_t I = 0, E = Slice.Length; I < E; ++I) {
444 if (Slice.Array->getElementAsInteger(I + Slice.Offset) == 0) {
445 NullTermIdx = I;
446 break;
447 }
448 }
449 // If the string does not have '\0', leave it to strlen to compute
450 // its length.
451 if (NullTermIdx == ~((uint64_t)0))
452 return nullptr;
453 }
454
David L Kreitzer752c1442016-04-13 14:31:06 +0000455 Value *Offset = GEP->getOperand(2);
Craig Topper8205a1a2017-05-24 16:53:07 +0000456 KnownBits Known = computeKnownBits(Offset, DL, 0, nullptr, CI, nullptr);
Craig Topperb45eabc2017-04-26 16:39:58 +0000457 Known.Zero.flipAllBits();
Matthias Braun50ec0b52017-05-19 22:37:09 +0000458 uint64_t ArrSize =
David L Kreitzer752c1442016-04-13 14:31:06 +0000459 cast<ArrayType>(GEP->getSourceElementType())->getNumElements();
460
Matthias Braun50ec0b52017-05-19 22:37:09 +0000461 // KnownZero's bits are flipped, so zeros in KnownZero now represent
462 // bits known to be zeros in Offset, and ones in KnowZero represent
David L Kreitzer752c1442016-04-13 14:31:06 +0000463 // bits unknown in Offset. Therefore, Offset is known to be in range
Matthias Braun50ec0b52017-05-19 22:37:09 +0000464 // [0, NullTermIdx] when the flipped KnownZero is non-negative and
David L Kreitzer752c1442016-04-13 14:31:06 +0000465 // unsigned-less-than NullTermIdx.
466 //
Matthias Braun50ec0b52017-05-19 22:37:09 +0000467 // If Offset is not provably in the range [0, NullTermIdx], we can still
468 // optimize if we can prove that the program has undefined behavior when
469 // Offset is outside that range. That is the case when GEP->getOperand(0)
David L Kreitzer752c1442016-04-13 14:31:06 +0000470 // is a pointer to an object whose memory extent is NullTermIdx+1.
Matthias Braun50ec0b52017-05-19 22:37:09 +0000471 if ((Known.Zero.isNonNegative() && Known.Zero.ule(NullTermIdx)) ||
David L Kreitzer752c1442016-04-13 14:31:06 +0000472 (GEP->isInBounds() && isa<GlobalVariable>(GEP->getOperand(0)) &&
Matthias Braun50ec0b52017-05-19 22:37:09 +0000473 NullTermIdx == ArrSize - 1)) {
474 Offset = B.CreateSExtOrTrunc(Offset, CI->getType());
475 return B.CreateSub(ConstantInt::get(CI->getType(), NullTermIdx),
David L Kreitzer752c1442016-04-13 14:31:06 +0000476 Offset);
Matthias Braun50ec0b52017-05-19 22:37:09 +0000477 }
David L Kreitzer752c1442016-04-13 14:31:06 +0000478 }
479
480 return nullptr;
481 }
482
Chris Bienemanad070d02014-09-17 20:55:46 +0000483 // strlen(x?"foo":"bars") --> x ? 3 : 4
484 if (SelectInst *SI = dyn_cast<SelectInst>(Src)) {
Matthias Braun50ec0b52017-05-19 22:37:09 +0000485 uint64_t LenTrue = GetStringLength(SI->getTrueValue(), CharSize);
486 uint64_t LenFalse = GetStringLength(SI->getFalseValue(), CharSize);
Chris Bienemanad070d02014-09-17 20:55:46 +0000487 if (LenTrue && LenFalse) {
Adam Nemetea06e6e2017-07-26 19:03:18 +0000488 ORE.emit(OptimizationRemark("instcombine", "simplify-libcalls", CI)
489 << "folded strlen(select) to select of constants");
Chris Bienemanad070d02014-09-17 20:55:46 +0000490 return B.CreateSelect(SI->getCondition(),
491 ConstantInt::get(CI->getType(), LenTrue - 1),
492 ConstantInt::get(CI->getType(), LenFalse - 1));
493 }
Meador Inge7fb2f732012-10-13 16:45:32 +0000494 }
Meador Inge7fb2f732012-10-13 16:45:32 +0000495
Chris Bienemanad070d02014-09-17 20:55:46 +0000496 // strlen(x) != 0 --> *x != 0
497 // strlen(x) == 0 --> *x == 0
498 if (isOnlyUsedInZeroEqualityComparison(CI))
499 return B.CreateZExt(B.CreateLoad(Src, "strlenfirst"), CI->getType());
Meador Inge17418502012-10-13 16:45:37 +0000500
Chris Bienemanad070d02014-09-17 20:55:46 +0000501 return nullptr;
502}
Meador Inge17418502012-10-13 16:45:37 +0000503
Matthias Braun50ec0b52017-05-19 22:37:09 +0000504Value *LibCallSimplifier::optimizeStrLen(CallInst *CI, IRBuilder<> &B) {
505 return optimizeStringLength(CI, B, 8);
506}
507
508Value *LibCallSimplifier::optimizeWcslen(CallInst *CI, IRBuilder<> &B) {
509 Module &M = *CI->getParent()->getParent()->getParent();
510 unsigned WCharSize = TLI->getWCharSize(M) * 8;
Matthias Brauncc603ee2017-09-26 02:36:57 +0000511 // We cannot perform this optimization without wchar_size metadata.
512 if (WCharSize == 0)
513 return nullptr;
Matthias Braun50ec0b52017-05-19 22:37:09 +0000514
515 return optimizeStringLength(CI, B, WCharSize);
516}
517
Chris Bienemanad070d02014-09-17 20:55:46 +0000518Value *LibCallSimplifier::optimizeStrPBrk(CallInst *CI, IRBuilder<> &B) {
Chris Bienemanad070d02014-09-17 20:55:46 +0000519 StringRef S1, S2;
520 bool HasS1 = getConstantStringInfo(CI->getArgOperand(0), S1);
521 bool HasS2 = getConstantStringInfo(CI->getArgOperand(1), S2);
Meador Inge17418502012-10-13 16:45:37 +0000522
Reid Kleckner971c3ea2014-11-13 22:55:19 +0000523 // strpbrk(s, "") -> nullptr
524 // strpbrk("", s) -> nullptr
Chris Bienemanad070d02014-09-17 20:55:46 +0000525 if ((HasS1 && S1.empty()) || (HasS2 && S2.empty()))
526 return Constant::getNullValue(CI->getType());
Meador Inge17418502012-10-13 16:45:37 +0000527
Chris Bienemanad070d02014-09-17 20:55:46 +0000528 // Constant folding.
529 if (HasS1 && HasS2) {
530 size_t I = S1.find_first_of(S2);
531 if (I == StringRef::npos) // No match.
Meador Inge17418502012-10-13 16:45:37 +0000532 return Constant::getNullValue(CI->getType());
533
Sanjay Pateld707db92015-12-31 16:10:49 +0000534 return B.CreateGEP(B.getInt8Ty(), CI->getArgOperand(0), B.getInt64(I),
535 "strpbrk");
Meador Inge17418502012-10-13 16:45:37 +0000536 }
Meador Inge17418502012-10-13 16:45:37 +0000537
Chris Bienemanad070d02014-09-17 20:55:46 +0000538 // strpbrk(s, "a") -> strchr(s, 'a')
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000539 if (HasS2 && S2.size() == 1)
Sanjay Pateld3112a52016-01-19 19:46:10 +0000540 return emitStrChr(CI->getArgOperand(0), S2[0], B, TLI);
Chris Bienemanad070d02014-09-17 20:55:46 +0000541
542 return nullptr;
543}
544
545Value *LibCallSimplifier::optimizeStrTo(CallInst *CI, IRBuilder<> &B) {
Chris Bienemanad070d02014-09-17 20:55:46 +0000546 Value *EndPtr = CI->getArgOperand(1);
547 if (isa<ConstantPointerNull>(EndPtr)) {
548 // With a null EndPtr, this function won't capture the main argument.
549 // It would be readonly too, except that it still may write to errno.
Reid Klecknera0b45f42017-05-03 18:17:31 +0000550 CI->addParamAttr(0, Attribute::NoCapture);
Chris Bienemanad070d02014-09-17 20:55:46 +0000551 }
552
553 return nullptr;
554}
555
556Value *LibCallSimplifier::optimizeStrSpn(CallInst *CI, IRBuilder<> &B) {
Chris Bienemanad070d02014-09-17 20:55:46 +0000557 StringRef S1, S2;
558 bool HasS1 = getConstantStringInfo(CI->getArgOperand(0), S1);
559 bool HasS2 = getConstantStringInfo(CI->getArgOperand(1), S2);
560
561 // strspn(s, "") -> 0
562 // strspn("", s) -> 0
563 if ((HasS1 && S1.empty()) || (HasS2 && S2.empty()))
564 return Constant::getNullValue(CI->getType());
565
566 // Constant folding.
567 if (HasS1 && HasS2) {
568 size_t Pos = S1.find_first_not_of(S2);
569 if (Pos == StringRef::npos)
570 Pos = S1.size();
571 return ConstantInt::get(CI->getType(), Pos);
572 }
573
574 return nullptr;
575}
576
577Value *LibCallSimplifier::optimizeStrCSpn(CallInst *CI, IRBuilder<> &B) {
Chris Bienemanad070d02014-09-17 20:55:46 +0000578 StringRef S1, S2;
579 bool HasS1 = getConstantStringInfo(CI->getArgOperand(0), S1);
580 bool HasS2 = getConstantStringInfo(CI->getArgOperand(1), S2);
581
582 // strcspn("", s) -> 0
583 if (HasS1 && S1.empty())
584 return Constant::getNullValue(CI->getType());
585
586 // Constant folding.
587 if (HasS1 && HasS2) {
588 size_t Pos = S1.find_first_of(S2);
589 if (Pos == StringRef::npos)
590 Pos = S1.size();
591 return ConstantInt::get(CI->getType(), Pos);
592 }
593
594 // strcspn(s, "") -> strlen(s)
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000595 if (HasS2 && S2.empty())
Sanjay Pateld3112a52016-01-19 19:46:10 +0000596 return emitStrLen(CI->getArgOperand(0), B, DL, TLI);
Chris Bienemanad070d02014-09-17 20:55:46 +0000597
598 return nullptr;
599}
600
601Value *LibCallSimplifier::optimizeStrStr(CallInst *CI, IRBuilder<> &B) {
Chris Bienemanad070d02014-09-17 20:55:46 +0000602 // fold strstr(x, x) -> x.
603 if (CI->getArgOperand(0) == CI->getArgOperand(1))
604 return B.CreateBitCast(CI->getArgOperand(0), CI->getType());
605
606 // fold strstr(a, b) == a -> strncmp(a, b, strlen(b)) == 0
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000607 if (isOnlyUsedInEqualityComparison(CI, CI->getArgOperand(0))) {
Sanjay Pateld3112a52016-01-19 19:46:10 +0000608 Value *StrLen = emitStrLen(CI->getArgOperand(1), B, DL, TLI);
Chris Bienemanad070d02014-09-17 20:55:46 +0000609 if (!StrLen)
Craig Topperf40110f2014-04-25 05:29:35 +0000610 return nullptr;
Sanjay Pateld3112a52016-01-19 19:46:10 +0000611 Value *StrNCmp = emitStrNCmp(CI->getArgOperand(0), CI->getArgOperand(1),
Chris Bienemanad070d02014-09-17 20:55:46 +0000612 StrLen, B, DL, TLI);
613 if (!StrNCmp)
Craig Topperf40110f2014-04-25 05:29:35 +0000614 return nullptr;
Chris Bienemanad070d02014-09-17 20:55:46 +0000615 for (auto UI = CI->user_begin(), UE = CI->user_end(); UI != UE;) {
616 ICmpInst *Old = cast<ICmpInst>(*UI++);
617 Value *Cmp =
618 B.CreateICmp(Old->getPredicate(), StrNCmp,
619 ConstantInt::getNullValue(StrNCmp->getType()), "cmp");
620 replaceAllUsesWith(Old, Cmp);
Meador Inge17418502012-10-13 16:45:37 +0000621 }
Chris Bienemanad070d02014-09-17 20:55:46 +0000622 return CI;
623 }
Meador Inge17418502012-10-13 16:45:37 +0000624
Chris Bienemanad070d02014-09-17 20:55:46 +0000625 // See if either input string is a constant string.
626 StringRef SearchStr, ToFindStr;
627 bool HasStr1 = getConstantStringInfo(CI->getArgOperand(0), SearchStr);
628 bool HasStr2 = getConstantStringInfo(CI->getArgOperand(1), ToFindStr);
629
630 // fold strstr(x, "") -> x.
631 if (HasStr2 && ToFindStr.empty())
632 return B.CreateBitCast(CI->getArgOperand(0), CI->getType());
633
634 // If both strings are known, constant fold it.
635 if (HasStr1 && HasStr2) {
636 size_t Offset = SearchStr.find(ToFindStr);
637
638 if (Offset == StringRef::npos) // strstr("foo", "bar") -> null
Meador Inge17418502012-10-13 16:45:37 +0000639 return Constant::getNullValue(CI->getType());
640
Chris Bienemanad070d02014-09-17 20:55:46 +0000641 // strstr("abcd", "bc") -> gep((char*)"abcd", 1)
Sanjay Pateld3112a52016-01-19 19:46:10 +0000642 Value *Result = castToCStr(CI->getArgOperand(0), B);
Chris Bienemanad070d02014-09-17 20:55:46 +0000643 Result = B.CreateConstInBoundsGEP1_64(Result, Offset, "strstr");
644 return B.CreateBitCast(Result, CI->getType());
Meador Inge17418502012-10-13 16:45:37 +0000645 }
Meador Inge17418502012-10-13 16:45:37 +0000646
Chris Bienemanad070d02014-09-17 20:55:46 +0000647 // fold strstr(x, "y") -> strchr(x, 'y').
648 if (HasStr2 && ToFindStr.size() == 1) {
Sanjay Pateld3112a52016-01-19 19:46:10 +0000649 Value *StrChr = emitStrChr(CI->getArgOperand(0), ToFindStr[0], B, TLI);
Chris Bienemanad070d02014-09-17 20:55:46 +0000650 return StrChr ? B.CreateBitCast(StrChr, CI->getType()) : nullptr;
651 }
652 return nullptr;
653}
Meador Inge40b6fac2012-10-15 03:47:37 +0000654
Benjamin Kramer691363e2015-03-21 15:36:21 +0000655Value *LibCallSimplifier::optimizeMemChr(CallInst *CI, IRBuilder<> &B) {
Benjamin Kramer691363e2015-03-21 15:36:21 +0000656 Value *SrcStr = CI->getArgOperand(0);
657 ConstantInt *CharC = dyn_cast<ConstantInt>(CI->getArgOperand(1));
658 ConstantInt *LenC = dyn_cast<ConstantInt>(CI->getArgOperand(2));
659
660 // memchr(x, y, 0) -> null
Craig Topper79ab6432017-07-06 18:39:47 +0000661 if (LenC && LenC->isZero())
Benjamin Kramer691363e2015-03-21 15:36:21 +0000662 return Constant::getNullValue(CI->getType());
663
Benjamin Kramer7857d722015-03-21 21:09:33 +0000664 // From now on we need at least constant length and string.
Benjamin Kramer691363e2015-03-21 15:36:21 +0000665 StringRef Str;
Benjamin Kramer7857d722015-03-21 21:09:33 +0000666 if (!LenC || !getConstantStringInfo(SrcStr, Str, 0, /*TrimAtNul=*/false))
Benjamin Kramer691363e2015-03-21 15:36:21 +0000667 return nullptr;
668
669 // Truncate the string to LenC. If Str is smaller than LenC we will still only
670 // scan the string, as reading past the end of it is undefined and we can just
671 // return null if we don't find the char.
672 Str = Str.substr(0, LenC->getZExtValue());
673
Benjamin Kramer7857d722015-03-21 21:09:33 +0000674 // If the char is variable but the input str and length are not we can turn
675 // this memchr call into a simple bit field test. Of course this only works
676 // when the return value is only checked against null.
677 //
678 // It would be really nice to reuse switch lowering here but we can't change
679 // the CFG at this point.
680 //
681 // memchr("\r\n", C, 2) != nullptr -> (C & ((1 << '\r') | (1 << '\n'))) != 0
682 // after bounds check.
683 if (!CharC && !Str.empty() && isOnlyUsedInZeroEqualityComparison(CI)) {
Benjamin Kramerd6aa0ec2015-03-21 22:04:26 +0000684 unsigned char Max =
685 *std::max_element(reinterpret_cast<const unsigned char *>(Str.begin()),
686 reinterpret_cast<const unsigned char *>(Str.end()));
Benjamin Kramer7857d722015-03-21 21:09:33 +0000687
688 // Make sure the bit field we're about to create fits in a register on the
689 // target.
690 // FIXME: On a 64 bit architecture this prevents us from using the
691 // interesting range of alpha ascii chars. We could do better by emitting
692 // two bitfields or shifting the range by 64 if no lower chars are used.
693 if (!DL.fitsInLegalInteger(Max + 1))
694 return nullptr;
695
696 // For the bit field use a power-of-2 type with at least 8 bits to avoid
697 // creating unnecessary illegal types.
698 unsigned char Width = NextPowerOf2(std::max((unsigned char)7, Max));
699
700 // Now build the bit field.
701 APInt Bitfield(Width, 0);
702 for (char C : Str)
703 Bitfield.setBit((unsigned char)C);
704 Value *BitfieldC = B.getInt(Bitfield);
705
706 // First check that the bit field access is within bounds.
707 Value *C = B.CreateZExtOrTrunc(CI->getArgOperand(1), BitfieldC->getType());
708 Value *Bounds = B.CreateICmp(ICmpInst::ICMP_ULT, C, B.getIntN(Width, Width),
709 "memchr.bounds");
710
711 // Create code that checks if the given bit is set in the field.
712 Value *Shl = B.CreateShl(B.getIntN(Width, 1ULL), C);
713 Value *Bits = B.CreateIsNotNull(B.CreateAnd(Shl, BitfieldC), "memchr.bits");
714
715 // Finally merge both checks and cast to pointer type. The inttoptr
716 // implicitly zexts the i1 to intptr type.
717 return B.CreateIntToPtr(B.CreateAnd(Bounds, Bits, "memchr"), CI->getType());
718 }
719
720 // Check if all arguments are constants. If so, we can constant fold.
721 if (!CharC)
722 return nullptr;
723
Benjamin Kramer691363e2015-03-21 15:36:21 +0000724 // Compute the offset.
725 size_t I = Str.find(CharC->getSExtValue() & 0xFF);
726 if (I == StringRef::npos) // Didn't find the char. memchr returns null.
727 return Constant::getNullValue(CI->getType());
728
729 // memchr(s+n,c,l) -> gep(s+n+i,c)
David Blaikie3909da72015-03-30 20:42:56 +0000730 return B.CreateGEP(B.getInt8Ty(), SrcStr, B.getInt64(I), "memchr");
Benjamin Kramer691363e2015-03-21 15:36:21 +0000731}
732
Chris Bienemanad070d02014-09-17 20:55:46 +0000733Value *LibCallSimplifier::optimizeMemCmp(CallInst *CI, IRBuilder<> &B) {
Chris Bienemanad070d02014-09-17 20:55:46 +0000734 Value *LHS = CI->getArgOperand(0), *RHS = CI->getArgOperand(1);
Meador Inge40b6fac2012-10-15 03:47:37 +0000735
Chris Bienemanad070d02014-09-17 20:55:46 +0000736 if (LHS == RHS) // memcmp(s,s,x) -> 0
737 return Constant::getNullValue(CI->getType());
Meador Inge40b6fac2012-10-15 03:47:37 +0000738
Chris Bienemanad070d02014-09-17 20:55:46 +0000739 // Make sure we have a constant length.
740 ConstantInt *LenC = dyn_cast<ConstantInt>(CI->getArgOperand(2));
741 if (!LenC)
Craig Topperf40110f2014-04-25 05:29:35 +0000742 return nullptr;
Chris Bienemanad070d02014-09-17 20:55:46 +0000743
Sanjay Patel70db4242017-06-09 14:22:03 +0000744 uint64_t Len = LenC->getZExtValue();
Chris Bienemanad070d02014-09-17 20:55:46 +0000745 if (Len == 0) // memcmp(s1,s2,0) -> 0
746 return Constant::getNullValue(CI->getType());
747
748 // memcmp(S1,S2,1) -> *(unsigned char*)LHS - *(unsigned char*)RHS
749 if (Len == 1) {
Sanjay Pateld3112a52016-01-19 19:46:10 +0000750 Value *LHSV = B.CreateZExt(B.CreateLoad(castToCStr(LHS, B), "lhsc"),
Chris Bienemanad070d02014-09-17 20:55:46 +0000751 CI->getType(), "lhsv");
Sanjay Pateld3112a52016-01-19 19:46:10 +0000752 Value *RHSV = B.CreateZExt(B.CreateLoad(castToCStr(RHS, B), "rhsc"),
Chris Bienemanad070d02014-09-17 20:55:46 +0000753 CI->getType(), "rhsv");
754 return B.CreateSub(LHSV, RHSV, "chardiff");
Meador Inge40b6fac2012-10-15 03:47:37 +0000755 }
Meador Inge40b6fac2012-10-15 03:47:37 +0000756
Chad Rosierdc655322015-08-28 18:30:18 +0000757 // memcmp(S1,S2,N/8)==0 -> (*(intN_t*)S1 != *(intN_t*)S2)==0
Sanjay Patel82ec8722017-08-21 19:13:14 +0000758 // TODO: The case where both inputs are constants does not need to be limited
759 // to legal integers or equality comparison. See block below this.
Chad Rosierdc655322015-08-28 18:30:18 +0000760 if (DL.isLegalInteger(Len * 8) && isOnlyUsedInZeroEqualityComparison(CI)) {
Chad Rosierdc655322015-08-28 18:30:18 +0000761 IntegerType *IntType = IntegerType::get(CI->getContext(), Len * 8);
762 unsigned PrefAlignment = DL.getPrefTypeAlignment(IntType);
763
Sanjay Patel82ec8722017-08-21 19:13:14 +0000764 // First, see if we can fold either argument to a constant.
765 Value *LHSV = nullptr;
766 if (auto *LHSC = dyn_cast<Constant>(LHS)) {
767 LHSC = ConstantExpr::getBitCast(LHSC, IntType->getPointerTo());
768 LHSV = ConstantFoldLoadFromConstPtr(LHSC, IntType, DL);
769 }
770 Value *RHSV = nullptr;
771 if (auto *RHSC = dyn_cast<Constant>(RHS)) {
772 RHSC = ConstantExpr::getBitCast(RHSC, IntType->getPointerTo());
773 RHSV = ConstantFoldLoadFromConstPtr(RHSC, IntType, DL);
774 }
Chad Rosierdc655322015-08-28 18:30:18 +0000775
Sanjay Patel82ec8722017-08-21 19:13:14 +0000776 // Don't generate unaligned loads. If either source is constant data,
777 // alignment doesn't matter for that source because there is no load.
778 if ((LHSV || getKnownAlignment(LHS, DL, CI) >= PrefAlignment) &&
779 (RHSV || getKnownAlignment(RHS, DL, CI) >= PrefAlignment)) {
780 if (!LHSV) {
781 Type *LHSPtrTy =
782 IntType->getPointerTo(LHS->getType()->getPointerAddressSpace());
783 LHSV = B.CreateLoad(B.CreateBitCast(LHS, LHSPtrTy), "lhsv");
784 }
785 if (!RHSV) {
786 Type *RHSPtrTy =
787 IntType->getPointerTo(RHS->getType()->getPointerAddressSpace());
788 RHSV = B.CreateLoad(B.CreateBitCast(RHS, RHSPtrTy), "rhsv");
789 }
Sanjay Patel7756edf2017-08-21 13:55:49 +0000790 return B.CreateZExt(B.CreateICmpNE(LHSV, RHSV), CI->getType(), "memcmp");
Sanjay Patel707f7862017-08-21 15:16:25 +0000791 }
Chad Rosierdc655322015-08-28 18:30:18 +0000792 }
793
Sanjay Patel82ec8722017-08-21 19:13:14 +0000794 // Constant folding: memcmp(x, y, Len) -> constant (all arguments are const).
795 // TODO: This is limited to i8 arrays.
Chris Bienemanad070d02014-09-17 20:55:46 +0000796 StringRef LHSStr, RHSStr;
797 if (getConstantStringInfo(LHS, LHSStr) &&
798 getConstantStringInfo(RHS, RHSStr)) {
799 // Make sure we're not reading out-of-bounds memory.
800 if (Len > LHSStr.size() || Len > RHSStr.size())
Craig Topperf40110f2014-04-25 05:29:35 +0000801 return nullptr;
Chris Bienemanad070d02014-09-17 20:55:46 +0000802 // Fold the memcmp and normalize the result. This way we get consistent
803 // results across multiple platforms.
804 uint64_t Ret = 0;
805 int Cmp = memcmp(LHSStr.data(), RHSStr.data(), Len);
806 if (Cmp < 0)
807 Ret = -1;
808 else if (Cmp > 0)
809 Ret = 1;
810 return ConstantInt::get(CI->getType(), Ret);
Meador Inge000dbcc2012-10-18 18:12:40 +0000811 }
Meador Inge000dbcc2012-10-18 18:12:40 +0000812
Chris Bienemanad070d02014-09-17 20:55:46 +0000813 return nullptr;
814}
Meador Inge9a6a1902012-10-31 00:20:56 +0000815
Chris Bienemanad070d02014-09-17 20:55:46 +0000816Value *LibCallSimplifier::optimizeMemCpy(CallInst *CI, IRBuilder<> &B) {
Chris Bienemanad070d02014-09-17 20:55:46 +0000817 // memcpy(x, y, n) -> llvm.memcpy(x, y, n, 1)
818 B.CreateMemCpy(CI->getArgOperand(0), CI->getArgOperand(1),
Pete Cooper67cf9a72015-11-19 05:56:52 +0000819 CI->getArgOperand(2), 1);
Chris Bienemanad070d02014-09-17 20:55:46 +0000820 return CI->getArgOperand(0);
821}
Meador Inge05a625a2012-10-31 14:58:26 +0000822
Chris Bienemanad070d02014-09-17 20:55:46 +0000823Value *LibCallSimplifier::optimizeMemMove(CallInst *CI, IRBuilder<> &B) {
Chris Bienemanad070d02014-09-17 20:55:46 +0000824 // memmove(x, y, n) -> llvm.memmove(x, y, n, 1)
825 B.CreateMemMove(CI->getArgOperand(0), CI->getArgOperand(1),
Pete Cooper67cf9a72015-11-19 05:56:52 +0000826 CI->getArgOperand(2), 1);
Chris Bienemanad070d02014-09-17 20:55:46 +0000827 return CI->getArgOperand(0);
828}
Meador Ingebcd88ef72012-11-10 15:16:48 +0000829
Sanjay Patel980b2802016-01-26 16:17:24 +0000830// TODO: Does this belong in BuildLibCalls or should all of those similar
831// functions be moved here?
Reid Klecknerb5180542017-03-21 16:57:19 +0000832static Value *emitCalloc(Value *Num, Value *Size, const AttributeList &Attrs,
Sanjay Patel980b2802016-01-26 16:17:24 +0000833 IRBuilder<> &B, const TargetLibraryInfo &TLI) {
David L. Jonesd21529f2017-01-23 23:16:46 +0000834 LibFunc Func;
Sanjay Patel980b2802016-01-26 16:17:24 +0000835 if (!TLI.getLibFunc("calloc", Func) || !TLI.has(Func))
836 return nullptr;
837
838 Module *M = B.GetInsertBlock()->getModule();
839 const DataLayout &DL = M->getDataLayout();
840 IntegerType *PtrType = DL.getIntPtrType((B.GetInsertBlock()->getContext()));
841 Value *Calloc = M->getOrInsertFunction("calloc", Attrs, B.getInt8PtrTy(),
Serge Guelton59a2d7b2017-04-11 15:01:18 +0000842 PtrType, PtrType);
Sanjay Patel980b2802016-01-26 16:17:24 +0000843 CallInst *CI = B.CreateCall(Calloc, { Num, Size }, "calloc");
844
845 if (const auto *F = dyn_cast<Function>(Calloc->stripPointerCasts()))
846 CI->setCallingConv(F->getCallingConv());
847
848 return CI;
849}
850
851/// Fold memset[_chk](malloc(n), 0, n) --> calloc(1, n).
852static Value *foldMallocMemset(CallInst *Memset, IRBuilder<> &B,
853 const TargetLibraryInfo &TLI) {
854 // This has to be a memset of zeros (bzero).
855 auto *FillValue = dyn_cast<ConstantInt>(Memset->getArgOperand(1));
856 if (!FillValue || FillValue->getZExtValue() != 0)
857 return nullptr;
858
859 // TODO: We should handle the case where the malloc has more than one use.
860 // This is necessary to optimize common patterns such as when the result of
861 // the malloc is checked against null or when a memset intrinsic is used in
862 // place of a memset library call.
863 auto *Malloc = dyn_cast<CallInst>(Memset->getArgOperand(0));
864 if (!Malloc || !Malloc->hasOneUse())
865 return nullptr;
866
867 // Is the inner call really malloc()?
868 Function *InnerCallee = Malloc->getCalledFunction();
Matthias Braunc36a78c2017-04-25 19:44:25 +0000869 if (!InnerCallee)
870 return nullptr;
871
David L. Jonesd21529f2017-01-23 23:16:46 +0000872 LibFunc Func;
Ahmed Bougachad765a822016-04-27 19:04:35 +0000873 if (!TLI.getLibFunc(*InnerCallee, Func) || !TLI.has(Func) ||
David L. Jonesd21529f2017-01-23 23:16:46 +0000874 Func != LibFunc_malloc)
Sanjay Patel980b2802016-01-26 16:17:24 +0000875 return nullptr;
876
Sanjay Patel980b2802016-01-26 16:17:24 +0000877 // The memset must cover the same number of bytes that are malloc'd.
878 if (Memset->getArgOperand(2) != Malloc->getArgOperand(0))
879 return nullptr;
880
881 // Replace the malloc with a calloc. We need the data layout to know what the
882 // actual size of a 'size_t' parameter is.
883 B.SetInsertPoint(Malloc->getParent(), ++Malloc->getIterator());
884 const DataLayout &DL = Malloc->getModule()->getDataLayout();
885 IntegerType *SizeType = DL.getIntPtrType(B.GetInsertBlock()->getContext());
886 Value *Calloc = emitCalloc(ConstantInt::get(SizeType, 1),
887 Malloc->getArgOperand(0), Malloc->getAttributes(),
888 B, TLI);
889 if (!Calloc)
890 return nullptr;
891
892 Malloc->replaceAllUsesWith(Calloc);
893 Malloc->eraseFromParent();
894
895 return Calloc;
896}
897
Chris Bienemanad070d02014-09-17 20:55:46 +0000898Value *LibCallSimplifier::optimizeMemSet(CallInst *CI, IRBuilder<> &B) {
Sanjay Patel980b2802016-01-26 16:17:24 +0000899 if (auto *Calloc = foldMallocMemset(CI, B, *TLI))
900 return Calloc;
901
Chris Bienemanad070d02014-09-17 20:55:46 +0000902 // memset(p, v, n) -> llvm.memset(p, v, n, 1)
903 Value *Val = B.CreateIntCast(CI->getArgOperand(1), B.getInt8Ty(), false);
904 B.CreateMemSet(CI->getArgOperand(0), Val, CI->getArgOperand(2), 1);
905 return CI->getArgOperand(0);
906}
Meador Inged4825782012-11-11 06:49:03 +0000907
Meador Inge193e0352012-11-13 04:16:17 +0000908//===----------------------------------------------------------------------===//
909// Math Library Optimizations
910//===----------------------------------------------------------------------===//
911
Matthias Braund34e4d22014-12-03 21:46:33 +0000912/// Return a variant of Val with float type.
913/// Currently this works in two cases: If Val is an FPExtension of a float
914/// value to something bigger, simply return the operand.
915/// If Val is a ConstantFP but can be converted to a float ConstantFP without
916/// loss of precision do so.
917static Value *valueHasFloatPrecision(Value *Val) {
918 if (FPExtInst *Cast = dyn_cast<FPExtInst>(Val)) {
919 Value *Op = Cast->getOperand(0);
920 if (Op->getType()->isFloatTy())
921 return Op;
922 }
923 if (ConstantFP *Const = dyn_cast<ConstantFP>(Val)) {
924 APFloat F = Const->getValueAPF();
Matthias Braun395a82f2014-12-03 22:10:39 +0000925 bool losesInfo;
Stephan Bergmann17c7f702016-12-14 11:57:17 +0000926 (void)F.convert(APFloat::IEEEsingle(), APFloat::rmNearestTiesToEven,
Matthias Braun395a82f2014-12-03 22:10:39 +0000927 &losesInfo);
928 if (!losesInfo)
Matthias Braund34e4d22014-12-03 21:46:33 +0000929 return ConstantFP::get(Const->getContext(), F);
930 }
931 return nullptr;
932}
933
Sanjay Patel4e971da2016-01-21 18:01:57 +0000934/// Shrink double -> float for unary functions like 'floor'.
935static Value *optimizeUnaryDoubleFP(CallInst *CI, IRBuilder<> &B,
936 bool CheckRetType) {
Chris Bienemanad070d02014-09-17 20:55:46 +0000937 Function *Callee = CI->getCalledFunction();
Ahmed Bougachad765a822016-04-27 19:04:35 +0000938 // We know this libcall has a valid prototype, but we don't know which.
939 if (!CI->getType()->isDoubleTy())
Chris Bienemanad070d02014-09-17 20:55:46 +0000940 return nullptr;
Meador Inge193e0352012-11-13 04:16:17 +0000941
Chris Bienemanad070d02014-09-17 20:55:46 +0000942 if (CheckRetType) {
943 // Check if all the uses for function like 'sin' are converted to float.
944 for (User *U : CI->users()) {
945 FPTruncInst *Cast = dyn_cast<FPTruncInst>(U);
946 if (!Cast || !Cast->getType()->isFloatTy())
947 return nullptr;
Meador Inge193e0352012-11-13 04:16:17 +0000948 }
Meador Inge193e0352012-11-13 04:16:17 +0000949 }
Chris Bienemanad070d02014-09-17 20:55:46 +0000950
951 // If this is something like 'floor((double)floatval)', convert to floorf.
Matthias Braund34e4d22014-12-03 21:46:33 +0000952 Value *V = valueHasFloatPrecision(CI->getArgOperand(0));
953 if (V == nullptr)
Chris Bienemanad070d02014-09-17 20:55:46 +0000954 return nullptr;
Sanjay Patelaa231142015-12-31 21:52:31 +0000955
Andrew Ng1606fc02017-04-25 12:36:14 +0000956 // If call isn't an intrinsic, check that it isn't within a function with the
957 // same name as the float version of this call.
958 //
959 // e.g. inline float expf(float val) { return (float) exp((double) val); }
960 //
961 // A similar such definition exists in the MinGW-w64 math.h header file which
962 // when compiled with -O2 -ffast-math causes the generation of infinite loops
963 // where expf is called.
964 if (!Callee->isIntrinsic()) {
965 const Function *F = CI->getFunction();
966 StringRef FName = F->getName();
967 StringRef CalleeName = Callee->getName();
968 if ((FName.size() == (CalleeName.size() + 1)) &&
969 (FName.back() == 'f') &&
970 FName.startswith(CalleeName))
971 return nullptr;
972 }
973
Sanjay Patelaa231142015-12-31 21:52:31 +0000974 // Propagate fast-math flags from the existing call to the new call.
975 IRBuilder<>::FastMathFlagGuard Guard(B);
Sanjay Patela2528152016-01-12 18:03:37 +0000976 B.setFastMathFlags(CI->getFastMathFlags());
Chris Bienemanad070d02014-09-17 20:55:46 +0000977
978 // floor((double)floatval) -> (double)floorf(floatval)
Sanjay Patel848309d2014-10-23 21:52:45 +0000979 if (Callee->isIntrinsic()) {
Sanjay Patelaf674fb2015-12-14 17:24:23 +0000980 Module *M = CI->getModule();
Pete Cooper9e1d3352015-05-20 17:16:39 +0000981 Intrinsic::ID IID = Callee->getIntrinsicID();
Sanjay Patel848309d2014-10-23 21:52:45 +0000982 Function *F = Intrinsic::getDeclaration(M, IID, B.getFloatTy());
983 V = B.CreateCall(F, V);
984 } else {
985 // The call is a library call rather than an intrinsic.
Sanjay Pateld3112a52016-01-19 19:46:10 +0000986 V = emitUnaryFloatFnCall(V, Callee->getName(), B, Callee->getAttributes());
Sanjay Patel848309d2014-10-23 21:52:45 +0000987 }
988
Chris Bienemanad070d02014-09-17 20:55:46 +0000989 return B.CreateFPExt(V, B.getDoubleTy());
990}
Meador Inge193e0352012-11-13 04:16:17 +0000991
Matt Arsenault954a6242017-01-23 23:55:08 +0000992// Replace a libcall \p CI with a call to intrinsic \p IID
993static Value *replaceUnaryCall(CallInst *CI, IRBuilder<> &B, Intrinsic::ID IID) {
994 // Propagate fast-math flags from the existing call to the new call.
995 IRBuilder<>::FastMathFlagGuard Guard(B);
996 B.setFastMathFlags(CI->getFastMathFlags());
997
998 Module *M = CI->getModule();
999 Value *V = CI->getArgOperand(0);
1000 Function *F = Intrinsic::getDeclaration(M, IID, CI->getType());
1001 CallInst *NewCall = B.CreateCall(F, V);
1002 NewCall->takeName(CI);
1003 return NewCall;
1004}
1005
Sanjay Patel4e971da2016-01-21 18:01:57 +00001006/// Shrink double -> float for binary functions like 'fmin/fmax'.
1007static Value *optimizeBinaryDoubleFP(CallInst *CI, IRBuilder<> &B) {
Chris Bienemanad070d02014-09-17 20:55:46 +00001008 Function *Callee = CI->getCalledFunction();
Ahmed Bougachad765a822016-04-27 19:04:35 +00001009 // We know this libcall has a valid prototype, but we don't know which.
1010 if (!CI->getType()->isDoubleTy())
Craig Topperf40110f2014-04-25 05:29:35 +00001011 return nullptr;
Meador Inge193e0352012-11-13 04:16:17 +00001012
Chris Bienemanad070d02014-09-17 20:55:46 +00001013 // If this is something like 'fmin((double)floatval1, (double)floatval2)',
Matthias Braund34e4d22014-12-03 21:46:33 +00001014 // or fmin(1.0, (double)floatval), then we convert it to fminf.
1015 Value *V1 = valueHasFloatPrecision(CI->getArgOperand(0));
1016 if (V1 == nullptr)
1017 return nullptr;
1018 Value *V2 = valueHasFloatPrecision(CI->getArgOperand(1));
1019 if (V2 == nullptr)
Craig Topperf40110f2014-04-25 05:29:35 +00001020 return nullptr;
Chris Bienemanad070d02014-09-17 20:55:46 +00001021
Sanjay Patelbee05ca2015-12-31 23:40:59 +00001022 // Propagate fast-math flags from the existing call to the new call.
1023 IRBuilder<>::FastMathFlagGuard Guard(B);
Sanjay Patela2528152016-01-12 18:03:37 +00001024 B.setFastMathFlags(CI->getFastMathFlags());
Sanjay Patelbee05ca2015-12-31 23:40:59 +00001025
Chris Bienemanad070d02014-09-17 20:55:46 +00001026 // fmin((double)floatval1, (double)floatval2)
Matthias Braund34e4d22014-12-03 21:46:33 +00001027 // -> (double)fminf(floatval1, floatval2)
Sanjay Patel848309d2014-10-23 21:52:45 +00001028 // TODO: Handle intrinsics in the same way as in optimizeUnaryDoubleFP().
Sanjay Pateld3112a52016-01-19 19:46:10 +00001029 Value *V = emitBinaryFloatFnCall(V1, V2, Callee->getName(), B,
Matthias Braund34e4d22014-12-03 21:46:33 +00001030 Callee->getAttributes());
Chris Bienemanad070d02014-09-17 20:55:46 +00001031 return B.CreateFPExt(V, B.getDoubleTy());
1032}
1033
1034Value *LibCallSimplifier::optimizeCos(CallInst *CI, IRBuilder<> &B) {
1035 Function *Callee = CI->getCalledFunction();
1036 Value *Ret = nullptr;
Davide Italianoa3458772015-11-05 19:18:23 +00001037 StringRef Name = Callee->getName();
1038 if (UnsafeFPShrink && Name == "cos" && hasFloatVersion(Name))
Chris Bienemanad070d02014-09-17 20:55:46 +00001039 Ret = optimizeUnaryDoubleFP(CI, B, true);
Bob Wilsond8d92d92013-11-03 06:48:38 +00001040
Chris Bienemanad070d02014-09-17 20:55:46 +00001041 // cos(-x) -> cos(x)
1042 Value *Op1 = CI->getArgOperand(0);
1043 if (BinaryOperator::isFNeg(Op1)) {
1044 BinaryOperator *BinExpr = cast<BinaryOperator>(Op1);
1045 return B.CreateCall(Callee, BinExpr->getOperand(1), "cos");
1046 }
1047 return Ret;
1048}
Bob Wilsond8d92d92013-11-03 06:48:38 +00001049
Weiming Zhao82130722015-12-04 22:00:47 +00001050static Value *getPow(Value *InnerChain[33], unsigned Exp, IRBuilder<> &B) {
1051 // Multiplications calculated using Addition Chains.
1052 // Refer: http://wwwhomes.uni-bielefeld.de/achim/addition_chain.html
1053
1054 assert(Exp != 0 && "Incorrect exponent 0 not handled");
1055
1056 if (InnerChain[Exp])
1057 return InnerChain[Exp];
1058
1059 static const unsigned AddChain[33][2] = {
1060 {0, 0}, // Unused.
1061 {0, 0}, // Unused (base case = pow1).
1062 {1, 1}, // Unused (pre-computed).
1063 {1, 2}, {2, 2}, {2, 3}, {3, 3}, {2, 5}, {4, 4},
1064 {1, 8}, {5, 5}, {1, 10}, {6, 6}, {4, 9}, {7, 7},
1065 {3, 12}, {8, 8}, {8, 9}, {2, 16}, {1, 18}, {10, 10},
1066 {6, 15}, {11, 11}, {3, 20}, {12, 12}, {8, 17}, {13, 13},
1067 {3, 24}, {14, 14}, {4, 25}, {15, 15}, {3, 28}, {16, 16},
1068 };
1069
1070 InnerChain[Exp] = B.CreateFMul(getPow(InnerChain, AddChain[Exp][0], B),
1071 getPow(InnerChain, AddChain[Exp][1], B));
1072 return InnerChain[Exp];
1073}
1074
Chris Bienemanad070d02014-09-17 20:55:46 +00001075Value *LibCallSimplifier::optimizePow(CallInst *CI, IRBuilder<> &B) {
1076 Function *Callee = CI->getCalledFunction();
Chris Bienemanad070d02014-09-17 20:55:46 +00001077 Value *Ret = nullptr;
Davide Italianoa3458772015-11-05 19:18:23 +00001078 StringRef Name = Callee->getName();
1079 if (UnsafeFPShrink && Name == "pow" && hasFloatVersion(Name))
Chris Bienemanad070d02014-09-17 20:55:46 +00001080 Ret = optimizeUnaryDoubleFP(CI, B, true);
Bob Wilsond8d92d92013-11-03 06:48:38 +00001081
Chris Bienemanad070d02014-09-17 20:55:46 +00001082 Value *Op1 = CI->getArgOperand(0), *Op2 = CI->getArgOperand(1);
Davide Italiano27da1312016-08-07 20:27:03 +00001083
1084 // pow(1.0, x) -> 1.0
1085 if (match(Op1, m_SpecificFP(1.0)))
1086 return Op1;
1087 // pow(2.0, x) -> llvm.exp2(x)
1088 if (match(Op1, m_SpecificFP(2.0))) {
1089 Value *Exp2 = Intrinsic::getDeclaration(CI->getModule(), Intrinsic::exp2,
1090 CI->getType());
1091 return B.CreateCall(Exp2, Op2, "exp2");
1092 }
1093
1094 // There's no llvm.exp10 intrinsic yet, but, maybe, some day there will
1095 // be one.
Chris Bienemanad070d02014-09-17 20:55:46 +00001096 if (ConstantFP *Op1C = dyn_cast<ConstantFP>(Op1)) {
Chris Bienemanad070d02014-09-17 20:55:46 +00001097 // pow(10.0, x) -> exp10(x)
1098 if (Op1C->isExactlyValue(10.0) &&
David L. Jonesd21529f2017-01-23 23:16:46 +00001099 hasUnaryFloatFn(TLI, Op1->getType(), LibFunc_exp10, LibFunc_exp10f,
1100 LibFunc_exp10l))
1101 return emitUnaryFloatFnCall(Op2, TLI->getName(LibFunc_exp10), B,
Chris Bienemanad070d02014-09-17 20:55:46 +00001102 Callee->getAttributes());
Bob Wilsond8d92d92013-11-03 06:48:38 +00001103 }
1104
Sanjay Patel6002e782016-01-12 17:30:37 +00001105 // pow(exp(x), y) -> exp(x * y)
Davide Italianoc8a79132015-11-03 20:32:23 +00001106 // pow(exp2(x), y) -> exp2(x * y)
Sanjay Patel6002e782016-01-12 17:30:37 +00001107 // We enable these only with fast-math. Besides rounding differences, the
1108 // transformation changes overflow and underflow behavior quite dramatically.
Davide Italianoc8a79132015-11-03 20:32:23 +00001109 // Example: x = 1000, y = 0.001.
1110 // pow(exp(x), y) = pow(inf, 0.001) = inf, whereas exp(x*y) = exp(1).
Sanjay Patel6002e782016-01-12 17:30:37 +00001111 auto *OpC = dyn_cast<CallInst>(Op1);
1112 if (OpC && OpC->hasUnsafeAlgebra() && CI->hasUnsafeAlgebra()) {
David L. Jonesd21529f2017-01-23 23:16:46 +00001113 LibFunc Func;
Sanjay Patel6002e782016-01-12 17:30:37 +00001114 Function *OpCCallee = OpC->getCalledFunction();
1115 if (OpCCallee && TLI->getLibFunc(OpCCallee->getName(), Func) &&
David L. Jonesd21529f2017-01-23 23:16:46 +00001116 TLI->has(Func) && (Func == LibFunc_exp || Func == LibFunc_exp2)) {
Davide Italianoc8a79132015-11-03 20:32:23 +00001117 IRBuilder<>::FastMathFlagGuard Guard(B);
Sanjay Patela2528152016-01-12 18:03:37 +00001118 B.setFastMathFlags(CI->getFastMathFlags());
Sanjay Patel6002e782016-01-12 17:30:37 +00001119 Value *FMul = B.CreateFMul(OpC->getArgOperand(0), Op2, "mul");
Sanjay Pateld3112a52016-01-19 19:46:10 +00001120 return emitUnaryFloatFnCall(FMul, OpCCallee->getName(), B,
Sanjay Patel6002e782016-01-12 17:30:37 +00001121 OpCCallee->getAttributes());
Davide Italianoc8a79132015-11-03 20:32:23 +00001122 }
1123 }
1124
Chris Bienemanad070d02014-09-17 20:55:46 +00001125 ConstantFP *Op2C = dyn_cast<ConstantFP>(Op2);
1126 if (!Op2C)
1127 return Ret;
1128
1129 if (Op2C->getValueAPF().isZero()) // pow(x, 0.0) -> 1.0
1130 return ConstantFP::get(CI->getType(), 1.0);
1131
Davide Italiano472684e2017-01-09 21:55:23 +00001132 if (Op2C->isExactlyValue(-0.5) &&
David L. Jonesd21529f2017-01-23 23:16:46 +00001133 hasUnaryFloatFn(TLI, Op2->getType(), LibFunc_sqrt, LibFunc_sqrtf,
1134 LibFunc_sqrtl)) {
Davide Italiano472684e2017-01-09 21:55:23 +00001135 // If -ffast-math:
1136 // pow(x, -0.5) -> 1.0 / sqrt(x)
1137 if (CI->hasUnsafeAlgebra()) {
1138 IRBuilder<>::FastMathFlagGuard Guard(B);
1139 B.setFastMathFlags(CI->getFastMathFlags());
1140
Justin Lebarcb9b41d2017-01-27 00:58:03 +00001141 // TODO: If the pow call is an intrinsic, we should lower to the sqrt
1142 // intrinsic, so we match errno semantics. We also should check that the
1143 // target can in fact lower the sqrt intrinsic -- we currently have no way
1144 // to ask this question other than asking whether the target has a sqrt
1145 // libcall, which is a sufficient but not necessary condition.
David L. Jonesd21529f2017-01-23 23:16:46 +00001146 Value *Sqrt = emitUnaryFloatFnCall(Op1, TLI->getName(LibFunc_sqrt), B,
Davide Italiano472684e2017-01-09 21:55:23 +00001147 Callee->getAttributes());
1148
1149 return B.CreateFDiv(ConstantFP::get(CI->getType(), 1.0), Sqrt, "sqrtrecip");
1150 }
1151 }
1152
Chris Bienemanad070d02014-09-17 20:55:46 +00001153 if (Op2C->isExactlyValue(0.5) &&
David L. Jonesd21529f2017-01-23 23:16:46 +00001154 hasUnaryFloatFn(TLI, Op2->getType(), LibFunc_sqrt, LibFunc_sqrtf,
1155 LibFunc_sqrtl)) {
Davide Italianoc5cedd12015-11-18 23:21:32 +00001156
1157 // In -ffast-math, pow(x, 0.5) -> sqrt(x).
Sanjay Patel53ba88d2016-01-12 19:06:35 +00001158 if (CI->hasUnsafeAlgebra()) {
1159 IRBuilder<>::FastMathFlagGuard Guard(B);
1160 B.setFastMathFlags(CI->getFastMathFlags());
Davide Italiano873219c2016-08-10 06:33:32 +00001161
Justin Lebarcb9b41d2017-01-27 00:58:03 +00001162 // TODO: As above, we should lower to the sqrt intrinsic if the pow is an
1163 // intrinsic, to match errno semantics.
David L. Jonesd21529f2017-01-23 23:16:46 +00001164 return emitUnaryFloatFnCall(Op1, TLI->getName(LibFunc_sqrt), B,
Davide Italiano873219c2016-08-10 06:33:32 +00001165 Callee->getAttributes());
Sanjay Patel53ba88d2016-01-12 19:06:35 +00001166 }
Davide Italianoc5cedd12015-11-18 23:21:32 +00001167
Chris Bienemanad070d02014-09-17 20:55:46 +00001168 // Expand pow(x, 0.5) to (x == -infinity ? +infinity : fabs(sqrt(x))).
1169 // This is faster than calling pow, and still handles negative zero
1170 // and negative infinity correctly.
Chris Bienemanad070d02014-09-17 20:55:46 +00001171 // TODO: In finite-only mode, this could be just fabs(sqrt(x)).
1172 Value *Inf = ConstantFP::getInfinity(CI->getType());
1173 Value *NegInf = ConstantFP::getInfinity(CI->getType(), true);
Justin Lebarcb9b41d2017-01-27 00:58:03 +00001174
1175 // TODO: As above, we should lower to the sqrt intrinsic if the pow is an
1176 // intrinsic, to match errno semantics.
Sanjay Pateld3112a52016-01-19 19:46:10 +00001177 Value *Sqrt = emitUnaryFloatFnCall(Op1, "sqrt", B, Callee->getAttributes());
Matt Arsenaultb948b4d2017-01-17 00:30:31 +00001178
1179 Module *M = Callee->getParent();
1180 Function *FabsF = Intrinsic::getDeclaration(M, Intrinsic::fabs,
1181 CI->getType());
1182 Value *FAbs = B.CreateCall(FabsF, Sqrt);
1183
Chris Bienemanad070d02014-09-17 20:55:46 +00001184 Value *FCmp = B.CreateFCmpOEQ(Op1, NegInf);
1185 Value *Sel = B.CreateSelect(FCmp, Inf, FAbs);
1186 return Sel;
Bob Wilsond8d92d92013-11-03 06:48:38 +00001187 }
1188
Chris Bienemanad070d02014-09-17 20:55:46 +00001189 if (Op2C->isExactlyValue(1.0)) // pow(x, 1.0) -> x
1190 return Op1;
1191 if (Op2C->isExactlyValue(2.0)) // pow(x, 2.0) -> x*x
1192 return B.CreateFMul(Op1, Op1, "pow2");
1193 if (Op2C->isExactlyValue(-1.0)) // pow(x, -1.0) -> 1.0/x
1194 return B.CreateFDiv(ConstantFP::get(CI->getType(), 1.0), Op1, "powrecip");
Weiming Zhao82130722015-12-04 22:00:47 +00001195
1196 // In -ffast-math, generate repeated fmul instead of generating pow(x, n).
Sanjay Patel81a63cd2016-01-19 18:15:12 +00001197 if (CI->hasUnsafeAlgebra()) {
Weiming Zhao82130722015-12-04 22:00:47 +00001198 APFloat V = abs(Op2C->getValueAPF());
1199 // We limit to a max of 7 fmul(s). Thus max exponent is 32.
1200 // This transformation applies to integer exponents only.
1201 if (V.compare(APFloat(V.getSemantics(), 32.0)) == APFloat::cmpGreaterThan ||
1202 !V.isInteger())
1203 return nullptr;
1204
Davide Italianof8711f02017-01-10 18:02:05 +00001205 // Propagate fast math flags.
1206 IRBuilder<>::FastMathFlagGuard Guard(B);
1207 B.setFastMathFlags(CI->getFastMathFlags());
1208
Weiming Zhao82130722015-12-04 22:00:47 +00001209 // We will memoize intermediate products of the Addition Chain.
1210 Value *InnerChain[33] = {nullptr};
1211 InnerChain[1] = Op1;
1212 InnerChain[2] = B.CreateFMul(Op1, Op1);
1213
1214 // We cannot readily convert a non-double type (like float) to a double.
1215 // So we first convert V to something which could be converted to double.
1216 bool ignored;
Stephan Bergmann17c7f702016-12-14 11:57:17 +00001217 V.convert(APFloat::IEEEdouble(), APFloat::rmTowardZero, &ignored);
Sanjay Patel81a63cd2016-01-19 18:15:12 +00001218
Weiming Zhao82130722015-12-04 22:00:47 +00001219 Value *FMul = getPow(InnerChain, V.convertToDouble(), B);
1220 // For negative exponents simply compute the reciprocal.
1221 if (Op2C->isNegative())
1222 FMul = B.CreateFDiv(ConstantFP::get(CI->getType(), 1.0), FMul);
1223 return FMul;
1224 }
1225
Chris Bienemanad070d02014-09-17 20:55:46 +00001226 return nullptr;
1227}
Bob Wilsond8d92d92013-11-03 06:48:38 +00001228
Chris Bienemanad070d02014-09-17 20:55:46 +00001229Value *LibCallSimplifier::optimizeExp2(CallInst *CI, IRBuilder<> &B) {
1230 Function *Callee = CI->getCalledFunction();
Chris Bienemanad070d02014-09-17 20:55:46 +00001231 Value *Ret = nullptr;
Davide Italianoa3458772015-11-05 19:18:23 +00001232 StringRef Name = Callee->getName();
1233 if (UnsafeFPShrink && Name == "exp2" && hasFloatVersion(Name))
Chris Bienemanad070d02014-09-17 20:55:46 +00001234 Ret = optimizeUnaryDoubleFP(CI, B, true);
Bob Wilsond8d92d92013-11-03 06:48:38 +00001235
Chris Bienemanad070d02014-09-17 20:55:46 +00001236 Value *Op = CI->getArgOperand(0);
1237 // Turn exp2(sitofp(x)) -> ldexp(1.0, sext(x)) if sizeof(x) <= 32
1238 // Turn exp2(uitofp(x)) -> ldexp(1.0, zext(x)) if sizeof(x) < 32
David L. Jonesd21529f2017-01-23 23:16:46 +00001239 LibFunc LdExp = LibFunc_ldexpl;
Chris Bienemanad070d02014-09-17 20:55:46 +00001240 if (Op->getType()->isFloatTy())
David L. Jonesd21529f2017-01-23 23:16:46 +00001241 LdExp = LibFunc_ldexpf;
Chris Bienemanad070d02014-09-17 20:55:46 +00001242 else if (Op->getType()->isDoubleTy())
David L. Jonesd21529f2017-01-23 23:16:46 +00001243 LdExp = LibFunc_ldexp;
Chris Bienemanad070d02014-09-17 20:55:46 +00001244
1245 if (TLI->has(LdExp)) {
1246 Value *LdExpArg = nullptr;
1247 if (SIToFPInst *OpC = dyn_cast<SIToFPInst>(Op)) {
1248 if (OpC->getOperand(0)->getType()->getPrimitiveSizeInBits() <= 32)
1249 LdExpArg = B.CreateSExt(OpC->getOperand(0), B.getInt32Ty());
1250 } else if (UIToFPInst *OpC = dyn_cast<UIToFPInst>(Op)) {
1251 if (OpC->getOperand(0)->getType()->getPrimitiveSizeInBits() < 32)
1252 LdExpArg = B.CreateZExt(OpC->getOperand(0), B.getInt32Ty());
1253 }
1254
1255 if (LdExpArg) {
1256 Constant *One = ConstantFP::get(CI->getContext(), APFloat(1.0f));
1257 if (!Op->getType()->isFloatTy())
1258 One = ConstantExpr::getFPExtend(One, Op->getType());
1259
Sanjay Patel0e603fc2016-01-21 22:31:18 +00001260 Module *M = CI->getModule();
Mehdi Aminidb11fdf2017-04-06 20:23:57 +00001261 Value *NewCallee =
1262 M->getOrInsertFunction(TLI->getName(LdExp), Op->getType(),
Serge Guelton59a2d7b2017-04-11 15:01:18 +00001263 Op->getType(), B.getInt32Ty());
Sanjay Patel042aed902016-01-21 22:41:16 +00001264 CallInst *CI = B.CreateCall(NewCallee, {One, LdExpArg});
Chris Bienemanad070d02014-09-17 20:55:46 +00001265 if (const Function *F = dyn_cast<Function>(Callee->stripPointerCasts()))
1266 CI->setCallingConv(F->getCallingConv());
1267
1268 return CI;
1269 }
1270 }
1271 return Ret;
1272}
1273
Sanjay Patel57fd1dc2015-08-16 20:18:19 +00001274Value *LibCallSimplifier::optimizeFMinFMax(CallInst *CI, IRBuilder<> &B) {
Sanjay Patel9beec212016-01-21 22:58:01 +00001275 Function *Callee = CI->getCalledFunction();
Sanjay Patel57fd1dc2015-08-16 20:18:19 +00001276 // If we can shrink the call to a float function rather than a double
1277 // function, do that first.
Davide Italianoa3458772015-11-05 19:18:23 +00001278 StringRef Name = Callee->getName();
Sanjay Patelc7ddb7f2016-01-06 00:32:15 +00001279 if ((Name == "fmin" || Name == "fmax") && hasFloatVersion(Name))
1280 if (Value *Ret = optimizeBinaryDoubleFP(CI, B))
Sanjay Patel57fd1dc2015-08-16 20:18:19 +00001281 return Ret;
Sanjay Patel57fd1dc2015-08-16 20:18:19 +00001282
Benjamin Kramerbb70d752015-08-16 21:16:37 +00001283 IRBuilder<>::FastMathFlagGuard Guard(B);
Sanjay Patel57fd1dc2015-08-16 20:18:19 +00001284 FastMathFlags FMF;
Sanjay Patel29095ea2016-01-05 20:46:19 +00001285 if (CI->hasUnsafeAlgebra()) {
Sanjay Patel57fd1dc2015-08-16 20:18:19 +00001286 // Unsafe algebra sets all fast-math-flags to true.
1287 FMF.setUnsafeAlgebra();
1288 } else {
1289 // At a minimum, no-nans-fp-math must be true.
Sanjay Patel29095ea2016-01-05 20:46:19 +00001290 if (!CI->hasNoNaNs())
Sanjay Patel57fd1dc2015-08-16 20:18:19 +00001291 return nullptr;
1292 // No-signed-zeros is implied by the definitions of fmax/fmin themselves:
1293 // "Ideally, fmax would be sensitive to the sign of zero, for example
NAKAMURA Takumi0d725392015-09-07 00:26:54 +00001294 // fmax(-0. 0, +0. 0) would return +0; however, implementation in software
Sanjay Patel57fd1dc2015-08-16 20:18:19 +00001295 // might be impractical."
1296 FMF.setNoSignedZeros();
1297 FMF.setNoNaNs();
1298 }
Sanjay Patela2528152016-01-12 18:03:37 +00001299 B.setFastMathFlags(FMF);
Sanjay Patel57fd1dc2015-08-16 20:18:19 +00001300
1301 // We have a relaxed floating-point environment. We can ignore NaN-handling
1302 // and transform to a compare and select. We do not have to consider errno or
1303 // exceptions, because fmin/fmax do not have those.
1304 Value *Op0 = CI->getArgOperand(0);
1305 Value *Op1 = CI->getArgOperand(1);
1306 Value *Cmp = Callee->getName().startswith("fmin") ?
1307 B.CreateFCmpOLT(Op0, Op1) : B.CreateFCmpOGT(Op0, Op1);
1308 return B.CreateSelect(Cmp, Op0, Op1);
1309}
1310
Davide Italianob8b71332015-11-29 20:58:04 +00001311Value *LibCallSimplifier::optimizeLog(CallInst *CI, IRBuilder<> &B) {
1312 Function *Callee = CI->getCalledFunction();
1313 Value *Ret = nullptr;
1314 StringRef Name = Callee->getName();
1315 if (UnsafeFPShrink && hasFloatVersion(Name))
1316 Ret = optimizeUnaryDoubleFP(CI, B, true);
Davide Italianob8b71332015-11-29 20:58:04 +00001317
Sanjay Patele896ede2016-01-11 23:31:48 +00001318 if (!CI->hasUnsafeAlgebra())
Davide Italianob8b71332015-11-29 20:58:04 +00001319 return Ret;
1320 Value *Op1 = CI->getArgOperand(0);
1321 auto *OpC = dyn_cast<CallInst>(Op1);
Sanjay Patele896ede2016-01-11 23:31:48 +00001322
1323 // The earlier call must also be unsafe in order to do these transforms.
1324 if (!OpC || !OpC->hasUnsafeAlgebra())
Davide Italianob8b71332015-11-29 20:58:04 +00001325 return Ret;
1326
1327 // log(pow(x,y)) -> y*log(x)
1328 // This is only applicable to log, log2, log10.
1329 if (Name != "log" && Name != "log2" && Name != "log10")
1330 return Ret;
1331
1332 IRBuilder<>::FastMathFlagGuard Guard(B);
1333 FastMathFlags FMF;
1334 FMF.setUnsafeAlgebra();
Sanjay Patela2528152016-01-12 18:03:37 +00001335 B.setFastMathFlags(FMF);
Davide Italianob8b71332015-11-29 20:58:04 +00001336
David L. Jonesd21529f2017-01-23 23:16:46 +00001337 LibFunc Func;
Davide Italianob8b71332015-11-29 20:58:04 +00001338 Function *F = OpC->getCalledFunction();
Davide Italiano0b14f292015-11-29 21:58:56 +00001339 if (F && ((TLI->getLibFunc(F->getName(), Func) && TLI->has(Func) &&
David L. Jonesd21529f2017-01-23 23:16:46 +00001340 Func == LibFunc_pow) || F->getIntrinsicID() == Intrinsic::pow))
Davide Italianob8b71332015-11-29 20:58:04 +00001341 return B.CreateFMul(OpC->getArgOperand(1),
Sanjay Pateld3112a52016-01-19 19:46:10 +00001342 emitUnaryFloatFnCall(OpC->getOperand(0), Callee->getName(), B,
Davide Italianob8b71332015-11-29 20:58:04 +00001343 Callee->getAttributes()), "mul");
Davide Italiano1aeed6a2015-11-30 19:36:35 +00001344
1345 // log(exp2(y)) -> y*log(2)
1346 if (F && Name == "log" && TLI->getLibFunc(F->getName(), Func) &&
David L. Jonesd21529f2017-01-23 23:16:46 +00001347 TLI->has(Func) && Func == LibFunc_exp2)
Davide Italiano1aeed6a2015-11-30 19:36:35 +00001348 return B.CreateFMul(
1349 OpC->getArgOperand(0),
Sanjay Pateld3112a52016-01-19 19:46:10 +00001350 emitUnaryFloatFnCall(ConstantFP::get(CI->getType(), 2.0),
Davide Italiano1aeed6a2015-11-30 19:36:35 +00001351 Callee->getName(), B, Callee->getAttributes()),
1352 "logmul");
Davide Italianob8b71332015-11-29 20:58:04 +00001353 return Ret;
1354}
1355
Sanjay Patelc699a612014-10-16 18:48:17 +00001356Value *LibCallSimplifier::optimizeSqrt(CallInst *CI, IRBuilder<> &B) {
1357 Function *Callee = CI->getCalledFunction();
Sanjay Patelc699a612014-10-16 18:48:17 +00001358 Value *Ret = nullptr;
Justin Lebarcb9b41d2017-01-27 00:58:03 +00001359 // TODO: Once we have a way (other than checking for the existince of the
1360 // libcall) to tell whether our target can lower @llvm.sqrt, relax the
1361 // condition below.
David L. Jonesd21529f2017-01-23 23:16:46 +00001362 if (TLI->has(LibFunc_sqrtf) && (Callee->getName() == "sqrt" ||
Justin Lebarcb9b41d2017-01-27 00:58:03 +00001363 Callee->getIntrinsicID() == Intrinsic::sqrt))
Sanjay Patelc699a612014-10-16 18:48:17 +00001364 Ret = optimizeUnaryDoubleFP(CI, B, true);
Sanjay Patel683f2972016-01-11 22:34:19 +00001365
1366 if (!CI->hasUnsafeAlgebra())
Davide Italianoa904e522015-10-29 02:58:44 +00001367 return Ret;
Sanjay Patelc699a612014-10-16 18:48:17 +00001368
Sanjay Patelc2d64612016-01-06 20:52:21 +00001369 Instruction *I = dyn_cast<Instruction>(CI->getArgOperand(0));
1370 if (!I || I->getOpcode() != Instruction::FMul || !I->hasUnsafeAlgebra())
1371 return Ret;
1372
1373 // We're looking for a repeated factor in a multiplication tree,
1374 // so we can do this fold: sqrt(x * x) -> fabs(x);
Sanjay Patel683f2972016-01-11 22:34:19 +00001375 // or this fold: sqrt((x * x) * y) -> fabs(x) * sqrt(y).
Sanjay Patelc2d64612016-01-06 20:52:21 +00001376 Value *Op0 = I->getOperand(0);
1377 Value *Op1 = I->getOperand(1);
1378 Value *RepeatOp = nullptr;
1379 Value *OtherOp = nullptr;
1380 if (Op0 == Op1) {
1381 // Simple match: the operands of the multiply are identical.
1382 RepeatOp = Op0;
1383 } else {
1384 // Look for a more complicated pattern: one of the operands is itself
1385 // a multiply, so search for a common factor in that multiply.
1386 // Note: We don't bother looking any deeper than this first level or for
1387 // variations of this pattern because instcombine's visitFMUL and/or the
1388 // reassociation pass should give us this form.
1389 Value *OtherMul0, *OtherMul1;
1390 if (match(Op0, m_FMul(m_Value(OtherMul0), m_Value(OtherMul1)))) {
1391 // Pattern: sqrt((x * y) * z)
Sanjay Patel6c1ddbb2016-01-11 22:50:36 +00001392 if (OtherMul0 == OtherMul1 &&
1393 cast<Instruction>(Op0)->hasUnsafeAlgebra()) {
Sanjay Patelc2d64612016-01-06 20:52:21 +00001394 // Matched: sqrt((x * x) * z)
1395 RepeatOp = OtherMul0;
1396 OtherOp = Op1;
Sanjay Patelc699a612014-10-16 18:48:17 +00001397 }
1398 }
1399 }
Sanjay Patelc2d64612016-01-06 20:52:21 +00001400 if (!RepeatOp)
1401 return Ret;
1402
1403 // Fast math flags for any created instructions should match the sqrt
1404 // and multiply.
Sanjay Patelc2d64612016-01-06 20:52:21 +00001405 IRBuilder<>::FastMathFlagGuard Guard(B);
Sanjay Patela2528152016-01-12 18:03:37 +00001406 B.setFastMathFlags(I->getFastMathFlags());
Sanjay Patel9f67dad2016-01-11 22:35:39 +00001407
Sanjay Patelc2d64612016-01-06 20:52:21 +00001408 // If we found a repeated factor, hoist it out of the square root and
1409 // replace it with the fabs of that factor.
1410 Module *M = Callee->getParent();
1411 Type *ArgType = I->getType();
1412 Value *Fabs = Intrinsic::getDeclaration(M, Intrinsic::fabs, ArgType);
1413 Value *FabsCall = B.CreateCall(Fabs, RepeatOp, "fabs");
1414 if (OtherOp) {
1415 // If we found a non-repeated factor, we still need to get its square
1416 // root. We then multiply that by the value that was simplified out
1417 // of the square root calculation.
1418 Value *Sqrt = Intrinsic::getDeclaration(M, Intrinsic::sqrt, ArgType);
1419 Value *SqrtCall = B.CreateCall(Sqrt, OtherOp, "sqrt");
1420 return B.CreateFMul(FabsCall, SqrtCall);
1421 }
1422 return FabsCall;
Sanjay Patelc699a612014-10-16 18:48:17 +00001423}
1424
Sanjay Patelcddcd722016-01-06 19:23:35 +00001425// TODO: Generalize to handle any trig function and its inverse.
Davide Italiano51507d22015-11-04 23:36:56 +00001426Value *LibCallSimplifier::optimizeTan(CallInst *CI, IRBuilder<> &B) {
1427 Function *Callee = CI->getCalledFunction();
1428 Value *Ret = nullptr;
Davide Italianoa3458772015-11-05 19:18:23 +00001429 StringRef Name = Callee->getName();
1430 if (UnsafeFPShrink && Name == "tan" && hasFloatVersion(Name))
Davide Italiano51507d22015-11-04 23:36:56 +00001431 Ret = optimizeUnaryDoubleFP(CI, B, true);
Davide Italiano51507d22015-11-04 23:36:56 +00001432
Davide Italiano51507d22015-11-04 23:36:56 +00001433 Value *Op1 = CI->getArgOperand(0);
1434 auto *OpC = dyn_cast<CallInst>(Op1);
1435 if (!OpC)
1436 return Ret;
1437
Sanjay Patelcddcd722016-01-06 19:23:35 +00001438 // Both calls must allow unsafe optimizations in order to remove them.
1439 if (!CI->hasUnsafeAlgebra() || !OpC->hasUnsafeAlgebra())
1440 return Ret;
1441
Davide Italiano51507d22015-11-04 23:36:56 +00001442 // tan(atan(x)) -> x
1443 // tanf(atanf(x)) -> x
1444 // tanl(atanl(x)) -> x
David L. Jonesd21529f2017-01-23 23:16:46 +00001445 LibFunc Func;
Davide Italiano51507d22015-11-04 23:36:56 +00001446 Function *F = OpC->getCalledFunction();
Benjamin Kramerfb419e72015-11-26 09:51:17 +00001447 if (F && TLI->getLibFunc(F->getName(), Func) && TLI->has(Func) &&
David L. Jonesd21529f2017-01-23 23:16:46 +00001448 ((Func == LibFunc_atan && Callee->getName() == "tan") ||
1449 (Func == LibFunc_atanf && Callee->getName() == "tanf") ||
1450 (Func == LibFunc_atanl && Callee->getName() == "tanl")))
Davide Italiano51507d22015-11-04 23:36:56 +00001451 Ret = OpC->getArgOperand(0);
1452 return Ret;
1453}
1454
Sanjay Patel57747212016-01-21 23:38:43 +00001455static bool isTrigLibCall(CallInst *CI) {
Sanjay Patel57747212016-01-21 23:38:43 +00001456 // We can only hope to do anything useful if we can ignore things like errno
1457 // and floating-point exceptions.
Ahmed Bougachad765a822016-04-27 19:04:35 +00001458 // We already checked the prototype.
1459 return CI->hasFnAttr(Attribute::NoUnwind) &&
1460 CI->hasFnAttr(Attribute::ReadNone);
Sanjay Patel57747212016-01-21 23:38:43 +00001461}
1462
Chris Bienemanad070d02014-09-17 20:55:46 +00001463static void insertSinCosCall(IRBuilder<> &B, Function *OrigCallee, Value *Arg,
1464 bool UseFloat, Value *&Sin, Value *&Cos,
Sanjay Patel57747212016-01-21 23:38:43 +00001465 Value *&SinCos) {
1466 Type *ArgTy = Arg->getType();
1467 Type *ResTy;
1468 StringRef Name;
1469
1470 Triple T(OrigCallee->getParent()->getTargetTriple());
1471 if (UseFloat) {
1472 Name = "__sincospif_stret";
1473
1474 assert(T.getArch() != Triple::x86 && "x86 messy and unsupported for now");
1475 // x86_64 can't use {float, float} since that would be returned in both
1476 // xmm0 and xmm1, which isn't what a real struct would do.
1477 ResTy = T.getArch() == Triple::x86_64
Serge Gueltone38003f2017-05-09 19:31:13 +00001478 ? static_cast<Type *>(VectorType::get(ArgTy, 2))
1479 : static_cast<Type *>(StructType::get(ArgTy, ArgTy));
Sanjay Patel57747212016-01-21 23:38:43 +00001480 } else {
1481 Name = "__sincospi_stret";
Serge Gueltone38003f2017-05-09 19:31:13 +00001482 ResTy = StructType::get(ArgTy, ArgTy);
Sanjay Patel57747212016-01-21 23:38:43 +00001483 }
1484
1485 Module *M = OrigCallee->getParent();
Mehdi Aminidb11fdf2017-04-06 20:23:57 +00001486 Value *Callee = M->getOrInsertFunction(Name, OrigCallee->getAttributes(),
Serge Guelton59a2d7b2017-04-11 15:01:18 +00001487 ResTy, ArgTy);
Sanjay Patel57747212016-01-21 23:38:43 +00001488
1489 if (Instruction *ArgInst = dyn_cast<Instruction>(Arg)) {
1490 // If the argument is an instruction, it must dominate all uses so put our
1491 // sincos call there.
1492 B.SetInsertPoint(ArgInst->getParent(), ++ArgInst->getIterator());
1493 } else {
1494 // Otherwise (e.g. for a constant) the beginning of the function is as
1495 // good a place as any.
1496 BasicBlock &EntryBB = B.GetInsertBlock()->getParent()->getEntryBlock();
1497 B.SetInsertPoint(&EntryBB, EntryBB.begin());
1498 }
1499
1500 SinCos = B.CreateCall(Callee, Arg, "sincospi");
1501
1502 if (SinCos->getType()->isStructTy()) {
1503 Sin = B.CreateExtractValue(SinCos, 0, "sinpi");
1504 Cos = B.CreateExtractValue(SinCos, 1, "cospi");
1505 } else {
1506 Sin = B.CreateExtractElement(SinCos, ConstantInt::get(B.getInt32Ty(), 0),
1507 "sinpi");
1508 Cos = B.CreateExtractElement(SinCos, ConstantInt::get(B.getInt32Ty(), 1),
1509 "cospi");
1510 }
1511}
Chris Bienemanad070d02014-09-17 20:55:46 +00001512
1513Value *LibCallSimplifier::optimizeSinCosPi(CallInst *CI, IRBuilder<> &B) {
Chris Bienemanad070d02014-09-17 20:55:46 +00001514 // Make sure the prototype is as expected, otherwise the rest of the
1515 // function is probably invalid and likely to abort.
1516 if (!isTrigLibCall(CI))
1517 return nullptr;
1518
1519 Value *Arg = CI->getArgOperand(0);
1520 SmallVector<CallInst *, 1> SinCalls;
1521 SmallVector<CallInst *, 1> CosCalls;
1522 SmallVector<CallInst *, 1> SinCosCalls;
1523
1524 bool IsFloat = Arg->getType()->isFloatTy();
1525
1526 // Look for all compatible sinpi, cospi and sincospi calls with the same
1527 // argument. If there are enough (in some sense) we can make the
1528 // substitution.
David Majnemerabae6b52016-03-19 04:53:02 +00001529 Function *F = CI->getFunction();
Chris Bienemanad070d02014-09-17 20:55:46 +00001530 for (User *U : Arg->users())
David Majnemerabae6b52016-03-19 04:53:02 +00001531 classifyArgUse(U, F, IsFloat, SinCalls, CosCalls, SinCosCalls);
Chris Bienemanad070d02014-09-17 20:55:46 +00001532
1533 // It's only worthwhile if both sinpi and cospi are actually used.
1534 if (SinCosCalls.empty() && (SinCalls.empty() || CosCalls.empty()))
1535 return nullptr;
1536
1537 Value *Sin, *Cos, *SinCos;
1538 insertSinCosCall(B, CI->getCalledFunction(), Arg, IsFloat, Sin, Cos, SinCos);
1539
Davide Italianof024a562016-12-16 02:28:38 +00001540 auto replaceTrigInsts = [this](SmallVectorImpl<CallInst *> &Calls,
1541 Value *Res) {
1542 for (CallInst *C : Calls)
1543 replaceAllUsesWith(C, Res);
1544 };
1545
Chris Bienemanad070d02014-09-17 20:55:46 +00001546 replaceTrigInsts(SinCalls, Sin);
1547 replaceTrigInsts(CosCalls, Cos);
1548 replaceTrigInsts(SinCosCalls, SinCos);
1549
1550 return nullptr;
1551}
1552
David Majnemerabae6b52016-03-19 04:53:02 +00001553void LibCallSimplifier::classifyArgUse(
1554 Value *Val, Function *F, bool IsFloat,
1555 SmallVectorImpl<CallInst *> &SinCalls,
1556 SmallVectorImpl<CallInst *> &CosCalls,
1557 SmallVectorImpl<CallInst *> &SinCosCalls) {
Chris Bienemanad070d02014-09-17 20:55:46 +00001558 CallInst *CI = dyn_cast<CallInst>(Val);
1559
1560 if (!CI)
1561 return;
1562
David Majnemerabae6b52016-03-19 04:53:02 +00001563 // Don't consider calls in other functions.
1564 if (CI->getFunction() != F)
1565 return;
1566
Chris Bienemanad070d02014-09-17 20:55:46 +00001567 Function *Callee = CI->getCalledFunction();
David L. Jonesd21529f2017-01-23 23:16:46 +00001568 LibFunc Func;
Ahmed Bougachad765a822016-04-27 19:04:35 +00001569 if (!Callee || !TLI->getLibFunc(*Callee, Func) || !TLI->has(Func) ||
Benjamin Kramer89766e52015-11-28 21:43:12 +00001570 !isTrigLibCall(CI))
Chris Bienemanad070d02014-09-17 20:55:46 +00001571 return;
1572
1573 if (IsFloat) {
David L. Jonesd21529f2017-01-23 23:16:46 +00001574 if (Func == LibFunc_sinpif)
Chris Bienemanad070d02014-09-17 20:55:46 +00001575 SinCalls.push_back(CI);
David L. Jonesd21529f2017-01-23 23:16:46 +00001576 else if (Func == LibFunc_cospif)
Chris Bienemanad070d02014-09-17 20:55:46 +00001577 CosCalls.push_back(CI);
David L. Jonesd21529f2017-01-23 23:16:46 +00001578 else if (Func == LibFunc_sincospif_stret)
Chris Bienemanad070d02014-09-17 20:55:46 +00001579 SinCosCalls.push_back(CI);
1580 } else {
David L. Jonesd21529f2017-01-23 23:16:46 +00001581 if (Func == LibFunc_sinpi)
Chris Bienemanad070d02014-09-17 20:55:46 +00001582 SinCalls.push_back(CI);
David L. Jonesd21529f2017-01-23 23:16:46 +00001583 else if (Func == LibFunc_cospi)
Chris Bienemanad070d02014-09-17 20:55:46 +00001584 CosCalls.push_back(CI);
David L. Jonesd21529f2017-01-23 23:16:46 +00001585 else if (Func == LibFunc_sincospi_stret)
Chris Bienemanad070d02014-09-17 20:55:46 +00001586 SinCosCalls.push_back(CI);
1587 }
1588}
1589
Meador Inge7415f842012-11-25 20:45:27 +00001590//===----------------------------------------------------------------------===//
1591// Integer Library Call Optimizations
1592//===----------------------------------------------------------------------===//
1593
Chris Bienemanad070d02014-09-17 20:55:46 +00001594Value *LibCallSimplifier::optimizeFFS(CallInst *CI, IRBuilder<> &B) {
Chris Bienemanad070d02014-09-17 20:55:46 +00001595 // ffs(x) -> x != 0 ? (i32)llvm.cttz(x)+1 : 0
Davide Italiano890e8502016-12-15 23:11:00 +00001596 Value *Op = CI->getArgOperand(0);
Chris Bienemanad070d02014-09-17 20:55:46 +00001597 Type *ArgType = Op->getType();
Davide Italiano890e8502016-12-15 23:11:00 +00001598 Value *F = Intrinsic::getDeclaration(CI->getCalledFunction()->getParent(),
1599 Intrinsic::cttz, ArgType);
Davide Italianoa1953862015-08-13 20:34:26 +00001600 Value *V = B.CreateCall(F, {Op, B.getTrue()}, "cttz");
Chris Bienemanad070d02014-09-17 20:55:46 +00001601 V = B.CreateAdd(V, ConstantInt::get(V->getType(), 1));
1602 V = B.CreateIntCast(V, B.getInt32Ty(), false);
Meador Ingea0b6d872012-11-26 00:24:07 +00001603
Chris Bienemanad070d02014-09-17 20:55:46 +00001604 Value *Cond = B.CreateICmpNE(Op, Constant::getNullValue(ArgType));
1605 return B.CreateSelect(Cond, V, B.getInt32(0));
1606}
Meador Ingea0b6d872012-11-26 00:24:07 +00001607
Davide Italiano85ad36b2016-12-15 23:45:11 +00001608Value *LibCallSimplifier::optimizeFls(CallInst *CI, IRBuilder<> &B) {
1609 // fls(x) -> (i32)(sizeInBits(x) - llvm.ctlz(x, false))
1610 Value *Op = CI->getArgOperand(0);
1611 Type *ArgType = Op->getType();
1612 Value *F = Intrinsic::getDeclaration(CI->getCalledFunction()->getParent(),
1613 Intrinsic::ctlz, ArgType);
1614 Value *V = B.CreateCall(F, {Op, B.getFalse()}, "ctlz");
1615 V = B.CreateSub(ConstantInt::get(V->getType(), ArgType->getIntegerBitWidth()),
1616 V);
1617 return B.CreateIntCast(V, CI->getType(), false);
1618}
1619
Chris Bienemanad070d02014-09-17 20:55:46 +00001620Value *LibCallSimplifier::optimizeAbs(CallInst *CI, IRBuilder<> &B) {
Chris Bienemanad070d02014-09-17 20:55:46 +00001621 // abs(x) -> x >s -1 ? x : -x
1622 Value *Op = CI->getArgOperand(0);
1623 Value *Pos =
1624 B.CreateICmpSGT(Op, Constant::getAllOnesValue(Op->getType()), "ispos");
1625 Value *Neg = B.CreateNeg(Op, "neg");
1626 return B.CreateSelect(Pos, Op, Neg);
1627}
Meador Inge9a59ab62012-11-26 02:31:59 +00001628
Chris Bienemanad070d02014-09-17 20:55:46 +00001629Value *LibCallSimplifier::optimizeIsDigit(CallInst *CI, IRBuilder<> &B) {
Chris Bienemanad070d02014-09-17 20:55:46 +00001630 // isdigit(c) -> (c-'0') <u 10
1631 Value *Op = CI->getArgOperand(0);
1632 Op = B.CreateSub(Op, B.getInt32('0'), "isdigittmp");
1633 Op = B.CreateICmpULT(Op, B.getInt32(10), "isdigit");
1634 return B.CreateZExt(Op, CI->getType());
1635}
Meador Ingea62a39e2012-11-26 03:10:07 +00001636
Chris Bienemanad070d02014-09-17 20:55:46 +00001637Value *LibCallSimplifier::optimizeIsAscii(CallInst *CI, IRBuilder<> &B) {
Chris Bienemanad070d02014-09-17 20:55:46 +00001638 // isascii(c) -> c <u 128
1639 Value *Op = CI->getArgOperand(0);
1640 Op = B.CreateICmpULT(Op, B.getInt32(128), "isascii");
1641 return B.CreateZExt(Op, CI->getType());
1642}
1643
1644Value *LibCallSimplifier::optimizeToAscii(CallInst *CI, IRBuilder<> &B) {
Chris Bienemanad070d02014-09-17 20:55:46 +00001645 // toascii(c) -> c & 0x7f
1646 return B.CreateAnd(CI->getArgOperand(0),
1647 ConstantInt::get(CI->getType(), 0x7F));
1648}
Meador Inge604937d2012-11-26 03:38:52 +00001649
Meador Inge08ca1152012-11-26 20:37:20 +00001650//===----------------------------------------------------------------------===//
1651// Formatting and IO Library Call Optimizations
1652//===----------------------------------------------------------------------===//
1653
Chris Bienemanad070d02014-09-17 20:55:46 +00001654static bool isReportingError(Function *Callee, CallInst *CI, int StreamArg);
Hal Finkel66cd3f12013-11-17 02:06:35 +00001655
Chris Bienemanad070d02014-09-17 20:55:46 +00001656Value *LibCallSimplifier::optimizeErrorReporting(CallInst *CI, IRBuilder<> &B,
1657 int StreamArg) {
Ahmed Bougachad765a822016-04-27 19:04:35 +00001658 Function *Callee = CI->getCalledFunction();
Chris Bienemanad070d02014-09-17 20:55:46 +00001659 // Error reporting calls should be cold, mark them as such.
1660 // This applies even to non-builtin calls: it is only a hint and applies to
1661 // functions that the frontend might not understand as builtins.
Hal Finkel66cd3f12013-11-17 02:06:35 +00001662
Chris Bienemanad070d02014-09-17 20:55:46 +00001663 // This heuristic was suggested in:
1664 // Improving Static Branch Prediction in a Compiler
1665 // Brian L. Deitrich, Ben-Chung Cheng, Wen-mei W. Hwu
1666 // Proceedings of PACT'98, Oct. 1998, IEEE
Chris Bienemanad070d02014-09-17 20:55:46 +00001667 if (!CI->hasFnAttr(Attribute::Cold) &&
1668 isReportingError(Callee, CI, StreamArg)) {
Reid Klecknerb5180542017-03-21 16:57:19 +00001669 CI->addAttribute(AttributeList::FunctionIndex, Attribute::Cold);
Chris Bienemanad070d02014-09-17 20:55:46 +00001670 }
Hal Finkel66cd3f12013-11-17 02:06:35 +00001671
Chris Bienemanad070d02014-09-17 20:55:46 +00001672 return nullptr;
1673}
1674
1675static bool isReportingError(Function *Callee, CallInst *CI, int StreamArg) {
Davide Italiano5b65f122017-04-25 03:48:47 +00001676 if (!Callee || !Callee->isDeclaration())
Chris Bienemanad070d02014-09-17 20:55:46 +00001677 return false;
1678
1679 if (StreamArg < 0)
1680 return true;
1681
1682 // These functions might be considered cold, but only if their stream
1683 // argument is stderr.
1684
1685 if (StreamArg >= (int)CI->getNumArgOperands())
1686 return false;
1687 LoadInst *LI = dyn_cast<LoadInst>(CI->getArgOperand(StreamArg));
1688 if (!LI)
1689 return false;
1690 GlobalVariable *GV = dyn_cast<GlobalVariable>(LI->getPointerOperand());
1691 if (!GV || !GV->isDeclaration())
1692 return false;
1693 return GV->getName() == "stderr";
1694}
1695
1696Value *LibCallSimplifier::optimizePrintFString(CallInst *CI, IRBuilder<> &B) {
1697 // Check for a fixed format string.
1698 StringRef FormatStr;
1699 if (!getConstantStringInfo(CI->getArgOperand(0), FormatStr))
Craig Topperf40110f2014-04-25 05:29:35 +00001700 return nullptr;
Hal Finkel66cd3f12013-11-17 02:06:35 +00001701
Chris Bienemanad070d02014-09-17 20:55:46 +00001702 // Empty format string -> noop.
1703 if (FormatStr.empty()) // Tolerate printf's declared void.
1704 return CI->use_empty() ? (Value *)CI : ConstantInt::get(CI->getType(), 0);
Hal Finkel66cd3f12013-11-17 02:06:35 +00001705
Chris Bienemanad070d02014-09-17 20:55:46 +00001706 // Do not do any of the following transformations if the printf return value
1707 // is used, in general the printf return value is not compatible with either
1708 // putchar() or puts().
1709 if (!CI->use_empty())
Craig Topperf40110f2014-04-25 05:29:35 +00001710 return nullptr;
Chris Bienemanad070d02014-09-17 20:55:46 +00001711
Joerg Sonnenberger8ffe7ab2016-05-09 14:36:16 +00001712 // printf("x") -> putchar('x'), even for "%" and "%%".
1713 if (FormatStr.size() == 1 || FormatStr == "%%")
Davide Italianod4f5a052016-04-03 01:46:52 +00001714 return emitPutChar(B.getInt32(FormatStr[0]), B, TLI);
Meador Inge08ca1152012-11-26 20:37:20 +00001715
Davide Italiano6db1dcb2016-03-28 15:54:01 +00001716 // printf("%s", "a") --> putchar('a')
1717 if (FormatStr == "%s" && CI->getNumArgOperands() > 1) {
1718 StringRef ChrStr;
1719 if (!getConstantStringInfo(CI->getOperand(1), ChrStr))
1720 return nullptr;
1721 if (ChrStr.size() != 1)
1722 return nullptr;
Davide Italianod4f5a052016-04-03 01:46:52 +00001723 return emitPutChar(B.getInt32(ChrStr[0]), B, TLI);
Davide Italiano6db1dcb2016-03-28 15:54:01 +00001724 }
1725
Chris Bienemanad070d02014-09-17 20:55:46 +00001726 // printf("foo\n") --> puts("foo")
1727 if (FormatStr[FormatStr.size() - 1] == '\n' &&
1728 FormatStr.find('%') == StringRef::npos) { // No format characters.
1729 // Create a string literal with no \n on it. We expect the constant merge
1730 // pass to be run after this pass, to merge duplicate strings.
1731 FormatStr = FormatStr.drop_back();
1732 Value *GV = B.CreateGlobalString(FormatStr, "str");
Davide Italianod4f5a052016-04-03 01:46:52 +00001733 return emitPutS(GV, B, TLI);
Chris Bienemanad070d02014-09-17 20:55:46 +00001734 }
Meador Inge08ca1152012-11-26 20:37:20 +00001735
Chris Bienemanad070d02014-09-17 20:55:46 +00001736 // Optimize specific format strings.
1737 // printf("%c", chr) --> putchar(chr)
1738 if (FormatStr == "%c" && CI->getNumArgOperands() > 1 &&
Davide Italianod4f5a052016-04-03 01:46:52 +00001739 CI->getArgOperand(1)->getType()->isIntegerTy())
1740 return emitPutChar(CI->getArgOperand(1), B, TLI);
Chris Bienemanad070d02014-09-17 20:55:46 +00001741
1742 // printf("%s\n", str) --> puts(str)
1743 if (FormatStr == "%s\n" && CI->getNumArgOperands() > 1 &&
Davide Italianod4f5a052016-04-03 01:46:52 +00001744 CI->getArgOperand(1)->getType()->isPointerTy())
Sanjay Pateld3112a52016-01-19 19:46:10 +00001745 return emitPutS(CI->getArgOperand(1), B, TLI);
Chris Bienemanad070d02014-09-17 20:55:46 +00001746 return nullptr;
1747}
1748
1749Value *LibCallSimplifier::optimizePrintF(CallInst *CI, IRBuilder<> &B) {
1750
1751 Function *Callee = CI->getCalledFunction();
Chris Bienemanad070d02014-09-17 20:55:46 +00001752 FunctionType *FT = Callee->getFunctionType();
Chris Bienemanad070d02014-09-17 20:55:46 +00001753 if (Value *V = optimizePrintFString(CI, B)) {
1754 return V;
1755 }
1756
1757 // printf(format, ...) -> iprintf(format, ...) if no floating point
1758 // arguments.
David L. Jonesd21529f2017-01-23 23:16:46 +00001759 if (TLI->has(LibFunc_iprintf) && !callHasFloatingPointArgument(CI)) {
Chris Bienemanad070d02014-09-17 20:55:46 +00001760 Module *M = B.GetInsertBlock()->getParent()->getParent();
1761 Constant *IPrintFFn =
Meador Inge08ca1152012-11-26 20:37:20 +00001762 M->getOrInsertFunction("iprintf", FT, Callee->getAttributes());
Chris Bienemanad070d02014-09-17 20:55:46 +00001763 CallInst *New = cast<CallInst>(CI->clone());
1764 New->setCalledFunction(IPrintFFn);
1765 B.Insert(New);
1766 return New;
Meador Inge08ca1152012-11-26 20:37:20 +00001767 }
Chris Bienemanad070d02014-09-17 20:55:46 +00001768 return nullptr;
1769}
Meador Inge08ca1152012-11-26 20:37:20 +00001770
Chris Bienemanad070d02014-09-17 20:55:46 +00001771Value *LibCallSimplifier::optimizeSPrintFString(CallInst *CI, IRBuilder<> &B) {
1772 // Check for a fixed format string.
1773 StringRef FormatStr;
1774 if (!getConstantStringInfo(CI->getArgOperand(1), FormatStr))
Craig Topperf40110f2014-04-25 05:29:35 +00001775 return nullptr;
Meador Inge25c9b3b2012-11-27 05:57:54 +00001776
Chris Bienemanad070d02014-09-17 20:55:46 +00001777 // If we just have a format string (nothing else crazy) transform it.
1778 if (CI->getNumArgOperands() == 2) {
1779 // Make sure there's no % in the constant array. We could try to handle
1780 // %% -> % in the future if we cared.
1781 for (unsigned i = 0, e = FormatStr.size(); i != e; ++i)
1782 if (FormatStr[i] == '%')
1783 return nullptr; // we found a format specifier, bail out.
Hal Finkel66cd3f12013-11-17 02:06:35 +00001784
Chris Bienemanad070d02014-09-17 20:55:46 +00001785 // sprintf(str, fmt) -> llvm.memcpy(str, fmt, strlen(fmt)+1, 1)
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001786 B.CreateMemCpy(CI->getArgOperand(0), CI->getArgOperand(1),
1787 ConstantInt::get(DL.getIntPtrType(CI->getContext()),
1788 FormatStr.size() + 1),
Pete Cooper67cf9a72015-11-19 05:56:52 +00001789 1); // Copy the null byte.
Chris Bienemanad070d02014-09-17 20:55:46 +00001790 return ConstantInt::get(CI->getType(), FormatStr.size());
Meador Ingef8e72502012-11-29 15:45:43 +00001791 }
Meador Ingef8e72502012-11-29 15:45:43 +00001792
Chris Bienemanad070d02014-09-17 20:55:46 +00001793 // The remaining optimizations require the format string to be "%s" or "%c"
1794 // and have an extra operand.
1795 if (FormatStr.size() != 2 || FormatStr[0] != '%' ||
1796 CI->getNumArgOperands() < 3)
Craig Topperf40110f2014-04-25 05:29:35 +00001797 return nullptr;
Meador Inge75798bb2012-11-29 19:15:17 +00001798
Chris Bienemanad070d02014-09-17 20:55:46 +00001799 // Decode the second character of the format string.
1800 if (FormatStr[1] == 'c') {
1801 // sprintf(dst, "%c", chr) --> *(i8*)dst = chr; *((i8*)dst+1) = 0
1802 if (!CI->getArgOperand(2)->getType()->isIntegerTy())
1803 return nullptr;
1804 Value *V = B.CreateTrunc(CI->getArgOperand(2), B.getInt8Ty(), "char");
Sanjay Pateld3112a52016-01-19 19:46:10 +00001805 Value *Ptr = castToCStr(CI->getArgOperand(0), B);
Chris Bienemanad070d02014-09-17 20:55:46 +00001806 B.CreateStore(V, Ptr);
David Blaikie3909da72015-03-30 20:42:56 +00001807 Ptr = B.CreateGEP(B.getInt8Ty(), Ptr, B.getInt32(1), "nul");
Chris Bienemanad070d02014-09-17 20:55:46 +00001808 B.CreateStore(B.getInt8(0), Ptr);
Meador Ingedf796f82012-10-13 16:45:24 +00001809
Chris Bienemanad070d02014-09-17 20:55:46 +00001810 return ConstantInt::get(CI->getType(), 1);
Meador Ingedf796f82012-10-13 16:45:24 +00001811 }
1812
Chris Bienemanad070d02014-09-17 20:55:46 +00001813 if (FormatStr[1] == 's') {
Chris Bienemanad070d02014-09-17 20:55:46 +00001814 // sprintf(dest, "%s", str) -> llvm.memcpy(dest, str, strlen(str)+1, 1)
1815 if (!CI->getArgOperand(2)->getType()->isPointerTy())
1816 return nullptr;
1817
Sanjay Pateld3112a52016-01-19 19:46:10 +00001818 Value *Len = emitStrLen(CI->getArgOperand(2), B, DL, TLI);
Chris Bienemanad070d02014-09-17 20:55:46 +00001819 if (!Len)
1820 return nullptr;
David Majnemerabb9f552016-04-26 21:04:47 +00001821 Value *IncLen =
1822 B.CreateAdd(Len, ConstantInt::get(Len->getType(), 1), "leninc");
1823 B.CreateMemCpy(CI->getArgOperand(0), CI->getArgOperand(2), IncLen, 1);
Chris Bienemanad070d02014-09-17 20:55:46 +00001824
1825 // The sprintf result is the unincremented number of bytes in the string.
1826 return B.CreateIntCast(Len, CI->getType(), false);
1827 }
1828 return nullptr;
1829}
1830
1831Value *LibCallSimplifier::optimizeSPrintF(CallInst *CI, IRBuilder<> &B) {
1832 Function *Callee = CI->getCalledFunction();
Chris Bienemanad070d02014-09-17 20:55:46 +00001833 FunctionType *FT = Callee->getFunctionType();
Chris Bienemanad070d02014-09-17 20:55:46 +00001834 if (Value *V = optimizeSPrintFString(CI, B)) {
1835 return V;
1836 }
1837
1838 // sprintf(str, format, ...) -> siprintf(str, format, ...) if no floating
1839 // point arguments.
David L. Jonesd21529f2017-01-23 23:16:46 +00001840 if (TLI->has(LibFunc_siprintf) && !callHasFloatingPointArgument(CI)) {
Chris Bienemanad070d02014-09-17 20:55:46 +00001841 Module *M = B.GetInsertBlock()->getParent()->getParent();
1842 Constant *SIPrintFFn =
1843 M->getOrInsertFunction("siprintf", FT, Callee->getAttributes());
1844 CallInst *New = cast<CallInst>(CI->clone());
1845 New->setCalledFunction(SIPrintFFn);
1846 B.Insert(New);
1847 return New;
1848 }
1849 return nullptr;
1850}
1851
1852Value *LibCallSimplifier::optimizeFPrintFString(CallInst *CI, IRBuilder<> &B) {
1853 optimizeErrorReporting(CI, B, 0);
1854
1855 // All the optimizations depend on the format string.
1856 StringRef FormatStr;
1857 if (!getConstantStringInfo(CI->getArgOperand(1), FormatStr))
1858 return nullptr;
1859
1860 // Do not do any of the following transformations if the fprintf return
1861 // value is used, in general the fprintf return value is not compatible
1862 // with fwrite(), fputc() or fputs().
1863 if (!CI->use_empty())
1864 return nullptr;
1865
1866 // fprintf(F, "foo") --> fwrite("foo", 3, 1, F)
1867 if (CI->getNumArgOperands() == 2) {
1868 for (unsigned i = 0, e = FormatStr.size(); i != e; ++i)
1869 if (FormatStr[i] == '%') // Could handle %% -> % if we cared.
1870 return nullptr; // We found a format specifier.
1871
Sanjay Pateld3112a52016-01-19 19:46:10 +00001872 return emitFWrite(
Chris Bienemanad070d02014-09-17 20:55:46 +00001873 CI->getArgOperand(1),
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001874 ConstantInt::get(DL.getIntPtrType(CI->getContext()), FormatStr.size()),
Chris Bienemanad070d02014-09-17 20:55:46 +00001875 CI->getArgOperand(0), B, DL, TLI);
1876 }
1877
1878 // The remaining optimizations require the format string to be "%s" or "%c"
1879 // and have an extra operand.
1880 if (FormatStr.size() != 2 || FormatStr[0] != '%' ||
1881 CI->getNumArgOperands() < 3)
1882 return nullptr;
1883
1884 // Decode the second character of the format string.
1885 if (FormatStr[1] == 'c') {
1886 // fprintf(F, "%c", chr) --> fputc(chr, F)
1887 if (!CI->getArgOperand(2)->getType()->isIntegerTy())
1888 return nullptr;
Sanjay Pateld3112a52016-01-19 19:46:10 +00001889 return emitFPutC(CI->getArgOperand(2), CI->getArgOperand(0), B, TLI);
Chris Bienemanad070d02014-09-17 20:55:46 +00001890 }
1891
1892 if (FormatStr[1] == 's') {
1893 // fprintf(F, "%s", str) --> fputs(str, F)
1894 if (!CI->getArgOperand(2)->getType()->isPointerTy())
1895 return nullptr;
Sanjay Pateld3112a52016-01-19 19:46:10 +00001896 return emitFPutS(CI->getArgOperand(2), CI->getArgOperand(0), B, TLI);
Chris Bienemanad070d02014-09-17 20:55:46 +00001897 }
1898 return nullptr;
1899}
1900
1901Value *LibCallSimplifier::optimizeFPrintF(CallInst *CI, IRBuilder<> &B) {
1902 Function *Callee = CI->getCalledFunction();
Chris Bienemanad070d02014-09-17 20:55:46 +00001903 FunctionType *FT = Callee->getFunctionType();
Chris Bienemanad070d02014-09-17 20:55:46 +00001904 if (Value *V = optimizeFPrintFString(CI, B)) {
1905 return V;
1906 }
1907
1908 // fprintf(stream, format, ...) -> fiprintf(stream, format, ...) if no
1909 // floating point arguments.
David L. Jonesd21529f2017-01-23 23:16:46 +00001910 if (TLI->has(LibFunc_fiprintf) && !callHasFloatingPointArgument(CI)) {
Chris Bienemanad070d02014-09-17 20:55:46 +00001911 Module *M = B.GetInsertBlock()->getParent()->getParent();
1912 Constant *FIPrintFFn =
1913 M->getOrInsertFunction("fiprintf", FT, Callee->getAttributes());
1914 CallInst *New = cast<CallInst>(CI->clone());
1915 New->setCalledFunction(FIPrintFFn);
1916 B.Insert(New);
1917 return New;
1918 }
1919 return nullptr;
1920}
1921
1922Value *LibCallSimplifier::optimizeFWrite(CallInst *CI, IRBuilder<> &B) {
1923 optimizeErrorReporting(CI, B, 3);
1924
Chris Bienemanad070d02014-09-17 20:55:46 +00001925 // Get the element size and count.
1926 ConstantInt *SizeC = dyn_cast<ConstantInt>(CI->getArgOperand(1));
1927 ConstantInt *CountC = dyn_cast<ConstantInt>(CI->getArgOperand(2));
1928 if (!SizeC || !CountC)
1929 return nullptr;
1930 uint64_t Bytes = SizeC->getZExtValue() * CountC->getZExtValue();
1931
1932 // If this is writing zero records, remove the call (it's a noop).
1933 if (Bytes == 0)
1934 return ConstantInt::get(CI->getType(), 0);
1935
1936 // If this is writing one byte, turn it into fputc.
1937 // This optimisation is only valid, if the return value is unused.
1938 if (Bytes == 1 && CI->use_empty()) { // fwrite(S,1,1,F) -> fputc(S[0],F)
Sanjay Pateld3112a52016-01-19 19:46:10 +00001939 Value *Char = B.CreateLoad(castToCStr(CI->getArgOperand(0), B), "char");
1940 Value *NewCI = emitFPutC(Char, CI->getArgOperand(3), B, TLI);
Chris Bienemanad070d02014-09-17 20:55:46 +00001941 return NewCI ? ConstantInt::get(CI->getType(), 1) : nullptr;
1942 }
1943
1944 return nullptr;
1945}
1946
1947Value *LibCallSimplifier::optimizeFPuts(CallInst *CI, IRBuilder<> &B) {
1948 optimizeErrorReporting(CI, B, 1);
1949
Sjoerd Meijer7435a912016-07-07 14:31:19 +00001950 // Don't rewrite fputs to fwrite when optimising for size because fwrite
1951 // requires more arguments and thus extra MOVs are required.
1952 if (CI->getParent()->getParent()->optForSize())
1953 return nullptr;
1954
Ahmed Bougachad765a822016-04-27 19:04:35 +00001955 // We can't optimize if return value is used.
1956 if (!CI->use_empty())
Chris Bienemanad070d02014-09-17 20:55:46 +00001957 return nullptr;
1958
1959 // fputs(s,F) --> fwrite(s,1,strlen(s),F)
1960 uint64_t Len = GetStringLength(CI->getArgOperand(0));
1961 if (!Len)
1962 return nullptr;
1963
1964 // Known to have no uses (see above).
Sanjay Pateld3112a52016-01-19 19:46:10 +00001965 return emitFWrite(
Chris Bienemanad070d02014-09-17 20:55:46 +00001966 CI->getArgOperand(0),
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001967 ConstantInt::get(DL.getIntPtrType(CI->getContext()), Len - 1),
Chris Bienemanad070d02014-09-17 20:55:46 +00001968 CI->getArgOperand(1), B, DL, TLI);
1969}
1970
1971Value *LibCallSimplifier::optimizePuts(CallInst *CI, IRBuilder<> &B) {
Chris Bienemanad070d02014-09-17 20:55:46 +00001972 // Check for a constant string.
1973 StringRef Str;
1974 if (!getConstantStringInfo(CI->getArgOperand(0), Str))
1975 return nullptr;
1976
1977 if (Str.empty() && CI->use_empty()) {
1978 // puts("") -> putchar('\n')
Sanjay Pateld3112a52016-01-19 19:46:10 +00001979 Value *Res = emitPutChar(B.getInt32('\n'), B, TLI);
Chris Bienemanad070d02014-09-17 20:55:46 +00001980 if (CI->use_empty() || !Res)
1981 return Res;
1982 return B.CreateIntCast(Res, CI->getType(), true);
1983 }
1984
1985 return nullptr;
1986}
1987
1988bool LibCallSimplifier::hasFloatVersion(StringRef FuncName) {
David L. Jonesd21529f2017-01-23 23:16:46 +00001989 LibFunc Func;
Meador Inge20255ef2013-03-12 00:08:29 +00001990 SmallString<20> FloatFuncName = FuncName;
1991 FloatFuncName += 'f';
1992 if (TLI->getLibFunc(FloatFuncName, Func))
1993 return TLI->has(Func);
1994 return false;
1995}
Meador Inge7fb2f732012-10-13 16:45:32 +00001996
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00001997Value *LibCallSimplifier::optimizeStringMemoryLibCall(CallInst *CI,
1998 IRBuilder<> &Builder) {
David L. Jonesd21529f2017-01-23 23:16:46 +00001999 LibFunc Func;
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00002000 Function *Callee = CI->getCalledFunction();
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00002001 // Check for string/memory library functions.
Ahmed Bougachad765a822016-04-27 19:04:35 +00002002 if (TLI->getLibFunc(*Callee, Func) && TLI->has(Func)) {
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00002003 // Make sure we never change the calling convention.
2004 assert((ignoreCallingConv(Func) ||
Sam Parker214f7bf2016-09-13 12:10:14 +00002005 isCallingConvCCompatible(CI)) &&
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00002006 "Optimizing string/memory libcall would change the calling convention");
2007 switch (Func) {
David L. Jonesd21529f2017-01-23 23:16:46 +00002008 case LibFunc_strcat:
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00002009 return optimizeStrCat(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002010 case LibFunc_strncat:
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00002011 return optimizeStrNCat(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002012 case LibFunc_strchr:
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00002013 return optimizeStrChr(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002014 case LibFunc_strrchr:
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00002015 return optimizeStrRChr(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002016 case LibFunc_strcmp:
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00002017 return optimizeStrCmp(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002018 case LibFunc_strncmp:
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00002019 return optimizeStrNCmp(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002020 case LibFunc_strcpy:
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00002021 return optimizeStrCpy(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002022 case LibFunc_stpcpy:
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00002023 return optimizeStpCpy(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002024 case LibFunc_strncpy:
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00002025 return optimizeStrNCpy(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002026 case LibFunc_strlen:
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00002027 return optimizeStrLen(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002028 case LibFunc_strpbrk:
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00002029 return optimizeStrPBrk(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002030 case LibFunc_strtol:
2031 case LibFunc_strtod:
2032 case LibFunc_strtof:
2033 case LibFunc_strtoul:
2034 case LibFunc_strtoll:
2035 case LibFunc_strtold:
2036 case LibFunc_strtoull:
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00002037 return optimizeStrTo(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002038 case LibFunc_strspn:
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00002039 return optimizeStrSpn(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002040 case LibFunc_strcspn:
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00002041 return optimizeStrCSpn(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002042 case LibFunc_strstr:
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00002043 return optimizeStrStr(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002044 case LibFunc_memchr:
Benjamin Kramer691363e2015-03-21 15:36:21 +00002045 return optimizeMemChr(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002046 case LibFunc_memcmp:
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00002047 return optimizeMemCmp(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002048 case LibFunc_memcpy:
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00002049 return optimizeMemCpy(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002050 case LibFunc_memmove:
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00002051 return optimizeMemMove(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002052 case LibFunc_memset:
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00002053 return optimizeMemSet(CI, Builder);
Matthias Braun50ec0b52017-05-19 22:37:09 +00002054 case LibFunc_wcslen:
2055 return optimizeWcslen(CI, Builder);
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00002056 default:
2057 break;
2058 }
2059 }
2060 return nullptr;
2061}
2062
Andrew Kaylor53a5fbb2017-08-14 21:15:13 +00002063Value *LibCallSimplifier::optimizeFloatingPointLibCall(CallInst *CI,
2064 LibFunc Func,
2065 IRBuilder<> &Builder) {
2066 // Don't optimize calls that require strict floating point semantics.
2067 if (CI->isStrictFP())
2068 return nullptr;
2069
2070 switch (Func) {
2071 case LibFunc_cosf:
2072 case LibFunc_cos:
2073 case LibFunc_cosl:
2074 return optimizeCos(CI, Builder);
2075 case LibFunc_sinpif:
2076 case LibFunc_sinpi:
2077 case LibFunc_cospif:
2078 case LibFunc_cospi:
2079 return optimizeSinCosPi(CI, Builder);
2080 case LibFunc_powf:
2081 case LibFunc_pow:
2082 case LibFunc_powl:
2083 return optimizePow(CI, Builder);
2084 case LibFunc_exp2l:
2085 case LibFunc_exp2:
2086 case LibFunc_exp2f:
2087 return optimizeExp2(CI, Builder);
2088 case LibFunc_fabsf:
2089 case LibFunc_fabs:
2090 case LibFunc_fabsl:
2091 return replaceUnaryCall(CI, Builder, Intrinsic::fabs);
2092 case LibFunc_sqrtf:
2093 case LibFunc_sqrt:
2094 case LibFunc_sqrtl:
2095 return optimizeSqrt(CI, Builder);
2096 case LibFunc_log:
2097 case LibFunc_log10:
2098 case LibFunc_log1p:
2099 case LibFunc_log2:
2100 case LibFunc_logb:
2101 return optimizeLog(CI, Builder);
2102 case LibFunc_tan:
2103 case LibFunc_tanf:
2104 case LibFunc_tanl:
2105 return optimizeTan(CI, Builder);
2106 case LibFunc_ceil:
2107 return replaceUnaryCall(CI, Builder, Intrinsic::ceil);
2108 case LibFunc_floor:
2109 return replaceUnaryCall(CI, Builder, Intrinsic::floor);
2110 case LibFunc_round:
2111 return replaceUnaryCall(CI, Builder, Intrinsic::round);
2112 case LibFunc_nearbyint:
2113 return replaceUnaryCall(CI, Builder, Intrinsic::nearbyint);
2114 case LibFunc_rint:
2115 return replaceUnaryCall(CI, Builder, Intrinsic::rint);
2116 case LibFunc_trunc:
2117 return replaceUnaryCall(CI, Builder, Intrinsic::trunc);
2118 case LibFunc_acos:
2119 case LibFunc_acosh:
2120 case LibFunc_asin:
2121 case LibFunc_asinh:
2122 case LibFunc_atan:
2123 case LibFunc_atanh:
2124 case LibFunc_cbrt:
2125 case LibFunc_cosh:
2126 case LibFunc_exp:
2127 case LibFunc_exp10:
2128 case LibFunc_expm1:
2129 case LibFunc_sin:
2130 case LibFunc_sinh:
2131 case LibFunc_tanh:
2132 if (UnsafeFPShrink && hasFloatVersion(CI->getCalledFunction()->getName()))
2133 return optimizeUnaryDoubleFP(CI, Builder, true);
2134 return nullptr;
2135 case LibFunc_copysign:
2136 if (hasFloatVersion(CI->getCalledFunction()->getName()))
2137 return optimizeBinaryDoubleFP(CI, Builder);
2138 return nullptr;
2139 case LibFunc_fminf:
2140 case LibFunc_fmin:
2141 case LibFunc_fminl:
2142 case LibFunc_fmaxf:
2143 case LibFunc_fmax:
2144 case LibFunc_fmaxl:
2145 return optimizeFMinFMax(CI, Builder);
2146 default:
2147 return nullptr;
2148 }
2149}
2150
Chris Bienemanad070d02014-09-17 20:55:46 +00002151Value *LibCallSimplifier::optimizeCall(CallInst *CI) {
Andrew Kaylor53a5fbb2017-08-14 21:15:13 +00002152 // TODO: Split out the code below that operates on FP calls so that
2153 // we can all non-FP calls with the StrictFP attribute to be
2154 // optimized.
Chris Bienemanad070d02014-09-17 20:55:46 +00002155 if (CI->isNoBuiltin())
2156 return nullptr;
Meador Inge4d2827c2012-11-11 05:11:20 +00002157
David L. Jonesd21529f2017-01-23 23:16:46 +00002158 LibFunc Func;
Meador Inge20255ef2013-03-12 00:08:29 +00002159 Function *Callee = CI->getCalledFunction();
David Majnemerb70e23c2016-01-06 05:01:34 +00002160
2161 SmallVector<OperandBundleDef, 2> OpBundles;
2162 CI->getOperandBundlesAsDefs(OpBundles);
2163 IRBuilder<> Builder(CI, /*FPMathTag=*/nullptr, OpBundles);
Sam Parker214f7bf2016-09-13 12:10:14 +00002164 bool isCallingConvC = isCallingConvCCompatible(CI);
Meador Inge20255ef2013-03-12 00:08:29 +00002165
Sanjay Pateld1f4f032016-01-19 18:38:52 +00002166 // Command-line parameter overrides instruction attribute.
Andrew Kaylor53a5fbb2017-08-14 21:15:13 +00002167 // This can't be moved to optimizeFloatingPointLibCall() because it may be
2168 // used by the intrinsic optimizations.
Sanjay Patela92fa442014-10-22 15:29:23 +00002169 if (EnableUnsafeFPShrink.getNumOccurrences() > 0)
2170 UnsafeFPShrink = EnableUnsafeFPShrink;
Sanjay Pateld1f4f032016-01-19 18:38:52 +00002171 else if (isa<FPMathOperator>(CI) && CI->hasUnsafeAlgebra())
Davide Italianoa904e522015-10-29 02:58:44 +00002172 UnsafeFPShrink = true;
Sanjay Patela92fa442014-10-22 15:29:23 +00002173
Sanjay Patel848309d2014-10-23 21:52:45 +00002174 // First, check for intrinsics.
Meador Inge20255ef2013-03-12 00:08:29 +00002175 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(CI)) {
Chris Bienemanad070d02014-09-17 20:55:46 +00002176 if (!isCallingConvC)
2177 return nullptr;
Andrew Kaylor53a5fbb2017-08-14 21:15:13 +00002178 // The FP intrinsics have corresponding constrained versions so we don't
2179 // need to check for the StrictFP attribute here.
Meador Inge20255ef2013-03-12 00:08:29 +00002180 switch (II->getIntrinsicID()) {
2181 case Intrinsic::pow:
Chris Bienemanad070d02014-09-17 20:55:46 +00002182 return optimizePow(CI, Builder);
Meador Inge20255ef2013-03-12 00:08:29 +00002183 case Intrinsic::exp2:
Chris Bienemanad070d02014-09-17 20:55:46 +00002184 return optimizeExp2(CI, Builder);
Davide Italianob8b71332015-11-29 20:58:04 +00002185 case Intrinsic::log:
2186 return optimizeLog(CI, Builder);
Sanjay Patelc699a612014-10-16 18:48:17 +00002187 case Intrinsic::sqrt:
2188 return optimizeSqrt(CI, Builder);
Sanjay Patel980b2802016-01-26 16:17:24 +00002189 // TODO: Use foldMallocMemset() with memset intrinsic.
Meador Inge20255ef2013-03-12 00:08:29 +00002190 default:
Chris Bienemanad070d02014-09-17 20:55:46 +00002191 return nullptr;
Meador Inge20255ef2013-03-12 00:08:29 +00002192 }
2193 }
2194
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002195 // Also try to simplify calls to fortified library functions.
2196 if (Value *SimplifiedFortifiedCI = FortifiedSimplifier.optimizeCall(CI)) {
2197 // Try to further simplify the result.
Ahmed Bougacha71d7b182015-01-14 00:55:05 +00002198 CallInst *SimplifiedCI = dyn_cast<CallInst>(SimplifiedFortifiedCI);
Bruno Cardoso Lopesb491a2d2015-10-01 22:43:53 +00002199 if (SimplifiedCI && SimplifiedCI->getCalledFunction()) {
2200 // Use an IR Builder from SimplifiedCI if available instead of CI
2201 // to guarantee we reach all uses we might replace later on.
2202 IRBuilder<> TmpBuilder(SimplifiedCI);
2203 if (Value *V = optimizeStringMemoryLibCall(SimplifiedCI, TmpBuilder)) {
Ahmed Bougacha1ac93562015-01-27 21:52:16 +00002204 // If we were able to further simplify, remove the now redundant call.
2205 SimplifiedCI->replaceAllUsesWith(V);
2206 SimplifiedCI->eraseFromParent();
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002207 return V;
Ahmed Bougacha1ac93562015-01-27 21:52:16 +00002208 }
Bruno Cardoso Lopesb491a2d2015-10-01 22:43:53 +00002209 }
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002210 return SimplifiedFortifiedCI;
2211 }
2212
Meador Inge20255ef2013-03-12 00:08:29 +00002213 // Then check for known library functions.
Ahmed Bougachad765a822016-04-27 19:04:35 +00002214 if (TLI->getLibFunc(*Callee, Func) && TLI->has(Func)) {
Chris Bienemanad070d02014-09-17 20:55:46 +00002215 // We never change the calling convention.
2216 if (!ignoreCallingConv(Func) && !isCallingConvC)
2217 return nullptr;
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00002218 if (Value *V = optimizeStringMemoryLibCall(CI, Builder))
2219 return V;
Andrew Kaylor53a5fbb2017-08-14 21:15:13 +00002220 if (Value *V = optimizeFloatingPointLibCall(CI, Func, Builder))
2221 return V;
Meador Inge20255ef2013-03-12 00:08:29 +00002222 switch (Func) {
David L. Jonesd21529f2017-01-23 23:16:46 +00002223 case LibFunc_ffs:
2224 case LibFunc_ffsl:
2225 case LibFunc_ffsll:
Chris Bienemanad070d02014-09-17 20:55:46 +00002226 return optimizeFFS(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002227 case LibFunc_fls:
2228 case LibFunc_flsl:
2229 case LibFunc_flsll:
Davide Italiano85ad36b2016-12-15 23:45:11 +00002230 return optimizeFls(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002231 case LibFunc_abs:
2232 case LibFunc_labs:
2233 case LibFunc_llabs:
Chris Bienemanad070d02014-09-17 20:55:46 +00002234 return optimizeAbs(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002235 case LibFunc_isdigit:
Chris Bienemanad070d02014-09-17 20:55:46 +00002236 return optimizeIsDigit(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002237 case LibFunc_isascii:
Chris Bienemanad070d02014-09-17 20:55:46 +00002238 return optimizeIsAscii(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002239 case LibFunc_toascii:
Chris Bienemanad070d02014-09-17 20:55:46 +00002240 return optimizeToAscii(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002241 case LibFunc_printf:
Chris Bienemanad070d02014-09-17 20:55:46 +00002242 return optimizePrintF(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002243 case LibFunc_sprintf:
Chris Bienemanad070d02014-09-17 20:55:46 +00002244 return optimizeSPrintF(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002245 case LibFunc_fprintf:
Chris Bienemanad070d02014-09-17 20:55:46 +00002246 return optimizeFPrintF(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002247 case LibFunc_fwrite:
Chris Bienemanad070d02014-09-17 20:55:46 +00002248 return optimizeFWrite(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002249 case LibFunc_fputs:
Chris Bienemanad070d02014-09-17 20:55:46 +00002250 return optimizeFPuts(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002251 case LibFunc_puts:
Chris Bienemanad070d02014-09-17 20:55:46 +00002252 return optimizePuts(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002253 case LibFunc_perror:
Chris Bienemanad070d02014-09-17 20:55:46 +00002254 return optimizeErrorReporting(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002255 case LibFunc_vfprintf:
2256 case LibFunc_fiprintf:
Chris Bienemanad070d02014-09-17 20:55:46 +00002257 return optimizeErrorReporting(CI, Builder, 0);
David L. Jonesd21529f2017-01-23 23:16:46 +00002258 case LibFunc_fputc:
Chris Bienemanad070d02014-09-17 20:55:46 +00002259 return optimizeErrorReporting(CI, Builder, 1);
Chris Bienemanad070d02014-09-17 20:55:46 +00002260 default:
2261 return nullptr;
2262 }
Meador Inge20255ef2013-03-12 00:08:29 +00002263 }
Craig Topperf40110f2014-04-25 05:29:35 +00002264 return nullptr;
Meador Ingedf796f82012-10-13 16:45:24 +00002265}
2266
Chandler Carruth92803822015-01-21 02:11:59 +00002267LibCallSimplifier::LibCallSimplifier(
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002268 const DataLayout &DL, const TargetLibraryInfo *TLI,
Adam Nemetea06e6e2017-07-26 19:03:18 +00002269 OptimizationRemarkEmitter &ORE,
Chandler Carruth92803822015-01-21 02:11:59 +00002270 function_ref<void(Instruction *, Value *)> Replacer)
Adam Nemetea06e6e2017-07-26 19:03:18 +00002271 : FortifiedSimplifier(TLI), DL(DL), TLI(TLI), ORE(ORE),
2272 UnsafeFPShrink(false), Replacer(Replacer) {}
Chandler Carruth92803822015-01-21 02:11:59 +00002273
2274void LibCallSimplifier::replaceAllUsesWith(Instruction *I, Value *With) {
2275 // Indirect through the replacer used in this instance.
2276 Replacer(I, With);
Meador Ingedf796f82012-10-13 16:45:24 +00002277}
2278
Meador Ingedfb08a22013-06-20 19:48:07 +00002279// TODO:
2280// Additional cases that we need to add to this file:
2281//
2282// cbrt:
2283// * cbrt(expN(X)) -> expN(x/3)
2284// * cbrt(sqrt(x)) -> pow(x,1/6)
David Majnemer3354fe42015-08-26 18:30:16 +00002285// * cbrt(cbrt(x)) -> pow(x,1/9)
Meador Ingedfb08a22013-06-20 19:48:07 +00002286//
2287// exp, expf, expl:
2288// * exp(log(x)) -> x
2289//
2290// log, logf, logl:
2291// * log(exp(x)) -> x
Meador Ingedfb08a22013-06-20 19:48:07 +00002292// * log(exp(y)) -> y*log(e)
Meador Ingedfb08a22013-06-20 19:48:07 +00002293// * log(exp10(y)) -> y*log(10)
2294// * log(sqrt(x)) -> 0.5*log(x)
Meador Ingedfb08a22013-06-20 19:48:07 +00002295//
Meador Ingedfb08a22013-06-20 19:48:07 +00002296// pow, powf, powl:
Meador Ingedfb08a22013-06-20 19:48:07 +00002297// * pow(sqrt(x),y) -> pow(x,y*0.5)
2298// * pow(pow(x,y),z)-> pow(x,y*z)
2299//
Meador Ingedfb08a22013-06-20 19:48:07 +00002300// signbit:
2301// * signbit(cnst) -> cnst'
2302// * signbit(nncst) -> 0 (if pstv is a non-negative constant)
2303//
2304// sqrt, sqrtf, sqrtl:
2305// * sqrt(expN(x)) -> expN(x*0.5)
2306// * sqrt(Nroot(x)) -> pow(x,1/(2*N))
2307// * sqrt(pow(x,y)) -> pow(|x|,y*0.5)
2308//
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002309
2310//===----------------------------------------------------------------------===//
2311// Fortified Library Call Optimizations
2312//===----------------------------------------------------------------------===//
2313
2314bool FortifiedLibCallSimplifier::isFortifiedCallFoldable(CallInst *CI,
2315 unsigned ObjSizeOp,
2316 unsigned SizeOp,
2317 bool isString) {
2318 if (CI->getArgOperand(ObjSizeOp) == CI->getArgOperand(SizeOp))
2319 return true;
2320 if (ConstantInt *ObjSizeCI =
2321 dyn_cast<ConstantInt>(CI->getArgOperand(ObjSizeOp))) {
Craig Topper79ab6432017-07-06 18:39:47 +00002322 if (ObjSizeCI->isMinusOne())
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002323 return true;
2324 // If the object size wasn't -1 (unknown), bail out if we were asked to.
2325 if (OnlyLowerUnknownSize)
2326 return false;
2327 if (isString) {
2328 uint64_t Len = GetStringLength(CI->getArgOperand(SizeOp));
2329 // If the length is 0 we don't know how long it is and so we can't
2330 // remove the check.
2331 if (Len == 0)
2332 return false;
2333 return ObjSizeCI->getZExtValue() >= Len;
2334 }
2335 if (ConstantInt *SizeCI = dyn_cast<ConstantInt>(CI->getArgOperand(SizeOp)))
2336 return ObjSizeCI->getZExtValue() >= SizeCI->getZExtValue();
2337 }
2338 return false;
2339}
2340
Sanjay Pateld707db92015-12-31 16:10:49 +00002341Value *FortifiedLibCallSimplifier::optimizeMemCpyChk(CallInst *CI,
2342 IRBuilder<> &B) {
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002343 if (isFortifiedCallFoldable(CI, 3, 2, false)) {
2344 B.CreateMemCpy(CI->getArgOperand(0), CI->getArgOperand(1),
Pete Cooper67cf9a72015-11-19 05:56:52 +00002345 CI->getArgOperand(2), 1);
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002346 return CI->getArgOperand(0);
2347 }
2348 return nullptr;
2349}
2350
Sanjay Pateld707db92015-12-31 16:10:49 +00002351Value *FortifiedLibCallSimplifier::optimizeMemMoveChk(CallInst *CI,
2352 IRBuilder<> &B) {
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002353 if (isFortifiedCallFoldable(CI, 3, 2, false)) {
2354 B.CreateMemMove(CI->getArgOperand(0), CI->getArgOperand(1),
Pete Cooper67cf9a72015-11-19 05:56:52 +00002355 CI->getArgOperand(2), 1);
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002356 return CI->getArgOperand(0);
2357 }
2358 return nullptr;
2359}
2360
Sanjay Pateld707db92015-12-31 16:10:49 +00002361Value *FortifiedLibCallSimplifier::optimizeMemSetChk(CallInst *CI,
2362 IRBuilder<> &B) {
Sanjay Patel980b2802016-01-26 16:17:24 +00002363 // TODO: Try foldMallocMemset() here.
2364
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002365 if (isFortifiedCallFoldable(CI, 3, 2, false)) {
2366 Value *Val = B.CreateIntCast(CI->getArgOperand(1), B.getInt8Ty(), false);
2367 B.CreateMemSet(CI->getArgOperand(0), Val, CI->getArgOperand(2), 1);
2368 return CI->getArgOperand(0);
2369 }
2370 return nullptr;
2371}
2372
Ahmed Bougacha1ac93562015-01-27 21:52:16 +00002373Value *FortifiedLibCallSimplifier::optimizeStrpCpyChk(CallInst *CI,
2374 IRBuilder<> &B,
David L. Jonesd21529f2017-01-23 23:16:46 +00002375 LibFunc Func) {
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002376 Function *Callee = CI->getCalledFunction();
2377 StringRef Name = Callee->getName();
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002378 const DataLayout &DL = CI->getModule()->getDataLayout();
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002379 Value *Dst = CI->getArgOperand(0), *Src = CI->getArgOperand(1),
2380 *ObjSize = CI->getArgOperand(2);
2381
2382 // __stpcpy_chk(x,x,...) -> x+strlen(x)
David L. Jonesd21529f2017-01-23 23:16:46 +00002383 if (Func == LibFunc_stpcpy_chk && !OnlyLowerUnknownSize && Dst == Src) {
Sanjay Pateld3112a52016-01-19 19:46:10 +00002384 Value *StrLen = emitStrLen(Src, B, DL, TLI);
David Blaikieaa41cd52015-04-03 21:33:42 +00002385 return StrLen ? B.CreateInBoundsGEP(B.getInt8Ty(), Dst, StrLen) : nullptr;
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002386 }
2387
2388 // If a) we don't have any length information, or b) we know this will
2389 // fit then just lower to a plain st[rp]cpy. Otherwise we'll keep our
2390 // st[rp]cpy_chk call which may fail at runtime if the size is too long.
2391 // TODO: It might be nice to get a maximum length out of the possible
2392 // string lengths for varying.
David Blaikie65fab6d2015-04-03 21:32:06 +00002393 if (isFortifiedCallFoldable(CI, 2, 1, true))
Sanjay Pateld3112a52016-01-19 19:46:10 +00002394 return emitStrCpy(Dst, Src, B, TLI, Name.substr(2, 6));
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002395
David Blaikie65fab6d2015-04-03 21:32:06 +00002396 if (OnlyLowerUnknownSize)
2397 return nullptr;
2398
2399 // Maybe we can stil fold __st[rp]cpy_chk to __memcpy_chk.
2400 uint64_t Len = GetStringLength(Src);
2401 if (Len == 0)
2402 return nullptr;
2403
2404 Type *SizeTTy = DL.getIntPtrType(CI->getContext());
2405 Value *LenV = ConstantInt::get(SizeTTy, Len);
Sanjay Pateld3112a52016-01-19 19:46:10 +00002406 Value *Ret = emitMemCpyChk(Dst, Src, LenV, ObjSize, B, DL, TLI);
David Blaikie65fab6d2015-04-03 21:32:06 +00002407 // If the function was an __stpcpy_chk, and we were able to fold it into
2408 // a __memcpy_chk, we still need to return the correct end pointer.
David L. Jonesd21529f2017-01-23 23:16:46 +00002409 if (Ret && Func == LibFunc_stpcpy_chk)
David Blaikie65fab6d2015-04-03 21:32:06 +00002410 return B.CreateGEP(B.getInt8Ty(), Dst, ConstantInt::get(SizeTTy, Len - 1));
2411 return Ret;
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002412}
2413
Ahmed Bougacha1ac93562015-01-27 21:52:16 +00002414Value *FortifiedLibCallSimplifier::optimizeStrpNCpyChk(CallInst *CI,
2415 IRBuilder<> &B,
David L. Jonesd21529f2017-01-23 23:16:46 +00002416 LibFunc Func) {
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002417 Function *Callee = CI->getCalledFunction();
2418 StringRef Name = Callee->getName();
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002419 if (isFortifiedCallFoldable(CI, 3, 2, false)) {
Sanjay Pateld3112a52016-01-19 19:46:10 +00002420 Value *Ret = emitStrNCpy(CI->getArgOperand(0), CI->getArgOperand(1),
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002421 CI->getArgOperand(2), B, TLI, Name.substr(2, 7));
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002422 return Ret;
2423 }
2424 return nullptr;
2425}
2426
2427Value *FortifiedLibCallSimplifier::optimizeCall(CallInst *CI) {
Ahmed Bougacha408d0102015-04-01 00:45:09 +00002428 // FIXME: We shouldn't be changing "nobuiltin" or TLI unavailable calls here.
2429 // Some clang users checked for _chk libcall availability using:
2430 // __has_builtin(__builtin___memcpy_chk)
2431 // When compiling with -fno-builtin, this is always true.
2432 // When passing -ffreestanding/-mkernel, which both imply -fno-builtin, we
2433 // end up with fortified libcalls, which isn't acceptable in a freestanding
2434 // environment which only provides their non-fortified counterparts.
2435 //
2436 // Until we change clang and/or teach external users to check for availability
2437 // differently, disregard the "nobuiltin" attribute and TLI::has.
2438 //
2439 // PR23093.
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002440
David L. Jonesd21529f2017-01-23 23:16:46 +00002441 LibFunc Func;
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002442 Function *Callee = CI->getCalledFunction();
David Majnemerb70e23c2016-01-06 05:01:34 +00002443
2444 SmallVector<OperandBundleDef, 2> OpBundles;
2445 CI->getOperandBundlesAsDefs(OpBundles);
2446 IRBuilder<> Builder(CI, /*FPMathTag=*/nullptr, OpBundles);
Sam Parker214f7bf2016-09-13 12:10:14 +00002447 bool isCallingConvC = isCallingConvCCompatible(CI);
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002448
Ahmed Bougachad765a822016-04-27 19:04:35 +00002449 // First, check that this is a known library functions and that the prototype
2450 // is correct.
2451 if (!TLI->getLibFunc(*Callee, Func))
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002452 return nullptr;
2453
2454 // We never change the calling convention.
2455 if (!ignoreCallingConv(Func) && !isCallingConvC)
2456 return nullptr;
2457
2458 switch (Func) {
David L. Jonesd21529f2017-01-23 23:16:46 +00002459 case LibFunc_memcpy_chk:
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002460 return optimizeMemCpyChk(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002461 case LibFunc_memmove_chk:
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002462 return optimizeMemMoveChk(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002463 case LibFunc_memset_chk:
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002464 return optimizeMemSetChk(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002465 case LibFunc_stpcpy_chk:
2466 case LibFunc_strcpy_chk:
Ahmed Bougacha1ac93562015-01-27 21:52:16 +00002467 return optimizeStrpCpyChk(CI, Builder, Func);
David L. Jonesd21529f2017-01-23 23:16:46 +00002468 case LibFunc_stpncpy_chk:
2469 case LibFunc_strncpy_chk:
Ahmed Bougacha1ac93562015-01-27 21:52:16 +00002470 return optimizeStrpNCpyChk(CI, Builder, Func);
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002471 default:
2472 break;
2473 }
2474 return nullptr;
2475}
2476
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002477FortifiedLibCallSimplifier::FortifiedLibCallSimplifier(
2478 const TargetLibraryInfo *TLI, bool OnlyLowerUnknownSize)
2479 : TLI(TLI), OnlyLowerUnknownSize(OnlyLowerUnknownSize) {}