blob: cd2d7f91920d7a8e5a47eb855d244b86bafaff86 [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"
Weiming Zhao45d4cb92015-11-24 18:57:06 +000021#include "llvm/Analysis/TargetLibraryInfo.h"
Meador Ingedf796f82012-10-13 16:45:24 +000022#include "llvm/Analysis/ValueTracking.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000023#include "llvm/IR/DataLayout.h"
Diego Novillo7f8af8b2014-05-22 14:19:46 +000024#include "llvm/IR/DiagnosticInfo.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000025#include "llvm/IR/Function.h"
26#include "llvm/IR/IRBuilder.h"
Meador Inge20255ef2013-03-12 00:08:29 +000027#include "llvm/IR/IntrinsicInst.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000028#include "llvm/IR/Intrinsics.h"
29#include "llvm/IR/LLVMContext.h"
30#include "llvm/IR/Module.h"
Sanjay Patelc699a612014-10-16 18:48:17 +000031#include "llvm/IR/PatternMatch.h"
Hal Finkel66cd3f12013-11-17 02:06:35 +000032#include "llvm/Support/CommandLine.h"
Meador Ingedf796f82012-10-13 16:45:24 +000033#include "llvm/Transforms/Utils/BuildLibCalls.h"
Chad Rosierdc655322015-08-28 18:30:18 +000034#include "llvm/Transforms/Utils/Local.h"
Meador Ingedf796f82012-10-13 16:45:24 +000035
36using namespace llvm;
Sanjay Patelc699a612014-10-16 18:48:17 +000037using namespace PatternMatch;
Meador Ingedf796f82012-10-13 16:45:24 +000038
Hal Finkel66cd3f12013-11-17 02:06:35 +000039static cl::opt<bool>
Chris Bienemanad070d02014-09-17 20:55:46 +000040 ColdErrorCalls("error-reporting-is-cold", cl::init(true), cl::Hidden,
41 cl::desc("Treat error-reporting calls as cold"));
Meador Ingedf796f82012-10-13 16:45:24 +000042
Sanjay Patela92fa442014-10-22 15:29:23 +000043static cl::opt<bool>
44 EnableUnsafeFPShrink("enable-double-float-shrink", cl::Hidden,
45 cl::init(false),
46 cl::desc("Enable unsafe double to float "
47 "shrinking for math lib calls"));
48
49
Meador Ingedf796f82012-10-13 16:45:24 +000050//===----------------------------------------------------------------------===//
Meador Inged589ac62012-10-31 03:33:06 +000051// Helper Functions
52//===----------------------------------------------------------------------===//
53
David L. Jonesd21529f2017-01-23 23:16:46 +000054static bool ignoreCallingConv(LibFunc Func) {
55 return Func == LibFunc_abs || Func == LibFunc_labs ||
56 Func == LibFunc_llabs || Func == LibFunc_strlen;
Chris Bienemanad070d02014-09-17 20:55:46 +000057}
58
Sam Parker214f7bf2016-09-13 12:10:14 +000059static bool isCallingConvCCompatible(CallInst *CI) {
60 switch(CI->getCallingConv()) {
61 default:
62 return false;
63 case llvm::CallingConv::C:
64 return true;
65 case llvm::CallingConv::ARM_APCS:
66 case llvm::CallingConv::ARM_AAPCS:
67 case llvm::CallingConv::ARM_AAPCS_VFP: {
68
69 // The iOS ABI diverges from the standard in some cases, so for now don't
70 // try to simplify those calls.
71 if (Triple(CI->getModule()->getTargetTriple()).isiOS())
72 return false;
73
74 auto *FuncTy = CI->getFunctionType();
75
76 if (!FuncTy->getReturnType()->isPointerTy() &&
77 !FuncTy->getReturnType()->isIntegerTy() &&
78 !FuncTy->getReturnType()->isVoidTy())
79 return false;
80
81 for (auto Param : FuncTy->params()) {
82 if (!Param->isPointerTy() && !Param->isIntegerTy())
83 return false;
84 }
85 return true;
86 }
87 }
88 return false;
89}
90
Sanjay Pateld707db92015-12-31 16:10:49 +000091/// Return true if it only matters that the value is equal or not-equal to zero.
Meador Inged589ac62012-10-31 03:33:06 +000092static bool isOnlyUsedInZeroEqualityComparison(Value *V) {
Chandler Carruthcdf47882014-03-09 03:16:01 +000093 for (User *U : V->users()) {
94 if (ICmpInst *IC = dyn_cast<ICmpInst>(U))
Meador Inged589ac62012-10-31 03:33:06 +000095 if (IC->isEquality())
96 if (Constant *C = dyn_cast<Constant>(IC->getOperand(1)))
97 if (C->isNullValue())
98 continue;
99 // Unknown instruction.
100 return false;
101 }
102 return true;
103}
104
Sanjay Pateld707db92015-12-31 16:10:49 +0000105/// Return true if it is only used in equality comparisons with With.
Meador Inge56edbc92012-11-11 03:51:48 +0000106static bool isOnlyUsedInEqualityComparison(Value *V, Value *With) {
Chandler Carruthcdf47882014-03-09 03:16:01 +0000107 for (User *U : V->users()) {
108 if (ICmpInst *IC = dyn_cast<ICmpInst>(U))
Meador Inge56edbc92012-11-11 03:51:48 +0000109 if (IC->isEquality() && IC->getOperand(1) == With)
110 continue;
111 // Unknown instruction.
112 return false;
113 }
114 return true;
115}
116
Meador Inge08ca1152012-11-26 20:37:20 +0000117static bool callHasFloatingPointArgument(const CallInst *CI) {
David Majnemer0a16c222016-08-11 21:15:00 +0000118 return any_of(CI->operands(), [](const Use &OI) {
Davide Italianoda3beeb2015-11-28 22:27:48 +0000119 return OI->getType()->isFloatingPointTy();
120 });
Meador Inge08ca1152012-11-26 20:37:20 +0000121}
122
Benjamin Kramer2702caa2013-08-31 18:19:35 +0000123/// \brief Check whether the overloaded unary floating point function
Sanjay Patele24c60e2015-08-12 20:36:18 +0000124/// corresponding to \a Ty is available.
Benjamin Kramer2702caa2013-08-31 18:19:35 +0000125static bool hasUnaryFloatFn(const TargetLibraryInfo *TLI, Type *Ty,
David L. Jonesd21529f2017-01-23 23:16:46 +0000126 LibFunc DoubleFn, LibFunc FloatFn,
127 LibFunc LongDoubleFn) {
Benjamin Kramer2702caa2013-08-31 18:19:35 +0000128 switch (Ty->getTypeID()) {
129 case Type::FloatTyID:
130 return TLI->has(FloatFn);
131 case Type::DoubleTyID:
132 return TLI->has(DoubleFn);
133 default:
134 return TLI->has(LongDoubleFn);
135 }
136}
137
Meador Inged589ac62012-10-31 03:33:06 +0000138//===----------------------------------------------------------------------===//
Meador Inge7fb2f732012-10-13 16:45:32 +0000139// String and Memory Library Call Optimizations
140//===----------------------------------------------------------------------===//
141
Chris Bienemanad070d02014-09-17 20:55:46 +0000142Value *LibCallSimplifier::optimizeStrCat(CallInst *CI, IRBuilder<> &B) {
Chris Bienemanad070d02014-09-17 20:55:46 +0000143 // Extract some information from the instruction
144 Value *Dst = CI->getArgOperand(0);
145 Value *Src = CI->getArgOperand(1);
146
147 // See if we can get the length of the input string.
148 uint64_t Len = GetStringLength(Src);
149 if (Len == 0)
150 return nullptr;
151 --Len; // Unbias length.
152
153 // Handle the simple, do-nothing case: strcat(x, "") -> x
154 if (Len == 0)
155 return Dst;
156
Chris Bienemanad070d02014-09-17 20:55:46 +0000157 return emitStrLenMemCpy(Src, Dst, Len, B);
158}
159
160Value *LibCallSimplifier::emitStrLenMemCpy(Value *Src, Value *Dst, uint64_t Len,
161 IRBuilder<> &B) {
162 // We need to find the end of the destination string. That's where the
163 // memory is to be moved to. We just generate a call to strlen.
Sanjay Pateld3112a52016-01-19 19:46:10 +0000164 Value *DstLen = emitStrLen(Dst, B, DL, TLI);
Chris Bienemanad070d02014-09-17 20:55:46 +0000165 if (!DstLen)
166 return nullptr;
167
168 // Now that we have the destination's length, we must index into the
169 // destination's pointer to get the actual memcpy destination (end of
170 // the string .. we're concatenating).
David Blaikie3909da72015-03-30 20:42:56 +0000171 Value *CpyDst = B.CreateGEP(B.getInt8Ty(), Dst, DstLen, "endptr");
Chris Bienemanad070d02014-09-17 20:55:46 +0000172
173 // We have enough information to now generate the memcpy call to do the
174 // concatenation for us. Make a memcpy to copy the nul byte with align = 1.
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000175 B.CreateMemCpy(CpyDst, Src,
176 ConstantInt::get(DL.getIntPtrType(Src->getContext()), Len + 1),
Pete Cooper67cf9a72015-11-19 05:56:52 +0000177 1);
Chris Bienemanad070d02014-09-17 20:55:46 +0000178 return Dst;
179}
180
181Value *LibCallSimplifier::optimizeStrNCat(CallInst *CI, IRBuilder<> &B) {
Sanjay Pateld707db92015-12-31 16:10:49 +0000182 // Extract some information from the instruction.
Chris Bienemanad070d02014-09-17 20:55:46 +0000183 Value *Dst = CI->getArgOperand(0);
184 Value *Src = CI->getArgOperand(1);
185 uint64_t Len;
186
Sanjay Pateld707db92015-12-31 16:10:49 +0000187 // We don't do anything if length is not constant.
Chris Bienemanad070d02014-09-17 20:55:46 +0000188 if (ConstantInt *LengthArg = dyn_cast<ConstantInt>(CI->getArgOperand(2)))
189 Len = LengthArg->getZExtValue();
190 else
191 return nullptr;
192
193 // See if we can get the length of the input string.
194 uint64_t SrcLen = GetStringLength(Src);
195 if (SrcLen == 0)
196 return nullptr;
197 --SrcLen; // Unbias length.
198
199 // Handle the simple, do-nothing cases:
200 // strncat(x, "", c) -> x
201 // strncat(x, c, 0) -> x
202 if (SrcLen == 0 || Len == 0)
203 return Dst;
204
Sanjay Pateld707db92015-12-31 16:10:49 +0000205 // We don't optimize this case.
Chris Bienemanad070d02014-09-17 20:55:46 +0000206 if (Len < SrcLen)
207 return nullptr;
208
209 // strncat(x, s, c) -> strcat(x, s)
Sanjay Pateld707db92015-12-31 16:10:49 +0000210 // s is constant so the strcat can be optimized further.
Chris Bienemanad070d02014-09-17 20:55:46 +0000211 return emitStrLenMemCpy(Src, Dst, SrcLen, B);
212}
213
214Value *LibCallSimplifier::optimizeStrChr(CallInst *CI, IRBuilder<> &B) {
215 Function *Callee = CI->getCalledFunction();
Chris Bienemanad070d02014-09-17 20:55:46 +0000216 FunctionType *FT = Callee->getFunctionType();
Chris Bienemanad070d02014-09-17 20:55:46 +0000217 Value *SrcStr = CI->getArgOperand(0);
218
219 // If the second operand is non-constant, see if we can compute the length
220 // of the input string and turn this into memchr.
221 ConstantInt *CharC = dyn_cast<ConstantInt>(CI->getArgOperand(1));
222 if (!CharC) {
Chris Bienemanad070d02014-09-17 20:55:46 +0000223 uint64_t Len = GetStringLength(SrcStr);
224 if (Len == 0 || !FT->getParamType(1)->isIntegerTy(32)) // memchr needs i32.
225 return nullptr;
Meador Inge7fb2f732012-10-13 16:45:32 +0000226
Sanjay Pateld3112a52016-01-19 19:46:10 +0000227 return emitMemChr(SrcStr, CI->getArgOperand(1), // include nul.
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000228 ConstantInt::get(DL.getIntPtrType(CI->getContext()), Len),
229 B, DL, TLI);
Meador Inge7fb2f732012-10-13 16:45:32 +0000230 }
231
Chris Bienemanad070d02014-09-17 20:55:46 +0000232 // Otherwise, the character is a constant, see if the first argument is
233 // a string literal. If so, we can constant fold.
234 StringRef Str;
235 if (!getConstantStringInfo(SrcStr, Str)) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000236 if (CharC->isZero()) // strchr(p, 0) -> p + strlen(p)
Sanjay Pateld3112a52016-01-19 19:46:10 +0000237 return B.CreateGEP(B.getInt8Ty(), SrcStr, emitStrLen(SrcStr, B, DL, TLI),
Sanjay Pateld707db92015-12-31 16:10:49 +0000238 "strchr");
Chris Bienemanad070d02014-09-17 20:55:46 +0000239 return nullptr;
240 }
241
242 // Compute the offset, make sure to handle the case when we're searching for
243 // zero (a weird way to spell strlen).
244 size_t I = (0xFF & CharC->getSExtValue()) == 0
245 ? Str.size()
246 : Str.find(CharC->getSExtValue());
247 if (I == StringRef::npos) // Didn't find the char. strchr returns null.
248 return Constant::getNullValue(CI->getType());
249
250 // strchr(s+n,c) -> gep(s+n+i,c)
David Blaikie3909da72015-03-30 20:42:56 +0000251 return B.CreateGEP(B.getInt8Ty(), SrcStr, B.getInt64(I), "strchr");
Chris Bienemanad070d02014-09-17 20:55:46 +0000252}
253
254Value *LibCallSimplifier::optimizeStrRChr(CallInst *CI, IRBuilder<> &B) {
Chris Bienemanad070d02014-09-17 20:55:46 +0000255 Value *SrcStr = CI->getArgOperand(0);
256 ConstantInt *CharC = dyn_cast<ConstantInt>(CI->getArgOperand(1));
257
258 // Cannot fold anything if we're not looking for a constant.
259 if (!CharC)
260 return nullptr;
261
262 StringRef Str;
263 if (!getConstantStringInfo(SrcStr, Str)) {
264 // strrchr(s, 0) -> strchr(s, 0)
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000265 if (CharC->isZero())
Sanjay Pateld3112a52016-01-19 19:46:10 +0000266 return emitStrChr(SrcStr, '\0', B, TLI);
Chris Bienemanad070d02014-09-17 20:55:46 +0000267 return nullptr;
268 }
269
270 // Compute the offset.
271 size_t I = (0xFF & CharC->getSExtValue()) == 0
272 ? Str.size()
273 : Str.rfind(CharC->getSExtValue());
274 if (I == StringRef::npos) // Didn't find the char. Return null.
275 return Constant::getNullValue(CI->getType());
276
277 // strrchr(s+n,c) -> gep(s+n+i,c)
David Blaikie3909da72015-03-30 20:42:56 +0000278 return B.CreateGEP(B.getInt8Ty(), SrcStr, B.getInt64(I), "strrchr");
Chris Bienemanad070d02014-09-17 20:55:46 +0000279}
280
281Value *LibCallSimplifier::optimizeStrCmp(CallInst *CI, IRBuilder<> &B) {
Chris Bienemanad070d02014-09-17 20:55:46 +0000282 Value *Str1P = CI->getArgOperand(0), *Str2P = CI->getArgOperand(1);
283 if (Str1P == Str2P) // strcmp(x,x) -> 0
284 return ConstantInt::get(CI->getType(), 0);
285
286 StringRef Str1, Str2;
287 bool HasStr1 = getConstantStringInfo(Str1P, Str1);
288 bool HasStr2 = getConstantStringInfo(Str2P, Str2);
289
290 // strcmp(x, y) -> cnst (if both x and y are constant strings)
291 if (HasStr1 && HasStr2)
292 return ConstantInt::get(CI->getType(), Str1.compare(Str2));
293
294 if (HasStr1 && Str1.empty()) // strcmp("", x) -> -*x
295 return B.CreateNeg(
296 B.CreateZExt(B.CreateLoad(Str2P, "strcmpload"), CI->getType()));
297
298 if (HasStr2 && Str2.empty()) // strcmp(x,"") -> *x
299 return B.CreateZExt(B.CreateLoad(Str1P, "strcmpload"), CI->getType());
300
301 // strcmp(P, "x") -> memcmp(P, "x", 2)
302 uint64_t Len1 = GetStringLength(Str1P);
303 uint64_t Len2 = GetStringLength(Str2P);
304 if (Len1 && Len2) {
Sanjay Pateld3112a52016-01-19 19:46:10 +0000305 return emitMemCmp(Str1P, Str2P,
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000306 ConstantInt::get(DL.getIntPtrType(CI->getContext()),
Chris Bienemanad070d02014-09-17 20:55:46 +0000307 std::min(Len1, Len2)),
308 B, DL, TLI);
309 }
Meador Inge7fb2f732012-10-13 16:45:32 +0000310
Chris Bienemanad070d02014-09-17 20:55:46 +0000311 return nullptr;
312}
313
314Value *LibCallSimplifier::optimizeStrNCmp(CallInst *CI, IRBuilder<> &B) {
Chris Bienemanad070d02014-09-17 20:55:46 +0000315 Value *Str1P = CI->getArgOperand(0), *Str2P = CI->getArgOperand(1);
316 if (Str1P == Str2P) // strncmp(x,x,n) -> 0
317 return ConstantInt::get(CI->getType(), 0);
318
319 // Get the length argument if it is constant.
320 uint64_t Length;
321 if (ConstantInt *LengthArg = dyn_cast<ConstantInt>(CI->getArgOperand(2)))
322 Length = LengthArg->getZExtValue();
323 else
324 return nullptr;
325
326 if (Length == 0) // strncmp(x,y,0) -> 0
327 return ConstantInt::get(CI->getType(), 0);
328
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000329 if (Length == 1) // strncmp(x,y,1) -> memcmp(x,y,1)
Sanjay Pateld3112a52016-01-19 19:46:10 +0000330 return emitMemCmp(Str1P, Str2P, CI->getArgOperand(2), B, DL, TLI);
Chris Bienemanad070d02014-09-17 20:55:46 +0000331
332 StringRef Str1, Str2;
333 bool HasStr1 = getConstantStringInfo(Str1P, Str1);
334 bool HasStr2 = getConstantStringInfo(Str2P, Str2);
335
336 // strncmp(x, y) -> cnst (if both x and y are constant strings)
337 if (HasStr1 && HasStr2) {
338 StringRef SubStr1 = Str1.substr(0, Length);
339 StringRef SubStr2 = Str2.substr(0, Length);
340 return ConstantInt::get(CI->getType(), SubStr1.compare(SubStr2));
341 }
342
343 if (HasStr1 && Str1.empty()) // strncmp("", x, n) -> -*x
344 return B.CreateNeg(
345 B.CreateZExt(B.CreateLoad(Str2P, "strcmpload"), CI->getType()));
346
347 if (HasStr2 && Str2.empty()) // strncmp(x, "", n) -> *x
348 return B.CreateZExt(B.CreateLoad(Str1P, "strcmpload"), CI->getType());
349
350 return nullptr;
351}
352
353Value *LibCallSimplifier::optimizeStrCpy(CallInst *CI, IRBuilder<> &B) {
Chris Bienemanad070d02014-09-17 20:55:46 +0000354 Value *Dst = CI->getArgOperand(0), *Src = CI->getArgOperand(1);
355 if (Dst == Src) // strcpy(x,x) -> x
356 return Src;
357
Chris Bienemanad070d02014-09-17 20:55:46 +0000358 // See if we can get the length of the input string.
359 uint64_t Len = GetStringLength(Src);
360 if (Len == 0)
361 return nullptr;
362
363 // We have enough information to now generate the memcpy call to do the
364 // copy for us. Make a memcpy to copy the nul byte with align = 1.
365 B.CreateMemCpy(Dst, Src,
Pete Cooper67cf9a72015-11-19 05:56:52 +0000366 ConstantInt::get(DL.getIntPtrType(CI->getContext()), Len), 1);
Chris Bienemanad070d02014-09-17 20:55:46 +0000367 return Dst;
368}
369
370Value *LibCallSimplifier::optimizeStpCpy(CallInst *CI, IRBuilder<> &B) {
371 Function *Callee = CI->getCalledFunction();
Chris Bienemanad070d02014-09-17 20:55:46 +0000372 Value *Dst = CI->getArgOperand(0), *Src = CI->getArgOperand(1);
373 if (Dst == Src) { // stpcpy(x,x) -> x+strlen(x)
Sanjay Pateld3112a52016-01-19 19:46:10 +0000374 Value *StrLen = emitStrLen(Src, B, DL, TLI);
David Blaikieaa41cd52015-04-03 21:33:42 +0000375 return StrLen ? B.CreateInBoundsGEP(B.getInt8Ty(), Dst, StrLen) : nullptr;
Chris Bienemanad070d02014-09-17 20:55:46 +0000376 }
377
378 // See if we can get the length of the input string.
379 uint64_t Len = GetStringLength(Src);
380 if (Len == 0)
381 return nullptr;
382
Davide Italianob7487e62015-11-02 23:07:14 +0000383 Type *PT = Callee->getFunctionType()->getParamType(0);
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000384 Value *LenV = ConstantInt::get(DL.getIntPtrType(PT), Len);
Sanjay Pateld707db92015-12-31 16:10:49 +0000385 Value *DstEnd = B.CreateGEP(B.getInt8Ty(), Dst,
386 ConstantInt::get(DL.getIntPtrType(PT), Len - 1));
Chris Bienemanad070d02014-09-17 20:55:46 +0000387
388 // We have enough information to now generate the memcpy call to do the
389 // copy for us. Make a memcpy to copy the nul byte with align = 1.
Pete Cooper67cf9a72015-11-19 05:56:52 +0000390 B.CreateMemCpy(Dst, Src, LenV, 1);
Chris Bienemanad070d02014-09-17 20:55:46 +0000391 return DstEnd;
392}
393
394Value *LibCallSimplifier::optimizeStrNCpy(CallInst *CI, IRBuilder<> &B) {
395 Function *Callee = CI->getCalledFunction();
Chris Bienemanad070d02014-09-17 20:55:46 +0000396 Value *Dst = CI->getArgOperand(0);
397 Value *Src = CI->getArgOperand(1);
398 Value *LenOp = CI->getArgOperand(2);
399
400 // See if we can get the length of the input string.
401 uint64_t SrcLen = GetStringLength(Src);
402 if (SrcLen == 0)
403 return nullptr;
404 --SrcLen;
405
406 if (SrcLen == 0) {
407 // strncpy(x, "", y) -> memset(x, '\0', y, 1)
408 B.CreateMemSet(Dst, B.getInt8('\0'), LenOp, 1);
Meador Inge7fb2f732012-10-13 16:45:32 +0000409 return Dst;
410 }
Meador Inge7fb2f732012-10-13 16:45:32 +0000411
Chris Bienemanad070d02014-09-17 20:55:46 +0000412 uint64_t Len;
413 if (ConstantInt *LengthArg = dyn_cast<ConstantInt>(LenOp))
414 Len = LengthArg->getZExtValue();
415 else
416 return nullptr;
Meador Inge7fb2f732012-10-13 16:45:32 +0000417
Chris Bienemanad070d02014-09-17 20:55:46 +0000418 if (Len == 0)
419 return Dst; // strncpy(x, y, 0) -> x
Meador Inge7fb2f732012-10-13 16:45:32 +0000420
Chris Bienemanad070d02014-09-17 20:55:46 +0000421 // Let strncpy handle the zero padding
422 if (Len > SrcLen + 1)
423 return nullptr;
Meador Inge7fb2f732012-10-13 16:45:32 +0000424
Davide Italianob7487e62015-11-02 23:07:14 +0000425 Type *PT = Callee->getFunctionType()->getParamType(0);
Chris Bienemanad070d02014-09-17 20:55:46 +0000426 // strncpy(x, s, c) -> memcpy(x, s, c, 1) [s and c are constant]
Pete Cooper67cf9a72015-11-19 05:56:52 +0000427 B.CreateMemCpy(Dst, Src, ConstantInt::get(DL.getIntPtrType(PT), Len), 1);
Meador Inge7fb2f732012-10-13 16:45:32 +0000428
Chris Bienemanad070d02014-09-17 20:55:46 +0000429 return Dst;
430}
Meador Inge7fb2f732012-10-13 16:45:32 +0000431
Chris Bienemanad070d02014-09-17 20:55:46 +0000432Value *LibCallSimplifier::optimizeStrLen(CallInst *CI, IRBuilder<> &B) {
Chris Bienemanad070d02014-09-17 20:55:46 +0000433 Value *Src = CI->getArgOperand(0);
434
435 // Constant folding: strlen("xyz") -> 3
436 if (uint64_t Len = GetStringLength(Src))
437 return ConstantInt::get(CI->getType(), Len - 1);
438
David L Kreitzer752c1442016-04-13 14:31:06 +0000439 // If s is a constant pointer pointing to a string literal, we can fold
440 // strlen(s + x) to strlen(s) - x, when x is known to be in the range
441 // [0, strlen(s)] or the string has a single null terminator '\0' at the end.
442 // We only try to simplify strlen when the pointer s points to an array
443 // of i8. Otherwise, we would need to scale the offset x before doing the
444 // subtraction. This will make the optimization more complex, and it's not
445 // very useful because calling strlen for a pointer of other types is
446 // very uncommon.
447 if (GEPOperator *GEP = dyn_cast<GEPOperator>(Src)) {
448 if (!isGEPBasedOnPointerToString(GEP))
449 return nullptr;
450
451 StringRef Str;
452 if (getConstantStringInfo(GEP->getOperand(0), Str, 0, false)) {
453 size_t NullTermIdx = Str.find('\0');
454
455 // If the string does not have '\0', leave it to strlen to compute
456 // its length.
457 if (NullTermIdx == StringRef::npos)
458 return nullptr;
459
460 Value *Offset = GEP->getOperand(2);
461 unsigned BitWidth = Offset->getType()->getIntegerBitWidth();
462 APInt KnownZero(BitWidth, 0);
463 APInt KnownOne(BitWidth, 0);
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000464 computeKnownBits(Offset, KnownZero, KnownOne, DL, 0, nullptr, CI,
465 nullptr);
David L Kreitzer752c1442016-04-13 14:31:06 +0000466 KnownZero.flipAllBits();
467 size_t ArrSize =
468 cast<ArrayType>(GEP->getSourceElementType())->getNumElements();
469
470 // KnownZero's bits are flipped, so zeros in KnownZero now represent
471 // bits known to be zeros in Offset, and ones in KnowZero represent
472 // bits unknown in Offset. Therefore, Offset is known to be in range
473 // [0, NullTermIdx] when the flipped KnownZero is non-negative and
474 // unsigned-less-than NullTermIdx.
475 //
476 // If Offset is not provably in the range [0, NullTermIdx], we can still
477 // optimize if we can prove that the program has undefined behavior when
478 // Offset is outside that range. That is the case when GEP->getOperand(0)
479 // is a pointer to an object whose memory extent is NullTermIdx+1.
480 if ((KnownZero.isNonNegative() && KnownZero.ule(NullTermIdx)) ||
481 (GEP->isInBounds() && isa<GlobalVariable>(GEP->getOperand(0)) &&
482 NullTermIdx == ArrSize - 1))
483 return B.CreateSub(ConstantInt::get(CI->getType(), NullTermIdx),
484 Offset);
485 }
486
487 return nullptr;
488 }
489
Chris Bienemanad070d02014-09-17 20:55:46 +0000490 // strlen(x?"foo":"bars") --> x ? 3 : 4
491 if (SelectInst *SI = dyn_cast<SelectInst>(Src)) {
492 uint64_t LenTrue = GetStringLength(SI->getTrueValue());
493 uint64_t LenFalse = GetStringLength(SI->getFalseValue());
494 if (LenTrue && LenFalse) {
495 Function *Caller = CI->getParent()->getParent();
496 emitOptimizationRemark(CI->getContext(), "simplify-libcalls", *Caller,
497 SI->getDebugLoc(),
498 "folded strlen(select) to select of constants");
499 return B.CreateSelect(SI->getCondition(),
500 ConstantInt::get(CI->getType(), LenTrue - 1),
501 ConstantInt::get(CI->getType(), LenFalse - 1));
502 }
Meador Inge7fb2f732012-10-13 16:45:32 +0000503 }
Meador Inge7fb2f732012-10-13 16:45:32 +0000504
Chris Bienemanad070d02014-09-17 20:55:46 +0000505 // strlen(x) != 0 --> *x != 0
506 // strlen(x) == 0 --> *x == 0
507 if (isOnlyUsedInZeroEqualityComparison(CI))
508 return B.CreateZExt(B.CreateLoad(Src, "strlenfirst"), CI->getType());
Meador Inge17418502012-10-13 16:45:37 +0000509
Chris Bienemanad070d02014-09-17 20:55:46 +0000510 return nullptr;
511}
Meador Inge17418502012-10-13 16:45:37 +0000512
Chris Bienemanad070d02014-09-17 20:55:46 +0000513Value *LibCallSimplifier::optimizeStrPBrk(CallInst *CI, IRBuilder<> &B) {
Chris Bienemanad070d02014-09-17 20:55:46 +0000514 StringRef S1, S2;
515 bool HasS1 = getConstantStringInfo(CI->getArgOperand(0), S1);
516 bool HasS2 = getConstantStringInfo(CI->getArgOperand(1), S2);
Meador Inge17418502012-10-13 16:45:37 +0000517
Reid Kleckner971c3ea2014-11-13 22:55:19 +0000518 // strpbrk(s, "") -> nullptr
519 // strpbrk("", s) -> nullptr
Chris Bienemanad070d02014-09-17 20:55:46 +0000520 if ((HasS1 && S1.empty()) || (HasS2 && S2.empty()))
521 return Constant::getNullValue(CI->getType());
Meador Inge17418502012-10-13 16:45:37 +0000522
Chris Bienemanad070d02014-09-17 20:55:46 +0000523 // Constant folding.
524 if (HasS1 && HasS2) {
525 size_t I = S1.find_first_of(S2);
526 if (I == StringRef::npos) // No match.
Meador Inge17418502012-10-13 16:45:37 +0000527 return Constant::getNullValue(CI->getType());
528
Sanjay Pateld707db92015-12-31 16:10:49 +0000529 return B.CreateGEP(B.getInt8Ty(), CI->getArgOperand(0), B.getInt64(I),
530 "strpbrk");
Meador Inge17418502012-10-13 16:45:37 +0000531 }
Meador Inge17418502012-10-13 16:45:37 +0000532
Chris Bienemanad070d02014-09-17 20:55:46 +0000533 // strpbrk(s, "a") -> strchr(s, 'a')
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000534 if (HasS2 && S2.size() == 1)
Sanjay Pateld3112a52016-01-19 19:46:10 +0000535 return emitStrChr(CI->getArgOperand(0), S2[0], B, TLI);
Chris Bienemanad070d02014-09-17 20:55:46 +0000536
537 return nullptr;
538}
539
540Value *LibCallSimplifier::optimizeStrTo(CallInst *CI, IRBuilder<> &B) {
Chris Bienemanad070d02014-09-17 20:55:46 +0000541 Value *EndPtr = CI->getArgOperand(1);
542 if (isa<ConstantPointerNull>(EndPtr)) {
543 // With a null EndPtr, this function won't capture the main argument.
544 // It would be readonly too, except that it still may write to errno.
545 CI->addAttribute(1, Attribute::NoCapture);
546 }
547
548 return nullptr;
549}
550
551Value *LibCallSimplifier::optimizeStrSpn(CallInst *CI, IRBuilder<> &B) {
Chris Bienemanad070d02014-09-17 20:55:46 +0000552 StringRef S1, S2;
553 bool HasS1 = getConstantStringInfo(CI->getArgOperand(0), S1);
554 bool HasS2 = getConstantStringInfo(CI->getArgOperand(1), S2);
555
556 // strspn(s, "") -> 0
557 // strspn("", s) -> 0
558 if ((HasS1 && S1.empty()) || (HasS2 && S2.empty()))
559 return Constant::getNullValue(CI->getType());
560
561 // Constant folding.
562 if (HasS1 && HasS2) {
563 size_t Pos = S1.find_first_not_of(S2);
564 if (Pos == StringRef::npos)
565 Pos = S1.size();
566 return ConstantInt::get(CI->getType(), Pos);
567 }
568
569 return nullptr;
570}
571
572Value *LibCallSimplifier::optimizeStrCSpn(CallInst *CI, IRBuilder<> &B) {
Chris Bienemanad070d02014-09-17 20:55:46 +0000573 StringRef S1, S2;
574 bool HasS1 = getConstantStringInfo(CI->getArgOperand(0), S1);
575 bool HasS2 = getConstantStringInfo(CI->getArgOperand(1), S2);
576
577 // strcspn("", s) -> 0
578 if (HasS1 && S1.empty())
579 return Constant::getNullValue(CI->getType());
580
581 // Constant folding.
582 if (HasS1 && HasS2) {
583 size_t Pos = S1.find_first_of(S2);
584 if (Pos == StringRef::npos)
585 Pos = S1.size();
586 return ConstantInt::get(CI->getType(), Pos);
587 }
588
589 // strcspn(s, "") -> strlen(s)
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000590 if (HasS2 && S2.empty())
Sanjay Pateld3112a52016-01-19 19:46:10 +0000591 return emitStrLen(CI->getArgOperand(0), B, DL, TLI);
Chris Bienemanad070d02014-09-17 20:55:46 +0000592
593 return nullptr;
594}
595
596Value *LibCallSimplifier::optimizeStrStr(CallInst *CI, IRBuilder<> &B) {
Chris Bienemanad070d02014-09-17 20:55:46 +0000597 // fold strstr(x, x) -> x.
598 if (CI->getArgOperand(0) == CI->getArgOperand(1))
599 return B.CreateBitCast(CI->getArgOperand(0), CI->getType());
600
601 // fold strstr(a, b) == a -> strncmp(a, b, strlen(b)) == 0
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000602 if (isOnlyUsedInEqualityComparison(CI, CI->getArgOperand(0))) {
Sanjay Pateld3112a52016-01-19 19:46:10 +0000603 Value *StrLen = emitStrLen(CI->getArgOperand(1), B, DL, TLI);
Chris Bienemanad070d02014-09-17 20:55:46 +0000604 if (!StrLen)
Craig Topperf40110f2014-04-25 05:29:35 +0000605 return nullptr;
Sanjay Pateld3112a52016-01-19 19:46:10 +0000606 Value *StrNCmp = emitStrNCmp(CI->getArgOperand(0), CI->getArgOperand(1),
Chris Bienemanad070d02014-09-17 20:55:46 +0000607 StrLen, B, DL, TLI);
608 if (!StrNCmp)
Craig Topperf40110f2014-04-25 05:29:35 +0000609 return nullptr;
Chris Bienemanad070d02014-09-17 20:55:46 +0000610 for (auto UI = CI->user_begin(), UE = CI->user_end(); UI != UE;) {
611 ICmpInst *Old = cast<ICmpInst>(*UI++);
612 Value *Cmp =
613 B.CreateICmp(Old->getPredicate(), StrNCmp,
614 ConstantInt::getNullValue(StrNCmp->getType()), "cmp");
615 replaceAllUsesWith(Old, Cmp);
Meador Inge17418502012-10-13 16:45:37 +0000616 }
Chris Bienemanad070d02014-09-17 20:55:46 +0000617 return CI;
618 }
Meador Inge17418502012-10-13 16:45:37 +0000619
Chris Bienemanad070d02014-09-17 20:55:46 +0000620 // See if either input string is a constant string.
621 StringRef SearchStr, ToFindStr;
622 bool HasStr1 = getConstantStringInfo(CI->getArgOperand(0), SearchStr);
623 bool HasStr2 = getConstantStringInfo(CI->getArgOperand(1), ToFindStr);
624
625 // fold strstr(x, "") -> x.
626 if (HasStr2 && ToFindStr.empty())
627 return B.CreateBitCast(CI->getArgOperand(0), CI->getType());
628
629 // If both strings are known, constant fold it.
630 if (HasStr1 && HasStr2) {
631 size_t Offset = SearchStr.find(ToFindStr);
632
633 if (Offset == StringRef::npos) // strstr("foo", "bar") -> null
Meador Inge17418502012-10-13 16:45:37 +0000634 return Constant::getNullValue(CI->getType());
635
Chris Bienemanad070d02014-09-17 20:55:46 +0000636 // strstr("abcd", "bc") -> gep((char*)"abcd", 1)
Sanjay Pateld3112a52016-01-19 19:46:10 +0000637 Value *Result = castToCStr(CI->getArgOperand(0), B);
Chris Bienemanad070d02014-09-17 20:55:46 +0000638 Result = B.CreateConstInBoundsGEP1_64(Result, Offset, "strstr");
639 return B.CreateBitCast(Result, CI->getType());
Meador Inge17418502012-10-13 16:45:37 +0000640 }
Meador Inge17418502012-10-13 16:45:37 +0000641
Chris Bienemanad070d02014-09-17 20:55:46 +0000642 // fold strstr(x, "y") -> strchr(x, 'y').
643 if (HasStr2 && ToFindStr.size() == 1) {
Sanjay Pateld3112a52016-01-19 19:46:10 +0000644 Value *StrChr = emitStrChr(CI->getArgOperand(0), ToFindStr[0], B, TLI);
Chris Bienemanad070d02014-09-17 20:55:46 +0000645 return StrChr ? B.CreateBitCast(StrChr, CI->getType()) : nullptr;
646 }
647 return nullptr;
648}
Meador Inge40b6fac2012-10-15 03:47:37 +0000649
Benjamin Kramer691363e2015-03-21 15:36:21 +0000650Value *LibCallSimplifier::optimizeMemChr(CallInst *CI, IRBuilder<> &B) {
Benjamin Kramer691363e2015-03-21 15:36:21 +0000651 Value *SrcStr = CI->getArgOperand(0);
652 ConstantInt *CharC = dyn_cast<ConstantInt>(CI->getArgOperand(1));
653 ConstantInt *LenC = dyn_cast<ConstantInt>(CI->getArgOperand(2));
654
655 // memchr(x, y, 0) -> null
656 if (LenC && LenC->isNullValue())
657 return Constant::getNullValue(CI->getType());
658
Benjamin Kramer7857d722015-03-21 21:09:33 +0000659 // From now on we need at least constant length and string.
Benjamin Kramer691363e2015-03-21 15:36:21 +0000660 StringRef Str;
Benjamin Kramer7857d722015-03-21 21:09:33 +0000661 if (!LenC || !getConstantStringInfo(SrcStr, Str, 0, /*TrimAtNul=*/false))
Benjamin Kramer691363e2015-03-21 15:36:21 +0000662 return nullptr;
663
664 // Truncate the string to LenC. If Str is smaller than LenC we will still only
665 // scan the string, as reading past the end of it is undefined and we can just
666 // return null if we don't find the char.
667 Str = Str.substr(0, LenC->getZExtValue());
668
Benjamin Kramer7857d722015-03-21 21:09:33 +0000669 // If the char is variable but the input str and length are not we can turn
670 // this memchr call into a simple bit field test. Of course this only works
671 // when the return value is only checked against null.
672 //
673 // It would be really nice to reuse switch lowering here but we can't change
674 // the CFG at this point.
675 //
676 // memchr("\r\n", C, 2) != nullptr -> (C & ((1 << '\r') | (1 << '\n'))) != 0
677 // after bounds check.
678 if (!CharC && !Str.empty() && isOnlyUsedInZeroEqualityComparison(CI)) {
Benjamin Kramerd6aa0ec2015-03-21 22:04:26 +0000679 unsigned char Max =
680 *std::max_element(reinterpret_cast<const unsigned char *>(Str.begin()),
681 reinterpret_cast<const unsigned char *>(Str.end()));
Benjamin Kramer7857d722015-03-21 21:09:33 +0000682
683 // Make sure the bit field we're about to create fits in a register on the
684 // target.
685 // FIXME: On a 64 bit architecture this prevents us from using the
686 // interesting range of alpha ascii chars. We could do better by emitting
687 // two bitfields or shifting the range by 64 if no lower chars are used.
688 if (!DL.fitsInLegalInteger(Max + 1))
689 return nullptr;
690
691 // For the bit field use a power-of-2 type with at least 8 bits to avoid
692 // creating unnecessary illegal types.
693 unsigned char Width = NextPowerOf2(std::max((unsigned char)7, Max));
694
695 // Now build the bit field.
696 APInt Bitfield(Width, 0);
697 for (char C : Str)
698 Bitfield.setBit((unsigned char)C);
699 Value *BitfieldC = B.getInt(Bitfield);
700
701 // First check that the bit field access is within bounds.
702 Value *C = B.CreateZExtOrTrunc(CI->getArgOperand(1), BitfieldC->getType());
703 Value *Bounds = B.CreateICmp(ICmpInst::ICMP_ULT, C, B.getIntN(Width, Width),
704 "memchr.bounds");
705
706 // Create code that checks if the given bit is set in the field.
707 Value *Shl = B.CreateShl(B.getIntN(Width, 1ULL), C);
708 Value *Bits = B.CreateIsNotNull(B.CreateAnd(Shl, BitfieldC), "memchr.bits");
709
710 // Finally merge both checks and cast to pointer type. The inttoptr
711 // implicitly zexts the i1 to intptr type.
712 return B.CreateIntToPtr(B.CreateAnd(Bounds, Bits, "memchr"), CI->getType());
713 }
714
715 // Check if all arguments are constants. If so, we can constant fold.
716 if (!CharC)
717 return nullptr;
718
Benjamin Kramer691363e2015-03-21 15:36:21 +0000719 // Compute the offset.
720 size_t I = Str.find(CharC->getSExtValue() & 0xFF);
721 if (I == StringRef::npos) // Didn't find the char. memchr returns null.
722 return Constant::getNullValue(CI->getType());
723
724 // memchr(s+n,c,l) -> gep(s+n+i,c)
David Blaikie3909da72015-03-30 20:42:56 +0000725 return B.CreateGEP(B.getInt8Ty(), SrcStr, B.getInt64(I), "memchr");
Benjamin Kramer691363e2015-03-21 15:36:21 +0000726}
727
Chris Bienemanad070d02014-09-17 20:55:46 +0000728Value *LibCallSimplifier::optimizeMemCmp(CallInst *CI, IRBuilder<> &B) {
Chris Bienemanad070d02014-09-17 20:55:46 +0000729 Value *LHS = CI->getArgOperand(0), *RHS = CI->getArgOperand(1);
Meador Inge40b6fac2012-10-15 03:47:37 +0000730
Chris Bienemanad070d02014-09-17 20:55:46 +0000731 if (LHS == RHS) // memcmp(s,s,x) -> 0
732 return Constant::getNullValue(CI->getType());
Meador Inge40b6fac2012-10-15 03:47:37 +0000733
Chris Bienemanad070d02014-09-17 20:55:46 +0000734 // Make sure we have a constant length.
735 ConstantInt *LenC = dyn_cast<ConstantInt>(CI->getArgOperand(2));
736 if (!LenC)
Craig Topperf40110f2014-04-25 05:29:35 +0000737 return nullptr;
Chris Bienemanad070d02014-09-17 20:55:46 +0000738 uint64_t Len = LenC->getZExtValue();
739
740 if (Len == 0) // memcmp(s1,s2,0) -> 0
741 return Constant::getNullValue(CI->getType());
742
743 // memcmp(S1,S2,1) -> *(unsigned char*)LHS - *(unsigned char*)RHS
744 if (Len == 1) {
Sanjay Pateld3112a52016-01-19 19:46:10 +0000745 Value *LHSV = B.CreateZExt(B.CreateLoad(castToCStr(LHS, B), "lhsc"),
Chris Bienemanad070d02014-09-17 20:55:46 +0000746 CI->getType(), "lhsv");
Sanjay Pateld3112a52016-01-19 19:46:10 +0000747 Value *RHSV = B.CreateZExt(B.CreateLoad(castToCStr(RHS, B), "rhsc"),
Chris Bienemanad070d02014-09-17 20:55:46 +0000748 CI->getType(), "rhsv");
749 return B.CreateSub(LHSV, RHSV, "chardiff");
Meador Inge40b6fac2012-10-15 03:47:37 +0000750 }
Meador Inge40b6fac2012-10-15 03:47:37 +0000751
Chad Rosierdc655322015-08-28 18:30:18 +0000752 // memcmp(S1,S2,N/8)==0 -> (*(intN_t*)S1 != *(intN_t*)S2)==0
753 if (DL.isLegalInteger(Len * 8) && isOnlyUsedInZeroEqualityComparison(CI)) {
754
755 IntegerType *IntType = IntegerType::get(CI->getContext(), Len * 8);
756 unsigned PrefAlignment = DL.getPrefTypeAlignment(IntType);
757
758 if (getKnownAlignment(LHS, DL, CI) >= PrefAlignment &&
759 getKnownAlignment(RHS, DL, CI) >= PrefAlignment) {
760
761 Type *LHSPtrTy =
762 IntType->getPointerTo(LHS->getType()->getPointerAddressSpace());
763 Type *RHSPtrTy =
764 IntType->getPointerTo(RHS->getType()->getPointerAddressSpace());
765
Sanjay Pateld707db92015-12-31 16:10:49 +0000766 Value *LHSV =
767 B.CreateLoad(B.CreateBitCast(LHS, LHSPtrTy, "lhsc"), "lhsv");
768 Value *RHSV =
769 B.CreateLoad(B.CreateBitCast(RHS, RHSPtrTy, "rhsc"), "rhsv");
Chad Rosierdc655322015-08-28 18:30:18 +0000770
771 return B.CreateZExt(B.CreateICmpNE(LHSV, RHSV), CI->getType(), "memcmp");
772 }
773 }
774
Chris Bienemanad070d02014-09-17 20:55:46 +0000775 // Constant folding: memcmp(x, y, l) -> cnst (all arguments are constant)
776 StringRef LHSStr, RHSStr;
777 if (getConstantStringInfo(LHS, LHSStr) &&
778 getConstantStringInfo(RHS, RHSStr)) {
779 // Make sure we're not reading out-of-bounds memory.
780 if (Len > LHSStr.size() || Len > RHSStr.size())
Craig Topperf40110f2014-04-25 05:29:35 +0000781 return nullptr;
Chris Bienemanad070d02014-09-17 20:55:46 +0000782 // Fold the memcmp and normalize the result. This way we get consistent
783 // results across multiple platforms.
784 uint64_t Ret = 0;
785 int Cmp = memcmp(LHSStr.data(), RHSStr.data(), Len);
786 if (Cmp < 0)
787 Ret = -1;
788 else if (Cmp > 0)
789 Ret = 1;
790 return ConstantInt::get(CI->getType(), Ret);
Meador Inge000dbcc2012-10-18 18:12:40 +0000791 }
Meador Inge000dbcc2012-10-18 18:12:40 +0000792
Chris Bienemanad070d02014-09-17 20:55:46 +0000793 return nullptr;
794}
Meador Inge9a6a1902012-10-31 00:20:56 +0000795
Chris Bienemanad070d02014-09-17 20:55:46 +0000796Value *LibCallSimplifier::optimizeMemCpy(CallInst *CI, IRBuilder<> &B) {
Chris Bienemanad070d02014-09-17 20:55:46 +0000797 // memcpy(x, y, n) -> llvm.memcpy(x, y, n, 1)
798 B.CreateMemCpy(CI->getArgOperand(0), CI->getArgOperand(1),
Pete Cooper67cf9a72015-11-19 05:56:52 +0000799 CI->getArgOperand(2), 1);
Chris Bienemanad070d02014-09-17 20:55:46 +0000800 return CI->getArgOperand(0);
801}
Meador Inge05a625a2012-10-31 14:58:26 +0000802
Chris Bienemanad070d02014-09-17 20:55:46 +0000803Value *LibCallSimplifier::optimizeMemMove(CallInst *CI, IRBuilder<> &B) {
Chris Bienemanad070d02014-09-17 20:55:46 +0000804 // memmove(x, y, n) -> llvm.memmove(x, y, n, 1)
805 B.CreateMemMove(CI->getArgOperand(0), CI->getArgOperand(1),
Pete Cooper67cf9a72015-11-19 05:56:52 +0000806 CI->getArgOperand(2), 1);
Chris Bienemanad070d02014-09-17 20:55:46 +0000807 return CI->getArgOperand(0);
808}
Meador Ingebcd88ef72012-11-10 15:16:48 +0000809
Sanjay Patel980b2802016-01-26 16:17:24 +0000810// TODO: Does this belong in BuildLibCalls or should all of those similar
811// functions be moved here?
Reid Klecknerb5180542017-03-21 16:57:19 +0000812static Value *emitCalloc(Value *Num, Value *Size, const AttributeList &Attrs,
Sanjay Patel980b2802016-01-26 16:17:24 +0000813 IRBuilder<> &B, const TargetLibraryInfo &TLI) {
David L. Jonesd21529f2017-01-23 23:16:46 +0000814 LibFunc Func;
Sanjay Patel980b2802016-01-26 16:17:24 +0000815 if (!TLI.getLibFunc("calloc", Func) || !TLI.has(Func))
816 return nullptr;
817
818 Module *M = B.GetInsertBlock()->getModule();
819 const DataLayout &DL = M->getDataLayout();
820 IntegerType *PtrType = DL.getIntPtrType((B.GetInsertBlock()->getContext()));
821 Value *Calloc = M->getOrInsertFunction("calloc", Attrs, B.getInt8PtrTy(),
Diana Picusb050c7f2017-04-11 10:07:12 +0000822 PtrType, PtrType, nullptr);
Sanjay Patel980b2802016-01-26 16:17:24 +0000823 CallInst *CI = B.CreateCall(Calloc, { Num, Size }, "calloc");
824
825 if (const auto *F = dyn_cast<Function>(Calloc->stripPointerCasts()))
826 CI->setCallingConv(F->getCallingConv());
827
828 return CI;
829}
830
831/// Fold memset[_chk](malloc(n), 0, n) --> calloc(1, n).
832static Value *foldMallocMemset(CallInst *Memset, IRBuilder<> &B,
833 const TargetLibraryInfo &TLI) {
834 // This has to be a memset of zeros (bzero).
835 auto *FillValue = dyn_cast<ConstantInt>(Memset->getArgOperand(1));
836 if (!FillValue || FillValue->getZExtValue() != 0)
837 return nullptr;
838
839 // TODO: We should handle the case where the malloc has more than one use.
840 // This is necessary to optimize common patterns such as when the result of
841 // the malloc is checked against null or when a memset intrinsic is used in
842 // place of a memset library call.
843 auto *Malloc = dyn_cast<CallInst>(Memset->getArgOperand(0));
844 if (!Malloc || !Malloc->hasOneUse())
845 return nullptr;
846
847 // Is the inner call really malloc()?
848 Function *InnerCallee = Malloc->getCalledFunction();
David L. Jonesd21529f2017-01-23 23:16:46 +0000849 LibFunc Func;
Ahmed Bougachad765a822016-04-27 19:04:35 +0000850 if (!TLI.getLibFunc(*InnerCallee, Func) || !TLI.has(Func) ||
David L. Jonesd21529f2017-01-23 23:16:46 +0000851 Func != LibFunc_malloc)
Sanjay Patel980b2802016-01-26 16:17:24 +0000852 return nullptr;
853
Sanjay Patel980b2802016-01-26 16:17:24 +0000854 // The memset must cover the same number of bytes that are malloc'd.
855 if (Memset->getArgOperand(2) != Malloc->getArgOperand(0))
856 return nullptr;
857
858 // Replace the malloc with a calloc. We need the data layout to know what the
859 // actual size of a 'size_t' parameter is.
860 B.SetInsertPoint(Malloc->getParent(), ++Malloc->getIterator());
861 const DataLayout &DL = Malloc->getModule()->getDataLayout();
862 IntegerType *SizeType = DL.getIntPtrType(B.GetInsertBlock()->getContext());
863 Value *Calloc = emitCalloc(ConstantInt::get(SizeType, 1),
864 Malloc->getArgOperand(0), Malloc->getAttributes(),
865 B, TLI);
866 if (!Calloc)
867 return nullptr;
868
869 Malloc->replaceAllUsesWith(Calloc);
870 Malloc->eraseFromParent();
871
872 return Calloc;
873}
874
Chris Bienemanad070d02014-09-17 20:55:46 +0000875Value *LibCallSimplifier::optimizeMemSet(CallInst *CI, IRBuilder<> &B) {
Sanjay Patel980b2802016-01-26 16:17:24 +0000876 if (auto *Calloc = foldMallocMemset(CI, B, *TLI))
877 return Calloc;
878
Chris Bienemanad070d02014-09-17 20:55:46 +0000879 // memset(p, v, n) -> llvm.memset(p, v, n, 1)
880 Value *Val = B.CreateIntCast(CI->getArgOperand(1), B.getInt8Ty(), false);
881 B.CreateMemSet(CI->getArgOperand(0), Val, CI->getArgOperand(2), 1);
882 return CI->getArgOperand(0);
883}
Meador Inged4825782012-11-11 06:49:03 +0000884
Meador Inge193e0352012-11-13 04:16:17 +0000885//===----------------------------------------------------------------------===//
886// Math Library Optimizations
887//===----------------------------------------------------------------------===//
888
Matthias Braund34e4d22014-12-03 21:46:33 +0000889/// Return a variant of Val with float type.
890/// Currently this works in two cases: If Val is an FPExtension of a float
891/// value to something bigger, simply return the operand.
892/// If Val is a ConstantFP but can be converted to a float ConstantFP without
893/// loss of precision do so.
894static Value *valueHasFloatPrecision(Value *Val) {
895 if (FPExtInst *Cast = dyn_cast<FPExtInst>(Val)) {
896 Value *Op = Cast->getOperand(0);
897 if (Op->getType()->isFloatTy())
898 return Op;
899 }
900 if (ConstantFP *Const = dyn_cast<ConstantFP>(Val)) {
901 APFloat F = Const->getValueAPF();
Matthias Braun395a82f2014-12-03 22:10:39 +0000902 bool losesInfo;
Stephan Bergmann17c7f702016-12-14 11:57:17 +0000903 (void)F.convert(APFloat::IEEEsingle(), APFloat::rmNearestTiesToEven,
Matthias Braun395a82f2014-12-03 22:10:39 +0000904 &losesInfo);
905 if (!losesInfo)
Matthias Braund34e4d22014-12-03 21:46:33 +0000906 return ConstantFP::get(Const->getContext(), F);
907 }
908 return nullptr;
909}
910
Sanjay Patel4e971da2016-01-21 18:01:57 +0000911/// Shrink double -> float for unary functions like 'floor'.
912static Value *optimizeUnaryDoubleFP(CallInst *CI, IRBuilder<> &B,
913 bool CheckRetType) {
Chris Bienemanad070d02014-09-17 20:55:46 +0000914 Function *Callee = CI->getCalledFunction();
Ahmed Bougachad765a822016-04-27 19:04:35 +0000915 // We know this libcall has a valid prototype, but we don't know which.
916 if (!CI->getType()->isDoubleTy())
Chris Bienemanad070d02014-09-17 20:55:46 +0000917 return nullptr;
Meador Inge193e0352012-11-13 04:16:17 +0000918
Chris Bienemanad070d02014-09-17 20:55:46 +0000919 if (CheckRetType) {
920 // Check if all the uses for function like 'sin' are converted to float.
921 for (User *U : CI->users()) {
922 FPTruncInst *Cast = dyn_cast<FPTruncInst>(U);
923 if (!Cast || !Cast->getType()->isFloatTy())
924 return nullptr;
Meador Inge193e0352012-11-13 04:16:17 +0000925 }
Meador Inge193e0352012-11-13 04:16:17 +0000926 }
Chris Bienemanad070d02014-09-17 20:55:46 +0000927
928 // If this is something like 'floor((double)floatval)', convert to floorf.
Matthias Braund34e4d22014-12-03 21:46:33 +0000929 Value *V = valueHasFloatPrecision(CI->getArgOperand(0));
930 if (V == nullptr)
Chris Bienemanad070d02014-09-17 20:55:46 +0000931 return nullptr;
Sanjay Patelaa231142015-12-31 21:52:31 +0000932
933 // Propagate fast-math flags from the existing call to the new call.
934 IRBuilder<>::FastMathFlagGuard Guard(B);
Sanjay Patela2528152016-01-12 18:03:37 +0000935 B.setFastMathFlags(CI->getFastMathFlags());
Chris Bienemanad070d02014-09-17 20:55:46 +0000936
937 // floor((double)floatval) -> (double)floorf(floatval)
Sanjay Patel848309d2014-10-23 21:52:45 +0000938 if (Callee->isIntrinsic()) {
Sanjay Patelaf674fb2015-12-14 17:24:23 +0000939 Module *M = CI->getModule();
Pete Cooper9e1d3352015-05-20 17:16:39 +0000940 Intrinsic::ID IID = Callee->getIntrinsicID();
Sanjay Patel848309d2014-10-23 21:52:45 +0000941 Function *F = Intrinsic::getDeclaration(M, IID, B.getFloatTy());
942 V = B.CreateCall(F, V);
943 } else {
944 // The call is a library call rather than an intrinsic.
Sanjay Pateld3112a52016-01-19 19:46:10 +0000945 V = emitUnaryFloatFnCall(V, Callee->getName(), B, Callee->getAttributes());
Sanjay Patel848309d2014-10-23 21:52:45 +0000946 }
947
Chris Bienemanad070d02014-09-17 20:55:46 +0000948 return B.CreateFPExt(V, B.getDoubleTy());
949}
Meador Inge193e0352012-11-13 04:16:17 +0000950
Matt Arsenault954a6242017-01-23 23:55:08 +0000951// Replace a libcall \p CI with a call to intrinsic \p IID
952static Value *replaceUnaryCall(CallInst *CI, IRBuilder<> &B, Intrinsic::ID IID) {
953 // Propagate fast-math flags from the existing call to the new call.
954 IRBuilder<>::FastMathFlagGuard Guard(B);
955 B.setFastMathFlags(CI->getFastMathFlags());
956
957 Module *M = CI->getModule();
958 Value *V = CI->getArgOperand(0);
959 Function *F = Intrinsic::getDeclaration(M, IID, CI->getType());
960 CallInst *NewCall = B.CreateCall(F, V);
961 NewCall->takeName(CI);
962 return NewCall;
963}
964
Sanjay Patel4e971da2016-01-21 18:01:57 +0000965/// Shrink double -> float for binary functions like 'fmin/fmax'.
966static Value *optimizeBinaryDoubleFP(CallInst *CI, IRBuilder<> &B) {
Chris Bienemanad070d02014-09-17 20:55:46 +0000967 Function *Callee = CI->getCalledFunction();
Ahmed Bougachad765a822016-04-27 19:04:35 +0000968 // We know this libcall has a valid prototype, but we don't know which.
969 if (!CI->getType()->isDoubleTy())
Craig Topperf40110f2014-04-25 05:29:35 +0000970 return nullptr;
Meador Inge193e0352012-11-13 04:16:17 +0000971
Chris Bienemanad070d02014-09-17 20:55:46 +0000972 // If this is something like 'fmin((double)floatval1, (double)floatval2)',
Matthias Braund34e4d22014-12-03 21:46:33 +0000973 // or fmin(1.0, (double)floatval), then we convert it to fminf.
974 Value *V1 = valueHasFloatPrecision(CI->getArgOperand(0));
975 if (V1 == nullptr)
976 return nullptr;
977 Value *V2 = valueHasFloatPrecision(CI->getArgOperand(1));
978 if (V2 == nullptr)
Craig Topperf40110f2014-04-25 05:29:35 +0000979 return nullptr;
Chris Bienemanad070d02014-09-17 20:55:46 +0000980
Sanjay Patelbee05ca2015-12-31 23:40:59 +0000981 // Propagate fast-math flags from the existing call to the new call.
982 IRBuilder<>::FastMathFlagGuard Guard(B);
Sanjay Patela2528152016-01-12 18:03:37 +0000983 B.setFastMathFlags(CI->getFastMathFlags());
Sanjay Patelbee05ca2015-12-31 23:40:59 +0000984
Chris Bienemanad070d02014-09-17 20:55:46 +0000985 // fmin((double)floatval1, (double)floatval2)
Matthias Braund34e4d22014-12-03 21:46:33 +0000986 // -> (double)fminf(floatval1, floatval2)
Sanjay Patel848309d2014-10-23 21:52:45 +0000987 // TODO: Handle intrinsics in the same way as in optimizeUnaryDoubleFP().
Sanjay Pateld3112a52016-01-19 19:46:10 +0000988 Value *V = emitBinaryFloatFnCall(V1, V2, Callee->getName(), B,
Matthias Braund34e4d22014-12-03 21:46:33 +0000989 Callee->getAttributes());
Chris Bienemanad070d02014-09-17 20:55:46 +0000990 return B.CreateFPExt(V, B.getDoubleTy());
991}
992
993Value *LibCallSimplifier::optimizeCos(CallInst *CI, IRBuilder<> &B) {
994 Function *Callee = CI->getCalledFunction();
995 Value *Ret = nullptr;
Davide Italianoa3458772015-11-05 19:18:23 +0000996 StringRef Name = Callee->getName();
997 if (UnsafeFPShrink && Name == "cos" && hasFloatVersion(Name))
Chris Bienemanad070d02014-09-17 20:55:46 +0000998 Ret = optimizeUnaryDoubleFP(CI, B, true);
Bob Wilsond8d92d92013-11-03 06:48:38 +0000999
Chris Bienemanad070d02014-09-17 20:55:46 +00001000 // cos(-x) -> cos(x)
1001 Value *Op1 = CI->getArgOperand(0);
1002 if (BinaryOperator::isFNeg(Op1)) {
1003 BinaryOperator *BinExpr = cast<BinaryOperator>(Op1);
1004 return B.CreateCall(Callee, BinExpr->getOperand(1), "cos");
1005 }
1006 return Ret;
1007}
Bob Wilsond8d92d92013-11-03 06:48:38 +00001008
Weiming Zhao82130722015-12-04 22:00:47 +00001009static Value *getPow(Value *InnerChain[33], unsigned Exp, IRBuilder<> &B) {
1010 // Multiplications calculated using Addition Chains.
1011 // Refer: http://wwwhomes.uni-bielefeld.de/achim/addition_chain.html
1012
1013 assert(Exp != 0 && "Incorrect exponent 0 not handled");
1014
1015 if (InnerChain[Exp])
1016 return InnerChain[Exp];
1017
1018 static const unsigned AddChain[33][2] = {
1019 {0, 0}, // Unused.
1020 {0, 0}, // Unused (base case = pow1).
1021 {1, 1}, // Unused (pre-computed).
1022 {1, 2}, {2, 2}, {2, 3}, {3, 3}, {2, 5}, {4, 4},
1023 {1, 8}, {5, 5}, {1, 10}, {6, 6}, {4, 9}, {7, 7},
1024 {3, 12}, {8, 8}, {8, 9}, {2, 16}, {1, 18}, {10, 10},
1025 {6, 15}, {11, 11}, {3, 20}, {12, 12}, {8, 17}, {13, 13},
1026 {3, 24}, {14, 14}, {4, 25}, {15, 15}, {3, 28}, {16, 16},
1027 };
1028
1029 InnerChain[Exp] = B.CreateFMul(getPow(InnerChain, AddChain[Exp][0], B),
1030 getPow(InnerChain, AddChain[Exp][1], B));
1031 return InnerChain[Exp];
1032}
1033
Chris Bienemanad070d02014-09-17 20:55:46 +00001034Value *LibCallSimplifier::optimizePow(CallInst *CI, IRBuilder<> &B) {
1035 Function *Callee = CI->getCalledFunction();
Chris Bienemanad070d02014-09-17 20:55:46 +00001036 Value *Ret = nullptr;
Davide Italianoa3458772015-11-05 19:18:23 +00001037 StringRef Name = Callee->getName();
1038 if (UnsafeFPShrink && Name == "pow" && 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 Value *Op1 = CI->getArgOperand(0), *Op2 = CI->getArgOperand(1);
Davide Italiano27da1312016-08-07 20:27:03 +00001042
1043 // pow(1.0, x) -> 1.0
1044 if (match(Op1, m_SpecificFP(1.0)))
1045 return Op1;
1046 // pow(2.0, x) -> llvm.exp2(x)
1047 if (match(Op1, m_SpecificFP(2.0))) {
1048 Value *Exp2 = Intrinsic::getDeclaration(CI->getModule(), Intrinsic::exp2,
1049 CI->getType());
1050 return B.CreateCall(Exp2, Op2, "exp2");
1051 }
1052
1053 // There's no llvm.exp10 intrinsic yet, but, maybe, some day there will
1054 // be one.
Chris Bienemanad070d02014-09-17 20:55:46 +00001055 if (ConstantFP *Op1C = dyn_cast<ConstantFP>(Op1)) {
Chris Bienemanad070d02014-09-17 20:55:46 +00001056 // pow(10.0, x) -> exp10(x)
1057 if (Op1C->isExactlyValue(10.0) &&
David L. Jonesd21529f2017-01-23 23:16:46 +00001058 hasUnaryFloatFn(TLI, Op1->getType(), LibFunc_exp10, LibFunc_exp10f,
1059 LibFunc_exp10l))
1060 return emitUnaryFloatFnCall(Op2, TLI->getName(LibFunc_exp10), B,
Chris Bienemanad070d02014-09-17 20:55:46 +00001061 Callee->getAttributes());
Bob Wilsond8d92d92013-11-03 06:48:38 +00001062 }
1063
Sanjay Patel6002e782016-01-12 17:30:37 +00001064 // pow(exp(x), y) -> exp(x * y)
Davide Italianoc8a79132015-11-03 20:32:23 +00001065 // pow(exp2(x), y) -> exp2(x * y)
Sanjay Patel6002e782016-01-12 17:30:37 +00001066 // We enable these only with fast-math. Besides rounding differences, the
1067 // transformation changes overflow and underflow behavior quite dramatically.
Davide Italianoc8a79132015-11-03 20:32:23 +00001068 // Example: x = 1000, y = 0.001.
1069 // pow(exp(x), y) = pow(inf, 0.001) = inf, whereas exp(x*y) = exp(1).
Sanjay Patel6002e782016-01-12 17:30:37 +00001070 auto *OpC = dyn_cast<CallInst>(Op1);
1071 if (OpC && OpC->hasUnsafeAlgebra() && CI->hasUnsafeAlgebra()) {
David L. Jonesd21529f2017-01-23 23:16:46 +00001072 LibFunc Func;
Sanjay Patel6002e782016-01-12 17:30:37 +00001073 Function *OpCCallee = OpC->getCalledFunction();
1074 if (OpCCallee && TLI->getLibFunc(OpCCallee->getName(), Func) &&
David L. Jonesd21529f2017-01-23 23:16:46 +00001075 TLI->has(Func) && (Func == LibFunc_exp || Func == LibFunc_exp2)) {
Davide Italianoc8a79132015-11-03 20:32:23 +00001076 IRBuilder<>::FastMathFlagGuard Guard(B);
Sanjay Patela2528152016-01-12 18:03:37 +00001077 B.setFastMathFlags(CI->getFastMathFlags());
Sanjay Patel6002e782016-01-12 17:30:37 +00001078 Value *FMul = B.CreateFMul(OpC->getArgOperand(0), Op2, "mul");
Sanjay Pateld3112a52016-01-19 19:46:10 +00001079 return emitUnaryFloatFnCall(FMul, OpCCallee->getName(), B,
Sanjay Patel6002e782016-01-12 17:30:37 +00001080 OpCCallee->getAttributes());
Davide Italianoc8a79132015-11-03 20:32:23 +00001081 }
1082 }
1083
Chris Bienemanad070d02014-09-17 20:55:46 +00001084 ConstantFP *Op2C = dyn_cast<ConstantFP>(Op2);
1085 if (!Op2C)
1086 return Ret;
1087
1088 if (Op2C->getValueAPF().isZero()) // pow(x, 0.0) -> 1.0
1089 return ConstantFP::get(CI->getType(), 1.0);
1090
Davide Italiano472684e2017-01-09 21:55:23 +00001091 if (Op2C->isExactlyValue(-0.5) &&
David L. Jonesd21529f2017-01-23 23:16:46 +00001092 hasUnaryFloatFn(TLI, Op2->getType(), LibFunc_sqrt, LibFunc_sqrtf,
1093 LibFunc_sqrtl)) {
Davide Italiano472684e2017-01-09 21:55:23 +00001094 // If -ffast-math:
1095 // pow(x, -0.5) -> 1.0 / sqrt(x)
1096 if (CI->hasUnsafeAlgebra()) {
1097 IRBuilder<>::FastMathFlagGuard Guard(B);
1098 B.setFastMathFlags(CI->getFastMathFlags());
1099
Justin Lebarcb9b41d2017-01-27 00:58:03 +00001100 // TODO: If the pow call is an intrinsic, we should lower to the sqrt
1101 // intrinsic, so we match errno semantics. We also should check that the
1102 // target can in fact lower the sqrt intrinsic -- we currently have no way
1103 // to ask this question other than asking whether the target has a sqrt
1104 // libcall, which is a sufficient but not necessary condition.
David L. Jonesd21529f2017-01-23 23:16:46 +00001105 Value *Sqrt = emitUnaryFloatFnCall(Op1, TLI->getName(LibFunc_sqrt), B,
Davide Italiano472684e2017-01-09 21:55:23 +00001106 Callee->getAttributes());
1107
1108 return B.CreateFDiv(ConstantFP::get(CI->getType(), 1.0), Sqrt, "sqrtrecip");
1109 }
1110 }
1111
Chris Bienemanad070d02014-09-17 20:55:46 +00001112 if (Op2C->isExactlyValue(0.5) &&
David L. Jonesd21529f2017-01-23 23:16:46 +00001113 hasUnaryFloatFn(TLI, Op2->getType(), LibFunc_sqrt, LibFunc_sqrtf,
1114 LibFunc_sqrtl)) {
Davide Italianoc5cedd12015-11-18 23:21:32 +00001115
1116 // In -ffast-math, pow(x, 0.5) -> sqrt(x).
Sanjay Patel53ba88d2016-01-12 19:06:35 +00001117 if (CI->hasUnsafeAlgebra()) {
1118 IRBuilder<>::FastMathFlagGuard Guard(B);
1119 B.setFastMathFlags(CI->getFastMathFlags());
Davide Italiano873219c2016-08-10 06:33:32 +00001120
Justin Lebarcb9b41d2017-01-27 00:58:03 +00001121 // TODO: As above, we should lower to the sqrt intrinsic if the pow is an
1122 // intrinsic, to match errno semantics.
David L. Jonesd21529f2017-01-23 23:16:46 +00001123 return emitUnaryFloatFnCall(Op1, TLI->getName(LibFunc_sqrt), B,
Davide Italiano873219c2016-08-10 06:33:32 +00001124 Callee->getAttributes());
Sanjay Patel53ba88d2016-01-12 19:06:35 +00001125 }
Davide Italianoc5cedd12015-11-18 23:21:32 +00001126
Chris Bienemanad070d02014-09-17 20:55:46 +00001127 // Expand pow(x, 0.5) to (x == -infinity ? +infinity : fabs(sqrt(x))).
1128 // This is faster than calling pow, and still handles negative zero
1129 // and negative infinity correctly.
Chris Bienemanad070d02014-09-17 20:55:46 +00001130 // TODO: In finite-only mode, this could be just fabs(sqrt(x)).
1131 Value *Inf = ConstantFP::getInfinity(CI->getType());
1132 Value *NegInf = ConstantFP::getInfinity(CI->getType(), true);
Justin Lebarcb9b41d2017-01-27 00:58:03 +00001133
1134 // TODO: As above, we should lower to the sqrt intrinsic if the pow is an
1135 // intrinsic, to match errno semantics.
Sanjay Pateld3112a52016-01-19 19:46:10 +00001136 Value *Sqrt = emitUnaryFloatFnCall(Op1, "sqrt", B, Callee->getAttributes());
Matt Arsenaultb948b4d2017-01-17 00:30:31 +00001137
1138 Module *M = Callee->getParent();
1139 Function *FabsF = Intrinsic::getDeclaration(M, Intrinsic::fabs,
1140 CI->getType());
1141 Value *FAbs = B.CreateCall(FabsF, Sqrt);
1142
Chris Bienemanad070d02014-09-17 20:55:46 +00001143 Value *FCmp = B.CreateFCmpOEQ(Op1, NegInf);
1144 Value *Sel = B.CreateSelect(FCmp, Inf, FAbs);
1145 return Sel;
Bob Wilsond8d92d92013-11-03 06:48:38 +00001146 }
1147
Chris Bienemanad070d02014-09-17 20:55:46 +00001148 if (Op2C->isExactlyValue(1.0)) // pow(x, 1.0) -> x
1149 return Op1;
1150 if (Op2C->isExactlyValue(2.0)) // pow(x, 2.0) -> x*x
1151 return B.CreateFMul(Op1, Op1, "pow2");
1152 if (Op2C->isExactlyValue(-1.0)) // pow(x, -1.0) -> 1.0/x
1153 return B.CreateFDiv(ConstantFP::get(CI->getType(), 1.0), Op1, "powrecip");
Weiming Zhao82130722015-12-04 22:00:47 +00001154
1155 // In -ffast-math, generate repeated fmul instead of generating pow(x, n).
Sanjay Patel81a63cd2016-01-19 18:15:12 +00001156 if (CI->hasUnsafeAlgebra()) {
Weiming Zhao82130722015-12-04 22:00:47 +00001157 APFloat V = abs(Op2C->getValueAPF());
1158 // We limit to a max of 7 fmul(s). Thus max exponent is 32.
1159 // This transformation applies to integer exponents only.
1160 if (V.compare(APFloat(V.getSemantics(), 32.0)) == APFloat::cmpGreaterThan ||
1161 !V.isInteger())
1162 return nullptr;
1163
Davide Italianof8711f02017-01-10 18:02:05 +00001164 // Propagate fast math flags.
1165 IRBuilder<>::FastMathFlagGuard Guard(B);
1166 B.setFastMathFlags(CI->getFastMathFlags());
1167
Weiming Zhao82130722015-12-04 22:00:47 +00001168 // We will memoize intermediate products of the Addition Chain.
1169 Value *InnerChain[33] = {nullptr};
1170 InnerChain[1] = Op1;
1171 InnerChain[2] = B.CreateFMul(Op1, Op1);
1172
1173 // We cannot readily convert a non-double type (like float) to a double.
1174 // So we first convert V to something which could be converted to double.
1175 bool ignored;
Stephan Bergmann17c7f702016-12-14 11:57:17 +00001176 V.convert(APFloat::IEEEdouble(), APFloat::rmTowardZero, &ignored);
Sanjay Patel81a63cd2016-01-19 18:15:12 +00001177
Weiming Zhao82130722015-12-04 22:00:47 +00001178 Value *FMul = getPow(InnerChain, V.convertToDouble(), B);
1179 // For negative exponents simply compute the reciprocal.
1180 if (Op2C->isNegative())
1181 FMul = B.CreateFDiv(ConstantFP::get(CI->getType(), 1.0), FMul);
1182 return FMul;
1183 }
1184
Chris Bienemanad070d02014-09-17 20:55:46 +00001185 return nullptr;
1186}
Bob Wilsond8d92d92013-11-03 06:48:38 +00001187
Chris Bienemanad070d02014-09-17 20:55:46 +00001188Value *LibCallSimplifier::optimizeExp2(CallInst *CI, IRBuilder<> &B) {
1189 Function *Callee = CI->getCalledFunction();
Chris Bienemanad070d02014-09-17 20:55:46 +00001190 Value *Ret = nullptr;
Davide Italianoa3458772015-11-05 19:18:23 +00001191 StringRef Name = Callee->getName();
1192 if (UnsafeFPShrink && Name == "exp2" && hasFloatVersion(Name))
Chris Bienemanad070d02014-09-17 20:55:46 +00001193 Ret = optimizeUnaryDoubleFP(CI, B, true);
Bob Wilsond8d92d92013-11-03 06:48:38 +00001194
Chris Bienemanad070d02014-09-17 20:55:46 +00001195 Value *Op = CI->getArgOperand(0);
1196 // Turn exp2(sitofp(x)) -> ldexp(1.0, sext(x)) if sizeof(x) <= 32
1197 // Turn exp2(uitofp(x)) -> ldexp(1.0, zext(x)) if sizeof(x) < 32
David L. Jonesd21529f2017-01-23 23:16:46 +00001198 LibFunc LdExp = LibFunc_ldexpl;
Chris Bienemanad070d02014-09-17 20:55:46 +00001199 if (Op->getType()->isFloatTy())
David L. Jonesd21529f2017-01-23 23:16:46 +00001200 LdExp = LibFunc_ldexpf;
Chris Bienemanad070d02014-09-17 20:55:46 +00001201 else if (Op->getType()->isDoubleTy())
David L. Jonesd21529f2017-01-23 23:16:46 +00001202 LdExp = LibFunc_ldexp;
Chris Bienemanad070d02014-09-17 20:55:46 +00001203
1204 if (TLI->has(LdExp)) {
1205 Value *LdExpArg = nullptr;
1206 if (SIToFPInst *OpC = dyn_cast<SIToFPInst>(Op)) {
1207 if (OpC->getOperand(0)->getType()->getPrimitiveSizeInBits() <= 32)
1208 LdExpArg = B.CreateSExt(OpC->getOperand(0), B.getInt32Ty());
1209 } else if (UIToFPInst *OpC = dyn_cast<UIToFPInst>(Op)) {
1210 if (OpC->getOperand(0)->getType()->getPrimitiveSizeInBits() < 32)
1211 LdExpArg = B.CreateZExt(OpC->getOperand(0), B.getInt32Ty());
1212 }
1213
1214 if (LdExpArg) {
1215 Constant *One = ConstantFP::get(CI->getContext(), APFloat(1.0f));
1216 if (!Op->getType()->isFloatTy())
1217 One = ConstantExpr::getFPExtend(One, Op->getType());
1218
Sanjay Patel0e603fc2016-01-21 22:31:18 +00001219 Module *M = CI->getModule();
Mehdi Aminidb11fdf2017-04-06 20:23:57 +00001220 Value *NewCallee =
1221 M->getOrInsertFunction(TLI->getName(LdExp), Op->getType(),
Diana Picusb050c7f2017-04-11 10:07:12 +00001222 Op->getType(), B.getInt32Ty(), nullptr);
Sanjay Patel042aed902016-01-21 22:41:16 +00001223 CallInst *CI = B.CreateCall(NewCallee, {One, LdExpArg});
Chris Bienemanad070d02014-09-17 20:55:46 +00001224 if (const Function *F = dyn_cast<Function>(Callee->stripPointerCasts()))
1225 CI->setCallingConv(F->getCallingConv());
1226
1227 return CI;
1228 }
1229 }
1230 return Ret;
1231}
1232
Sanjay Patel57fd1dc2015-08-16 20:18:19 +00001233Value *LibCallSimplifier::optimizeFMinFMax(CallInst *CI, IRBuilder<> &B) {
Sanjay Patel9beec212016-01-21 22:58:01 +00001234 Function *Callee = CI->getCalledFunction();
Sanjay Patel57fd1dc2015-08-16 20:18:19 +00001235 // If we can shrink the call to a float function rather than a double
1236 // function, do that first.
Davide Italianoa3458772015-11-05 19:18:23 +00001237 StringRef Name = Callee->getName();
Sanjay Patelc7ddb7f2016-01-06 00:32:15 +00001238 if ((Name == "fmin" || Name == "fmax") && hasFloatVersion(Name))
1239 if (Value *Ret = optimizeBinaryDoubleFP(CI, B))
Sanjay Patel57fd1dc2015-08-16 20:18:19 +00001240 return Ret;
Sanjay Patel57fd1dc2015-08-16 20:18:19 +00001241
Benjamin Kramerbb70d752015-08-16 21:16:37 +00001242 IRBuilder<>::FastMathFlagGuard Guard(B);
Sanjay Patel57fd1dc2015-08-16 20:18:19 +00001243 FastMathFlags FMF;
Sanjay Patel29095ea2016-01-05 20:46:19 +00001244 if (CI->hasUnsafeAlgebra()) {
Sanjay Patel57fd1dc2015-08-16 20:18:19 +00001245 // Unsafe algebra sets all fast-math-flags to true.
1246 FMF.setUnsafeAlgebra();
1247 } else {
1248 // At a minimum, no-nans-fp-math must be true.
Sanjay Patel29095ea2016-01-05 20:46:19 +00001249 if (!CI->hasNoNaNs())
Sanjay Patel57fd1dc2015-08-16 20:18:19 +00001250 return nullptr;
1251 // No-signed-zeros is implied by the definitions of fmax/fmin themselves:
1252 // "Ideally, fmax would be sensitive to the sign of zero, for example
NAKAMURA Takumi0d725392015-09-07 00:26:54 +00001253 // fmax(-0. 0, +0. 0) would return +0; however, implementation in software
Sanjay Patel57fd1dc2015-08-16 20:18:19 +00001254 // might be impractical."
1255 FMF.setNoSignedZeros();
1256 FMF.setNoNaNs();
1257 }
Sanjay Patela2528152016-01-12 18:03:37 +00001258 B.setFastMathFlags(FMF);
Sanjay Patel57fd1dc2015-08-16 20:18:19 +00001259
1260 // We have a relaxed floating-point environment. We can ignore NaN-handling
1261 // and transform to a compare and select. We do not have to consider errno or
1262 // exceptions, because fmin/fmax do not have those.
1263 Value *Op0 = CI->getArgOperand(0);
1264 Value *Op1 = CI->getArgOperand(1);
1265 Value *Cmp = Callee->getName().startswith("fmin") ?
1266 B.CreateFCmpOLT(Op0, Op1) : B.CreateFCmpOGT(Op0, Op1);
1267 return B.CreateSelect(Cmp, Op0, Op1);
1268}
1269
Davide Italianob8b71332015-11-29 20:58:04 +00001270Value *LibCallSimplifier::optimizeLog(CallInst *CI, IRBuilder<> &B) {
1271 Function *Callee = CI->getCalledFunction();
1272 Value *Ret = nullptr;
1273 StringRef Name = Callee->getName();
1274 if (UnsafeFPShrink && hasFloatVersion(Name))
1275 Ret = optimizeUnaryDoubleFP(CI, B, true);
Davide Italianob8b71332015-11-29 20:58:04 +00001276
Sanjay Patele896ede2016-01-11 23:31:48 +00001277 if (!CI->hasUnsafeAlgebra())
Davide Italianob8b71332015-11-29 20:58:04 +00001278 return Ret;
1279 Value *Op1 = CI->getArgOperand(0);
1280 auto *OpC = dyn_cast<CallInst>(Op1);
Sanjay Patele896ede2016-01-11 23:31:48 +00001281
1282 // The earlier call must also be unsafe in order to do these transforms.
1283 if (!OpC || !OpC->hasUnsafeAlgebra())
Davide Italianob8b71332015-11-29 20:58:04 +00001284 return Ret;
1285
1286 // log(pow(x,y)) -> y*log(x)
1287 // This is only applicable to log, log2, log10.
1288 if (Name != "log" && Name != "log2" && Name != "log10")
1289 return Ret;
1290
1291 IRBuilder<>::FastMathFlagGuard Guard(B);
1292 FastMathFlags FMF;
1293 FMF.setUnsafeAlgebra();
Sanjay Patela2528152016-01-12 18:03:37 +00001294 B.setFastMathFlags(FMF);
Davide Italianob8b71332015-11-29 20:58:04 +00001295
David L. Jonesd21529f2017-01-23 23:16:46 +00001296 LibFunc Func;
Davide Italianob8b71332015-11-29 20:58:04 +00001297 Function *F = OpC->getCalledFunction();
Davide Italiano0b14f292015-11-29 21:58:56 +00001298 if (F && ((TLI->getLibFunc(F->getName(), Func) && TLI->has(Func) &&
David L. Jonesd21529f2017-01-23 23:16:46 +00001299 Func == LibFunc_pow) || F->getIntrinsicID() == Intrinsic::pow))
Davide Italianob8b71332015-11-29 20:58:04 +00001300 return B.CreateFMul(OpC->getArgOperand(1),
Sanjay Pateld3112a52016-01-19 19:46:10 +00001301 emitUnaryFloatFnCall(OpC->getOperand(0), Callee->getName(), B,
Davide Italianob8b71332015-11-29 20:58:04 +00001302 Callee->getAttributes()), "mul");
Davide Italiano1aeed6a2015-11-30 19:36:35 +00001303
1304 // log(exp2(y)) -> y*log(2)
1305 if (F && Name == "log" && TLI->getLibFunc(F->getName(), Func) &&
David L. Jonesd21529f2017-01-23 23:16:46 +00001306 TLI->has(Func) && Func == LibFunc_exp2)
Davide Italiano1aeed6a2015-11-30 19:36:35 +00001307 return B.CreateFMul(
1308 OpC->getArgOperand(0),
Sanjay Pateld3112a52016-01-19 19:46:10 +00001309 emitUnaryFloatFnCall(ConstantFP::get(CI->getType(), 2.0),
Davide Italiano1aeed6a2015-11-30 19:36:35 +00001310 Callee->getName(), B, Callee->getAttributes()),
1311 "logmul");
Davide Italianob8b71332015-11-29 20:58:04 +00001312 return Ret;
1313}
1314
Sanjay Patelc699a612014-10-16 18:48:17 +00001315Value *LibCallSimplifier::optimizeSqrt(CallInst *CI, IRBuilder<> &B) {
1316 Function *Callee = CI->getCalledFunction();
Sanjay Patelc699a612014-10-16 18:48:17 +00001317 Value *Ret = nullptr;
Justin Lebarcb9b41d2017-01-27 00:58:03 +00001318 // TODO: Once we have a way (other than checking for the existince of the
1319 // libcall) to tell whether our target can lower @llvm.sqrt, relax the
1320 // condition below.
David L. Jonesd21529f2017-01-23 23:16:46 +00001321 if (TLI->has(LibFunc_sqrtf) && (Callee->getName() == "sqrt" ||
Justin Lebarcb9b41d2017-01-27 00:58:03 +00001322 Callee->getIntrinsicID() == Intrinsic::sqrt))
Sanjay Patelc699a612014-10-16 18:48:17 +00001323 Ret = optimizeUnaryDoubleFP(CI, B, true);
Sanjay Patel683f2972016-01-11 22:34:19 +00001324
1325 if (!CI->hasUnsafeAlgebra())
Davide Italianoa904e522015-10-29 02:58:44 +00001326 return Ret;
Sanjay Patelc699a612014-10-16 18:48:17 +00001327
Sanjay Patelc2d64612016-01-06 20:52:21 +00001328 Instruction *I = dyn_cast<Instruction>(CI->getArgOperand(0));
1329 if (!I || I->getOpcode() != Instruction::FMul || !I->hasUnsafeAlgebra())
1330 return Ret;
1331
1332 // We're looking for a repeated factor in a multiplication tree,
1333 // so we can do this fold: sqrt(x * x) -> fabs(x);
Sanjay Patel683f2972016-01-11 22:34:19 +00001334 // or this fold: sqrt((x * x) * y) -> fabs(x) * sqrt(y).
Sanjay Patelc2d64612016-01-06 20:52:21 +00001335 Value *Op0 = I->getOperand(0);
1336 Value *Op1 = I->getOperand(1);
1337 Value *RepeatOp = nullptr;
1338 Value *OtherOp = nullptr;
1339 if (Op0 == Op1) {
1340 // Simple match: the operands of the multiply are identical.
1341 RepeatOp = Op0;
1342 } else {
1343 // Look for a more complicated pattern: one of the operands is itself
1344 // a multiply, so search for a common factor in that multiply.
1345 // Note: We don't bother looking any deeper than this first level or for
1346 // variations of this pattern because instcombine's visitFMUL and/or the
1347 // reassociation pass should give us this form.
1348 Value *OtherMul0, *OtherMul1;
1349 if (match(Op0, m_FMul(m_Value(OtherMul0), m_Value(OtherMul1)))) {
1350 // Pattern: sqrt((x * y) * z)
Sanjay Patel6c1ddbb2016-01-11 22:50:36 +00001351 if (OtherMul0 == OtherMul1 &&
1352 cast<Instruction>(Op0)->hasUnsafeAlgebra()) {
Sanjay Patelc2d64612016-01-06 20:52:21 +00001353 // Matched: sqrt((x * x) * z)
1354 RepeatOp = OtherMul0;
1355 OtherOp = Op1;
Sanjay Patelc699a612014-10-16 18:48:17 +00001356 }
1357 }
1358 }
Sanjay Patelc2d64612016-01-06 20:52:21 +00001359 if (!RepeatOp)
1360 return Ret;
1361
1362 // Fast math flags for any created instructions should match the sqrt
1363 // and multiply.
Sanjay Patelc2d64612016-01-06 20:52:21 +00001364 IRBuilder<>::FastMathFlagGuard Guard(B);
Sanjay Patela2528152016-01-12 18:03:37 +00001365 B.setFastMathFlags(I->getFastMathFlags());
Sanjay Patel9f67dad2016-01-11 22:35:39 +00001366
Sanjay Patelc2d64612016-01-06 20:52:21 +00001367 // If we found a repeated factor, hoist it out of the square root and
1368 // replace it with the fabs of that factor.
1369 Module *M = Callee->getParent();
1370 Type *ArgType = I->getType();
1371 Value *Fabs = Intrinsic::getDeclaration(M, Intrinsic::fabs, ArgType);
1372 Value *FabsCall = B.CreateCall(Fabs, RepeatOp, "fabs");
1373 if (OtherOp) {
1374 // If we found a non-repeated factor, we still need to get its square
1375 // root. We then multiply that by the value that was simplified out
1376 // of the square root calculation.
1377 Value *Sqrt = Intrinsic::getDeclaration(M, Intrinsic::sqrt, ArgType);
1378 Value *SqrtCall = B.CreateCall(Sqrt, OtherOp, "sqrt");
1379 return B.CreateFMul(FabsCall, SqrtCall);
1380 }
1381 return FabsCall;
Sanjay Patelc699a612014-10-16 18:48:17 +00001382}
1383
Sanjay Patelcddcd722016-01-06 19:23:35 +00001384// TODO: Generalize to handle any trig function and its inverse.
Davide Italiano51507d22015-11-04 23:36:56 +00001385Value *LibCallSimplifier::optimizeTan(CallInst *CI, IRBuilder<> &B) {
1386 Function *Callee = CI->getCalledFunction();
1387 Value *Ret = nullptr;
Davide Italianoa3458772015-11-05 19:18:23 +00001388 StringRef Name = Callee->getName();
1389 if (UnsafeFPShrink && Name == "tan" && hasFloatVersion(Name))
Davide Italiano51507d22015-11-04 23:36:56 +00001390 Ret = optimizeUnaryDoubleFP(CI, B, true);
Davide Italiano51507d22015-11-04 23:36:56 +00001391
Davide Italiano51507d22015-11-04 23:36:56 +00001392 Value *Op1 = CI->getArgOperand(0);
1393 auto *OpC = dyn_cast<CallInst>(Op1);
1394 if (!OpC)
1395 return Ret;
1396
Sanjay Patelcddcd722016-01-06 19:23:35 +00001397 // Both calls must allow unsafe optimizations in order to remove them.
1398 if (!CI->hasUnsafeAlgebra() || !OpC->hasUnsafeAlgebra())
1399 return Ret;
1400
Davide Italiano51507d22015-11-04 23:36:56 +00001401 // tan(atan(x)) -> x
1402 // tanf(atanf(x)) -> x
1403 // tanl(atanl(x)) -> x
David L. Jonesd21529f2017-01-23 23:16:46 +00001404 LibFunc Func;
Davide Italiano51507d22015-11-04 23:36:56 +00001405 Function *F = OpC->getCalledFunction();
Benjamin Kramerfb419e72015-11-26 09:51:17 +00001406 if (F && TLI->getLibFunc(F->getName(), Func) && TLI->has(Func) &&
David L. Jonesd21529f2017-01-23 23:16:46 +00001407 ((Func == LibFunc_atan && Callee->getName() == "tan") ||
1408 (Func == LibFunc_atanf && Callee->getName() == "tanf") ||
1409 (Func == LibFunc_atanl && Callee->getName() == "tanl")))
Davide Italiano51507d22015-11-04 23:36:56 +00001410 Ret = OpC->getArgOperand(0);
1411 return Ret;
1412}
1413
Sanjay Patel57747212016-01-21 23:38:43 +00001414static bool isTrigLibCall(CallInst *CI) {
Sanjay Patel57747212016-01-21 23:38:43 +00001415 // We can only hope to do anything useful if we can ignore things like errno
1416 // and floating-point exceptions.
Ahmed Bougachad765a822016-04-27 19:04:35 +00001417 // We already checked the prototype.
1418 return CI->hasFnAttr(Attribute::NoUnwind) &&
1419 CI->hasFnAttr(Attribute::ReadNone);
Sanjay Patel57747212016-01-21 23:38:43 +00001420}
1421
Chris Bienemanad070d02014-09-17 20:55:46 +00001422static void insertSinCosCall(IRBuilder<> &B, Function *OrigCallee, Value *Arg,
1423 bool UseFloat, Value *&Sin, Value *&Cos,
Sanjay Patel57747212016-01-21 23:38:43 +00001424 Value *&SinCos) {
1425 Type *ArgTy = Arg->getType();
1426 Type *ResTy;
1427 StringRef Name;
1428
1429 Triple T(OrigCallee->getParent()->getTargetTriple());
1430 if (UseFloat) {
1431 Name = "__sincospif_stret";
1432
1433 assert(T.getArch() != Triple::x86 && "x86 messy and unsupported for now");
1434 // x86_64 can't use {float, float} since that would be returned in both
1435 // xmm0 and xmm1, which isn't what a real struct would do.
1436 ResTy = T.getArch() == Triple::x86_64
1437 ? static_cast<Type *>(VectorType::get(ArgTy, 2))
1438 : static_cast<Type *>(StructType::get(ArgTy, ArgTy, nullptr));
1439 } else {
1440 Name = "__sincospi_stret";
1441 ResTy = StructType::get(ArgTy, ArgTy, nullptr);
1442 }
1443
1444 Module *M = OrigCallee->getParent();
Mehdi Aminidb11fdf2017-04-06 20:23:57 +00001445 Value *Callee = M->getOrInsertFunction(Name, OrigCallee->getAttributes(),
Diana Picusb050c7f2017-04-11 10:07:12 +00001446 ResTy, ArgTy, nullptr);
Sanjay Patel57747212016-01-21 23:38:43 +00001447
1448 if (Instruction *ArgInst = dyn_cast<Instruction>(Arg)) {
1449 // If the argument is an instruction, it must dominate all uses so put our
1450 // sincos call there.
1451 B.SetInsertPoint(ArgInst->getParent(), ++ArgInst->getIterator());
1452 } else {
1453 // Otherwise (e.g. for a constant) the beginning of the function is as
1454 // good a place as any.
1455 BasicBlock &EntryBB = B.GetInsertBlock()->getParent()->getEntryBlock();
1456 B.SetInsertPoint(&EntryBB, EntryBB.begin());
1457 }
1458
1459 SinCos = B.CreateCall(Callee, Arg, "sincospi");
1460
1461 if (SinCos->getType()->isStructTy()) {
1462 Sin = B.CreateExtractValue(SinCos, 0, "sinpi");
1463 Cos = B.CreateExtractValue(SinCos, 1, "cospi");
1464 } else {
1465 Sin = B.CreateExtractElement(SinCos, ConstantInt::get(B.getInt32Ty(), 0),
1466 "sinpi");
1467 Cos = B.CreateExtractElement(SinCos, ConstantInt::get(B.getInt32Ty(), 1),
1468 "cospi");
1469 }
1470}
Chris Bienemanad070d02014-09-17 20:55:46 +00001471
1472Value *LibCallSimplifier::optimizeSinCosPi(CallInst *CI, IRBuilder<> &B) {
Chris Bienemanad070d02014-09-17 20:55:46 +00001473 // Make sure the prototype is as expected, otherwise the rest of the
1474 // function is probably invalid and likely to abort.
1475 if (!isTrigLibCall(CI))
1476 return nullptr;
1477
1478 Value *Arg = CI->getArgOperand(0);
1479 SmallVector<CallInst *, 1> SinCalls;
1480 SmallVector<CallInst *, 1> CosCalls;
1481 SmallVector<CallInst *, 1> SinCosCalls;
1482
1483 bool IsFloat = Arg->getType()->isFloatTy();
1484
1485 // Look for all compatible sinpi, cospi and sincospi calls with the same
1486 // argument. If there are enough (in some sense) we can make the
1487 // substitution.
David Majnemerabae6b52016-03-19 04:53:02 +00001488 Function *F = CI->getFunction();
Chris Bienemanad070d02014-09-17 20:55:46 +00001489 for (User *U : Arg->users())
David Majnemerabae6b52016-03-19 04:53:02 +00001490 classifyArgUse(U, F, IsFloat, SinCalls, CosCalls, SinCosCalls);
Chris Bienemanad070d02014-09-17 20:55:46 +00001491
1492 // It's only worthwhile if both sinpi and cospi are actually used.
1493 if (SinCosCalls.empty() && (SinCalls.empty() || CosCalls.empty()))
1494 return nullptr;
1495
1496 Value *Sin, *Cos, *SinCos;
1497 insertSinCosCall(B, CI->getCalledFunction(), Arg, IsFloat, Sin, Cos, SinCos);
1498
Davide Italianof024a562016-12-16 02:28:38 +00001499 auto replaceTrigInsts = [this](SmallVectorImpl<CallInst *> &Calls,
1500 Value *Res) {
1501 for (CallInst *C : Calls)
1502 replaceAllUsesWith(C, Res);
1503 };
1504
Chris Bienemanad070d02014-09-17 20:55:46 +00001505 replaceTrigInsts(SinCalls, Sin);
1506 replaceTrigInsts(CosCalls, Cos);
1507 replaceTrigInsts(SinCosCalls, SinCos);
1508
1509 return nullptr;
1510}
1511
David Majnemerabae6b52016-03-19 04:53:02 +00001512void LibCallSimplifier::classifyArgUse(
1513 Value *Val, Function *F, bool IsFloat,
1514 SmallVectorImpl<CallInst *> &SinCalls,
1515 SmallVectorImpl<CallInst *> &CosCalls,
1516 SmallVectorImpl<CallInst *> &SinCosCalls) {
Chris Bienemanad070d02014-09-17 20:55:46 +00001517 CallInst *CI = dyn_cast<CallInst>(Val);
1518
1519 if (!CI)
1520 return;
1521
David Majnemerabae6b52016-03-19 04:53:02 +00001522 // Don't consider calls in other functions.
1523 if (CI->getFunction() != F)
1524 return;
1525
Chris Bienemanad070d02014-09-17 20:55:46 +00001526 Function *Callee = CI->getCalledFunction();
David L. Jonesd21529f2017-01-23 23:16:46 +00001527 LibFunc Func;
Ahmed Bougachad765a822016-04-27 19:04:35 +00001528 if (!Callee || !TLI->getLibFunc(*Callee, Func) || !TLI->has(Func) ||
Benjamin Kramer89766e52015-11-28 21:43:12 +00001529 !isTrigLibCall(CI))
Chris Bienemanad070d02014-09-17 20:55:46 +00001530 return;
1531
1532 if (IsFloat) {
David L. Jonesd21529f2017-01-23 23:16:46 +00001533 if (Func == LibFunc_sinpif)
Chris Bienemanad070d02014-09-17 20:55:46 +00001534 SinCalls.push_back(CI);
David L. Jonesd21529f2017-01-23 23:16:46 +00001535 else if (Func == LibFunc_cospif)
Chris Bienemanad070d02014-09-17 20:55:46 +00001536 CosCalls.push_back(CI);
David L. Jonesd21529f2017-01-23 23:16:46 +00001537 else if (Func == LibFunc_sincospif_stret)
Chris Bienemanad070d02014-09-17 20:55:46 +00001538 SinCosCalls.push_back(CI);
1539 } else {
David L. Jonesd21529f2017-01-23 23:16:46 +00001540 if (Func == LibFunc_sinpi)
Chris Bienemanad070d02014-09-17 20:55:46 +00001541 SinCalls.push_back(CI);
David L. Jonesd21529f2017-01-23 23:16:46 +00001542 else if (Func == LibFunc_cospi)
Chris Bienemanad070d02014-09-17 20:55:46 +00001543 CosCalls.push_back(CI);
David L. Jonesd21529f2017-01-23 23:16:46 +00001544 else if (Func == LibFunc_sincospi_stret)
Chris Bienemanad070d02014-09-17 20:55:46 +00001545 SinCosCalls.push_back(CI);
1546 }
1547}
1548
Meador Inge7415f842012-11-25 20:45:27 +00001549//===----------------------------------------------------------------------===//
1550// Integer Library Call Optimizations
1551//===----------------------------------------------------------------------===//
1552
Chris Bienemanad070d02014-09-17 20:55:46 +00001553Value *LibCallSimplifier::optimizeFFS(CallInst *CI, IRBuilder<> &B) {
Chris Bienemanad070d02014-09-17 20:55:46 +00001554 // ffs(x) -> x != 0 ? (i32)llvm.cttz(x)+1 : 0
Davide Italiano890e8502016-12-15 23:11:00 +00001555 Value *Op = CI->getArgOperand(0);
Chris Bienemanad070d02014-09-17 20:55:46 +00001556 Type *ArgType = Op->getType();
Davide Italiano890e8502016-12-15 23:11:00 +00001557 Value *F = Intrinsic::getDeclaration(CI->getCalledFunction()->getParent(),
1558 Intrinsic::cttz, ArgType);
Davide Italianoa1953862015-08-13 20:34:26 +00001559 Value *V = B.CreateCall(F, {Op, B.getTrue()}, "cttz");
Chris Bienemanad070d02014-09-17 20:55:46 +00001560 V = B.CreateAdd(V, ConstantInt::get(V->getType(), 1));
1561 V = B.CreateIntCast(V, B.getInt32Ty(), false);
Meador Ingea0b6d872012-11-26 00:24:07 +00001562
Chris Bienemanad070d02014-09-17 20:55:46 +00001563 Value *Cond = B.CreateICmpNE(Op, Constant::getNullValue(ArgType));
1564 return B.CreateSelect(Cond, V, B.getInt32(0));
1565}
Meador Ingea0b6d872012-11-26 00:24:07 +00001566
Davide Italiano85ad36b2016-12-15 23:45:11 +00001567Value *LibCallSimplifier::optimizeFls(CallInst *CI, IRBuilder<> &B) {
1568 // fls(x) -> (i32)(sizeInBits(x) - llvm.ctlz(x, false))
1569 Value *Op = CI->getArgOperand(0);
1570 Type *ArgType = Op->getType();
1571 Value *F = Intrinsic::getDeclaration(CI->getCalledFunction()->getParent(),
1572 Intrinsic::ctlz, ArgType);
1573 Value *V = B.CreateCall(F, {Op, B.getFalse()}, "ctlz");
1574 V = B.CreateSub(ConstantInt::get(V->getType(), ArgType->getIntegerBitWidth()),
1575 V);
1576 return B.CreateIntCast(V, CI->getType(), false);
1577}
1578
Chris Bienemanad070d02014-09-17 20:55:46 +00001579Value *LibCallSimplifier::optimizeAbs(CallInst *CI, IRBuilder<> &B) {
Chris Bienemanad070d02014-09-17 20:55:46 +00001580 // abs(x) -> x >s -1 ? x : -x
1581 Value *Op = CI->getArgOperand(0);
1582 Value *Pos =
1583 B.CreateICmpSGT(Op, Constant::getAllOnesValue(Op->getType()), "ispos");
1584 Value *Neg = B.CreateNeg(Op, "neg");
1585 return B.CreateSelect(Pos, Op, Neg);
1586}
Meador Inge9a59ab62012-11-26 02:31:59 +00001587
Chris Bienemanad070d02014-09-17 20:55:46 +00001588Value *LibCallSimplifier::optimizeIsDigit(CallInst *CI, IRBuilder<> &B) {
Chris Bienemanad070d02014-09-17 20:55:46 +00001589 // isdigit(c) -> (c-'0') <u 10
1590 Value *Op = CI->getArgOperand(0);
1591 Op = B.CreateSub(Op, B.getInt32('0'), "isdigittmp");
1592 Op = B.CreateICmpULT(Op, B.getInt32(10), "isdigit");
1593 return B.CreateZExt(Op, CI->getType());
1594}
Meador Ingea62a39e2012-11-26 03:10:07 +00001595
Chris Bienemanad070d02014-09-17 20:55:46 +00001596Value *LibCallSimplifier::optimizeIsAscii(CallInst *CI, IRBuilder<> &B) {
Chris Bienemanad070d02014-09-17 20:55:46 +00001597 // isascii(c) -> c <u 128
1598 Value *Op = CI->getArgOperand(0);
1599 Op = B.CreateICmpULT(Op, B.getInt32(128), "isascii");
1600 return B.CreateZExt(Op, CI->getType());
1601}
1602
1603Value *LibCallSimplifier::optimizeToAscii(CallInst *CI, IRBuilder<> &B) {
Chris Bienemanad070d02014-09-17 20:55:46 +00001604 // toascii(c) -> c & 0x7f
1605 return B.CreateAnd(CI->getArgOperand(0),
1606 ConstantInt::get(CI->getType(), 0x7F));
1607}
Meador Inge604937d2012-11-26 03:38:52 +00001608
Meador Inge08ca1152012-11-26 20:37:20 +00001609//===----------------------------------------------------------------------===//
1610// Formatting and IO Library Call Optimizations
1611//===----------------------------------------------------------------------===//
1612
Chris Bienemanad070d02014-09-17 20:55:46 +00001613static bool isReportingError(Function *Callee, CallInst *CI, int StreamArg);
Hal Finkel66cd3f12013-11-17 02:06:35 +00001614
Chris Bienemanad070d02014-09-17 20:55:46 +00001615Value *LibCallSimplifier::optimizeErrorReporting(CallInst *CI, IRBuilder<> &B,
1616 int StreamArg) {
Ahmed Bougachad765a822016-04-27 19:04:35 +00001617 Function *Callee = CI->getCalledFunction();
Chris Bienemanad070d02014-09-17 20:55:46 +00001618 // Error reporting calls should be cold, mark them as such.
1619 // This applies even to non-builtin calls: it is only a hint and applies to
1620 // functions that the frontend might not understand as builtins.
Hal Finkel66cd3f12013-11-17 02:06:35 +00001621
Chris Bienemanad070d02014-09-17 20:55:46 +00001622 // This heuristic was suggested in:
1623 // Improving Static Branch Prediction in a Compiler
1624 // Brian L. Deitrich, Ben-Chung Cheng, Wen-mei W. Hwu
1625 // Proceedings of PACT'98, Oct. 1998, IEEE
Chris Bienemanad070d02014-09-17 20:55:46 +00001626 if (!CI->hasFnAttr(Attribute::Cold) &&
1627 isReportingError(Callee, CI, StreamArg)) {
Reid Klecknerb5180542017-03-21 16:57:19 +00001628 CI->addAttribute(AttributeList::FunctionIndex, Attribute::Cold);
Chris Bienemanad070d02014-09-17 20:55:46 +00001629 }
Hal Finkel66cd3f12013-11-17 02:06:35 +00001630
Chris Bienemanad070d02014-09-17 20:55:46 +00001631 return nullptr;
1632}
1633
1634static bool isReportingError(Function *Callee, CallInst *CI, int StreamArg) {
Davide Italianoe84d4da2015-11-02 22:33:26 +00001635 if (!ColdErrorCalls || !Callee || !Callee->isDeclaration())
Chris Bienemanad070d02014-09-17 20:55:46 +00001636 return false;
1637
1638 if (StreamArg < 0)
1639 return true;
1640
1641 // These functions might be considered cold, but only if their stream
1642 // argument is stderr.
1643
1644 if (StreamArg >= (int)CI->getNumArgOperands())
1645 return false;
1646 LoadInst *LI = dyn_cast<LoadInst>(CI->getArgOperand(StreamArg));
1647 if (!LI)
1648 return false;
1649 GlobalVariable *GV = dyn_cast<GlobalVariable>(LI->getPointerOperand());
1650 if (!GV || !GV->isDeclaration())
1651 return false;
1652 return GV->getName() == "stderr";
1653}
1654
1655Value *LibCallSimplifier::optimizePrintFString(CallInst *CI, IRBuilder<> &B) {
1656 // Check for a fixed format string.
1657 StringRef FormatStr;
1658 if (!getConstantStringInfo(CI->getArgOperand(0), FormatStr))
Craig Topperf40110f2014-04-25 05:29:35 +00001659 return nullptr;
Hal Finkel66cd3f12013-11-17 02:06:35 +00001660
Chris Bienemanad070d02014-09-17 20:55:46 +00001661 // Empty format string -> noop.
1662 if (FormatStr.empty()) // Tolerate printf's declared void.
1663 return CI->use_empty() ? (Value *)CI : ConstantInt::get(CI->getType(), 0);
Hal Finkel66cd3f12013-11-17 02:06:35 +00001664
Chris Bienemanad070d02014-09-17 20:55:46 +00001665 // Do not do any of the following transformations if the printf return value
1666 // is used, in general the printf return value is not compatible with either
1667 // putchar() or puts().
1668 if (!CI->use_empty())
Craig Topperf40110f2014-04-25 05:29:35 +00001669 return nullptr;
Chris Bienemanad070d02014-09-17 20:55:46 +00001670
Joerg Sonnenberger8ffe7ab2016-05-09 14:36:16 +00001671 // printf("x") -> putchar('x'), even for "%" and "%%".
1672 if (FormatStr.size() == 1 || FormatStr == "%%")
Davide Italianod4f5a052016-04-03 01:46:52 +00001673 return emitPutChar(B.getInt32(FormatStr[0]), B, TLI);
Meador Inge08ca1152012-11-26 20:37:20 +00001674
Davide Italiano6db1dcb2016-03-28 15:54:01 +00001675 // printf("%s", "a") --> putchar('a')
1676 if (FormatStr == "%s" && CI->getNumArgOperands() > 1) {
1677 StringRef ChrStr;
1678 if (!getConstantStringInfo(CI->getOperand(1), ChrStr))
1679 return nullptr;
1680 if (ChrStr.size() != 1)
1681 return nullptr;
Davide Italianod4f5a052016-04-03 01:46:52 +00001682 return emitPutChar(B.getInt32(ChrStr[0]), B, TLI);
Davide Italiano6db1dcb2016-03-28 15:54:01 +00001683 }
1684
Chris Bienemanad070d02014-09-17 20:55:46 +00001685 // printf("foo\n") --> puts("foo")
1686 if (FormatStr[FormatStr.size() - 1] == '\n' &&
1687 FormatStr.find('%') == StringRef::npos) { // No format characters.
1688 // Create a string literal with no \n on it. We expect the constant merge
1689 // pass to be run after this pass, to merge duplicate strings.
1690 FormatStr = FormatStr.drop_back();
1691 Value *GV = B.CreateGlobalString(FormatStr, "str");
Davide Italianod4f5a052016-04-03 01:46:52 +00001692 return emitPutS(GV, B, TLI);
Chris Bienemanad070d02014-09-17 20:55:46 +00001693 }
Meador Inge08ca1152012-11-26 20:37:20 +00001694
Chris Bienemanad070d02014-09-17 20:55:46 +00001695 // Optimize specific format strings.
1696 // printf("%c", chr) --> putchar(chr)
1697 if (FormatStr == "%c" && CI->getNumArgOperands() > 1 &&
Davide Italianod4f5a052016-04-03 01:46:52 +00001698 CI->getArgOperand(1)->getType()->isIntegerTy())
1699 return emitPutChar(CI->getArgOperand(1), B, TLI);
Chris Bienemanad070d02014-09-17 20:55:46 +00001700
1701 // printf("%s\n", str) --> puts(str)
1702 if (FormatStr == "%s\n" && CI->getNumArgOperands() > 1 &&
Davide Italianod4f5a052016-04-03 01:46:52 +00001703 CI->getArgOperand(1)->getType()->isPointerTy())
Sanjay Pateld3112a52016-01-19 19:46:10 +00001704 return emitPutS(CI->getArgOperand(1), B, TLI);
Chris Bienemanad070d02014-09-17 20:55:46 +00001705 return nullptr;
1706}
1707
1708Value *LibCallSimplifier::optimizePrintF(CallInst *CI, IRBuilder<> &B) {
1709
1710 Function *Callee = CI->getCalledFunction();
Chris Bienemanad070d02014-09-17 20:55:46 +00001711 FunctionType *FT = Callee->getFunctionType();
Chris Bienemanad070d02014-09-17 20:55:46 +00001712 if (Value *V = optimizePrintFString(CI, B)) {
1713 return V;
1714 }
1715
1716 // printf(format, ...) -> iprintf(format, ...) if no floating point
1717 // arguments.
David L. Jonesd21529f2017-01-23 23:16:46 +00001718 if (TLI->has(LibFunc_iprintf) && !callHasFloatingPointArgument(CI)) {
Chris Bienemanad070d02014-09-17 20:55:46 +00001719 Module *M = B.GetInsertBlock()->getParent()->getParent();
1720 Constant *IPrintFFn =
Meador Inge08ca1152012-11-26 20:37:20 +00001721 M->getOrInsertFunction("iprintf", FT, Callee->getAttributes());
Chris Bienemanad070d02014-09-17 20:55:46 +00001722 CallInst *New = cast<CallInst>(CI->clone());
1723 New->setCalledFunction(IPrintFFn);
1724 B.Insert(New);
1725 return New;
Meador Inge08ca1152012-11-26 20:37:20 +00001726 }
Chris Bienemanad070d02014-09-17 20:55:46 +00001727 return nullptr;
1728}
Meador Inge08ca1152012-11-26 20:37:20 +00001729
Chris Bienemanad070d02014-09-17 20:55:46 +00001730Value *LibCallSimplifier::optimizeSPrintFString(CallInst *CI, IRBuilder<> &B) {
1731 // Check for a fixed format string.
1732 StringRef FormatStr;
1733 if (!getConstantStringInfo(CI->getArgOperand(1), FormatStr))
Craig Topperf40110f2014-04-25 05:29:35 +00001734 return nullptr;
Meador Inge25c9b3b2012-11-27 05:57:54 +00001735
Chris Bienemanad070d02014-09-17 20:55:46 +00001736 // If we just have a format string (nothing else crazy) transform it.
1737 if (CI->getNumArgOperands() == 2) {
1738 // Make sure there's no % in the constant array. We could try to handle
1739 // %% -> % in the future if we cared.
1740 for (unsigned i = 0, e = FormatStr.size(); i != e; ++i)
1741 if (FormatStr[i] == '%')
1742 return nullptr; // we found a format specifier, bail out.
Hal Finkel66cd3f12013-11-17 02:06:35 +00001743
Chris Bienemanad070d02014-09-17 20:55:46 +00001744 // sprintf(str, fmt) -> llvm.memcpy(str, fmt, strlen(fmt)+1, 1)
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001745 B.CreateMemCpy(CI->getArgOperand(0), CI->getArgOperand(1),
1746 ConstantInt::get(DL.getIntPtrType(CI->getContext()),
1747 FormatStr.size() + 1),
Pete Cooper67cf9a72015-11-19 05:56:52 +00001748 1); // Copy the null byte.
Chris Bienemanad070d02014-09-17 20:55:46 +00001749 return ConstantInt::get(CI->getType(), FormatStr.size());
Meador Ingef8e72502012-11-29 15:45:43 +00001750 }
Meador Ingef8e72502012-11-29 15:45:43 +00001751
Chris Bienemanad070d02014-09-17 20:55:46 +00001752 // The remaining optimizations require the format string to be "%s" or "%c"
1753 // and have an extra operand.
1754 if (FormatStr.size() != 2 || FormatStr[0] != '%' ||
1755 CI->getNumArgOperands() < 3)
Craig Topperf40110f2014-04-25 05:29:35 +00001756 return nullptr;
Meador Inge75798bb2012-11-29 19:15:17 +00001757
Chris Bienemanad070d02014-09-17 20:55:46 +00001758 // Decode the second character of the format string.
1759 if (FormatStr[1] == 'c') {
1760 // sprintf(dst, "%c", chr) --> *(i8*)dst = chr; *((i8*)dst+1) = 0
1761 if (!CI->getArgOperand(2)->getType()->isIntegerTy())
1762 return nullptr;
1763 Value *V = B.CreateTrunc(CI->getArgOperand(2), B.getInt8Ty(), "char");
Sanjay Pateld3112a52016-01-19 19:46:10 +00001764 Value *Ptr = castToCStr(CI->getArgOperand(0), B);
Chris Bienemanad070d02014-09-17 20:55:46 +00001765 B.CreateStore(V, Ptr);
David Blaikie3909da72015-03-30 20:42:56 +00001766 Ptr = B.CreateGEP(B.getInt8Ty(), Ptr, B.getInt32(1), "nul");
Chris Bienemanad070d02014-09-17 20:55:46 +00001767 B.CreateStore(B.getInt8(0), Ptr);
Meador Ingedf796f82012-10-13 16:45:24 +00001768
Chris Bienemanad070d02014-09-17 20:55:46 +00001769 return ConstantInt::get(CI->getType(), 1);
Meador Ingedf796f82012-10-13 16:45:24 +00001770 }
1771
Chris Bienemanad070d02014-09-17 20:55:46 +00001772 if (FormatStr[1] == 's') {
Chris Bienemanad070d02014-09-17 20:55:46 +00001773 // sprintf(dest, "%s", str) -> llvm.memcpy(dest, str, strlen(str)+1, 1)
1774 if (!CI->getArgOperand(2)->getType()->isPointerTy())
1775 return nullptr;
1776
Sanjay Pateld3112a52016-01-19 19:46:10 +00001777 Value *Len = emitStrLen(CI->getArgOperand(2), B, DL, TLI);
Chris Bienemanad070d02014-09-17 20:55:46 +00001778 if (!Len)
1779 return nullptr;
David Majnemerabb9f552016-04-26 21:04:47 +00001780 Value *IncLen =
1781 B.CreateAdd(Len, ConstantInt::get(Len->getType(), 1), "leninc");
1782 B.CreateMemCpy(CI->getArgOperand(0), CI->getArgOperand(2), IncLen, 1);
Chris Bienemanad070d02014-09-17 20:55:46 +00001783
1784 // The sprintf result is the unincremented number of bytes in the string.
1785 return B.CreateIntCast(Len, CI->getType(), false);
1786 }
1787 return nullptr;
1788}
1789
1790Value *LibCallSimplifier::optimizeSPrintF(CallInst *CI, IRBuilder<> &B) {
1791 Function *Callee = CI->getCalledFunction();
Chris Bienemanad070d02014-09-17 20:55:46 +00001792 FunctionType *FT = Callee->getFunctionType();
Chris Bienemanad070d02014-09-17 20:55:46 +00001793 if (Value *V = optimizeSPrintFString(CI, B)) {
1794 return V;
1795 }
1796
1797 // sprintf(str, format, ...) -> siprintf(str, format, ...) if no floating
1798 // point arguments.
David L. Jonesd21529f2017-01-23 23:16:46 +00001799 if (TLI->has(LibFunc_siprintf) && !callHasFloatingPointArgument(CI)) {
Chris Bienemanad070d02014-09-17 20:55:46 +00001800 Module *M = B.GetInsertBlock()->getParent()->getParent();
1801 Constant *SIPrintFFn =
1802 M->getOrInsertFunction("siprintf", FT, Callee->getAttributes());
1803 CallInst *New = cast<CallInst>(CI->clone());
1804 New->setCalledFunction(SIPrintFFn);
1805 B.Insert(New);
1806 return New;
1807 }
1808 return nullptr;
1809}
1810
1811Value *LibCallSimplifier::optimizeFPrintFString(CallInst *CI, IRBuilder<> &B) {
1812 optimizeErrorReporting(CI, B, 0);
1813
1814 // All the optimizations depend on the format string.
1815 StringRef FormatStr;
1816 if (!getConstantStringInfo(CI->getArgOperand(1), FormatStr))
1817 return nullptr;
1818
1819 // Do not do any of the following transformations if the fprintf return
1820 // value is used, in general the fprintf return value is not compatible
1821 // with fwrite(), fputc() or fputs().
1822 if (!CI->use_empty())
1823 return nullptr;
1824
1825 // fprintf(F, "foo") --> fwrite("foo", 3, 1, F)
1826 if (CI->getNumArgOperands() == 2) {
1827 for (unsigned i = 0, e = FormatStr.size(); i != e; ++i)
1828 if (FormatStr[i] == '%') // Could handle %% -> % if we cared.
1829 return nullptr; // We found a format specifier.
1830
Sanjay Pateld3112a52016-01-19 19:46:10 +00001831 return emitFWrite(
Chris Bienemanad070d02014-09-17 20:55:46 +00001832 CI->getArgOperand(1),
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001833 ConstantInt::get(DL.getIntPtrType(CI->getContext()), FormatStr.size()),
Chris Bienemanad070d02014-09-17 20:55:46 +00001834 CI->getArgOperand(0), B, DL, TLI);
1835 }
1836
1837 // The remaining optimizations require the format string to be "%s" or "%c"
1838 // and have an extra operand.
1839 if (FormatStr.size() != 2 || FormatStr[0] != '%' ||
1840 CI->getNumArgOperands() < 3)
1841 return nullptr;
1842
1843 // Decode the second character of the format string.
1844 if (FormatStr[1] == 'c') {
1845 // fprintf(F, "%c", chr) --> fputc(chr, F)
1846 if (!CI->getArgOperand(2)->getType()->isIntegerTy())
1847 return nullptr;
Sanjay Pateld3112a52016-01-19 19:46:10 +00001848 return emitFPutC(CI->getArgOperand(2), CI->getArgOperand(0), B, TLI);
Chris Bienemanad070d02014-09-17 20:55:46 +00001849 }
1850
1851 if (FormatStr[1] == 's') {
1852 // fprintf(F, "%s", str) --> fputs(str, F)
1853 if (!CI->getArgOperand(2)->getType()->isPointerTy())
1854 return nullptr;
Sanjay Pateld3112a52016-01-19 19:46:10 +00001855 return emitFPutS(CI->getArgOperand(2), CI->getArgOperand(0), B, TLI);
Chris Bienemanad070d02014-09-17 20:55:46 +00001856 }
1857 return nullptr;
1858}
1859
1860Value *LibCallSimplifier::optimizeFPrintF(CallInst *CI, IRBuilder<> &B) {
1861 Function *Callee = CI->getCalledFunction();
Chris Bienemanad070d02014-09-17 20:55:46 +00001862 FunctionType *FT = Callee->getFunctionType();
Chris Bienemanad070d02014-09-17 20:55:46 +00001863 if (Value *V = optimizeFPrintFString(CI, B)) {
1864 return V;
1865 }
1866
1867 // fprintf(stream, format, ...) -> fiprintf(stream, format, ...) if no
1868 // floating point arguments.
David L. Jonesd21529f2017-01-23 23:16:46 +00001869 if (TLI->has(LibFunc_fiprintf) && !callHasFloatingPointArgument(CI)) {
Chris Bienemanad070d02014-09-17 20:55:46 +00001870 Module *M = B.GetInsertBlock()->getParent()->getParent();
1871 Constant *FIPrintFFn =
1872 M->getOrInsertFunction("fiprintf", FT, Callee->getAttributes());
1873 CallInst *New = cast<CallInst>(CI->clone());
1874 New->setCalledFunction(FIPrintFFn);
1875 B.Insert(New);
1876 return New;
1877 }
1878 return nullptr;
1879}
1880
1881Value *LibCallSimplifier::optimizeFWrite(CallInst *CI, IRBuilder<> &B) {
1882 optimizeErrorReporting(CI, B, 3);
1883
Chris Bienemanad070d02014-09-17 20:55:46 +00001884 // Get the element size and count.
1885 ConstantInt *SizeC = dyn_cast<ConstantInt>(CI->getArgOperand(1));
1886 ConstantInt *CountC = dyn_cast<ConstantInt>(CI->getArgOperand(2));
1887 if (!SizeC || !CountC)
1888 return nullptr;
1889 uint64_t Bytes = SizeC->getZExtValue() * CountC->getZExtValue();
1890
1891 // If this is writing zero records, remove the call (it's a noop).
1892 if (Bytes == 0)
1893 return ConstantInt::get(CI->getType(), 0);
1894
1895 // If this is writing one byte, turn it into fputc.
1896 // This optimisation is only valid, if the return value is unused.
1897 if (Bytes == 1 && CI->use_empty()) { // fwrite(S,1,1,F) -> fputc(S[0],F)
Sanjay Pateld3112a52016-01-19 19:46:10 +00001898 Value *Char = B.CreateLoad(castToCStr(CI->getArgOperand(0), B), "char");
1899 Value *NewCI = emitFPutC(Char, CI->getArgOperand(3), B, TLI);
Chris Bienemanad070d02014-09-17 20:55:46 +00001900 return NewCI ? ConstantInt::get(CI->getType(), 1) : nullptr;
1901 }
1902
1903 return nullptr;
1904}
1905
1906Value *LibCallSimplifier::optimizeFPuts(CallInst *CI, IRBuilder<> &B) {
1907 optimizeErrorReporting(CI, B, 1);
1908
Sjoerd Meijer7435a912016-07-07 14:31:19 +00001909 // Don't rewrite fputs to fwrite when optimising for size because fwrite
1910 // requires more arguments and thus extra MOVs are required.
1911 if (CI->getParent()->getParent()->optForSize())
1912 return nullptr;
1913
Ahmed Bougachad765a822016-04-27 19:04:35 +00001914 // We can't optimize if return value is used.
1915 if (!CI->use_empty())
Chris Bienemanad070d02014-09-17 20:55:46 +00001916 return nullptr;
1917
1918 // fputs(s,F) --> fwrite(s,1,strlen(s),F)
1919 uint64_t Len = GetStringLength(CI->getArgOperand(0));
1920 if (!Len)
1921 return nullptr;
1922
1923 // Known to have no uses (see above).
Sanjay Pateld3112a52016-01-19 19:46:10 +00001924 return emitFWrite(
Chris Bienemanad070d02014-09-17 20:55:46 +00001925 CI->getArgOperand(0),
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001926 ConstantInt::get(DL.getIntPtrType(CI->getContext()), Len - 1),
Chris Bienemanad070d02014-09-17 20:55:46 +00001927 CI->getArgOperand(1), B, DL, TLI);
1928}
1929
1930Value *LibCallSimplifier::optimizePuts(CallInst *CI, IRBuilder<> &B) {
Chris Bienemanad070d02014-09-17 20:55:46 +00001931 // Check for a constant string.
1932 StringRef Str;
1933 if (!getConstantStringInfo(CI->getArgOperand(0), Str))
1934 return nullptr;
1935
1936 if (Str.empty() && CI->use_empty()) {
1937 // puts("") -> putchar('\n')
Sanjay Pateld3112a52016-01-19 19:46:10 +00001938 Value *Res = emitPutChar(B.getInt32('\n'), B, TLI);
Chris Bienemanad070d02014-09-17 20:55:46 +00001939 if (CI->use_empty() || !Res)
1940 return Res;
1941 return B.CreateIntCast(Res, CI->getType(), true);
1942 }
1943
1944 return nullptr;
1945}
1946
1947bool LibCallSimplifier::hasFloatVersion(StringRef FuncName) {
David L. Jonesd21529f2017-01-23 23:16:46 +00001948 LibFunc Func;
Meador Inge20255ef2013-03-12 00:08:29 +00001949 SmallString<20> FloatFuncName = FuncName;
1950 FloatFuncName += 'f';
1951 if (TLI->getLibFunc(FloatFuncName, Func))
1952 return TLI->has(Func);
1953 return false;
1954}
Meador Inge7fb2f732012-10-13 16:45:32 +00001955
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00001956Value *LibCallSimplifier::optimizeStringMemoryLibCall(CallInst *CI,
1957 IRBuilder<> &Builder) {
David L. Jonesd21529f2017-01-23 23:16:46 +00001958 LibFunc Func;
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00001959 Function *Callee = CI->getCalledFunction();
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00001960 // Check for string/memory library functions.
Ahmed Bougachad765a822016-04-27 19:04:35 +00001961 if (TLI->getLibFunc(*Callee, Func) && TLI->has(Func)) {
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00001962 // Make sure we never change the calling convention.
1963 assert((ignoreCallingConv(Func) ||
Sam Parker214f7bf2016-09-13 12:10:14 +00001964 isCallingConvCCompatible(CI)) &&
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00001965 "Optimizing string/memory libcall would change the calling convention");
1966 switch (Func) {
David L. Jonesd21529f2017-01-23 23:16:46 +00001967 case LibFunc_strcat:
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00001968 return optimizeStrCat(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00001969 case LibFunc_strncat:
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00001970 return optimizeStrNCat(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00001971 case LibFunc_strchr:
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00001972 return optimizeStrChr(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00001973 case LibFunc_strrchr:
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00001974 return optimizeStrRChr(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00001975 case LibFunc_strcmp:
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00001976 return optimizeStrCmp(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00001977 case LibFunc_strncmp:
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00001978 return optimizeStrNCmp(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00001979 case LibFunc_strcpy:
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00001980 return optimizeStrCpy(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00001981 case LibFunc_stpcpy:
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00001982 return optimizeStpCpy(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00001983 case LibFunc_strncpy:
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00001984 return optimizeStrNCpy(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00001985 case LibFunc_strlen:
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00001986 return optimizeStrLen(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00001987 case LibFunc_strpbrk:
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00001988 return optimizeStrPBrk(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00001989 case LibFunc_strtol:
1990 case LibFunc_strtod:
1991 case LibFunc_strtof:
1992 case LibFunc_strtoul:
1993 case LibFunc_strtoll:
1994 case LibFunc_strtold:
1995 case LibFunc_strtoull:
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00001996 return optimizeStrTo(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00001997 case LibFunc_strspn:
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00001998 return optimizeStrSpn(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00001999 case LibFunc_strcspn:
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00002000 return optimizeStrCSpn(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002001 case LibFunc_strstr:
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00002002 return optimizeStrStr(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002003 case LibFunc_memchr:
Benjamin Kramer691363e2015-03-21 15:36:21 +00002004 return optimizeMemChr(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002005 case LibFunc_memcmp:
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00002006 return optimizeMemCmp(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002007 case LibFunc_memcpy:
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00002008 return optimizeMemCpy(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002009 case LibFunc_memmove:
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00002010 return optimizeMemMove(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002011 case LibFunc_memset:
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00002012 return optimizeMemSet(CI, Builder);
2013 default:
2014 break;
2015 }
2016 }
2017 return nullptr;
2018}
2019
Chris Bienemanad070d02014-09-17 20:55:46 +00002020Value *LibCallSimplifier::optimizeCall(CallInst *CI) {
2021 if (CI->isNoBuiltin())
2022 return nullptr;
Meador Inge4d2827c2012-11-11 05:11:20 +00002023
David L. Jonesd21529f2017-01-23 23:16:46 +00002024 LibFunc Func;
Meador Inge20255ef2013-03-12 00:08:29 +00002025 Function *Callee = CI->getCalledFunction();
2026 StringRef FuncName = Callee->getName();
David Majnemerb70e23c2016-01-06 05:01:34 +00002027
2028 SmallVector<OperandBundleDef, 2> OpBundles;
2029 CI->getOperandBundlesAsDefs(OpBundles);
2030 IRBuilder<> Builder(CI, /*FPMathTag=*/nullptr, OpBundles);
Sam Parker214f7bf2016-09-13 12:10:14 +00002031 bool isCallingConvC = isCallingConvCCompatible(CI);
Meador Inge20255ef2013-03-12 00:08:29 +00002032
Sanjay Pateld1f4f032016-01-19 18:38:52 +00002033 // Command-line parameter overrides instruction attribute.
Sanjay Patela92fa442014-10-22 15:29:23 +00002034 if (EnableUnsafeFPShrink.getNumOccurrences() > 0)
2035 UnsafeFPShrink = EnableUnsafeFPShrink;
Sanjay Pateld1f4f032016-01-19 18:38:52 +00002036 else if (isa<FPMathOperator>(CI) && CI->hasUnsafeAlgebra())
Davide Italianoa904e522015-10-29 02:58:44 +00002037 UnsafeFPShrink = true;
Sanjay Patela92fa442014-10-22 15:29:23 +00002038
Sanjay Patel848309d2014-10-23 21:52:45 +00002039 // First, check for intrinsics.
Meador Inge20255ef2013-03-12 00:08:29 +00002040 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(CI)) {
Chris Bienemanad070d02014-09-17 20:55:46 +00002041 if (!isCallingConvC)
2042 return nullptr;
Meador Inge20255ef2013-03-12 00:08:29 +00002043 switch (II->getIntrinsicID()) {
2044 case Intrinsic::pow:
Chris Bienemanad070d02014-09-17 20:55:46 +00002045 return optimizePow(CI, Builder);
Meador Inge20255ef2013-03-12 00:08:29 +00002046 case Intrinsic::exp2:
Chris Bienemanad070d02014-09-17 20:55:46 +00002047 return optimizeExp2(CI, Builder);
Davide Italianob8b71332015-11-29 20:58:04 +00002048 case Intrinsic::log:
2049 return optimizeLog(CI, Builder);
Sanjay Patelc699a612014-10-16 18:48:17 +00002050 case Intrinsic::sqrt:
2051 return optimizeSqrt(CI, Builder);
Sanjay Patel980b2802016-01-26 16:17:24 +00002052 // TODO: Use foldMallocMemset() with memset intrinsic.
Meador Inge20255ef2013-03-12 00:08:29 +00002053 default:
Chris Bienemanad070d02014-09-17 20:55:46 +00002054 return nullptr;
Meador Inge20255ef2013-03-12 00:08:29 +00002055 }
2056 }
2057
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002058 // Also try to simplify calls to fortified library functions.
2059 if (Value *SimplifiedFortifiedCI = FortifiedSimplifier.optimizeCall(CI)) {
2060 // Try to further simplify the result.
Ahmed Bougacha71d7b182015-01-14 00:55:05 +00002061 CallInst *SimplifiedCI = dyn_cast<CallInst>(SimplifiedFortifiedCI);
Bruno Cardoso Lopesb491a2d2015-10-01 22:43:53 +00002062 if (SimplifiedCI && SimplifiedCI->getCalledFunction()) {
2063 // Use an IR Builder from SimplifiedCI if available instead of CI
2064 // to guarantee we reach all uses we might replace later on.
2065 IRBuilder<> TmpBuilder(SimplifiedCI);
2066 if (Value *V = optimizeStringMemoryLibCall(SimplifiedCI, TmpBuilder)) {
Ahmed Bougacha1ac93562015-01-27 21:52:16 +00002067 // If we were able to further simplify, remove the now redundant call.
2068 SimplifiedCI->replaceAllUsesWith(V);
2069 SimplifiedCI->eraseFromParent();
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002070 return V;
Ahmed Bougacha1ac93562015-01-27 21:52:16 +00002071 }
Bruno Cardoso Lopesb491a2d2015-10-01 22:43:53 +00002072 }
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002073 return SimplifiedFortifiedCI;
2074 }
2075
Meador Inge20255ef2013-03-12 00:08:29 +00002076 // Then check for known library functions.
Ahmed Bougachad765a822016-04-27 19:04:35 +00002077 if (TLI->getLibFunc(*Callee, Func) && TLI->has(Func)) {
Chris Bienemanad070d02014-09-17 20:55:46 +00002078 // We never change the calling convention.
2079 if (!ignoreCallingConv(Func) && !isCallingConvC)
2080 return nullptr;
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00002081 if (Value *V = optimizeStringMemoryLibCall(CI, Builder))
2082 return V;
Meador Inge20255ef2013-03-12 00:08:29 +00002083 switch (Func) {
David L. Jonesd21529f2017-01-23 23:16:46 +00002084 case LibFunc_cosf:
2085 case LibFunc_cos:
2086 case LibFunc_cosl:
Chris Bienemanad070d02014-09-17 20:55:46 +00002087 return optimizeCos(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002088 case LibFunc_sinpif:
2089 case LibFunc_sinpi:
2090 case LibFunc_cospif:
2091 case LibFunc_cospi:
Chris Bienemanad070d02014-09-17 20:55:46 +00002092 return optimizeSinCosPi(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002093 case LibFunc_powf:
2094 case LibFunc_pow:
2095 case LibFunc_powl:
Chris Bienemanad070d02014-09-17 20:55:46 +00002096 return optimizePow(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002097 case LibFunc_exp2l:
2098 case LibFunc_exp2:
2099 case LibFunc_exp2f:
Chris Bienemanad070d02014-09-17 20:55:46 +00002100 return optimizeExp2(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002101 case LibFunc_fabsf:
2102 case LibFunc_fabs:
2103 case LibFunc_fabsl:
Matt Arsenault954a6242017-01-23 23:55:08 +00002104 return replaceUnaryCall(CI, Builder, Intrinsic::fabs);
David L. Jonesd21529f2017-01-23 23:16:46 +00002105 case LibFunc_sqrtf:
2106 case LibFunc_sqrt:
2107 case LibFunc_sqrtl:
Sanjay Patelc699a612014-10-16 18:48:17 +00002108 return optimizeSqrt(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002109 case LibFunc_ffs:
2110 case LibFunc_ffsl:
2111 case LibFunc_ffsll:
Chris Bienemanad070d02014-09-17 20:55:46 +00002112 return optimizeFFS(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002113 case LibFunc_fls:
2114 case LibFunc_flsl:
2115 case LibFunc_flsll:
Davide Italiano85ad36b2016-12-15 23:45:11 +00002116 return optimizeFls(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002117 case LibFunc_abs:
2118 case LibFunc_labs:
2119 case LibFunc_llabs:
Chris Bienemanad070d02014-09-17 20:55:46 +00002120 return optimizeAbs(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002121 case LibFunc_isdigit:
Chris Bienemanad070d02014-09-17 20:55:46 +00002122 return optimizeIsDigit(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002123 case LibFunc_isascii:
Chris Bienemanad070d02014-09-17 20:55:46 +00002124 return optimizeIsAscii(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002125 case LibFunc_toascii:
Chris Bienemanad070d02014-09-17 20:55:46 +00002126 return optimizeToAscii(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002127 case LibFunc_printf:
Chris Bienemanad070d02014-09-17 20:55:46 +00002128 return optimizePrintF(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002129 case LibFunc_sprintf:
Chris Bienemanad070d02014-09-17 20:55:46 +00002130 return optimizeSPrintF(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002131 case LibFunc_fprintf:
Chris Bienemanad070d02014-09-17 20:55:46 +00002132 return optimizeFPrintF(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002133 case LibFunc_fwrite:
Chris Bienemanad070d02014-09-17 20:55:46 +00002134 return optimizeFWrite(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002135 case LibFunc_fputs:
Chris Bienemanad070d02014-09-17 20:55:46 +00002136 return optimizeFPuts(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002137 case LibFunc_log:
2138 case LibFunc_log10:
2139 case LibFunc_log1p:
2140 case LibFunc_log2:
2141 case LibFunc_logb:
Davide Italianob8b71332015-11-29 20:58:04 +00002142 return optimizeLog(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002143 case LibFunc_puts:
Chris Bienemanad070d02014-09-17 20:55:46 +00002144 return optimizePuts(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002145 case LibFunc_tan:
2146 case LibFunc_tanf:
2147 case LibFunc_tanl:
Davide Italiano51507d22015-11-04 23:36:56 +00002148 return optimizeTan(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002149 case LibFunc_perror:
Chris Bienemanad070d02014-09-17 20:55:46 +00002150 return optimizeErrorReporting(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002151 case LibFunc_vfprintf:
2152 case LibFunc_fiprintf:
Chris Bienemanad070d02014-09-17 20:55:46 +00002153 return optimizeErrorReporting(CI, Builder, 0);
David L. Jonesd21529f2017-01-23 23:16:46 +00002154 case LibFunc_fputc:
Chris Bienemanad070d02014-09-17 20:55:46 +00002155 return optimizeErrorReporting(CI, Builder, 1);
David L. Jonesd21529f2017-01-23 23:16:46 +00002156 case LibFunc_ceil:
Matt Arsenault954a6242017-01-23 23:55:08 +00002157 return replaceUnaryCall(CI, Builder, Intrinsic::ceil);
David L. Jonesd21529f2017-01-23 23:16:46 +00002158 case LibFunc_floor:
Matt Arsenault954a6242017-01-23 23:55:08 +00002159 return replaceUnaryCall(CI, Builder, Intrinsic::floor);
David L. Jonesd21529f2017-01-23 23:16:46 +00002160 case LibFunc_round:
Matt Arsenault954a6242017-01-23 23:55:08 +00002161 return replaceUnaryCall(CI, Builder, Intrinsic::round);
David L. Jonesd21529f2017-01-23 23:16:46 +00002162 case LibFunc_nearbyint:
Matt Arsenault954a6242017-01-23 23:55:08 +00002163 return replaceUnaryCall(CI, Builder, Intrinsic::nearbyint);
Joerg Sonnenberger28bed102017-03-31 19:58:07 +00002164 case LibFunc_rint:
2165 return replaceUnaryCall(CI, Builder, Intrinsic::rint);
David L. Jonesd21529f2017-01-23 23:16:46 +00002166 case LibFunc_trunc:
Matt Arsenault954a6242017-01-23 23:55:08 +00002167 return replaceUnaryCall(CI, Builder, Intrinsic::trunc);
David L. Jonesd21529f2017-01-23 23:16:46 +00002168 case LibFunc_acos:
2169 case LibFunc_acosh:
2170 case LibFunc_asin:
2171 case LibFunc_asinh:
2172 case LibFunc_atan:
2173 case LibFunc_atanh:
2174 case LibFunc_cbrt:
2175 case LibFunc_cosh:
2176 case LibFunc_exp:
2177 case LibFunc_exp10:
2178 case LibFunc_expm1:
2179 case LibFunc_sin:
2180 case LibFunc_sinh:
2181 case LibFunc_tanh:
Chris Bienemanad070d02014-09-17 20:55:46 +00002182 if (UnsafeFPShrink && hasFloatVersion(FuncName))
2183 return optimizeUnaryDoubleFP(CI, Builder, true);
2184 return nullptr;
David L. Jonesd21529f2017-01-23 23:16:46 +00002185 case LibFunc_copysign:
Chris Bienemanad070d02014-09-17 20:55:46 +00002186 if (hasFloatVersion(FuncName))
2187 return optimizeBinaryDoubleFP(CI, Builder);
2188 return nullptr;
David L. Jonesd21529f2017-01-23 23:16:46 +00002189 case LibFunc_fminf:
2190 case LibFunc_fmin:
2191 case LibFunc_fminl:
2192 case LibFunc_fmaxf:
2193 case LibFunc_fmax:
2194 case LibFunc_fmaxl:
Sanjay Patel57fd1dc2015-08-16 20:18:19 +00002195 return optimizeFMinFMax(CI, Builder);
Chris Bienemanad070d02014-09-17 20:55:46 +00002196 default:
2197 return nullptr;
2198 }
Meador Inge20255ef2013-03-12 00:08:29 +00002199 }
Craig Topperf40110f2014-04-25 05:29:35 +00002200 return nullptr;
Meador Ingedf796f82012-10-13 16:45:24 +00002201}
2202
Chandler Carruth92803822015-01-21 02:11:59 +00002203LibCallSimplifier::LibCallSimplifier(
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002204 const DataLayout &DL, const TargetLibraryInfo *TLI,
Chandler Carruth92803822015-01-21 02:11:59 +00002205 function_ref<void(Instruction *, Value *)> Replacer)
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002206 : FortifiedSimplifier(TLI), DL(DL), TLI(TLI), UnsafeFPShrink(false),
Chandler Carruth92803822015-01-21 02:11:59 +00002207 Replacer(Replacer) {}
2208
2209void LibCallSimplifier::replaceAllUsesWith(Instruction *I, Value *With) {
2210 // Indirect through the replacer used in this instance.
2211 Replacer(I, With);
Meador Ingedf796f82012-10-13 16:45:24 +00002212}
2213
Meador Ingedfb08a22013-06-20 19:48:07 +00002214// TODO:
2215// Additional cases that we need to add to this file:
2216//
2217// cbrt:
2218// * cbrt(expN(X)) -> expN(x/3)
2219// * cbrt(sqrt(x)) -> pow(x,1/6)
David Majnemer3354fe42015-08-26 18:30:16 +00002220// * cbrt(cbrt(x)) -> pow(x,1/9)
Meador Ingedfb08a22013-06-20 19:48:07 +00002221//
2222// exp, expf, expl:
2223// * exp(log(x)) -> x
2224//
2225// log, logf, logl:
2226// * log(exp(x)) -> x
Meador Ingedfb08a22013-06-20 19:48:07 +00002227// * log(exp(y)) -> y*log(e)
Meador Ingedfb08a22013-06-20 19:48:07 +00002228// * log(exp10(y)) -> y*log(10)
2229// * log(sqrt(x)) -> 0.5*log(x)
Meador Ingedfb08a22013-06-20 19:48:07 +00002230//
Meador Ingedfb08a22013-06-20 19:48:07 +00002231// pow, powf, powl:
Meador Ingedfb08a22013-06-20 19:48:07 +00002232// * pow(sqrt(x),y) -> pow(x,y*0.5)
2233// * pow(pow(x,y),z)-> pow(x,y*z)
2234//
Meador Ingedfb08a22013-06-20 19:48:07 +00002235// signbit:
2236// * signbit(cnst) -> cnst'
2237// * signbit(nncst) -> 0 (if pstv is a non-negative constant)
2238//
2239// sqrt, sqrtf, sqrtl:
2240// * sqrt(expN(x)) -> expN(x*0.5)
2241// * sqrt(Nroot(x)) -> pow(x,1/(2*N))
2242// * sqrt(pow(x,y)) -> pow(|x|,y*0.5)
2243//
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002244
2245//===----------------------------------------------------------------------===//
2246// Fortified Library Call Optimizations
2247//===----------------------------------------------------------------------===//
2248
2249bool FortifiedLibCallSimplifier::isFortifiedCallFoldable(CallInst *CI,
2250 unsigned ObjSizeOp,
2251 unsigned SizeOp,
2252 bool isString) {
2253 if (CI->getArgOperand(ObjSizeOp) == CI->getArgOperand(SizeOp))
2254 return true;
2255 if (ConstantInt *ObjSizeCI =
2256 dyn_cast<ConstantInt>(CI->getArgOperand(ObjSizeOp))) {
2257 if (ObjSizeCI->isAllOnesValue())
2258 return true;
2259 // If the object size wasn't -1 (unknown), bail out if we were asked to.
2260 if (OnlyLowerUnknownSize)
2261 return false;
2262 if (isString) {
2263 uint64_t Len = GetStringLength(CI->getArgOperand(SizeOp));
2264 // If the length is 0 we don't know how long it is and so we can't
2265 // remove the check.
2266 if (Len == 0)
2267 return false;
2268 return ObjSizeCI->getZExtValue() >= Len;
2269 }
2270 if (ConstantInt *SizeCI = dyn_cast<ConstantInt>(CI->getArgOperand(SizeOp)))
2271 return ObjSizeCI->getZExtValue() >= SizeCI->getZExtValue();
2272 }
2273 return false;
2274}
2275
Sanjay Pateld707db92015-12-31 16:10:49 +00002276Value *FortifiedLibCallSimplifier::optimizeMemCpyChk(CallInst *CI,
2277 IRBuilder<> &B) {
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002278 if (isFortifiedCallFoldable(CI, 3, 2, false)) {
2279 B.CreateMemCpy(CI->getArgOperand(0), CI->getArgOperand(1),
Pete Cooper67cf9a72015-11-19 05:56:52 +00002280 CI->getArgOperand(2), 1);
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002281 return CI->getArgOperand(0);
2282 }
2283 return nullptr;
2284}
2285
Sanjay Pateld707db92015-12-31 16:10:49 +00002286Value *FortifiedLibCallSimplifier::optimizeMemMoveChk(CallInst *CI,
2287 IRBuilder<> &B) {
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002288 if (isFortifiedCallFoldable(CI, 3, 2, false)) {
2289 B.CreateMemMove(CI->getArgOperand(0), CI->getArgOperand(1),
Pete Cooper67cf9a72015-11-19 05:56:52 +00002290 CI->getArgOperand(2), 1);
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002291 return CI->getArgOperand(0);
2292 }
2293 return nullptr;
2294}
2295
Sanjay Pateld707db92015-12-31 16:10:49 +00002296Value *FortifiedLibCallSimplifier::optimizeMemSetChk(CallInst *CI,
2297 IRBuilder<> &B) {
Sanjay Patel980b2802016-01-26 16:17:24 +00002298 // TODO: Try foldMallocMemset() here.
2299
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002300 if (isFortifiedCallFoldable(CI, 3, 2, false)) {
2301 Value *Val = B.CreateIntCast(CI->getArgOperand(1), B.getInt8Ty(), false);
2302 B.CreateMemSet(CI->getArgOperand(0), Val, CI->getArgOperand(2), 1);
2303 return CI->getArgOperand(0);
2304 }
2305 return nullptr;
2306}
2307
Ahmed Bougacha1ac93562015-01-27 21:52:16 +00002308Value *FortifiedLibCallSimplifier::optimizeStrpCpyChk(CallInst *CI,
2309 IRBuilder<> &B,
David L. Jonesd21529f2017-01-23 23:16:46 +00002310 LibFunc Func) {
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002311 Function *Callee = CI->getCalledFunction();
2312 StringRef Name = Callee->getName();
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002313 const DataLayout &DL = CI->getModule()->getDataLayout();
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002314 Value *Dst = CI->getArgOperand(0), *Src = CI->getArgOperand(1),
2315 *ObjSize = CI->getArgOperand(2);
2316
2317 // __stpcpy_chk(x,x,...) -> x+strlen(x)
David L. Jonesd21529f2017-01-23 23:16:46 +00002318 if (Func == LibFunc_stpcpy_chk && !OnlyLowerUnknownSize && Dst == Src) {
Sanjay Pateld3112a52016-01-19 19:46:10 +00002319 Value *StrLen = emitStrLen(Src, B, DL, TLI);
David Blaikieaa41cd52015-04-03 21:33:42 +00002320 return StrLen ? B.CreateInBoundsGEP(B.getInt8Ty(), Dst, StrLen) : nullptr;
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002321 }
2322
2323 // If a) we don't have any length information, or b) we know this will
2324 // fit then just lower to a plain st[rp]cpy. Otherwise we'll keep our
2325 // st[rp]cpy_chk call which may fail at runtime if the size is too long.
2326 // TODO: It might be nice to get a maximum length out of the possible
2327 // string lengths for varying.
David Blaikie65fab6d2015-04-03 21:32:06 +00002328 if (isFortifiedCallFoldable(CI, 2, 1, true))
Sanjay Pateld3112a52016-01-19 19:46:10 +00002329 return emitStrCpy(Dst, Src, B, TLI, Name.substr(2, 6));
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002330
David Blaikie65fab6d2015-04-03 21:32:06 +00002331 if (OnlyLowerUnknownSize)
2332 return nullptr;
2333
2334 // Maybe we can stil fold __st[rp]cpy_chk to __memcpy_chk.
2335 uint64_t Len = GetStringLength(Src);
2336 if (Len == 0)
2337 return nullptr;
2338
2339 Type *SizeTTy = DL.getIntPtrType(CI->getContext());
2340 Value *LenV = ConstantInt::get(SizeTTy, Len);
Sanjay Pateld3112a52016-01-19 19:46:10 +00002341 Value *Ret = emitMemCpyChk(Dst, Src, LenV, ObjSize, B, DL, TLI);
David Blaikie65fab6d2015-04-03 21:32:06 +00002342 // If the function was an __stpcpy_chk, and we were able to fold it into
2343 // a __memcpy_chk, we still need to return the correct end pointer.
David L. Jonesd21529f2017-01-23 23:16:46 +00002344 if (Ret && Func == LibFunc_stpcpy_chk)
David Blaikie65fab6d2015-04-03 21:32:06 +00002345 return B.CreateGEP(B.getInt8Ty(), Dst, ConstantInt::get(SizeTTy, Len - 1));
2346 return Ret;
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002347}
2348
Ahmed Bougacha1ac93562015-01-27 21:52:16 +00002349Value *FortifiedLibCallSimplifier::optimizeStrpNCpyChk(CallInst *CI,
2350 IRBuilder<> &B,
David L. Jonesd21529f2017-01-23 23:16:46 +00002351 LibFunc Func) {
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002352 Function *Callee = CI->getCalledFunction();
2353 StringRef Name = Callee->getName();
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002354 if (isFortifiedCallFoldable(CI, 3, 2, false)) {
Sanjay Pateld3112a52016-01-19 19:46:10 +00002355 Value *Ret = emitStrNCpy(CI->getArgOperand(0), CI->getArgOperand(1),
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002356 CI->getArgOperand(2), B, TLI, Name.substr(2, 7));
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002357 return Ret;
2358 }
2359 return nullptr;
2360}
2361
2362Value *FortifiedLibCallSimplifier::optimizeCall(CallInst *CI) {
Ahmed Bougacha408d0102015-04-01 00:45:09 +00002363 // FIXME: We shouldn't be changing "nobuiltin" or TLI unavailable calls here.
2364 // Some clang users checked for _chk libcall availability using:
2365 // __has_builtin(__builtin___memcpy_chk)
2366 // When compiling with -fno-builtin, this is always true.
2367 // When passing -ffreestanding/-mkernel, which both imply -fno-builtin, we
2368 // end up with fortified libcalls, which isn't acceptable in a freestanding
2369 // environment which only provides their non-fortified counterparts.
2370 //
2371 // Until we change clang and/or teach external users to check for availability
2372 // differently, disregard the "nobuiltin" attribute and TLI::has.
2373 //
2374 // PR23093.
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002375
David L. Jonesd21529f2017-01-23 23:16:46 +00002376 LibFunc Func;
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002377 Function *Callee = CI->getCalledFunction();
David Majnemerb70e23c2016-01-06 05:01:34 +00002378
2379 SmallVector<OperandBundleDef, 2> OpBundles;
2380 CI->getOperandBundlesAsDefs(OpBundles);
2381 IRBuilder<> Builder(CI, /*FPMathTag=*/nullptr, OpBundles);
Sam Parker214f7bf2016-09-13 12:10:14 +00002382 bool isCallingConvC = isCallingConvCCompatible(CI);
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002383
Ahmed Bougachad765a822016-04-27 19:04:35 +00002384 // First, check that this is a known library functions and that the prototype
2385 // is correct.
2386 if (!TLI->getLibFunc(*Callee, Func))
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002387 return nullptr;
2388
2389 // We never change the calling convention.
2390 if (!ignoreCallingConv(Func) && !isCallingConvC)
2391 return nullptr;
2392
2393 switch (Func) {
David L. Jonesd21529f2017-01-23 23:16:46 +00002394 case LibFunc_memcpy_chk:
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002395 return optimizeMemCpyChk(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002396 case LibFunc_memmove_chk:
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002397 return optimizeMemMoveChk(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002398 case LibFunc_memset_chk:
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002399 return optimizeMemSetChk(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002400 case LibFunc_stpcpy_chk:
2401 case LibFunc_strcpy_chk:
Ahmed Bougacha1ac93562015-01-27 21:52:16 +00002402 return optimizeStrpCpyChk(CI, Builder, Func);
David L. Jonesd21529f2017-01-23 23:16:46 +00002403 case LibFunc_stpncpy_chk:
2404 case LibFunc_strncpy_chk:
Ahmed Bougacha1ac93562015-01-27 21:52:16 +00002405 return optimizeStrpNCpyChk(CI, Builder, Func);
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002406 default:
2407 break;
2408 }
2409 return nullptr;
2410}
2411
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002412FortifiedLibCallSimplifier::FortifiedLibCallSimplifier(
2413 const TargetLibraryInfo *TLI, bool OnlyLowerUnknownSize)
2414 : TLI(TLI), OnlyLowerUnknownSize(OnlyLowerUnknownSize) {}