blob: 505136420163315cbeb68eb1e6721e7b70d69576 [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"
Meador Ingedf796f82012-10-13 16:45:24 +000021#include "llvm/Analysis/ValueTracking.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000022#include "llvm/IR/DataLayout.h"
Diego Novillo7f8af8b2014-05-22 14:19:46 +000023#include "llvm/IR/DiagnosticInfo.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000024#include "llvm/IR/Function.h"
25#include "llvm/IR/IRBuilder.h"
Meador Inge20255ef2013-03-12 00:08:29 +000026#include "llvm/IR/IntrinsicInst.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000027#include "llvm/IR/Intrinsics.h"
28#include "llvm/IR/LLVMContext.h"
29#include "llvm/IR/Module.h"
Sanjay Patelc699a612014-10-16 18:48:17 +000030#include "llvm/IR/PatternMatch.h"
Nadav Rotem464e8072013-02-27 05:53:43 +000031#include "llvm/Support/Allocator.h"
Hal Finkel66cd3f12013-11-17 02:06:35 +000032#include "llvm/Support/CommandLine.h"
Chandler Carruth62d42152015-01-15 02:16:27 +000033#include "llvm/Analysis/TargetLibraryInfo.h"
Meador Ingedf796f82012-10-13 16:45:24 +000034#include "llvm/Transforms/Utils/BuildLibCalls.h"
35
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
Chris Bienemanad070d02014-09-17 20:55:46 +000054static bool ignoreCallingConv(LibFunc::Func Func) {
55 switch (Func) {
56 case LibFunc::abs:
57 case LibFunc::labs:
58 case LibFunc::llabs:
59 case LibFunc::strlen:
60 return true;
61 default:
62 return false;
63 }
Chris Bienemancf93cbb2014-09-17 21:06:59 +000064 llvm_unreachable("All cases should be covered in the switch.");
Chris Bienemanad070d02014-09-17 20:55:46 +000065}
66
Meador Inged589ac62012-10-31 03:33:06 +000067/// isOnlyUsedInZeroEqualityComparison - Return true if it only matters that the
68/// value is equal or not-equal to zero.
69static bool isOnlyUsedInZeroEqualityComparison(Value *V) {
Chandler Carruthcdf47882014-03-09 03:16:01 +000070 for (User *U : V->users()) {
71 if (ICmpInst *IC = dyn_cast<ICmpInst>(U))
Meador Inged589ac62012-10-31 03:33:06 +000072 if (IC->isEquality())
73 if (Constant *C = dyn_cast<Constant>(IC->getOperand(1)))
74 if (C->isNullValue())
75 continue;
76 // Unknown instruction.
77 return false;
78 }
79 return true;
80}
81
Meador Inge56edbc92012-11-11 03:51:48 +000082/// isOnlyUsedInEqualityComparison - Return true if it is only used in equality
83/// comparisons with With.
84static bool isOnlyUsedInEqualityComparison(Value *V, Value *With) {
Chandler Carruthcdf47882014-03-09 03:16:01 +000085 for (User *U : V->users()) {
86 if (ICmpInst *IC = dyn_cast<ICmpInst>(U))
Meador Inge56edbc92012-11-11 03:51:48 +000087 if (IC->isEquality() && IC->getOperand(1) == With)
88 continue;
89 // Unknown instruction.
90 return false;
91 }
92 return true;
93}
94
Meador Inge08ca1152012-11-26 20:37:20 +000095static bool callHasFloatingPointArgument(const CallInst *CI) {
96 for (CallInst::const_op_iterator it = CI->op_begin(), e = CI->op_end();
97 it != e; ++it) {
98 if ((*it)->getType()->isFloatingPointTy())
99 return true;
100 }
101 return false;
102}
103
Benjamin Kramer2702caa2013-08-31 18:19:35 +0000104/// \brief Check whether the overloaded unary floating point function
Sanjay Patele24c60e2015-08-12 20:36:18 +0000105/// corresponding to \a Ty is available.
Benjamin Kramer2702caa2013-08-31 18:19:35 +0000106static bool hasUnaryFloatFn(const TargetLibraryInfo *TLI, Type *Ty,
107 LibFunc::Func DoubleFn, LibFunc::Func FloatFn,
108 LibFunc::Func LongDoubleFn) {
109 switch (Ty->getTypeID()) {
110 case Type::FloatTyID:
111 return TLI->has(FloatFn);
112 case Type::DoubleTyID:
113 return TLI->has(DoubleFn);
114 default:
115 return TLI->has(LongDoubleFn);
116 }
117}
118
Ahmed Bougachab7d8afb2015-01-12 17:18:19 +0000119/// \brief Returns whether \p F matches the signature expected for the
120/// string/memory copying library function \p Func.
121/// Acceptable functions are st[rp][n]?cpy, memove, memcpy, and memset.
122/// Their fortified (_chk) counterparts are also accepted.
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000123static bool checkStringCopyLibFuncSignature(Function *F, LibFunc::Func Func) {
124 const DataLayout &DL = F->getParent()->getDataLayout();
Ahmed Bougachab7d8afb2015-01-12 17:18:19 +0000125 FunctionType *FT = F->getFunctionType();
126 LLVMContext &Context = F->getContext();
127 Type *PCharTy = Type::getInt8PtrTy(Context);
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000128 Type *SizeTTy = DL.getIntPtrType(Context);
Ahmed Bougachab7d8afb2015-01-12 17:18:19 +0000129 unsigned NumParams = FT->getNumParams();
130
131 // All string libfuncs return the same type as the first parameter.
132 if (FT->getReturnType() != FT->getParamType(0))
133 return false;
134
135 switch (Func) {
136 default:
137 llvm_unreachable("Can't check signature for non-string-copy libfunc.");
138 case LibFunc::stpncpy_chk:
139 case LibFunc::strncpy_chk:
140 --NumParams; // fallthrough
141 case LibFunc::stpncpy:
142 case LibFunc::strncpy: {
143 if (NumParams != 3 || FT->getParamType(0) != FT->getParamType(1) ||
144 FT->getParamType(0) != PCharTy || !FT->getParamType(2)->isIntegerTy())
145 return false;
146 break;
147 }
148 case LibFunc::strcpy_chk:
149 case LibFunc::stpcpy_chk:
150 --NumParams; // fallthrough
151 case LibFunc::stpcpy:
152 case LibFunc::strcpy: {
153 if (NumParams != 2 || FT->getParamType(0) != FT->getParamType(1) ||
154 FT->getParamType(0) != PCharTy)
155 return false;
156 break;
157 }
158 case LibFunc::memmove_chk:
159 case LibFunc::memcpy_chk:
160 --NumParams; // fallthrough
161 case LibFunc::memmove:
162 case LibFunc::memcpy: {
163 if (NumParams != 3 || !FT->getParamType(0)->isPointerTy() ||
164 !FT->getParamType(1)->isPointerTy() || FT->getParamType(2) != SizeTTy)
165 return false;
166 break;
167 }
168 case LibFunc::memset_chk:
169 --NumParams; // fallthrough
170 case LibFunc::memset: {
171 if (NumParams != 3 || !FT->getParamType(0)->isPointerTy() ||
172 !FT->getParamType(1)->isIntegerTy() || FT->getParamType(2) != SizeTTy)
173 return false;
174 break;
175 }
176 }
177 // If this is a fortified libcall, the last parameter is a size_t.
178 if (NumParams == FT->getNumParams() - 1)
179 return FT->getParamType(FT->getNumParams() - 1) == SizeTTy;
180 return true;
181}
182
Meador Inged589ac62012-10-31 03:33:06 +0000183//===----------------------------------------------------------------------===//
Meador Inge7fb2f732012-10-13 16:45:32 +0000184// String and Memory Library Call Optimizations
185//===----------------------------------------------------------------------===//
186
Chris Bienemanad070d02014-09-17 20:55:46 +0000187Value *LibCallSimplifier::optimizeStrCat(CallInst *CI, IRBuilder<> &B) {
188 Function *Callee = CI->getCalledFunction();
189 // Verify the "strcat" function prototype.
190 FunctionType *FT = Callee->getFunctionType();
191 if (FT->getNumParams() != 2||
192 FT->getReturnType() != B.getInt8PtrTy() ||
193 FT->getParamType(0) != FT->getReturnType() ||
194 FT->getParamType(1) != FT->getReturnType())
195 return nullptr;
196
197 // Extract some information from the instruction
198 Value *Dst = CI->getArgOperand(0);
199 Value *Src = CI->getArgOperand(1);
200
201 // See if we can get the length of the input string.
202 uint64_t Len = GetStringLength(Src);
203 if (Len == 0)
204 return nullptr;
205 --Len; // Unbias length.
206
207 // Handle the simple, do-nothing case: strcat(x, "") -> x
208 if (Len == 0)
209 return Dst;
210
Chris Bienemanad070d02014-09-17 20:55:46 +0000211 return emitStrLenMemCpy(Src, Dst, Len, B);
212}
213
214Value *LibCallSimplifier::emitStrLenMemCpy(Value *Src, Value *Dst, uint64_t Len,
215 IRBuilder<> &B) {
216 // We need to find the end of the destination string. That's where the
217 // memory is to be moved to. We just generate a call to strlen.
218 Value *DstLen = EmitStrLen(Dst, B, DL, TLI);
219 if (!DstLen)
220 return nullptr;
221
222 // Now that we have the destination's length, we must index into the
223 // destination's pointer to get the actual memcpy destination (end of
224 // the string .. we're concatenating).
David Blaikie3909da72015-03-30 20:42:56 +0000225 Value *CpyDst = B.CreateGEP(B.getInt8Ty(), Dst, DstLen, "endptr");
Chris Bienemanad070d02014-09-17 20:55:46 +0000226
227 // We have enough information to now generate the memcpy call to do the
228 // concatenation for us. Make a memcpy to copy the nul byte with align = 1.
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000229 B.CreateMemCpy(CpyDst, Src,
230 ConstantInt::get(DL.getIntPtrType(Src->getContext()), Len + 1),
231 1);
Chris Bienemanad070d02014-09-17 20:55:46 +0000232 return Dst;
233}
234
235Value *LibCallSimplifier::optimizeStrNCat(CallInst *CI, IRBuilder<> &B) {
236 Function *Callee = CI->getCalledFunction();
237 // Verify the "strncat" function prototype.
238 FunctionType *FT = Callee->getFunctionType();
239 if (FT->getNumParams() != 3 || FT->getReturnType() != B.getInt8PtrTy() ||
240 FT->getParamType(0) != FT->getReturnType() ||
241 FT->getParamType(1) != FT->getReturnType() ||
242 !FT->getParamType(2)->isIntegerTy())
243 return nullptr;
244
245 // Extract some information from the instruction
246 Value *Dst = CI->getArgOperand(0);
247 Value *Src = CI->getArgOperand(1);
248 uint64_t Len;
249
250 // We don't do anything if length is not constant
251 if (ConstantInt *LengthArg = dyn_cast<ConstantInt>(CI->getArgOperand(2)))
252 Len = LengthArg->getZExtValue();
253 else
254 return nullptr;
255
256 // See if we can get the length of the input string.
257 uint64_t SrcLen = GetStringLength(Src);
258 if (SrcLen == 0)
259 return nullptr;
260 --SrcLen; // Unbias length.
261
262 // Handle the simple, do-nothing cases:
263 // strncat(x, "", c) -> x
264 // strncat(x, c, 0) -> x
265 if (SrcLen == 0 || Len == 0)
266 return Dst;
267
Chris Bienemanad070d02014-09-17 20:55:46 +0000268 // We don't optimize this case
269 if (Len < SrcLen)
270 return nullptr;
271
272 // strncat(x, s, c) -> strcat(x, s)
273 // s is constant so the strcat can be optimized further
274 return emitStrLenMemCpy(Src, Dst, SrcLen, B);
275}
276
277Value *LibCallSimplifier::optimizeStrChr(CallInst *CI, IRBuilder<> &B) {
278 Function *Callee = CI->getCalledFunction();
279 // Verify the "strchr" function prototype.
280 FunctionType *FT = Callee->getFunctionType();
281 if (FT->getNumParams() != 2 || FT->getReturnType() != B.getInt8PtrTy() ||
282 FT->getParamType(0) != FT->getReturnType() ||
283 !FT->getParamType(1)->isIntegerTy(32))
284 return nullptr;
285
286 Value *SrcStr = CI->getArgOperand(0);
287
288 // If the second operand is non-constant, see if we can compute the length
289 // of the input string and turn this into memchr.
290 ConstantInt *CharC = dyn_cast<ConstantInt>(CI->getArgOperand(1));
291 if (!CharC) {
Chris Bienemanad070d02014-09-17 20:55:46 +0000292 uint64_t Len = GetStringLength(SrcStr);
293 if (Len == 0 || !FT->getParamType(1)->isIntegerTy(32)) // memchr needs i32.
294 return nullptr;
Meador Inge7fb2f732012-10-13 16:45:32 +0000295
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000296 return EmitMemChr(SrcStr, CI->getArgOperand(1), // include nul.
297 ConstantInt::get(DL.getIntPtrType(CI->getContext()), Len),
298 B, DL, TLI);
Meador Inge7fb2f732012-10-13 16:45:32 +0000299 }
300
Chris Bienemanad070d02014-09-17 20:55:46 +0000301 // Otherwise, the character is a constant, see if the first argument is
302 // a string literal. If so, we can constant fold.
303 StringRef Str;
304 if (!getConstantStringInfo(SrcStr, Str)) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000305 if (CharC->isZero()) // strchr(p, 0) -> p + strlen(p)
David Blaikie3909da72015-03-30 20:42:56 +0000306 return B.CreateGEP(B.getInt8Ty(), SrcStr, EmitStrLen(SrcStr, B, DL, TLI), "strchr");
Chris Bienemanad070d02014-09-17 20:55:46 +0000307 return nullptr;
308 }
309
310 // Compute the offset, make sure to handle the case when we're searching for
311 // zero (a weird way to spell strlen).
312 size_t I = (0xFF & CharC->getSExtValue()) == 0
313 ? Str.size()
314 : Str.find(CharC->getSExtValue());
315 if (I == StringRef::npos) // Didn't find the char. strchr returns null.
316 return Constant::getNullValue(CI->getType());
317
318 // strchr(s+n,c) -> gep(s+n+i,c)
David Blaikie3909da72015-03-30 20:42:56 +0000319 return B.CreateGEP(B.getInt8Ty(), SrcStr, B.getInt64(I), "strchr");
Chris Bienemanad070d02014-09-17 20:55:46 +0000320}
321
322Value *LibCallSimplifier::optimizeStrRChr(CallInst *CI, IRBuilder<> &B) {
323 Function *Callee = CI->getCalledFunction();
324 // Verify the "strrchr" function prototype.
325 FunctionType *FT = Callee->getFunctionType();
326 if (FT->getNumParams() != 2 || FT->getReturnType() != B.getInt8PtrTy() ||
327 FT->getParamType(0) != FT->getReturnType() ||
328 !FT->getParamType(1)->isIntegerTy(32))
329 return nullptr;
330
331 Value *SrcStr = CI->getArgOperand(0);
332 ConstantInt *CharC = dyn_cast<ConstantInt>(CI->getArgOperand(1));
333
334 // Cannot fold anything if we're not looking for a constant.
335 if (!CharC)
336 return nullptr;
337
338 StringRef Str;
339 if (!getConstantStringInfo(SrcStr, Str)) {
340 // strrchr(s, 0) -> strchr(s, 0)
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000341 if (CharC->isZero())
342 return EmitStrChr(SrcStr, '\0', B, TLI);
Chris Bienemanad070d02014-09-17 20:55:46 +0000343 return nullptr;
344 }
345
346 // Compute the offset.
347 size_t I = (0xFF & CharC->getSExtValue()) == 0
348 ? Str.size()
349 : Str.rfind(CharC->getSExtValue());
350 if (I == StringRef::npos) // Didn't find the char. Return null.
351 return Constant::getNullValue(CI->getType());
352
353 // strrchr(s+n,c) -> gep(s+n+i,c)
David Blaikie3909da72015-03-30 20:42:56 +0000354 return B.CreateGEP(B.getInt8Ty(), SrcStr, B.getInt64(I), "strrchr");
Chris Bienemanad070d02014-09-17 20:55:46 +0000355}
356
357Value *LibCallSimplifier::optimizeStrCmp(CallInst *CI, IRBuilder<> &B) {
358 Function *Callee = CI->getCalledFunction();
359 // Verify the "strcmp" function prototype.
360 FunctionType *FT = Callee->getFunctionType();
361 if (FT->getNumParams() != 2 || !FT->getReturnType()->isIntegerTy(32) ||
362 FT->getParamType(0) != FT->getParamType(1) ||
363 FT->getParamType(0) != B.getInt8PtrTy())
364 return nullptr;
365
366 Value *Str1P = CI->getArgOperand(0), *Str2P = CI->getArgOperand(1);
367 if (Str1P == Str2P) // strcmp(x,x) -> 0
368 return ConstantInt::get(CI->getType(), 0);
369
370 StringRef Str1, Str2;
371 bool HasStr1 = getConstantStringInfo(Str1P, Str1);
372 bool HasStr2 = getConstantStringInfo(Str2P, Str2);
373
374 // strcmp(x, y) -> cnst (if both x and y are constant strings)
375 if (HasStr1 && HasStr2)
376 return ConstantInt::get(CI->getType(), Str1.compare(Str2));
377
378 if (HasStr1 && Str1.empty()) // strcmp("", x) -> -*x
379 return B.CreateNeg(
380 B.CreateZExt(B.CreateLoad(Str2P, "strcmpload"), CI->getType()));
381
382 if (HasStr2 && Str2.empty()) // strcmp(x,"") -> *x
383 return B.CreateZExt(B.CreateLoad(Str1P, "strcmpload"), CI->getType());
384
385 // strcmp(P, "x") -> memcmp(P, "x", 2)
386 uint64_t Len1 = GetStringLength(Str1P);
387 uint64_t Len2 = GetStringLength(Str2P);
388 if (Len1 && Len2) {
Chris Bienemanad070d02014-09-17 20:55:46 +0000389 return EmitMemCmp(Str1P, Str2P,
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000390 ConstantInt::get(DL.getIntPtrType(CI->getContext()),
Chris Bienemanad070d02014-09-17 20:55:46 +0000391 std::min(Len1, Len2)),
392 B, DL, TLI);
393 }
Meador Inge7fb2f732012-10-13 16:45:32 +0000394
Chris Bienemanad070d02014-09-17 20:55:46 +0000395 return nullptr;
396}
397
398Value *LibCallSimplifier::optimizeStrNCmp(CallInst *CI, IRBuilder<> &B) {
399 Function *Callee = CI->getCalledFunction();
400 // Verify the "strncmp" function prototype.
401 FunctionType *FT = Callee->getFunctionType();
402 if (FT->getNumParams() != 3 || !FT->getReturnType()->isIntegerTy(32) ||
403 FT->getParamType(0) != FT->getParamType(1) ||
404 FT->getParamType(0) != B.getInt8PtrTy() ||
405 !FT->getParamType(2)->isIntegerTy())
406 return nullptr;
407
408 Value *Str1P = CI->getArgOperand(0), *Str2P = CI->getArgOperand(1);
409 if (Str1P == Str2P) // strncmp(x,x,n) -> 0
410 return ConstantInt::get(CI->getType(), 0);
411
412 // Get the length argument if it is constant.
413 uint64_t Length;
414 if (ConstantInt *LengthArg = dyn_cast<ConstantInt>(CI->getArgOperand(2)))
415 Length = LengthArg->getZExtValue();
416 else
417 return nullptr;
418
419 if (Length == 0) // strncmp(x,y,0) -> 0
420 return ConstantInt::get(CI->getType(), 0);
421
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000422 if (Length == 1) // strncmp(x,y,1) -> memcmp(x,y,1)
Chris Bienemanad070d02014-09-17 20:55:46 +0000423 return EmitMemCmp(Str1P, Str2P, CI->getArgOperand(2), B, DL, TLI);
424
425 StringRef Str1, Str2;
426 bool HasStr1 = getConstantStringInfo(Str1P, Str1);
427 bool HasStr2 = getConstantStringInfo(Str2P, Str2);
428
429 // strncmp(x, y) -> cnst (if both x and y are constant strings)
430 if (HasStr1 && HasStr2) {
431 StringRef SubStr1 = Str1.substr(0, Length);
432 StringRef SubStr2 = Str2.substr(0, Length);
433 return ConstantInt::get(CI->getType(), SubStr1.compare(SubStr2));
434 }
435
436 if (HasStr1 && Str1.empty()) // strncmp("", x, n) -> -*x
437 return B.CreateNeg(
438 B.CreateZExt(B.CreateLoad(Str2P, "strcmpload"), CI->getType()));
439
440 if (HasStr2 && Str2.empty()) // strncmp(x, "", n) -> *x
441 return B.CreateZExt(B.CreateLoad(Str1P, "strcmpload"), CI->getType());
442
443 return nullptr;
444}
445
446Value *LibCallSimplifier::optimizeStrCpy(CallInst *CI, IRBuilder<> &B) {
447 Function *Callee = CI->getCalledFunction();
Ahmed Bougachab7d8afb2015-01-12 17:18:19 +0000448
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000449 if (!checkStringCopyLibFuncSignature(Callee, LibFunc::strcpy))
Chris Bienemanad070d02014-09-17 20:55:46 +0000450 return nullptr;
451
452 Value *Dst = CI->getArgOperand(0), *Src = CI->getArgOperand(1);
453 if (Dst == Src) // strcpy(x,x) -> x
454 return Src;
455
Chris Bienemanad070d02014-09-17 20:55:46 +0000456 // See if we can get the length of the input string.
457 uint64_t Len = GetStringLength(Src);
458 if (Len == 0)
459 return nullptr;
460
461 // We have enough information to now generate the memcpy call to do the
462 // copy for us. Make a memcpy to copy the nul byte with align = 1.
463 B.CreateMemCpy(Dst, Src,
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000464 ConstantInt::get(DL.getIntPtrType(CI->getContext()), Len), 1);
Chris Bienemanad070d02014-09-17 20:55:46 +0000465 return Dst;
466}
467
468Value *LibCallSimplifier::optimizeStpCpy(CallInst *CI, IRBuilder<> &B) {
469 Function *Callee = CI->getCalledFunction();
470 // Verify the "stpcpy" function prototype.
471 FunctionType *FT = Callee->getFunctionType();
Ahmed Bougachab7d8afb2015-01-12 17:18:19 +0000472
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000473 if (!checkStringCopyLibFuncSignature(Callee, LibFunc::stpcpy))
Chris Bienemanad070d02014-09-17 20:55:46 +0000474 return nullptr;
475
476 Value *Dst = CI->getArgOperand(0), *Src = CI->getArgOperand(1);
477 if (Dst == Src) { // stpcpy(x,x) -> x+strlen(x)
478 Value *StrLen = EmitStrLen(Src, B, DL, TLI);
David Blaikieaa41cd52015-04-03 21:33:42 +0000479 return StrLen ? B.CreateInBoundsGEP(B.getInt8Ty(), Dst, StrLen) : nullptr;
Chris Bienemanad070d02014-09-17 20:55:46 +0000480 }
481
482 // See if we can get the length of the input string.
483 uint64_t Len = GetStringLength(Src);
484 if (Len == 0)
485 return nullptr;
486
487 Type *PT = FT->getParamType(0);
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000488 Value *LenV = ConstantInt::get(DL.getIntPtrType(PT), Len);
Chris Bienemanad070d02014-09-17 20:55:46 +0000489 Value *DstEnd =
David Blaikie3909da72015-03-30 20:42:56 +0000490 B.CreateGEP(B.getInt8Ty(), Dst, ConstantInt::get(DL.getIntPtrType(PT), Len - 1));
Chris Bienemanad070d02014-09-17 20:55:46 +0000491
492 // We have enough information to now generate the memcpy call to do the
493 // copy for us. Make a memcpy to copy the nul byte with align = 1.
494 B.CreateMemCpy(Dst, Src, LenV, 1);
495 return DstEnd;
496}
497
498Value *LibCallSimplifier::optimizeStrNCpy(CallInst *CI, IRBuilder<> &B) {
499 Function *Callee = CI->getCalledFunction();
500 FunctionType *FT = Callee->getFunctionType();
Ahmed Bougachab7d8afb2015-01-12 17:18:19 +0000501
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000502 if (!checkStringCopyLibFuncSignature(Callee, LibFunc::strncpy))
Chris Bienemanad070d02014-09-17 20:55:46 +0000503 return nullptr;
504
505 Value *Dst = CI->getArgOperand(0);
506 Value *Src = CI->getArgOperand(1);
507 Value *LenOp = CI->getArgOperand(2);
508
509 // See if we can get the length of the input string.
510 uint64_t SrcLen = GetStringLength(Src);
511 if (SrcLen == 0)
512 return nullptr;
513 --SrcLen;
514
515 if (SrcLen == 0) {
516 // strncpy(x, "", y) -> memset(x, '\0', y, 1)
517 B.CreateMemSet(Dst, B.getInt8('\0'), LenOp, 1);
Meador Inge7fb2f732012-10-13 16:45:32 +0000518 return Dst;
519 }
Meador Inge7fb2f732012-10-13 16:45:32 +0000520
Chris Bienemanad070d02014-09-17 20:55:46 +0000521 uint64_t Len;
522 if (ConstantInt *LengthArg = dyn_cast<ConstantInt>(LenOp))
523 Len = LengthArg->getZExtValue();
524 else
525 return nullptr;
Meador Inge7fb2f732012-10-13 16:45:32 +0000526
Chris Bienemanad070d02014-09-17 20:55:46 +0000527 if (Len == 0)
528 return Dst; // strncpy(x, y, 0) -> x
Meador Inge7fb2f732012-10-13 16:45:32 +0000529
Chris Bienemanad070d02014-09-17 20:55:46 +0000530 // Let strncpy handle the zero padding
531 if (Len > SrcLen + 1)
532 return nullptr;
Meador Inge7fb2f732012-10-13 16:45:32 +0000533
Chris Bienemanad070d02014-09-17 20:55:46 +0000534 Type *PT = FT->getParamType(0);
535 // strncpy(x, s, c) -> memcpy(x, s, c, 1) [s and c are constant]
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000536 B.CreateMemCpy(Dst, Src, ConstantInt::get(DL.getIntPtrType(PT), Len), 1);
Meador Inge7fb2f732012-10-13 16:45:32 +0000537
Chris Bienemanad070d02014-09-17 20:55:46 +0000538 return Dst;
539}
Meador Inge7fb2f732012-10-13 16:45:32 +0000540
Chris Bienemanad070d02014-09-17 20:55:46 +0000541Value *LibCallSimplifier::optimizeStrLen(CallInst *CI, IRBuilder<> &B) {
542 Function *Callee = CI->getCalledFunction();
543 FunctionType *FT = Callee->getFunctionType();
544 if (FT->getNumParams() != 1 || FT->getParamType(0) != B.getInt8PtrTy() ||
545 !FT->getReturnType()->isIntegerTy())
546 return nullptr;
Meador Inge7fb2f732012-10-13 16:45:32 +0000547
Chris Bienemanad070d02014-09-17 20:55:46 +0000548 Value *Src = CI->getArgOperand(0);
549
550 // Constant folding: strlen("xyz") -> 3
551 if (uint64_t Len = GetStringLength(Src))
552 return ConstantInt::get(CI->getType(), Len - 1);
553
554 // strlen(x?"foo":"bars") --> x ? 3 : 4
555 if (SelectInst *SI = dyn_cast<SelectInst>(Src)) {
556 uint64_t LenTrue = GetStringLength(SI->getTrueValue());
557 uint64_t LenFalse = GetStringLength(SI->getFalseValue());
558 if (LenTrue && LenFalse) {
559 Function *Caller = CI->getParent()->getParent();
560 emitOptimizationRemark(CI->getContext(), "simplify-libcalls", *Caller,
561 SI->getDebugLoc(),
562 "folded strlen(select) to select of constants");
563 return B.CreateSelect(SI->getCondition(),
564 ConstantInt::get(CI->getType(), LenTrue - 1),
565 ConstantInt::get(CI->getType(), LenFalse - 1));
566 }
Meador Inge7fb2f732012-10-13 16:45:32 +0000567 }
Meador Inge7fb2f732012-10-13 16:45:32 +0000568
Chris Bienemanad070d02014-09-17 20:55:46 +0000569 // strlen(x) != 0 --> *x != 0
570 // strlen(x) == 0 --> *x == 0
571 if (isOnlyUsedInZeroEqualityComparison(CI))
572 return B.CreateZExt(B.CreateLoad(Src, "strlenfirst"), CI->getType());
Meador Inge17418502012-10-13 16:45:37 +0000573
Chris Bienemanad070d02014-09-17 20:55:46 +0000574 return nullptr;
575}
Meador Inge17418502012-10-13 16:45:37 +0000576
Chris Bienemanad070d02014-09-17 20:55:46 +0000577Value *LibCallSimplifier::optimizeStrPBrk(CallInst *CI, IRBuilder<> &B) {
578 Function *Callee = CI->getCalledFunction();
579 FunctionType *FT = Callee->getFunctionType();
580 if (FT->getNumParams() != 2 || FT->getParamType(0) != B.getInt8PtrTy() ||
581 FT->getParamType(1) != FT->getParamType(0) ||
582 FT->getReturnType() != FT->getParamType(0))
583 return nullptr;
Meador Inge17418502012-10-13 16:45:37 +0000584
Chris Bienemanad070d02014-09-17 20:55:46 +0000585 StringRef S1, S2;
586 bool HasS1 = getConstantStringInfo(CI->getArgOperand(0), S1);
587 bool HasS2 = getConstantStringInfo(CI->getArgOperand(1), S2);
Meador Inge17418502012-10-13 16:45:37 +0000588
Reid Kleckner971c3ea2014-11-13 22:55:19 +0000589 // strpbrk(s, "") -> nullptr
590 // strpbrk("", s) -> nullptr
Chris Bienemanad070d02014-09-17 20:55:46 +0000591 if ((HasS1 && S1.empty()) || (HasS2 && S2.empty()))
592 return Constant::getNullValue(CI->getType());
Meador Inge17418502012-10-13 16:45:37 +0000593
Chris Bienemanad070d02014-09-17 20:55:46 +0000594 // Constant folding.
595 if (HasS1 && HasS2) {
596 size_t I = S1.find_first_of(S2);
597 if (I == StringRef::npos) // No match.
Meador Inge17418502012-10-13 16:45:37 +0000598 return Constant::getNullValue(CI->getType());
599
David Blaikie3909da72015-03-30 20:42:56 +0000600 return B.CreateGEP(B.getInt8Ty(), CI->getArgOperand(0), B.getInt64(I), "strpbrk");
Meador Inge17418502012-10-13 16:45:37 +0000601 }
Meador Inge17418502012-10-13 16:45:37 +0000602
Chris Bienemanad070d02014-09-17 20:55:46 +0000603 // strpbrk(s, "a") -> strchr(s, 'a')
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000604 if (HasS2 && S2.size() == 1)
605 return EmitStrChr(CI->getArgOperand(0), S2[0], B, TLI);
Chris Bienemanad070d02014-09-17 20:55:46 +0000606
607 return nullptr;
608}
609
610Value *LibCallSimplifier::optimizeStrTo(CallInst *CI, IRBuilder<> &B) {
611 Function *Callee = CI->getCalledFunction();
612 FunctionType *FT = Callee->getFunctionType();
613 if ((FT->getNumParams() != 2 && FT->getNumParams() != 3) ||
614 !FT->getParamType(0)->isPointerTy() ||
615 !FT->getParamType(1)->isPointerTy())
616 return nullptr;
617
618 Value *EndPtr = CI->getArgOperand(1);
619 if (isa<ConstantPointerNull>(EndPtr)) {
620 // With a null EndPtr, this function won't capture the main argument.
621 // It would be readonly too, except that it still may write to errno.
622 CI->addAttribute(1, Attribute::NoCapture);
623 }
624
625 return nullptr;
626}
627
628Value *LibCallSimplifier::optimizeStrSpn(CallInst *CI, IRBuilder<> &B) {
629 Function *Callee = CI->getCalledFunction();
630 FunctionType *FT = Callee->getFunctionType();
631 if (FT->getNumParams() != 2 || FT->getParamType(0) != B.getInt8PtrTy() ||
632 FT->getParamType(1) != FT->getParamType(0) ||
633 !FT->getReturnType()->isIntegerTy())
634 return nullptr;
635
636 StringRef S1, S2;
637 bool HasS1 = getConstantStringInfo(CI->getArgOperand(0), S1);
638 bool HasS2 = getConstantStringInfo(CI->getArgOperand(1), S2);
639
640 // strspn(s, "") -> 0
641 // strspn("", s) -> 0
642 if ((HasS1 && S1.empty()) || (HasS2 && S2.empty()))
643 return Constant::getNullValue(CI->getType());
644
645 // Constant folding.
646 if (HasS1 && HasS2) {
647 size_t Pos = S1.find_first_not_of(S2);
648 if (Pos == StringRef::npos)
649 Pos = S1.size();
650 return ConstantInt::get(CI->getType(), Pos);
651 }
652
653 return nullptr;
654}
655
656Value *LibCallSimplifier::optimizeStrCSpn(CallInst *CI, IRBuilder<> &B) {
657 Function *Callee = CI->getCalledFunction();
658 FunctionType *FT = Callee->getFunctionType();
659 if (FT->getNumParams() != 2 || FT->getParamType(0) != B.getInt8PtrTy() ||
660 FT->getParamType(1) != FT->getParamType(0) ||
661 !FT->getReturnType()->isIntegerTy())
662 return nullptr;
663
664 StringRef S1, S2;
665 bool HasS1 = getConstantStringInfo(CI->getArgOperand(0), S1);
666 bool HasS2 = getConstantStringInfo(CI->getArgOperand(1), S2);
667
668 // strcspn("", s) -> 0
669 if (HasS1 && S1.empty())
670 return Constant::getNullValue(CI->getType());
671
672 // Constant folding.
673 if (HasS1 && HasS2) {
674 size_t Pos = S1.find_first_of(S2);
675 if (Pos == StringRef::npos)
676 Pos = S1.size();
677 return ConstantInt::get(CI->getType(), Pos);
678 }
679
680 // strcspn(s, "") -> strlen(s)
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000681 if (HasS2 && S2.empty())
Chris Bienemanad070d02014-09-17 20:55:46 +0000682 return EmitStrLen(CI->getArgOperand(0), B, DL, TLI);
683
684 return nullptr;
685}
686
687Value *LibCallSimplifier::optimizeStrStr(CallInst *CI, IRBuilder<> &B) {
688 Function *Callee = CI->getCalledFunction();
689 FunctionType *FT = Callee->getFunctionType();
690 if (FT->getNumParams() != 2 || !FT->getParamType(0)->isPointerTy() ||
691 !FT->getParamType(1)->isPointerTy() ||
692 !FT->getReturnType()->isPointerTy())
693 return nullptr;
694
695 // fold strstr(x, x) -> x.
696 if (CI->getArgOperand(0) == CI->getArgOperand(1))
697 return B.CreateBitCast(CI->getArgOperand(0), CI->getType());
698
699 // fold strstr(a, b) == a -> strncmp(a, b, strlen(b)) == 0
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000700 if (isOnlyUsedInEqualityComparison(CI, CI->getArgOperand(0))) {
Chris Bienemanad070d02014-09-17 20:55:46 +0000701 Value *StrLen = EmitStrLen(CI->getArgOperand(1), B, DL, TLI);
702 if (!StrLen)
Craig Topperf40110f2014-04-25 05:29:35 +0000703 return nullptr;
Chris Bienemanad070d02014-09-17 20:55:46 +0000704 Value *StrNCmp = EmitStrNCmp(CI->getArgOperand(0), CI->getArgOperand(1),
705 StrLen, B, DL, TLI);
706 if (!StrNCmp)
Craig Topperf40110f2014-04-25 05:29:35 +0000707 return nullptr;
Chris Bienemanad070d02014-09-17 20:55:46 +0000708 for (auto UI = CI->user_begin(), UE = CI->user_end(); UI != UE;) {
709 ICmpInst *Old = cast<ICmpInst>(*UI++);
710 Value *Cmp =
711 B.CreateICmp(Old->getPredicate(), StrNCmp,
712 ConstantInt::getNullValue(StrNCmp->getType()), "cmp");
713 replaceAllUsesWith(Old, Cmp);
Meador Inge17418502012-10-13 16:45:37 +0000714 }
Chris Bienemanad070d02014-09-17 20:55:46 +0000715 return CI;
716 }
Meador Inge17418502012-10-13 16:45:37 +0000717
Chris Bienemanad070d02014-09-17 20:55:46 +0000718 // See if either input string is a constant string.
719 StringRef SearchStr, ToFindStr;
720 bool HasStr1 = getConstantStringInfo(CI->getArgOperand(0), SearchStr);
721 bool HasStr2 = getConstantStringInfo(CI->getArgOperand(1), ToFindStr);
722
723 // fold strstr(x, "") -> x.
724 if (HasStr2 && ToFindStr.empty())
725 return B.CreateBitCast(CI->getArgOperand(0), CI->getType());
726
727 // If both strings are known, constant fold it.
728 if (HasStr1 && HasStr2) {
729 size_t Offset = SearchStr.find(ToFindStr);
730
731 if (Offset == StringRef::npos) // strstr("foo", "bar") -> null
Meador Inge17418502012-10-13 16:45:37 +0000732 return Constant::getNullValue(CI->getType());
733
Chris Bienemanad070d02014-09-17 20:55:46 +0000734 // strstr("abcd", "bc") -> gep((char*)"abcd", 1)
735 Value *Result = CastToCStr(CI->getArgOperand(0), B);
736 Result = B.CreateConstInBoundsGEP1_64(Result, Offset, "strstr");
737 return B.CreateBitCast(Result, CI->getType());
Meador Inge17418502012-10-13 16:45:37 +0000738 }
Meador Inge17418502012-10-13 16:45:37 +0000739
Chris Bienemanad070d02014-09-17 20:55:46 +0000740 // fold strstr(x, "y") -> strchr(x, 'y').
741 if (HasStr2 && ToFindStr.size() == 1) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000742 Value *StrChr = EmitStrChr(CI->getArgOperand(0), ToFindStr[0], B, TLI);
Chris Bienemanad070d02014-09-17 20:55:46 +0000743 return StrChr ? B.CreateBitCast(StrChr, CI->getType()) : nullptr;
744 }
745 return nullptr;
746}
Meador Inge40b6fac2012-10-15 03:47:37 +0000747
Benjamin Kramer691363e2015-03-21 15:36:21 +0000748Value *LibCallSimplifier::optimizeMemChr(CallInst *CI, IRBuilder<> &B) {
749 Function *Callee = CI->getCalledFunction();
750 FunctionType *FT = Callee->getFunctionType();
751 if (FT->getNumParams() != 3 || !FT->getParamType(0)->isPointerTy() ||
752 !FT->getParamType(1)->isIntegerTy(32) ||
753 !FT->getParamType(2)->isIntegerTy() ||
754 !FT->getReturnType()->isPointerTy())
755 return nullptr;
756
757 Value *SrcStr = CI->getArgOperand(0);
758 ConstantInt *CharC = dyn_cast<ConstantInt>(CI->getArgOperand(1));
759 ConstantInt *LenC = dyn_cast<ConstantInt>(CI->getArgOperand(2));
760
761 // memchr(x, y, 0) -> null
762 if (LenC && LenC->isNullValue())
763 return Constant::getNullValue(CI->getType());
764
Benjamin Kramer7857d722015-03-21 21:09:33 +0000765 // From now on we need at least constant length and string.
Benjamin Kramer691363e2015-03-21 15:36:21 +0000766 StringRef Str;
Benjamin Kramer7857d722015-03-21 21:09:33 +0000767 if (!LenC || !getConstantStringInfo(SrcStr, Str, 0, /*TrimAtNul=*/false))
Benjamin Kramer691363e2015-03-21 15:36:21 +0000768 return nullptr;
769
770 // Truncate the string to LenC. If Str is smaller than LenC we will still only
771 // scan the string, as reading past the end of it is undefined and we can just
772 // return null if we don't find the char.
773 Str = Str.substr(0, LenC->getZExtValue());
774
Benjamin Kramer7857d722015-03-21 21:09:33 +0000775 // If the char is variable but the input str and length are not we can turn
776 // this memchr call into a simple bit field test. Of course this only works
777 // when the return value is only checked against null.
778 //
779 // It would be really nice to reuse switch lowering here but we can't change
780 // the CFG at this point.
781 //
782 // memchr("\r\n", C, 2) != nullptr -> (C & ((1 << '\r') | (1 << '\n'))) != 0
783 // after bounds check.
784 if (!CharC && !Str.empty() && isOnlyUsedInZeroEqualityComparison(CI)) {
Benjamin Kramerd6aa0ec2015-03-21 22:04:26 +0000785 unsigned char Max =
786 *std::max_element(reinterpret_cast<const unsigned char *>(Str.begin()),
787 reinterpret_cast<const unsigned char *>(Str.end()));
Benjamin Kramer7857d722015-03-21 21:09:33 +0000788
789 // Make sure the bit field we're about to create fits in a register on the
790 // target.
791 // FIXME: On a 64 bit architecture this prevents us from using the
792 // interesting range of alpha ascii chars. We could do better by emitting
793 // two bitfields or shifting the range by 64 if no lower chars are used.
794 if (!DL.fitsInLegalInteger(Max + 1))
795 return nullptr;
796
797 // For the bit field use a power-of-2 type with at least 8 bits to avoid
798 // creating unnecessary illegal types.
799 unsigned char Width = NextPowerOf2(std::max((unsigned char)7, Max));
800
801 // Now build the bit field.
802 APInt Bitfield(Width, 0);
803 for (char C : Str)
804 Bitfield.setBit((unsigned char)C);
805 Value *BitfieldC = B.getInt(Bitfield);
806
807 // First check that the bit field access is within bounds.
808 Value *C = B.CreateZExtOrTrunc(CI->getArgOperand(1), BitfieldC->getType());
809 Value *Bounds = B.CreateICmp(ICmpInst::ICMP_ULT, C, B.getIntN(Width, Width),
810 "memchr.bounds");
811
812 // Create code that checks if the given bit is set in the field.
813 Value *Shl = B.CreateShl(B.getIntN(Width, 1ULL), C);
814 Value *Bits = B.CreateIsNotNull(B.CreateAnd(Shl, BitfieldC), "memchr.bits");
815
816 // Finally merge both checks and cast to pointer type. The inttoptr
817 // implicitly zexts the i1 to intptr type.
818 return B.CreateIntToPtr(B.CreateAnd(Bounds, Bits, "memchr"), CI->getType());
819 }
820
821 // Check if all arguments are constants. If so, we can constant fold.
822 if (!CharC)
823 return nullptr;
824
Benjamin Kramer691363e2015-03-21 15:36:21 +0000825 // Compute the offset.
826 size_t I = Str.find(CharC->getSExtValue() & 0xFF);
827 if (I == StringRef::npos) // Didn't find the char. memchr returns null.
828 return Constant::getNullValue(CI->getType());
829
830 // memchr(s+n,c,l) -> gep(s+n+i,c)
David Blaikie3909da72015-03-30 20:42:56 +0000831 return B.CreateGEP(B.getInt8Ty(), SrcStr, B.getInt64(I), "memchr");
Benjamin Kramer691363e2015-03-21 15:36:21 +0000832}
833
Chris Bienemanad070d02014-09-17 20:55:46 +0000834Value *LibCallSimplifier::optimizeMemCmp(CallInst *CI, IRBuilder<> &B) {
835 Function *Callee = CI->getCalledFunction();
836 FunctionType *FT = Callee->getFunctionType();
837 if (FT->getNumParams() != 3 || !FT->getParamType(0)->isPointerTy() ||
838 !FT->getParamType(1)->isPointerTy() ||
839 !FT->getReturnType()->isIntegerTy(32))
Craig Topperf40110f2014-04-25 05:29:35 +0000840 return nullptr;
Meador Inge40b6fac2012-10-15 03:47:37 +0000841
Chris Bienemanad070d02014-09-17 20:55:46 +0000842 Value *LHS = CI->getArgOperand(0), *RHS = CI->getArgOperand(1);
Meador Inge40b6fac2012-10-15 03:47:37 +0000843
Chris Bienemanad070d02014-09-17 20:55:46 +0000844 if (LHS == RHS) // memcmp(s,s,x) -> 0
845 return Constant::getNullValue(CI->getType());
Meador Inge40b6fac2012-10-15 03:47:37 +0000846
Chris Bienemanad070d02014-09-17 20:55:46 +0000847 // Make sure we have a constant length.
848 ConstantInt *LenC = dyn_cast<ConstantInt>(CI->getArgOperand(2));
849 if (!LenC)
Craig Topperf40110f2014-04-25 05:29:35 +0000850 return nullptr;
Chris Bienemanad070d02014-09-17 20:55:46 +0000851 uint64_t Len = LenC->getZExtValue();
852
853 if (Len == 0) // memcmp(s1,s2,0) -> 0
854 return Constant::getNullValue(CI->getType());
855
856 // memcmp(S1,S2,1) -> *(unsigned char*)LHS - *(unsigned char*)RHS
857 if (Len == 1) {
858 Value *LHSV = B.CreateZExt(B.CreateLoad(CastToCStr(LHS, B), "lhsc"),
859 CI->getType(), "lhsv");
860 Value *RHSV = B.CreateZExt(B.CreateLoad(CastToCStr(RHS, B), "rhsc"),
861 CI->getType(), "rhsv");
862 return B.CreateSub(LHSV, RHSV, "chardiff");
Meador Inge40b6fac2012-10-15 03:47:37 +0000863 }
Meador Inge40b6fac2012-10-15 03:47:37 +0000864
Chris Bienemanad070d02014-09-17 20:55:46 +0000865 // Constant folding: memcmp(x, y, l) -> cnst (all arguments are constant)
866 StringRef LHSStr, RHSStr;
867 if (getConstantStringInfo(LHS, LHSStr) &&
868 getConstantStringInfo(RHS, RHSStr)) {
869 // Make sure we're not reading out-of-bounds memory.
870 if (Len > LHSStr.size() || Len > RHSStr.size())
Craig Topperf40110f2014-04-25 05:29:35 +0000871 return nullptr;
Chris Bienemanad070d02014-09-17 20:55:46 +0000872 // Fold the memcmp and normalize the result. This way we get consistent
873 // results across multiple platforms.
874 uint64_t Ret = 0;
875 int Cmp = memcmp(LHSStr.data(), RHSStr.data(), Len);
876 if (Cmp < 0)
877 Ret = -1;
878 else if (Cmp > 0)
879 Ret = 1;
880 return ConstantInt::get(CI->getType(), Ret);
Meador Inge000dbcc2012-10-18 18:12:40 +0000881 }
Meador Inge000dbcc2012-10-18 18:12:40 +0000882
Chris Bienemanad070d02014-09-17 20:55:46 +0000883 return nullptr;
884}
Meador Inge9a6a1902012-10-31 00:20:56 +0000885
Chris Bienemanad070d02014-09-17 20:55:46 +0000886Value *LibCallSimplifier::optimizeMemCpy(CallInst *CI, IRBuilder<> &B) {
887 Function *Callee = CI->getCalledFunction();
Meador Inged589ac62012-10-31 03:33:06 +0000888
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000889 if (!checkStringCopyLibFuncSignature(Callee, LibFunc::memcpy))
Craig Topperf40110f2014-04-25 05:29:35 +0000890 return nullptr;
Meador Inge6f8e0112012-10-31 04:29:58 +0000891
Chris Bienemanad070d02014-09-17 20:55:46 +0000892 // memcpy(x, y, n) -> llvm.memcpy(x, y, n, 1)
893 B.CreateMemCpy(CI->getArgOperand(0), CI->getArgOperand(1),
894 CI->getArgOperand(2), 1);
895 return CI->getArgOperand(0);
896}
Meador Inge05a625a2012-10-31 14:58:26 +0000897
Chris Bienemanad070d02014-09-17 20:55:46 +0000898Value *LibCallSimplifier::optimizeMemMove(CallInst *CI, IRBuilder<> &B) {
899 Function *Callee = CI->getCalledFunction();
Meador Inge05a625a2012-10-31 14:58:26 +0000900
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000901 if (!checkStringCopyLibFuncSignature(Callee, LibFunc::memmove))
Craig Topperf40110f2014-04-25 05:29:35 +0000902 return nullptr;
Meador Inge489b5d62012-11-08 01:33:50 +0000903
Chris Bienemanad070d02014-09-17 20:55:46 +0000904 // memmove(x, y, n) -> llvm.memmove(x, y, n, 1)
905 B.CreateMemMove(CI->getArgOperand(0), CI->getArgOperand(1),
906 CI->getArgOperand(2), 1);
907 return CI->getArgOperand(0);
908}
Meador Ingebcd88ef72012-11-10 15:16:48 +0000909
Chris Bienemanad070d02014-09-17 20:55:46 +0000910Value *LibCallSimplifier::optimizeMemSet(CallInst *CI, IRBuilder<> &B) {
911 Function *Callee = CI->getCalledFunction();
Meador Ingebcd88ef72012-11-10 15:16:48 +0000912
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000913 if (!checkStringCopyLibFuncSignature(Callee, LibFunc::memset))
Craig Topperf40110f2014-04-25 05:29:35 +0000914 return nullptr;
Meador Inge56edbc92012-11-11 03:51:48 +0000915
Chris Bienemanad070d02014-09-17 20:55:46 +0000916 // memset(p, v, n) -> llvm.memset(p, v, n, 1)
917 Value *Val = B.CreateIntCast(CI->getArgOperand(1), B.getInt8Ty(), false);
918 B.CreateMemSet(CI->getArgOperand(0), Val, CI->getArgOperand(2), 1);
919 return CI->getArgOperand(0);
920}
Meador Inged4825782012-11-11 06:49:03 +0000921
Meador Inge193e0352012-11-13 04:16:17 +0000922//===----------------------------------------------------------------------===//
923// Math Library Optimizations
924//===----------------------------------------------------------------------===//
925
Matthias Braund34e4d22014-12-03 21:46:33 +0000926/// Return a variant of Val with float type.
927/// Currently this works in two cases: If Val is an FPExtension of a float
928/// value to something bigger, simply return the operand.
929/// If Val is a ConstantFP but can be converted to a float ConstantFP without
930/// loss of precision do so.
931static Value *valueHasFloatPrecision(Value *Val) {
932 if (FPExtInst *Cast = dyn_cast<FPExtInst>(Val)) {
933 Value *Op = Cast->getOperand(0);
934 if (Op->getType()->isFloatTy())
935 return Op;
936 }
937 if (ConstantFP *Const = dyn_cast<ConstantFP>(Val)) {
938 APFloat F = Const->getValueAPF();
Matthias Braun395a82f2014-12-03 22:10:39 +0000939 bool losesInfo;
Matthias Braund34e4d22014-12-03 21:46:33 +0000940 (void)F.convert(APFloat::IEEEsingle, APFloat::rmNearestTiesToEven,
Matthias Braun395a82f2014-12-03 22:10:39 +0000941 &losesInfo);
942 if (!losesInfo)
Matthias Braund34e4d22014-12-03 21:46:33 +0000943 return ConstantFP::get(Const->getContext(), F);
944 }
945 return nullptr;
946}
947
Meador Inge193e0352012-11-13 04:16:17 +0000948//===----------------------------------------------------------------------===//
949// Double -> Float Shrinking Optimizations for Unary Functions like 'floor'
950
Chris Bienemanad070d02014-09-17 20:55:46 +0000951Value *LibCallSimplifier::optimizeUnaryDoubleFP(CallInst *CI, IRBuilder<> &B,
952 bool CheckRetType) {
953 Function *Callee = CI->getCalledFunction();
954 FunctionType *FT = Callee->getFunctionType();
955 if (FT->getNumParams() != 1 || !FT->getReturnType()->isDoubleTy() ||
956 !FT->getParamType(0)->isDoubleTy())
957 return nullptr;
Meador Inge193e0352012-11-13 04:16:17 +0000958
Chris Bienemanad070d02014-09-17 20:55:46 +0000959 if (CheckRetType) {
960 // Check if all the uses for function like 'sin' are converted to float.
961 for (User *U : CI->users()) {
962 FPTruncInst *Cast = dyn_cast<FPTruncInst>(U);
963 if (!Cast || !Cast->getType()->isFloatTy())
964 return nullptr;
Meador Inge193e0352012-11-13 04:16:17 +0000965 }
Meador Inge193e0352012-11-13 04:16:17 +0000966 }
Chris Bienemanad070d02014-09-17 20:55:46 +0000967
968 // If this is something like 'floor((double)floatval)', convert to floorf.
Matthias Braund34e4d22014-12-03 21:46:33 +0000969 Value *V = valueHasFloatPrecision(CI->getArgOperand(0));
970 if (V == nullptr)
Chris Bienemanad070d02014-09-17 20:55:46 +0000971 return nullptr;
972
973 // floor((double)floatval) -> (double)floorf(floatval)
Sanjay Patel848309d2014-10-23 21:52:45 +0000974 if (Callee->isIntrinsic()) {
975 Module *M = CI->getParent()->getParent()->getParent();
Pete Cooper9e1d3352015-05-20 17:16:39 +0000976 Intrinsic::ID IID = Callee->getIntrinsicID();
Sanjay Patel848309d2014-10-23 21:52:45 +0000977 Function *F = Intrinsic::getDeclaration(M, IID, B.getFloatTy());
978 V = B.CreateCall(F, V);
979 } else {
980 // The call is a library call rather than an intrinsic.
981 V = EmitUnaryFloatFnCall(V, Callee->getName(), B, Callee->getAttributes());
982 }
983
Chris Bienemanad070d02014-09-17 20:55:46 +0000984 return B.CreateFPExt(V, B.getDoubleTy());
985}
Meador Inge193e0352012-11-13 04:16:17 +0000986
Yi Jiang6ab044e2013-12-16 22:42:40 +0000987// Double -> Float Shrinking Optimizations for Binary Functions like 'fmin/fmax'
Chris Bienemanad070d02014-09-17 20:55:46 +0000988Value *LibCallSimplifier::optimizeBinaryDoubleFP(CallInst *CI, IRBuilder<> &B) {
989 Function *Callee = CI->getCalledFunction();
990 FunctionType *FT = Callee->getFunctionType();
991 // Just make sure this has 2 arguments of the same FP type, which match the
992 // result type.
993 if (FT->getNumParams() != 2 || FT->getReturnType() != FT->getParamType(0) ||
994 FT->getParamType(0) != FT->getParamType(1) ||
995 !FT->getParamType(0)->isFloatingPointTy())
Craig Topperf40110f2014-04-25 05:29:35 +0000996 return nullptr;
Meador Inge193e0352012-11-13 04:16:17 +0000997
Chris Bienemanad070d02014-09-17 20:55:46 +0000998 // If this is something like 'fmin((double)floatval1, (double)floatval2)',
Matthias Braund34e4d22014-12-03 21:46:33 +0000999 // or fmin(1.0, (double)floatval), then we convert it to fminf.
1000 Value *V1 = valueHasFloatPrecision(CI->getArgOperand(0));
1001 if (V1 == nullptr)
1002 return nullptr;
1003 Value *V2 = valueHasFloatPrecision(CI->getArgOperand(1));
1004 if (V2 == nullptr)
Craig Topperf40110f2014-04-25 05:29:35 +00001005 return nullptr;
Chris Bienemanad070d02014-09-17 20:55:46 +00001006
1007 // fmin((double)floatval1, (double)floatval2)
Matthias Braund34e4d22014-12-03 21:46:33 +00001008 // -> (double)fminf(floatval1, floatval2)
Sanjay Patel848309d2014-10-23 21:52:45 +00001009 // TODO: Handle intrinsics in the same way as in optimizeUnaryDoubleFP().
Matthias Braund34e4d22014-12-03 21:46:33 +00001010 Value *V = EmitBinaryFloatFnCall(V1, V2, Callee->getName(), B,
1011 Callee->getAttributes());
Chris Bienemanad070d02014-09-17 20:55:46 +00001012 return B.CreateFPExt(V, B.getDoubleTy());
1013}
1014
1015Value *LibCallSimplifier::optimizeCos(CallInst *CI, IRBuilder<> &B) {
1016 Function *Callee = CI->getCalledFunction();
1017 Value *Ret = nullptr;
1018 if (UnsafeFPShrink && Callee->getName() == "cos" && TLI->has(LibFunc::cosf)) {
1019 Ret = optimizeUnaryDoubleFP(CI, B, true);
Bob Wilsond8d92d92013-11-03 06:48:38 +00001020 }
1021
Chris Bienemanad070d02014-09-17 20:55:46 +00001022 FunctionType *FT = Callee->getFunctionType();
1023 // Just make sure this has 1 argument of FP type, which matches the
1024 // result type.
1025 if (FT->getNumParams() != 1 || FT->getReturnType() != FT->getParamType(0) ||
1026 !FT->getParamType(0)->isFloatingPointTy())
1027 return Ret;
Bob Wilsond8d92d92013-11-03 06:48:38 +00001028
Chris Bienemanad070d02014-09-17 20:55:46 +00001029 // cos(-x) -> cos(x)
1030 Value *Op1 = CI->getArgOperand(0);
1031 if (BinaryOperator::isFNeg(Op1)) {
1032 BinaryOperator *BinExpr = cast<BinaryOperator>(Op1);
1033 return B.CreateCall(Callee, BinExpr->getOperand(1), "cos");
1034 }
1035 return Ret;
1036}
Bob Wilsond8d92d92013-11-03 06:48:38 +00001037
Chris Bienemanad070d02014-09-17 20:55:46 +00001038Value *LibCallSimplifier::optimizePow(CallInst *CI, IRBuilder<> &B) {
1039 Function *Callee = CI->getCalledFunction();
1040
1041 Value *Ret = nullptr;
1042 if (UnsafeFPShrink && Callee->getName() == "pow" && TLI->has(LibFunc::powf)) {
1043 Ret = optimizeUnaryDoubleFP(CI, B, true);
Bob Wilsond8d92d92013-11-03 06:48:38 +00001044 }
1045
Chris Bienemanad070d02014-09-17 20:55:46 +00001046 FunctionType *FT = Callee->getFunctionType();
1047 // Just make sure this has 2 arguments of the same FP type, which match the
1048 // result type.
1049 if (FT->getNumParams() != 2 || FT->getReturnType() != FT->getParamType(0) ||
1050 FT->getParamType(0) != FT->getParamType(1) ||
1051 !FT->getParamType(0)->isFloatingPointTy())
1052 return Ret;
Bob Wilsond8d92d92013-11-03 06:48:38 +00001053
Chris Bienemanad070d02014-09-17 20:55:46 +00001054 Value *Op1 = CI->getArgOperand(0), *Op2 = CI->getArgOperand(1);
1055 if (ConstantFP *Op1C = dyn_cast<ConstantFP>(Op1)) {
1056 // pow(1.0, x) -> 1.0
1057 if (Op1C->isExactlyValue(1.0))
1058 return Op1C;
1059 // pow(2.0, x) -> exp2(x)
1060 if (Op1C->isExactlyValue(2.0) &&
1061 hasUnaryFloatFn(TLI, Op1->getType(), LibFunc::exp2, LibFunc::exp2f,
1062 LibFunc::exp2l))
1063 return EmitUnaryFloatFnCall(Op2, "exp2", B, Callee->getAttributes());
1064 // pow(10.0, x) -> exp10(x)
1065 if (Op1C->isExactlyValue(10.0) &&
1066 hasUnaryFloatFn(TLI, Op1->getType(), LibFunc::exp10, LibFunc::exp10f,
1067 LibFunc::exp10l))
1068 return EmitUnaryFloatFnCall(Op2, TLI->getName(LibFunc::exp10), B,
1069 Callee->getAttributes());
Bob Wilsond8d92d92013-11-03 06:48:38 +00001070 }
1071
Chris Bienemanad070d02014-09-17 20:55:46 +00001072 ConstantFP *Op2C = dyn_cast<ConstantFP>(Op2);
1073 if (!Op2C)
1074 return Ret;
1075
1076 if (Op2C->getValueAPF().isZero()) // pow(x, 0.0) -> 1.0
1077 return ConstantFP::get(CI->getType(), 1.0);
1078
1079 if (Op2C->isExactlyValue(0.5) &&
1080 hasUnaryFloatFn(TLI, Op2->getType(), LibFunc::sqrt, LibFunc::sqrtf,
1081 LibFunc::sqrtl) &&
1082 hasUnaryFloatFn(TLI, Op2->getType(), LibFunc::fabs, LibFunc::fabsf,
1083 LibFunc::fabsl)) {
1084 // Expand pow(x, 0.5) to (x == -infinity ? +infinity : fabs(sqrt(x))).
1085 // This is faster than calling pow, and still handles negative zero
1086 // and negative infinity correctly.
1087 // TODO: In fast-math mode, this could be just sqrt(x).
1088 // TODO: In finite-only mode, this could be just fabs(sqrt(x)).
1089 Value *Inf = ConstantFP::getInfinity(CI->getType());
1090 Value *NegInf = ConstantFP::getInfinity(CI->getType(), true);
1091 Value *Sqrt = EmitUnaryFloatFnCall(Op1, "sqrt", B, Callee->getAttributes());
1092 Value *FAbs =
1093 EmitUnaryFloatFnCall(Sqrt, "fabs", B, Callee->getAttributes());
1094 Value *FCmp = B.CreateFCmpOEQ(Op1, NegInf);
1095 Value *Sel = B.CreateSelect(FCmp, Inf, FAbs);
1096 return Sel;
Bob Wilsond8d92d92013-11-03 06:48:38 +00001097 }
1098
Chris Bienemanad070d02014-09-17 20:55:46 +00001099 if (Op2C->isExactlyValue(1.0)) // pow(x, 1.0) -> x
1100 return Op1;
1101 if (Op2C->isExactlyValue(2.0)) // pow(x, 2.0) -> x*x
1102 return B.CreateFMul(Op1, Op1, "pow2");
1103 if (Op2C->isExactlyValue(-1.0)) // pow(x, -1.0) -> 1.0/x
1104 return B.CreateFDiv(ConstantFP::get(CI->getType(), 1.0), Op1, "powrecip");
1105 return nullptr;
1106}
Bob Wilsond8d92d92013-11-03 06:48:38 +00001107
Chris Bienemanad070d02014-09-17 20:55:46 +00001108Value *LibCallSimplifier::optimizeExp2(CallInst *CI, IRBuilder<> &B) {
1109 Function *Callee = CI->getCalledFunction();
1110 Function *Caller = CI->getParent()->getParent();
Bob Wilsond8d92d92013-11-03 06:48:38 +00001111
Chris Bienemanad070d02014-09-17 20:55:46 +00001112 Value *Ret = nullptr;
1113 if (UnsafeFPShrink && Callee->getName() == "exp2" &&
1114 TLI->has(LibFunc::exp2f)) {
1115 Ret = optimizeUnaryDoubleFP(CI, B, true);
Bob Wilsond8d92d92013-11-03 06:48:38 +00001116 }
1117
Chris Bienemanad070d02014-09-17 20:55:46 +00001118 FunctionType *FT = Callee->getFunctionType();
1119 // Just make sure this has 1 argument of FP type, which matches the
1120 // result type.
1121 if (FT->getNumParams() != 1 || FT->getReturnType() != FT->getParamType(0) ||
1122 !FT->getParamType(0)->isFloatingPointTy())
1123 return Ret;
1124
1125 Value *Op = CI->getArgOperand(0);
1126 // Turn exp2(sitofp(x)) -> ldexp(1.0, sext(x)) if sizeof(x) <= 32
1127 // Turn exp2(uitofp(x)) -> ldexp(1.0, zext(x)) if sizeof(x) < 32
1128 LibFunc::Func LdExp = LibFunc::ldexpl;
1129 if (Op->getType()->isFloatTy())
1130 LdExp = LibFunc::ldexpf;
1131 else if (Op->getType()->isDoubleTy())
1132 LdExp = LibFunc::ldexp;
1133
1134 if (TLI->has(LdExp)) {
1135 Value *LdExpArg = nullptr;
1136 if (SIToFPInst *OpC = dyn_cast<SIToFPInst>(Op)) {
1137 if (OpC->getOperand(0)->getType()->getPrimitiveSizeInBits() <= 32)
1138 LdExpArg = B.CreateSExt(OpC->getOperand(0), B.getInt32Ty());
1139 } else if (UIToFPInst *OpC = dyn_cast<UIToFPInst>(Op)) {
1140 if (OpC->getOperand(0)->getType()->getPrimitiveSizeInBits() < 32)
1141 LdExpArg = B.CreateZExt(OpC->getOperand(0), B.getInt32Ty());
1142 }
1143
1144 if (LdExpArg) {
1145 Constant *One = ConstantFP::get(CI->getContext(), APFloat(1.0f));
1146 if (!Op->getType()->isFloatTy())
1147 One = ConstantExpr::getFPExtend(One, Op->getType());
1148
1149 Module *M = Caller->getParent();
1150 Value *Callee =
1151 M->getOrInsertFunction(TLI->getName(LdExp), Op->getType(),
Reid Kleckner971c3ea2014-11-13 22:55:19 +00001152 Op->getType(), B.getInt32Ty(), nullptr);
David Blaikieff6409d2015-05-18 22:13:54 +00001153 CallInst *CI = B.CreateCall(Callee, {One, LdExpArg});
Chris Bienemanad070d02014-09-17 20:55:46 +00001154 if (const Function *F = dyn_cast<Function>(Callee->stripPointerCasts()))
1155 CI->setCallingConv(F->getCallingConv());
1156
1157 return CI;
1158 }
1159 }
1160 return Ret;
1161}
1162
Sanjay Patel0ca42bb2014-10-14 20:43:11 +00001163Value *LibCallSimplifier::optimizeFabs(CallInst *CI, IRBuilder<> &B) {
1164 Function *Callee = CI->getCalledFunction();
1165
1166 Value *Ret = nullptr;
1167 if (Callee->getName() == "fabs" && TLI->has(LibFunc::fabsf)) {
1168 Ret = optimizeUnaryDoubleFP(CI, B, false);
1169 }
1170
1171 FunctionType *FT = Callee->getFunctionType();
1172 // Make sure this has 1 argument of FP type which matches the result type.
1173 if (FT->getNumParams() != 1 || FT->getReturnType() != FT->getParamType(0) ||
1174 !FT->getParamType(0)->isFloatingPointTy())
1175 return Ret;
1176
1177 Value *Op = CI->getArgOperand(0);
1178 if (Instruction *I = dyn_cast<Instruction>(Op)) {
1179 // Fold fabs(x * x) -> x * x; any squared FP value must already be positive.
1180 if (I->getOpcode() == Instruction::FMul)
1181 if (I->getOperand(0) == I->getOperand(1))
1182 return Op;
1183 }
1184 return Ret;
1185}
1186
Sanjay Patel57fd1dc2015-08-16 20:18:19 +00001187Value *LibCallSimplifier::optimizeFMinFMax(CallInst *CI, IRBuilder<> &B) {
1188 // If we can shrink the call to a float function rather than a double
1189 // function, do that first.
1190 Function *Callee = CI->getCalledFunction();
1191 if ((Callee->getName() == "fmin" && TLI->has(LibFunc::fminf)) ||
1192 (Callee->getName() == "fmax" && TLI->has(LibFunc::fmaxf))) {
1193 Value *Ret = optimizeBinaryDoubleFP(CI, B);
1194 if (Ret)
1195 return Ret;
1196 }
1197
1198 // Make sure this has 2 arguments of FP type which match the result type.
1199 FunctionType *FT = Callee->getFunctionType();
1200 if (FT->getNumParams() != 2 || FT->getReturnType() != FT->getParamType(0) ||
1201 FT->getParamType(0) != FT->getParamType(1) ||
1202 !FT->getParamType(0)->isFloatingPointTy())
1203 return nullptr;
1204
1205 // FIXME: For finer-grain optimization, we need intrinsics to have the same
1206 // fast-math flag decorations that are applied to FP instructions. For now,
1207 // we have to rely on the function-level attributes to do this optimization
1208 // because there's no other way to express that the calls can be relaxed.
1209 IRBuilder<true, ConstantFolder,
1210 IRBuilderDefaultInserter<true> >::FastMathFlagGuard Guard(B);
1211 FastMathFlags FMF;
1212 Function *F = CI->getParent()->getParent();
1213 Attribute Attr = F->getFnAttribute("unsafe-fp-math");
1214 if (Attr.getValueAsString() == "true") {
1215 // Unsafe algebra sets all fast-math-flags to true.
1216 FMF.setUnsafeAlgebra();
1217 } else {
1218 // At a minimum, no-nans-fp-math must be true.
1219 Attr = F->getFnAttribute("no-nans-fp-math");
1220 if (Attr.getValueAsString() != "true")
1221 return nullptr;
1222 // No-signed-zeros is implied by the definitions of fmax/fmin themselves:
1223 // "Ideally, fmax would be sensitive to the sign of zero, for example
1224 // fmax(−0. 0, +0. 0) would return +0; however, implementation in software
1225 // might be impractical."
1226 FMF.setNoSignedZeros();
1227 FMF.setNoNaNs();
1228 }
1229 B.SetFastMathFlags(FMF);
1230
1231 // We have a relaxed floating-point environment. We can ignore NaN-handling
1232 // and transform to a compare and select. We do not have to consider errno or
1233 // exceptions, because fmin/fmax do not have those.
1234 Value *Op0 = CI->getArgOperand(0);
1235 Value *Op1 = CI->getArgOperand(1);
1236 Value *Cmp = Callee->getName().startswith("fmin") ?
1237 B.CreateFCmpOLT(Op0, Op1) : B.CreateFCmpOGT(Op0, Op1);
1238 return B.CreateSelect(Cmp, Op0, Op1);
1239}
1240
Sanjay Patelc699a612014-10-16 18:48:17 +00001241Value *LibCallSimplifier::optimizeSqrt(CallInst *CI, IRBuilder<> &B) {
1242 Function *Callee = CI->getCalledFunction();
1243
1244 Value *Ret = nullptr;
Sanjay Patel848309d2014-10-23 21:52:45 +00001245 if (TLI->has(LibFunc::sqrtf) && (Callee->getName() == "sqrt" ||
1246 Callee->getIntrinsicID() == Intrinsic::sqrt))
Sanjay Patelc699a612014-10-16 18:48:17 +00001247 Ret = optimizeUnaryDoubleFP(CI, B, true);
Sanjay Patelc699a612014-10-16 18:48:17 +00001248
1249 // FIXME: For finer-grain optimization, we need intrinsics to have the same
1250 // fast-math flag decorations that are applied to FP instructions. For now,
1251 // we have to rely on the function-level unsafe-fp-math attribute to do this
1252 // optimization because there's no other way to express that the sqrt can be
1253 // reassociated.
1254 Function *F = CI->getParent()->getParent();
1255 if (F->hasFnAttribute("unsafe-fp-math")) {
1256 // Check for unsafe-fp-math = true.
1257 Attribute Attr = F->getFnAttribute("unsafe-fp-math");
1258 if (Attr.getValueAsString() != "true")
1259 return Ret;
1260 }
1261 Value *Op = CI->getArgOperand(0);
1262 if (Instruction *I = dyn_cast<Instruction>(Op)) {
1263 if (I->getOpcode() == Instruction::FMul && I->hasUnsafeAlgebra()) {
1264 // We're looking for a repeated factor in a multiplication tree,
1265 // so we can do this fold: sqrt(x * x) -> fabs(x);
1266 // or this fold: sqrt(x * x * y) -> fabs(x) * sqrt(y).
1267 Value *Op0 = I->getOperand(0);
1268 Value *Op1 = I->getOperand(1);
1269 Value *RepeatOp = nullptr;
1270 Value *OtherOp = nullptr;
1271 if (Op0 == Op1) {
1272 // Simple match: the operands of the multiply are identical.
1273 RepeatOp = Op0;
1274 } else {
1275 // Look for a more complicated pattern: one of the operands is itself
1276 // a multiply, so search for a common factor in that multiply.
1277 // Note: We don't bother looking any deeper than this first level or for
1278 // variations of this pattern because instcombine's visitFMUL and/or the
1279 // reassociation pass should give us this form.
1280 Value *OtherMul0, *OtherMul1;
1281 if (match(Op0, m_FMul(m_Value(OtherMul0), m_Value(OtherMul1)))) {
1282 // Pattern: sqrt((x * y) * z)
1283 if (OtherMul0 == OtherMul1) {
1284 // Matched: sqrt((x * x) * z)
1285 RepeatOp = OtherMul0;
1286 OtherOp = Op1;
1287 }
1288 }
1289 }
1290 if (RepeatOp) {
1291 // Fast math flags for any created instructions should match the sqrt
1292 // and multiply.
1293 // FIXME: We're not checking the sqrt because it doesn't have
1294 // fast-math-flags (see earlier comment).
1295 IRBuilder<true, ConstantFolder,
1296 IRBuilderDefaultInserter<true> >::FastMathFlagGuard Guard(B);
1297 B.SetFastMathFlags(I->getFastMathFlags());
1298 // If we found a repeated factor, hoist it out of the square root and
1299 // replace it with the fabs of that factor.
1300 Module *M = Callee->getParent();
1301 Type *ArgType = Op->getType();
1302 Value *Fabs = Intrinsic::getDeclaration(M, Intrinsic::fabs, ArgType);
1303 Value *FabsCall = B.CreateCall(Fabs, RepeatOp, "fabs");
1304 if (OtherOp) {
1305 // If we found a non-repeated factor, we still need to get its square
1306 // root. We then multiply that by the value that was simplified out
1307 // of the square root calculation.
1308 Value *Sqrt = Intrinsic::getDeclaration(M, Intrinsic::sqrt, ArgType);
1309 Value *SqrtCall = B.CreateCall(Sqrt, OtherOp, "sqrt");
1310 return B.CreateFMul(FabsCall, SqrtCall);
1311 }
1312 return FabsCall;
1313 }
1314 }
1315 }
1316 return Ret;
1317}
1318
Chris Bienemanad070d02014-09-17 20:55:46 +00001319static bool isTrigLibCall(CallInst *CI);
1320static void insertSinCosCall(IRBuilder<> &B, Function *OrigCallee, Value *Arg,
1321 bool UseFloat, Value *&Sin, Value *&Cos,
1322 Value *&SinCos);
1323
1324Value *LibCallSimplifier::optimizeSinCosPi(CallInst *CI, IRBuilder<> &B) {
1325
1326 // Make sure the prototype is as expected, otherwise the rest of the
1327 // function is probably invalid and likely to abort.
1328 if (!isTrigLibCall(CI))
1329 return nullptr;
1330
1331 Value *Arg = CI->getArgOperand(0);
1332 SmallVector<CallInst *, 1> SinCalls;
1333 SmallVector<CallInst *, 1> CosCalls;
1334 SmallVector<CallInst *, 1> SinCosCalls;
1335
1336 bool IsFloat = Arg->getType()->isFloatTy();
1337
1338 // Look for all compatible sinpi, cospi and sincospi calls with the same
1339 // argument. If there are enough (in some sense) we can make the
1340 // substitution.
1341 for (User *U : Arg->users())
1342 classifyArgUse(U, CI->getParent(), IsFloat, SinCalls, CosCalls,
1343 SinCosCalls);
1344
1345 // It's only worthwhile if both sinpi and cospi are actually used.
1346 if (SinCosCalls.empty() && (SinCalls.empty() || CosCalls.empty()))
1347 return nullptr;
1348
1349 Value *Sin, *Cos, *SinCos;
1350 insertSinCosCall(B, CI->getCalledFunction(), Arg, IsFloat, Sin, Cos, SinCos);
1351
1352 replaceTrigInsts(SinCalls, Sin);
1353 replaceTrigInsts(CosCalls, Cos);
1354 replaceTrigInsts(SinCosCalls, SinCos);
1355
1356 return nullptr;
1357}
1358
1359static bool isTrigLibCall(CallInst *CI) {
1360 Function *Callee = CI->getCalledFunction();
1361 FunctionType *FT = Callee->getFunctionType();
1362
1363 // We can only hope to do anything useful if we can ignore things like errno
1364 // and floating-point exceptions.
1365 bool AttributesSafe =
1366 CI->hasFnAttr(Attribute::NoUnwind) && CI->hasFnAttr(Attribute::ReadNone);
1367
1368 // Other than that we need float(float) or double(double)
1369 return AttributesSafe && FT->getNumParams() == 1 &&
1370 FT->getReturnType() == FT->getParamType(0) &&
1371 (FT->getParamType(0)->isFloatTy() ||
1372 FT->getParamType(0)->isDoubleTy());
1373}
1374
1375void
1376LibCallSimplifier::classifyArgUse(Value *Val, BasicBlock *BB, bool IsFloat,
1377 SmallVectorImpl<CallInst *> &SinCalls,
1378 SmallVectorImpl<CallInst *> &CosCalls,
1379 SmallVectorImpl<CallInst *> &SinCosCalls) {
1380 CallInst *CI = dyn_cast<CallInst>(Val);
1381
1382 if (!CI)
1383 return;
1384
1385 Function *Callee = CI->getCalledFunction();
1386 StringRef FuncName = Callee->getName();
1387 LibFunc::Func Func;
1388 if (!TLI->getLibFunc(FuncName, Func) || !TLI->has(Func) || !isTrigLibCall(CI))
1389 return;
1390
1391 if (IsFloat) {
1392 if (Func == LibFunc::sinpif)
1393 SinCalls.push_back(CI);
1394 else if (Func == LibFunc::cospif)
1395 CosCalls.push_back(CI);
1396 else if (Func == LibFunc::sincospif_stret)
1397 SinCosCalls.push_back(CI);
1398 } else {
1399 if (Func == LibFunc::sinpi)
1400 SinCalls.push_back(CI);
1401 else if (Func == LibFunc::cospi)
1402 CosCalls.push_back(CI);
1403 else if (Func == LibFunc::sincospi_stret)
1404 SinCosCalls.push_back(CI);
1405 }
1406}
1407
1408void LibCallSimplifier::replaceTrigInsts(SmallVectorImpl<CallInst *> &Calls,
1409 Value *Res) {
1410 for (SmallVectorImpl<CallInst *>::iterator I = Calls.begin(), E = Calls.end();
1411 I != E; ++I) {
1412 replaceAllUsesWith(*I, Res);
1413 }
1414}
1415
1416void insertSinCosCall(IRBuilder<> &B, Function *OrigCallee, Value *Arg,
1417 bool UseFloat, Value *&Sin, Value *&Cos, Value *&SinCos) {
1418 Type *ArgTy = Arg->getType();
1419 Type *ResTy;
1420 StringRef Name;
1421
1422 Triple T(OrigCallee->getParent()->getTargetTriple());
1423 if (UseFloat) {
1424 Name = "__sincospif_stret";
1425
1426 assert(T.getArch() != Triple::x86 && "x86 messy and unsupported for now");
1427 // x86_64 can't use {float, float} since that would be returned in both
1428 // xmm0 and xmm1, which isn't what a real struct would do.
1429 ResTy = T.getArch() == Triple::x86_64
1430 ? static_cast<Type *>(VectorType::get(ArgTy, 2))
Reid Kleckner971c3ea2014-11-13 22:55:19 +00001431 : static_cast<Type *>(StructType::get(ArgTy, ArgTy, nullptr));
Chris Bienemanad070d02014-09-17 20:55:46 +00001432 } else {
1433 Name = "__sincospi_stret";
Reid Kleckner971c3ea2014-11-13 22:55:19 +00001434 ResTy = StructType::get(ArgTy, ArgTy, nullptr);
Chris Bienemanad070d02014-09-17 20:55:46 +00001435 }
1436
1437 Module *M = OrigCallee->getParent();
1438 Value *Callee = M->getOrInsertFunction(Name, OrigCallee->getAttributes(),
Reid Kleckner971c3ea2014-11-13 22:55:19 +00001439 ResTy, ArgTy, nullptr);
Chris Bienemanad070d02014-09-17 20:55:46 +00001440
1441 if (Instruction *ArgInst = dyn_cast<Instruction>(Arg)) {
1442 // If the argument is an instruction, it must dominate all uses so put our
1443 // sincos call there.
1444 BasicBlock::iterator Loc = ArgInst;
1445 B.SetInsertPoint(ArgInst->getParent(), ++Loc);
1446 } else {
1447 // Otherwise (e.g. for a constant) the beginning of the function is as
1448 // good a place as any.
1449 BasicBlock &EntryBB = B.GetInsertBlock()->getParent()->getEntryBlock();
1450 B.SetInsertPoint(&EntryBB, EntryBB.begin());
1451 }
1452
1453 SinCos = B.CreateCall(Callee, Arg, "sincospi");
1454
1455 if (SinCos->getType()->isStructTy()) {
1456 Sin = B.CreateExtractValue(SinCos, 0, "sinpi");
1457 Cos = B.CreateExtractValue(SinCos, 1, "cospi");
1458 } else {
1459 Sin = B.CreateExtractElement(SinCos, ConstantInt::get(B.getInt32Ty(), 0),
1460 "sinpi");
1461 Cos = B.CreateExtractElement(SinCos, ConstantInt::get(B.getInt32Ty(), 1),
1462 "cospi");
1463 }
1464}
Bob Wilsond8d92d92013-11-03 06:48:38 +00001465
Meador Inge7415f842012-11-25 20:45:27 +00001466//===----------------------------------------------------------------------===//
1467// Integer Library Call Optimizations
1468//===----------------------------------------------------------------------===//
1469
Chris Bienemanad070d02014-09-17 20:55:46 +00001470Value *LibCallSimplifier::optimizeFFS(CallInst *CI, IRBuilder<> &B) {
1471 Function *Callee = CI->getCalledFunction();
1472 FunctionType *FT = Callee->getFunctionType();
1473 // Just make sure this has 2 arguments of the same FP type, which match the
1474 // result type.
1475 if (FT->getNumParams() != 1 || !FT->getReturnType()->isIntegerTy(32) ||
1476 !FT->getParamType(0)->isIntegerTy())
1477 return nullptr;
Meador Inge7415f842012-11-25 20:45:27 +00001478
Chris Bienemanad070d02014-09-17 20:55:46 +00001479 Value *Op = CI->getArgOperand(0);
Meador Inge7415f842012-11-25 20:45:27 +00001480
Chris Bienemanad070d02014-09-17 20:55:46 +00001481 // Constant fold.
1482 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op)) {
1483 if (CI->isZero()) // ffs(0) -> 0.
1484 return B.getInt32(0);
1485 // ffs(c) -> cttz(c)+1
1486 return B.getInt32(CI->getValue().countTrailingZeros() + 1);
Meador Inge7415f842012-11-25 20:45:27 +00001487 }
Meador Inge7415f842012-11-25 20:45:27 +00001488
Chris Bienemanad070d02014-09-17 20:55:46 +00001489 // ffs(x) -> x != 0 ? (i32)llvm.cttz(x)+1 : 0
1490 Type *ArgType = Op->getType();
1491 Value *F =
1492 Intrinsic::getDeclaration(Callee->getParent(), Intrinsic::cttz, ArgType);
Davide Italianoa1953862015-08-13 20:34:26 +00001493 Value *V = B.CreateCall(F, {Op, B.getTrue()}, "cttz");
Chris Bienemanad070d02014-09-17 20:55:46 +00001494 V = B.CreateAdd(V, ConstantInt::get(V->getType(), 1));
1495 V = B.CreateIntCast(V, B.getInt32Ty(), false);
Meador Ingea0b6d872012-11-26 00:24:07 +00001496
Chris Bienemanad070d02014-09-17 20:55:46 +00001497 Value *Cond = B.CreateICmpNE(Op, Constant::getNullValue(ArgType));
1498 return B.CreateSelect(Cond, V, B.getInt32(0));
1499}
Meador Ingea0b6d872012-11-26 00:24:07 +00001500
Chris Bienemanad070d02014-09-17 20:55:46 +00001501Value *LibCallSimplifier::optimizeAbs(CallInst *CI, IRBuilder<> &B) {
1502 Function *Callee = CI->getCalledFunction();
1503 FunctionType *FT = Callee->getFunctionType();
1504 // We require integer(integer) where the types agree.
1505 if (FT->getNumParams() != 1 || !FT->getReturnType()->isIntegerTy() ||
1506 FT->getParamType(0) != FT->getReturnType())
1507 return nullptr;
Meador Inge9a59ab62012-11-26 02:31:59 +00001508
Chris Bienemanad070d02014-09-17 20:55:46 +00001509 // abs(x) -> x >s -1 ? x : -x
1510 Value *Op = CI->getArgOperand(0);
1511 Value *Pos =
1512 B.CreateICmpSGT(Op, Constant::getAllOnesValue(Op->getType()), "ispos");
1513 Value *Neg = B.CreateNeg(Op, "neg");
1514 return B.CreateSelect(Pos, Op, Neg);
1515}
Meador Inge9a59ab62012-11-26 02:31:59 +00001516
Chris Bienemanad070d02014-09-17 20:55:46 +00001517Value *LibCallSimplifier::optimizeIsDigit(CallInst *CI, IRBuilder<> &B) {
1518 Function *Callee = CI->getCalledFunction();
1519 FunctionType *FT = Callee->getFunctionType();
1520 // We require integer(i32)
1521 if (FT->getNumParams() != 1 || !FT->getReturnType()->isIntegerTy() ||
1522 !FT->getParamType(0)->isIntegerTy(32))
1523 return nullptr;
Meador Ingea62a39e2012-11-26 03:10:07 +00001524
Chris Bienemanad070d02014-09-17 20:55:46 +00001525 // isdigit(c) -> (c-'0') <u 10
1526 Value *Op = CI->getArgOperand(0);
1527 Op = B.CreateSub(Op, B.getInt32('0'), "isdigittmp");
1528 Op = B.CreateICmpULT(Op, B.getInt32(10), "isdigit");
1529 return B.CreateZExt(Op, CI->getType());
1530}
Meador Ingea62a39e2012-11-26 03:10:07 +00001531
Chris Bienemanad070d02014-09-17 20:55:46 +00001532Value *LibCallSimplifier::optimizeIsAscii(CallInst *CI, IRBuilder<> &B) {
1533 Function *Callee = CI->getCalledFunction();
1534 FunctionType *FT = Callee->getFunctionType();
1535 // We require integer(i32)
1536 if (FT->getNumParams() != 1 || !FT->getReturnType()->isIntegerTy() ||
1537 !FT->getParamType(0)->isIntegerTy(32))
1538 return nullptr;
Meador Inge604937d2012-11-26 03:38:52 +00001539
Chris Bienemanad070d02014-09-17 20:55:46 +00001540 // isascii(c) -> c <u 128
1541 Value *Op = CI->getArgOperand(0);
1542 Op = B.CreateICmpULT(Op, B.getInt32(128), "isascii");
1543 return B.CreateZExt(Op, CI->getType());
1544}
1545
1546Value *LibCallSimplifier::optimizeToAscii(CallInst *CI, IRBuilder<> &B) {
1547 Function *Callee = CI->getCalledFunction();
1548 FunctionType *FT = Callee->getFunctionType();
1549 // We require i32(i32)
1550 if (FT->getNumParams() != 1 || FT->getReturnType() != FT->getParamType(0) ||
1551 !FT->getParamType(0)->isIntegerTy(32))
1552 return nullptr;
1553
1554 // toascii(c) -> c & 0x7f
1555 return B.CreateAnd(CI->getArgOperand(0),
1556 ConstantInt::get(CI->getType(), 0x7F));
1557}
Meador Inge604937d2012-11-26 03:38:52 +00001558
Meador Inge08ca1152012-11-26 20:37:20 +00001559//===----------------------------------------------------------------------===//
1560// Formatting and IO Library Call Optimizations
1561//===----------------------------------------------------------------------===//
1562
Chris Bienemanad070d02014-09-17 20:55:46 +00001563static bool isReportingError(Function *Callee, CallInst *CI, int StreamArg);
Hal Finkel66cd3f12013-11-17 02:06:35 +00001564
Chris Bienemanad070d02014-09-17 20:55:46 +00001565Value *LibCallSimplifier::optimizeErrorReporting(CallInst *CI, IRBuilder<> &B,
1566 int StreamArg) {
1567 // Error reporting calls should be cold, mark them as such.
1568 // This applies even to non-builtin calls: it is only a hint and applies to
1569 // functions that the frontend might not understand as builtins.
Hal Finkel66cd3f12013-11-17 02:06:35 +00001570
Chris Bienemanad070d02014-09-17 20:55:46 +00001571 // This heuristic was suggested in:
1572 // Improving Static Branch Prediction in a Compiler
1573 // Brian L. Deitrich, Ben-Chung Cheng, Wen-mei W. Hwu
1574 // Proceedings of PACT'98, Oct. 1998, IEEE
1575 Function *Callee = CI->getCalledFunction();
Hal Finkel66cd3f12013-11-17 02:06:35 +00001576
Chris Bienemanad070d02014-09-17 20:55:46 +00001577 if (!CI->hasFnAttr(Attribute::Cold) &&
1578 isReportingError(Callee, CI, StreamArg)) {
1579 CI->addAttribute(AttributeSet::FunctionIndex, Attribute::Cold);
1580 }
Hal Finkel66cd3f12013-11-17 02:06:35 +00001581
Chris Bienemanad070d02014-09-17 20:55:46 +00001582 return nullptr;
1583}
1584
1585static bool isReportingError(Function *Callee, CallInst *CI, int StreamArg) {
1586 if (!ColdErrorCalls)
1587 return false;
1588
1589 if (!Callee || !Callee->isDeclaration())
1590 return false;
1591
1592 if (StreamArg < 0)
1593 return true;
1594
1595 // These functions might be considered cold, but only if their stream
1596 // argument is stderr.
1597
1598 if (StreamArg >= (int)CI->getNumArgOperands())
1599 return false;
1600 LoadInst *LI = dyn_cast<LoadInst>(CI->getArgOperand(StreamArg));
1601 if (!LI)
1602 return false;
1603 GlobalVariable *GV = dyn_cast<GlobalVariable>(LI->getPointerOperand());
1604 if (!GV || !GV->isDeclaration())
1605 return false;
1606 return GV->getName() == "stderr";
1607}
1608
1609Value *LibCallSimplifier::optimizePrintFString(CallInst *CI, IRBuilder<> &B) {
1610 // Check for a fixed format string.
1611 StringRef FormatStr;
1612 if (!getConstantStringInfo(CI->getArgOperand(0), FormatStr))
Craig Topperf40110f2014-04-25 05:29:35 +00001613 return nullptr;
Hal Finkel66cd3f12013-11-17 02:06:35 +00001614
Chris Bienemanad070d02014-09-17 20:55:46 +00001615 // Empty format string -> noop.
1616 if (FormatStr.empty()) // Tolerate printf's declared void.
1617 return CI->use_empty() ? (Value *)CI : ConstantInt::get(CI->getType(), 0);
Hal Finkel66cd3f12013-11-17 02:06:35 +00001618
Chris Bienemanad070d02014-09-17 20:55:46 +00001619 // Do not do any of the following transformations if the printf return value
1620 // is used, in general the printf return value is not compatible with either
1621 // putchar() or puts().
1622 if (!CI->use_empty())
Craig Topperf40110f2014-04-25 05:29:35 +00001623 return nullptr;
Chris Bienemanad070d02014-09-17 20:55:46 +00001624
1625 // printf("x") -> putchar('x'), even for '%'.
1626 if (FormatStr.size() == 1) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001627 Value *Res = EmitPutChar(B.getInt32(FormatStr[0]), B, TLI);
Chris Bienemanad070d02014-09-17 20:55:46 +00001628 if (CI->use_empty() || !Res)
1629 return Res;
1630 return B.CreateIntCast(Res, CI->getType(), true);
Meador Inge08ca1152012-11-26 20:37:20 +00001631 }
1632
Chris Bienemanad070d02014-09-17 20:55:46 +00001633 // printf("foo\n") --> puts("foo")
1634 if (FormatStr[FormatStr.size() - 1] == '\n' &&
1635 FormatStr.find('%') == StringRef::npos) { // No format characters.
1636 // Create a string literal with no \n on it. We expect the constant merge
1637 // pass to be run after this pass, to merge duplicate strings.
1638 FormatStr = FormatStr.drop_back();
1639 Value *GV = B.CreateGlobalString(FormatStr, "str");
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001640 Value *NewCI = EmitPutS(GV, B, TLI);
Chris Bienemanad070d02014-09-17 20:55:46 +00001641 return (CI->use_empty() || !NewCI)
1642 ? NewCI
1643 : ConstantInt::get(CI->getType(), FormatStr.size() + 1);
1644 }
Meador Inge08ca1152012-11-26 20:37:20 +00001645
Chris Bienemanad070d02014-09-17 20:55:46 +00001646 // Optimize specific format strings.
1647 // printf("%c", chr) --> putchar(chr)
1648 if (FormatStr == "%c" && CI->getNumArgOperands() > 1 &&
1649 CI->getArgOperand(1)->getType()->isIntegerTy()) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001650 Value *Res = EmitPutChar(CI->getArgOperand(1), B, TLI);
Meador Inge08ca1152012-11-26 20:37:20 +00001651
Chris Bienemanad070d02014-09-17 20:55:46 +00001652 if (CI->use_empty() || !Res)
1653 return Res;
1654 return B.CreateIntCast(Res, CI->getType(), true);
1655 }
1656
1657 // printf("%s\n", str) --> puts(str)
1658 if (FormatStr == "%s\n" && CI->getNumArgOperands() > 1 &&
1659 CI->getArgOperand(1)->getType()->isPointerTy()) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001660 return EmitPutS(CI->getArgOperand(1), B, TLI);
Chris Bienemanad070d02014-09-17 20:55:46 +00001661 }
1662 return nullptr;
1663}
1664
1665Value *LibCallSimplifier::optimizePrintF(CallInst *CI, IRBuilder<> &B) {
1666
1667 Function *Callee = CI->getCalledFunction();
1668 // Require one fixed pointer argument and an integer/void result.
1669 FunctionType *FT = Callee->getFunctionType();
1670 if (FT->getNumParams() < 1 || !FT->getParamType(0)->isPointerTy() ||
1671 !(FT->getReturnType()->isIntegerTy() || FT->getReturnType()->isVoidTy()))
1672 return nullptr;
1673
1674 if (Value *V = optimizePrintFString(CI, B)) {
1675 return V;
1676 }
1677
1678 // printf(format, ...) -> iprintf(format, ...) if no floating point
1679 // arguments.
1680 if (TLI->has(LibFunc::iprintf) && !callHasFloatingPointArgument(CI)) {
1681 Module *M = B.GetInsertBlock()->getParent()->getParent();
1682 Constant *IPrintFFn =
Meador Inge08ca1152012-11-26 20:37:20 +00001683 M->getOrInsertFunction("iprintf", FT, Callee->getAttributes());
Chris Bienemanad070d02014-09-17 20:55:46 +00001684 CallInst *New = cast<CallInst>(CI->clone());
1685 New->setCalledFunction(IPrintFFn);
1686 B.Insert(New);
1687 return New;
Meador Inge08ca1152012-11-26 20:37:20 +00001688 }
Chris Bienemanad070d02014-09-17 20:55:46 +00001689 return nullptr;
1690}
Meador Inge08ca1152012-11-26 20:37:20 +00001691
Chris Bienemanad070d02014-09-17 20:55:46 +00001692Value *LibCallSimplifier::optimizeSPrintFString(CallInst *CI, IRBuilder<> &B) {
1693 // Check for a fixed format string.
1694 StringRef FormatStr;
1695 if (!getConstantStringInfo(CI->getArgOperand(1), FormatStr))
Craig Topperf40110f2014-04-25 05:29:35 +00001696 return nullptr;
Meador Inge25c9b3b2012-11-27 05:57:54 +00001697
Chris Bienemanad070d02014-09-17 20:55:46 +00001698 // If we just have a format string (nothing else crazy) transform it.
1699 if (CI->getNumArgOperands() == 2) {
1700 // Make sure there's no % in the constant array. We could try to handle
1701 // %% -> % in the future if we cared.
1702 for (unsigned i = 0, e = FormatStr.size(); i != e; ++i)
1703 if (FormatStr[i] == '%')
1704 return nullptr; // we found a format specifier, bail out.
Hal Finkel66cd3f12013-11-17 02:06:35 +00001705
Chris Bienemanad070d02014-09-17 20:55:46 +00001706 // sprintf(str, fmt) -> llvm.memcpy(str, fmt, strlen(fmt)+1, 1)
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001707 B.CreateMemCpy(CI->getArgOperand(0), CI->getArgOperand(1),
1708 ConstantInt::get(DL.getIntPtrType(CI->getContext()),
1709 FormatStr.size() + 1),
1710 1); // Copy the null byte.
Chris Bienemanad070d02014-09-17 20:55:46 +00001711 return ConstantInt::get(CI->getType(), FormatStr.size());
Meador Ingef8e72502012-11-29 15:45:43 +00001712 }
Meador Ingef8e72502012-11-29 15:45:43 +00001713
Chris Bienemanad070d02014-09-17 20:55:46 +00001714 // The remaining optimizations require the format string to be "%s" or "%c"
1715 // and have an extra operand.
1716 if (FormatStr.size() != 2 || FormatStr[0] != '%' ||
1717 CI->getNumArgOperands() < 3)
Craig Topperf40110f2014-04-25 05:29:35 +00001718 return nullptr;
Meador Inge75798bb2012-11-29 19:15:17 +00001719
Chris Bienemanad070d02014-09-17 20:55:46 +00001720 // Decode the second character of the format string.
1721 if (FormatStr[1] == 'c') {
1722 // sprintf(dst, "%c", chr) --> *(i8*)dst = chr; *((i8*)dst+1) = 0
1723 if (!CI->getArgOperand(2)->getType()->isIntegerTy())
1724 return nullptr;
1725 Value *V = B.CreateTrunc(CI->getArgOperand(2), B.getInt8Ty(), "char");
1726 Value *Ptr = CastToCStr(CI->getArgOperand(0), B);
1727 B.CreateStore(V, Ptr);
David Blaikie3909da72015-03-30 20:42:56 +00001728 Ptr = B.CreateGEP(B.getInt8Ty(), Ptr, B.getInt32(1), "nul");
Chris Bienemanad070d02014-09-17 20:55:46 +00001729 B.CreateStore(B.getInt8(0), Ptr);
Meador Ingedf796f82012-10-13 16:45:24 +00001730
Chris Bienemanad070d02014-09-17 20:55:46 +00001731 return ConstantInt::get(CI->getType(), 1);
Meador Ingedf796f82012-10-13 16:45:24 +00001732 }
1733
Chris Bienemanad070d02014-09-17 20:55:46 +00001734 if (FormatStr[1] == 's') {
Chris Bienemanad070d02014-09-17 20:55:46 +00001735 // sprintf(dest, "%s", str) -> llvm.memcpy(dest, str, strlen(str)+1, 1)
1736 if (!CI->getArgOperand(2)->getType()->isPointerTy())
1737 return nullptr;
1738
1739 Value *Len = EmitStrLen(CI->getArgOperand(2), B, DL, TLI);
1740 if (!Len)
1741 return nullptr;
1742 Value *IncLen =
1743 B.CreateAdd(Len, ConstantInt::get(Len->getType(), 1), "leninc");
1744 B.CreateMemCpy(CI->getArgOperand(0), CI->getArgOperand(2), IncLen, 1);
1745
1746 // The sprintf result is the unincremented number of bytes in the string.
1747 return B.CreateIntCast(Len, CI->getType(), false);
1748 }
1749 return nullptr;
1750}
1751
1752Value *LibCallSimplifier::optimizeSPrintF(CallInst *CI, IRBuilder<> &B) {
1753 Function *Callee = CI->getCalledFunction();
1754 // Require two fixed pointer arguments and an integer result.
1755 FunctionType *FT = Callee->getFunctionType();
1756 if (FT->getNumParams() != 2 || !FT->getParamType(0)->isPointerTy() ||
1757 !FT->getParamType(1)->isPointerTy() ||
1758 !FT->getReturnType()->isIntegerTy())
1759 return nullptr;
1760
1761 if (Value *V = optimizeSPrintFString(CI, B)) {
1762 return V;
1763 }
1764
1765 // sprintf(str, format, ...) -> siprintf(str, format, ...) if no floating
1766 // point arguments.
1767 if (TLI->has(LibFunc::siprintf) && !callHasFloatingPointArgument(CI)) {
1768 Module *M = B.GetInsertBlock()->getParent()->getParent();
1769 Constant *SIPrintFFn =
1770 M->getOrInsertFunction("siprintf", FT, Callee->getAttributes());
1771 CallInst *New = cast<CallInst>(CI->clone());
1772 New->setCalledFunction(SIPrintFFn);
1773 B.Insert(New);
1774 return New;
1775 }
1776 return nullptr;
1777}
1778
1779Value *LibCallSimplifier::optimizeFPrintFString(CallInst *CI, IRBuilder<> &B) {
1780 optimizeErrorReporting(CI, B, 0);
1781
1782 // All the optimizations depend on the format string.
1783 StringRef FormatStr;
1784 if (!getConstantStringInfo(CI->getArgOperand(1), FormatStr))
1785 return nullptr;
1786
1787 // Do not do any of the following transformations if the fprintf return
1788 // value is used, in general the fprintf return value is not compatible
1789 // with fwrite(), fputc() or fputs().
1790 if (!CI->use_empty())
1791 return nullptr;
1792
1793 // fprintf(F, "foo") --> fwrite("foo", 3, 1, F)
1794 if (CI->getNumArgOperands() == 2) {
1795 for (unsigned i = 0, e = FormatStr.size(); i != e; ++i)
1796 if (FormatStr[i] == '%') // Could handle %% -> % if we cared.
1797 return nullptr; // We found a format specifier.
1798
Chris Bienemanad070d02014-09-17 20:55:46 +00001799 return EmitFWrite(
1800 CI->getArgOperand(1),
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001801 ConstantInt::get(DL.getIntPtrType(CI->getContext()), FormatStr.size()),
Chris Bienemanad070d02014-09-17 20:55:46 +00001802 CI->getArgOperand(0), B, DL, TLI);
1803 }
1804
1805 // The remaining optimizations require the format string to be "%s" or "%c"
1806 // and have an extra operand.
1807 if (FormatStr.size() != 2 || FormatStr[0] != '%' ||
1808 CI->getNumArgOperands() < 3)
1809 return nullptr;
1810
1811 // Decode the second character of the format string.
1812 if (FormatStr[1] == 'c') {
1813 // fprintf(F, "%c", chr) --> fputc(chr, F)
1814 if (!CI->getArgOperand(2)->getType()->isIntegerTy())
1815 return nullptr;
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001816 return EmitFPutC(CI->getArgOperand(2), CI->getArgOperand(0), B, TLI);
Chris Bienemanad070d02014-09-17 20:55:46 +00001817 }
1818
1819 if (FormatStr[1] == 's') {
1820 // fprintf(F, "%s", str) --> fputs(str, F)
1821 if (!CI->getArgOperand(2)->getType()->isPointerTy())
1822 return nullptr;
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001823 return EmitFPutS(CI->getArgOperand(2), CI->getArgOperand(0), B, TLI);
Chris Bienemanad070d02014-09-17 20:55:46 +00001824 }
1825 return nullptr;
1826}
1827
1828Value *LibCallSimplifier::optimizeFPrintF(CallInst *CI, IRBuilder<> &B) {
1829 Function *Callee = CI->getCalledFunction();
1830 // Require two fixed paramters as pointers and integer result.
1831 FunctionType *FT = Callee->getFunctionType();
1832 if (FT->getNumParams() != 2 || !FT->getParamType(0)->isPointerTy() ||
1833 !FT->getParamType(1)->isPointerTy() ||
1834 !FT->getReturnType()->isIntegerTy())
1835 return nullptr;
1836
1837 if (Value *V = optimizeFPrintFString(CI, B)) {
1838 return V;
1839 }
1840
1841 // fprintf(stream, format, ...) -> fiprintf(stream, format, ...) if no
1842 // floating point arguments.
1843 if (TLI->has(LibFunc::fiprintf) && !callHasFloatingPointArgument(CI)) {
1844 Module *M = B.GetInsertBlock()->getParent()->getParent();
1845 Constant *FIPrintFFn =
1846 M->getOrInsertFunction("fiprintf", FT, Callee->getAttributes());
1847 CallInst *New = cast<CallInst>(CI->clone());
1848 New->setCalledFunction(FIPrintFFn);
1849 B.Insert(New);
1850 return New;
1851 }
1852 return nullptr;
1853}
1854
1855Value *LibCallSimplifier::optimizeFWrite(CallInst *CI, IRBuilder<> &B) {
1856 optimizeErrorReporting(CI, B, 3);
1857
1858 Function *Callee = CI->getCalledFunction();
1859 // Require a pointer, an integer, an integer, a pointer, returning integer.
1860 FunctionType *FT = Callee->getFunctionType();
1861 if (FT->getNumParams() != 4 || !FT->getParamType(0)->isPointerTy() ||
1862 !FT->getParamType(1)->isIntegerTy() ||
1863 !FT->getParamType(2)->isIntegerTy() ||
1864 !FT->getParamType(3)->isPointerTy() ||
1865 !FT->getReturnType()->isIntegerTy())
1866 return nullptr;
1867
1868 // Get the element size and count.
1869 ConstantInt *SizeC = dyn_cast<ConstantInt>(CI->getArgOperand(1));
1870 ConstantInt *CountC = dyn_cast<ConstantInt>(CI->getArgOperand(2));
1871 if (!SizeC || !CountC)
1872 return nullptr;
1873 uint64_t Bytes = SizeC->getZExtValue() * CountC->getZExtValue();
1874
1875 // If this is writing zero records, remove the call (it's a noop).
1876 if (Bytes == 0)
1877 return ConstantInt::get(CI->getType(), 0);
1878
1879 // If this is writing one byte, turn it into fputc.
1880 // This optimisation is only valid, if the return value is unused.
1881 if (Bytes == 1 && CI->use_empty()) { // fwrite(S,1,1,F) -> fputc(S[0],F)
1882 Value *Char = B.CreateLoad(CastToCStr(CI->getArgOperand(0), B), "char");
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001883 Value *NewCI = EmitFPutC(Char, CI->getArgOperand(3), B, TLI);
Chris Bienemanad070d02014-09-17 20:55:46 +00001884 return NewCI ? ConstantInt::get(CI->getType(), 1) : nullptr;
1885 }
1886
1887 return nullptr;
1888}
1889
1890Value *LibCallSimplifier::optimizeFPuts(CallInst *CI, IRBuilder<> &B) {
1891 optimizeErrorReporting(CI, B, 1);
1892
1893 Function *Callee = CI->getCalledFunction();
1894
Chris Bienemanad070d02014-09-17 20:55:46 +00001895 // Require two pointers. Also, we can't optimize if return value is used.
1896 FunctionType *FT = Callee->getFunctionType();
1897 if (FT->getNumParams() != 2 || !FT->getParamType(0)->isPointerTy() ||
1898 !FT->getParamType(1)->isPointerTy() || !CI->use_empty())
1899 return nullptr;
1900
1901 // fputs(s,F) --> fwrite(s,1,strlen(s),F)
1902 uint64_t Len = GetStringLength(CI->getArgOperand(0));
1903 if (!Len)
1904 return nullptr;
1905
1906 // Known to have no uses (see above).
1907 return EmitFWrite(
1908 CI->getArgOperand(0),
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001909 ConstantInt::get(DL.getIntPtrType(CI->getContext()), Len - 1),
Chris Bienemanad070d02014-09-17 20:55:46 +00001910 CI->getArgOperand(1), B, DL, TLI);
1911}
1912
1913Value *LibCallSimplifier::optimizePuts(CallInst *CI, IRBuilder<> &B) {
1914 Function *Callee = CI->getCalledFunction();
1915 // Require one fixed pointer argument and an integer/void result.
1916 FunctionType *FT = Callee->getFunctionType();
1917 if (FT->getNumParams() < 1 || !FT->getParamType(0)->isPointerTy() ||
1918 !(FT->getReturnType()->isIntegerTy() || FT->getReturnType()->isVoidTy()))
1919 return nullptr;
1920
1921 // Check for a constant string.
1922 StringRef Str;
1923 if (!getConstantStringInfo(CI->getArgOperand(0), Str))
1924 return nullptr;
1925
1926 if (Str.empty() && CI->use_empty()) {
1927 // puts("") -> putchar('\n')
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001928 Value *Res = EmitPutChar(B.getInt32('\n'), B, TLI);
Chris Bienemanad070d02014-09-17 20:55:46 +00001929 if (CI->use_empty() || !Res)
1930 return Res;
1931 return B.CreateIntCast(Res, CI->getType(), true);
1932 }
1933
1934 return nullptr;
1935}
1936
1937bool LibCallSimplifier::hasFloatVersion(StringRef FuncName) {
Meador Inge20255ef2013-03-12 00:08:29 +00001938 LibFunc::Func Func;
1939 SmallString<20> FloatFuncName = FuncName;
1940 FloatFuncName += 'f';
1941 if (TLI->getLibFunc(FloatFuncName, Func))
1942 return TLI->has(Func);
1943 return false;
1944}
Meador Inge7fb2f732012-10-13 16:45:32 +00001945
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00001946Value *LibCallSimplifier::optimizeStringMemoryLibCall(CallInst *CI,
1947 IRBuilder<> &Builder) {
1948 LibFunc::Func Func;
1949 Function *Callee = CI->getCalledFunction();
1950 StringRef FuncName = Callee->getName();
1951
1952 // Check for string/memory library functions.
1953 if (TLI->getLibFunc(FuncName, Func) && TLI->has(Func)) {
1954 // Make sure we never change the calling convention.
1955 assert((ignoreCallingConv(Func) ||
1956 CI->getCallingConv() == llvm::CallingConv::C) &&
1957 "Optimizing string/memory libcall would change the calling convention");
1958 switch (Func) {
1959 case LibFunc::strcat:
1960 return optimizeStrCat(CI, Builder);
1961 case LibFunc::strncat:
1962 return optimizeStrNCat(CI, Builder);
1963 case LibFunc::strchr:
1964 return optimizeStrChr(CI, Builder);
1965 case LibFunc::strrchr:
1966 return optimizeStrRChr(CI, Builder);
1967 case LibFunc::strcmp:
1968 return optimizeStrCmp(CI, Builder);
1969 case LibFunc::strncmp:
1970 return optimizeStrNCmp(CI, Builder);
1971 case LibFunc::strcpy:
1972 return optimizeStrCpy(CI, Builder);
1973 case LibFunc::stpcpy:
1974 return optimizeStpCpy(CI, Builder);
1975 case LibFunc::strncpy:
1976 return optimizeStrNCpy(CI, Builder);
1977 case LibFunc::strlen:
1978 return optimizeStrLen(CI, Builder);
1979 case LibFunc::strpbrk:
1980 return optimizeStrPBrk(CI, Builder);
1981 case LibFunc::strtol:
1982 case LibFunc::strtod:
1983 case LibFunc::strtof:
1984 case LibFunc::strtoul:
1985 case LibFunc::strtoll:
1986 case LibFunc::strtold:
1987 case LibFunc::strtoull:
1988 return optimizeStrTo(CI, Builder);
1989 case LibFunc::strspn:
1990 return optimizeStrSpn(CI, Builder);
1991 case LibFunc::strcspn:
1992 return optimizeStrCSpn(CI, Builder);
1993 case LibFunc::strstr:
1994 return optimizeStrStr(CI, Builder);
Benjamin Kramer691363e2015-03-21 15:36:21 +00001995 case LibFunc::memchr:
1996 return optimizeMemChr(CI, Builder);
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00001997 case LibFunc::memcmp:
1998 return optimizeMemCmp(CI, Builder);
1999 case LibFunc::memcpy:
2000 return optimizeMemCpy(CI, Builder);
2001 case LibFunc::memmove:
2002 return optimizeMemMove(CI, Builder);
2003 case LibFunc::memset:
2004 return optimizeMemSet(CI, Builder);
2005 default:
2006 break;
2007 }
2008 }
2009 return nullptr;
2010}
2011
Chris Bienemanad070d02014-09-17 20:55:46 +00002012Value *LibCallSimplifier::optimizeCall(CallInst *CI) {
2013 if (CI->isNoBuiltin())
2014 return nullptr;
Meador Inge4d2827c2012-11-11 05:11:20 +00002015
Meador Inge20255ef2013-03-12 00:08:29 +00002016 LibFunc::Func Func;
2017 Function *Callee = CI->getCalledFunction();
2018 StringRef FuncName = Callee->getName();
Chris Bienemanad070d02014-09-17 20:55:46 +00002019 IRBuilder<> Builder(CI);
2020 bool isCallingConvC = CI->getCallingConv() == llvm::CallingConv::C;
Meador Inge20255ef2013-03-12 00:08:29 +00002021
Sanjay Patela92fa442014-10-22 15:29:23 +00002022 // Command-line parameter overrides function attribute.
2023 if (EnableUnsafeFPShrink.getNumOccurrences() > 0)
2024 UnsafeFPShrink = EnableUnsafeFPShrink;
2025 else if (Callee->hasFnAttribute("unsafe-fp-math")) {
2026 // FIXME: This is the same problem as described in optimizeSqrt().
2027 // If calls gain access to IR-level FMF, then use that instead of a
2028 // function attribute.
2029
2030 // Check for unsafe-fp-math = true.
2031 Attribute Attr = Callee->getFnAttribute("unsafe-fp-math");
2032 if (Attr.getValueAsString() == "true")
2033 UnsafeFPShrink = true;
2034 }
2035
Sanjay Patel848309d2014-10-23 21:52:45 +00002036 // First, check for intrinsics.
Meador Inge20255ef2013-03-12 00:08:29 +00002037 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(CI)) {
Chris Bienemanad070d02014-09-17 20:55:46 +00002038 if (!isCallingConvC)
2039 return nullptr;
Meador Inge20255ef2013-03-12 00:08:29 +00002040 switch (II->getIntrinsicID()) {
2041 case Intrinsic::pow:
Chris Bienemanad070d02014-09-17 20:55:46 +00002042 return optimizePow(CI, Builder);
Meador Inge20255ef2013-03-12 00:08:29 +00002043 case Intrinsic::exp2:
Chris Bienemanad070d02014-09-17 20:55:46 +00002044 return optimizeExp2(CI, Builder);
Sanjay Patel0ca42bb2014-10-14 20:43:11 +00002045 case Intrinsic::fabs:
2046 return optimizeFabs(CI, Builder);
Sanjay Patelc699a612014-10-16 18:48:17 +00002047 case Intrinsic::sqrt:
2048 return optimizeSqrt(CI, Builder);
Meador Inge20255ef2013-03-12 00:08:29 +00002049 default:
Chris Bienemanad070d02014-09-17 20:55:46 +00002050 return nullptr;
Meador Inge20255ef2013-03-12 00:08:29 +00002051 }
2052 }
2053
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002054 // Also try to simplify calls to fortified library functions.
2055 if (Value *SimplifiedFortifiedCI = FortifiedSimplifier.optimizeCall(CI)) {
2056 // Try to further simplify the result.
Ahmed Bougacha71d7b182015-01-14 00:55:05 +00002057 CallInst *SimplifiedCI = dyn_cast<CallInst>(SimplifiedFortifiedCI);
2058 if (SimplifiedCI && SimplifiedCI->getCalledFunction())
Ahmed Bougacha1ac93562015-01-27 21:52:16 +00002059 if (Value *V = optimizeStringMemoryLibCall(SimplifiedCI, Builder)) {
2060 // If we were able to further simplify, remove the now redundant call.
2061 SimplifiedCI->replaceAllUsesWith(V);
2062 SimplifiedCI->eraseFromParent();
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002063 return V;
Ahmed Bougacha1ac93562015-01-27 21:52:16 +00002064 }
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002065 return SimplifiedFortifiedCI;
2066 }
2067
Meador Inge20255ef2013-03-12 00:08:29 +00002068 // Then check for known library functions.
2069 if (TLI->getLibFunc(FuncName, Func) && TLI->has(Func)) {
Chris Bienemanad070d02014-09-17 20:55:46 +00002070 // We never change the calling convention.
2071 if (!ignoreCallingConv(Func) && !isCallingConvC)
2072 return nullptr;
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00002073 if (Value *V = optimizeStringMemoryLibCall(CI, Builder))
2074 return V;
Meador Inge20255ef2013-03-12 00:08:29 +00002075 switch (Func) {
Chris Bienemanad070d02014-09-17 20:55:46 +00002076 case LibFunc::cosf:
2077 case LibFunc::cos:
2078 case LibFunc::cosl:
2079 return optimizeCos(CI, Builder);
2080 case LibFunc::sinpif:
2081 case LibFunc::sinpi:
2082 case LibFunc::cospif:
2083 case LibFunc::cospi:
2084 return optimizeSinCosPi(CI, Builder);
2085 case LibFunc::powf:
2086 case LibFunc::pow:
2087 case LibFunc::powl:
2088 return optimizePow(CI, Builder);
2089 case LibFunc::exp2l:
2090 case LibFunc::exp2:
2091 case LibFunc::exp2f:
2092 return optimizeExp2(CI, Builder);
Sanjay Patel0ca42bb2014-10-14 20:43:11 +00002093 case LibFunc::fabsf:
2094 case LibFunc::fabs:
2095 case LibFunc::fabsl:
2096 return optimizeFabs(CI, Builder);
Sanjay Patelc699a612014-10-16 18:48:17 +00002097 case LibFunc::sqrtf:
2098 case LibFunc::sqrt:
2099 case LibFunc::sqrtl:
2100 return optimizeSqrt(CI, Builder);
Chris Bienemanad070d02014-09-17 20:55:46 +00002101 case LibFunc::ffs:
2102 case LibFunc::ffsl:
2103 case LibFunc::ffsll:
2104 return optimizeFFS(CI, Builder);
2105 case LibFunc::abs:
2106 case LibFunc::labs:
2107 case LibFunc::llabs:
2108 return optimizeAbs(CI, Builder);
2109 case LibFunc::isdigit:
2110 return optimizeIsDigit(CI, Builder);
2111 case LibFunc::isascii:
2112 return optimizeIsAscii(CI, Builder);
2113 case LibFunc::toascii:
2114 return optimizeToAscii(CI, Builder);
2115 case LibFunc::printf:
2116 return optimizePrintF(CI, Builder);
2117 case LibFunc::sprintf:
2118 return optimizeSPrintF(CI, Builder);
2119 case LibFunc::fprintf:
2120 return optimizeFPrintF(CI, Builder);
2121 case LibFunc::fwrite:
2122 return optimizeFWrite(CI, Builder);
2123 case LibFunc::fputs:
2124 return optimizeFPuts(CI, Builder);
2125 case LibFunc::puts:
2126 return optimizePuts(CI, Builder);
2127 case LibFunc::perror:
2128 return optimizeErrorReporting(CI, Builder);
2129 case LibFunc::vfprintf:
2130 case LibFunc::fiprintf:
2131 return optimizeErrorReporting(CI, Builder, 0);
2132 case LibFunc::fputc:
2133 return optimizeErrorReporting(CI, Builder, 1);
2134 case LibFunc::ceil:
Chris Bienemanad070d02014-09-17 20:55:46 +00002135 case LibFunc::floor:
2136 case LibFunc::rint:
2137 case LibFunc::round:
2138 case LibFunc::nearbyint:
2139 case LibFunc::trunc:
2140 if (hasFloatVersion(FuncName))
2141 return optimizeUnaryDoubleFP(CI, Builder, false);
2142 return nullptr;
2143 case LibFunc::acos:
2144 case LibFunc::acosh:
2145 case LibFunc::asin:
2146 case LibFunc::asinh:
2147 case LibFunc::atan:
2148 case LibFunc::atanh:
2149 case LibFunc::cbrt:
2150 case LibFunc::cosh:
2151 case LibFunc::exp:
2152 case LibFunc::exp10:
2153 case LibFunc::expm1:
2154 case LibFunc::log:
2155 case LibFunc::log10:
2156 case LibFunc::log1p:
2157 case LibFunc::log2:
2158 case LibFunc::logb:
2159 case LibFunc::sin:
2160 case LibFunc::sinh:
Chris Bienemanad070d02014-09-17 20:55:46 +00002161 case LibFunc::tan:
2162 case LibFunc::tanh:
2163 if (UnsafeFPShrink && hasFloatVersion(FuncName))
2164 return optimizeUnaryDoubleFP(CI, Builder, true);
2165 return nullptr;
Matthias Braun892c9232014-12-03 21:46:29 +00002166 case LibFunc::copysign:
Chris Bienemanad070d02014-09-17 20:55:46 +00002167 if (hasFloatVersion(FuncName))
2168 return optimizeBinaryDoubleFP(CI, Builder);
2169 return nullptr;
Sanjay Patel57fd1dc2015-08-16 20:18:19 +00002170 case LibFunc::fminf:
2171 case LibFunc::fmin:
2172 case LibFunc::fminl:
2173 case LibFunc::fmaxf:
2174 case LibFunc::fmax:
2175 case LibFunc::fmaxl:
2176 return optimizeFMinFMax(CI, Builder);
Chris Bienemanad070d02014-09-17 20:55:46 +00002177 default:
2178 return nullptr;
2179 }
Meador Inge20255ef2013-03-12 00:08:29 +00002180 }
Craig Topperf40110f2014-04-25 05:29:35 +00002181 return nullptr;
Meador Ingedf796f82012-10-13 16:45:24 +00002182}
2183
Chandler Carruth92803822015-01-21 02:11:59 +00002184LibCallSimplifier::LibCallSimplifier(
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002185 const DataLayout &DL, const TargetLibraryInfo *TLI,
Chandler Carruth92803822015-01-21 02:11:59 +00002186 function_ref<void(Instruction *, Value *)> Replacer)
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002187 : FortifiedSimplifier(TLI), DL(DL), TLI(TLI), UnsafeFPShrink(false),
Chandler Carruth92803822015-01-21 02:11:59 +00002188 Replacer(Replacer) {}
2189
2190void LibCallSimplifier::replaceAllUsesWith(Instruction *I, Value *With) {
2191 // Indirect through the replacer used in this instance.
2192 Replacer(I, With);
Meador Ingedf796f82012-10-13 16:45:24 +00002193}
2194
Chandler Carruth92803822015-01-21 02:11:59 +00002195/*static*/ void LibCallSimplifier::replaceAllUsesWithDefault(Instruction *I,
2196 Value *With) {
Meador Inge76fc1a42012-11-11 03:51:43 +00002197 I->replaceAllUsesWith(With);
2198 I->eraseFromParent();
2199}
2200
Meador Ingedfb08a22013-06-20 19:48:07 +00002201// TODO:
2202// Additional cases that we need to add to this file:
2203//
2204// cbrt:
2205// * cbrt(expN(X)) -> expN(x/3)
2206// * cbrt(sqrt(x)) -> pow(x,1/6)
2207// * cbrt(sqrt(x)) -> pow(x,1/9)
2208//
2209// exp, expf, expl:
2210// * exp(log(x)) -> x
2211//
2212// log, logf, logl:
2213// * log(exp(x)) -> x
2214// * log(x**y) -> y*log(x)
2215// * log(exp(y)) -> y*log(e)
2216// * log(exp2(y)) -> y*log(2)
2217// * log(exp10(y)) -> y*log(10)
2218// * log(sqrt(x)) -> 0.5*log(x)
2219// * log(pow(x,y)) -> y*log(x)
2220//
2221// lround, lroundf, lroundl:
2222// * lround(cnst) -> cnst'
2223//
2224// pow, powf, powl:
2225// * pow(exp(x),y) -> exp(x*y)
2226// * pow(sqrt(x),y) -> pow(x,y*0.5)
2227// * pow(pow(x,y),z)-> pow(x,y*z)
2228//
2229// round, roundf, roundl:
2230// * round(cnst) -> cnst'
2231//
2232// signbit:
2233// * signbit(cnst) -> cnst'
2234// * signbit(nncst) -> 0 (if pstv is a non-negative constant)
2235//
2236// sqrt, sqrtf, sqrtl:
2237// * sqrt(expN(x)) -> expN(x*0.5)
2238// * sqrt(Nroot(x)) -> pow(x,1/(2*N))
2239// * sqrt(pow(x,y)) -> pow(|x|,y*0.5)
2240//
Meador Ingedfb08a22013-06-20 19:48:07 +00002241// tan, tanf, tanl:
2242// * tan(atan(x)) -> x
2243//
2244// trunc, truncf, truncl:
2245// * trunc(cnst) -> cnst'
2246//
2247//
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002248
2249//===----------------------------------------------------------------------===//
2250// Fortified Library Call Optimizations
2251//===----------------------------------------------------------------------===//
2252
2253bool FortifiedLibCallSimplifier::isFortifiedCallFoldable(CallInst *CI,
2254 unsigned ObjSizeOp,
2255 unsigned SizeOp,
2256 bool isString) {
2257 if (CI->getArgOperand(ObjSizeOp) == CI->getArgOperand(SizeOp))
2258 return true;
2259 if (ConstantInt *ObjSizeCI =
2260 dyn_cast<ConstantInt>(CI->getArgOperand(ObjSizeOp))) {
2261 if (ObjSizeCI->isAllOnesValue())
2262 return true;
2263 // If the object size wasn't -1 (unknown), bail out if we were asked to.
2264 if (OnlyLowerUnknownSize)
2265 return false;
2266 if (isString) {
2267 uint64_t Len = GetStringLength(CI->getArgOperand(SizeOp));
2268 // If the length is 0 we don't know how long it is and so we can't
2269 // remove the check.
2270 if (Len == 0)
2271 return false;
2272 return ObjSizeCI->getZExtValue() >= Len;
2273 }
2274 if (ConstantInt *SizeCI = dyn_cast<ConstantInt>(CI->getArgOperand(SizeOp)))
2275 return ObjSizeCI->getZExtValue() >= SizeCI->getZExtValue();
2276 }
2277 return false;
2278}
2279
2280Value *FortifiedLibCallSimplifier::optimizeMemCpyChk(CallInst *CI, IRBuilder<> &B) {
2281 Function *Callee = CI->getCalledFunction();
2282
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002283 if (!checkStringCopyLibFuncSignature(Callee, LibFunc::memcpy_chk))
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002284 return nullptr;
2285
2286 if (isFortifiedCallFoldable(CI, 3, 2, false)) {
2287 B.CreateMemCpy(CI->getArgOperand(0), CI->getArgOperand(1),
2288 CI->getArgOperand(2), 1);
2289 return CI->getArgOperand(0);
2290 }
2291 return nullptr;
2292}
2293
2294Value *FortifiedLibCallSimplifier::optimizeMemMoveChk(CallInst *CI, IRBuilder<> &B) {
2295 Function *Callee = CI->getCalledFunction();
2296
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002297 if (!checkStringCopyLibFuncSignature(Callee, LibFunc::memmove_chk))
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002298 return nullptr;
2299
2300 if (isFortifiedCallFoldable(CI, 3, 2, false)) {
2301 B.CreateMemMove(CI->getArgOperand(0), CI->getArgOperand(1),
2302 CI->getArgOperand(2), 1);
2303 return CI->getArgOperand(0);
2304 }
2305 return nullptr;
2306}
2307
2308Value *FortifiedLibCallSimplifier::optimizeMemSetChk(CallInst *CI, IRBuilder<> &B) {
2309 Function *Callee = CI->getCalledFunction();
2310
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002311 if (!checkStringCopyLibFuncSignature(Callee, LibFunc::memset_chk))
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002312 return nullptr;
2313
2314 if (isFortifiedCallFoldable(CI, 3, 2, false)) {
2315 Value *Val = B.CreateIntCast(CI->getArgOperand(1), B.getInt8Ty(), false);
2316 B.CreateMemSet(CI->getArgOperand(0), Val, CI->getArgOperand(2), 1);
2317 return CI->getArgOperand(0);
2318 }
2319 return nullptr;
2320}
2321
Ahmed Bougacha1ac93562015-01-27 21:52:16 +00002322Value *FortifiedLibCallSimplifier::optimizeStrpCpyChk(CallInst *CI,
2323 IRBuilder<> &B,
2324 LibFunc::Func Func) {
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002325 Function *Callee = CI->getCalledFunction();
2326 StringRef Name = Callee->getName();
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002327 const DataLayout &DL = CI->getModule()->getDataLayout();
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002328
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002329 if (!checkStringCopyLibFuncSignature(Callee, Func))
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002330 return nullptr;
2331
2332 Value *Dst = CI->getArgOperand(0), *Src = CI->getArgOperand(1),
2333 *ObjSize = CI->getArgOperand(2);
2334
2335 // __stpcpy_chk(x,x,...) -> x+strlen(x)
Ahmed Bougacha1ac93562015-01-27 21:52:16 +00002336 if (Func == LibFunc::stpcpy_chk && !OnlyLowerUnknownSize && Dst == Src) {
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002337 Value *StrLen = EmitStrLen(Src, B, DL, TLI);
David Blaikieaa41cd52015-04-03 21:33:42 +00002338 return StrLen ? B.CreateInBoundsGEP(B.getInt8Ty(), Dst, StrLen) : nullptr;
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002339 }
2340
2341 // If a) we don't have any length information, or b) we know this will
2342 // fit then just lower to a plain st[rp]cpy. Otherwise we'll keep our
2343 // st[rp]cpy_chk call which may fail at runtime if the size is too long.
2344 // TODO: It might be nice to get a maximum length out of the possible
2345 // string lengths for varying.
David Blaikie65fab6d2015-04-03 21:32:06 +00002346 if (isFortifiedCallFoldable(CI, 2, 1, true))
2347 return EmitStrCpy(Dst, Src, B, TLI, Name.substr(2, 6));
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002348
David Blaikie65fab6d2015-04-03 21:32:06 +00002349 if (OnlyLowerUnknownSize)
2350 return nullptr;
2351
2352 // Maybe we can stil fold __st[rp]cpy_chk to __memcpy_chk.
2353 uint64_t Len = GetStringLength(Src);
2354 if (Len == 0)
2355 return nullptr;
2356
2357 Type *SizeTTy = DL.getIntPtrType(CI->getContext());
2358 Value *LenV = ConstantInt::get(SizeTTy, Len);
2359 Value *Ret = EmitMemCpyChk(Dst, Src, LenV, ObjSize, B, DL, TLI);
2360 // If the function was an __stpcpy_chk, and we were able to fold it into
2361 // a __memcpy_chk, we still need to return the correct end pointer.
2362 if (Ret && Func == LibFunc::stpcpy_chk)
2363 return B.CreateGEP(B.getInt8Ty(), Dst, ConstantInt::get(SizeTTy, Len - 1));
2364 return Ret;
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002365}
2366
Ahmed Bougacha1ac93562015-01-27 21:52:16 +00002367Value *FortifiedLibCallSimplifier::optimizeStrpNCpyChk(CallInst *CI,
2368 IRBuilder<> &B,
2369 LibFunc::Func Func) {
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002370 Function *Callee = CI->getCalledFunction();
2371 StringRef Name = Callee->getName();
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002372
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002373 if (!checkStringCopyLibFuncSignature(Callee, Func))
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002374 return nullptr;
2375 if (isFortifiedCallFoldable(CI, 3, 2, false)) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002376 Value *Ret = EmitStrNCpy(CI->getArgOperand(0), CI->getArgOperand(1),
2377 CI->getArgOperand(2), B, TLI, Name.substr(2, 7));
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002378 return Ret;
2379 }
2380 return nullptr;
2381}
2382
2383Value *FortifiedLibCallSimplifier::optimizeCall(CallInst *CI) {
Ahmed Bougacha408d0102015-04-01 00:45:09 +00002384 // FIXME: We shouldn't be changing "nobuiltin" or TLI unavailable calls here.
2385 // Some clang users checked for _chk libcall availability using:
2386 // __has_builtin(__builtin___memcpy_chk)
2387 // When compiling with -fno-builtin, this is always true.
2388 // When passing -ffreestanding/-mkernel, which both imply -fno-builtin, we
2389 // end up with fortified libcalls, which isn't acceptable in a freestanding
2390 // environment which only provides their non-fortified counterparts.
2391 //
2392 // Until we change clang and/or teach external users to check for availability
2393 // differently, disregard the "nobuiltin" attribute and TLI::has.
2394 //
2395 // PR23093.
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002396
2397 LibFunc::Func Func;
2398 Function *Callee = CI->getCalledFunction();
2399 StringRef FuncName = Callee->getName();
2400 IRBuilder<> Builder(CI);
2401 bool isCallingConvC = CI->getCallingConv() == llvm::CallingConv::C;
2402
2403 // First, check that this is a known library functions.
Ahmed Bougacha408d0102015-04-01 00:45:09 +00002404 if (!TLI->getLibFunc(FuncName, Func))
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002405 return nullptr;
2406
2407 // We never change the calling convention.
2408 if (!ignoreCallingConv(Func) && !isCallingConvC)
2409 return nullptr;
2410
2411 switch (Func) {
2412 case LibFunc::memcpy_chk:
2413 return optimizeMemCpyChk(CI, Builder);
2414 case LibFunc::memmove_chk:
2415 return optimizeMemMoveChk(CI, Builder);
2416 case LibFunc::memset_chk:
2417 return optimizeMemSetChk(CI, Builder);
2418 case LibFunc::stpcpy_chk:
2419 case LibFunc::strcpy_chk:
Ahmed Bougacha1ac93562015-01-27 21:52:16 +00002420 return optimizeStrpCpyChk(CI, Builder, Func);
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002421 case LibFunc::stpncpy_chk:
2422 case LibFunc::strncpy_chk:
Ahmed Bougacha1ac93562015-01-27 21:52:16 +00002423 return optimizeStrpNCpyChk(CI, Builder, Func);
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002424 default:
2425 break;
2426 }
2427 return nullptr;
2428}
2429
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002430FortifiedLibCallSimplifier::FortifiedLibCallSimplifier(
2431 const TargetLibraryInfo *TLI, bool OnlyLowerUnknownSize)
2432 : TLI(TLI), OnlyLowerUnknownSize(OnlyLowerUnknownSize) {}