blob: a30514e4d9e860b5533db45b6dbc67f036a0abaf [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
105/// corresponing to \a Ty is available.
106static 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).
225 Value *CpyDst = B.CreateGEP(Dst, DstLen, "endptr");
226
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)
Chris Bienemanad070d02014-09-17 20:55:46 +0000306 return B.CreateGEP(SrcStr, EmitStrLen(SrcStr, B, DL, TLI), "strchr");
307 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)
319 return B.CreateGEP(SrcStr, B.getInt64(I), "strchr");
320}
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)
354 return B.CreateGEP(SrcStr, B.getInt64(I), "strrchr");
355}
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);
479 return StrLen ? B.CreateInBoundsGEP(Dst, StrLen) : nullptr;
480 }
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 =
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000490 B.CreateGEP(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
Chris Bienemanad070d02014-09-17 20:55:46 +0000600 return B.CreateGEP(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
Chris Bienemanad070d02014-09-17 20:55:46 +0000748Value *LibCallSimplifier::optimizeMemCmp(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)->isPointerTy() ||
753 !FT->getReturnType()->isIntegerTy(32))
Craig Topperf40110f2014-04-25 05:29:35 +0000754 return nullptr;
Meador Inge40b6fac2012-10-15 03:47:37 +0000755
Chris Bienemanad070d02014-09-17 20:55:46 +0000756 Value *LHS = CI->getArgOperand(0), *RHS = CI->getArgOperand(1);
Meador Inge40b6fac2012-10-15 03:47:37 +0000757
Chris Bienemanad070d02014-09-17 20:55:46 +0000758 if (LHS == RHS) // memcmp(s,s,x) -> 0
759 return Constant::getNullValue(CI->getType());
Meador Inge40b6fac2012-10-15 03:47:37 +0000760
Chris Bienemanad070d02014-09-17 20:55:46 +0000761 // Make sure we have a constant length.
762 ConstantInt *LenC = dyn_cast<ConstantInt>(CI->getArgOperand(2));
763 if (!LenC)
Craig Topperf40110f2014-04-25 05:29:35 +0000764 return nullptr;
Chris Bienemanad070d02014-09-17 20:55:46 +0000765 uint64_t Len = LenC->getZExtValue();
766
767 if (Len == 0) // memcmp(s1,s2,0) -> 0
768 return Constant::getNullValue(CI->getType());
769
770 // memcmp(S1,S2,1) -> *(unsigned char*)LHS - *(unsigned char*)RHS
771 if (Len == 1) {
772 Value *LHSV = B.CreateZExt(B.CreateLoad(CastToCStr(LHS, B), "lhsc"),
773 CI->getType(), "lhsv");
774 Value *RHSV = B.CreateZExt(B.CreateLoad(CastToCStr(RHS, B), "rhsc"),
775 CI->getType(), "rhsv");
776 return B.CreateSub(LHSV, RHSV, "chardiff");
Meador Inge40b6fac2012-10-15 03:47:37 +0000777 }
Meador Inge40b6fac2012-10-15 03:47:37 +0000778
Chris Bienemanad070d02014-09-17 20:55:46 +0000779 // Constant folding: memcmp(x, y, l) -> cnst (all arguments are constant)
780 StringRef LHSStr, RHSStr;
781 if (getConstantStringInfo(LHS, LHSStr) &&
782 getConstantStringInfo(RHS, RHSStr)) {
783 // Make sure we're not reading out-of-bounds memory.
784 if (Len > LHSStr.size() || Len > RHSStr.size())
Craig Topperf40110f2014-04-25 05:29:35 +0000785 return nullptr;
Chris Bienemanad070d02014-09-17 20:55:46 +0000786 // Fold the memcmp and normalize the result. This way we get consistent
787 // results across multiple platforms.
788 uint64_t Ret = 0;
789 int Cmp = memcmp(LHSStr.data(), RHSStr.data(), Len);
790 if (Cmp < 0)
791 Ret = -1;
792 else if (Cmp > 0)
793 Ret = 1;
794 return ConstantInt::get(CI->getType(), Ret);
Meador Inge000dbcc2012-10-18 18:12:40 +0000795 }
Meador Inge000dbcc2012-10-18 18:12:40 +0000796
Chris Bienemanad070d02014-09-17 20:55:46 +0000797 return nullptr;
798}
Meador Inge9a6a1902012-10-31 00:20:56 +0000799
Chris Bienemanad070d02014-09-17 20:55:46 +0000800Value *LibCallSimplifier::optimizeMemCpy(CallInst *CI, IRBuilder<> &B) {
801 Function *Callee = CI->getCalledFunction();
Meador Inged589ac62012-10-31 03:33:06 +0000802
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000803 if (!checkStringCopyLibFuncSignature(Callee, LibFunc::memcpy))
Craig Topperf40110f2014-04-25 05:29:35 +0000804 return nullptr;
Meador Inge6f8e0112012-10-31 04:29:58 +0000805
Chris Bienemanad070d02014-09-17 20:55:46 +0000806 // memcpy(x, y, n) -> llvm.memcpy(x, y, n, 1)
807 B.CreateMemCpy(CI->getArgOperand(0), CI->getArgOperand(1),
808 CI->getArgOperand(2), 1);
809 return CI->getArgOperand(0);
810}
Meador Inge05a625a2012-10-31 14:58:26 +0000811
Chris Bienemanad070d02014-09-17 20:55:46 +0000812Value *LibCallSimplifier::optimizeMemMove(CallInst *CI, IRBuilder<> &B) {
813 Function *Callee = CI->getCalledFunction();
Meador Inge05a625a2012-10-31 14:58:26 +0000814
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000815 if (!checkStringCopyLibFuncSignature(Callee, LibFunc::memmove))
Craig Topperf40110f2014-04-25 05:29:35 +0000816 return nullptr;
Meador Inge489b5d62012-11-08 01:33:50 +0000817
Chris Bienemanad070d02014-09-17 20:55:46 +0000818 // memmove(x, y, n) -> llvm.memmove(x, y, n, 1)
819 B.CreateMemMove(CI->getArgOperand(0), CI->getArgOperand(1),
820 CI->getArgOperand(2), 1);
821 return CI->getArgOperand(0);
822}
Meador Ingebcd88ef72012-11-10 15:16:48 +0000823
Chris Bienemanad070d02014-09-17 20:55:46 +0000824Value *LibCallSimplifier::optimizeMemSet(CallInst *CI, IRBuilder<> &B) {
825 Function *Callee = CI->getCalledFunction();
Meador Ingebcd88ef72012-11-10 15:16:48 +0000826
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000827 if (!checkStringCopyLibFuncSignature(Callee, LibFunc::memset))
Craig Topperf40110f2014-04-25 05:29:35 +0000828 return nullptr;
Meador Inge56edbc92012-11-11 03:51:48 +0000829
Chris Bienemanad070d02014-09-17 20:55:46 +0000830 // memset(p, v, n) -> llvm.memset(p, v, n, 1)
831 Value *Val = B.CreateIntCast(CI->getArgOperand(1), B.getInt8Ty(), false);
832 B.CreateMemSet(CI->getArgOperand(0), Val, CI->getArgOperand(2), 1);
833 return CI->getArgOperand(0);
834}
Meador Inged4825782012-11-11 06:49:03 +0000835
Meador Inge193e0352012-11-13 04:16:17 +0000836//===----------------------------------------------------------------------===//
837// Math Library Optimizations
838//===----------------------------------------------------------------------===//
839
Matthias Braund34e4d22014-12-03 21:46:33 +0000840/// Return a variant of Val with float type.
841/// Currently this works in two cases: If Val is an FPExtension of a float
842/// value to something bigger, simply return the operand.
843/// If Val is a ConstantFP but can be converted to a float ConstantFP without
844/// loss of precision do so.
845static Value *valueHasFloatPrecision(Value *Val) {
846 if (FPExtInst *Cast = dyn_cast<FPExtInst>(Val)) {
847 Value *Op = Cast->getOperand(0);
848 if (Op->getType()->isFloatTy())
849 return Op;
850 }
851 if (ConstantFP *Const = dyn_cast<ConstantFP>(Val)) {
852 APFloat F = Const->getValueAPF();
Matthias Braun395a82f2014-12-03 22:10:39 +0000853 bool losesInfo;
Matthias Braund34e4d22014-12-03 21:46:33 +0000854 (void)F.convert(APFloat::IEEEsingle, APFloat::rmNearestTiesToEven,
Matthias Braun395a82f2014-12-03 22:10:39 +0000855 &losesInfo);
856 if (!losesInfo)
Matthias Braund34e4d22014-12-03 21:46:33 +0000857 return ConstantFP::get(Const->getContext(), F);
858 }
859 return nullptr;
860}
861
Meador Inge193e0352012-11-13 04:16:17 +0000862//===----------------------------------------------------------------------===//
863// Double -> Float Shrinking Optimizations for Unary Functions like 'floor'
864
Chris Bienemanad070d02014-09-17 20:55:46 +0000865Value *LibCallSimplifier::optimizeUnaryDoubleFP(CallInst *CI, IRBuilder<> &B,
866 bool CheckRetType) {
867 Function *Callee = CI->getCalledFunction();
868 FunctionType *FT = Callee->getFunctionType();
869 if (FT->getNumParams() != 1 || !FT->getReturnType()->isDoubleTy() ||
870 !FT->getParamType(0)->isDoubleTy())
871 return nullptr;
Meador Inge193e0352012-11-13 04:16:17 +0000872
Chris Bienemanad070d02014-09-17 20:55:46 +0000873 if (CheckRetType) {
874 // Check if all the uses for function like 'sin' are converted to float.
875 for (User *U : CI->users()) {
876 FPTruncInst *Cast = dyn_cast<FPTruncInst>(U);
877 if (!Cast || !Cast->getType()->isFloatTy())
878 return nullptr;
Meador Inge193e0352012-11-13 04:16:17 +0000879 }
Meador Inge193e0352012-11-13 04:16:17 +0000880 }
Chris Bienemanad070d02014-09-17 20:55:46 +0000881
882 // If this is something like 'floor((double)floatval)', convert to floorf.
Matthias Braund34e4d22014-12-03 21:46:33 +0000883 Value *V = valueHasFloatPrecision(CI->getArgOperand(0));
884 if (V == nullptr)
Chris Bienemanad070d02014-09-17 20:55:46 +0000885 return nullptr;
886
887 // floor((double)floatval) -> (double)floorf(floatval)
Sanjay Patel848309d2014-10-23 21:52:45 +0000888 if (Callee->isIntrinsic()) {
889 Module *M = CI->getParent()->getParent()->getParent();
890 Intrinsic::ID IID = (Intrinsic::ID) Callee->getIntrinsicID();
891 Function *F = Intrinsic::getDeclaration(M, IID, B.getFloatTy());
892 V = B.CreateCall(F, V);
893 } else {
894 // The call is a library call rather than an intrinsic.
895 V = EmitUnaryFloatFnCall(V, Callee->getName(), B, Callee->getAttributes());
896 }
897
Chris Bienemanad070d02014-09-17 20:55:46 +0000898 return B.CreateFPExt(V, B.getDoubleTy());
899}
Meador Inge193e0352012-11-13 04:16:17 +0000900
Yi Jiang6ab044e2013-12-16 22:42:40 +0000901// Double -> Float Shrinking Optimizations for Binary Functions like 'fmin/fmax'
Chris Bienemanad070d02014-09-17 20:55:46 +0000902Value *LibCallSimplifier::optimizeBinaryDoubleFP(CallInst *CI, IRBuilder<> &B) {
903 Function *Callee = CI->getCalledFunction();
904 FunctionType *FT = Callee->getFunctionType();
905 // Just make sure this has 2 arguments of the same FP type, which match the
906 // result type.
907 if (FT->getNumParams() != 2 || FT->getReturnType() != FT->getParamType(0) ||
908 FT->getParamType(0) != FT->getParamType(1) ||
909 !FT->getParamType(0)->isFloatingPointTy())
Craig Topperf40110f2014-04-25 05:29:35 +0000910 return nullptr;
Meador Inge193e0352012-11-13 04:16:17 +0000911
Chris Bienemanad070d02014-09-17 20:55:46 +0000912 // If this is something like 'fmin((double)floatval1, (double)floatval2)',
Matthias Braund34e4d22014-12-03 21:46:33 +0000913 // or fmin(1.0, (double)floatval), then we convert it to fminf.
914 Value *V1 = valueHasFloatPrecision(CI->getArgOperand(0));
915 if (V1 == nullptr)
916 return nullptr;
917 Value *V2 = valueHasFloatPrecision(CI->getArgOperand(1));
918 if (V2 == nullptr)
Craig Topperf40110f2014-04-25 05:29:35 +0000919 return nullptr;
Chris Bienemanad070d02014-09-17 20:55:46 +0000920
921 // fmin((double)floatval1, (double)floatval2)
Matthias Braund34e4d22014-12-03 21:46:33 +0000922 // -> (double)fminf(floatval1, floatval2)
Sanjay Patel848309d2014-10-23 21:52:45 +0000923 // TODO: Handle intrinsics in the same way as in optimizeUnaryDoubleFP().
Matthias Braund34e4d22014-12-03 21:46:33 +0000924 Value *V = EmitBinaryFloatFnCall(V1, V2, Callee->getName(), B,
925 Callee->getAttributes());
Chris Bienemanad070d02014-09-17 20:55:46 +0000926 return B.CreateFPExt(V, B.getDoubleTy());
927}
928
929Value *LibCallSimplifier::optimizeCos(CallInst *CI, IRBuilder<> &B) {
930 Function *Callee = CI->getCalledFunction();
931 Value *Ret = nullptr;
932 if (UnsafeFPShrink && Callee->getName() == "cos" && TLI->has(LibFunc::cosf)) {
933 Ret = optimizeUnaryDoubleFP(CI, B, true);
Bob Wilsond8d92d92013-11-03 06:48:38 +0000934 }
935
Chris Bienemanad070d02014-09-17 20:55:46 +0000936 FunctionType *FT = Callee->getFunctionType();
937 // Just make sure this has 1 argument of FP type, which matches the
938 // result type.
939 if (FT->getNumParams() != 1 || FT->getReturnType() != FT->getParamType(0) ||
940 !FT->getParamType(0)->isFloatingPointTy())
941 return Ret;
Bob Wilsond8d92d92013-11-03 06:48:38 +0000942
Chris Bienemanad070d02014-09-17 20:55:46 +0000943 // cos(-x) -> cos(x)
944 Value *Op1 = CI->getArgOperand(0);
945 if (BinaryOperator::isFNeg(Op1)) {
946 BinaryOperator *BinExpr = cast<BinaryOperator>(Op1);
947 return B.CreateCall(Callee, BinExpr->getOperand(1), "cos");
948 }
949 return Ret;
950}
Bob Wilsond8d92d92013-11-03 06:48:38 +0000951
Chris Bienemanad070d02014-09-17 20:55:46 +0000952Value *LibCallSimplifier::optimizePow(CallInst *CI, IRBuilder<> &B) {
953 Function *Callee = CI->getCalledFunction();
954
955 Value *Ret = nullptr;
956 if (UnsafeFPShrink && Callee->getName() == "pow" && TLI->has(LibFunc::powf)) {
957 Ret = optimizeUnaryDoubleFP(CI, B, true);
Bob Wilsond8d92d92013-11-03 06:48:38 +0000958 }
959
Chris Bienemanad070d02014-09-17 20:55:46 +0000960 FunctionType *FT = Callee->getFunctionType();
961 // Just make sure this has 2 arguments of the same FP type, which match the
962 // result type.
963 if (FT->getNumParams() != 2 || FT->getReturnType() != FT->getParamType(0) ||
964 FT->getParamType(0) != FT->getParamType(1) ||
965 !FT->getParamType(0)->isFloatingPointTy())
966 return Ret;
Bob Wilsond8d92d92013-11-03 06:48:38 +0000967
Chris Bienemanad070d02014-09-17 20:55:46 +0000968 Value *Op1 = CI->getArgOperand(0), *Op2 = CI->getArgOperand(1);
969 if (ConstantFP *Op1C = dyn_cast<ConstantFP>(Op1)) {
970 // pow(1.0, x) -> 1.0
971 if (Op1C->isExactlyValue(1.0))
972 return Op1C;
973 // pow(2.0, x) -> exp2(x)
974 if (Op1C->isExactlyValue(2.0) &&
975 hasUnaryFloatFn(TLI, Op1->getType(), LibFunc::exp2, LibFunc::exp2f,
976 LibFunc::exp2l))
977 return EmitUnaryFloatFnCall(Op2, "exp2", B, Callee->getAttributes());
978 // pow(10.0, x) -> exp10(x)
979 if (Op1C->isExactlyValue(10.0) &&
980 hasUnaryFloatFn(TLI, Op1->getType(), LibFunc::exp10, LibFunc::exp10f,
981 LibFunc::exp10l))
982 return EmitUnaryFloatFnCall(Op2, TLI->getName(LibFunc::exp10), B,
983 Callee->getAttributes());
Bob Wilsond8d92d92013-11-03 06:48:38 +0000984 }
985
Chris Bienemanad070d02014-09-17 20:55:46 +0000986 ConstantFP *Op2C = dyn_cast<ConstantFP>(Op2);
987 if (!Op2C)
988 return Ret;
989
990 if (Op2C->getValueAPF().isZero()) // pow(x, 0.0) -> 1.0
991 return ConstantFP::get(CI->getType(), 1.0);
992
993 if (Op2C->isExactlyValue(0.5) &&
994 hasUnaryFloatFn(TLI, Op2->getType(), LibFunc::sqrt, LibFunc::sqrtf,
995 LibFunc::sqrtl) &&
996 hasUnaryFloatFn(TLI, Op2->getType(), LibFunc::fabs, LibFunc::fabsf,
997 LibFunc::fabsl)) {
998 // Expand pow(x, 0.5) to (x == -infinity ? +infinity : fabs(sqrt(x))).
999 // This is faster than calling pow, and still handles negative zero
1000 // and negative infinity correctly.
1001 // TODO: In fast-math mode, this could be just sqrt(x).
1002 // TODO: In finite-only mode, this could be just fabs(sqrt(x)).
1003 Value *Inf = ConstantFP::getInfinity(CI->getType());
1004 Value *NegInf = ConstantFP::getInfinity(CI->getType(), true);
1005 Value *Sqrt = EmitUnaryFloatFnCall(Op1, "sqrt", B, Callee->getAttributes());
1006 Value *FAbs =
1007 EmitUnaryFloatFnCall(Sqrt, "fabs", B, Callee->getAttributes());
1008 Value *FCmp = B.CreateFCmpOEQ(Op1, NegInf);
1009 Value *Sel = B.CreateSelect(FCmp, Inf, FAbs);
1010 return Sel;
Bob Wilsond8d92d92013-11-03 06:48:38 +00001011 }
1012
Chris Bienemanad070d02014-09-17 20:55:46 +00001013 if (Op2C->isExactlyValue(1.0)) // pow(x, 1.0) -> x
1014 return Op1;
1015 if (Op2C->isExactlyValue(2.0)) // pow(x, 2.0) -> x*x
1016 return B.CreateFMul(Op1, Op1, "pow2");
1017 if (Op2C->isExactlyValue(-1.0)) // pow(x, -1.0) -> 1.0/x
1018 return B.CreateFDiv(ConstantFP::get(CI->getType(), 1.0), Op1, "powrecip");
1019 return nullptr;
1020}
Bob Wilsond8d92d92013-11-03 06:48:38 +00001021
Chris Bienemanad070d02014-09-17 20:55:46 +00001022Value *LibCallSimplifier::optimizeExp2(CallInst *CI, IRBuilder<> &B) {
1023 Function *Callee = CI->getCalledFunction();
1024 Function *Caller = CI->getParent()->getParent();
Bob Wilsond8d92d92013-11-03 06:48:38 +00001025
Chris Bienemanad070d02014-09-17 20:55:46 +00001026 Value *Ret = nullptr;
1027 if (UnsafeFPShrink && Callee->getName() == "exp2" &&
1028 TLI->has(LibFunc::exp2f)) {
1029 Ret = optimizeUnaryDoubleFP(CI, B, true);
Bob Wilsond8d92d92013-11-03 06:48:38 +00001030 }
1031
Chris Bienemanad070d02014-09-17 20:55:46 +00001032 FunctionType *FT = Callee->getFunctionType();
1033 // Just make sure this has 1 argument of FP type, which matches the
1034 // result type.
1035 if (FT->getNumParams() != 1 || FT->getReturnType() != FT->getParamType(0) ||
1036 !FT->getParamType(0)->isFloatingPointTy())
1037 return Ret;
1038
1039 Value *Op = CI->getArgOperand(0);
1040 // Turn exp2(sitofp(x)) -> ldexp(1.0, sext(x)) if sizeof(x) <= 32
1041 // Turn exp2(uitofp(x)) -> ldexp(1.0, zext(x)) if sizeof(x) < 32
1042 LibFunc::Func LdExp = LibFunc::ldexpl;
1043 if (Op->getType()->isFloatTy())
1044 LdExp = LibFunc::ldexpf;
1045 else if (Op->getType()->isDoubleTy())
1046 LdExp = LibFunc::ldexp;
1047
1048 if (TLI->has(LdExp)) {
1049 Value *LdExpArg = nullptr;
1050 if (SIToFPInst *OpC = dyn_cast<SIToFPInst>(Op)) {
1051 if (OpC->getOperand(0)->getType()->getPrimitiveSizeInBits() <= 32)
1052 LdExpArg = B.CreateSExt(OpC->getOperand(0), B.getInt32Ty());
1053 } else if (UIToFPInst *OpC = dyn_cast<UIToFPInst>(Op)) {
1054 if (OpC->getOperand(0)->getType()->getPrimitiveSizeInBits() < 32)
1055 LdExpArg = B.CreateZExt(OpC->getOperand(0), B.getInt32Ty());
1056 }
1057
1058 if (LdExpArg) {
1059 Constant *One = ConstantFP::get(CI->getContext(), APFloat(1.0f));
1060 if (!Op->getType()->isFloatTy())
1061 One = ConstantExpr::getFPExtend(One, Op->getType());
1062
1063 Module *M = Caller->getParent();
1064 Value *Callee =
1065 M->getOrInsertFunction(TLI->getName(LdExp), Op->getType(),
Reid Kleckner971c3ea2014-11-13 22:55:19 +00001066 Op->getType(), B.getInt32Ty(), nullptr);
Chris Bienemanad070d02014-09-17 20:55:46 +00001067 CallInst *CI = B.CreateCall2(Callee, One, LdExpArg);
1068 if (const Function *F = dyn_cast<Function>(Callee->stripPointerCasts()))
1069 CI->setCallingConv(F->getCallingConv());
1070
1071 return CI;
1072 }
1073 }
1074 return Ret;
1075}
1076
Sanjay Patel0ca42bb2014-10-14 20:43:11 +00001077Value *LibCallSimplifier::optimizeFabs(CallInst *CI, IRBuilder<> &B) {
1078 Function *Callee = CI->getCalledFunction();
1079
1080 Value *Ret = nullptr;
1081 if (Callee->getName() == "fabs" && TLI->has(LibFunc::fabsf)) {
1082 Ret = optimizeUnaryDoubleFP(CI, B, false);
1083 }
1084
1085 FunctionType *FT = Callee->getFunctionType();
1086 // Make sure this has 1 argument of FP type which matches the result type.
1087 if (FT->getNumParams() != 1 || FT->getReturnType() != FT->getParamType(0) ||
1088 !FT->getParamType(0)->isFloatingPointTy())
1089 return Ret;
1090
1091 Value *Op = CI->getArgOperand(0);
1092 if (Instruction *I = dyn_cast<Instruction>(Op)) {
1093 // Fold fabs(x * x) -> x * x; any squared FP value must already be positive.
1094 if (I->getOpcode() == Instruction::FMul)
1095 if (I->getOperand(0) == I->getOperand(1))
1096 return Op;
1097 }
1098 return Ret;
1099}
1100
Sanjay Patelc699a612014-10-16 18:48:17 +00001101Value *LibCallSimplifier::optimizeSqrt(CallInst *CI, IRBuilder<> &B) {
1102 Function *Callee = CI->getCalledFunction();
1103
1104 Value *Ret = nullptr;
Sanjay Patel848309d2014-10-23 21:52:45 +00001105 if (TLI->has(LibFunc::sqrtf) && (Callee->getName() == "sqrt" ||
1106 Callee->getIntrinsicID() == Intrinsic::sqrt))
Sanjay Patelc699a612014-10-16 18:48:17 +00001107 Ret = optimizeUnaryDoubleFP(CI, B, true);
Sanjay Patelc699a612014-10-16 18:48:17 +00001108
1109 // FIXME: For finer-grain optimization, we need intrinsics to have the same
1110 // fast-math flag decorations that are applied to FP instructions. For now,
1111 // we have to rely on the function-level unsafe-fp-math attribute to do this
1112 // optimization because there's no other way to express that the sqrt can be
1113 // reassociated.
1114 Function *F = CI->getParent()->getParent();
1115 if (F->hasFnAttribute("unsafe-fp-math")) {
1116 // Check for unsafe-fp-math = true.
1117 Attribute Attr = F->getFnAttribute("unsafe-fp-math");
1118 if (Attr.getValueAsString() != "true")
1119 return Ret;
1120 }
1121 Value *Op = CI->getArgOperand(0);
1122 if (Instruction *I = dyn_cast<Instruction>(Op)) {
1123 if (I->getOpcode() == Instruction::FMul && I->hasUnsafeAlgebra()) {
1124 // We're looking for a repeated factor in a multiplication tree,
1125 // so we can do this fold: sqrt(x * x) -> fabs(x);
1126 // or this fold: sqrt(x * x * y) -> fabs(x) * sqrt(y).
1127 Value *Op0 = I->getOperand(0);
1128 Value *Op1 = I->getOperand(1);
1129 Value *RepeatOp = nullptr;
1130 Value *OtherOp = nullptr;
1131 if (Op0 == Op1) {
1132 // Simple match: the operands of the multiply are identical.
1133 RepeatOp = Op0;
1134 } else {
1135 // Look for a more complicated pattern: one of the operands is itself
1136 // a multiply, so search for a common factor in that multiply.
1137 // Note: We don't bother looking any deeper than this first level or for
1138 // variations of this pattern because instcombine's visitFMUL and/or the
1139 // reassociation pass should give us this form.
1140 Value *OtherMul0, *OtherMul1;
1141 if (match(Op0, m_FMul(m_Value(OtherMul0), m_Value(OtherMul1)))) {
1142 // Pattern: sqrt((x * y) * z)
1143 if (OtherMul0 == OtherMul1) {
1144 // Matched: sqrt((x * x) * z)
1145 RepeatOp = OtherMul0;
1146 OtherOp = Op1;
1147 }
1148 }
1149 }
1150 if (RepeatOp) {
1151 // Fast math flags for any created instructions should match the sqrt
1152 // and multiply.
1153 // FIXME: We're not checking the sqrt because it doesn't have
1154 // fast-math-flags (see earlier comment).
1155 IRBuilder<true, ConstantFolder,
1156 IRBuilderDefaultInserter<true> >::FastMathFlagGuard Guard(B);
1157 B.SetFastMathFlags(I->getFastMathFlags());
1158 // If we found a repeated factor, hoist it out of the square root and
1159 // replace it with the fabs of that factor.
1160 Module *M = Callee->getParent();
1161 Type *ArgType = Op->getType();
1162 Value *Fabs = Intrinsic::getDeclaration(M, Intrinsic::fabs, ArgType);
1163 Value *FabsCall = B.CreateCall(Fabs, RepeatOp, "fabs");
1164 if (OtherOp) {
1165 // If we found a non-repeated factor, we still need to get its square
1166 // root. We then multiply that by the value that was simplified out
1167 // of the square root calculation.
1168 Value *Sqrt = Intrinsic::getDeclaration(M, Intrinsic::sqrt, ArgType);
1169 Value *SqrtCall = B.CreateCall(Sqrt, OtherOp, "sqrt");
1170 return B.CreateFMul(FabsCall, SqrtCall);
1171 }
1172 return FabsCall;
1173 }
1174 }
1175 }
1176 return Ret;
1177}
1178
Chris Bienemanad070d02014-09-17 20:55:46 +00001179static bool isTrigLibCall(CallInst *CI);
1180static void insertSinCosCall(IRBuilder<> &B, Function *OrigCallee, Value *Arg,
1181 bool UseFloat, Value *&Sin, Value *&Cos,
1182 Value *&SinCos);
1183
1184Value *LibCallSimplifier::optimizeSinCosPi(CallInst *CI, IRBuilder<> &B) {
1185
1186 // Make sure the prototype is as expected, otherwise the rest of the
1187 // function is probably invalid and likely to abort.
1188 if (!isTrigLibCall(CI))
1189 return nullptr;
1190
1191 Value *Arg = CI->getArgOperand(0);
1192 SmallVector<CallInst *, 1> SinCalls;
1193 SmallVector<CallInst *, 1> CosCalls;
1194 SmallVector<CallInst *, 1> SinCosCalls;
1195
1196 bool IsFloat = Arg->getType()->isFloatTy();
1197
1198 // Look for all compatible sinpi, cospi and sincospi calls with the same
1199 // argument. If there are enough (in some sense) we can make the
1200 // substitution.
1201 for (User *U : Arg->users())
1202 classifyArgUse(U, CI->getParent(), IsFloat, SinCalls, CosCalls,
1203 SinCosCalls);
1204
1205 // It's only worthwhile if both sinpi and cospi are actually used.
1206 if (SinCosCalls.empty() && (SinCalls.empty() || CosCalls.empty()))
1207 return nullptr;
1208
1209 Value *Sin, *Cos, *SinCos;
1210 insertSinCosCall(B, CI->getCalledFunction(), Arg, IsFloat, Sin, Cos, SinCos);
1211
1212 replaceTrigInsts(SinCalls, Sin);
1213 replaceTrigInsts(CosCalls, Cos);
1214 replaceTrigInsts(SinCosCalls, SinCos);
1215
1216 return nullptr;
1217}
1218
1219static bool isTrigLibCall(CallInst *CI) {
1220 Function *Callee = CI->getCalledFunction();
1221 FunctionType *FT = Callee->getFunctionType();
1222
1223 // We can only hope to do anything useful if we can ignore things like errno
1224 // and floating-point exceptions.
1225 bool AttributesSafe =
1226 CI->hasFnAttr(Attribute::NoUnwind) && CI->hasFnAttr(Attribute::ReadNone);
1227
1228 // Other than that we need float(float) or double(double)
1229 return AttributesSafe && FT->getNumParams() == 1 &&
1230 FT->getReturnType() == FT->getParamType(0) &&
1231 (FT->getParamType(0)->isFloatTy() ||
1232 FT->getParamType(0)->isDoubleTy());
1233}
1234
1235void
1236LibCallSimplifier::classifyArgUse(Value *Val, BasicBlock *BB, bool IsFloat,
1237 SmallVectorImpl<CallInst *> &SinCalls,
1238 SmallVectorImpl<CallInst *> &CosCalls,
1239 SmallVectorImpl<CallInst *> &SinCosCalls) {
1240 CallInst *CI = dyn_cast<CallInst>(Val);
1241
1242 if (!CI)
1243 return;
1244
1245 Function *Callee = CI->getCalledFunction();
1246 StringRef FuncName = Callee->getName();
1247 LibFunc::Func Func;
1248 if (!TLI->getLibFunc(FuncName, Func) || !TLI->has(Func) || !isTrigLibCall(CI))
1249 return;
1250
1251 if (IsFloat) {
1252 if (Func == LibFunc::sinpif)
1253 SinCalls.push_back(CI);
1254 else if (Func == LibFunc::cospif)
1255 CosCalls.push_back(CI);
1256 else if (Func == LibFunc::sincospif_stret)
1257 SinCosCalls.push_back(CI);
1258 } else {
1259 if (Func == LibFunc::sinpi)
1260 SinCalls.push_back(CI);
1261 else if (Func == LibFunc::cospi)
1262 CosCalls.push_back(CI);
1263 else if (Func == LibFunc::sincospi_stret)
1264 SinCosCalls.push_back(CI);
1265 }
1266}
1267
1268void LibCallSimplifier::replaceTrigInsts(SmallVectorImpl<CallInst *> &Calls,
1269 Value *Res) {
1270 for (SmallVectorImpl<CallInst *>::iterator I = Calls.begin(), E = Calls.end();
1271 I != E; ++I) {
1272 replaceAllUsesWith(*I, Res);
1273 }
1274}
1275
1276void insertSinCosCall(IRBuilder<> &B, Function *OrigCallee, Value *Arg,
1277 bool UseFloat, Value *&Sin, Value *&Cos, Value *&SinCos) {
1278 Type *ArgTy = Arg->getType();
1279 Type *ResTy;
1280 StringRef Name;
1281
1282 Triple T(OrigCallee->getParent()->getTargetTriple());
1283 if (UseFloat) {
1284 Name = "__sincospif_stret";
1285
1286 assert(T.getArch() != Triple::x86 && "x86 messy and unsupported for now");
1287 // x86_64 can't use {float, float} since that would be returned in both
1288 // xmm0 and xmm1, which isn't what a real struct would do.
1289 ResTy = T.getArch() == Triple::x86_64
1290 ? static_cast<Type *>(VectorType::get(ArgTy, 2))
Reid Kleckner971c3ea2014-11-13 22:55:19 +00001291 : static_cast<Type *>(StructType::get(ArgTy, ArgTy, nullptr));
Chris Bienemanad070d02014-09-17 20:55:46 +00001292 } else {
1293 Name = "__sincospi_stret";
Reid Kleckner971c3ea2014-11-13 22:55:19 +00001294 ResTy = StructType::get(ArgTy, ArgTy, nullptr);
Chris Bienemanad070d02014-09-17 20:55:46 +00001295 }
1296
1297 Module *M = OrigCallee->getParent();
1298 Value *Callee = M->getOrInsertFunction(Name, OrigCallee->getAttributes(),
Reid Kleckner971c3ea2014-11-13 22:55:19 +00001299 ResTy, ArgTy, nullptr);
Chris Bienemanad070d02014-09-17 20:55:46 +00001300
1301 if (Instruction *ArgInst = dyn_cast<Instruction>(Arg)) {
1302 // If the argument is an instruction, it must dominate all uses so put our
1303 // sincos call there.
1304 BasicBlock::iterator Loc = ArgInst;
1305 B.SetInsertPoint(ArgInst->getParent(), ++Loc);
1306 } else {
1307 // Otherwise (e.g. for a constant) the beginning of the function is as
1308 // good a place as any.
1309 BasicBlock &EntryBB = B.GetInsertBlock()->getParent()->getEntryBlock();
1310 B.SetInsertPoint(&EntryBB, EntryBB.begin());
1311 }
1312
1313 SinCos = B.CreateCall(Callee, Arg, "sincospi");
1314
1315 if (SinCos->getType()->isStructTy()) {
1316 Sin = B.CreateExtractValue(SinCos, 0, "sinpi");
1317 Cos = B.CreateExtractValue(SinCos, 1, "cospi");
1318 } else {
1319 Sin = B.CreateExtractElement(SinCos, ConstantInt::get(B.getInt32Ty(), 0),
1320 "sinpi");
1321 Cos = B.CreateExtractElement(SinCos, ConstantInt::get(B.getInt32Ty(), 1),
1322 "cospi");
1323 }
1324}
Bob Wilsond8d92d92013-11-03 06:48:38 +00001325
Meador Inge7415f842012-11-25 20:45:27 +00001326//===----------------------------------------------------------------------===//
1327// Integer Library Call Optimizations
1328//===----------------------------------------------------------------------===//
1329
Chris Bienemanad070d02014-09-17 20:55:46 +00001330Value *LibCallSimplifier::optimizeFFS(CallInst *CI, IRBuilder<> &B) {
1331 Function *Callee = CI->getCalledFunction();
1332 FunctionType *FT = Callee->getFunctionType();
1333 // Just make sure this has 2 arguments of the same FP type, which match the
1334 // result type.
1335 if (FT->getNumParams() != 1 || !FT->getReturnType()->isIntegerTy(32) ||
1336 !FT->getParamType(0)->isIntegerTy())
1337 return nullptr;
Meador Inge7415f842012-11-25 20:45:27 +00001338
Chris Bienemanad070d02014-09-17 20:55:46 +00001339 Value *Op = CI->getArgOperand(0);
Meador Inge7415f842012-11-25 20:45:27 +00001340
Chris Bienemanad070d02014-09-17 20:55:46 +00001341 // Constant fold.
1342 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op)) {
1343 if (CI->isZero()) // ffs(0) -> 0.
1344 return B.getInt32(0);
1345 // ffs(c) -> cttz(c)+1
1346 return B.getInt32(CI->getValue().countTrailingZeros() + 1);
Meador Inge7415f842012-11-25 20:45:27 +00001347 }
Meador Inge7415f842012-11-25 20:45:27 +00001348
Chris Bienemanad070d02014-09-17 20:55:46 +00001349 // ffs(x) -> x != 0 ? (i32)llvm.cttz(x)+1 : 0
1350 Type *ArgType = Op->getType();
1351 Value *F =
1352 Intrinsic::getDeclaration(Callee->getParent(), Intrinsic::cttz, ArgType);
1353 Value *V = B.CreateCall2(F, Op, B.getFalse(), "cttz");
1354 V = B.CreateAdd(V, ConstantInt::get(V->getType(), 1));
1355 V = B.CreateIntCast(V, B.getInt32Ty(), false);
Meador Ingea0b6d872012-11-26 00:24:07 +00001356
Chris Bienemanad070d02014-09-17 20:55:46 +00001357 Value *Cond = B.CreateICmpNE(Op, Constant::getNullValue(ArgType));
1358 return B.CreateSelect(Cond, V, B.getInt32(0));
1359}
Meador Ingea0b6d872012-11-26 00:24:07 +00001360
Chris Bienemanad070d02014-09-17 20:55:46 +00001361Value *LibCallSimplifier::optimizeAbs(CallInst *CI, IRBuilder<> &B) {
1362 Function *Callee = CI->getCalledFunction();
1363 FunctionType *FT = Callee->getFunctionType();
1364 // We require integer(integer) where the types agree.
1365 if (FT->getNumParams() != 1 || !FT->getReturnType()->isIntegerTy() ||
1366 FT->getParamType(0) != FT->getReturnType())
1367 return nullptr;
Meador Inge9a59ab62012-11-26 02:31:59 +00001368
Chris Bienemanad070d02014-09-17 20:55:46 +00001369 // abs(x) -> x >s -1 ? x : -x
1370 Value *Op = CI->getArgOperand(0);
1371 Value *Pos =
1372 B.CreateICmpSGT(Op, Constant::getAllOnesValue(Op->getType()), "ispos");
1373 Value *Neg = B.CreateNeg(Op, "neg");
1374 return B.CreateSelect(Pos, Op, Neg);
1375}
Meador Inge9a59ab62012-11-26 02:31:59 +00001376
Chris Bienemanad070d02014-09-17 20:55:46 +00001377Value *LibCallSimplifier::optimizeIsDigit(CallInst *CI, IRBuilder<> &B) {
1378 Function *Callee = CI->getCalledFunction();
1379 FunctionType *FT = Callee->getFunctionType();
1380 // We require integer(i32)
1381 if (FT->getNumParams() != 1 || !FT->getReturnType()->isIntegerTy() ||
1382 !FT->getParamType(0)->isIntegerTy(32))
1383 return nullptr;
Meador Ingea62a39e2012-11-26 03:10:07 +00001384
Chris Bienemanad070d02014-09-17 20:55:46 +00001385 // isdigit(c) -> (c-'0') <u 10
1386 Value *Op = CI->getArgOperand(0);
1387 Op = B.CreateSub(Op, B.getInt32('0'), "isdigittmp");
1388 Op = B.CreateICmpULT(Op, B.getInt32(10), "isdigit");
1389 return B.CreateZExt(Op, CI->getType());
1390}
Meador Ingea62a39e2012-11-26 03:10:07 +00001391
Chris Bienemanad070d02014-09-17 20:55:46 +00001392Value *LibCallSimplifier::optimizeIsAscii(CallInst *CI, IRBuilder<> &B) {
1393 Function *Callee = CI->getCalledFunction();
1394 FunctionType *FT = Callee->getFunctionType();
1395 // We require integer(i32)
1396 if (FT->getNumParams() != 1 || !FT->getReturnType()->isIntegerTy() ||
1397 !FT->getParamType(0)->isIntegerTy(32))
1398 return nullptr;
Meador Inge604937d2012-11-26 03:38:52 +00001399
Chris Bienemanad070d02014-09-17 20:55:46 +00001400 // isascii(c) -> c <u 128
1401 Value *Op = CI->getArgOperand(0);
1402 Op = B.CreateICmpULT(Op, B.getInt32(128), "isascii");
1403 return B.CreateZExt(Op, CI->getType());
1404}
1405
1406Value *LibCallSimplifier::optimizeToAscii(CallInst *CI, IRBuilder<> &B) {
1407 Function *Callee = CI->getCalledFunction();
1408 FunctionType *FT = Callee->getFunctionType();
1409 // We require i32(i32)
1410 if (FT->getNumParams() != 1 || FT->getReturnType() != FT->getParamType(0) ||
1411 !FT->getParamType(0)->isIntegerTy(32))
1412 return nullptr;
1413
1414 // toascii(c) -> c & 0x7f
1415 return B.CreateAnd(CI->getArgOperand(0),
1416 ConstantInt::get(CI->getType(), 0x7F));
1417}
Meador Inge604937d2012-11-26 03:38:52 +00001418
Meador Inge08ca1152012-11-26 20:37:20 +00001419//===----------------------------------------------------------------------===//
1420// Formatting and IO Library Call Optimizations
1421//===----------------------------------------------------------------------===//
1422
Chris Bienemanad070d02014-09-17 20:55:46 +00001423static bool isReportingError(Function *Callee, CallInst *CI, int StreamArg);
Hal Finkel66cd3f12013-11-17 02:06:35 +00001424
Chris Bienemanad070d02014-09-17 20:55:46 +00001425Value *LibCallSimplifier::optimizeErrorReporting(CallInst *CI, IRBuilder<> &B,
1426 int StreamArg) {
1427 // Error reporting calls should be cold, mark them as such.
1428 // This applies even to non-builtin calls: it is only a hint and applies to
1429 // functions that the frontend might not understand as builtins.
Hal Finkel66cd3f12013-11-17 02:06:35 +00001430
Chris Bienemanad070d02014-09-17 20:55:46 +00001431 // This heuristic was suggested in:
1432 // Improving Static Branch Prediction in a Compiler
1433 // Brian L. Deitrich, Ben-Chung Cheng, Wen-mei W. Hwu
1434 // Proceedings of PACT'98, Oct. 1998, IEEE
1435 Function *Callee = CI->getCalledFunction();
Hal Finkel66cd3f12013-11-17 02:06:35 +00001436
Chris Bienemanad070d02014-09-17 20:55:46 +00001437 if (!CI->hasFnAttr(Attribute::Cold) &&
1438 isReportingError(Callee, CI, StreamArg)) {
1439 CI->addAttribute(AttributeSet::FunctionIndex, Attribute::Cold);
1440 }
Hal Finkel66cd3f12013-11-17 02:06:35 +00001441
Chris Bienemanad070d02014-09-17 20:55:46 +00001442 return nullptr;
1443}
1444
1445static bool isReportingError(Function *Callee, CallInst *CI, int StreamArg) {
1446 if (!ColdErrorCalls)
1447 return false;
1448
1449 if (!Callee || !Callee->isDeclaration())
1450 return false;
1451
1452 if (StreamArg < 0)
1453 return true;
1454
1455 // These functions might be considered cold, but only if their stream
1456 // argument is stderr.
1457
1458 if (StreamArg >= (int)CI->getNumArgOperands())
1459 return false;
1460 LoadInst *LI = dyn_cast<LoadInst>(CI->getArgOperand(StreamArg));
1461 if (!LI)
1462 return false;
1463 GlobalVariable *GV = dyn_cast<GlobalVariable>(LI->getPointerOperand());
1464 if (!GV || !GV->isDeclaration())
1465 return false;
1466 return GV->getName() == "stderr";
1467}
1468
1469Value *LibCallSimplifier::optimizePrintFString(CallInst *CI, IRBuilder<> &B) {
1470 // Check for a fixed format string.
1471 StringRef FormatStr;
1472 if (!getConstantStringInfo(CI->getArgOperand(0), FormatStr))
Craig Topperf40110f2014-04-25 05:29:35 +00001473 return nullptr;
Hal Finkel66cd3f12013-11-17 02:06:35 +00001474
Chris Bienemanad070d02014-09-17 20:55:46 +00001475 // Empty format string -> noop.
1476 if (FormatStr.empty()) // Tolerate printf's declared void.
1477 return CI->use_empty() ? (Value *)CI : ConstantInt::get(CI->getType(), 0);
Hal Finkel66cd3f12013-11-17 02:06:35 +00001478
Chris Bienemanad070d02014-09-17 20:55:46 +00001479 // Do not do any of the following transformations if the printf return value
1480 // is used, in general the printf return value is not compatible with either
1481 // putchar() or puts().
1482 if (!CI->use_empty())
Craig Topperf40110f2014-04-25 05:29:35 +00001483 return nullptr;
Chris Bienemanad070d02014-09-17 20:55:46 +00001484
1485 // printf("x") -> putchar('x'), even for '%'.
1486 if (FormatStr.size() == 1) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001487 Value *Res = EmitPutChar(B.getInt32(FormatStr[0]), B, TLI);
Chris Bienemanad070d02014-09-17 20:55:46 +00001488 if (CI->use_empty() || !Res)
1489 return Res;
1490 return B.CreateIntCast(Res, CI->getType(), true);
Meador Inge08ca1152012-11-26 20:37:20 +00001491 }
1492
Chris Bienemanad070d02014-09-17 20:55:46 +00001493 // printf("foo\n") --> puts("foo")
1494 if (FormatStr[FormatStr.size() - 1] == '\n' &&
1495 FormatStr.find('%') == StringRef::npos) { // No format characters.
1496 // Create a string literal with no \n on it. We expect the constant merge
1497 // pass to be run after this pass, to merge duplicate strings.
1498 FormatStr = FormatStr.drop_back();
1499 Value *GV = B.CreateGlobalString(FormatStr, "str");
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001500 Value *NewCI = EmitPutS(GV, B, TLI);
Chris Bienemanad070d02014-09-17 20:55:46 +00001501 return (CI->use_empty() || !NewCI)
1502 ? NewCI
1503 : ConstantInt::get(CI->getType(), FormatStr.size() + 1);
1504 }
Meador Inge08ca1152012-11-26 20:37:20 +00001505
Chris Bienemanad070d02014-09-17 20:55:46 +00001506 // Optimize specific format strings.
1507 // printf("%c", chr) --> putchar(chr)
1508 if (FormatStr == "%c" && CI->getNumArgOperands() > 1 &&
1509 CI->getArgOperand(1)->getType()->isIntegerTy()) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001510 Value *Res = EmitPutChar(CI->getArgOperand(1), B, TLI);
Meador Inge08ca1152012-11-26 20:37:20 +00001511
Chris Bienemanad070d02014-09-17 20:55:46 +00001512 if (CI->use_empty() || !Res)
1513 return Res;
1514 return B.CreateIntCast(Res, CI->getType(), true);
1515 }
1516
1517 // printf("%s\n", str) --> puts(str)
1518 if (FormatStr == "%s\n" && CI->getNumArgOperands() > 1 &&
1519 CI->getArgOperand(1)->getType()->isPointerTy()) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001520 return EmitPutS(CI->getArgOperand(1), B, TLI);
Chris Bienemanad070d02014-09-17 20:55:46 +00001521 }
1522 return nullptr;
1523}
1524
1525Value *LibCallSimplifier::optimizePrintF(CallInst *CI, IRBuilder<> &B) {
1526
1527 Function *Callee = CI->getCalledFunction();
1528 // Require one fixed pointer argument and an integer/void result.
1529 FunctionType *FT = Callee->getFunctionType();
1530 if (FT->getNumParams() < 1 || !FT->getParamType(0)->isPointerTy() ||
1531 !(FT->getReturnType()->isIntegerTy() || FT->getReturnType()->isVoidTy()))
1532 return nullptr;
1533
1534 if (Value *V = optimizePrintFString(CI, B)) {
1535 return V;
1536 }
1537
1538 // printf(format, ...) -> iprintf(format, ...) if no floating point
1539 // arguments.
1540 if (TLI->has(LibFunc::iprintf) && !callHasFloatingPointArgument(CI)) {
1541 Module *M = B.GetInsertBlock()->getParent()->getParent();
1542 Constant *IPrintFFn =
Meador Inge08ca1152012-11-26 20:37:20 +00001543 M->getOrInsertFunction("iprintf", FT, Callee->getAttributes());
Chris Bienemanad070d02014-09-17 20:55:46 +00001544 CallInst *New = cast<CallInst>(CI->clone());
1545 New->setCalledFunction(IPrintFFn);
1546 B.Insert(New);
1547 return New;
Meador Inge08ca1152012-11-26 20:37:20 +00001548 }
Chris Bienemanad070d02014-09-17 20:55:46 +00001549 return nullptr;
1550}
Meador Inge08ca1152012-11-26 20:37:20 +00001551
Chris Bienemanad070d02014-09-17 20:55:46 +00001552Value *LibCallSimplifier::optimizeSPrintFString(CallInst *CI, IRBuilder<> &B) {
1553 // Check for a fixed format string.
1554 StringRef FormatStr;
1555 if (!getConstantStringInfo(CI->getArgOperand(1), FormatStr))
Craig Topperf40110f2014-04-25 05:29:35 +00001556 return nullptr;
Meador Inge25c9b3b2012-11-27 05:57:54 +00001557
Chris Bienemanad070d02014-09-17 20:55:46 +00001558 // If we just have a format string (nothing else crazy) transform it.
1559 if (CI->getNumArgOperands() == 2) {
1560 // Make sure there's no % in the constant array. We could try to handle
1561 // %% -> % in the future if we cared.
1562 for (unsigned i = 0, e = FormatStr.size(); i != e; ++i)
1563 if (FormatStr[i] == '%')
1564 return nullptr; // we found a format specifier, bail out.
Hal Finkel66cd3f12013-11-17 02:06:35 +00001565
Chris Bienemanad070d02014-09-17 20:55:46 +00001566 // sprintf(str, fmt) -> llvm.memcpy(str, fmt, strlen(fmt)+1, 1)
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001567 B.CreateMemCpy(CI->getArgOperand(0), CI->getArgOperand(1),
1568 ConstantInt::get(DL.getIntPtrType(CI->getContext()),
1569 FormatStr.size() + 1),
1570 1); // Copy the null byte.
Chris Bienemanad070d02014-09-17 20:55:46 +00001571 return ConstantInt::get(CI->getType(), FormatStr.size());
Meador Ingef8e72502012-11-29 15:45:43 +00001572 }
Meador Ingef8e72502012-11-29 15:45:43 +00001573
Chris Bienemanad070d02014-09-17 20:55:46 +00001574 // The remaining optimizations require the format string to be "%s" or "%c"
1575 // and have an extra operand.
1576 if (FormatStr.size() != 2 || FormatStr[0] != '%' ||
1577 CI->getNumArgOperands() < 3)
Craig Topperf40110f2014-04-25 05:29:35 +00001578 return nullptr;
Meador Inge75798bb2012-11-29 19:15:17 +00001579
Chris Bienemanad070d02014-09-17 20:55:46 +00001580 // Decode the second character of the format string.
1581 if (FormatStr[1] == 'c') {
1582 // sprintf(dst, "%c", chr) --> *(i8*)dst = chr; *((i8*)dst+1) = 0
1583 if (!CI->getArgOperand(2)->getType()->isIntegerTy())
1584 return nullptr;
1585 Value *V = B.CreateTrunc(CI->getArgOperand(2), B.getInt8Ty(), "char");
1586 Value *Ptr = CastToCStr(CI->getArgOperand(0), B);
1587 B.CreateStore(V, Ptr);
1588 Ptr = B.CreateGEP(Ptr, B.getInt32(1), "nul");
1589 B.CreateStore(B.getInt8(0), Ptr);
Meador Ingedf796f82012-10-13 16:45:24 +00001590
Chris Bienemanad070d02014-09-17 20:55:46 +00001591 return ConstantInt::get(CI->getType(), 1);
Meador Ingedf796f82012-10-13 16:45:24 +00001592 }
1593
Chris Bienemanad070d02014-09-17 20:55:46 +00001594 if (FormatStr[1] == 's') {
Chris Bienemanad070d02014-09-17 20:55:46 +00001595 // sprintf(dest, "%s", str) -> llvm.memcpy(dest, str, strlen(str)+1, 1)
1596 if (!CI->getArgOperand(2)->getType()->isPointerTy())
1597 return nullptr;
1598
1599 Value *Len = EmitStrLen(CI->getArgOperand(2), B, DL, TLI);
1600 if (!Len)
1601 return nullptr;
1602 Value *IncLen =
1603 B.CreateAdd(Len, ConstantInt::get(Len->getType(), 1), "leninc");
1604 B.CreateMemCpy(CI->getArgOperand(0), CI->getArgOperand(2), IncLen, 1);
1605
1606 // The sprintf result is the unincremented number of bytes in the string.
1607 return B.CreateIntCast(Len, CI->getType(), false);
1608 }
1609 return nullptr;
1610}
1611
1612Value *LibCallSimplifier::optimizeSPrintF(CallInst *CI, IRBuilder<> &B) {
1613 Function *Callee = CI->getCalledFunction();
1614 // Require two fixed pointer arguments and an integer result.
1615 FunctionType *FT = Callee->getFunctionType();
1616 if (FT->getNumParams() != 2 || !FT->getParamType(0)->isPointerTy() ||
1617 !FT->getParamType(1)->isPointerTy() ||
1618 !FT->getReturnType()->isIntegerTy())
1619 return nullptr;
1620
1621 if (Value *V = optimizeSPrintFString(CI, B)) {
1622 return V;
1623 }
1624
1625 // sprintf(str, format, ...) -> siprintf(str, format, ...) if no floating
1626 // point arguments.
1627 if (TLI->has(LibFunc::siprintf) && !callHasFloatingPointArgument(CI)) {
1628 Module *M = B.GetInsertBlock()->getParent()->getParent();
1629 Constant *SIPrintFFn =
1630 M->getOrInsertFunction("siprintf", FT, Callee->getAttributes());
1631 CallInst *New = cast<CallInst>(CI->clone());
1632 New->setCalledFunction(SIPrintFFn);
1633 B.Insert(New);
1634 return New;
1635 }
1636 return nullptr;
1637}
1638
1639Value *LibCallSimplifier::optimizeFPrintFString(CallInst *CI, IRBuilder<> &B) {
1640 optimizeErrorReporting(CI, B, 0);
1641
1642 // All the optimizations depend on the format string.
1643 StringRef FormatStr;
1644 if (!getConstantStringInfo(CI->getArgOperand(1), FormatStr))
1645 return nullptr;
1646
1647 // Do not do any of the following transformations if the fprintf return
1648 // value is used, in general the fprintf return value is not compatible
1649 // with fwrite(), fputc() or fputs().
1650 if (!CI->use_empty())
1651 return nullptr;
1652
1653 // fprintf(F, "foo") --> fwrite("foo", 3, 1, F)
1654 if (CI->getNumArgOperands() == 2) {
1655 for (unsigned i = 0, e = FormatStr.size(); i != e; ++i)
1656 if (FormatStr[i] == '%') // Could handle %% -> % if we cared.
1657 return nullptr; // We found a format specifier.
1658
Chris Bienemanad070d02014-09-17 20:55:46 +00001659 return EmitFWrite(
1660 CI->getArgOperand(1),
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001661 ConstantInt::get(DL.getIntPtrType(CI->getContext()), FormatStr.size()),
Chris Bienemanad070d02014-09-17 20:55:46 +00001662 CI->getArgOperand(0), B, DL, TLI);
1663 }
1664
1665 // The remaining optimizations require the format string to be "%s" or "%c"
1666 // and have an extra operand.
1667 if (FormatStr.size() != 2 || FormatStr[0] != '%' ||
1668 CI->getNumArgOperands() < 3)
1669 return nullptr;
1670
1671 // Decode the second character of the format string.
1672 if (FormatStr[1] == 'c') {
1673 // fprintf(F, "%c", chr) --> fputc(chr, F)
1674 if (!CI->getArgOperand(2)->getType()->isIntegerTy())
1675 return nullptr;
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001676 return EmitFPutC(CI->getArgOperand(2), CI->getArgOperand(0), B, TLI);
Chris Bienemanad070d02014-09-17 20:55:46 +00001677 }
1678
1679 if (FormatStr[1] == 's') {
1680 // fprintf(F, "%s", str) --> fputs(str, F)
1681 if (!CI->getArgOperand(2)->getType()->isPointerTy())
1682 return nullptr;
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001683 return EmitFPutS(CI->getArgOperand(2), CI->getArgOperand(0), B, TLI);
Chris Bienemanad070d02014-09-17 20:55:46 +00001684 }
1685 return nullptr;
1686}
1687
1688Value *LibCallSimplifier::optimizeFPrintF(CallInst *CI, IRBuilder<> &B) {
1689 Function *Callee = CI->getCalledFunction();
1690 // Require two fixed paramters as pointers and integer result.
1691 FunctionType *FT = Callee->getFunctionType();
1692 if (FT->getNumParams() != 2 || !FT->getParamType(0)->isPointerTy() ||
1693 !FT->getParamType(1)->isPointerTy() ||
1694 !FT->getReturnType()->isIntegerTy())
1695 return nullptr;
1696
1697 if (Value *V = optimizeFPrintFString(CI, B)) {
1698 return V;
1699 }
1700
1701 // fprintf(stream, format, ...) -> fiprintf(stream, format, ...) if no
1702 // floating point arguments.
1703 if (TLI->has(LibFunc::fiprintf) && !callHasFloatingPointArgument(CI)) {
1704 Module *M = B.GetInsertBlock()->getParent()->getParent();
1705 Constant *FIPrintFFn =
1706 M->getOrInsertFunction("fiprintf", FT, Callee->getAttributes());
1707 CallInst *New = cast<CallInst>(CI->clone());
1708 New->setCalledFunction(FIPrintFFn);
1709 B.Insert(New);
1710 return New;
1711 }
1712 return nullptr;
1713}
1714
1715Value *LibCallSimplifier::optimizeFWrite(CallInst *CI, IRBuilder<> &B) {
1716 optimizeErrorReporting(CI, B, 3);
1717
1718 Function *Callee = CI->getCalledFunction();
1719 // Require a pointer, an integer, an integer, a pointer, returning integer.
1720 FunctionType *FT = Callee->getFunctionType();
1721 if (FT->getNumParams() != 4 || !FT->getParamType(0)->isPointerTy() ||
1722 !FT->getParamType(1)->isIntegerTy() ||
1723 !FT->getParamType(2)->isIntegerTy() ||
1724 !FT->getParamType(3)->isPointerTy() ||
1725 !FT->getReturnType()->isIntegerTy())
1726 return nullptr;
1727
1728 // Get the element size and count.
1729 ConstantInt *SizeC = dyn_cast<ConstantInt>(CI->getArgOperand(1));
1730 ConstantInt *CountC = dyn_cast<ConstantInt>(CI->getArgOperand(2));
1731 if (!SizeC || !CountC)
1732 return nullptr;
1733 uint64_t Bytes = SizeC->getZExtValue() * CountC->getZExtValue();
1734
1735 // If this is writing zero records, remove the call (it's a noop).
1736 if (Bytes == 0)
1737 return ConstantInt::get(CI->getType(), 0);
1738
1739 // If this is writing one byte, turn it into fputc.
1740 // This optimisation is only valid, if the return value is unused.
1741 if (Bytes == 1 && CI->use_empty()) { // fwrite(S,1,1,F) -> fputc(S[0],F)
1742 Value *Char = B.CreateLoad(CastToCStr(CI->getArgOperand(0), B), "char");
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001743 Value *NewCI = EmitFPutC(Char, CI->getArgOperand(3), B, TLI);
Chris Bienemanad070d02014-09-17 20:55:46 +00001744 return NewCI ? ConstantInt::get(CI->getType(), 1) : nullptr;
1745 }
1746
1747 return nullptr;
1748}
1749
1750Value *LibCallSimplifier::optimizeFPuts(CallInst *CI, IRBuilder<> &B) {
1751 optimizeErrorReporting(CI, B, 1);
1752
1753 Function *Callee = CI->getCalledFunction();
1754
Chris Bienemanad070d02014-09-17 20:55:46 +00001755 // Require two pointers. Also, we can't optimize if return value is used.
1756 FunctionType *FT = Callee->getFunctionType();
1757 if (FT->getNumParams() != 2 || !FT->getParamType(0)->isPointerTy() ||
1758 !FT->getParamType(1)->isPointerTy() || !CI->use_empty())
1759 return nullptr;
1760
1761 // fputs(s,F) --> fwrite(s,1,strlen(s),F)
1762 uint64_t Len = GetStringLength(CI->getArgOperand(0));
1763 if (!Len)
1764 return nullptr;
1765
1766 // Known to have no uses (see above).
1767 return EmitFWrite(
1768 CI->getArgOperand(0),
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001769 ConstantInt::get(DL.getIntPtrType(CI->getContext()), Len - 1),
Chris Bienemanad070d02014-09-17 20:55:46 +00001770 CI->getArgOperand(1), B, DL, TLI);
1771}
1772
1773Value *LibCallSimplifier::optimizePuts(CallInst *CI, IRBuilder<> &B) {
1774 Function *Callee = CI->getCalledFunction();
1775 // Require one fixed pointer argument and an integer/void result.
1776 FunctionType *FT = Callee->getFunctionType();
1777 if (FT->getNumParams() < 1 || !FT->getParamType(0)->isPointerTy() ||
1778 !(FT->getReturnType()->isIntegerTy() || FT->getReturnType()->isVoidTy()))
1779 return nullptr;
1780
1781 // Check for a constant string.
1782 StringRef Str;
1783 if (!getConstantStringInfo(CI->getArgOperand(0), Str))
1784 return nullptr;
1785
1786 if (Str.empty() && CI->use_empty()) {
1787 // puts("") -> putchar('\n')
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001788 Value *Res = EmitPutChar(B.getInt32('\n'), B, TLI);
Chris Bienemanad070d02014-09-17 20:55:46 +00001789 if (CI->use_empty() || !Res)
1790 return Res;
1791 return B.CreateIntCast(Res, CI->getType(), true);
1792 }
1793
1794 return nullptr;
1795}
1796
1797bool LibCallSimplifier::hasFloatVersion(StringRef FuncName) {
Meador Inge20255ef2013-03-12 00:08:29 +00001798 LibFunc::Func Func;
1799 SmallString<20> FloatFuncName = FuncName;
1800 FloatFuncName += 'f';
1801 if (TLI->getLibFunc(FloatFuncName, Func))
1802 return TLI->has(Func);
1803 return false;
1804}
Meador Inge7fb2f732012-10-13 16:45:32 +00001805
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00001806Value *LibCallSimplifier::optimizeStringMemoryLibCall(CallInst *CI,
1807 IRBuilder<> &Builder) {
1808 LibFunc::Func Func;
1809 Function *Callee = CI->getCalledFunction();
1810 StringRef FuncName = Callee->getName();
1811
1812 // Check for string/memory library functions.
1813 if (TLI->getLibFunc(FuncName, Func) && TLI->has(Func)) {
1814 // Make sure we never change the calling convention.
1815 assert((ignoreCallingConv(Func) ||
1816 CI->getCallingConv() == llvm::CallingConv::C) &&
1817 "Optimizing string/memory libcall would change the calling convention");
1818 switch (Func) {
1819 case LibFunc::strcat:
1820 return optimizeStrCat(CI, Builder);
1821 case LibFunc::strncat:
1822 return optimizeStrNCat(CI, Builder);
1823 case LibFunc::strchr:
1824 return optimizeStrChr(CI, Builder);
1825 case LibFunc::strrchr:
1826 return optimizeStrRChr(CI, Builder);
1827 case LibFunc::strcmp:
1828 return optimizeStrCmp(CI, Builder);
1829 case LibFunc::strncmp:
1830 return optimizeStrNCmp(CI, Builder);
1831 case LibFunc::strcpy:
1832 return optimizeStrCpy(CI, Builder);
1833 case LibFunc::stpcpy:
1834 return optimizeStpCpy(CI, Builder);
1835 case LibFunc::strncpy:
1836 return optimizeStrNCpy(CI, Builder);
1837 case LibFunc::strlen:
1838 return optimizeStrLen(CI, Builder);
1839 case LibFunc::strpbrk:
1840 return optimizeStrPBrk(CI, Builder);
1841 case LibFunc::strtol:
1842 case LibFunc::strtod:
1843 case LibFunc::strtof:
1844 case LibFunc::strtoul:
1845 case LibFunc::strtoll:
1846 case LibFunc::strtold:
1847 case LibFunc::strtoull:
1848 return optimizeStrTo(CI, Builder);
1849 case LibFunc::strspn:
1850 return optimizeStrSpn(CI, Builder);
1851 case LibFunc::strcspn:
1852 return optimizeStrCSpn(CI, Builder);
1853 case LibFunc::strstr:
1854 return optimizeStrStr(CI, Builder);
1855 case LibFunc::memcmp:
1856 return optimizeMemCmp(CI, Builder);
1857 case LibFunc::memcpy:
1858 return optimizeMemCpy(CI, Builder);
1859 case LibFunc::memmove:
1860 return optimizeMemMove(CI, Builder);
1861 case LibFunc::memset:
1862 return optimizeMemSet(CI, Builder);
1863 default:
1864 break;
1865 }
1866 }
1867 return nullptr;
1868}
1869
Chris Bienemanad070d02014-09-17 20:55:46 +00001870Value *LibCallSimplifier::optimizeCall(CallInst *CI) {
1871 if (CI->isNoBuiltin())
1872 return nullptr;
Meador Inge4d2827c2012-11-11 05:11:20 +00001873
Meador Inge20255ef2013-03-12 00:08:29 +00001874 LibFunc::Func Func;
1875 Function *Callee = CI->getCalledFunction();
1876 StringRef FuncName = Callee->getName();
Chris Bienemanad070d02014-09-17 20:55:46 +00001877 IRBuilder<> Builder(CI);
1878 bool isCallingConvC = CI->getCallingConv() == llvm::CallingConv::C;
Meador Inge20255ef2013-03-12 00:08:29 +00001879
Sanjay Patela92fa442014-10-22 15:29:23 +00001880 // Command-line parameter overrides function attribute.
1881 if (EnableUnsafeFPShrink.getNumOccurrences() > 0)
1882 UnsafeFPShrink = EnableUnsafeFPShrink;
1883 else if (Callee->hasFnAttribute("unsafe-fp-math")) {
1884 // FIXME: This is the same problem as described in optimizeSqrt().
1885 // If calls gain access to IR-level FMF, then use that instead of a
1886 // function attribute.
1887
1888 // Check for unsafe-fp-math = true.
1889 Attribute Attr = Callee->getFnAttribute("unsafe-fp-math");
1890 if (Attr.getValueAsString() == "true")
1891 UnsafeFPShrink = true;
1892 }
1893
Sanjay Patel848309d2014-10-23 21:52:45 +00001894 // First, check for intrinsics.
Meador Inge20255ef2013-03-12 00:08:29 +00001895 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(CI)) {
Chris Bienemanad070d02014-09-17 20:55:46 +00001896 if (!isCallingConvC)
1897 return nullptr;
Meador Inge20255ef2013-03-12 00:08:29 +00001898 switch (II->getIntrinsicID()) {
1899 case Intrinsic::pow:
Chris Bienemanad070d02014-09-17 20:55:46 +00001900 return optimizePow(CI, Builder);
Meador Inge20255ef2013-03-12 00:08:29 +00001901 case Intrinsic::exp2:
Chris Bienemanad070d02014-09-17 20:55:46 +00001902 return optimizeExp2(CI, Builder);
Sanjay Patel0ca42bb2014-10-14 20:43:11 +00001903 case Intrinsic::fabs:
1904 return optimizeFabs(CI, Builder);
Sanjay Patelc699a612014-10-16 18:48:17 +00001905 case Intrinsic::sqrt:
1906 return optimizeSqrt(CI, Builder);
Meador Inge20255ef2013-03-12 00:08:29 +00001907 default:
Chris Bienemanad070d02014-09-17 20:55:46 +00001908 return nullptr;
Meador Inge20255ef2013-03-12 00:08:29 +00001909 }
1910 }
1911
Ahmed Bougachae03bef72015-01-12 17:22:43 +00001912 // Also try to simplify calls to fortified library functions.
1913 if (Value *SimplifiedFortifiedCI = FortifiedSimplifier.optimizeCall(CI)) {
1914 // Try to further simplify the result.
Ahmed Bougacha71d7b182015-01-14 00:55:05 +00001915 CallInst *SimplifiedCI = dyn_cast<CallInst>(SimplifiedFortifiedCI);
1916 if (SimplifiedCI && SimplifiedCI->getCalledFunction())
Ahmed Bougacha1ac93562015-01-27 21:52:16 +00001917 if (Value *V = optimizeStringMemoryLibCall(SimplifiedCI, Builder)) {
1918 // If we were able to further simplify, remove the now redundant call.
1919 SimplifiedCI->replaceAllUsesWith(V);
1920 SimplifiedCI->eraseFromParent();
Ahmed Bougachae03bef72015-01-12 17:22:43 +00001921 return V;
Ahmed Bougacha1ac93562015-01-27 21:52:16 +00001922 }
Ahmed Bougachae03bef72015-01-12 17:22:43 +00001923 return SimplifiedFortifiedCI;
1924 }
1925
Meador Inge20255ef2013-03-12 00:08:29 +00001926 // Then check for known library functions.
1927 if (TLI->getLibFunc(FuncName, Func) && TLI->has(Func)) {
Chris Bienemanad070d02014-09-17 20:55:46 +00001928 // We never change the calling convention.
1929 if (!ignoreCallingConv(Func) && !isCallingConvC)
1930 return nullptr;
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00001931 if (Value *V = optimizeStringMemoryLibCall(CI, Builder))
1932 return V;
Meador Inge20255ef2013-03-12 00:08:29 +00001933 switch (Func) {
Chris Bienemanad070d02014-09-17 20:55:46 +00001934 case LibFunc::cosf:
1935 case LibFunc::cos:
1936 case LibFunc::cosl:
1937 return optimizeCos(CI, Builder);
1938 case LibFunc::sinpif:
1939 case LibFunc::sinpi:
1940 case LibFunc::cospif:
1941 case LibFunc::cospi:
1942 return optimizeSinCosPi(CI, Builder);
1943 case LibFunc::powf:
1944 case LibFunc::pow:
1945 case LibFunc::powl:
1946 return optimizePow(CI, Builder);
1947 case LibFunc::exp2l:
1948 case LibFunc::exp2:
1949 case LibFunc::exp2f:
1950 return optimizeExp2(CI, Builder);
Sanjay Patel0ca42bb2014-10-14 20:43:11 +00001951 case LibFunc::fabsf:
1952 case LibFunc::fabs:
1953 case LibFunc::fabsl:
1954 return optimizeFabs(CI, Builder);
Sanjay Patelc699a612014-10-16 18:48:17 +00001955 case LibFunc::sqrtf:
1956 case LibFunc::sqrt:
1957 case LibFunc::sqrtl:
1958 return optimizeSqrt(CI, Builder);
Chris Bienemanad070d02014-09-17 20:55:46 +00001959 case LibFunc::ffs:
1960 case LibFunc::ffsl:
1961 case LibFunc::ffsll:
1962 return optimizeFFS(CI, Builder);
1963 case LibFunc::abs:
1964 case LibFunc::labs:
1965 case LibFunc::llabs:
1966 return optimizeAbs(CI, Builder);
1967 case LibFunc::isdigit:
1968 return optimizeIsDigit(CI, Builder);
1969 case LibFunc::isascii:
1970 return optimizeIsAscii(CI, Builder);
1971 case LibFunc::toascii:
1972 return optimizeToAscii(CI, Builder);
1973 case LibFunc::printf:
1974 return optimizePrintF(CI, Builder);
1975 case LibFunc::sprintf:
1976 return optimizeSPrintF(CI, Builder);
1977 case LibFunc::fprintf:
1978 return optimizeFPrintF(CI, Builder);
1979 case LibFunc::fwrite:
1980 return optimizeFWrite(CI, Builder);
1981 case LibFunc::fputs:
1982 return optimizeFPuts(CI, Builder);
1983 case LibFunc::puts:
1984 return optimizePuts(CI, Builder);
1985 case LibFunc::perror:
1986 return optimizeErrorReporting(CI, Builder);
1987 case LibFunc::vfprintf:
1988 case LibFunc::fiprintf:
1989 return optimizeErrorReporting(CI, Builder, 0);
1990 case LibFunc::fputc:
1991 return optimizeErrorReporting(CI, Builder, 1);
1992 case LibFunc::ceil:
Chris Bienemanad070d02014-09-17 20:55:46 +00001993 case LibFunc::floor:
1994 case LibFunc::rint:
1995 case LibFunc::round:
1996 case LibFunc::nearbyint:
1997 case LibFunc::trunc:
1998 if (hasFloatVersion(FuncName))
1999 return optimizeUnaryDoubleFP(CI, Builder, false);
2000 return nullptr;
2001 case LibFunc::acos:
2002 case LibFunc::acosh:
2003 case LibFunc::asin:
2004 case LibFunc::asinh:
2005 case LibFunc::atan:
2006 case LibFunc::atanh:
2007 case LibFunc::cbrt:
2008 case LibFunc::cosh:
2009 case LibFunc::exp:
2010 case LibFunc::exp10:
2011 case LibFunc::expm1:
2012 case LibFunc::log:
2013 case LibFunc::log10:
2014 case LibFunc::log1p:
2015 case LibFunc::log2:
2016 case LibFunc::logb:
2017 case LibFunc::sin:
2018 case LibFunc::sinh:
Chris Bienemanad070d02014-09-17 20:55:46 +00002019 case LibFunc::tan:
2020 case LibFunc::tanh:
2021 if (UnsafeFPShrink && hasFloatVersion(FuncName))
2022 return optimizeUnaryDoubleFP(CI, Builder, true);
2023 return nullptr;
Matthias Braun892c9232014-12-03 21:46:29 +00002024 case LibFunc::copysign:
Chris Bienemanad070d02014-09-17 20:55:46 +00002025 case LibFunc::fmin:
2026 case LibFunc::fmax:
2027 if (hasFloatVersion(FuncName))
2028 return optimizeBinaryDoubleFP(CI, Builder);
2029 return nullptr;
Chris Bienemanad070d02014-09-17 20:55:46 +00002030 default:
2031 return nullptr;
2032 }
Meador Inge20255ef2013-03-12 00:08:29 +00002033 }
Craig Topperf40110f2014-04-25 05:29:35 +00002034 return nullptr;
Meador Ingedf796f82012-10-13 16:45:24 +00002035}
2036
Chandler Carruth92803822015-01-21 02:11:59 +00002037LibCallSimplifier::LibCallSimplifier(
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002038 const DataLayout &DL, const TargetLibraryInfo *TLI,
Chandler Carruth92803822015-01-21 02:11:59 +00002039 function_ref<void(Instruction *, Value *)> Replacer)
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002040 : FortifiedSimplifier(TLI), DL(DL), TLI(TLI), UnsafeFPShrink(false),
Chandler Carruth92803822015-01-21 02:11:59 +00002041 Replacer(Replacer) {}
2042
2043void LibCallSimplifier::replaceAllUsesWith(Instruction *I, Value *With) {
2044 // Indirect through the replacer used in this instance.
2045 Replacer(I, With);
Meador Ingedf796f82012-10-13 16:45:24 +00002046}
2047
Chandler Carruth92803822015-01-21 02:11:59 +00002048/*static*/ void LibCallSimplifier::replaceAllUsesWithDefault(Instruction *I,
2049 Value *With) {
Meador Inge76fc1a42012-11-11 03:51:43 +00002050 I->replaceAllUsesWith(With);
2051 I->eraseFromParent();
2052}
2053
Meador Ingedfb08a22013-06-20 19:48:07 +00002054// TODO:
2055// Additional cases that we need to add to this file:
2056//
2057// cbrt:
2058// * cbrt(expN(X)) -> expN(x/3)
2059// * cbrt(sqrt(x)) -> pow(x,1/6)
2060// * cbrt(sqrt(x)) -> pow(x,1/9)
2061//
2062// exp, expf, expl:
2063// * exp(log(x)) -> x
2064//
2065// log, logf, logl:
2066// * log(exp(x)) -> x
2067// * log(x**y) -> y*log(x)
2068// * log(exp(y)) -> y*log(e)
2069// * log(exp2(y)) -> y*log(2)
2070// * log(exp10(y)) -> y*log(10)
2071// * log(sqrt(x)) -> 0.5*log(x)
2072// * log(pow(x,y)) -> y*log(x)
2073//
2074// lround, lroundf, lroundl:
2075// * lround(cnst) -> cnst'
2076//
2077// pow, powf, powl:
2078// * pow(exp(x),y) -> exp(x*y)
2079// * pow(sqrt(x),y) -> pow(x,y*0.5)
2080// * pow(pow(x,y),z)-> pow(x,y*z)
2081//
2082// round, roundf, roundl:
2083// * round(cnst) -> cnst'
2084//
2085// signbit:
2086// * signbit(cnst) -> cnst'
2087// * signbit(nncst) -> 0 (if pstv is a non-negative constant)
2088//
2089// sqrt, sqrtf, sqrtl:
2090// * sqrt(expN(x)) -> expN(x*0.5)
2091// * sqrt(Nroot(x)) -> pow(x,1/(2*N))
2092// * sqrt(pow(x,y)) -> pow(|x|,y*0.5)
2093//
Meador Ingedfb08a22013-06-20 19:48:07 +00002094// tan, tanf, tanl:
2095// * tan(atan(x)) -> x
2096//
2097// trunc, truncf, truncl:
2098// * trunc(cnst) -> cnst'
2099//
2100//
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002101
2102//===----------------------------------------------------------------------===//
2103// Fortified Library Call Optimizations
2104//===----------------------------------------------------------------------===//
2105
2106bool FortifiedLibCallSimplifier::isFortifiedCallFoldable(CallInst *CI,
2107 unsigned ObjSizeOp,
2108 unsigned SizeOp,
2109 bool isString) {
2110 if (CI->getArgOperand(ObjSizeOp) == CI->getArgOperand(SizeOp))
2111 return true;
2112 if (ConstantInt *ObjSizeCI =
2113 dyn_cast<ConstantInt>(CI->getArgOperand(ObjSizeOp))) {
2114 if (ObjSizeCI->isAllOnesValue())
2115 return true;
2116 // If the object size wasn't -1 (unknown), bail out if we were asked to.
2117 if (OnlyLowerUnknownSize)
2118 return false;
2119 if (isString) {
2120 uint64_t Len = GetStringLength(CI->getArgOperand(SizeOp));
2121 // If the length is 0 we don't know how long it is and so we can't
2122 // remove the check.
2123 if (Len == 0)
2124 return false;
2125 return ObjSizeCI->getZExtValue() >= Len;
2126 }
2127 if (ConstantInt *SizeCI = dyn_cast<ConstantInt>(CI->getArgOperand(SizeOp)))
2128 return ObjSizeCI->getZExtValue() >= SizeCI->getZExtValue();
2129 }
2130 return false;
2131}
2132
2133Value *FortifiedLibCallSimplifier::optimizeMemCpyChk(CallInst *CI, IRBuilder<> &B) {
2134 Function *Callee = CI->getCalledFunction();
2135
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002136 if (!checkStringCopyLibFuncSignature(Callee, LibFunc::memcpy_chk))
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002137 return nullptr;
2138
2139 if (isFortifiedCallFoldable(CI, 3, 2, false)) {
2140 B.CreateMemCpy(CI->getArgOperand(0), CI->getArgOperand(1),
2141 CI->getArgOperand(2), 1);
2142 return CI->getArgOperand(0);
2143 }
2144 return nullptr;
2145}
2146
2147Value *FortifiedLibCallSimplifier::optimizeMemMoveChk(CallInst *CI, IRBuilder<> &B) {
2148 Function *Callee = CI->getCalledFunction();
2149
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002150 if (!checkStringCopyLibFuncSignature(Callee, LibFunc::memmove_chk))
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002151 return nullptr;
2152
2153 if (isFortifiedCallFoldable(CI, 3, 2, false)) {
2154 B.CreateMemMove(CI->getArgOperand(0), CI->getArgOperand(1),
2155 CI->getArgOperand(2), 1);
2156 return CI->getArgOperand(0);
2157 }
2158 return nullptr;
2159}
2160
2161Value *FortifiedLibCallSimplifier::optimizeMemSetChk(CallInst *CI, IRBuilder<> &B) {
2162 Function *Callee = CI->getCalledFunction();
2163
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002164 if (!checkStringCopyLibFuncSignature(Callee, LibFunc::memset_chk))
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002165 return nullptr;
2166
2167 if (isFortifiedCallFoldable(CI, 3, 2, false)) {
2168 Value *Val = B.CreateIntCast(CI->getArgOperand(1), B.getInt8Ty(), false);
2169 B.CreateMemSet(CI->getArgOperand(0), Val, CI->getArgOperand(2), 1);
2170 return CI->getArgOperand(0);
2171 }
2172 return nullptr;
2173}
2174
Ahmed Bougacha1ac93562015-01-27 21:52:16 +00002175Value *FortifiedLibCallSimplifier::optimizeStrpCpyChk(CallInst *CI,
2176 IRBuilder<> &B,
2177 LibFunc::Func Func) {
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002178 Function *Callee = CI->getCalledFunction();
2179 StringRef Name = Callee->getName();
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002180 const DataLayout &DL = CI->getModule()->getDataLayout();
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002181
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002182 if (!checkStringCopyLibFuncSignature(Callee, Func))
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002183 return nullptr;
2184
2185 Value *Dst = CI->getArgOperand(0), *Src = CI->getArgOperand(1),
2186 *ObjSize = CI->getArgOperand(2);
2187
2188 // __stpcpy_chk(x,x,...) -> x+strlen(x)
Ahmed Bougacha1ac93562015-01-27 21:52:16 +00002189 if (Func == LibFunc::stpcpy_chk && !OnlyLowerUnknownSize && Dst == Src) {
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002190 Value *StrLen = EmitStrLen(Src, B, DL, TLI);
2191 return StrLen ? B.CreateInBoundsGEP(Dst, StrLen) : nullptr;
2192 }
2193
2194 // If a) we don't have any length information, or b) we know this will
2195 // fit then just lower to a plain st[rp]cpy. Otherwise we'll keep our
2196 // st[rp]cpy_chk call which may fail at runtime if the size is too long.
2197 // TODO: It might be nice to get a maximum length out of the possible
2198 // string lengths for varying.
2199 if (isFortifiedCallFoldable(CI, 2, 1, true)) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002200 Value *Ret = EmitStrCpy(Dst, Src, B, TLI, Name.substr(2, 6));
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002201 return Ret;
2202 } else if (!OnlyLowerUnknownSize) {
2203 // Maybe we can stil fold __st[rp]cpy_chk to __memcpy_chk.
2204 uint64_t Len = GetStringLength(Src);
2205 if (Len == 0)
2206 return nullptr;
2207
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002208 Type *SizeTTy = DL.getIntPtrType(CI->getContext());
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002209 Value *LenV = ConstantInt::get(SizeTTy, Len);
2210 Value *Ret = EmitMemCpyChk(Dst, Src, LenV, ObjSize, B, DL, TLI);
2211 // If the function was an __stpcpy_chk, and we were able to fold it into
2212 // a __memcpy_chk, we still need to return the correct end pointer.
2213 if (Ret && Func == LibFunc::stpcpy_chk)
2214 return B.CreateGEP(Dst, ConstantInt::get(SizeTTy, Len - 1));
2215 return Ret;
2216 }
2217 return nullptr;
2218}
2219
Ahmed Bougacha1ac93562015-01-27 21:52:16 +00002220Value *FortifiedLibCallSimplifier::optimizeStrpNCpyChk(CallInst *CI,
2221 IRBuilder<> &B,
2222 LibFunc::Func Func) {
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002223 Function *Callee = CI->getCalledFunction();
2224 StringRef Name = Callee->getName();
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002225
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002226 if (!checkStringCopyLibFuncSignature(Callee, Func))
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002227 return nullptr;
2228 if (isFortifiedCallFoldable(CI, 3, 2, false)) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002229 Value *Ret = EmitStrNCpy(CI->getArgOperand(0), CI->getArgOperand(1),
2230 CI->getArgOperand(2), B, TLI, Name.substr(2, 7));
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002231 return Ret;
2232 }
2233 return nullptr;
2234}
2235
2236Value *FortifiedLibCallSimplifier::optimizeCall(CallInst *CI) {
2237 if (CI->isNoBuiltin())
2238 return nullptr;
2239
2240 LibFunc::Func Func;
2241 Function *Callee = CI->getCalledFunction();
2242 StringRef FuncName = Callee->getName();
2243 IRBuilder<> Builder(CI);
2244 bool isCallingConvC = CI->getCallingConv() == llvm::CallingConv::C;
2245
2246 // First, check that this is a known library functions.
2247 if (!TLI->getLibFunc(FuncName, Func) || !TLI->has(Func))
2248 return nullptr;
2249
2250 // We never change the calling convention.
2251 if (!ignoreCallingConv(Func) && !isCallingConvC)
2252 return nullptr;
2253
2254 switch (Func) {
2255 case LibFunc::memcpy_chk:
2256 return optimizeMemCpyChk(CI, Builder);
2257 case LibFunc::memmove_chk:
2258 return optimizeMemMoveChk(CI, Builder);
2259 case LibFunc::memset_chk:
2260 return optimizeMemSetChk(CI, Builder);
2261 case LibFunc::stpcpy_chk:
2262 case LibFunc::strcpy_chk:
Ahmed Bougacha1ac93562015-01-27 21:52:16 +00002263 return optimizeStrpCpyChk(CI, Builder, Func);
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002264 case LibFunc::stpncpy_chk:
2265 case LibFunc::strncpy_chk:
Ahmed Bougacha1ac93562015-01-27 21:52:16 +00002266 return optimizeStrpNCpyChk(CI, Builder, Func);
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002267 default:
2268 break;
2269 }
2270 return nullptr;
2271}
2272
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002273FortifiedLibCallSimplifier::FortifiedLibCallSimplifier(
2274 const TargetLibraryInfo *TLI, bool OnlyLowerUnknownSize)
2275 : TLI(TLI), OnlyLowerUnknownSize(OnlyLowerUnknownSize) {}