blob: 0713ed1e9c73260da147c7c8cde283dcde0e36b5 [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"
Chad Rosierdc655322015-08-28 18:30:18 +000035#include "llvm/Transforms/Utils/Local.h"
Meador Ingedf796f82012-10-13 16:45:24 +000036
37using namespace llvm;
Sanjay Patelc699a612014-10-16 18:48:17 +000038using namespace PatternMatch;
Meador Ingedf796f82012-10-13 16:45:24 +000039
Hal Finkel66cd3f12013-11-17 02:06:35 +000040static cl::opt<bool>
Chris Bienemanad070d02014-09-17 20:55:46 +000041 ColdErrorCalls("error-reporting-is-cold", cl::init(true), cl::Hidden,
42 cl::desc("Treat error-reporting calls as cold"));
Meador Ingedf796f82012-10-13 16:45:24 +000043
Sanjay Patela92fa442014-10-22 15:29:23 +000044static cl::opt<bool>
45 EnableUnsafeFPShrink("enable-double-float-shrink", cl::Hidden,
46 cl::init(false),
47 cl::desc("Enable unsafe double to float "
48 "shrinking for math lib calls"));
49
50
Meador Ingedf796f82012-10-13 16:45:24 +000051//===----------------------------------------------------------------------===//
Meador Inged589ac62012-10-31 03:33:06 +000052// Helper Functions
53//===----------------------------------------------------------------------===//
54
Chris Bienemanad070d02014-09-17 20:55:46 +000055static bool ignoreCallingConv(LibFunc::Func Func) {
56 switch (Func) {
57 case LibFunc::abs:
58 case LibFunc::labs:
59 case LibFunc::llabs:
60 case LibFunc::strlen:
61 return true;
62 default:
63 return false;
64 }
Chris Bienemancf93cbb2014-09-17 21:06:59 +000065 llvm_unreachable("All cases should be covered in the switch.");
Chris Bienemanad070d02014-09-17 20:55:46 +000066}
67
Meador Inged589ac62012-10-31 03:33:06 +000068/// isOnlyUsedInZeroEqualityComparison - Return true if it only matters that the
69/// value is equal or not-equal to zero.
70static bool isOnlyUsedInZeroEqualityComparison(Value *V) {
Chandler Carruthcdf47882014-03-09 03:16:01 +000071 for (User *U : V->users()) {
72 if (ICmpInst *IC = dyn_cast<ICmpInst>(U))
Meador Inged589ac62012-10-31 03:33:06 +000073 if (IC->isEquality())
74 if (Constant *C = dyn_cast<Constant>(IC->getOperand(1)))
75 if (C->isNullValue())
76 continue;
77 // Unknown instruction.
78 return false;
79 }
80 return true;
81}
82
Meador Inge56edbc92012-11-11 03:51:48 +000083/// isOnlyUsedInEqualityComparison - Return true if it is only used in equality
84/// comparisons with With.
85static bool isOnlyUsedInEqualityComparison(Value *V, Value *With) {
Chandler Carruthcdf47882014-03-09 03:16:01 +000086 for (User *U : V->users()) {
87 if (ICmpInst *IC = dyn_cast<ICmpInst>(U))
Meador Inge56edbc92012-11-11 03:51:48 +000088 if (IC->isEquality() && IC->getOperand(1) == With)
89 continue;
90 // Unknown instruction.
91 return false;
92 }
93 return true;
94}
95
Meador Inge08ca1152012-11-26 20:37:20 +000096static bool callHasFloatingPointArgument(const CallInst *CI) {
97 for (CallInst::const_op_iterator it = CI->op_begin(), e = CI->op_end();
98 it != e; ++it) {
99 if ((*it)->getType()->isFloatingPointTy())
100 return true;
101 }
102 return false;
103}
104
Benjamin Kramer2702caa2013-08-31 18:19:35 +0000105/// \brief Check whether the overloaded unary floating point function
Sanjay Patele24c60e2015-08-12 20:36:18 +0000106/// corresponding to \a Ty is available.
Benjamin Kramer2702caa2013-08-31 18:19:35 +0000107static bool hasUnaryFloatFn(const TargetLibraryInfo *TLI, Type *Ty,
108 LibFunc::Func DoubleFn, LibFunc::Func FloatFn,
109 LibFunc::Func LongDoubleFn) {
110 switch (Ty->getTypeID()) {
111 case Type::FloatTyID:
112 return TLI->has(FloatFn);
113 case Type::DoubleTyID:
114 return TLI->has(DoubleFn);
115 default:
116 return TLI->has(LongDoubleFn);
117 }
118}
119
Davide Italianoa904e522015-10-29 02:58:44 +0000120/// \brief Check whether we can use unsafe floating point math for
121/// the function passed as input.
122static bool canUseUnsafeFPMath(Function *F) {
123
124 // FIXME: For finer-grain optimization, we need intrinsics to have the same
125 // fast-math flag decorations that are applied to FP instructions. For now,
126 // we have to rely on the function-level unsafe-fp-math attribute to do this
127 // optimization because there's no other way to express that the sqrt can be
128 // reassociated.
129 if (F->hasFnAttribute("unsafe-fp-math")) {
130 Attribute Attr = F->getFnAttribute("unsafe-fp-math");
131 if (Attr.getValueAsString() == "true")
132 return true;
133 }
134 return false;
135}
136
Ahmed Bougachab7d8afb2015-01-12 17:18:19 +0000137/// \brief Returns whether \p F matches the signature expected for the
138/// string/memory copying library function \p Func.
139/// Acceptable functions are st[rp][n]?cpy, memove, memcpy, and memset.
140/// Their fortified (_chk) counterparts are also accepted.
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000141static bool checkStringCopyLibFuncSignature(Function *F, LibFunc::Func Func) {
142 const DataLayout &DL = F->getParent()->getDataLayout();
Ahmed Bougachab7d8afb2015-01-12 17:18:19 +0000143 FunctionType *FT = F->getFunctionType();
144 LLVMContext &Context = F->getContext();
145 Type *PCharTy = Type::getInt8PtrTy(Context);
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000146 Type *SizeTTy = DL.getIntPtrType(Context);
Ahmed Bougachab7d8afb2015-01-12 17:18:19 +0000147 unsigned NumParams = FT->getNumParams();
148
149 // All string libfuncs return the same type as the first parameter.
150 if (FT->getReturnType() != FT->getParamType(0))
151 return false;
152
153 switch (Func) {
154 default:
155 llvm_unreachable("Can't check signature for non-string-copy libfunc.");
156 case LibFunc::stpncpy_chk:
157 case LibFunc::strncpy_chk:
158 --NumParams; // fallthrough
159 case LibFunc::stpncpy:
160 case LibFunc::strncpy: {
161 if (NumParams != 3 || FT->getParamType(0) != FT->getParamType(1) ||
162 FT->getParamType(0) != PCharTy || !FT->getParamType(2)->isIntegerTy())
163 return false;
164 break;
165 }
166 case LibFunc::strcpy_chk:
167 case LibFunc::stpcpy_chk:
168 --NumParams; // fallthrough
169 case LibFunc::stpcpy:
170 case LibFunc::strcpy: {
171 if (NumParams != 2 || FT->getParamType(0) != FT->getParamType(1) ||
172 FT->getParamType(0) != PCharTy)
173 return false;
174 break;
175 }
176 case LibFunc::memmove_chk:
177 case LibFunc::memcpy_chk:
178 --NumParams; // fallthrough
179 case LibFunc::memmove:
180 case LibFunc::memcpy: {
181 if (NumParams != 3 || !FT->getParamType(0)->isPointerTy() ||
182 !FT->getParamType(1)->isPointerTy() || FT->getParamType(2) != SizeTTy)
183 return false;
184 break;
185 }
186 case LibFunc::memset_chk:
187 --NumParams; // fallthrough
188 case LibFunc::memset: {
189 if (NumParams != 3 || !FT->getParamType(0)->isPointerTy() ||
190 !FT->getParamType(1)->isIntegerTy() || FT->getParamType(2) != SizeTTy)
191 return false;
192 break;
193 }
194 }
195 // If this is a fortified libcall, the last parameter is a size_t.
196 if (NumParams == FT->getNumParams() - 1)
197 return FT->getParamType(FT->getNumParams() - 1) == SizeTTy;
198 return true;
199}
200
Meador Inged589ac62012-10-31 03:33:06 +0000201//===----------------------------------------------------------------------===//
Meador Inge7fb2f732012-10-13 16:45:32 +0000202// String and Memory Library Call Optimizations
203//===----------------------------------------------------------------------===//
204
Chris Bienemanad070d02014-09-17 20:55:46 +0000205Value *LibCallSimplifier::optimizeStrCat(CallInst *CI, IRBuilder<> &B) {
206 Function *Callee = CI->getCalledFunction();
207 // Verify the "strcat" function prototype.
208 FunctionType *FT = Callee->getFunctionType();
209 if (FT->getNumParams() != 2||
210 FT->getReturnType() != B.getInt8PtrTy() ||
211 FT->getParamType(0) != FT->getReturnType() ||
212 FT->getParamType(1) != FT->getReturnType())
213 return nullptr;
214
215 // Extract some information from the instruction
216 Value *Dst = CI->getArgOperand(0);
217 Value *Src = CI->getArgOperand(1);
218
219 // See if we can get the length of the input string.
220 uint64_t Len = GetStringLength(Src);
221 if (Len == 0)
222 return nullptr;
223 --Len; // Unbias length.
224
225 // Handle the simple, do-nothing case: strcat(x, "") -> x
226 if (Len == 0)
227 return Dst;
228
Chris Bienemanad070d02014-09-17 20:55:46 +0000229 return emitStrLenMemCpy(Src, Dst, Len, B);
230}
231
232Value *LibCallSimplifier::emitStrLenMemCpy(Value *Src, Value *Dst, uint64_t Len,
233 IRBuilder<> &B) {
234 // We need to find the end of the destination string. That's where the
235 // memory is to be moved to. We just generate a call to strlen.
236 Value *DstLen = EmitStrLen(Dst, B, DL, TLI);
237 if (!DstLen)
238 return nullptr;
239
240 // Now that we have the destination's length, we must index into the
241 // destination's pointer to get the actual memcpy destination (end of
242 // the string .. we're concatenating).
David Blaikie3909da72015-03-30 20:42:56 +0000243 Value *CpyDst = B.CreateGEP(B.getInt8Ty(), Dst, DstLen, "endptr");
Chris Bienemanad070d02014-09-17 20:55:46 +0000244
245 // We have enough information to now generate the memcpy call to do the
246 // concatenation for us. Make a memcpy to copy the nul byte with align = 1.
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000247 B.CreateMemCpy(CpyDst, Src,
248 ConstantInt::get(DL.getIntPtrType(Src->getContext()), Len + 1),
249 1);
Chris Bienemanad070d02014-09-17 20:55:46 +0000250 return Dst;
251}
252
253Value *LibCallSimplifier::optimizeStrNCat(CallInst *CI, IRBuilder<> &B) {
254 Function *Callee = CI->getCalledFunction();
255 // Verify the "strncat" function prototype.
256 FunctionType *FT = Callee->getFunctionType();
257 if (FT->getNumParams() != 3 || FT->getReturnType() != B.getInt8PtrTy() ||
258 FT->getParamType(0) != FT->getReturnType() ||
259 FT->getParamType(1) != FT->getReturnType() ||
260 !FT->getParamType(2)->isIntegerTy())
261 return nullptr;
262
263 // Extract some information from the instruction
264 Value *Dst = CI->getArgOperand(0);
265 Value *Src = CI->getArgOperand(1);
266 uint64_t Len;
267
268 // We don't do anything if length is not constant
269 if (ConstantInt *LengthArg = dyn_cast<ConstantInt>(CI->getArgOperand(2)))
270 Len = LengthArg->getZExtValue();
271 else
272 return nullptr;
273
274 // See if we can get the length of the input string.
275 uint64_t SrcLen = GetStringLength(Src);
276 if (SrcLen == 0)
277 return nullptr;
278 --SrcLen; // Unbias length.
279
280 // Handle the simple, do-nothing cases:
281 // strncat(x, "", c) -> x
282 // strncat(x, c, 0) -> x
283 if (SrcLen == 0 || Len == 0)
284 return Dst;
285
Chris Bienemanad070d02014-09-17 20:55:46 +0000286 // We don't optimize this case
287 if (Len < SrcLen)
288 return nullptr;
289
290 // strncat(x, s, c) -> strcat(x, s)
291 // s is constant so the strcat can be optimized further
292 return emitStrLenMemCpy(Src, Dst, SrcLen, B);
293}
294
295Value *LibCallSimplifier::optimizeStrChr(CallInst *CI, IRBuilder<> &B) {
296 Function *Callee = CI->getCalledFunction();
297 // Verify the "strchr" function prototype.
298 FunctionType *FT = Callee->getFunctionType();
299 if (FT->getNumParams() != 2 || FT->getReturnType() != B.getInt8PtrTy() ||
300 FT->getParamType(0) != FT->getReturnType() ||
301 !FT->getParamType(1)->isIntegerTy(32))
302 return nullptr;
303
304 Value *SrcStr = CI->getArgOperand(0);
305
306 // If the second operand is non-constant, see if we can compute the length
307 // of the input string and turn this into memchr.
308 ConstantInt *CharC = dyn_cast<ConstantInt>(CI->getArgOperand(1));
309 if (!CharC) {
Chris Bienemanad070d02014-09-17 20:55:46 +0000310 uint64_t Len = GetStringLength(SrcStr);
311 if (Len == 0 || !FT->getParamType(1)->isIntegerTy(32)) // memchr needs i32.
312 return nullptr;
Meador Inge7fb2f732012-10-13 16:45:32 +0000313
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000314 return EmitMemChr(SrcStr, CI->getArgOperand(1), // include nul.
315 ConstantInt::get(DL.getIntPtrType(CI->getContext()), Len),
316 B, DL, TLI);
Meador Inge7fb2f732012-10-13 16:45:32 +0000317 }
318
Chris Bienemanad070d02014-09-17 20:55:46 +0000319 // Otherwise, the character is a constant, see if the first argument is
320 // a string literal. If so, we can constant fold.
321 StringRef Str;
322 if (!getConstantStringInfo(SrcStr, Str)) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000323 if (CharC->isZero()) // strchr(p, 0) -> p + strlen(p)
David Blaikie3909da72015-03-30 20:42:56 +0000324 return B.CreateGEP(B.getInt8Ty(), SrcStr, EmitStrLen(SrcStr, B, DL, TLI), "strchr");
Chris Bienemanad070d02014-09-17 20:55:46 +0000325 return nullptr;
326 }
327
328 // Compute the offset, make sure to handle the case when we're searching for
329 // zero (a weird way to spell strlen).
330 size_t I = (0xFF & CharC->getSExtValue()) == 0
331 ? Str.size()
332 : Str.find(CharC->getSExtValue());
333 if (I == StringRef::npos) // Didn't find the char. strchr returns null.
334 return Constant::getNullValue(CI->getType());
335
336 // strchr(s+n,c) -> gep(s+n+i,c)
David Blaikie3909da72015-03-30 20:42:56 +0000337 return B.CreateGEP(B.getInt8Ty(), SrcStr, B.getInt64(I), "strchr");
Chris Bienemanad070d02014-09-17 20:55:46 +0000338}
339
340Value *LibCallSimplifier::optimizeStrRChr(CallInst *CI, IRBuilder<> &B) {
341 Function *Callee = CI->getCalledFunction();
342 // Verify the "strrchr" function prototype.
343 FunctionType *FT = Callee->getFunctionType();
344 if (FT->getNumParams() != 2 || FT->getReturnType() != B.getInt8PtrTy() ||
345 FT->getParamType(0) != FT->getReturnType() ||
346 !FT->getParamType(1)->isIntegerTy(32))
347 return nullptr;
348
349 Value *SrcStr = CI->getArgOperand(0);
350 ConstantInt *CharC = dyn_cast<ConstantInt>(CI->getArgOperand(1));
351
352 // Cannot fold anything if we're not looking for a constant.
353 if (!CharC)
354 return nullptr;
355
356 StringRef Str;
357 if (!getConstantStringInfo(SrcStr, Str)) {
358 // strrchr(s, 0) -> strchr(s, 0)
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000359 if (CharC->isZero())
360 return EmitStrChr(SrcStr, '\0', B, TLI);
Chris Bienemanad070d02014-09-17 20:55:46 +0000361 return nullptr;
362 }
363
364 // Compute the offset.
365 size_t I = (0xFF & CharC->getSExtValue()) == 0
366 ? Str.size()
367 : Str.rfind(CharC->getSExtValue());
368 if (I == StringRef::npos) // Didn't find the char. Return null.
369 return Constant::getNullValue(CI->getType());
370
371 // strrchr(s+n,c) -> gep(s+n+i,c)
David Blaikie3909da72015-03-30 20:42:56 +0000372 return B.CreateGEP(B.getInt8Ty(), SrcStr, B.getInt64(I), "strrchr");
Chris Bienemanad070d02014-09-17 20:55:46 +0000373}
374
375Value *LibCallSimplifier::optimizeStrCmp(CallInst *CI, IRBuilder<> &B) {
376 Function *Callee = CI->getCalledFunction();
377 // Verify the "strcmp" function prototype.
378 FunctionType *FT = Callee->getFunctionType();
379 if (FT->getNumParams() != 2 || !FT->getReturnType()->isIntegerTy(32) ||
380 FT->getParamType(0) != FT->getParamType(1) ||
381 FT->getParamType(0) != B.getInt8PtrTy())
382 return nullptr;
383
384 Value *Str1P = CI->getArgOperand(0), *Str2P = CI->getArgOperand(1);
385 if (Str1P == Str2P) // strcmp(x,x) -> 0
386 return ConstantInt::get(CI->getType(), 0);
387
388 StringRef Str1, Str2;
389 bool HasStr1 = getConstantStringInfo(Str1P, Str1);
390 bool HasStr2 = getConstantStringInfo(Str2P, Str2);
391
392 // strcmp(x, y) -> cnst (if both x and y are constant strings)
393 if (HasStr1 && HasStr2)
394 return ConstantInt::get(CI->getType(), Str1.compare(Str2));
395
396 if (HasStr1 && Str1.empty()) // strcmp("", x) -> -*x
397 return B.CreateNeg(
398 B.CreateZExt(B.CreateLoad(Str2P, "strcmpload"), CI->getType()));
399
400 if (HasStr2 && Str2.empty()) // strcmp(x,"") -> *x
401 return B.CreateZExt(B.CreateLoad(Str1P, "strcmpload"), CI->getType());
402
403 // strcmp(P, "x") -> memcmp(P, "x", 2)
404 uint64_t Len1 = GetStringLength(Str1P);
405 uint64_t Len2 = GetStringLength(Str2P);
406 if (Len1 && Len2) {
Chris Bienemanad070d02014-09-17 20:55:46 +0000407 return EmitMemCmp(Str1P, Str2P,
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000408 ConstantInt::get(DL.getIntPtrType(CI->getContext()),
Chris Bienemanad070d02014-09-17 20:55:46 +0000409 std::min(Len1, Len2)),
410 B, DL, TLI);
411 }
Meador Inge7fb2f732012-10-13 16:45:32 +0000412
Chris Bienemanad070d02014-09-17 20:55:46 +0000413 return nullptr;
414}
415
416Value *LibCallSimplifier::optimizeStrNCmp(CallInst *CI, IRBuilder<> &B) {
417 Function *Callee = CI->getCalledFunction();
418 // Verify the "strncmp" function prototype.
419 FunctionType *FT = Callee->getFunctionType();
420 if (FT->getNumParams() != 3 || !FT->getReturnType()->isIntegerTy(32) ||
421 FT->getParamType(0) != FT->getParamType(1) ||
422 FT->getParamType(0) != B.getInt8PtrTy() ||
423 !FT->getParamType(2)->isIntegerTy())
424 return nullptr;
425
426 Value *Str1P = CI->getArgOperand(0), *Str2P = CI->getArgOperand(1);
427 if (Str1P == Str2P) // strncmp(x,x,n) -> 0
428 return ConstantInt::get(CI->getType(), 0);
429
430 // Get the length argument if it is constant.
431 uint64_t Length;
432 if (ConstantInt *LengthArg = dyn_cast<ConstantInt>(CI->getArgOperand(2)))
433 Length = LengthArg->getZExtValue();
434 else
435 return nullptr;
436
437 if (Length == 0) // strncmp(x,y,0) -> 0
438 return ConstantInt::get(CI->getType(), 0);
439
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000440 if (Length == 1) // strncmp(x,y,1) -> memcmp(x,y,1)
Chris Bienemanad070d02014-09-17 20:55:46 +0000441 return EmitMemCmp(Str1P, Str2P, CI->getArgOperand(2), B, DL, TLI);
442
443 StringRef Str1, Str2;
444 bool HasStr1 = getConstantStringInfo(Str1P, Str1);
445 bool HasStr2 = getConstantStringInfo(Str2P, Str2);
446
447 // strncmp(x, y) -> cnst (if both x and y are constant strings)
448 if (HasStr1 && HasStr2) {
449 StringRef SubStr1 = Str1.substr(0, Length);
450 StringRef SubStr2 = Str2.substr(0, Length);
451 return ConstantInt::get(CI->getType(), SubStr1.compare(SubStr2));
452 }
453
454 if (HasStr1 && Str1.empty()) // strncmp("", x, n) -> -*x
455 return B.CreateNeg(
456 B.CreateZExt(B.CreateLoad(Str2P, "strcmpload"), CI->getType()));
457
458 if (HasStr2 && Str2.empty()) // strncmp(x, "", n) -> *x
459 return B.CreateZExt(B.CreateLoad(Str1P, "strcmpload"), CI->getType());
460
461 return nullptr;
462}
463
464Value *LibCallSimplifier::optimizeStrCpy(CallInst *CI, IRBuilder<> &B) {
465 Function *Callee = CI->getCalledFunction();
Ahmed Bougachab7d8afb2015-01-12 17:18:19 +0000466
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000467 if (!checkStringCopyLibFuncSignature(Callee, LibFunc::strcpy))
Chris Bienemanad070d02014-09-17 20:55:46 +0000468 return nullptr;
469
470 Value *Dst = CI->getArgOperand(0), *Src = CI->getArgOperand(1);
471 if (Dst == Src) // strcpy(x,x) -> x
472 return Src;
473
Chris Bienemanad070d02014-09-17 20:55:46 +0000474 // See if we can get the length of the input string.
475 uint64_t Len = GetStringLength(Src);
476 if (Len == 0)
477 return nullptr;
478
479 // We have enough information to now generate the memcpy call to do the
480 // copy for us. Make a memcpy to copy the nul byte with align = 1.
481 B.CreateMemCpy(Dst, Src,
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000482 ConstantInt::get(DL.getIntPtrType(CI->getContext()), Len), 1);
Chris Bienemanad070d02014-09-17 20:55:46 +0000483 return Dst;
484}
485
486Value *LibCallSimplifier::optimizeStpCpy(CallInst *CI, IRBuilder<> &B) {
487 Function *Callee = CI->getCalledFunction();
488 // Verify the "stpcpy" function prototype.
489 FunctionType *FT = Callee->getFunctionType();
Ahmed Bougachab7d8afb2015-01-12 17:18:19 +0000490
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000491 if (!checkStringCopyLibFuncSignature(Callee, LibFunc::stpcpy))
Chris Bienemanad070d02014-09-17 20:55:46 +0000492 return nullptr;
493
494 Value *Dst = CI->getArgOperand(0), *Src = CI->getArgOperand(1);
495 if (Dst == Src) { // stpcpy(x,x) -> x+strlen(x)
496 Value *StrLen = EmitStrLen(Src, B, DL, TLI);
David Blaikieaa41cd52015-04-03 21:33:42 +0000497 return StrLen ? B.CreateInBoundsGEP(B.getInt8Ty(), Dst, StrLen) : nullptr;
Chris Bienemanad070d02014-09-17 20:55:46 +0000498 }
499
500 // See if we can get the length of the input string.
501 uint64_t Len = GetStringLength(Src);
502 if (Len == 0)
503 return nullptr;
504
505 Type *PT = FT->getParamType(0);
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000506 Value *LenV = ConstantInt::get(DL.getIntPtrType(PT), Len);
Chris Bienemanad070d02014-09-17 20:55:46 +0000507 Value *DstEnd =
David Blaikie3909da72015-03-30 20:42:56 +0000508 B.CreateGEP(B.getInt8Ty(), Dst, ConstantInt::get(DL.getIntPtrType(PT), Len - 1));
Chris Bienemanad070d02014-09-17 20:55:46 +0000509
510 // We have enough information to now generate the memcpy call to do the
511 // copy for us. Make a memcpy to copy the nul byte with align = 1.
512 B.CreateMemCpy(Dst, Src, LenV, 1);
513 return DstEnd;
514}
515
516Value *LibCallSimplifier::optimizeStrNCpy(CallInst *CI, IRBuilder<> &B) {
517 Function *Callee = CI->getCalledFunction();
518 FunctionType *FT = Callee->getFunctionType();
Ahmed Bougachab7d8afb2015-01-12 17:18:19 +0000519
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000520 if (!checkStringCopyLibFuncSignature(Callee, LibFunc::strncpy))
Chris Bienemanad070d02014-09-17 20:55:46 +0000521 return nullptr;
522
523 Value *Dst = CI->getArgOperand(0);
524 Value *Src = CI->getArgOperand(1);
525 Value *LenOp = CI->getArgOperand(2);
526
527 // See if we can get the length of the input string.
528 uint64_t SrcLen = GetStringLength(Src);
529 if (SrcLen == 0)
530 return nullptr;
531 --SrcLen;
532
533 if (SrcLen == 0) {
534 // strncpy(x, "", y) -> memset(x, '\0', y, 1)
535 B.CreateMemSet(Dst, B.getInt8('\0'), LenOp, 1);
Meador Inge7fb2f732012-10-13 16:45:32 +0000536 return Dst;
537 }
Meador Inge7fb2f732012-10-13 16:45:32 +0000538
Chris Bienemanad070d02014-09-17 20:55:46 +0000539 uint64_t Len;
540 if (ConstantInt *LengthArg = dyn_cast<ConstantInt>(LenOp))
541 Len = LengthArg->getZExtValue();
542 else
543 return nullptr;
Meador Inge7fb2f732012-10-13 16:45:32 +0000544
Chris Bienemanad070d02014-09-17 20:55:46 +0000545 if (Len == 0)
546 return Dst; // strncpy(x, y, 0) -> x
Meador Inge7fb2f732012-10-13 16:45:32 +0000547
Chris Bienemanad070d02014-09-17 20:55:46 +0000548 // Let strncpy handle the zero padding
549 if (Len > SrcLen + 1)
550 return nullptr;
Meador Inge7fb2f732012-10-13 16:45:32 +0000551
Chris Bienemanad070d02014-09-17 20:55:46 +0000552 Type *PT = FT->getParamType(0);
553 // strncpy(x, s, c) -> memcpy(x, s, c, 1) [s and c are constant]
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000554 B.CreateMemCpy(Dst, Src, ConstantInt::get(DL.getIntPtrType(PT), Len), 1);
Meador Inge7fb2f732012-10-13 16:45:32 +0000555
Chris Bienemanad070d02014-09-17 20:55:46 +0000556 return Dst;
557}
Meador Inge7fb2f732012-10-13 16:45:32 +0000558
Chris Bienemanad070d02014-09-17 20:55:46 +0000559Value *LibCallSimplifier::optimizeStrLen(CallInst *CI, IRBuilder<> &B) {
560 Function *Callee = CI->getCalledFunction();
561 FunctionType *FT = Callee->getFunctionType();
562 if (FT->getNumParams() != 1 || FT->getParamType(0) != B.getInt8PtrTy() ||
563 !FT->getReturnType()->isIntegerTy())
564 return nullptr;
Meador Inge7fb2f732012-10-13 16:45:32 +0000565
Chris Bienemanad070d02014-09-17 20:55:46 +0000566 Value *Src = CI->getArgOperand(0);
567
568 // Constant folding: strlen("xyz") -> 3
569 if (uint64_t Len = GetStringLength(Src))
570 return ConstantInt::get(CI->getType(), Len - 1);
571
572 // strlen(x?"foo":"bars") --> x ? 3 : 4
573 if (SelectInst *SI = dyn_cast<SelectInst>(Src)) {
574 uint64_t LenTrue = GetStringLength(SI->getTrueValue());
575 uint64_t LenFalse = GetStringLength(SI->getFalseValue());
576 if (LenTrue && LenFalse) {
577 Function *Caller = CI->getParent()->getParent();
578 emitOptimizationRemark(CI->getContext(), "simplify-libcalls", *Caller,
579 SI->getDebugLoc(),
580 "folded strlen(select) to select of constants");
581 return B.CreateSelect(SI->getCondition(),
582 ConstantInt::get(CI->getType(), LenTrue - 1),
583 ConstantInt::get(CI->getType(), LenFalse - 1));
584 }
Meador Inge7fb2f732012-10-13 16:45:32 +0000585 }
Meador Inge7fb2f732012-10-13 16:45:32 +0000586
Chris Bienemanad070d02014-09-17 20:55:46 +0000587 // strlen(x) != 0 --> *x != 0
588 // strlen(x) == 0 --> *x == 0
589 if (isOnlyUsedInZeroEqualityComparison(CI))
590 return B.CreateZExt(B.CreateLoad(Src, "strlenfirst"), CI->getType());
Meador Inge17418502012-10-13 16:45:37 +0000591
Chris Bienemanad070d02014-09-17 20:55:46 +0000592 return nullptr;
593}
Meador Inge17418502012-10-13 16:45:37 +0000594
Chris Bienemanad070d02014-09-17 20:55:46 +0000595Value *LibCallSimplifier::optimizeStrPBrk(CallInst *CI, IRBuilder<> &B) {
596 Function *Callee = CI->getCalledFunction();
597 FunctionType *FT = Callee->getFunctionType();
598 if (FT->getNumParams() != 2 || FT->getParamType(0) != B.getInt8PtrTy() ||
599 FT->getParamType(1) != FT->getParamType(0) ||
600 FT->getReturnType() != FT->getParamType(0))
601 return nullptr;
Meador Inge17418502012-10-13 16:45:37 +0000602
Chris Bienemanad070d02014-09-17 20:55:46 +0000603 StringRef S1, S2;
604 bool HasS1 = getConstantStringInfo(CI->getArgOperand(0), S1);
605 bool HasS2 = getConstantStringInfo(CI->getArgOperand(1), S2);
Meador Inge17418502012-10-13 16:45:37 +0000606
Reid Kleckner971c3ea2014-11-13 22:55:19 +0000607 // strpbrk(s, "") -> nullptr
608 // strpbrk("", s) -> nullptr
Chris Bienemanad070d02014-09-17 20:55:46 +0000609 if ((HasS1 && S1.empty()) || (HasS2 && S2.empty()))
610 return Constant::getNullValue(CI->getType());
Meador Inge17418502012-10-13 16:45:37 +0000611
Chris Bienemanad070d02014-09-17 20:55:46 +0000612 // Constant folding.
613 if (HasS1 && HasS2) {
614 size_t I = S1.find_first_of(S2);
615 if (I == StringRef::npos) // No match.
Meador Inge17418502012-10-13 16:45:37 +0000616 return Constant::getNullValue(CI->getType());
617
David Blaikie3909da72015-03-30 20:42:56 +0000618 return B.CreateGEP(B.getInt8Ty(), CI->getArgOperand(0), B.getInt64(I), "strpbrk");
Meador Inge17418502012-10-13 16:45:37 +0000619 }
Meador Inge17418502012-10-13 16:45:37 +0000620
Chris Bienemanad070d02014-09-17 20:55:46 +0000621 // strpbrk(s, "a") -> strchr(s, 'a')
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000622 if (HasS2 && S2.size() == 1)
623 return EmitStrChr(CI->getArgOperand(0), S2[0], B, TLI);
Chris Bienemanad070d02014-09-17 20:55:46 +0000624
625 return nullptr;
626}
627
628Value *LibCallSimplifier::optimizeStrTo(CallInst *CI, IRBuilder<> &B) {
629 Function *Callee = CI->getCalledFunction();
630 FunctionType *FT = Callee->getFunctionType();
631 if ((FT->getNumParams() != 2 && FT->getNumParams() != 3) ||
632 !FT->getParamType(0)->isPointerTy() ||
633 !FT->getParamType(1)->isPointerTy())
634 return nullptr;
635
636 Value *EndPtr = CI->getArgOperand(1);
637 if (isa<ConstantPointerNull>(EndPtr)) {
638 // With a null EndPtr, this function won't capture the main argument.
639 // It would be readonly too, except that it still may write to errno.
640 CI->addAttribute(1, Attribute::NoCapture);
641 }
642
643 return nullptr;
644}
645
646Value *LibCallSimplifier::optimizeStrSpn(CallInst *CI, IRBuilder<> &B) {
647 Function *Callee = CI->getCalledFunction();
648 FunctionType *FT = Callee->getFunctionType();
649 if (FT->getNumParams() != 2 || FT->getParamType(0) != B.getInt8PtrTy() ||
650 FT->getParamType(1) != FT->getParamType(0) ||
651 !FT->getReturnType()->isIntegerTy())
652 return nullptr;
653
654 StringRef S1, S2;
655 bool HasS1 = getConstantStringInfo(CI->getArgOperand(0), S1);
656 bool HasS2 = getConstantStringInfo(CI->getArgOperand(1), S2);
657
658 // strspn(s, "") -> 0
659 // strspn("", s) -> 0
660 if ((HasS1 && S1.empty()) || (HasS2 && S2.empty()))
661 return Constant::getNullValue(CI->getType());
662
663 // Constant folding.
664 if (HasS1 && HasS2) {
665 size_t Pos = S1.find_first_not_of(S2);
666 if (Pos == StringRef::npos)
667 Pos = S1.size();
668 return ConstantInt::get(CI->getType(), Pos);
669 }
670
671 return nullptr;
672}
673
674Value *LibCallSimplifier::optimizeStrCSpn(CallInst *CI, IRBuilder<> &B) {
675 Function *Callee = CI->getCalledFunction();
676 FunctionType *FT = Callee->getFunctionType();
677 if (FT->getNumParams() != 2 || FT->getParamType(0) != B.getInt8PtrTy() ||
678 FT->getParamType(1) != FT->getParamType(0) ||
679 !FT->getReturnType()->isIntegerTy())
680 return nullptr;
681
682 StringRef S1, S2;
683 bool HasS1 = getConstantStringInfo(CI->getArgOperand(0), S1);
684 bool HasS2 = getConstantStringInfo(CI->getArgOperand(1), S2);
685
686 // strcspn("", s) -> 0
687 if (HasS1 && S1.empty())
688 return Constant::getNullValue(CI->getType());
689
690 // Constant folding.
691 if (HasS1 && HasS2) {
692 size_t Pos = S1.find_first_of(S2);
693 if (Pos == StringRef::npos)
694 Pos = S1.size();
695 return ConstantInt::get(CI->getType(), Pos);
696 }
697
698 // strcspn(s, "") -> strlen(s)
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000699 if (HasS2 && S2.empty())
Chris Bienemanad070d02014-09-17 20:55:46 +0000700 return EmitStrLen(CI->getArgOperand(0), B, DL, TLI);
701
702 return nullptr;
703}
704
705Value *LibCallSimplifier::optimizeStrStr(CallInst *CI, IRBuilder<> &B) {
706 Function *Callee = CI->getCalledFunction();
707 FunctionType *FT = Callee->getFunctionType();
708 if (FT->getNumParams() != 2 || !FT->getParamType(0)->isPointerTy() ||
709 !FT->getParamType(1)->isPointerTy() ||
710 !FT->getReturnType()->isPointerTy())
711 return nullptr;
712
713 // fold strstr(x, x) -> x.
714 if (CI->getArgOperand(0) == CI->getArgOperand(1))
715 return B.CreateBitCast(CI->getArgOperand(0), CI->getType());
716
717 // fold strstr(a, b) == a -> strncmp(a, b, strlen(b)) == 0
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000718 if (isOnlyUsedInEqualityComparison(CI, CI->getArgOperand(0))) {
Chris Bienemanad070d02014-09-17 20:55:46 +0000719 Value *StrLen = EmitStrLen(CI->getArgOperand(1), B, DL, TLI);
720 if (!StrLen)
Craig Topperf40110f2014-04-25 05:29:35 +0000721 return nullptr;
Chris Bienemanad070d02014-09-17 20:55:46 +0000722 Value *StrNCmp = EmitStrNCmp(CI->getArgOperand(0), CI->getArgOperand(1),
723 StrLen, B, DL, TLI);
724 if (!StrNCmp)
Craig Topperf40110f2014-04-25 05:29:35 +0000725 return nullptr;
Chris Bienemanad070d02014-09-17 20:55:46 +0000726 for (auto UI = CI->user_begin(), UE = CI->user_end(); UI != UE;) {
727 ICmpInst *Old = cast<ICmpInst>(*UI++);
728 Value *Cmp =
729 B.CreateICmp(Old->getPredicate(), StrNCmp,
730 ConstantInt::getNullValue(StrNCmp->getType()), "cmp");
731 replaceAllUsesWith(Old, Cmp);
Meador Inge17418502012-10-13 16:45:37 +0000732 }
Chris Bienemanad070d02014-09-17 20:55:46 +0000733 return CI;
734 }
Meador Inge17418502012-10-13 16:45:37 +0000735
Chris Bienemanad070d02014-09-17 20:55:46 +0000736 // See if either input string is a constant string.
737 StringRef SearchStr, ToFindStr;
738 bool HasStr1 = getConstantStringInfo(CI->getArgOperand(0), SearchStr);
739 bool HasStr2 = getConstantStringInfo(CI->getArgOperand(1), ToFindStr);
740
741 // fold strstr(x, "") -> x.
742 if (HasStr2 && ToFindStr.empty())
743 return B.CreateBitCast(CI->getArgOperand(0), CI->getType());
744
745 // If both strings are known, constant fold it.
746 if (HasStr1 && HasStr2) {
747 size_t Offset = SearchStr.find(ToFindStr);
748
749 if (Offset == StringRef::npos) // strstr("foo", "bar") -> null
Meador Inge17418502012-10-13 16:45:37 +0000750 return Constant::getNullValue(CI->getType());
751
Chris Bienemanad070d02014-09-17 20:55:46 +0000752 // strstr("abcd", "bc") -> gep((char*)"abcd", 1)
753 Value *Result = CastToCStr(CI->getArgOperand(0), B);
754 Result = B.CreateConstInBoundsGEP1_64(Result, Offset, "strstr");
755 return B.CreateBitCast(Result, CI->getType());
Meador Inge17418502012-10-13 16:45:37 +0000756 }
Meador Inge17418502012-10-13 16:45:37 +0000757
Chris Bienemanad070d02014-09-17 20:55:46 +0000758 // fold strstr(x, "y") -> strchr(x, 'y').
759 if (HasStr2 && ToFindStr.size() == 1) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000760 Value *StrChr = EmitStrChr(CI->getArgOperand(0), ToFindStr[0], B, TLI);
Chris Bienemanad070d02014-09-17 20:55:46 +0000761 return StrChr ? B.CreateBitCast(StrChr, CI->getType()) : nullptr;
762 }
763 return nullptr;
764}
Meador Inge40b6fac2012-10-15 03:47:37 +0000765
Benjamin Kramer691363e2015-03-21 15:36:21 +0000766Value *LibCallSimplifier::optimizeMemChr(CallInst *CI, IRBuilder<> &B) {
767 Function *Callee = CI->getCalledFunction();
768 FunctionType *FT = Callee->getFunctionType();
769 if (FT->getNumParams() != 3 || !FT->getParamType(0)->isPointerTy() ||
770 !FT->getParamType(1)->isIntegerTy(32) ||
771 !FT->getParamType(2)->isIntegerTy() ||
772 !FT->getReturnType()->isPointerTy())
773 return nullptr;
774
775 Value *SrcStr = CI->getArgOperand(0);
776 ConstantInt *CharC = dyn_cast<ConstantInt>(CI->getArgOperand(1));
777 ConstantInt *LenC = dyn_cast<ConstantInt>(CI->getArgOperand(2));
778
779 // memchr(x, y, 0) -> null
780 if (LenC && LenC->isNullValue())
781 return Constant::getNullValue(CI->getType());
782
Benjamin Kramer7857d722015-03-21 21:09:33 +0000783 // From now on we need at least constant length and string.
Benjamin Kramer691363e2015-03-21 15:36:21 +0000784 StringRef Str;
Benjamin Kramer7857d722015-03-21 21:09:33 +0000785 if (!LenC || !getConstantStringInfo(SrcStr, Str, 0, /*TrimAtNul=*/false))
Benjamin Kramer691363e2015-03-21 15:36:21 +0000786 return nullptr;
787
788 // Truncate the string to LenC. If Str is smaller than LenC we will still only
789 // scan the string, as reading past the end of it is undefined and we can just
790 // return null if we don't find the char.
791 Str = Str.substr(0, LenC->getZExtValue());
792
Benjamin Kramer7857d722015-03-21 21:09:33 +0000793 // If the char is variable but the input str and length are not we can turn
794 // this memchr call into a simple bit field test. Of course this only works
795 // when the return value is only checked against null.
796 //
797 // It would be really nice to reuse switch lowering here but we can't change
798 // the CFG at this point.
799 //
800 // memchr("\r\n", C, 2) != nullptr -> (C & ((1 << '\r') | (1 << '\n'))) != 0
801 // after bounds check.
802 if (!CharC && !Str.empty() && isOnlyUsedInZeroEqualityComparison(CI)) {
Benjamin Kramerd6aa0ec2015-03-21 22:04:26 +0000803 unsigned char Max =
804 *std::max_element(reinterpret_cast<const unsigned char *>(Str.begin()),
805 reinterpret_cast<const unsigned char *>(Str.end()));
Benjamin Kramer7857d722015-03-21 21:09:33 +0000806
807 // Make sure the bit field we're about to create fits in a register on the
808 // target.
809 // FIXME: On a 64 bit architecture this prevents us from using the
810 // interesting range of alpha ascii chars. We could do better by emitting
811 // two bitfields or shifting the range by 64 if no lower chars are used.
812 if (!DL.fitsInLegalInteger(Max + 1))
813 return nullptr;
814
815 // For the bit field use a power-of-2 type with at least 8 bits to avoid
816 // creating unnecessary illegal types.
817 unsigned char Width = NextPowerOf2(std::max((unsigned char)7, Max));
818
819 // Now build the bit field.
820 APInt Bitfield(Width, 0);
821 for (char C : Str)
822 Bitfield.setBit((unsigned char)C);
823 Value *BitfieldC = B.getInt(Bitfield);
824
825 // First check that the bit field access is within bounds.
826 Value *C = B.CreateZExtOrTrunc(CI->getArgOperand(1), BitfieldC->getType());
827 Value *Bounds = B.CreateICmp(ICmpInst::ICMP_ULT, C, B.getIntN(Width, Width),
828 "memchr.bounds");
829
830 // Create code that checks if the given bit is set in the field.
831 Value *Shl = B.CreateShl(B.getIntN(Width, 1ULL), C);
832 Value *Bits = B.CreateIsNotNull(B.CreateAnd(Shl, BitfieldC), "memchr.bits");
833
834 // Finally merge both checks and cast to pointer type. The inttoptr
835 // implicitly zexts the i1 to intptr type.
836 return B.CreateIntToPtr(B.CreateAnd(Bounds, Bits, "memchr"), CI->getType());
837 }
838
839 // Check if all arguments are constants. If so, we can constant fold.
840 if (!CharC)
841 return nullptr;
842
Benjamin Kramer691363e2015-03-21 15:36:21 +0000843 // Compute the offset.
844 size_t I = Str.find(CharC->getSExtValue() & 0xFF);
845 if (I == StringRef::npos) // Didn't find the char. memchr returns null.
846 return Constant::getNullValue(CI->getType());
847
848 // memchr(s+n,c,l) -> gep(s+n+i,c)
David Blaikie3909da72015-03-30 20:42:56 +0000849 return B.CreateGEP(B.getInt8Ty(), SrcStr, B.getInt64(I), "memchr");
Benjamin Kramer691363e2015-03-21 15:36:21 +0000850}
851
Chris Bienemanad070d02014-09-17 20:55:46 +0000852Value *LibCallSimplifier::optimizeMemCmp(CallInst *CI, IRBuilder<> &B) {
853 Function *Callee = CI->getCalledFunction();
854 FunctionType *FT = Callee->getFunctionType();
855 if (FT->getNumParams() != 3 || !FT->getParamType(0)->isPointerTy() ||
856 !FT->getParamType(1)->isPointerTy() ||
857 !FT->getReturnType()->isIntegerTy(32))
Craig Topperf40110f2014-04-25 05:29:35 +0000858 return nullptr;
Meador Inge40b6fac2012-10-15 03:47:37 +0000859
Chris Bienemanad070d02014-09-17 20:55:46 +0000860 Value *LHS = CI->getArgOperand(0), *RHS = CI->getArgOperand(1);
Meador Inge40b6fac2012-10-15 03:47:37 +0000861
Chris Bienemanad070d02014-09-17 20:55:46 +0000862 if (LHS == RHS) // memcmp(s,s,x) -> 0
863 return Constant::getNullValue(CI->getType());
Meador Inge40b6fac2012-10-15 03:47:37 +0000864
Chris Bienemanad070d02014-09-17 20:55:46 +0000865 // Make sure we have a constant length.
866 ConstantInt *LenC = dyn_cast<ConstantInt>(CI->getArgOperand(2));
867 if (!LenC)
Craig Topperf40110f2014-04-25 05:29:35 +0000868 return nullptr;
Chris Bienemanad070d02014-09-17 20:55:46 +0000869 uint64_t Len = LenC->getZExtValue();
870
871 if (Len == 0) // memcmp(s1,s2,0) -> 0
872 return Constant::getNullValue(CI->getType());
873
874 // memcmp(S1,S2,1) -> *(unsigned char*)LHS - *(unsigned char*)RHS
875 if (Len == 1) {
876 Value *LHSV = B.CreateZExt(B.CreateLoad(CastToCStr(LHS, B), "lhsc"),
877 CI->getType(), "lhsv");
878 Value *RHSV = B.CreateZExt(B.CreateLoad(CastToCStr(RHS, B), "rhsc"),
879 CI->getType(), "rhsv");
880 return B.CreateSub(LHSV, RHSV, "chardiff");
Meador Inge40b6fac2012-10-15 03:47:37 +0000881 }
Meador Inge40b6fac2012-10-15 03:47:37 +0000882
Chad Rosierdc655322015-08-28 18:30:18 +0000883 // memcmp(S1,S2,N/8)==0 -> (*(intN_t*)S1 != *(intN_t*)S2)==0
884 if (DL.isLegalInteger(Len * 8) && isOnlyUsedInZeroEqualityComparison(CI)) {
885
886 IntegerType *IntType = IntegerType::get(CI->getContext(), Len * 8);
887 unsigned PrefAlignment = DL.getPrefTypeAlignment(IntType);
888
889 if (getKnownAlignment(LHS, DL, CI) >= PrefAlignment &&
890 getKnownAlignment(RHS, DL, CI) >= PrefAlignment) {
891
892 Type *LHSPtrTy =
893 IntType->getPointerTo(LHS->getType()->getPointerAddressSpace());
894 Type *RHSPtrTy =
895 IntType->getPointerTo(RHS->getType()->getPointerAddressSpace());
896
897 Value *LHSV = B.CreateLoad(B.CreateBitCast(LHS, LHSPtrTy, "lhsc"), "lhsv");
898 Value *RHSV = B.CreateLoad(B.CreateBitCast(RHS, RHSPtrTy, "rhsc"), "rhsv");
899
900 return B.CreateZExt(B.CreateICmpNE(LHSV, RHSV), CI->getType(), "memcmp");
901 }
902 }
903
Chris Bienemanad070d02014-09-17 20:55:46 +0000904 // Constant folding: memcmp(x, y, l) -> cnst (all arguments are constant)
905 StringRef LHSStr, RHSStr;
906 if (getConstantStringInfo(LHS, LHSStr) &&
907 getConstantStringInfo(RHS, RHSStr)) {
908 // Make sure we're not reading out-of-bounds memory.
909 if (Len > LHSStr.size() || Len > RHSStr.size())
Craig Topperf40110f2014-04-25 05:29:35 +0000910 return nullptr;
Chris Bienemanad070d02014-09-17 20:55:46 +0000911 // Fold the memcmp and normalize the result. This way we get consistent
912 // results across multiple platforms.
913 uint64_t Ret = 0;
914 int Cmp = memcmp(LHSStr.data(), RHSStr.data(), Len);
915 if (Cmp < 0)
916 Ret = -1;
917 else if (Cmp > 0)
918 Ret = 1;
919 return ConstantInt::get(CI->getType(), Ret);
Meador Inge000dbcc2012-10-18 18:12:40 +0000920 }
Meador Inge000dbcc2012-10-18 18:12:40 +0000921
Chris Bienemanad070d02014-09-17 20:55:46 +0000922 return nullptr;
923}
Meador Inge9a6a1902012-10-31 00:20:56 +0000924
Chris Bienemanad070d02014-09-17 20:55:46 +0000925Value *LibCallSimplifier::optimizeMemCpy(CallInst *CI, IRBuilder<> &B) {
926 Function *Callee = CI->getCalledFunction();
Meador Inged589ac62012-10-31 03:33:06 +0000927
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000928 if (!checkStringCopyLibFuncSignature(Callee, LibFunc::memcpy))
Craig Topperf40110f2014-04-25 05:29:35 +0000929 return nullptr;
Meador Inge6f8e0112012-10-31 04:29:58 +0000930
Chris Bienemanad070d02014-09-17 20:55:46 +0000931 // memcpy(x, y, n) -> llvm.memcpy(x, y, n, 1)
932 B.CreateMemCpy(CI->getArgOperand(0), CI->getArgOperand(1),
933 CI->getArgOperand(2), 1);
934 return CI->getArgOperand(0);
935}
Meador Inge05a625a2012-10-31 14:58:26 +0000936
Chris Bienemanad070d02014-09-17 20:55:46 +0000937Value *LibCallSimplifier::optimizeMemMove(CallInst *CI, IRBuilder<> &B) {
938 Function *Callee = CI->getCalledFunction();
Meador Inge05a625a2012-10-31 14:58:26 +0000939
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000940 if (!checkStringCopyLibFuncSignature(Callee, LibFunc::memmove))
Craig Topperf40110f2014-04-25 05:29:35 +0000941 return nullptr;
Meador Inge489b5d62012-11-08 01:33:50 +0000942
Chris Bienemanad070d02014-09-17 20:55:46 +0000943 // memmove(x, y, n) -> llvm.memmove(x, y, n, 1)
944 B.CreateMemMove(CI->getArgOperand(0), CI->getArgOperand(1),
945 CI->getArgOperand(2), 1);
946 return CI->getArgOperand(0);
947}
Meador Ingebcd88ef72012-11-10 15:16:48 +0000948
Chris Bienemanad070d02014-09-17 20:55:46 +0000949Value *LibCallSimplifier::optimizeMemSet(CallInst *CI, IRBuilder<> &B) {
950 Function *Callee = CI->getCalledFunction();
Meador Ingebcd88ef72012-11-10 15:16:48 +0000951
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000952 if (!checkStringCopyLibFuncSignature(Callee, LibFunc::memset))
Craig Topperf40110f2014-04-25 05:29:35 +0000953 return nullptr;
Meador Inge56edbc92012-11-11 03:51:48 +0000954
Chris Bienemanad070d02014-09-17 20:55:46 +0000955 // memset(p, v, n) -> llvm.memset(p, v, n, 1)
956 Value *Val = B.CreateIntCast(CI->getArgOperand(1), B.getInt8Ty(), false);
957 B.CreateMemSet(CI->getArgOperand(0), Val, CI->getArgOperand(2), 1);
958 return CI->getArgOperand(0);
959}
Meador Inged4825782012-11-11 06:49:03 +0000960
Meador Inge193e0352012-11-13 04:16:17 +0000961//===----------------------------------------------------------------------===//
962// Math Library Optimizations
963//===----------------------------------------------------------------------===//
964
Matthias Braund34e4d22014-12-03 21:46:33 +0000965/// Return a variant of Val with float type.
966/// Currently this works in two cases: If Val is an FPExtension of a float
967/// value to something bigger, simply return the operand.
968/// If Val is a ConstantFP but can be converted to a float ConstantFP without
969/// loss of precision do so.
970static Value *valueHasFloatPrecision(Value *Val) {
971 if (FPExtInst *Cast = dyn_cast<FPExtInst>(Val)) {
972 Value *Op = Cast->getOperand(0);
973 if (Op->getType()->isFloatTy())
974 return Op;
975 }
976 if (ConstantFP *Const = dyn_cast<ConstantFP>(Val)) {
977 APFloat F = Const->getValueAPF();
Matthias Braun395a82f2014-12-03 22:10:39 +0000978 bool losesInfo;
Matthias Braund34e4d22014-12-03 21:46:33 +0000979 (void)F.convert(APFloat::IEEEsingle, APFloat::rmNearestTiesToEven,
Matthias Braun395a82f2014-12-03 22:10:39 +0000980 &losesInfo);
981 if (!losesInfo)
Matthias Braund34e4d22014-12-03 21:46:33 +0000982 return ConstantFP::get(Const->getContext(), F);
983 }
984 return nullptr;
985}
986
Meador Inge193e0352012-11-13 04:16:17 +0000987//===----------------------------------------------------------------------===//
988// Double -> Float Shrinking Optimizations for Unary Functions like 'floor'
989
Chris Bienemanad070d02014-09-17 20:55:46 +0000990Value *LibCallSimplifier::optimizeUnaryDoubleFP(CallInst *CI, IRBuilder<> &B,
991 bool CheckRetType) {
992 Function *Callee = CI->getCalledFunction();
993 FunctionType *FT = Callee->getFunctionType();
994 if (FT->getNumParams() != 1 || !FT->getReturnType()->isDoubleTy() ||
995 !FT->getParamType(0)->isDoubleTy())
996 return nullptr;
Meador Inge193e0352012-11-13 04:16:17 +0000997
Chris Bienemanad070d02014-09-17 20:55:46 +0000998 if (CheckRetType) {
999 // Check if all the uses for function like 'sin' are converted to float.
1000 for (User *U : CI->users()) {
1001 FPTruncInst *Cast = dyn_cast<FPTruncInst>(U);
1002 if (!Cast || !Cast->getType()->isFloatTy())
1003 return nullptr;
Meador Inge193e0352012-11-13 04:16:17 +00001004 }
Meador Inge193e0352012-11-13 04:16:17 +00001005 }
Chris Bienemanad070d02014-09-17 20:55:46 +00001006
1007 // If this is something like 'floor((double)floatval)', convert to floorf.
Matthias Braund34e4d22014-12-03 21:46:33 +00001008 Value *V = valueHasFloatPrecision(CI->getArgOperand(0));
1009 if (V == nullptr)
Chris Bienemanad070d02014-09-17 20:55:46 +00001010 return nullptr;
1011
1012 // floor((double)floatval) -> (double)floorf(floatval)
Sanjay Patel848309d2014-10-23 21:52:45 +00001013 if (Callee->isIntrinsic()) {
1014 Module *M = CI->getParent()->getParent()->getParent();
Pete Cooper9e1d3352015-05-20 17:16:39 +00001015 Intrinsic::ID IID = Callee->getIntrinsicID();
Sanjay Patel848309d2014-10-23 21:52:45 +00001016 Function *F = Intrinsic::getDeclaration(M, IID, B.getFloatTy());
1017 V = B.CreateCall(F, V);
1018 } else {
1019 // The call is a library call rather than an intrinsic.
1020 V = EmitUnaryFloatFnCall(V, Callee->getName(), B, Callee->getAttributes());
1021 }
1022
Chris Bienemanad070d02014-09-17 20:55:46 +00001023 return B.CreateFPExt(V, B.getDoubleTy());
1024}
Meador Inge193e0352012-11-13 04:16:17 +00001025
Yi Jiang6ab044e2013-12-16 22:42:40 +00001026// Double -> Float Shrinking Optimizations for Binary Functions like 'fmin/fmax'
Chris Bienemanad070d02014-09-17 20:55:46 +00001027Value *LibCallSimplifier::optimizeBinaryDoubleFP(CallInst *CI, IRBuilder<> &B) {
1028 Function *Callee = CI->getCalledFunction();
1029 FunctionType *FT = Callee->getFunctionType();
1030 // Just make sure this has 2 arguments of the same FP type, which match the
1031 // result type.
1032 if (FT->getNumParams() != 2 || FT->getReturnType() != FT->getParamType(0) ||
1033 FT->getParamType(0) != FT->getParamType(1) ||
1034 !FT->getParamType(0)->isFloatingPointTy())
Craig Topperf40110f2014-04-25 05:29:35 +00001035 return nullptr;
Meador Inge193e0352012-11-13 04:16:17 +00001036
Chris Bienemanad070d02014-09-17 20:55:46 +00001037 // If this is something like 'fmin((double)floatval1, (double)floatval2)',
Matthias Braund34e4d22014-12-03 21:46:33 +00001038 // or fmin(1.0, (double)floatval), then we convert it to fminf.
1039 Value *V1 = valueHasFloatPrecision(CI->getArgOperand(0));
1040 if (V1 == nullptr)
1041 return nullptr;
1042 Value *V2 = valueHasFloatPrecision(CI->getArgOperand(1));
1043 if (V2 == nullptr)
Craig Topperf40110f2014-04-25 05:29:35 +00001044 return nullptr;
Chris Bienemanad070d02014-09-17 20:55:46 +00001045
1046 // fmin((double)floatval1, (double)floatval2)
Matthias Braund34e4d22014-12-03 21:46:33 +00001047 // -> (double)fminf(floatval1, floatval2)
Sanjay Patel848309d2014-10-23 21:52:45 +00001048 // TODO: Handle intrinsics in the same way as in optimizeUnaryDoubleFP().
Matthias Braund34e4d22014-12-03 21:46:33 +00001049 Value *V = EmitBinaryFloatFnCall(V1, V2, Callee->getName(), B,
1050 Callee->getAttributes());
Chris Bienemanad070d02014-09-17 20:55:46 +00001051 return B.CreateFPExt(V, B.getDoubleTy());
1052}
1053
1054Value *LibCallSimplifier::optimizeCos(CallInst *CI, IRBuilder<> &B) {
1055 Function *Callee = CI->getCalledFunction();
1056 Value *Ret = nullptr;
1057 if (UnsafeFPShrink && Callee->getName() == "cos" && TLI->has(LibFunc::cosf)) {
1058 Ret = optimizeUnaryDoubleFP(CI, B, true);
Bob Wilsond8d92d92013-11-03 06:48:38 +00001059 }
1060
Chris Bienemanad070d02014-09-17 20:55:46 +00001061 FunctionType *FT = Callee->getFunctionType();
1062 // Just make sure this has 1 argument of FP type, which matches the
1063 // result type.
1064 if (FT->getNumParams() != 1 || FT->getReturnType() != FT->getParamType(0) ||
1065 !FT->getParamType(0)->isFloatingPointTy())
1066 return Ret;
Bob Wilsond8d92d92013-11-03 06:48:38 +00001067
Chris Bienemanad070d02014-09-17 20:55:46 +00001068 // cos(-x) -> cos(x)
1069 Value *Op1 = CI->getArgOperand(0);
1070 if (BinaryOperator::isFNeg(Op1)) {
1071 BinaryOperator *BinExpr = cast<BinaryOperator>(Op1);
1072 return B.CreateCall(Callee, BinExpr->getOperand(1), "cos");
1073 }
1074 return Ret;
1075}
Bob Wilsond8d92d92013-11-03 06:48:38 +00001076
Chris Bienemanad070d02014-09-17 20:55:46 +00001077Value *LibCallSimplifier::optimizePow(CallInst *CI, IRBuilder<> &B) {
1078 Function *Callee = CI->getCalledFunction();
1079
1080 Value *Ret = nullptr;
1081 if (UnsafeFPShrink && Callee->getName() == "pow" && TLI->has(LibFunc::powf)) {
1082 Ret = optimizeUnaryDoubleFP(CI, B, true);
Bob Wilsond8d92d92013-11-03 06:48:38 +00001083 }
1084
Chris Bienemanad070d02014-09-17 20:55:46 +00001085 FunctionType *FT = Callee->getFunctionType();
1086 // Just make sure this has 2 arguments of the same FP type, which match the
1087 // result type.
1088 if (FT->getNumParams() != 2 || FT->getReturnType() != FT->getParamType(0) ||
1089 FT->getParamType(0) != FT->getParamType(1) ||
1090 !FT->getParamType(0)->isFloatingPointTy())
1091 return Ret;
Bob Wilsond8d92d92013-11-03 06:48:38 +00001092
Chris Bienemanad070d02014-09-17 20:55:46 +00001093 Value *Op1 = CI->getArgOperand(0), *Op2 = CI->getArgOperand(1);
1094 if (ConstantFP *Op1C = dyn_cast<ConstantFP>(Op1)) {
1095 // pow(1.0, x) -> 1.0
1096 if (Op1C->isExactlyValue(1.0))
1097 return Op1C;
1098 // pow(2.0, x) -> exp2(x)
1099 if (Op1C->isExactlyValue(2.0) &&
1100 hasUnaryFloatFn(TLI, Op1->getType(), LibFunc::exp2, LibFunc::exp2f,
1101 LibFunc::exp2l))
1102 return EmitUnaryFloatFnCall(Op2, "exp2", B, Callee->getAttributes());
1103 // pow(10.0, x) -> exp10(x)
1104 if (Op1C->isExactlyValue(10.0) &&
1105 hasUnaryFloatFn(TLI, Op1->getType(), LibFunc::exp10, LibFunc::exp10f,
1106 LibFunc::exp10l))
1107 return EmitUnaryFloatFnCall(Op2, TLI->getName(LibFunc::exp10), B,
1108 Callee->getAttributes());
Bob Wilsond8d92d92013-11-03 06:48:38 +00001109 }
1110
Chris Bienemanad070d02014-09-17 20:55:46 +00001111 ConstantFP *Op2C = dyn_cast<ConstantFP>(Op2);
1112 if (!Op2C)
1113 return Ret;
1114
1115 if (Op2C->getValueAPF().isZero()) // pow(x, 0.0) -> 1.0
1116 return ConstantFP::get(CI->getType(), 1.0);
1117
1118 if (Op2C->isExactlyValue(0.5) &&
1119 hasUnaryFloatFn(TLI, Op2->getType(), LibFunc::sqrt, LibFunc::sqrtf,
1120 LibFunc::sqrtl) &&
1121 hasUnaryFloatFn(TLI, Op2->getType(), LibFunc::fabs, LibFunc::fabsf,
1122 LibFunc::fabsl)) {
1123 // Expand pow(x, 0.5) to (x == -infinity ? +infinity : fabs(sqrt(x))).
1124 // This is faster than calling pow, and still handles negative zero
1125 // and negative infinity correctly.
1126 // TODO: In fast-math mode, this could be just sqrt(x).
1127 // TODO: In finite-only mode, this could be just fabs(sqrt(x)).
1128 Value *Inf = ConstantFP::getInfinity(CI->getType());
1129 Value *NegInf = ConstantFP::getInfinity(CI->getType(), true);
1130 Value *Sqrt = EmitUnaryFloatFnCall(Op1, "sqrt", B, Callee->getAttributes());
1131 Value *FAbs =
1132 EmitUnaryFloatFnCall(Sqrt, "fabs", B, Callee->getAttributes());
1133 Value *FCmp = B.CreateFCmpOEQ(Op1, NegInf);
1134 Value *Sel = B.CreateSelect(FCmp, Inf, FAbs);
1135 return Sel;
Bob Wilsond8d92d92013-11-03 06:48:38 +00001136 }
1137
Chris Bienemanad070d02014-09-17 20:55:46 +00001138 if (Op2C->isExactlyValue(1.0)) // pow(x, 1.0) -> x
1139 return Op1;
1140 if (Op2C->isExactlyValue(2.0)) // pow(x, 2.0) -> x*x
1141 return B.CreateFMul(Op1, Op1, "pow2");
1142 if (Op2C->isExactlyValue(-1.0)) // pow(x, -1.0) -> 1.0/x
1143 return B.CreateFDiv(ConstantFP::get(CI->getType(), 1.0), Op1, "powrecip");
1144 return nullptr;
1145}
Bob Wilsond8d92d92013-11-03 06:48:38 +00001146
Chris Bienemanad070d02014-09-17 20:55:46 +00001147Value *LibCallSimplifier::optimizeExp2(CallInst *CI, IRBuilder<> &B) {
1148 Function *Callee = CI->getCalledFunction();
1149 Function *Caller = CI->getParent()->getParent();
Bob Wilsond8d92d92013-11-03 06:48:38 +00001150
Chris Bienemanad070d02014-09-17 20:55:46 +00001151 Value *Ret = nullptr;
1152 if (UnsafeFPShrink && Callee->getName() == "exp2" &&
1153 TLI->has(LibFunc::exp2f)) {
1154 Ret = optimizeUnaryDoubleFP(CI, B, true);
Bob Wilsond8d92d92013-11-03 06:48:38 +00001155 }
1156
Chris Bienemanad070d02014-09-17 20:55:46 +00001157 FunctionType *FT = Callee->getFunctionType();
1158 // Just make sure this has 1 argument of FP type, which matches the
1159 // result type.
1160 if (FT->getNumParams() != 1 || FT->getReturnType() != FT->getParamType(0) ||
1161 !FT->getParamType(0)->isFloatingPointTy())
1162 return Ret;
1163
1164 Value *Op = CI->getArgOperand(0);
1165 // Turn exp2(sitofp(x)) -> ldexp(1.0, sext(x)) if sizeof(x) <= 32
1166 // Turn exp2(uitofp(x)) -> ldexp(1.0, zext(x)) if sizeof(x) < 32
1167 LibFunc::Func LdExp = LibFunc::ldexpl;
1168 if (Op->getType()->isFloatTy())
1169 LdExp = LibFunc::ldexpf;
1170 else if (Op->getType()->isDoubleTy())
1171 LdExp = LibFunc::ldexp;
1172
1173 if (TLI->has(LdExp)) {
1174 Value *LdExpArg = nullptr;
1175 if (SIToFPInst *OpC = dyn_cast<SIToFPInst>(Op)) {
1176 if (OpC->getOperand(0)->getType()->getPrimitiveSizeInBits() <= 32)
1177 LdExpArg = B.CreateSExt(OpC->getOperand(0), B.getInt32Ty());
1178 } else if (UIToFPInst *OpC = dyn_cast<UIToFPInst>(Op)) {
1179 if (OpC->getOperand(0)->getType()->getPrimitiveSizeInBits() < 32)
1180 LdExpArg = B.CreateZExt(OpC->getOperand(0), B.getInt32Ty());
1181 }
1182
1183 if (LdExpArg) {
1184 Constant *One = ConstantFP::get(CI->getContext(), APFloat(1.0f));
1185 if (!Op->getType()->isFloatTy())
1186 One = ConstantExpr::getFPExtend(One, Op->getType());
1187
1188 Module *M = Caller->getParent();
1189 Value *Callee =
1190 M->getOrInsertFunction(TLI->getName(LdExp), Op->getType(),
Reid Kleckner971c3ea2014-11-13 22:55:19 +00001191 Op->getType(), B.getInt32Ty(), nullptr);
David Blaikieff6409d2015-05-18 22:13:54 +00001192 CallInst *CI = B.CreateCall(Callee, {One, LdExpArg});
Chris Bienemanad070d02014-09-17 20:55:46 +00001193 if (const Function *F = dyn_cast<Function>(Callee->stripPointerCasts()))
1194 CI->setCallingConv(F->getCallingConv());
1195
1196 return CI;
1197 }
1198 }
1199 return Ret;
1200}
1201
Sanjay Patel0ca42bb2014-10-14 20:43:11 +00001202Value *LibCallSimplifier::optimizeFabs(CallInst *CI, IRBuilder<> &B) {
1203 Function *Callee = CI->getCalledFunction();
1204
1205 Value *Ret = nullptr;
1206 if (Callee->getName() == "fabs" && TLI->has(LibFunc::fabsf)) {
1207 Ret = optimizeUnaryDoubleFP(CI, B, false);
1208 }
1209
1210 FunctionType *FT = Callee->getFunctionType();
1211 // Make sure this has 1 argument of FP type which matches the result type.
1212 if (FT->getNumParams() != 1 || FT->getReturnType() != FT->getParamType(0) ||
1213 !FT->getParamType(0)->isFloatingPointTy())
1214 return Ret;
1215
1216 Value *Op = CI->getArgOperand(0);
1217 if (Instruction *I = dyn_cast<Instruction>(Op)) {
1218 // Fold fabs(x * x) -> x * x; any squared FP value must already be positive.
1219 if (I->getOpcode() == Instruction::FMul)
1220 if (I->getOperand(0) == I->getOperand(1))
1221 return Op;
1222 }
1223 return Ret;
1224}
1225
Sanjay Patel57fd1dc2015-08-16 20:18:19 +00001226Value *LibCallSimplifier::optimizeFMinFMax(CallInst *CI, IRBuilder<> &B) {
1227 // If we can shrink the call to a float function rather than a double
1228 // function, do that first.
1229 Function *Callee = CI->getCalledFunction();
1230 if ((Callee->getName() == "fmin" && TLI->has(LibFunc::fminf)) ||
1231 (Callee->getName() == "fmax" && TLI->has(LibFunc::fmaxf))) {
1232 Value *Ret = optimizeBinaryDoubleFP(CI, B);
1233 if (Ret)
1234 return Ret;
1235 }
1236
1237 // Make sure this has 2 arguments of FP type which match the result type.
1238 FunctionType *FT = Callee->getFunctionType();
1239 if (FT->getNumParams() != 2 || FT->getReturnType() != FT->getParamType(0) ||
1240 FT->getParamType(0) != FT->getParamType(1) ||
1241 !FT->getParamType(0)->isFloatingPointTy())
1242 return nullptr;
1243
Benjamin Kramerbb70d752015-08-16 21:16:37 +00001244 IRBuilder<>::FastMathFlagGuard Guard(B);
Sanjay Patel57fd1dc2015-08-16 20:18:19 +00001245 FastMathFlags FMF;
1246 Function *F = CI->getParent()->getParent();
Davide Italianoa904e522015-10-29 02:58:44 +00001247 if (canUseUnsafeFPMath(F)) {
Sanjay Patel57fd1dc2015-08-16 20:18:19 +00001248 // Unsafe algebra sets all fast-math-flags to true.
1249 FMF.setUnsafeAlgebra();
1250 } else {
1251 // At a minimum, no-nans-fp-math must be true.
Davide Italianoa904e522015-10-29 02:58:44 +00001252 Attribute Attr = F->getFnAttribute("no-nans-fp-math");
Sanjay Patel57fd1dc2015-08-16 20:18:19 +00001253 if (Attr.getValueAsString() != "true")
1254 return nullptr;
1255 // No-signed-zeros is implied by the definitions of fmax/fmin themselves:
1256 // "Ideally, fmax would be sensitive to the sign of zero, for example
NAKAMURA Takumi0d725392015-09-07 00:26:54 +00001257 // fmax(-0. 0, +0. 0) would return +0; however, implementation in software
Sanjay Patel57fd1dc2015-08-16 20:18:19 +00001258 // might be impractical."
1259 FMF.setNoSignedZeros();
1260 FMF.setNoNaNs();
1261 }
1262 B.SetFastMathFlags(FMF);
1263
1264 // We have a relaxed floating-point environment. We can ignore NaN-handling
1265 // and transform to a compare and select. We do not have to consider errno or
1266 // exceptions, because fmin/fmax do not have those.
1267 Value *Op0 = CI->getArgOperand(0);
1268 Value *Op1 = CI->getArgOperand(1);
1269 Value *Cmp = Callee->getName().startswith("fmin") ?
1270 B.CreateFCmpOLT(Op0, Op1) : B.CreateFCmpOGT(Op0, Op1);
1271 return B.CreateSelect(Cmp, Op0, Op1);
1272}
1273
Sanjay Patelc699a612014-10-16 18:48:17 +00001274Value *LibCallSimplifier::optimizeSqrt(CallInst *CI, IRBuilder<> &B) {
1275 Function *Callee = CI->getCalledFunction();
1276
1277 Value *Ret = nullptr;
Sanjay Patel848309d2014-10-23 21:52:45 +00001278 if (TLI->has(LibFunc::sqrtf) && (Callee->getName() == "sqrt" ||
1279 Callee->getIntrinsicID() == Intrinsic::sqrt))
Sanjay Patelc699a612014-10-16 18:48:17 +00001280 Ret = optimizeUnaryDoubleFP(CI, B, true);
Davide Italianoa904e522015-10-29 02:58:44 +00001281 if (!canUseUnsafeFPMath(CI->getParent()->getParent()))
1282 return Ret;
Sanjay Patelc699a612014-10-16 18:48:17 +00001283
Sanjay Patelc699a612014-10-16 18:48:17 +00001284 Value *Op = CI->getArgOperand(0);
1285 if (Instruction *I = dyn_cast<Instruction>(Op)) {
1286 if (I->getOpcode() == Instruction::FMul && I->hasUnsafeAlgebra()) {
1287 // We're looking for a repeated factor in a multiplication tree,
1288 // so we can do this fold: sqrt(x * x) -> fabs(x);
1289 // or this fold: sqrt(x * x * y) -> fabs(x) * sqrt(y).
1290 Value *Op0 = I->getOperand(0);
1291 Value *Op1 = I->getOperand(1);
1292 Value *RepeatOp = nullptr;
1293 Value *OtherOp = nullptr;
1294 if (Op0 == Op1) {
1295 // Simple match: the operands of the multiply are identical.
1296 RepeatOp = Op0;
1297 } else {
1298 // Look for a more complicated pattern: one of the operands is itself
1299 // a multiply, so search for a common factor in that multiply.
1300 // Note: We don't bother looking any deeper than this first level or for
1301 // variations of this pattern because instcombine's visitFMUL and/or the
1302 // reassociation pass should give us this form.
1303 Value *OtherMul0, *OtherMul1;
1304 if (match(Op0, m_FMul(m_Value(OtherMul0), m_Value(OtherMul1)))) {
1305 // Pattern: sqrt((x * y) * z)
1306 if (OtherMul0 == OtherMul1) {
1307 // Matched: sqrt((x * x) * z)
1308 RepeatOp = OtherMul0;
1309 OtherOp = Op1;
1310 }
1311 }
1312 }
1313 if (RepeatOp) {
1314 // Fast math flags for any created instructions should match the sqrt
1315 // and multiply.
1316 // FIXME: We're not checking the sqrt because it doesn't have
1317 // fast-math-flags (see earlier comment).
Benjamin Kramerbb70d752015-08-16 21:16:37 +00001318 IRBuilder<>::FastMathFlagGuard Guard(B);
Sanjay Patelc699a612014-10-16 18:48:17 +00001319 B.SetFastMathFlags(I->getFastMathFlags());
1320 // If we found a repeated factor, hoist it out of the square root and
1321 // replace it with the fabs of that factor.
1322 Module *M = Callee->getParent();
1323 Type *ArgType = Op->getType();
1324 Value *Fabs = Intrinsic::getDeclaration(M, Intrinsic::fabs, ArgType);
1325 Value *FabsCall = B.CreateCall(Fabs, RepeatOp, "fabs");
1326 if (OtherOp) {
1327 // If we found a non-repeated factor, we still need to get its square
1328 // root. We then multiply that by the value that was simplified out
1329 // of the square root calculation.
1330 Value *Sqrt = Intrinsic::getDeclaration(M, Intrinsic::sqrt, ArgType);
1331 Value *SqrtCall = B.CreateCall(Sqrt, OtherOp, "sqrt");
1332 return B.CreateFMul(FabsCall, SqrtCall);
1333 }
1334 return FabsCall;
1335 }
1336 }
1337 }
1338 return Ret;
1339}
1340
Chris Bienemanad070d02014-09-17 20:55:46 +00001341static bool isTrigLibCall(CallInst *CI);
1342static void insertSinCosCall(IRBuilder<> &B, Function *OrigCallee, Value *Arg,
1343 bool UseFloat, Value *&Sin, Value *&Cos,
1344 Value *&SinCos);
1345
1346Value *LibCallSimplifier::optimizeSinCosPi(CallInst *CI, IRBuilder<> &B) {
1347
1348 // Make sure the prototype is as expected, otherwise the rest of the
1349 // function is probably invalid and likely to abort.
1350 if (!isTrigLibCall(CI))
1351 return nullptr;
1352
1353 Value *Arg = CI->getArgOperand(0);
1354 SmallVector<CallInst *, 1> SinCalls;
1355 SmallVector<CallInst *, 1> CosCalls;
1356 SmallVector<CallInst *, 1> SinCosCalls;
1357
1358 bool IsFloat = Arg->getType()->isFloatTy();
1359
1360 // Look for all compatible sinpi, cospi and sincospi calls with the same
1361 // argument. If there are enough (in some sense) we can make the
1362 // substitution.
1363 for (User *U : Arg->users())
1364 classifyArgUse(U, CI->getParent(), IsFloat, SinCalls, CosCalls,
1365 SinCosCalls);
1366
1367 // It's only worthwhile if both sinpi and cospi are actually used.
1368 if (SinCosCalls.empty() && (SinCalls.empty() || CosCalls.empty()))
1369 return nullptr;
1370
1371 Value *Sin, *Cos, *SinCos;
1372 insertSinCosCall(B, CI->getCalledFunction(), Arg, IsFloat, Sin, Cos, SinCos);
1373
1374 replaceTrigInsts(SinCalls, Sin);
1375 replaceTrigInsts(CosCalls, Cos);
1376 replaceTrigInsts(SinCosCalls, SinCos);
1377
1378 return nullptr;
1379}
1380
1381static bool isTrigLibCall(CallInst *CI) {
1382 Function *Callee = CI->getCalledFunction();
1383 FunctionType *FT = Callee->getFunctionType();
1384
1385 // We can only hope to do anything useful if we can ignore things like errno
1386 // and floating-point exceptions.
1387 bool AttributesSafe =
1388 CI->hasFnAttr(Attribute::NoUnwind) && CI->hasFnAttr(Attribute::ReadNone);
1389
1390 // Other than that we need float(float) or double(double)
1391 return AttributesSafe && FT->getNumParams() == 1 &&
1392 FT->getReturnType() == FT->getParamType(0) &&
1393 (FT->getParamType(0)->isFloatTy() ||
1394 FT->getParamType(0)->isDoubleTy());
1395}
1396
1397void
1398LibCallSimplifier::classifyArgUse(Value *Val, BasicBlock *BB, bool IsFloat,
1399 SmallVectorImpl<CallInst *> &SinCalls,
1400 SmallVectorImpl<CallInst *> &CosCalls,
1401 SmallVectorImpl<CallInst *> &SinCosCalls) {
1402 CallInst *CI = dyn_cast<CallInst>(Val);
1403
1404 if (!CI)
1405 return;
1406
1407 Function *Callee = CI->getCalledFunction();
1408 StringRef FuncName = Callee->getName();
1409 LibFunc::Func Func;
1410 if (!TLI->getLibFunc(FuncName, Func) || !TLI->has(Func) || !isTrigLibCall(CI))
1411 return;
1412
1413 if (IsFloat) {
1414 if (Func == LibFunc::sinpif)
1415 SinCalls.push_back(CI);
1416 else if (Func == LibFunc::cospif)
1417 CosCalls.push_back(CI);
1418 else if (Func == LibFunc::sincospif_stret)
1419 SinCosCalls.push_back(CI);
1420 } else {
1421 if (Func == LibFunc::sinpi)
1422 SinCalls.push_back(CI);
1423 else if (Func == LibFunc::cospi)
1424 CosCalls.push_back(CI);
1425 else if (Func == LibFunc::sincospi_stret)
1426 SinCosCalls.push_back(CI);
1427 }
1428}
1429
1430void LibCallSimplifier::replaceTrigInsts(SmallVectorImpl<CallInst *> &Calls,
1431 Value *Res) {
Davide Italianoc6926882015-10-27 04:17:51 +00001432 for (CallInst *C : Calls)
1433 replaceAllUsesWith(C, Res);
Chris Bienemanad070d02014-09-17 20:55:46 +00001434}
1435
1436void insertSinCosCall(IRBuilder<> &B, Function *OrigCallee, Value *Arg,
1437 bool UseFloat, Value *&Sin, Value *&Cos, Value *&SinCos) {
1438 Type *ArgTy = Arg->getType();
1439 Type *ResTy;
1440 StringRef Name;
1441
1442 Triple T(OrigCallee->getParent()->getTargetTriple());
1443 if (UseFloat) {
1444 Name = "__sincospif_stret";
1445
1446 assert(T.getArch() != Triple::x86 && "x86 messy and unsupported for now");
1447 // x86_64 can't use {float, float} since that would be returned in both
1448 // xmm0 and xmm1, which isn't what a real struct would do.
1449 ResTy = T.getArch() == Triple::x86_64
1450 ? static_cast<Type *>(VectorType::get(ArgTy, 2))
Reid Kleckner971c3ea2014-11-13 22:55:19 +00001451 : static_cast<Type *>(StructType::get(ArgTy, ArgTy, nullptr));
Chris Bienemanad070d02014-09-17 20:55:46 +00001452 } else {
1453 Name = "__sincospi_stret";
Reid Kleckner971c3ea2014-11-13 22:55:19 +00001454 ResTy = StructType::get(ArgTy, ArgTy, nullptr);
Chris Bienemanad070d02014-09-17 20:55:46 +00001455 }
1456
1457 Module *M = OrigCallee->getParent();
1458 Value *Callee = M->getOrInsertFunction(Name, OrigCallee->getAttributes(),
Reid Kleckner971c3ea2014-11-13 22:55:19 +00001459 ResTy, ArgTy, nullptr);
Chris Bienemanad070d02014-09-17 20:55:46 +00001460
1461 if (Instruction *ArgInst = dyn_cast<Instruction>(Arg)) {
1462 // If the argument is an instruction, it must dominate all uses so put our
1463 // sincos call there.
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +00001464 B.SetInsertPoint(ArgInst->getParent(), ++ArgInst->getIterator());
Chris Bienemanad070d02014-09-17 20:55:46 +00001465 } else {
1466 // Otherwise (e.g. for a constant) the beginning of the function is as
1467 // good a place as any.
1468 BasicBlock &EntryBB = B.GetInsertBlock()->getParent()->getEntryBlock();
1469 B.SetInsertPoint(&EntryBB, EntryBB.begin());
1470 }
1471
1472 SinCos = B.CreateCall(Callee, Arg, "sincospi");
1473
1474 if (SinCos->getType()->isStructTy()) {
1475 Sin = B.CreateExtractValue(SinCos, 0, "sinpi");
1476 Cos = B.CreateExtractValue(SinCos, 1, "cospi");
1477 } else {
1478 Sin = B.CreateExtractElement(SinCos, ConstantInt::get(B.getInt32Ty(), 0),
1479 "sinpi");
1480 Cos = B.CreateExtractElement(SinCos, ConstantInt::get(B.getInt32Ty(), 1),
1481 "cospi");
1482 }
1483}
Bob Wilsond8d92d92013-11-03 06:48:38 +00001484
Meador Inge7415f842012-11-25 20:45:27 +00001485//===----------------------------------------------------------------------===//
1486// Integer Library Call Optimizations
1487//===----------------------------------------------------------------------===//
1488
Davide Italiano396f3ee2015-10-31 23:17:45 +00001489static bool checkIntUnaryReturnAndParam(Function *Callee) {
1490 FunctionType *FT = Callee->getFunctionType();
Davide Italiano5cdf9152015-11-01 00:09:16 +00001491 return FT->getNumParams() == 1 && FT->getReturnType()->isIntegerTy(32) &&
1492 FT->getParamType(0)->isIntegerTy();
Davide Italiano396f3ee2015-10-31 23:17:45 +00001493}
1494
Chris Bienemanad070d02014-09-17 20:55:46 +00001495Value *LibCallSimplifier::optimizeFFS(CallInst *CI, IRBuilder<> &B) {
1496 Function *Callee = CI->getCalledFunction();
Davide Italiano396f3ee2015-10-31 23:17:45 +00001497 if (!checkIntUnaryReturnAndParam(Callee))
Chris Bienemanad070d02014-09-17 20:55:46 +00001498 return nullptr;
Chris Bienemanad070d02014-09-17 20:55:46 +00001499 Value *Op = CI->getArgOperand(0);
Meador Inge7415f842012-11-25 20:45:27 +00001500
Chris Bienemanad070d02014-09-17 20:55:46 +00001501 // Constant fold.
1502 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op)) {
1503 if (CI->isZero()) // ffs(0) -> 0.
1504 return B.getInt32(0);
1505 // ffs(c) -> cttz(c)+1
1506 return B.getInt32(CI->getValue().countTrailingZeros() + 1);
Meador Inge7415f842012-11-25 20:45:27 +00001507 }
Meador Inge7415f842012-11-25 20:45:27 +00001508
Chris Bienemanad070d02014-09-17 20:55:46 +00001509 // ffs(x) -> x != 0 ? (i32)llvm.cttz(x)+1 : 0
1510 Type *ArgType = Op->getType();
1511 Value *F =
1512 Intrinsic::getDeclaration(Callee->getParent(), Intrinsic::cttz, ArgType);
Davide Italianoa1953862015-08-13 20:34:26 +00001513 Value *V = B.CreateCall(F, {Op, B.getTrue()}, "cttz");
Chris Bienemanad070d02014-09-17 20:55:46 +00001514 V = B.CreateAdd(V, ConstantInt::get(V->getType(), 1));
1515 V = B.CreateIntCast(V, B.getInt32Ty(), false);
Meador Ingea0b6d872012-11-26 00:24:07 +00001516
Chris Bienemanad070d02014-09-17 20:55:46 +00001517 Value *Cond = B.CreateICmpNE(Op, Constant::getNullValue(ArgType));
1518 return B.CreateSelect(Cond, V, B.getInt32(0));
1519}
Meador Ingea0b6d872012-11-26 00:24:07 +00001520
Chris Bienemanad070d02014-09-17 20:55:46 +00001521Value *LibCallSimplifier::optimizeAbs(CallInst *CI, IRBuilder<> &B) {
1522 Function *Callee = CI->getCalledFunction();
1523 FunctionType *FT = Callee->getFunctionType();
1524 // We require integer(integer) where the types agree.
1525 if (FT->getNumParams() != 1 || !FT->getReturnType()->isIntegerTy() ||
1526 FT->getParamType(0) != FT->getReturnType())
1527 return nullptr;
Meador Inge9a59ab62012-11-26 02:31:59 +00001528
Chris Bienemanad070d02014-09-17 20:55:46 +00001529 // abs(x) -> x >s -1 ? x : -x
1530 Value *Op = CI->getArgOperand(0);
1531 Value *Pos =
1532 B.CreateICmpSGT(Op, Constant::getAllOnesValue(Op->getType()), "ispos");
1533 Value *Neg = B.CreateNeg(Op, "neg");
1534 return B.CreateSelect(Pos, Op, Neg);
1535}
Meador Inge9a59ab62012-11-26 02:31:59 +00001536
Chris Bienemanad070d02014-09-17 20:55:46 +00001537Value *LibCallSimplifier::optimizeIsDigit(CallInst *CI, IRBuilder<> &B) {
Davide Italiano396f3ee2015-10-31 23:17:45 +00001538 if (!checkIntUnaryReturnAndParam(CI->getCalledFunction()))
Chris Bienemanad070d02014-09-17 20:55:46 +00001539 return nullptr;
Meador Ingea62a39e2012-11-26 03:10:07 +00001540
Chris Bienemanad070d02014-09-17 20:55:46 +00001541 // isdigit(c) -> (c-'0') <u 10
1542 Value *Op = CI->getArgOperand(0);
1543 Op = B.CreateSub(Op, B.getInt32('0'), "isdigittmp");
1544 Op = B.CreateICmpULT(Op, B.getInt32(10), "isdigit");
1545 return B.CreateZExt(Op, CI->getType());
1546}
Meador Ingea62a39e2012-11-26 03:10:07 +00001547
Chris Bienemanad070d02014-09-17 20:55:46 +00001548Value *LibCallSimplifier::optimizeIsAscii(CallInst *CI, IRBuilder<> &B) {
Davide Italiano396f3ee2015-10-31 23:17:45 +00001549 if (!checkIntUnaryReturnAndParam(CI->getCalledFunction()))
Chris Bienemanad070d02014-09-17 20:55:46 +00001550 return nullptr;
Meador Inge604937d2012-11-26 03:38:52 +00001551
Chris Bienemanad070d02014-09-17 20:55:46 +00001552 // isascii(c) -> c <u 128
1553 Value *Op = CI->getArgOperand(0);
1554 Op = B.CreateICmpULT(Op, B.getInt32(128), "isascii");
1555 return B.CreateZExt(Op, CI->getType());
1556}
1557
1558Value *LibCallSimplifier::optimizeToAscii(CallInst *CI, IRBuilder<> &B) {
Davide Italiano396f3ee2015-10-31 23:17:45 +00001559 if (!checkIntUnaryReturnAndParam(CI->getCalledFunction()))
Chris Bienemanad070d02014-09-17 20:55:46 +00001560 return nullptr;
1561
1562 // toascii(c) -> c & 0x7f
1563 return B.CreateAnd(CI->getArgOperand(0),
1564 ConstantInt::get(CI->getType(), 0x7F));
1565}
Meador Inge604937d2012-11-26 03:38:52 +00001566
Meador Inge08ca1152012-11-26 20:37:20 +00001567//===----------------------------------------------------------------------===//
1568// Formatting and IO Library Call Optimizations
1569//===----------------------------------------------------------------------===//
1570
Chris Bienemanad070d02014-09-17 20:55:46 +00001571static bool isReportingError(Function *Callee, CallInst *CI, int StreamArg);
Hal Finkel66cd3f12013-11-17 02:06:35 +00001572
Chris Bienemanad070d02014-09-17 20:55:46 +00001573Value *LibCallSimplifier::optimizeErrorReporting(CallInst *CI, IRBuilder<> &B,
1574 int StreamArg) {
1575 // Error reporting calls should be cold, mark them as such.
1576 // This applies even to non-builtin calls: it is only a hint and applies to
1577 // functions that the frontend might not understand as builtins.
Hal Finkel66cd3f12013-11-17 02:06:35 +00001578
Chris Bienemanad070d02014-09-17 20:55:46 +00001579 // This heuristic was suggested in:
1580 // Improving Static Branch Prediction in a Compiler
1581 // Brian L. Deitrich, Ben-Chung Cheng, Wen-mei W. Hwu
1582 // Proceedings of PACT'98, Oct. 1998, IEEE
1583 Function *Callee = CI->getCalledFunction();
Hal Finkel66cd3f12013-11-17 02:06:35 +00001584
Chris Bienemanad070d02014-09-17 20:55:46 +00001585 if (!CI->hasFnAttr(Attribute::Cold) &&
1586 isReportingError(Callee, CI, StreamArg)) {
1587 CI->addAttribute(AttributeSet::FunctionIndex, Attribute::Cold);
1588 }
Hal Finkel66cd3f12013-11-17 02:06:35 +00001589
Chris Bienemanad070d02014-09-17 20:55:46 +00001590 return nullptr;
1591}
1592
1593static bool isReportingError(Function *Callee, CallInst *CI, int StreamArg) {
Davide Italianoe84d4da2015-11-02 22:33:26 +00001594 if (!ColdErrorCalls || !Callee || !Callee->isDeclaration())
Chris Bienemanad070d02014-09-17 20:55:46 +00001595 return false;
1596
1597 if (StreamArg < 0)
1598 return true;
1599
1600 // These functions might be considered cold, but only if their stream
1601 // argument is stderr.
1602
1603 if (StreamArg >= (int)CI->getNumArgOperands())
1604 return false;
1605 LoadInst *LI = dyn_cast<LoadInst>(CI->getArgOperand(StreamArg));
1606 if (!LI)
1607 return false;
1608 GlobalVariable *GV = dyn_cast<GlobalVariable>(LI->getPointerOperand());
1609 if (!GV || !GV->isDeclaration())
1610 return false;
1611 return GV->getName() == "stderr";
1612}
1613
1614Value *LibCallSimplifier::optimizePrintFString(CallInst *CI, IRBuilder<> &B) {
1615 // Check for a fixed format string.
1616 StringRef FormatStr;
1617 if (!getConstantStringInfo(CI->getArgOperand(0), FormatStr))
Craig Topperf40110f2014-04-25 05:29:35 +00001618 return nullptr;
Hal Finkel66cd3f12013-11-17 02:06:35 +00001619
Chris Bienemanad070d02014-09-17 20:55:46 +00001620 // Empty format string -> noop.
1621 if (FormatStr.empty()) // Tolerate printf's declared void.
1622 return CI->use_empty() ? (Value *)CI : ConstantInt::get(CI->getType(), 0);
Hal Finkel66cd3f12013-11-17 02:06:35 +00001623
Chris Bienemanad070d02014-09-17 20:55:46 +00001624 // Do not do any of the following transformations if the printf return value
1625 // is used, in general the printf return value is not compatible with either
1626 // putchar() or puts().
1627 if (!CI->use_empty())
Craig Topperf40110f2014-04-25 05:29:35 +00001628 return nullptr;
Chris Bienemanad070d02014-09-17 20:55:46 +00001629
1630 // printf("x") -> putchar('x'), even for '%'.
1631 if (FormatStr.size() == 1) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001632 Value *Res = EmitPutChar(B.getInt32(FormatStr[0]), B, TLI);
Chris Bienemanad070d02014-09-17 20:55:46 +00001633 if (CI->use_empty() || !Res)
1634 return Res;
1635 return B.CreateIntCast(Res, CI->getType(), true);
Meador Inge08ca1152012-11-26 20:37:20 +00001636 }
1637
Chris Bienemanad070d02014-09-17 20:55:46 +00001638 // printf("foo\n") --> puts("foo")
1639 if (FormatStr[FormatStr.size() - 1] == '\n' &&
1640 FormatStr.find('%') == StringRef::npos) { // No format characters.
1641 // Create a string literal with no \n on it. We expect the constant merge
1642 // pass to be run after this pass, to merge duplicate strings.
1643 FormatStr = FormatStr.drop_back();
1644 Value *GV = B.CreateGlobalString(FormatStr, "str");
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001645 Value *NewCI = EmitPutS(GV, B, TLI);
Chris Bienemanad070d02014-09-17 20:55:46 +00001646 return (CI->use_empty() || !NewCI)
1647 ? NewCI
1648 : ConstantInt::get(CI->getType(), FormatStr.size() + 1);
1649 }
Meador Inge08ca1152012-11-26 20:37:20 +00001650
Chris Bienemanad070d02014-09-17 20:55:46 +00001651 // Optimize specific format strings.
1652 // printf("%c", chr) --> putchar(chr)
1653 if (FormatStr == "%c" && CI->getNumArgOperands() > 1 &&
1654 CI->getArgOperand(1)->getType()->isIntegerTy()) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001655 Value *Res = EmitPutChar(CI->getArgOperand(1), B, TLI);
Meador Inge08ca1152012-11-26 20:37:20 +00001656
Chris Bienemanad070d02014-09-17 20:55:46 +00001657 if (CI->use_empty() || !Res)
1658 return Res;
1659 return B.CreateIntCast(Res, CI->getType(), true);
1660 }
1661
1662 // printf("%s\n", str) --> puts(str)
1663 if (FormatStr == "%s\n" && CI->getNumArgOperands() > 1 &&
1664 CI->getArgOperand(1)->getType()->isPointerTy()) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001665 return EmitPutS(CI->getArgOperand(1), B, TLI);
Chris Bienemanad070d02014-09-17 20:55:46 +00001666 }
1667 return nullptr;
1668}
1669
1670Value *LibCallSimplifier::optimizePrintF(CallInst *CI, IRBuilder<> &B) {
1671
1672 Function *Callee = CI->getCalledFunction();
1673 // Require one fixed pointer argument and an integer/void result.
1674 FunctionType *FT = Callee->getFunctionType();
1675 if (FT->getNumParams() < 1 || !FT->getParamType(0)->isPointerTy() ||
1676 !(FT->getReturnType()->isIntegerTy() || FT->getReturnType()->isVoidTy()))
1677 return nullptr;
1678
1679 if (Value *V = optimizePrintFString(CI, B)) {
1680 return V;
1681 }
1682
1683 // printf(format, ...) -> iprintf(format, ...) if no floating point
1684 // arguments.
1685 if (TLI->has(LibFunc::iprintf) && !callHasFloatingPointArgument(CI)) {
1686 Module *M = B.GetInsertBlock()->getParent()->getParent();
1687 Constant *IPrintFFn =
Meador Inge08ca1152012-11-26 20:37:20 +00001688 M->getOrInsertFunction("iprintf", FT, Callee->getAttributes());
Chris Bienemanad070d02014-09-17 20:55:46 +00001689 CallInst *New = cast<CallInst>(CI->clone());
1690 New->setCalledFunction(IPrintFFn);
1691 B.Insert(New);
1692 return New;
Meador Inge08ca1152012-11-26 20:37:20 +00001693 }
Chris Bienemanad070d02014-09-17 20:55:46 +00001694 return nullptr;
1695}
Meador Inge08ca1152012-11-26 20:37:20 +00001696
Chris Bienemanad070d02014-09-17 20:55:46 +00001697Value *LibCallSimplifier::optimizeSPrintFString(CallInst *CI, IRBuilder<> &B) {
1698 // Check for a fixed format string.
1699 StringRef FormatStr;
1700 if (!getConstantStringInfo(CI->getArgOperand(1), FormatStr))
Craig Topperf40110f2014-04-25 05:29:35 +00001701 return nullptr;
Meador Inge25c9b3b2012-11-27 05:57:54 +00001702
Chris Bienemanad070d02014-09-17 20:55:46 +00001703 // If we just have a format string (nothing else crazy) transform it.
1704 if (CI->getNumArgOperands() == 2) {
1705 // Make sure there's no % in the constant array. We could try to handle
1706 // %% -> % in the future if we cared.
1707 for (unsigned i = 0, e = FormatStr.size(); i != e; ++i)
1708 if (FormatStr[i] == '%')
1709 return nullptr; // we found a format specifier, bail out.
Hal Finkel66cd3f12013-11-17 02:06:35 +00001710
Chris Bienemanad070d02014-09-17 20:55:46 +00001711 // sprintf(str, fmt) -> llvm.memcpy(str, fmt, strlen(fmt)+1, 1)
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001712 B.CreateMemCpy(CI->getArgOperand(0), CI->getArgOperand(1),
1713 ConstantInt::get(DL.getIntPtrType(CI->getContext()),
1714 FormatStr.size() + 1),
1715 1); // Copy the null byte.
Chris Bienemanad070d02014-09-17 20:55:46 +00001716 return ConstantInt::get(CI->getType(), FormatStr.size());
Meador Ingef8e72502012-11-29 15:45:43 +00001717 }
Meador Ingef8e72502012-11-29 15:45:43 +00001718
Chris Bienemanad070d02014-09-17 20:55:46 +00001719 // The remaining optimizations require the format string to be "%s" or "%c"
1720 // and have an extra operand.
1721 if (FormatStr.size() != 2 || FormatStr[0] != '%' ||
1722 CI->getNumArgOperands() < 3)
Craig Topperf40110f2014-04-25 05:29:35 +00001723 return nullptr;
Meador Inge75798bb2012-11-29 19:15:17 +00001724
Chris Bienemanad070d02014-09-17 20:55:46 +00001725 // Decode the second character of the format string.
1726 if (FormatStr[1] == 'c') {
1727 // sprintf(dst, "%c", chr) --> *(i8*)dst = chr; *((i8*)dst+1) = 0
1728 if (!CI->getArgOperand(2)->getType()->isIntegerTy())
1729 return nullptr;
1730 Value *V = B.CreateTrunc(CI->getArgOperand(2), B.getInt8Ty(), "char");
1731 Value *Ptr = CastToCStr(CI->getArgOperand(0), B);
1732 B.CreateStore(V, Ptr);
David Blaikie3909da72015-03-30 20:42:56 +00001733 Ptr = B.CreateGEP(B.getInt8Ty(), Ptr, B.getInt32(1), "nul");
Chris Bienemanad070d02014-09-17 20:55:46 +00001734 B.CreateStore(B.getInt8(0), Ptr);
Meador Ingedf796f82012-10-13 16:45:24 +00001735
Chris Bienemanad070d02014-09-17 20:55:46 +00001736 return ConstantInt::get(CI->getType(), 1);
Meador Ingedf796f82012-10-13 16:45:24 +00001737 }
1738
Chris Bienemanad070d02014-09-17 20:55:46 +00001739 if (FormatStr[1] == 's') {
Chris Bienemanad070d02014-09-17 20:55:46 +00001740 // sprintf(dest, "%s", str) -> llvm.memcpy(dest, str, strlen(str)+1, 1)
1741 if (!CI->getArgOperand(2)->getType()->isPointerTy())
1742 return nullptr;
1743
1744 Value *Len = EmitStrLen(CI->getArgOperand(2), B, DL, TLI);
1745 if (!Len)
1746 return nullptr;
1747 Value *IncLen =
1748 B.CreateAdd(Len, ConstantInt::get(Len->getType(), 1), "leninc");
1749 B.CreateMemCpy(CI->getArgOperand(0), CI->getArgOperand(2), IncLen, 1);
1750
1751 // The sprintf result is the unincremented number of bytes in the string.
1752 return B.CreateIntCast(Len, CI->getType(), false);
1753 }
1754 return nullptr;
1755}
1756
1757Value *LibCallSimplifier::optimizeSPrintF(CallInst *CI, IRBuilder<> &B) {
1758 Function *Callee = CI->getCalledFunction();
1759 // Require two fixed pointer arguments and an integer result.
1760 FunctionType *FT = Callee->getFunctionType();
1761 if (FT->getNumParams() != 2 || !FT->getParamType(0)->isPointerTy() ||
1762 !FT->getParamType(1)->isPointerTy() ||
1763 !FT->getReturnType()->isIntegerTy())
1764 return nullptr;
1765
1766 if (Value *V = optimizeSPrintFString(CI, B)) {
1767 return V;
1768 }
1769
1770 // sprintf(str, format, ...) -> siprintf(str, format, ...) if no floating
1771 // point arguments.
1772 if (TLI->has(LibFunc::siprintf) && !callHasFloatingPointArgument(CI)) {
1773 Module *M = B.GetInsertBlock()->getParent()->getParent();
1774 Constant *SIPrintFFn =
1775 M->getOrInsertFunction("siprintf", FT, Callee->getAttributes());
1776 CallInst *New = cast<CallInst>(CI->clone());
1777 New->setCalledFunction(SIPrintFFn);
1778 B.Insert(New);
1779 return New;
1780 }
1781 return nullptr;
1782}
1783
1784Value *LibCallSimplifier::optimizeFPrintFString(CallInst *CI, IRBuilder<> &B) {
1785 optimizeErrorReporting(CI, B, 0);
1786
1787 // All the optimizations depend on the format string.
1788 StringRef FormatStr;
1789 if (!getConstantStringInfo(CI->getArgOperand(1), FormatStr))
1790 return nullptr;
1791
1792 // Do not do any of the following transformations if the fprintf return
1793 // value is used, in general the fprintf return value is not compatible
1794 // with fwrite(), fputc() or fputs().
1795 if (!CI->use_empty())
1796 return nullptr;
1797
1798 // fprintf(F, "foo") --> fwrite("foo", 3, 1, F)
1799 if (CI->getNumArgOperands() == 2) {
1800 for (unsigned i = 0, e = FormatStr.size(); i != e; ++i)
1801 if (FormatStr[i] == '%') // Could handle %% -> % if we cared.
1802 return nullptr; // We found a format specifier.
1803
Chris Bienemanad070d02014-09-17 20:55:46 +00001804 return EmitFWrite(
1805 CI->getArgOperand(1),
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001806 ConstantInt::get(DL.getIntPtrType(CI->getContext()), FormatStr.size()),
Chris Bienemanad070d02014-09-17 20:55:46 +00001807 CI->getArgOperand(0), B, DL, TLI);
1808 }
1809
1810 // The remaining optimizations require the format string to be "%s" or "%c"
1811 // and have an extra operand.
1812 if (FormatStr.size() != 2 || FormatStr[0] != '%' ||
1813 CI->getNumArgOperands() < 3)
1814 return nullptr;
1815
1816 // Decode the second character of the format string.
1817 if (FormatStr[1] == 'c') {
1818 // fprintf(F, "%c", chr) --> fputc(chr, F)
1819 if (!CI->getArgOperand(2)->getType()->isIntegerTy())
1820 return nullptr;
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001821 return EmitFPutC(CI->getArgOperand(2), CI->getArgOperand(0), B, TLI);
Chris Bienemanad070d02014-09-17 20:55:46 +00001822 }
1823
1824 if (FormatStr[1] == 's') {
1825 // fprintf(F, "%s", str) --> fputs(str, F)
1826 if (!CI->getArgOperand(2)->getType()->isPointerTy())
1827 return nullptr;
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001828 return EmitFPutS(CI->getArgOperand(2), CI->getArgOperand(0), B, TLI);
Chris Bienemanad070d02014-09-17 20:55:46 +00001829 }
1830 return nullptr;
1831}
1832
1833Value *LibCallSimplifier::optimizeFPrintF(CallInst *CI, IRBuilder<> &B) {
1834 Function *Callee = CI->getCalledFunction();
1835 // Require two fixed paramters as pointers and integer result.
1836 FunctionType *FT = Callee->getFunctionType();
1837 if (FT->getNumParams() != 2 || !FT->getParamType(0)->isPointerTy() ||
1838 !FT->getParamType(1)->isPointerTy() ||
1839 !FT->getReturnType()->isIntegerTy())
1840 return nullptr;
1841
1842 if (Value *V = optimizeFPrintFString(CI, B)) {
1843 return V;
1844 }
1845
1846 // fprintf(stream, format, ...) -> fiprintf(stream, format, ...) if no
1847 // floating point arguments.
1848 if (TLI->has(LibFunc::fiprintf) && !callHasFloatingPointArgument(CI)) {
1849 Module *M = B.GetInsertBlock()->getParent()->getParent();
1850 Constant *FIPrintFFn =
1851 M->getOrInsertFunction("fiprintf", FT, Callee->getAttributes());
1852 CallInst *New = cast<CallInst>(CI->clone());
1853 New->setCalledFunction(FIPrintFFn);
1854 B.Insert(New);
1855 return New;
1856 }
1857 return nullptr;
1858}
1859
1860Value *LibCallSimplifier::optimizeFWrite(CallInst *CI, IRBuilder<> &B) {
1861 optimizeErrorReporting(CI, B, 3);
1862
1863 Function *Callee = CI->getCalledFunction();
1864 // Require a pointer, an integer, an integer, a pointer, returning integer.
1865 FunctionType *FT = Callee->getFunctionType();
1866 if (FT->getNumParams() != 4 || !FT->getParamType(0)->isPointerTy() ||
1867 !FT->getParamType(1)->isIntegerTy() ||
1868 !FT->getParamType(2)->isIntegerTy() ||
1869 !FT->getParamType(3)->isPointerTy() ||
1870 !FT->getReturnType()->isIntegerTy())
1871 return nullptr;
1872
1873 // Get the element size and count.
1874 ConstantInt *SizeC = dyn_cast<ConstantInt>(CI->getArgOperand(1));
1875 ConstantInt *CountC = dyn_cast<ConstantInt>(CI->getArgOperand(2));
1876 if (!SizeC || !CountC)
1877 return nullptr;
1878 uint64_t Bytes = SizeC->getZExtValue() * CountC->getZExtValue();
1879
1880 // If this is writing zero records, remove the call (it's a noop).
1881 if (Bytes == 0)
1882 return ConstantInt::get(CI->getType(), 0);
1883
1884 // If this is writing one byte, turn it into fputc.
1885 // This optimisation is only valid, if the return value is unused.
1886 if (Bytes == 1 && CI->use_empty()) { // fwrite(S,1,1,F) -> fputc(S[0],F)
1887 Value *Char = B.CreateLoad(CastToCStr(CI->getArgOperand(0), B), "char");
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001888 Value *NewCI = EmitFPutC(Char, CI->getArgOperand(3), B, TLI);
Chris Bienemanad070d02014-09-17 20:55:46 +00001889 return NewCI ? ConstantInt::get(CI->getType(), 1) : nullptr;
1890 }
1891
1892 return nullptr;
1893}
1894
1895Value *LibCallSimplifier::optimizeFPuts(CallInst *CI, IRBuilder<> &B) {
1896 optimizeErrorReporting(CI, B, 1);
1897
1898 Function *Callee = CI->getCalledFunction();
1899
Chris Bienemanad070d02014-09-17 20:55:46 +00001900 // Require two pointers. Also, we can't optimize if return value is used.
1901 FunctionType *FT = Callee->getFunctionType();
1902 if (FT->getNumParams() != 2 || !FT->getParamType(0)->isPointerTy() ||
1903 !FT->getParamType(1)->isPointerTy() || !CI->use_empty())
1904 return nullptr;
1905
1906 // fputs(s,F) --> fwrite(s,1,strlen(s),F)
1907 uint64_t Len = GetStringLength(CI->getArgOperand(0));
1908 if (!Len)
1909 return nullptr;
1910
1911 // Known to have no uses (see above).
1912 return EmitFWrite(
1913 CI->getArgOperand(0),
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001914 ConstantInt::get(DL.getIntPtrType(CI->getContext()), Len - 1),
Chris Bienemanad070d02014-09-17 20:55:46 +00001915 CI->getArgOperand(1), B, DL, TLI);
1916}
1917
1918Value *LibCallSimplifier::optimizePuts(CallInst *CI, IRBuilder<> &B) {
1919 Function *Callee = CI->getCalledFunction();
1920 // Require one fixed pointer argument and an integer/void result.
1921 FunctionType *FT = Callee->getFunctionType();
1922 if (FT->getNumParams() < 1 || !FT->getParamType(0)->isPointerTy() ||
1923 !(FT->getReturnType()->isIntegerTy() || FT->getReturnType()->isVoidTy()))
1924 return nullptr;
1925
1926 // Check for a constant string.
1927 StringRef Str;
1928 if (!getConstantStringInfo(CI->getArgOperand(0), Str))
1929 return nullptr;
1930
1931 if (Str.empty() && CI->use_empty()) {
1932 // puts("") -> putchar('\n')
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001933 Value *Res = EmitPutChar(B.getInt32('\n'), B, TLI);
Chris Bienemanad070d02014-09-17 20:55:46 +00001934 if (CI->use_empty() || !Res)
1935 return Res;
1936 return B.CreateIntCast(Res, CI->getType(), true);
1937 }
1938
1939 return nullptr;
1940}
1941
1942bool LibCallSimplifier::hasFloatVersion(StringRef FuncName) {
Meador Inge20255ef2013-03-12 00:08:29 +00001943 LibFunc::Func Func;
1944 SmallString<20> FloatFuncName = FuncName;
1945 FloatFuncName += 'f';
1946 if (TLI->getLibFunc(FloatFuncName, Func))
1947 return TLI->has(Func);
1948 return false;
1949}
Meador Inge7fb2f732012-10-13 16:45:32 +00001950
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00001951Value *LibCallSimplifier::optimizeStringMemoryLibCall(CallInst *CI,
1952 IRBuilder<> &Builder) {
1953 LibFunc::Func Func;
1954 Function *Callee = CI->getCalledFunction();
1955 StringRef FuncName = Callee->getName();
1956
1957 // Check for string/memory library functions.
1958 if (TLI->getLibFunc(FuncName, Func) && TLI->has(Func)) {
1959 // Make sure we never change the calling convention.
1960 assert((ignoreCallingConv(Func) ||
1961 CI->getCallingConv() == llvm::CallingConv::C) &&
1962 "Optimizing string/memory libcall would change the calling convention");
1963 switch (Func) {
1964 case LibFunc::strcat:
1965 return optimizeStrCat(CI, Builder);
1966 case LibFunc::strncat:
1967 return optimizeStrNCat(CI, Builder);
1968 case LibFunc::strchr:
1969 return optimizeStrChr(CI, Builder);
1970 case LibFunc::strrchr:
1971 return optimizeStrRChr(CI, Builder);
1972 case LibFunc::strcmp:
1973 return optimizeStrCmp(CI, Builder);
1974 case LibFunc::strncmp:
1975 return optimizeStrNCmp(CI, Builder);
1976 case LibFunc::strcpy:
1977 return optimizeStrCpy(CI, Builder);
1978 case LibFunc::stpcpy:
1979 return optimizeStpCpy(CI, Builder);
1980 case LibFunc::strncpy:
1981 return optimizeStrNCpy(CI, Builder);
1982 case LibFunc::strlen:
1983 return optimizeStrLen(CI, Builder);
1984 case LibFunc::strpbrk:
1985 return optimizeStrPBrk(CI, Builder);
1986 case LibFunc::strtol:
1987 case LibFunc::strtod:
1988 case LibFunc::strtof:
1989 case LibFunc::strtoul:
1990 case LibFunc::strtoll:
1991 case LibFunc::strtold:
1992 case LibFunc::strtoull:
1993 return optimizeStrTo(CI, Builder);
1994 case LibFunc::strspn:
1995 return optimizeStrSpn(CI, Builder);
1996 case LibFunc::strcspn:
1997 return optimizeStrCSpn(CI, Builder);
1998 case LibFunc::strstr:
1999 return optimizeStrStr(CI, Builder);
Benjamin Kramer691363e2015-03-21 15:36:21 +00002000 case LibFunc::memchr:
2001 return optimizeMemChr(CI, Builder);
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00002002 case LibFunc::memcmp:
2003 return optimizeMemCmp(CI, Builder);
2004 case LibFunc::memcpy:
2005 return optimizeMemCpy(CI, Builder);
2006 case LibFunc::memmove:
2007 return optimizeMemMove(CI, Builder);
2008 case LibFunc::memset:
2009 return optimizeMemSet(CI, Builder);
2010 default:
2011 break;
2012 }
2013 }
2014 return nullptr;
2015}
2016
Chris Bienemanad070d02014-09-17 20:55:46 +00002017Value *LibCallSimplifier::optimizeCall(CallInst *CI) {
2018 if (CI->isNoBuiltin())
2019 return nullptr;
Meador Inge4d2827c2012-11-11 05:11:20 +00002020
Meador Inge20255ef2013-03-12 00:08:29 +00002021 LibFunc::Func Func;
2022 Function *Callee = CI->getCalledFunction();
2023 StringRef FuncName = Callee->getName();
Chris Bienemanad070d02014-09-17 20:55:46 +00002024 IRBuilder<> Builder(CI);
2025 bool isCallingConvC = CI->getCallingConv() == llvm::CallingConv::C;
Meador Inge20255ef2013-03-12 00:08:29 +00002026
Sanjay Patela92fa442014-10-22 15:29:23 +00002027 // Command-line parameter overrides function attribute.
2028 if (EnableUnsafeFPShrink.getNumOccurrences() > 0)
2029 UnsafeFPShrink = EnableUnsafeFPShrink;
Davide Italianoa904e522015-10-29 02:58:44 +00002030 else if (canUseUnsafeFPMath(Callee))
2031 UnsafeFPShrink = true;
Sanjay Patela92fa442014-10-22 15:29:23 +00002032
Sanjay Patel848309d2014-10-23 21:52:45 +00002033 // First, check for intrinsics.
Meador Inge20255ef2013-03-12 00:08:29 +00002034 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(CI)) {
Chris Bienemanad070d02014-09-17 20:55:46 +00002035 if (!isCallingConvC)
2036 return nullptr;
Meador Inge20255ef2013-03-12 00:08:29 +00002037 switch (II->getIntrinsicID()) {
2038 case Intrinsic::pow:
Chris Bienemanad070d02014-09-17 20:55:46 +00002039 return optimizePow(CI, Builder);
Meador Inge20255ef2013-03-12 00:08:29 +00002040 case Intrinsic::exp2:
Chris Bienemanad070d02014-09-17 20:55:46 +00002041 return optimizeExp2(CI, Builder);
Sanjay Patel0ca42bb2014-10-14 20:43:11 +00002042 case Intrinsic::fabs:
2043 return optimizeFabs(CI, Builder);
Sanjay Patelc699a612014-10-16 18:48:17 +00002044 case Intrinsic::sqrt:
2045 return optimizeSqrt(CI, Builder);
Meador Inge20255ef2013-03-12 00:08:29 +00002046 default:
Chris Bienemanad070d02014-09-17 20:55:46 +00002047 return nullptr;
Meador Inge20255ef2013-03-12 00:08:29 +00002048 }
2049 }
2050
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002051 // Also try to simplify calls to fortified library functions.
2052 if (Value *SimplifiedFortifiedCI = FortifiedSimplifier.optimizeCall(CI)) {
2053 // Try to further simplify the result.
Ahmed Bougacha71d7b182015-01-14 00:55:05 +00002054 CallInst *SimplifiedCI = dyn_cast<CallInst>(SimplifiedFortifiedCI);
Bruno Cardoso Lopesb491a2d2015-10-01 22:43:53 +00002055 if (SimplifiedCI && SimplifiedCI->getCalledFunction()) {
2056 // Use an IR Builder from SimplifiedCI if available instead of CI
2057 // to guarantee we reach all uses we might replace later on.
2058 IRBuilder<> TmpBuilder(SimplifiedCI);
2059 if (Value *V = optimizeStringMemoryLibCall(SimplifiedCI, TmpBuilder)) {
Ahmed Bougacha1ac93562015-01-27 21:52:16 +00002060 // If we were able to further simplify, remove the now redundant call.
2061 SimplifiedCI->replaceAllUsesWith(V);
2062 SimplifiedCI->eraseFromParent();
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002063 return V;
Ahmed Bougacha1ac93562015-01-27 21:52:16 +00002064 }
Bruno Cardoso Lopesb491a2d2015-10-01 22:43:53 +00002065 }
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002066 return SimplifiedFortifiedCI;
2067 }
2068
Meador Inge20255ef2013-03-12 00:08:29 +00002069 // Then check for known library functions.
2070 if (TLI->getLibFunc(FuncName, Func) && TLI->has(Func)) {
Chris Bienemanad070d02014-09-17 20:55:46 +00002071 // We never change the calling convention.
2072 if (!ignoreCallingConv(Func) && !isCallingConvC)
2073 return nullptr;
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00002074 if (Value *V = optimizeStringMemoryLibCall(CI, Builder))
2075 return V;
Meador Inge20255ef2013-03-12 00:08:29 +00002076 switch (Func) {
Chris Bienemanad070d02014-09-17 20:55:46 +00002077 case LibFunc::cosf:
2078 case LibFunc::cos:
2079 case LibFunc::cosl:
2080 return optimizeCos(CI, Builder);
2081 case LibFunc::sinpif:
2082 case LibFunc::sinpi:
2083 case LibFunc::cospif:
2084 case LibFunc::cospi:
2085 return optimizeSinCosPi(CI, Builder);
2086 case LibFunc::powf:
2087 case LibFunc::pow:
2088 case LibFunc::powl:
2089 return optimizePow(CI, Builder);
2090 case LibFunc::exp2l:
2091 case LibFunc::exp2:
2092 case LibFunc::exp2f:
2093 return optimizeExp2(CI, Builder);
Sanjay Patel0ca42bb2014-10-14 20:43:11 +00002094 case LibFunc::fabsf:
2095 case LibFunc::fabs:
2096 case LibFunc::fabsl:
2097 return optimizeFabs(CI, Builder);
Sanjay Patelc699a612014-10-16 18:48:17 +00002098 case LibFunc::sqrtf:
2099 case LibFunc::sqrt:
2100 case LibFunc::sqrtl:
2101 return optimizeSqrt(CI, Builder);
Chris Bienemanad070d02014-09-17 20:55:46 +00002102 case LibFunc::ffs:
2103 case LibFunc::ffsl:
2104 case LibFunc::ffsll:
2105 return optimizeFFS(CI, Builder);
2106 case LibFunc::abs:
2107 case LibFunc::labs:
2108 case LibFunc::llabs:
2109 return optimizeAbs(CI, Builder);
2110 case LibFunc::isdigit:
2111 return optimizeIsDigit(CI, Builder);
2112 case LibFunc::isascii:
2113 return optimizeIsAscii(CI, Builder);
2114 case LibFunc::toascii:
2115 return optimizeToAscii(CI, Builder);
2116 case LibFunc::printf:
2117 return optimizePrintF(CI, Builder);
2118 case LibFunc::sprintf:
2119 return optimizeSPrintF(CI, Builder);
2120 case LibFunc::fprintf:
2121 return optimizeFPrintF(CI, Builder);
2122 case LibFunc::fwrite:
2123 return optimizeFWrite(CI, Builder);
2124 case LibFunc::fputs:
2125 return optimizeFPuts(CI, Builder);
2126 case LibFunc::puts:
2127 return optimizePuts(CI, Builder);
2128 case LibFunc::perror:
2129 return optimizeErrorReporting(CI, Builder);
2130 case LibFunc::vfprintf:
2131 case LibFunc::fiprintf:
2132 return optimizeErrorReporting(CI, Builder, 0);
2133 case LibFunc::fputc:
2134 return optimizeErrorReporting(CI, Builder, 1);
2135 case LibFunc::ceil:
Chris Bienemanad070d02014-09-17 20:55:46 +00002136 case LibFunc::floor:
2137 case LibFunc::rint:
2138 case LibFunc::round:
2139 case LibFunc::nearbyint:
2140 case LibFunc::trunc:
2141 if (hasFloatVersion(FuncName))
2142 return optimizeUnaryDoubleFP(CI, Builder, false);
2143 return nullptr;
2144 case LibFunc::acos:
2145 case LibFunc::acosh:
2146 case LibFunc::asin:
2147 case LibFunc::asinh:
2148 case LibFunc::atan:
2149 case LibFunc::atanh:
2150 case LibFunc::cbrt:
2151 case LibFunc::cosh:
2152 case LibFunc::exp:
2153 case LibFunc::exp10:
2154 case LibFunc::expm1:
2155 case LibFunc::log:
2156 case LibFunc::log10:
2157 case LibFunc::log1p:
2158 case LibFunc::log2:
2159 case LibFunc::logb:
2160 case LibFunc::sin:
2161 case LibFunc::sinh:
Chris Bienemanad070d02014-09-17 20:55:46 +00002162 case LibFunc::tan:
2163 case LibFunc::tanh:
2164 if (UnsafeFPShrink && hasFloatVersion(FuncName))
2165 return optimizeUnaryDoubleFP(CI, Builder, true);
2166 return nullptr;
Matthias Braun892c9232014-12-03 21:46:29 +00002167 case LibFunc::copysign:
Chris Bienemanad070d02014-09-17 20:55:46 +00002168 if (hasFloatVersion(FuncName))
2169 return optimizeBinaryDoubleFP(CI, Builder);
2170 return nullptr;
Sanjay Patel57fd1dc2015-08-16 20:18:19 +00002171 case LibFunc::fminf:
2172 case LibFunc::fmin:
2173 case LibFunc::fminl:
2174 case LibFunc::fmaxf:
2175 case LibFunc::fmax:
2176 case LibFunc::fmaxl:
2177 return optimizeFMinFMax(CI, Builder);
Chris Bienemanad070d02014-09-17 20:55:46 +00002178 default:
2179 return nullptr;
2180 }
Meador Inge20255ef2013-03-12 00:08:29 +00002181 }
Craig Topperf40110f2014-04-25 05:29:35 +00002182 return nullptr;
Meador Ingedf796f82012-10-13 16:45:24 +00002183}
2184
Chandler Carruth92803822015-01-21 02:11:59 +00002185LibCallSimplifier::LibCallSimplifier(
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002186 const DataLayout &DL, const TargetLibraryInfo *TLI,
Chandler Carruth92803822015-01-21 02:11:59 +00002187 function_ref<void(Instruction *, Value *)> Replacer)
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002188 : FortifiedSimplifier(TLI), DL(DL), TLI(TLI), UnsafeFPShrink(false),
Chandler Carruth92803822015-01-21 02:11:59 +00002189 Replacer(Replacer) {}
2190
2191void LibCallSimplifier::replaceAllUsesWith(Instruction *I, Value *With) {
2192 // Indirect through the replacer used in this instance.
2193 Replacer(I, With);
Meador Ingedf796f82012-10-13 16:45:24 +00002194}
2195
Meador Ingedfb08a22013-06-20 19:48:07 +00002196// TODO:
2197// Additional cases that we need to add to this file:
2198//
2199// cbrt:
2200// * cbrt(expN(X)) -> expN(x/3)
2201// * cbrt(sqrt(x)) -> pow(x,1/6)
David Majnemer3354fe42015-08-26 18:30:16 +00002202// * cbrt(cbrt(x)) -> pow(x,1/9)
Meador Ingedfb08a22013-06-20 19:48:07 +00002203//
2204// exp, expf, expl:
2205// * exp(log(x)) -> x
2206//
2207// log, logf, logl:
2208// * log(exp(x)) -> x
2209// * log(x**y) -> y*log(x)
2210// * log(exp(y)) -> y*log(e)
2211// * log(exp2(y)) -> y*log(2)
2212// * log(exp10(y)) -> y*log(10)
2213// * log(sqrt(x)) -> 0.5*log(x)
2214// * log(pow(x,y)) -> y*log(x)
2215//
2216// lround, lroundf, lroundl:
2217// * lround(cnst) -> cnst'
2218//
2219// pow, powf, powl:
2220// * pow(exp(x),y) -> exp(x*y)
2221// * pow(sqrt(x),y) -> pow(x,y*0.5)
2222// * pow(pow(x,y),z)-> pow(x,y*z)
2223//
2224// round, roundf, roundl:
2225// * round(cnst) -> cnst'
2226//
2227// signbit:
2228// * signbit(cnst) -> cnst'
2229// * signbit(nncst) -> 0 (if pstv is a non-negative constant)
2230//
2231// sqrt, sqrtf, sqrtl:
2232// * sqrt(expN(x)) -> expN(x*0.5)
2233// * sqrt(Nroot(x)) -> pow(x,1/(2*N))
2234// * sqrt(pow(x,y)) -> pow(|x|,y*0.5)
2235//
Meador Ingedfb08a22013-06-20 19:48:07 +00002236// tan, tanf, tanl:
2237// * tan(atan(x)) -> x
2238//
2239// trunc, truncf, truncl:
2240// * trunc(cnst) -> cnst'
2241//
2242//
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002243
2244//===----------------------------------------------------------------------===//
2245// Fortified Library Call Optimizations
2246//===----------------------------------------------------------------------===//
2247
2248bool FortifiedLibCallSimplifier::isFortifiedCallFoldable(CallInst *CI,
2249 unsigned ObjSizeOp,
2250 unsigned SizeOp,
2251 bool isString) {
2252 if (CI->getArgOperand(ObjSizeOp) == CI->getArgOperand(SizeOp))
2253 return true;
2254 if (ConstantInt *ObjSizeCI =
2255 dyn_cast<ConstantInt>(CI->getArgOperand(ObjSizeOp))) {
2256 if (ObjSizeCI->isAllOnesValue())
2257 return true;
2258 // If the object size wasn't -1 (unknown), bail out if we were asked to.
2259 if (OnlyLowerUnknownSize)
2260 return false;
2261 if (isString) {
2262 uint64_t Len = GetStringLength(CI->getArgOperand(SizeOp));
2263 // If the length is 0 we don't know how long it is and so we can't
2264 // remove the check.
2265 if (Len == 0)
2266 return false;
2267 return ObjSizeCI->getZExtValue() >= Len;
2268 }
2269 if (ConstantInt *SizeCI = dyn_cast<ConstantInt>(CI->getArgOperand(SizeOp)))
2270 return ObjSizeCI->getZExtValue() >= SizeCI->getZExtValue();
2271 }
2272 return false;
2273}
2274
2275Value *FortifiedLibCallSimplifier::optimizeMemCpyChk(CallInst *CI, IRBuilder<> &B) {
2276 Function *Callee = CI->getCalledFunction();
2277
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002278 if (!checkStringCopyLibFuncSignature(Callee, LibFunc::memcpy_chk))
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002279 return nullptr;
2280
2281 if (isFortifiedCallFoldable(CI, 3, 2, false)) {
2282 B.CreateMemCpy(CI->getArgOperand(0), CI->getArgOperand(1),
2283 CI->getArgOperand(2), 1);
2284 return CI->getArgOperand(0);
2285 }
2286 return nullptr;
2287}
2288
2289Value *FortifiedLibCallSimplifier::optimizeMemMoveChk(CallInst *CI, IRBuilder<> &B) {
2290 Function *Callee = CI->getCalledFunction();
2291
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002292 if (!checkStringCopyLibFuncSignature(Callee, LibFunc::memmove_chk))
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002293 return nullptr;
2294
2295 if (isFortifiedCallFoldable(CI, 3, 2, false)) {
2296 B.CreateMemMove(CI->getArgOperand(0), CI->getArgOperand(1),
2297 CI->getArgOperand(2), 1);
2298 return CI->getArgOperand(0);
2299 }
2300 return nullptr;
2301}
2302
2303Value *FortifiedLibCallSimplifier::optimizeMemSetChk(CallInst *CI, IRBuilder<> &B) {
2304 Function *Callee = CI->getCalledFunction();
2305
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002306 if (!checkStringCopyLibFuncSignature(Callee, LibFunc::memset_chk))
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002307 return nullptr;
2308
2309 if (isFortifiedCallFoldable(CI, 3, 2, false)) {
2310 Value *Val = B.CreateIntCast(CI->getArgOperand(1), B.getInt8Ty(), false);
2311 B.CreateMemSet(CI->getArgOperand(0), Val, CI->getArgOperand(2), 1);
2312 return CI->getArgOperand(0);
2313 }
2314 return nullptr;
2315}
2316
Ahmed Bougacha1ac93562015-01-27 21:52:16 +00002317Value *FortifiedLibCallSimplifier::optimizeStrpCpyChk(CallInst *CI,
2318 IRBuilder<> &B,
2319 LibFunc::Func Func) {
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002320 Function *Callee = CI->getCalledFunction();
2321 StringRef Name = Callee->getName();
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002322 const DataLayout &DL = CI->getModule()->getDataLayout();
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002323
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002324 if (!checkStringCopyLibFuncSignature(Callee, Func))
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002325 return nullptr;
2326
2327 Value *Dst = CI->getArgOperand(0), *Src = CI->getArgOperand(1),
2328 *ObjSize = CI->getArgOperand(2);
2329
2330 // __stpcpy_chk(x,x,...) -> x+strlen(x)
Ahmed Bougacha1ac93562015-01-27 21:52:16 +00002331 if (Func == LibFunc::stpcpy_chk && !OnlyLowerUnknownSize && Dst == Src) {
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002332 Value *StrLen = EmitStrLen(Src, B, DL, TLI);
David Blaikieaa41cd52015-04-03 21:33:42 +00002333 return StrLen ? B.CreateInBoundsGEP(B.getInt8Ty(), Dst, StrLen) : nullptr;
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002334 }
2335
2336 // If a) we don't have any length information, or b) we know this will
2337 // fit then just lower to a plain st[rp]cpy. Otherwise we'll keep our
2338 // st[rp]cpy_chk call which may fail at runtime if the size is too long.
2339 // TODO: It might be nice to get a maximum length out of the possible
2340 // string lengths for varying.
David Blaikie65fab6d2015-04-03 21:32:06 +00002341 if (isFortifiedCallFoldable(CI, 2, 1, true))
2342 return EmitStrCpy(Dst, Src, B, TLI, Name.substr(2, 6));
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002343
David Blaikie65fab6d2015-04-03 21:32:06 +00002344 if (OnlyLowerUnknownSize)
2345 return nullptr;
2346
2347 // Maybe we can stil fold __st[rp]cpy_chk to __memcpy_chk.
2348 uint64_t Len = GetStringLength(Src);
2349 if (Len == 0)
2350 return nullptr;
2351
2352 Type *SizeTTy = DL.getIntPtrType(CI->getContext());
2353 Value *LenV = ConstantInt::get(SizeTTy, Len);
2354 Value *Ret = EmitMemCpyChk(Dst, Src, LenV, ObjSize, B, DL, TLI);
2355 // If the function was an __stpcpy_chk, and we were able to fold it into
2356 // a __memcpy_chk, we still need to return the correct end pointer.
2357 if (Ret && Func == LibFunc::stpcpy_chk)
2358 return B.CreateGEP(B.getInt8Ty(), Dst, ConstantInt::get(SizeTTy, Len - 1));
2359 return Ret;
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002360}
2361
Ahmed Bougacha1ac93562015-01-27 21:52:16 +00002362Value *FortifiedLibCallSimplifier::optimizeStrpNCpyChk(CallInst *CI,
2363 IRBuilder<> &B,
2364 LibFunc::Func Func) {
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002365 Function *Callee = CI->getCalledFunction();
2366 StringRef Name = Callee->getName();
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002367
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002368 if (!checkStringCopyLibFuncSignature(Callee, Func))
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002369 return nullptr;
2370 if (isFortifiedCallFoldable(CI, 3, 2, false)) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002371 Value *Ret = EmitStrNCpy(CI->getArgOperand(0), CI->getArgOperand(1),
2372 CI->getArgOperand(2), B, TLI, Name.substr(2, 7));
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002373 return Ret;
2374 }
2375 return nullptr;
2376}
2377
2378Value *FortifiedLibCallSimplifier::optimizeCall(CallInst *CI) {
Ahmed Bougacha408d0102015-04-01 00:45:09 +00002379 // FIXME: We shouldn't be changing "nobuiltin" or TLI unavailable calls here.
2380 // Some clang users checked for _chk libcall availability using:
2381 // __has_builtin(__builtin___memcpy_chk)
2382 // When compiling with -fno-builtin, this is always true.
2383 // When passing -ffreestanding/-mkernel, which both imply -fno-builtin, we
2384 // end up with fortified libcalls, which isn't acceptable in a freestanding
2385 // environment which only provides their non-fortified counterparts.
2386 //
2387 // Until we change clang and/or teach external users to check for availability
2388 // differently, disregard the "nobuiltin" attribute and TLI::has.
2389 //
2390 // PR23093.
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002391
2392 LibFunc::Func Func;
2393 Function *Callee = CI->getCalledFunction();
2394 StringRef FuncName = Callee->getName();
2395 IRBuilder<> Builder(CI);
2396 bool isCallingConvC = CI->getCallingConv() == llvm::CallingConv::C;
2397
2398 // First, check that this is a known library functions.
Ahmed Bougacha408d0102015-04-01 00:45:09 +00002399 if (!TLI->getLibFunc(FuncName, Func))
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002400 return nullptr;
2401
2402 // We never change the calling convention.
2403 if (!ignoreCallingConv(Func) && !isCallingConvC)
2404 return nullptr;
2405
2406 switch (Func) {
2407 case LibFunc::memcpy_chk:
2408 return optimizeMemCpyChk(CI, Builder);
2409 case LibFunc::memmove_chk:
2410 return optimizeMemMoveChk(CI, Builder);
2411 case LibFunc::memset_chk:
2412 return optimizeMemSetChk(CI, Builder);
2413 case LibFunc::stpcpy_chk:
2414 case LibFunc::strcpy_chk:
Ahmed Bougacha1ac93562015-01-27 21:52:16 +00002415 return optimizeStrpCpyChk(CI, Builder, Func);
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002416 case LibFunc::stpncpy_chk:
2417 case LibFunc::strncpy_chk:
Ahmed Bougacha1ac93562015-01-27 21:52:16 +00002418 return optimizeStrpNCpyChk(CI, Builder, Func);
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002419 default:
2420 break;
2421 }
2422 return nullptr;
2423}
2424
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002425FortifiedLibCallSimplifier::FortifiedLibCallSimplifier(
2426 const TargetLibraryInfo *TLI, bool OnlyLowerUnknownSize)
2427 : TLI(TLI), OnlyLowerUnknownSize(OnlyLowerUnknownSize) {}