blob: 9fac7ef540eeea799a6232d901934e70b0bbc173 [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"
Nadav Rotem464e8072013-02-27 05:53:43 +000030#include "llvm/Support/Allocator.h"
Hal Finkel66cd3f12013-11-17 02:06:35 +000031#include "llvm/Support/CommandLine.h"
Meador Ingedf796f82012-10-13 16:45:24 +000032#include "llvm/Target/TargetLibraryInfo.h"
33#include "llvm/Transforms/Utils/BuildLibCalls.h"
34
35using namespace llvm;
36
Hal Finkel66cd3f12013-11-17 02:06:35 +000037static cl::opt<bool>
Chris Bienemanad070d02014-09-17 20:55:46 +000038 ColdErrorCalls("error-reporting-is-cold", cl::init(true), cl::Hidden,
39 cl::desc("Treat error-reporting calls as cold"));
Meador Ingedf796f82012-10-13 16:45:24 +000040
41//===----------------------------------------------------------------------===//
Meador Inged589ac62012-10-31 03:33:06 +000042// Helper Functions
43//===----------------------------------------------------------------------===//
44
Chris Bienemanad070d02014-09-17 20:55:46 +000045static bool ignoreCallingConv(LibFunc::Func Func) {
46 switch (Func) {
47 case LibFunc::abs:
48 case LibFunc::labs:
49 case LibFunc::llabs:
50 case LibFunc::strlen:
51 return true;
52 default:
53 return false;
54 }
Chris Bienemancf93cbb2014-09-17 21:06:59 +000055 llvm_unreachable("All cases should be covered in the switch.");
Chris Bienemanad070d02014-09-17 20:55:46 +000056}
57
Meador Inged589ac62012-10-31 03:33:06 +000058/// isOnlyUsedInZeroEqualityComparison - Return true if it only matters that the
59/// value is equal or not-equal to zero.
60static bool isOnlyUsedInZeroEqualityComparison(Value *V) {
Chandler Carruthcdf47882014-03-09 03:16:01 +000061 for (User *U : V->users()) {
62 if (ICmpInst *IC = dyn_cast<ICmpInst>(U))
Meador Inged589ac62012-10-31 03:33:06 +000063 if (IC->isEquality())
64 if (Constant *C = dyn_cast<Constant>(IC->getOperand(1)))
65 if (C->isNullValue())
66 continue;
67 // Unknown instruction.
68 return false;
69 }
70 return true;
71}
72
Meador Inge56edbc92012-11-11 03:51:48 +000073/// isOnlyUsedInEqualityComparison - Return true if it is only used in equality
74/// comparisons with With.
75static bool isOnlyUsedInEqualityComparison(Value *V, Value *With) {
Chandler Carruthcdf47882014-03-09 03:16:01 +000076 for (User *U : V->users()) {
77 if (ICmpInst *IC = dyn_cast<ICmpInst>(U))
Meador Inge56edbc92012-11-11 03:51:48 +000078 if (IC->isEquality() && IC->getOperand(1) == With)
79 continue;
80 // Unknown instruction.
81 return false;
82 }
83 return true;
84}
85
Meador Inge08ca1152012-11-26 20:37:20 +000086static bool callHasFloatingPointArgument(const CallInst *CI) {
87 for (CallInst::const_op_iterator it = CI->op_begin(), e = CI->op_end();
88 it != e; ++it) {
89 if ((*it)->getType()->isFloatingPointTy())
90 return true;
91 }
92 return false;
93}
94
Benjamin Kramer2702caa2013-08-31 18:19:35 +000095/// \brief Check whether the overloaded unary floating point function
96/// corresponing to \a Ty is available.
97static bool hasUnaryFloatFn(const TargetLibraryInfo *TLI, Type *Ty,
98 LibFunc::Func DoubleFn, LibFunc::Func FloatFn,
99 LibFunc::Func LongDoubleFn) {
100 switch (Ty->getTypeID()) {
101 case Type::FloatTyID:
102 return TLI->has(FloatFn);
103 case Type::DoubleTyID:
104 return TLI->has(DoubleFn);
105 default:
106 return TLI->has(LongDoubleFn);
107 }
108}
109
Meador Inged589ac62012-10-31 03:33:06 +0000110//===----------------------------------------------------------------------===//
Meador Ingedf796f82012-10-13 16:45:24 +0000111// Fortified Library Call Optimizations
112//===----------------------------------------------------------------------===//
113
Chris Bienemanad070d02014-09-17 20:55:46 +0000114static bool isFortifiedCallFoldable(CallInst *CI, unsigned SizeCIOp, unsigned SizeArgOp,
115 bool isString) {
116 if (CI->getArgOperand(SizeCIOp) == CI->getArgOperand(SizeArgOp))
117 return true;
118 if (ConstantInt *SizeCI =
119 dyn_cast<ConstantInt>(CI->getArgOperand(SizeCIOp))) {
120 if (SizeCI->isAllOnesValue())
Meador Ingedf796f82012-10-13 16:45:24 +0000121 return true;
Chris Bienemanad070d02014-09-17 20:55:46 +0000122 if (isString) {
123 uint64_t Len = GetStringLength(CI->getArgOperand(SizeArgOp));
124 // If the length is 0 we don't know how long it is and so we can't
125 // remove the check.
126 if (Len == 0)
127 return false;
128 return SizeCI->getZExtValue() >= Len;
Meador Ingedf796f82012-10-13 16:45:24 +0000129 }
Chris Bienemanad070d02014-09-17 20:55:46 +0000130 if (ConstantInt *Arg = dyn_cast<ConstantInt>(CI->getArgOperand(SizeArgOp)))
131 return SizeCI->getZExtValue() >= Arg->getZExtValue();
Meador Ingedf796f82012-10-13 16:45:24 +0000132 }
Chris Bienemanad070d02014-09-17 20:55:46 +0000133 return false;
134}
Meador Ingedf796f82012-10-13 16:45:24 +0000135
Chris Bienemanad070d02014-09-17 20:55:46 +0000136Value *LibCallSimplifier::optimizeMemCpyChk(CallInst *CI, IRBuilder<> &B) {
137 Function *Callee = CI->getCalledFunction();
138 FunctionType *FT = Callee->getFunctionType();
139 LLVMContext &Context = CI->getContext();
Meador Ingedf796f82012-10-13 16:45:24 +0000140
Chris Bienemanad070d02014-09-17 20:55:46 +0000141 // Check if this has the right signature.
142 if (FT->getNumParams() != 4 || FT->getReturnType() != FT->getParamType(0) ||
143 !FT->getParamType(0)->isPointerTy() ||
144 !FT->getParamType(1)->isPointerTy() ||
145 FT->getParamType(2) != DL->getIntPtrType(Context) ||
146 FT->getParamType(3) != DL->getIntPtrType(Context))
147 return nullptr;
148
149 if (isFortifiedCallFoldable(CI, 3, 2, false)) {
150 B.CreateMemCpy(CI->getArgOperand(0), CI->getArgOperand(1),
151 CI->getArgOperand(2), 1);
152 return CI->getArgOperand(0);
153 }
154 return nullptr;
155}
156
157Value *LibCallSimplifier::optimizeMemMoveChk(CallInst *CI, IRBuilder<> &B) {
158 Function *Callee = CI->getCalledFunction();
159 FunctionType *FT = Callee->getFunctionType();
160 LLVMContext &Context = CI->getContext();
161
162 // Check if this has the right signature.
163 if (FT->getNumParams() != 4 || FT->getReturnType() != FT->getParamType(0) ||
164 !FT->getParamType(0)->isPointerTy() ||
165 !FT->getParamType(1)->isPointerTy() ||
166 FT->getParamType(2) != DL->getIntPtrType(Context) ||
167 FT->getParamType(3) != DL->getIntPtrType(Context))
168 return nullptr;
169
170 if (isFortifiedCallFoldable(CI, 3, 2, false)) {
171 B.CreateMemMove(CI->getArgOperand(0), CI->getArgOperand(1),
172 CI->getArgOperand(2), 1);
173 return CI->getArgOperand(0);
174 }
175 return nullptr;
176}
177
178Value *LibCallSimplifier::optimizeMemSetChk(CallInst *CI, IRBuilder<> &B) {
179 Function *Callee = CI->getCalledFunction();
180 FunctionType *FT = Callee->getFunctionType();
181 LLVMContext &Context = CI->getContext();
182
183 // Check if this has the right signature.
184 if (FT->getNumParams() != 4 || FT->getReturnType() != FT->getParamType(0) ||
185 !FT->getParamType(0)->isPointerTy() ||
186 !FT->getParamType(1)->isIntegerTy() ||
187 FT->getParamType(2) != DL->getIntPtrType(Context) ||
188 FT->getParamType(3) != DL->getIntPtrType(Context))
189 return nullptr;
190
191 if (isFortifiedCallFoldable(CI, 3, 2, false)) {
192 Value *Val = B.CreateIntCast(CI->getArgOperand(1), B.getInt8Ty(), false);
193 B.CreateMemSet(CI->getArgOperand(0), Val, CI->getArgOperand(2), 1);
194 return CI->getArgOperand(0);
195 }
196 return nullptr;
197}
198
199Value *LibCallSimplifier::optimizeStrCpyChk(CallInst *CI, IRBuilder<> &B) {
200 Function *Callee = CI->getCalledFunction();
201 StringRef Name = Callee->getName();
202 FunctionType *FT = Callee->getFunctionType();
203 LLVMContext &Context = CI->getContext();
204
205 // Check if this has the right signature.
206 if (FT->getNumParams() != 3 || FT->getReturnType() != FT->getParamType(0) ||
207 FT->getParamType(0) != FT->getParamType(1) ||
208 FT->getParamType(0) != Type::getInt8PtrTy(Context) ||
209 FT->getParamType(2) != DL->getIntPtrType(Context))
210 return nullptr;
211
212 Value *Dst = CI->getArgOperand(0), *Src = CI->getArgOperand(1);
213 if (Dst == Src) // __strcpy_chk(x,x) -> x
214 return Src;
215
216 // If a) we don't have any length information, or b) we know this will
217 // fit then just lower to a plain strcpy. Otherwise we'll keep our
218 // strcpy_chk call which may fail at runtime if the size is too long.
219 // TODO: It might be nice to get a maximum length out of the possible
220 // string lengths for varying.
221 if (isFortifiedCallFoldable(CI, 2, 1, true)) {
222 Value *Ret = EmitStrCpy(Dst, Src, B, DL, TLI, Name.substr(2, 6));
223 return Ret;
224 } else {
225 // Maybe we can stil fold __strcpy_chk to __memcpy_chk.
226 uint64_t Len = GetStringLength(Src);
227 if (Len == 0)
Craig Topperf40110f2014-04-25 05:29:35 +0000228 return nullptr;
Meador Ingedf796f82012-10-13 16:45:24 +0000229
Chris Bienemanad070d02014-09-17 20:55:46 +0000230 // This optimization require DataLayout.
231 if (!DL)
Craig Topperf40110f2014-04-25 05:29:35 +0000232 return nullptr;
Meador Ingedf796f82012-10-13 16:45:24 +0000233
Chris Bienemanad070d02014-09-17 20:55:46 +0000234 Value *Ret = EmitMemCpyChk(
235 Dst, Src, ConstantInt::get(DL->getIntPtrType(Context), Len),
236 CI->getArgOperand(2), B, DL, TLI);
237 return Ret;
Meador Ingedf796f82012-10-13 16:45:24 +0000238 }
Chris Bienemanad070d02014-09-17 20:55:46 +0000239 return nullptr;
240}
Meador Ingedf796f82012-10-13 16:45:24 +0000241
Chris Bienemanad070d02014-09-17 20:55:46 +0000242Value *LibCallSimplifier::optimizeStpCpyChk(CallInst *CI, IRBuilder<> &B) {
243 Function *Callee = CI->getCalledFunction();
244 StringRef Name = Callee->getName();
245 FunctionType *FT = Callee->getFunctionType();
246 LLVMContext &Context = CI->getContext();
Meador Ingedf796f82012-10-13 16:45:24 +0000247
Chris Bienemanad070d02014-09-17 20:55:46 +0000248 // Check if this has the right signature.
249 if (FT->getNumParams() != 3 || FT->getReturnType() != FT->getParamType(0) ||
250 FT->getParamType(0) != FT->getParamType(1) ||
251 FT->getParamType(0) != Type::getInt8PtrTy(Context) ||
252 FT->getParamType(2) != DL->getIntPtrType(FT->getParamType(0)))
253 return nullptr;
254
255 Value *Dst = CI->getArgOperand(0), *Src = CI->getArgOperand(1);
256 if (Dst == Src) { // stpcpy(x,x) -> x+strlen(x)
257 Value *StrLen = EmitStrLen(Src, B, DL, TLI);
258 return StrLen ? B.CreateInBoundsGEP(Dst, StrLen) : nullptr;
259 }
260
261 // If a) we don't have any length information, or b) we know this will
262 // fit then just lower to a plain stpcpy. Otherwise we'll keep our
263 // stpcpy_chk call which may fail at runtime if the size is too long.
264 // TODO: It might be nice to get a maximum length out of the possible
265 // string lengths for varying.
266 if (isFortifiedCallFoldable(CI, 2, 1, true)) {
267 Value *Ret = EmitStrCpy(Dst, Src, B, DL, TLI, Name.substr(2, 6));
268 return Ret;
269 } else {
270 // Maybe we can stil fold __stpcpy_chk to __memcpy_chk.
271 uint64_t Len = GetStringLength(Src);
272 if (Len == 0)
Craig Topperf40110f2014-04-25 05:29:35 +0000273 return nullptr;
Meador Ingedf796f82012-10-13 16:45:24 +0000274
Chris Bienemanad070d02014-09-17 20:55:46 +0000275 // This optimization require DataLayout.
276 if (!DL)
Craig Topperf40110f2014-04-25 05:29:35 +0000277 return nullptr;
Meador Ingedf796f82012-10-13 16:45:24 +0000278
Chris Bienemanad070d02014-09-17 20:55:46 +0000279 Type *PT = FT->getParamType(0);
280 Value *LenV = ConstantInt::get(DL->getIntPtrType(PT), Len);
281 Value *DstEnd =
282 B.CreateGEP(Dst, ConstantInt::get(DL->getIntPtrType(PT), Len - 1));
283 if (!EmitMemCpyChk(Dst, Src, LenV, CI->getArgOperand(2), B, DL, TLI))
Craig Topperf40110f2014-04-25 05:29:35 +0000284 return nullptr;
Chris Bienemanad070d02014-09-17 20:55:46 +0000285 return DstEnd;
Meador Ingecdb2ca52012-10-31 00:20:51 +0000286 }
Chris Bienemanad070d02014-09-17 20:55:46 +0000287 return nullptr;
288}
Meador Ingecdb2ca52012-10-31 00:20:51 +0000289
Chris Bienemanad070d02014-09-17 20:55:46 +0000290Value *LibCallSimplifier::optimizeStrNCpyChk(CallInst *CI, IRBuilder<> &B) {
291 Function *Callee = CI->getCalledFunction();
292 StringRef Name = Callee->getName();
293 FunctionType *FT = Callee->getFunctionType();
294 LLVMContext &Context = CI->getContext();
Meador Ingedf796f82012-10-13 16:45:24 +0000295
Chris Bienemanad070d02014-09-17 20:55:46 +0000296 // Check if this has the right signature.
297 if (FT->getNumParams() != 4 || FT->getReturnType() != FT->getParamType(0) ||
298 FT->getParamType(0) != FT->getParamType(1) ||
299 FT->getParamType(0) != Type::getInt8PtrTy(Context) ||
300 !FT->getParamType(2)->isIntegerTy() ||
301 FT->getParamType(3) != DL->getIntPtrType(Context))
Craig Topperf40110f2014-04-25 05:29:35 +0000302 return nullptr;
Chris Bienemanad070d02014-09-17 20:55:46 +0000303
304 if (isFortifiedCallFoldable(CI, 3, 2, false)) {
305 Value *Ret =
306 EmitStrNCpy(CI->getArgOperand(0), CI->getArgOperand(1),
307 CI->getArgOperand(2), B, DL, TLI, Name.substr(2, 7));
308 return Ret;
Meador Ingedf796f82012-10-13 16:45:24 +0000309 }
Chris Bienemanad070d02014-09-17 20:55:46 +0000310 return nullptr;
311}
Meador Ingedf796f82012-10-13 16:45:24 +0000312
Meador Inge7fb2f732012-10-13 16:45:32 +0000313//===----------------------------------------------------------------------===//
314// String and Memory Library Call Optimizations
315//===----------------------------------------------------------------------===//
316
Chris Bienemanad070d02014-09-17 20:55:46 +0000317Value *LibCallSimplifier::optimizeStrCat(CallInst *CI, IRBuilder<> &B) {
318 Function *Callee = CI->getCalledFunction();
319 // Verify the "strcat" function prototype.
320 FunctionType *FT = Callee->getFunctionType();
321 if (FT->getNumParams() != 2||
322 FT->getReturnType() != B.getInt8PtrTy() ||
323 FT->getParamType(0) != FT->getReturnType() ||
324 FT->getParamType(1) != FT->getReturnType())
325 return nullptr;
326
327 // Extract some information from the instruction
328 Value *Dst = CI->getArgOperand(0);
329 Value *Src = CI->getArgOperand(1);
330
331 // See if we can get the length of the input string.
332 uint64_t Len = GetStringLength(Src);
333 if (Len == 0)
334 return nullptr;
335 --Len; // Unbias length.
336
337 // Handle the simple, do-nothing case: strcat(x, "") -> x
338 if (Len == 0)
339 return Dst;
340
341 // These optimizations require DataLayout.
342 if (!DL)
343 return nullptr;
344
345 return emitStrLenMemCpy(Src, Dst, Len, B);
346}
347
348Value *LibCallSimplifier::emitStrLenMemCpy(Value *Src, Value *Dst, uint64_t Len,
349 IRBuilder<> &B) {
350 // We need to find the end of the destination string. That's where the
351 // memory is to be moved to. We just generate a call to strlen.
352 Value *DstLen = EmitStrLen(Dst, B, DL, TLI);
353 if (!DstLen)
354 return nullptr;
355
356 // Now that we have the destination's length, we must index into the
357 // destination's pointer to get the actual memcpy destination (end of
358 // the string .. we're concatenating).
359 Value *CpyDst = B.CreateGEP(Dst, DstLen, "endptr");
360
361 // We have enough information to now generate the memcpy call to do the
362 // concatenation for us. Make a memcpy to copy the nul byte with align = 1.
363 B.CreateMemCpy(
364 CpyDst, Src,
365 ConstantInt::get(DL->getIntPtrType(Src->getContext()), Len + 1), 1);
366 return Dst;
367}
368
369Value *LibCallSimplifier::optimizeStrNCat(CallInst *CI, IRBuilder<> &B) {
370 Function *Callee = CI->getCalledFunction();
371 // Verify the "strncat" function prototype.
372 FunctionType *FT = Callee->getFunctionType();
373 if (FT->getNumParams() != 3 || FT->getReturnType() != B.getInt8PtrTy() ||
374 FT->getParamType(0) != FT->getReturnType() ||
375 FT->getParamType(1) != FT->getReturnType() ||
376 !FT->getParamType(2)->isIntegerTy())
377 return nullptr;
378
379 // Extract some information from the instruction
380 Value *Dst = CI->getArgOperand(0);
381 Value *Src = CI->getArgOperand(1);
382 uint64_t Len;
383
384 // We don't do anything if length is not constant
385 if (ConstantInt *LengthArg = dyn_cast<ConstantInt>(CI->getArgOperand(2)))
386 Len = LengthArg->getZExtValue();
387 else
388 return nullptr;
389
390 // See if we can get the length of the input string.
391 uint64_t SrcLen = GetStringLength(Src);
392 if (SrcLen == 0)
393 return nullptr;
394 --SrcLen; // Unbias length.
395
396 // Handle the simple, do-nothing cases:
397 // strncat(x, "", c) -> x
398 // strncat(x, c, 0) -> x
399 if (SrcLen == 0 || Len == 0)
400 return Dst;
401
402 // These optimizations require DataLayout.
403 if (!DL)
404 return nullptr;
405
406 // We don't optimize this case
407 if (Len < SrcLen)
408 return nullptr;
409
410 // strncat(x, s, c) -> strcat(x, s)
411 // s is constant so the strcat can be optimized further
412 return emitStrLenMemCpy(Src, Dst, SrcLen, B);
413}
414
415Value *LibCallSimplifier::optimizeStrChr(CallInst *CI, IRBuilder<> &B) {
416 Function *Callee = CI->getCalledFunction();
417 // Verify the "strchr" function prototype.
418 FunctionType *FT = Callee->getFunctionType();
419 if (FT->getNumParams() != 2 || FT->getReturnType() != B.getInt8PtrTy() ||
420 FT->getParamType(0) != FT->getReturnType() ||
421 !FT->getParamType(1)->isIntegerTy(32))
422 return nullptr;
423
424 Value *SrcStr = CI->getArgOperand(0);
425
426 // If the second operand is non-constant, see if we can compute the length
427 // of the input string and turn this into memchr.
428 ConstantInt *CharC = dyn_cast<ConstantInt>(CI->getArgOperand(1));
429 if (!CharC) {
430 // These optimizations require DataLayout.
431 if (!DL)
Craig Topperf40110f2014-04-25 05:29:35 +0000432 return nullptr;
Meador Inge7fb2f732012-10-13 16:45:32 +0000433
Chris Bienemanad070d02014-09-17 20:55:46 +0000434 uint64_t Len = GetStringLength(SrcStr);
435 if (Len == 0 || !FT->getParamType(1)->isIntegerTy(32)) // memchr needs i32.
436 return nullptr;
Meador Inge7fb2f732012-10-13 16:45:32 +0000437
Chris Bienemanad070d02014-09-17 20:55:46 +0000438 return EmitMemChr(
439 SrcStr, CI->getArgOperand(1), // include nul.
440 ConstantInt::get(DL->getIntPtrType(CI->getContext()), Len), B, DL, TLI);
Meador Inge7fb2f732012-10-13 16:45:32 +0000441 }
442
Chris Bienemanad070d02014-09-17 20:55:46 +0000443 // Otherwise, the character is a constant, see if the first argument is
444 // a string literal. If so, we can constant fold.
445 StringRef Str;
446 if (!getConstantStringInfo(SrcStr, Str)) {
447 if (DL && CharC->isZero()) // strchr(p, 0) -> p + strlen(p)
448 return B.CreateGEP(SrcStr, EmitStrLen(SrcStr, B, DL, TLI), "strchr");
449 return nullptr;
450 }
451
452 // Compute the offset, make sure to handle the case when we're searching for
453 // zero (a weird way to spell strlen).
454 size_t I = (0xFF & CharC->getSExtValue()) == 0
455 ? Str.size()
456 : Str.find(CharC->getSExtValue());
457 if (I == StringRef::npos) // Didn't find the char. strchr returns null.
458 return Constant::getNullValue(CI->getType());
459
460 // strchr(s+n,c) -> gep(s+n+i,c)
461 return B.CreateGEP(SrcStr, B.getInt64(I), "strchr");
462}
463
464Value *LibCallSimplifier::optimizeStrRChr(CallInst *CI, IRBuilder<> &B) {
465 Function *Callee = CI->getCalledFunction();
466 // Verify the "strrchr" function prototype.
467 FunctionType *FT = Callee->getFunctionType();
468 if (FT->getNumParams() != 2 || FT->getReturnType() != B.getInt8PtrTy() ||
469 FT->getParamType(0) != FT->getReturnType() ||
470 !FT->getParamType(1)->isIntegerTy(32))
471 return nullptr;
472
473 Value *SrcStr = CI->getArgOperand(0);
474 ConstantInt *CharC = dyn_cast<ConstantInt>(CI->getArgOperand(1));
475
476 // Cannot fold anything if we're not looking for a constant.
477 if (!CharC)
478 return nullptr;
479
480 StringRef Str;
481 if (!getConstantStringInfo(SrcStr, Str)) {
482 // strrchr(s, 0) -> strchr(s, 0)
483 if (DL && CharC->isZero())
484 return EmitStrChr(SrcStr, '\0', B, DL, TLI);
485 return nullptr;
486 }
487
488 // Compute the offset.
489 size_t I = (0xFF & CharC->getSExtValue()) == 0
490 ? Str.size()
491 : Str.rfind(CharC->getSExtValue());
492 if (I == StringRef::npos) // Didn't find the char. Return null.
493 return Constant::getNullValue(CI->getType());
494
495 // strrchr(s+n,c) -> gep(s+n+i,c)
496 return B.CreateGEP(SrcStr, B.getInt64(I), "strrchr");
497}
498
499Value *LibCallSimplifier::optimizeStrCmp(CallInst *CI, IRBuilder<> &B) {
500 Function *Callee = CI->getCalledFunction();
501 // Verify the "strcmp" function prototype.
502 FunctionType *FT = Callee->getFunctionType();
503 if (FT->getNumParams() != 2 || !FT->getReturnType()->isIntegerTy(32) ||
504 FT->getParamType(0) != FT->getParamType(1) ||
505 FT->getParamType(0) != B.getInt8PtrTy())
506 return nullptr;
507
508 Value *Str1P = CI->getArgOperand(0), *Str2P = CI->getArgOperand(1);
509 if (Str1P == Str2P) // strcmp(x,x) -> 0
510 return ConstantInt::get(CI->getType(), 0);
511
512 StringRef Str1, Str2;
513 bool HasStr1 = getConstantStringInfo(Str1P, Str1);
514 bool HasStr2 = getConstantStringInfo(Str2P, Str2);
515
516 // strcmp(x, y) -> cnst (if both x and y are constant strings)
517 if (HasStr1 && HasStr2)
518 return ConstantInt::get(CI->getType(), Str1.compare(Str2));
519
520 if (HasStr1 && Str1.empty()) // strcmp("", x) -> -*x
521 return B.CreateNeg(
522 B.CreateZExt(B.CreateLoad(Str2P, "strcmpload"), CI->getType()));
523
524 if (HasStr2 && Str2.empty()) // strcmp(x,"") -> *x
525 return B.CreateZExt(B.CreateLoad(Str1P, "strcmpload"), CI->getType());
526
527 // strcmp(P, "x") -> memcmp(P, "x", 2)
528 uint64_t Len1 = GetStringLength(Str1P);
529 uint64_t Len2 = GetStringLength(Str2P);
530 if (Len1 && Len2) {
531 // These optimizations require DataLayout.
532 if (!DL)
Craig Topperf40110f2014-04-25 05:29:35 +0000533 return nullptr;
Meador Inge7fb2f732012-10-13 16:45:32 +0000534
Chris Bienemanad070d02014-09-17 20:55:46 +0000535 return EmitMemCmp(Str1P, Str2P,
536 ConstantInt::get(DL->getIntPtrType(CI->getContext()),
537 std::min(Len1, Len2)),
538 B, DL, TLI);
539 }
Meador Inge7fb2f732012-10-13 16:45:32 +0000540
Chris Bienemanad070d02014-09-17 20:55:46 +0000541 return nullptr;
542}
543
544Value *LibCallSimplifier::optimizeStrNCmp(CallInst *CI, IRBuilder<> &B) {
545 Function *Callee = CI->getCalledFunction();
546 // Verify the "strncmp" function prototype.
547 FunctionType *FT = Callee->getFunctionType();
548 if (FT->getNumParams() != 3 || !FT->getReturnType()->isIntegerTy(32) ||
549 FT->getParamType(0) != FT->getParamType(1) ||
550 FT->getParamType(0) != B.getInt8PtrTy() ||
551 !FT->getParamType(2)->isIntegerTy())
552 return nullptr;
553
554 Value *Str1P = CI->getArgOperand(0), *Str2P = CI->getArgOperand(1);
555 if (Str1P == Str2P) // strncmp(x,x,n) -> 0
556 return ConstantInt::get(CI->getType(), 0);
557
558 // Get the length argument if it is constant.
559 uint64_t Length;
560 if (ConstantInt *LengthArg = dyn_cast<ConstantInt>(CI->getArgOperand(2)))
561 Length = LengthArg->getZExtValue();
562 else
563 return nullptr;
564
565 if (Length == 0) // strncmp(x,y,0) -> 0
566 return ConstantInt::get(CI->getType(), 0);
567
568 if (DL && Length == 1) // strncmp(x,y,1) -> memcmp(x,y,1)
569 return EmitMemCmp(Str1P, Str2P, CI->getArgOperand(2), B, DL, TLI);
570
571 StringRef Str1, Str2;
572 bool HasStr1 = getConstantStringInfo(Str1P, Str1);
573 bool HasStr2 = getConstantStringInfo(Str2P, Str2);
574
575 // strncmp(x, y) -> cnst (if both x and y are constant strings)
576 if (HasStr1 && HasStr2) {
577 StringRef SubStr1 = Str1.substr(0, Length);
578 StringRef SubStr2 = Str2.substr(0, Length);
579 return ConstantInt::get(CI->getType(), SubStr1.compare(SubStr2));
580 }
581
582 if (HasStr1 && Str1.empty()) // strncmp("", x, n) -> -*x
583 return B.CreateNeg(
584 B.CreateZExt(B.CreateLoad(Str2P, "strcmpload"), CI->getType()));
585
586 if (HasStr2 && Str2.empty()) // strncmp(x, "", n) -> *x
587 return B.CreateZExt(B.CreateLoad(Str1P, "strcmpload"), CI->getType());
588
589 return nullptr;
590}
591
592Value *LibCallSimplifier::optimizeStrCpy(CallInst *CI, IRBuilder<> &B) {
593 Function *Callee = CI->getCalledFunction();
594 // Verify the "strcpy" function prototype.
595 FunctionType *FT = Callee->getFunctionType();
596 if (FT->getNumParams() != 2 || FT->getReturnType() != FT->getParamType(0) ||
597 FT->getParamType(0) != FT->getParamType(1) ||
598 FT->getParamType(0) != B.getInt8PtrTy())
599 return nullptr;
600
601 Value *Dst = CI->getArgOperand(0), *Src = CI->getArgOperand(1);
602 if (Dst == Src) // strcpy(x,x) -> x
603 return Src;
604
605 // These optimizations require DataLayout.
606 if (!DL)
607 return nullptr;
608
609 // See if we can get the length of the input string.
610 uint64_t Len = GetStringLength(Src);
611 if (Len == 0)
612 return nullptr;
613
614 // We have enough information to now generate the memcpy call to do the
615 // copy for us. Make a memcpy to copy the nul byte with align = 1.
616 B.CreateMemCpy(Dst, Src,
617 ConstantInt::get(DL->getIntPtrType(CI->getContext()), Len), 1);
618 return Dst;
619}
620
621Value *LibCallSimplifier::optimizeStpCpy(CallInst *CI, IRBuilder<> &B) {
622 Function *Callee = CI->getCalledFunction();
623 // Verify the "stpcpy" function prototype.
624 FunctionType *FT = Callee->getFunctionType();
625 if (FT->getNumParams() != 2 || FT->getReturnType() != FT->getParamType(0) ||
626 FT->getParamType(0) != FT->getParamType(1) ||
627 FT->getParamType(0) != B.getInt8PtrTy())
628 return nullptr;
629
630 // These optimizations require DataLayout.
631 if (!DL)
632 return nullptr;
633
634 Value *Dst = CI->getArgOperand(0), *Src = CI->getArgOperand(1);
635 if (Dst == Src) { // stpcpy(x,x) -> x+strlen(x)
636 Value *StrLen = EmitStrLen(Src, B, DL, TLI);
637 return StrLen ? B.CreateInBoundsGEP(Dst, StrLen) : nullptr;
638 }
639
640 // See if we can get the length of the input string.
641 uint64_t Len = GetStringLength(Src);
642 if (Len == 0)
643 return nullptr;
644
645 Type *PT = FT->getParamType(0);
646 Value *LenV = ConstantInt::get(DL->getIntPtrType(PT), Len);
647 Value *DstEnd =
648 B.CreateGEP(Dst, ConstantInt::get(DL->getIntPtrType(PT), Len - 1));
649
650 // We have enough information to now generate the memcpy call to do the
651 // copy for us. Make a memcpy to copy the nul byte with align = 1.
652 B.CreateMemCpy(Dst, Src, LenV, 1);
653 return DstEnd;
654}
655
656Value *LibCallSimplifier::optimizeStrNCpy(CallInst *CI, IRBuilder<> &B) {
657 Function *Callee = CI->getCalledFunction();
658 FunctionType *FT = Callee->getFunctionType();
659 if (FT->getNumParams() != 3 || FT->getReturnType() != FT->getParamType(0) ||
660 FT->getParamType(0) != FT->getParamType(1) ||
661 FT->getParamType(0) != B.getInt8PtrTy() ||
662 !FT->getParamType(2)->isIntegerTy())
663 return nullptr;
664
665 Value *Dst = CI->getArgOperand(0);
666 Value *Src = CI->getArgOperand(1);
667 Value *LenOp = CI->getArgOperand(2);
668
669 // See if we can get the length of the input string.
670 uint64_t SrcLen = GetStringLength(Src);
671 if (SrcLen == 0)
672 return nullptr;
673 --SrcLen;
674
675 if (SrcLen == 0) {
676 // strncpy(x, "", y) -> memset(x, '\0', y, 1)
677 B.CreateMemSet(Dst, B.getInt8('\0'), LenOp, 1);
Meador Inge7fb2f732012-10-13 16:45:32 +0000678 return Dst;
679 }
Meador Inge7fb2f732012-10-13 16:45:32 +0000680
Chris Bienemanad070d02014-09-17 20:55:46 +0000681 uint64_t Len;
682 if (ConstantInt *LengthArg = dyn_cast<ConstantInt>(LenOp))
683 Len = LengthArg->getZExtValue();
684 else
685 return nullptr;
Meador Inge7fb2f732012-10-13 16:45:32 +0000686
Chris Bienemanad070d02014-09-17 20:55:46 +0000687 if (Len == 0)
688 return Dst; // strncpy(x, y, 0) -> x
Meador Inge7fb2f732012-10-13 16:45:32 +0000689
Chris Bienemanad070d02014-09-17 20:55:46 +0000690 // These optimizations require DataLayout.
691 if (!DL)
692 return nullptr;
Meador Inge7fb2f732012-10-13 16:45:32 +0000693
Chris Bienemanad070d02014-09-17 20:55:46 +0000694 // Let strncpy handle the zero padding
695 if (Len > SrcLen + 1)
696 return nullptr;
Meador Inge7fb2f732012-10-13 16:45:32 +0000697
Chris Bienemanad070d02014-09-17 20:55:46 +0000698 Type *PT = FT->getParamType(0);
699 // strncpy(x, s, c) -> memcpy(x, s, c, 1) [s and c are constant]
700 B.CreateMemCpy(Dst, Src, ConstantInt::get(DL->getIntPtrType(PT), Len), 1);
Meador Inge7fb2f732012-10-13 16:45:32 +0000701
Chris Bienemanad070d02014-09-17 20:55:46 +0000702 return Dst;
703}
Meador Inge7fb2f732012-10-13 16:45:32 +0000704
Chris Bienemanad070d02014-09-17 20:55:46 +0000705Value *LibCallSimplifier::optimizeStrLen(CallInst *CI, IRBuilder<> &B) {
706 Function *Callee = CI->getCalledFunction();
707 FunctionType *FT = Callee->getFunctionType();
708 if (FT->getNumParams() != 1 || FT->getParamType(0) != B.getInt8PtrTy() ||
709 !FT->getReturnType()->isIntegerTy())
710 return nullptr;
Meador Inge7fb2f732012-10-13 16:45:32 +0000711
Chris Bienemanad070d02014-09-17 20:55:46 +0000712 Value *Src = CI->getArgOperand(0);
713
714 // Constant folding: strlen("xyz") -> 3
715 if (uint64_t Len = GetStringLength(Src))
716 return ConstantInt::get(CI->getType(), Len - 1);
717
718 // strlen(x?"foo":"bars") --> x ? 3 : 4
719 if (SelectInst *SI = dyn_cast<SelectInst>(Src)) {
720 uint64_t LenTrue = GetStringLength(SI->getTrueValue());
721 uint64_t LenFalse = GetStringLength(SI->getFalseValue());
722 if (LenTrue && LenFalse) {
723 Function *Caller = CI->getParent()->getParent();
724 emitOptimizationRemark(CI->getContext(), "simplify-libcalls", *Caller,
725 SI->getDebugLoc(),
726 "folded strlen(select) to select of constants");
727 return B.CreateSelect(SI->getCondition(),
728 ConstantInt::get(CI->getType(), LenTrue - 1),
729 ConstantInt::get(CI->getType(), LenFalse - 1));
730 }
Meador Inge7fb2f732012-10-13 16:45:32 +0000731 }
Meador Inge7fb2f732012-10-13 16:45:32 +0000732
Chris Bienemanad070d02014-09-17 20:55:46 +0000733 // strlen(x) != 0 --> *x != 0
734 // strlen(x) == 0 --> *x == 0
735 if (isOnlyUsedInZeroEqualityComparison(CI))
736 return B.CreateZExt(B.CreateLoad(Src, "strlenfirst"), CI->getType());
Meador Inge17418502012-10-13 16:45:37 +0000737
Chris Bienemanad070d02014-09-17 20:55:46 +0000738 return nullptr;
739}
Meador Inge17418502012-10-13 16:45:37 +0000740
Chris Bienemanad070d02014-09-17 20:55:46 +0000741Value *LibCallSimplifier::optimizeStrPBrk(CallInst *CI, IRBuilder<> &B) {
742 Function *Callee = CI->getCalledFunction();
743 FunctionType *FT = Callee->getFunctionType();
744 if (FT->getNumParams() != 2 || FT->getParamType(0) != B.getInt8PtrTy() ||
745 FT->getParamType(1) != FT->getParamType(0) ||
746 FT->getReturnType() != FT->getParamType(0))
747 return nullptr;
Meador Inge17418502012-10-13 16:45:37 +0000748
Chris Bienemanad070d02014-09-17 20:55:46 +0000749 StringRef S1, S2;
750 bool HasS1 = getConstantStringInfo(CI->getArgOperand(0), S1);
751 bool HasS2 = getConstantStringInfo(CI->getArgOperand(1), S2);
Meador Inge17418502012-10-13 16:45:37 +0000752
Chris Bienemanad070d02014-09-17 20:55:46 +0000753 // strpbrk(s, "") -> NULL
754 // strpbrk("", s) -> NULL
755 if ((HasS1 && S1.empty()) || (HasS2 && S2.empty()))
756 return Constant::getNullValue(CI->getType());
Meador Inge17418502012-10-13 16:45:37 +0000757
Chris Bienemanad070d02014-09-17 20:55:46 +0000758 // Constant folding.
759 if (HasS1 && HasS2) {
760 size_t I = S1.find_first_of(S2);
761 if (I == StringRef::npos) // No match.
Meador Inge17418502012-10-13 16:45:37 +0000762 return Constant::getNullValue(CI->getType());
763
Chris Bienemanad070d02014-09-17 20:55:46 +0000764 return B.CreateGEP(CI->getArgOperand(0), B.getInt64(I), "strpbrk");
Meador Inge17418502012-10-13 16:45:37 +0000765 }
Meador Inge17418502012-10-13 16:45:37 +0000766
Chris Bienemanad070d02014-09-17 20:55:46 +0000767 // strpbrk(s, "a") -> strchr(s, 'a')
768 if (DL && HasS2 && S2.size() == 1)
769 return EmitStrChr(CI->getArgOperand(0), S2[0], B, DL, TLI);
770
771 return nullptr;
772}
773
774Value *LibCallSimplifier::optimizeStrTo(CallInst *CI, IRBuilder<> &B) {
775 Function *Callee = CI->getCalledFunction();
776 FunctionType *FT = Callee->getFunctionType();
777 if ((FT->getNumParams() != 2 && FT->getNumParams() != 3) ||
778 !FT->getParamType(0)->isPointerTy() ||
779 !FT->getParamType(1)->isPointerTy())
780 return nullptr;
781
782 Value *EndPtr = CI->getArgOperand(1);
783 if (isa<ConstantPointerNull>(EndPtr)) {
784 // With a null EndPtr, this function won't capture the main argument.
785 // It would be readonly too, except that it still may write to errno.
786 CI->addAttribute(1, Attribute::NoCapture);
787 }
788
789 return nullptr;
790}
791
792Value *LibCallSimplifier::optimizeStrSpn(CallInst *CI, IRBuilder<> &B) {
793 Function *Callee = CI->getCalledFunction();
794 FunctionType *FT = Callee->getFunctionType();
795 if (FT->getNumParams() != 2 || FT->getParamType(0) != B.getInt8PtrTy() ||
796 FT->getParamType(1) != FT->getParamType(0) ||
797 !FT->getReturnType()->isIntegerTy())
798 return nullptr;
799
800 StringRef S1, S2;
801 bool HasS1 = getConstantStringInfo(CI->getArgOperand(0), S1);
802 bool HasS2 = getConstantStringInfo(CI->getArgOperand(1), S2);
803
804 // strspn(s, "") -> 0
805 // strspn("", s) -> 0
806 if ((HasS1 && S1.empty()) || (HasS2 && S2.empty()))
807 return Constant::getNullValue(CI->getType());
808
809 // Constant folding.
810 if (HasS1 && HasS2) {
811 size_t Pos = S1.find_first_not_of(S2);
812 if (Pos == StringRef::npos)
813 Pos = S1.size();
814 return ConstantInt::get(CI->getType(), Pos);
815 }
816
817 return nullptr;
818}
819
820Value *LibCallSimplifier::optimizeStrCSpn(CallInst *CI, IRBuilder<> &B) {
821 Function *Callee = CI->getCalledFunction();
822 FunctionType *FT = Callee->getFunctionType();
823 if (FT->getNumParams() != 2 || FT->getParamType(0) != B.getInt8PtrTy() ||
824 FT->getParamType(1) != FT->getParamType(0) ||
825 !FT->getReturnType()->isIntegerTy())
826 return nullptr;
827
828 StringRef S1, S2;
829 bool HasS1 = getConstantStringInfo(CI->getArgOperand(0), S1);
830 bool HasS2 = getConstantStringInfo(CI->getArgOperand(1), S2);
831
832 // strcspn("", s) -> 0
833 if (HasS1 && S1.empty())
834 return Constant::getNullValue(CI->getType());
835
836 // Constant folding.
837 if (HasS1 && HasS2) {
838 size_t Pos = S1.find_first_of(S2);
839 if (Pos == StringRef::npos)
840 Pos = S1.size();
841 return ConstantInt::get(CI->getType(), Pos);
842 }
843
844 // strcspn(s, "") -> strlen(s)
845 if (DL && HasS2 && S2.empty())
846 return EmitStrLen(CI->getArgOperand(0), B, DL, TLI);
847
848 return nullptr;
849}
850
851Value *LibCallSimplifier::optimizeStrStr(CallInst *CI, IRBuilder<> &B) {
852 Function *Callee = CI->getCalledFunction();
853 FunctionType *FT = Callee->getFunctionType();
854 if (FT->getNumParams() != 2 || !FT->getParamType(0)->isPointerTy() ||
855 !FT->getParamType(1)->isPointerTy() ||
856 !FT->getReturnType()->isPointerTy())
857 return nullptr;
858
859 // fold strstr(x, x) -> x.
860 if (CI->getArgOperand(0) == CI->getArgOperand(1))
861 return B.CreateBitCast(CI->getArgOperand(0), CI->getType());
862
863 // fold strstr(a, b) == a -> strncmp(a, b, strlen(b)) == 0
864 if (DL && isOnlyUsedInEqualityComparison(CI, CI->getArgOperand(0))) {
865 Value *StrLen = EmitStrLen(CI->getArgOperand(1), B, DL, TLI);
866 if (!StrLen)
Craig Topperf40110f2014-04-25 05:29:35 +0000867 return nullptr;
Chris Bienemanad070d02014-09-17 20:55:46 +0000868 Value *StrNCmp = EmitStrNCmp(CI->getArgOperand(0), CI->getArgOperand(1),
869 StrLen, B, DL, TLI);
870 if (!StrNCmp)
Craig Topperf40110f2014-04-25 05:29:35 +0000871 return nullptr;
Chris Bienemanad070d02014-09-17 20:55:46 +0000872 for (auto UI = CI->user_begin(), UE = CI->user_end(); UI != UE;) {
873 ICmpInst *Old = cast<ICmpInst>(*UI++);
874 Value *Cmp =
875 B.CreateICmp(Old->getPredicate(), StrNCmp,
876 ConstantInt::getNullValue(StrNCmp->getType()), "cmp");
877 replaceAllUsesWith(Old, Cmp);
Meador Inge17418502012-10-13 16:45:37 +0000878 }
Chris Bienemanad070d02014-09-17 20:55:46 +0000879 return CI;
880 }
Meador Inge17418502012-10-13 16:45:37 +0000881
Chris Bienemanad070d02014-09-17 20:55:46 +0000882 // See if either input string is a constant string.
883 StringRef SearchStr, ToFindStr;
884 bool HasStr1 = getConstantStringInfo(CI->getArgOperand(0), SearchStr);
885 bool HasStr2 = getConstantStringInfo(CI->getArgOperand(1), ToFindStr);
886
887 // fold strstr(x, "") -> x.
888 if (HasStr2 && ToFindStr.empty())
889 return B.CreateBitCast(CI->getArgOperand(0), CI->getType());
890
891 // If both strings are known, constant fold it.
892 if (HasStr1 && HasStr2) {
893 size_t Offset = SearchStr.find(ToFindStr);
894
895 if (Offset == StringRef::npos) // strstr("foo", "bar") -> null
Meador Inge17418502012-10-13 16:45:37 +0000896 return Constant::getNullValue(CI->getType());
897
Chris Bienemanad070d02014-09-17 20:55:46 +0000898 // strstr("abcd", "bc") -> gep((char*)"abcd", 1)
899 Value *Result = CastToCStr(CI->getArgOperand(0), B);
900 Result = B.CreateConstInBoundsGEP1_64(Result, Offset, "strstr");
901 return B.CreateBitCast(Result, CI->getType());
Meador Inge17418502012-10-13 16:45:37 +0000902 }
Meador Inge17418502012-10-13 16:45:37 +0000903
Chris Bienemanad070d02014-09-17 20:55:46 +0000904 // fold strstr(x, "y") -> strchr(x, 'y').
905 if (HasStr2 && ToFindStr.size() == 1) {
906 Value *StrChr = EmitStrChr(CI->getArgOperand(0), ToFindStr[0], B, DL, TLI);
907 return StrChr ? B.CreateBitCast(StrChr, CI->getType()) : nullptr;
908 }
909 return nullptr;
910}
Meador Inge40b6fac2012-10-15 03:47:37 +0000911
Chris Bienemanad070d02014-09-17 20:55:46 +0000912Value *LibCallSimplifier::optimizeMemCmp(CallInst *CI, IRBuilder<> &B) {
913 Function *Callee = CI->getCalledFunction();
914 FunctionType *FT = Callee->getFunctionType();
915 if (FT->getNumParams() != 3 || !FT->getParamType(0)->isPointerTy() ||
916 !FT->getParamType(1)->isPointerTy() ||
917 !FT->getReturnType()->isIntegerTy(32))
Craig Topperf40110f2014-04-25 05:29:35 +0000918 return nullptr;
Meador Inge40b6fac2012-10-15 03:47:37 +0000919
Chris Bienemanad070d02014-09-17 20:55:46 +0000920 Value *LHS = CI->getArgOperand(0), *RHS = CI->getArgOperand(1);
Meador Inge40b6fac2012-10-15 03:47:37 +0000921
Chris Bienemanad070d02014-09-17 20:55:46 +0000922 if (LHS == RHS) // memcmp(s,s,x) -> 0
923 return Constant::getNullValue(CI->getType());
Meador Inge40b6fac2012-10-15 03:47:37 +0000924
Chris Bienemanad070d02014-09-17 20:55:46 +0000925 // Make sure we have a constant length.
926 ConstantInt *LenC = dyn_cast<ConstantInt>(CI->getArgOperand(2));
927 if (!LenC)
Craig Topperf40110f2014-04-25 05:29:35 +0000928 return nullptr;
Chris Bienemanad070d02014-09-17 20:55:46 +0000929 uint64_t Len = LenC->getZExtValue();
930
931 if (Len == 0) // memcmp(s1,s2,0) -> 0
932 return Constant::getNullValue(CI->getType());
933
934 // memcmp(S1,S2,1) -> *(unsigned char*)LHS - *(unsigned char*)RHS
935 if (Len == 1) {
936 Value *LHSV = B.CreateZExt(B.CreateLoad(CastToCStr(LHS, B), "lhsc"),
937 CI->getType(), "lhsv");
938 Value *RHSV = B.CreateZExt(B.CreateLoad(CastToCStr(RHS, B), "rhsc"),
939 CI->getType(), "rhsv");
940 return B.CreateSub(LHSV, RHSV, "chardiff");
Meador Inge40b6fac2012-10-15 03:47:37 +0000941 }
Meador Inge40b6fac2012-10-15 03:47:37 +0000942
Chris Bienemanad070d02014-09-17 20:55:46 +0000943 // Constant folding: memcmp(x, y, l) -> cnst (all arguments are constant)
944 StringRef LHSStr, RHSStr;
945 if (getConstantStringInfo(LHS, LHSStr) &&
946 getConstantStringInfo(RHS, RHSStr)) {
947 // Make sure we're not reading out-of-bounds memory.
948 if (Len > LHSStr.size() || Len > RHSStr.size())
Craig Topperf40110f2014-04-25 05:29:35 +0000949 return nullptr;
Chris Bienemanad070d02014-09-17 20:55:46 +0000950 // Fold the memcmp and normalize the result. This way we get consistent
951 // results across multiple platforms.
952 uint64_t Ret = 0;
953 int Cmp = memcmp(LHSStr.data(), RHSStr.data(), Len);
954 if (Cmp < 0)
955 Ret = -1;
956 else if (Cmp > 0)
957 Ret = 1;
958 return ConstantInt::get(CI->getType(), Ret);
Meador Inge000dbcc2012-10-18 18:12:40 +0000959 }
Meador Inge000dbcc2012-10-18 18:12:40 +0000960
Chris Bienemanad070d02014-09-17 20:55:46 +0000961 return nullptr;
962}
Meador Inge9a6a1902012-10-31 00:20:56 +0000963
Chris Bienemanad070d02014-09-17 20:55:46 +0000964Value *LibCallSimplifier::optimizeMemCpy(CallInst *CI, IRBuilder<> &B) {
965 Function *Callee = CI->getCalledFunction();
966 // These optimizations require DataLayout.
967 if (!DL)
Craig Topperf40110f2014-04-25 05:29:35 +0000968 return nullptr;
Meador Inged589ac62012-10-31 03:33:06 +0000969
Chris Bienemanad070d02014-09-17 20:55:46 +0000970 FunctionType *FT = Callee->getFunctionType();
971 if (FT->getNumParams() != 3 || FT->getReturnType() != FT->getParamType(0) ||
972 !FT->getParamType(0)->isPointerTy() ||
973 !FT->getParamType(1)->isPointerTy() ||
974 FT->getParamType(2) != DL->getIntPtrType(CI->getContext()))
Craig Topperf40110f2014-04-25 05:29:35 +0000975 return nullptr;
Meador Inge6f8e0112012-10-31 04:29:58 +0000976
Chris Bienemanad070d02014-09-17 20:55:46 +0000977 // memcpy(x, y, n) -> llvm.memcpy(x, y, n, 1)
978 B.CreateMemCpy(CI->getArgOperand(0), CI->getArgOperand(1),
979 CI->getArgOperand(2), 1);
980 return CI->getArgOperand(0);
981}
Meador Inge05a625a2012-10-31 14:58:26 +0000982
Chris Bienemanad070d02014-09-17 20:55:46 +0000983Value *LibCallSimplifier::optimizeMemMove(CallInst *CI, IRBuilder<> &B) {
984 Function *Callee = CI->getCalledFunction();
985 // These optimizations require DataLayout.
986 if (!DL)
Craig Topperf40110f2014-04-25 05:29:35 +0000987 return nullptr;
Meador Inge05a625a2012-10-31 14:58:26 +0000988
Chris Bienemanad070d02014-09-17 20:55:46 +0000989 FunctionType *FT = Callee->getFunctionType();
990 if (FT->getNumParams() != 3 || FT->getReturnType() != FT->getParamType(0) ||
991 !FT->getParamType(0)->isPointerTy() ||
992 !FT->getParamType(1)->isPointerTy() ||
993 FT->getParamType(2) != DL->getIntPtrType(CI->getContext()))
Craig Topperf40110f2014-04-25 05:29:35 +0000994 return nullptr;
Meador Inge489b5d62012-11-08 01:33:50 +0000995
Chris Bienemanad070d02014-09-17 20:55:46 +0000996 // memmove(x, y, n) -> llvm.memmove(x, y, n, 1)
997 B.CreateMemMove(CI->getArgOperand(0), CI->getArgOperand(1),
998 CI->getArgOperand(2), 1);
999 return CI->getArgOperand(0);
1000}
Meador Ingebcd88ef72012-11-10 15:16:48 +00001001
Chris Bienemanad070d02014-09-17 20:55:46 +00001002Value *LibCallSimplifier::optimizeMemSet(CallInst *CI, IRBuilder<> &B) {
1003 Function *Callee = CI->getCalledFunction();
1004 // These optimizations require DataLayout.
1005 if (!DL)
Craig Topperf40110f2014-04-25 05:29:35 +00001006 return nullptr;
Meador Ingebcd88ef72012-11-10 15:16:48 +00001007
Chris Bienemanad070d02014-09-17 20:55:46 +00001008 FunctionType *FT = Callee->getFunctionType();
1009 if (FT->getNumParams() != 3 || FT->getReturnType() != FT->getParamType(0) ||
1010 !FT->getParamType(0)->isPointerTy() ||
1011 !FT->getParamType(1)->isIntegerTy() ||
1012 FT->getParamType(2) != DL->getIntPtrType(FT->getParamType(0)))
Craig Topperf40110f2014-04-25 05:29:35 +00001013 return nullptr;
Meador Inge56edbc92012-11-11 03:51:48 +00001014
Chris Bienemanad070d02014-09-17 20:55:46 +00001015 // memset(p, v, n) -> llvm.memset(p, v, n, 1)
1016 Value *Val = B.CreateIntCast(CI->getArgOperand(1), B.getInt8Ty(), false);
1017 B.CreateMemSet(CI->getArgOperand(0), Val, CI->getArgOperand(2), 1);
1018 return CI->getArgOperand(0);
1019}
Meador Inged4825782012-11-11 06:49:03 +00001020
Meador Inge193e0352012-11-13 04:16:17 +00001021//===----------------------------------------------------------------------===//
1022// Math Library Optimizations
1023//===----------------------------------------------------------------------===//
1024
1025//===----------------------------------------------------------------------===//
1026// Double -> Float Shrinking Optimizations for Unary Functions like 'floor'
1027
Chris Bienemanad070d02014-09-17 20:55:46 +00001028Value *LibCallSimplifier::optimizeUnaryDoubleFP(CallInst *CI, IRBuilder<> &B,
1029 bool CheckRetType) {
1030 Function *Callee = CI->getCalledFunction();
1031 FunctionType *FT = Callee->getFunctionType();
1032 if (FT->getNumParams() != 1 || !FT->getReturnType()->isDoubleTy() ||
1033 !FT->getParamType(0)->isDoubleTy())
1034 return nullptr;
Meador Inge193e0352012-11-13 04:16:17 +00001035
Chris Bienemanad070d02014-09-17 20:55:46 +00001036 if (CheckRetType) {
1037 // Check if all the uses for function like 'sin' are converted to float.
1038 for (User *U : CI->users()) {
1039 FPTruncInst *Cast = dyn_cast<FPTruncInst>(U);
1040 if (!Cast || !Cast->getType()->isFloatTy())
1041 return nullptr;
Meador Inge193e0352012-11-13 04:16:17 +00001042 }
Meador Inge193e0352012-11-13 04:16:17 +00001043 }
Chris Bienemanad070d02014-09-17 20:55:46 +00001044
1045 // If this is something like 'floor((double)floatval)', convert to floorf.
1046 FPExtInst *Cast = dyn_cast<FPExtInst>(CI->getArgOperand(0));
1047 if (!Cast || !Cast->getOperand(0)->getType()->isFloatTy())
1048 return nullptr;
1049
1050 // floor((double)floatval) -> (double)floorf(floatval)
1051 Value *V = Cast->getOperand(0);
1052 V = EmitUnaryFloatFnCall(V, Callee->getName(), B, Callee->getAttributes());
1053 return B.CreateFPExt(V, B.getDoubleTy());
1054}
Meador Inge193e0352012-11-13 04:16:17 +00001055
Yi Jiang6ab044e2013-12-16 22:42:40 +00001056// Double -> Float Shrinking Optimizations for Binary Functions like 'fmin/fmax'
Chris Bienemanad070d02014-09-17 20:55:46 +00001057Value *LibCallSimplifier::optimizeBinaryDoubleFP(CallInst *CI, IRBuilder<> &B) {
1058 Function *Callee = CI->getCalledFunction();
1059 FunctionType *FT = Callee->getFunctionType();
1060 // Just make sure this has 2 arguments of the same FP type, which match the
1061 // result type.
1062 if (FT->getNumParams() != 2 || FT->getReturnType() != FT->getParamType(0) ||
1063 FT->getParamType(0) != FT->getParamType(1) ||
1064 !FT->getParamType(0)->isFloatingPointTy())
Craig Topperf40110f2014-04-25 05:29:35 +00001065 return nullptr;
Meador Inge193e0352012-11-13 04:16:17 +00001066
Chris Bienemanad070d02014-09-17 20:55:46 +00001067 // If this is something like 'fmin((double)floatval1, (double)floatval2)',
1068 // we convert it to fminf.
1069 FPExtInst *Cast1 = dyn_cast<FPExtInst>(CI->getArgOperand(0));
1070 FPExtInst *Cast2 = dyn_cast<FPExtInst>(CI->getArgOperand(1));
1071 if (!Cast1 || !Cast1->getOperand(0)->getType()->isFloatTy() || !Cast2 ||
1072 !Cast2->getOperand(0)->getType()->isFloatTy())
Craig Topperf40110f2014-04-25 05:29:35 +00001073 return nullptr;
Chris Bienemanad070d02014-09-17 20:55:46 +00001074
1075 // fmin((double)floatval1, (double)floatval2)
1076 // -> (double)fmin(floatval1, floatval2)
1077 Value *V = nullptr;
1078 Value *V1 = Cast1->getOperand(0);
1079 Value *V2 = Cast2->getOperand(0);
1080 V = EmitBinaryFloatFnCall(V1, V2, Callee->getName(), B,
1081 Callee->getAttributes());
1082 return B.CreateFPExt(V, B.getDoubleTy());
1083}
1084
1085Value *LibCallSimplifier::optimizeCos(CallInst *CI, IRBuilder<> &B) {
1086 Function *Callee = CI->getCalledFunction();
1087 Value *Ret = nullptr;
1088 if (UnsafeFPShrink && Callee->getName() == "cos" && TLI->has(LibFunc::cosf)) {
1089 Ret = optimizeUnaryDoubleFP(CI, B, true);
Bob Wilsond8d92d92013-11-03 06:48:38 +00001090 }
1091
Chris Bienemanad070d02014-09-17 20:55:46 +00001092 FunctionType *FT = Callee->getFunctionType();
1093 // Just make sure this has 1 argument of FP type, which matches the
1094 // result type.
1095 if (FT->getNumParams() != 1 || FT->getReturnType() != FT->getParamType(0) ||
1096 !FT->getParamType(0)->isFloatingPointTy())
1097 return Ret;
Bob Wilsond8d92d92013-11-03 06:48:38 +00001098
Chris Bienemanad070d02014-09-17 20:55:46 +00001099 // cos(-x) -> cos(x)
1100 Value *Op1 = CI->getArgOperand(0);
1101 if (BinaryOperator::isFNeg(Op1)) {
1102 BinaryOperator *BinExpr = cast<BinaryOperator>(Op1);
1103 return B.CreateCall(Callee, BinExpr->getOperand(1), "cos");
1104 }
1105 return Ret;
1106}
Bob Wilsond8d92d92013-11-03 06:48:38 +00001107
Chris Bienemanad070d02014-09-17 20:55:46 +00001108Value *LibCallSimplifier::optimizePow(CallInst *CI, IRBuilder<> &B) {
1109 Function *Callee = CI->getCalledFunction();
1110
1111 Value *Ret = nullptr;
1112 if (UnsafeFPShrink && Callee->getName() == "pow" && TLI->has(LibFunc::powf)) {
1113 Ret = optimizeUnaryDoubleFP(CI, B, true);
Bob Wilsond8d92d92013-11-03 06:48:38 +00001114 }
1115
Chris Bienemanad070d02014-09-17 20:55:46 +00001116 FunctionType *FT = Callee->getFunctionType();
1117 // Just make sure this has 2 arguments of the same FP type, which match the
1118 // result type.
1119 if (FT->getNumParams() != 2 || FT->getReturnType() != FT->getParamType(0) ||
1120 FT->getParamType(0) != FT->getParamType(1) ||
1121 !FT->getParamType(0)->isFloatingPointTy())
1122 return Ret;
Bob Wilsond8d92d92013-11-03 06:48:38 +00001123
Chris Bienemanad070d02014-09-17 20:55:46 +00001124 Value *Op1 = CI->getArgOperand(0), *Op2 = CI->getArgOperand(1);
1125 if (ConstantFP *Op1C = dyn_cast<ConstantFP>(Op1)) {
1126 // pow(1.0, x) -> 1.0
1127 if (Op1C->isExactlyValue(1.0))
1128 return Op1C;
1129 // pow(2.0, x) -> exp2(x)
1130 if (Op1C->isExactlyValue(2.0) &&
1131 hasUnaryFloatFn(TLI, Op1->getType(), LibFunc::exp2, LibFunc::exp2f,
1132 LibFunc::exp2l))
1133 return EmitUnaryFloatFnCall(Op2, "exp2", B, Callee->getAttributes());
1134 // pow(10.0, x) -> exp10(x)
1135 if (Op1C->isExactlyValue(10.0) &&
1136 hasUnaryFloatFn(TLI, Op1->getType(), LibFunc::exp10, LibFunc::exp10f,
1137 LibFunc::exp10l))
1138 return EmitUnaryFloatFnCall(Op2, TLI->getName(LibFunc::exp10), B,
1139 Callee->getAttributes());
Bob Wilsond8d92d92013-11-03 06:48:38 +00001140 }
1141
Chris Bienemanad070d02014-09-17 20:55:46 +00001142 ConstantFP *Op2C = dyn_cast<ConstantFP>(Op2);
1143 if (!Op2C)
1144 return Ret;
1145
1146 if (Op2C->getValueAPF().isZero()) // pow(x, 0.0) -> 1.0
1147 return ConstantFP::get(CI->getType(), 1.0);
1148
1149 if (Op2C->isExactlyValue(0.5) &&
1150 hasUnaryFloatFn(TLI, Op2->getType(), LibFunc::sqrt, LibFunc::sqrtf,
1151 LibFunc::sqrtl) &&
1152 hasUnaryFloatFn(TLI, Op2->getType(), LibFunc::fabs, LibFunc::fabsf,
1153 LibFunc::fabsl)) {
1154 // Expand pow(x, 0.5) to (x == -infinity ? +infinity : fabs(sqrt(x))).
1155 // This is faster than calling pow, and still handles negative zero
1156 // and negative infinity correctly.
1157 // TODO: In fast-math mode, this could be just sqrt(x).
1158 // TODO: In finite-only mode, this could be just fabs(sqrt(x)).
1159 Value *Inf = ConstantFP::getInfinity(CI->getType());
1160 Value *NegInf = ConstantFP::getInfinity(CI->getType(), true);
1161 Value *Sqrt = EmitUnaryFloatFnCall(Op1, "sqrt", B, Callee->getAttributes());
1162 Value *FAbs =
1163 EmitUnaryFloatFnCall(Sqrt, "fabs", B, Callee->getAttributes());
1164 Value *FCmp = B.CreateFCmpOEQ(Op1, NegInf);
1165 Value *Sel = B.CreateSelect(FCmp, Inf, FAbs);
1166 return Sel;
Bob Wilsond8d92d92013-11-03 06:48:38 +00001167 }
1168
Chris Bienemanad070d02014-09-17 20:55:46 +00001169 if (Op2C->isExactlyValue(1.0)) // pow(x, 1.0) -> x
1170 return Op1;
1171 if (Op2C->isExactlyValue(2.0)) // pow(x, 2.0) -> x*x
1172 return B.CreateFMul(Op1, Op1, "pow2");
1173 if (Op2C->isExactlyValue(-1.0)) // pow(x, -1.0) -> 1.0/x
1174 return B.CreateFDiv(ConstantFP::get(CI->getType(), 1.0), Op1, "powrecip");
1175 return nullptr;
1176}
Bob Wilsond8d92d92013-11-03 06:48:38 +00001177
Chris Bienemanad070d02014-09-17 20:55:46 +00001178Value *LibCallSimplifier::optimizeExp2(CallInst *CI, IRBuilder<> &B) {
1179 Function *Callee = CI->getCalledFunction();
1180 Function *Caller = CI->getParent()->getParent();
Bob Wilsond8d92d92013-11-03 06:48:38 +00001181
Chris Bienemanad070d02014-09-17 20:55:46 +00001182 Value *Ret = nullptr;
1183 if (UnsafeFPShrink && Callee->getName() == "exp2" &&
1184 TLI->has(LibFunc::exp2f)) {
1185 Ret = optimizeUnaryDoubleFP(CI, B, true);
Bob Wilsond8d92d92013-11-03 06:48:38 +00001186 }
1187
Chris Bienemanad070d02014-09-17 20:55:46 +00001188 FunctionType *FT = Callee->getFunctionType();
1189 // Just make sure this has 1 argument of FP type, which matches the
1190 // result type.
1191 if (FT->getNumParams() != 1 || FT->getReturnType() != FT->getParamType(0) ||
1192 !FT->getParamType(0)->isFloatingPointTy())
1193 return Ret;
1194
1195 Value *Op = CI->getArgOperand(0);
1196 // Turn exp2(sitofp(x)) -> ldexp(1.0, sext(x)) if sizeof(x) <= 32
1197 // Turn exp2(uitofp(x)) -> ldexp(1.0, zext(x)) if sizeof(x) < 32
1198 LibFunc::Func LdExp = LibFunc::ldexpl;
1199 if (Op->getType()->isFloatTy())
1200 LdExp = LibFunc::ldexpf;
1201 else if (Op->getType()->isDoubleTy())
1202 LdExp = LibFunc::ldexp;
1203
1204 if (TLI->has(LdExp)) {
1205 Value *LdExpArg = nullptr;
1206 if (SIToFPInst *OpC = dyn_cast<SIToFPInst>(Op)) {
1207 if (OpC->getOperand(0)->getType()->getPrimitiveSizeInBits() <= 32)
1208 LdExpArg = B.CreateSExt(OpC->getOperand(0), B.getInt32Ty());
1209 } else if (UIToFPInst *OpC = dyn_cast<UIToFPInst>(Op)) {
1210 if (OpC->getOperand(0)->getType()->getPrimitiveSizeInBits() < 32)
1211 LdExpArg = B.CreateZExt(OpC->getOperand(0), B.getInt32Ty());
1212 }
1213
1214 if (LdExpArg) {
1215 Constant *One = ConstantFP::get(CI->getContext(), APFloat(1.0f));
1216 if (!Op->getType()->isFloatTy())
1217 One = ConstantExpr::getFPExtend(One, Op->getType());
1218
1219 Module *M = Caller->getParent();
1220 Value *Callee =
1221 M->getOrInsertFunction(TLI->getName(LdExp), Op->getType(),
1222 Op->getType(), B.getInt32Ty(), NULL);
1223 CallInst *CI = B.CreateCall2(Callee, One, LdExpArg);
1224 if (const Function *F = dyn_cast<Function>(Callee->stripPointerCasts()))
1225 CI->setCallingConv(F->getCallingConv());
1226
1227 return CI;
1228 }
1229 }
1230 return Ret;
1231}
1232
Sanjay Patel0ca42bb2014-10-14 20:43:11 +00001233Value *LibCallSimplifier::optimizeFabs(CallInst *CI, IRBuilder<> &B) {
1234 Function *Callee = CI->getCalledFunction();
1235
1236 Value *Ret = nullptr;
1237 if (Callee->getName() == "fabs" && TLI->has(LibFunc::fabsf)) {
1238 Ret = optimizeUnaryDoubleFP(CI, B, false);
1239 }
1240
1241 FunctionType *FT = Callee->getFunctionType();
1242 // Make sure this has 1 argument of FP type which matches the result type.
1243 if (FT->getNumParams() != 1 || FT->getReturnType() != FT->getParamType(0) ||
1244 !FT->getParamType(0)->isFloatingPointTy())
1245 return Ret;
1246
1247 Value *Op = CI->getArgOperand(0);
1248 if (Instruction *I = dyn_cast<Instruction>(Op)) {
1249 // Fold fabs(x * x) -> x * x; any squared FP value must already be positive.
1250 if (I->getOpcode() == Instruction::FMul)
1251 if (I->getOperand(0) == I->getOperand(1))
1252 return Op;
1253 }
1254 return Ret;
1255}
1256
Chris Bienemanad070d02014-09-17 20:55:46 +00001257static bool isTrigLibCall(CallInst *CI);
1258static void insertSinCosCall(IRBuilder<> &B, Function *OrigCallee, Value *Arg,
1259 bool UseFloat, Value *&Sin, Value *&Cos,
1260 Value *&SinCos);
1261
1262Value *LibCallSimplifier::optimizeSinCosPi(CallInst *CI, IRBuilder<> &B) {
1263
1264 // Make sure the prototype is as expected, otherwise the rest of the
1265 // function is probably invalid and likely to abort.
1266 if (!isTrigLibCall(CI))
1267 return nullptr;
1268
1269 Value *Arg = CI->getArgOperand(0);
1270 SmallVector<CallInst *, 1> SinCalls;
1271 SmallVector<CallInst *, 1> CosCalls;
1272 SmallVector<CallInst *, 1> SinCosCalls;
1273
1274 bool IsFloat = Arg->getType()->isFloatTy();
1275
1276 // Look for all compatible sinpi, cospi and sincospi calls with the same
1277 // argument. If there are enough (in some sense) we can make the
1278 // substitution.
1279 for (User *U : Arg->users())
1280 classifyArgUse(U, CI->getParent(), IsFloat, SinCalls, CosCalls,
1281 SinCosCalls);
1282
1283 // It's only worthwhile if both sinpi and cospi are actually used.
1284 if (SinCosCalls.empty() && (SinCalls.empty() || CosCalls.empty()))
1285 return nullptr;
1286
1287 Value *Sin, *Cos, *SinCos;
1288 insertSinCosCall(B, CI->getCalledFunction(), Arg, IsFloat, Sin, Cos, SinCos);
1289
1290 replaceTrigInsts(SinCalls, Sin);
1291 replaceTrigInsts(CosCalls, Cos);
1292 replaceTrigInsts(SinCosCalls, SinCos);
1293
1294 return nullptr;
1295}
1296
1297static bool isTrigLibCall(CallInst *CI) {
1298 Function *Callee = CI->getCalledFunction();
1299 FunctionType *FT = Callee->getFunctionType();
1300
1301 // We can only hope to do anything useful if we can ignore things like errno
1302 // and floating-point exceptions.
1303 bool AttributesSafe =
1304 CI->hasFnAttr(Attribute::NoUnwind) && CI->hasFnAttr(Attribute::ReadNone);
1305
1306 // Other than that we need float(float) or double(double)
1307 return AttributesSafe && FT->getNumParams() == 1 &&
1308 FT->getReturnType() == FT->getParamType(0) &&
1309 (FT->getParamType(0)->isFloatTy() ||
1310 FT->getParamType(0)->isDoubleTy());
1311}
1312
1313void
1314LibCallSimplifier::classifyArgUse(Value *Val, BasicBlock *BB, bool IsFloat,
1315 SmallVectorImpl<CallInst *> &SinCalls,
1316 SmallVectorImpl<CallInst *> &CosCalls,
1317 SmallVectorImpl<CallInst *> &SinCosCalls) {
1318 CallInst *CI = dyn_cast<CallInst>(Val);
1319
1320 if (!CI)
1321 return;
1322
1323 Function *Callee = CI->getCalledFunction();
1324 StringRef FuncName = Callee->getName();
1325 LibFunc::Func Func;
1326 if (!TLI->getLibFunc(FuncName, Func) || !TLI->has(Func) || !isTrigLibCall(CI))
1327 return;
1328
1329 if (IsFloat) {
1330 if (Func == LibFunc::sinpif)
1331 SinCalls.push_back(CI);
1332 else if (Func == LibFunc::cospif)
1333 CosCalls.push_back(CI);
1334 else if (Func == LibFunc::sincospif_stret)
1335 SinCosCalls.push_back(CI);
1336 } else {
1337 if (Func == LibFunc::sinpi)
1338 SinCalls.push_back(CI);
1339 else if (Func == LibFunc::cospi)
1340 CosCalls.push_back(CI);
1341 else if (Func == LibFunc::sincospi_stret)
1342 SinCosCalls.push_back(CI);
1343 }
1344}
1345
1346void LibCallSimplifier::replaceTrigInsts(SmallVectorImpl<CallInst *> &Calls,
1347 Value *Res) {
1348 for (SmallVectorImpl<CallInst *>::iterator I = Calls.begin(), E = Calls.end();
1349 I != E; ++I) {
1350 replaceAllUsesWith(*I, Res);
1351 }
1352}
1353
1354void insertSinCosCall(IRBuilder<> &B, Function *OrigCallee, Value *Arg,
1355 bool UseFloat, Value *&Sin, Value *&Cos, Value *&SinCos) {
1356 Type *ArgTy = Arg->getType();
1357 Type *ResTy;
1358 StringRef Name;
1359
1360 Triple T(OrigCallee->getParent()->getTargetTriple());
1361 if (UseFloat) {
1362 Name = "__sincospif_stret";
1363
1364 assert(T.getArch() != Triple::x86 && "x86 messy and unsupported for now");
1365 // x86_64 can't use {float, float} since that would be returned in both
1366 // xmm0 and xmm1, which isn't what a real struct would do.
1367 ResTy = T.getArch() == Triple::x86_64
1368 ? static_cast<Type *>(VectorType::get(ArgTy, 2))
1369 : static_cast<Type *>(StructType::get(ArgTy, ArgTy, NULL));
1370 } else {
1371 Name = "__sincospi_stret";
1372 ResTy = StructType::get(ArgTy, ArgTy, NULL);
1373 }
1374
1375 Module *M = OrigCallee->getParent();
1376 Value *Callee = M->getOrInsertFunction(Name, OrigCallee->getAttributes(),
1377 ResTy, ArgTy, NULL);
1378
1379 if (Instruction *ArgInst = dyn_cast<Instruction>(Arg)) {
1380 // If the argument is an instruction, it must dominate all uses so put our
1381 // sincos call there.
1382 BasicBlock::iterator Loc = ArgInst;
1383 B.SetInsertPoint(ArgInst->getParent(), ++Loc);
1384 } else {
1385 // Otherwise (e.g. for a constant) the beginning of the function is as
1386 // good a place as any.
1387 BasicBlock &EntryBB = B.GetInsertBlock()->getParent()->getEntryBlock();
1388 B.SetInsertPoint(&EntryBB, EntryBB.begin());
1389 }
1390
1391 SinCos = B.CreateCall(Callee, Arg, "sincospi");
1392
1393 if (SinCos->getType()->isStructTy()) {
1394 Sin = B.CreateExtractValue(SinCos, 0, "sinpi");
1395 Cos = B.CreateExtractValue(SinCos, 1, "cospi");
1396 } else {
1397 Sin = B.CreateExtractElement(SinCos, ConstantInt::get(B.getInt32Ty(), 0),
1398 "sinpi");
1399 Cos = B.CreateExtractElement(SinCos, ConstantInt::get(B.getInt32Ty(), 1),
1400 "cospi");
1401 }
1402}
Bob Wilsond8d92d92013-11-03 06:48:38 +00001403
Meador Inge7415f842012-11-25 20:45:27 +00001404//===----------------------------------------------------------------------===//
1405// Integer Library Call Optimizations
1406//===----------------------------------------------------------------------===//
1407
Chris Bienemanad070d02014-09-17 20:55:46 +00001408Value *LibCallSimplifier::optimizeFFS(CallInst *CI, IRBuilder<> &B) {
1409 Function *Callee = CI->getCalledFunction();
1410 FunctionType *FT = Callee->getFunctionType();
1411 // Just make sure this has 2 arguments of the same FP type, which match the
1412 // result type.
1413 if (FT->getNumParams() != 1 || !FT->getReturnType()->isIntegerTy(32) ||
1414 !FT->getParamType(0)->isIntegerTy())
1415 return nullptr;
Meador Inge7415f842012-11-25 20:45:27 +00001416
Chris Bienemanad070d02014-09-17 20:55:46 +00001417 Value *Op = CI->getArgOperand(0);
Meador Inge7415f842012-11-25 20:45:27 +00001418
Chris Bienemanad070d02014-09-17 20:55:46 +00001419 // Constant fold.
1420 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op)) {
1421 if (CI->isZero()) // ffs(0) -> 0.
1422 return B.getInt32(0);
1423 // ffs(c) -> cttz(c)+1
1424 return B.getInt32(CI->getValue().countTrailingZeros() + 1);
Meador Inge7415f842012-11-25 20:45:27 +00001425 }
Meador Inge7415f842012-11-25 20:45:27 +00001426
Chris Bienemanad070d02014-09-17 20:55:46 +00001427 // ffs(x) -> x != 0 ? (i32)llvm.cttz(x)+1 : 0
1428 Type *ArgType = Op->getType();
1429 Value *F =
1430 Intrinsic::getDeclaration(Callee->getParent(), Intrinsic::cttz, ArgType);
1431 Value *V = B.CreateCall2(F, Op, B.getFalse(), "cttz");
1432 V = B.CreateAdd(V, ConstantInt::get(V->getType(), 1));
1433 V = B.CreateIntCast(V, B.getInt32Ty(), false);
Meador Ingea0b6d872012-11-26 00:24:07 +00001434
Chris Bienemanad070d02014-09-17 20:55:46 +00001435 Value *Cond = B.CreateICmpNE(Op, Constant::getNullValue(ArgType));
1436 return B.CreateSelect(Cond, V, B.getInt32(0));
1437}
Meador Ingea0b6d872012-11-26 00:24:07 +00001438
Chris Bienemanad070d02014-09-17 20:55:46 +00001439Value *LibCallSimplifier::optimizeAbs(CallInst *CI, IRBuilder<> &B) {
1440 Function *Callee = CI->getCalledFunction();
1441 FunctionType *FT = Callee->getFunctionType();
1442 // We require integer(integer) where the types agree.
1443 if (FT->getNumParams() != 1 || !FT->getReturnType()->isIntegerTy() ||
1444 FT->getParamType(0) != FT->getReturnType())
1445 return nullptr;
Meador Inge9a59ab62012-11-26 02:31:59 +00001446
Chris Bienemanad070d02014-09-17 20:55:46 +00001447 // abs(x) -> x >s -1 ? x : -x
1448 Value *Op = CI->getArgOperand(0);
1449 Value *Pos =
1450 B.CreateICmpSGT(Op, Constant::getAllOnesValue(Op->getType()), "ispos");
1451 Value *Neg = B.CreateNeg(Op, "neg");
1452 return B.CreateSelect(Pos, Op, Neg);
1453}
Meador Inge9a59ab62012-11-26 02:31:59 +00001454
Chris Bienemanad070d02014-09-17 20:55:46 +00001455Value *LibCallSimplifier::optimizeIsDigit(CallInst *CI, IRBuilder<> &B) {
1456 Function *Callee = CI->getCalledFunction();
1457 FunctionType *FT = Callee->getFunctionType();
1458 // We require integer(i32)
1459 if (FT->getNumParams() != 1 || !FT->getReturnType()->isIntegerTy() ||
1460 !FT->getParamType(0)->isIntegerTy(32))
1461 return nullptr;
Meador Ingea62a39e2012-11-26 03:10:07 +00001462
Chris Bienemanad070d02014-09-17 20:55:46 +00001463 // isdigit(c) -> (c-'0') <u 10
1464 Value *Op = CI->getArgOperand(0);
1465 Op = B.CreateSub(Op, B.getInt32('0'), "isdigittmp");
1466 Op = B.CreateICmpULT(Op, B.getInt32(10), "isdigit");
1467 return B.CreateZExt(Op, CI->getType());
1468}
Meador Ingea62a39e2012-11-26 03:10:07 +00001469
Chris Bienemanad070d02014-09-17 20:55:46 +00001470Value *LibCallSimplifier::optimizeIsAscii(CallInst *CI, IRBuilder<> &B) {
1471 Function *Callee = CI->getCalledFunction();
1472 FunctionType *FT = Callee->getFunctionType();
1473 // We require integer(i32)
1474 if (FT->getNumParams() != 1 || !FT->getReturnType()->isIntegerTy() ||
1475 !FT->getParamType(0)->isIntegerTy(32))
1476 return nullptr;
Meador Inge604937d2012-11-26 03:38:52 +00001477
Chris Bienemanad070d02014-09-17 20:55:46 +00001478 // isascii(c) -> c <u 128
1479 Value *Op = CI->getArgOperand(0);
1480 Op = B.CreateICmpULT(Op, B.getInt32(128), "isascii");
1481 return B.CreateZExt(Op, CI->getType());
1482}
1483
1484Value *LibCallSimplifier::optimizeToAscii(CallInst *CI, IRBuilder<> &B) {
1485 Function *Callee = CI->getCalledFunction();
1486 FunctionType *FT = Callee->getFunctionType();
1487 // We require i32(i32)
1488 if (FT->getNumParams() != 1 || FT->getReturnType() != FT->getParamType(0) ||
1489 !FT->getParamType(0)->isIntegerTy(32))
1490 return nullptr;
1491
1492 // toascii(c) -> c & 0x7f
1493 return B.CreateAnd(CI->getArgOperand(0),
1494 ConstantInt::get(CI->getType(), 0x7F));
1495}
Meador Inge604937d2012-11-26 03:38:52 +00001496
Meador Inge08ca1152012-11-26 20:37:20 +00001497//===----------------------------------------------------------------------===//
1498// Formatting and IO Library Call Optimizations
1499//===----------------------------------------------------------------------===//
1500
Chris Bienemanad070d02014-09-17 20:55:46 +00001501static bool isReportingError(Function *Callee, CallInst *CI, int StreamArg);
Hal Finkel66cd3f12013-11-17 02:06:35 +00001502
Chris Bienemanad070d02014-09-17 20:55:46 +00001503Value *LibCallSimplifier::optimizeErrorReporting(CallInst *CI, IRBuilder<> &B,
1504 int StreamArg) {
1505 // Error reporting calls should be cold, mark them as such.
1506 // This applies even to non-builtin calls: it is only a hint and applies to
1507 // functions that the frontend might not understand as builtins.
Hal Finkel66cd3f12013-11-17 02:06:35 +00001508
Chris Bienemanad070d02014-09-17 20:55:46 +00001509 // This heuristic was suggested in:
1510 // Improving Static Branch Prediction in a Compiler
1511 // Brian L. Deitrich, Ben-Chung Cheng, Wen-mei W. Hwu
1512 // Proceedings of PACT'98, Oct. 1998, IEEE
1513 Function *Callee = CI->getCalledFunction();
Hal Finkel66cd3f12013-11-17 02:06:35 +00001514
Chris Bienemanad070d02014-09-17 20:55:46 +00001515 if (!CI->hasFnAttr(Attribute::Cold) &&
1516 isReportingError(Callee, CI, StreamArg)) {
1517 CI->addAttribute(AttributeSet::FunctionIndex, Attribute::Cold);
1518 }
Hal Finkel66cd3f12013-11-17 02:06:35 +00001519
Chris Bienemanad070d02014-09-17 20:55:46 +00001520 return nullptr;
1521}
1522
1523static bool isReportingError(Function *Callee, CallInst *CI, int StreamArg) {
1524 if (!ColdErrorCalls)
1525 return false;
1526
1527 if (!Callee || !Callee->isDeclaration())
1528 return false;
1529
1530 if (StreamArg < 0)
1531 return true;
1532
1533 // These functions might be considered cold, but only if their stream
1534 // argument is stderr.
1535
1536 if (StreamArg >= (int)CI->getNumArgOperands())
1537 return false;
1538 LoadInst *LI = dyn_cast<LoadInst>(CI->getArgOperand(StreamArg));
1539 if (!LI)
1540 return false;
1541 GlobalVariable *GV = dyn_cast<GlobalVariable>(LI->getPointerOperand());
1542 if (!GV || !GV->isDeclaration())
1543 return false;
1544 return GV->getName() == "stderr";
1545}
1546
1547Value *LibCallSimplifier::optimizePrintFString(CallInst *CI, IRBuilder<> &B) {
1548 // Check for a fixed format string.
1549 StringRef FormatStr;
1550 if (!getConstantStringInfo(CI->getArgOperand(0), FormatStr))
Craig Topperf40110f2014-04-25 05:29:35 +00001551 return nullptr;
Hal Finkel66cd3f12013-11-17 02:06:35 +00001552
Chris Bienemanad070d02014-09-17 20:55:46 +00001553 // Empty format string -> noop.
1554 if (FormatStr.empty()) // Tolerate printf's declared void.
1555 return CI->use_empty() ? (Value *)CI : ConstantInt::get(CI->getType(), 0);
Hal Finkel66cd3f12013-11-17 02:06:35 +00001556
Chris Bienemanad070d02014-09-17 20:55:46 +00001557 // Do not do any of the following transformations if the printf return value
1558 // is used, in general the printf return value is not compatible with either
1559 // putchar() or puts().
1560 if (!CI->use_empty())
Craig Topperf40110f2014-04-25 05:29:35 +00001561 return nullptr;
Chris Bienemanad070d02014-09-17 20:55:46 +00001562
1563 // printf("x") -> putchar('x'), even for '%'.
1564 if (FormatStr.size() == 1) {
1565 Value *Res = EmitPutChar(B.getInt32(FormatStr[0]), B, DL, TLI);
1566 if (CI->use_empty() || !Res)
1567 return Res;
1568 return B.CreateIntCast(Res, CI->getType(), true);
Meador Inge08ca1152012-11-26 20:37:20 +00001569 }
1570
Chris Bienemanad070d02014-09-17 20:55:46 +00001571 // printf("foo\n") --> puts("foo")
1572 if (FormatStr[FormatStr.size() - 1] == '\n' &&
1573 FormatStr.find('%') == StringRef::npos) { // No format characters.
1574 // Create a string literal with no \n on it. We expect the constant merge
1575 // pass to be run after this pass, to merge duplicate strings.
1576 FormatStr = FormatStr.drop_back();
1577 Value *GV = B.CreateGlobalString(FormatStr, "str");
1578 Value *NewCI = EmitPutS(GV, B, DL, TLI);
1579 return (CI->use_empty() || !NewCI)
1580 ? NewCI
1581 : ConstantInt::get(CI->getType(), FormatStr.size() + 1);
1582 }
Meador Inge08ca1152012-11-26 20:37:20 +00001583
Chris Bienemanad070d02014-09-17 20:55:46 +00001584 // Optimize specific format strings.
1585 // printf("%c", chr) --> putchar(chr)
1586 if (FormatStr == "%c" && CI->getNumArgOperands() > 1 &&
1587 CI->getArgOperand(1)->getType()->isIntegerTy()) {
1588 Value *Res = EmitPutChar(CI->getArgOperand(1), B, DL, TLI);
Meador Inge08ca1152012-11-26 20:37:20 +00001589
Chris Bienemanad070d02014-09-17 20:55:46 +00001590 if (CI->use_empty() || !Res)
1591 return Res;
1592 return B.CreateIntCast(Res, CI->getType(), true);
1593 }
1594
1595 // printf("%s\n", str) --> puts(str)
1596 if (FormatStr == "%s\n" && CI->getNumArgOperands() > 1 &&
1597 CI->getArgOperand(1)->getType()->isPointerTy()) {
1598 return EmitPutS(CI->getArgOperand(1), B, DL, TLI);
1599 }
1600 return nullptr;
1601}
1602
1603Value *LibCallSimplifier::optimizePrintF(CallInst *CI, IRBuilder<> &B) {
1604
1605 Function *Callee = CI->getCalledFunction();
1606 // Require one fixed pointer argument and an integer/void result.
1607 FunctionType *FT = Callee->getFunctionType();
1608 if (FT->getNumParams() < 1 || !FT->getParamType(0)->isPointerTy() ||
1609 !(FT->getReturnType()->isIntegerTy() || FT->getReturnType()->isVoidTy()))
1610 return nullptr;
1611
1612 if (Value *V = optimizePrintFString(CI, B)) {
1613 return V;
1614 }
1615
1616 // printf(format, ...) -> iprintf(format, ...) if no floating point
1617 // arguments.
1618 if (TLI->has(LibFunc::iprintf) && !callHasFloatingPointArgument(CI)) {
1619 Module *M = B.GetInsertBlock()->getParent()->getParent();
1620 Constant *IPrintFFn =
Meador Inge08ca1152012-11-26 20:37:20 +00001621 M->getOrInsertFunction("iprintf", FT, Callee->getAttributes());
Chris Bienemanad070d02014-09-17 20:55:46 +00001622 CallInst *New = cast<CallInst>(CI->clone());
1623 New->setCalledFunction(IPrintFFn);
1624 B.Insert(New);
1625 return New;
Meador Inge08ca1152012-11-26 20:37:20 +00001626 }
Chris Bienemanad070d02014-09-17 20:55:46 +00001627 return nullptr;
1628}
Meador Inge08ca1152012-11-26 20:37:20 +00001629
Chris Bienemanad070d02014-09-17 20:55:46 +00001630Value *LibCallSimplifier::optimizeSPrintFString(CallInst *CI, IRBuilder<> &B) {
1631 // Check for a fixed format string.
1632 StringRef FormatStr;
1633 if (!getConstantStringInfo(CI->getArgOperand(1), FormatStr))
Craig Topperf40110f2014-04-25 05:29:35 +00001634 return nullptr;
Meador Inge25c9b3b2012-11-27 05:57:54 +00001635
Chris Bienemanad070d02014-09-17 20:55:46 +00001636 // If we just have a format string (nothing else crazy) transform it.
1637 if (CI->getNumArgOperands() == 2) {
1638 // Make sure there's no % in the constant array. We could try to handle
1639 // %% -> % in the future if we cared.
1640 for (unsigned i = 0, e = FormatStr.size(); i != e; ++i)
1641 if (FormatStr[i] == '%')
1642 return nullptr; // we found a format specifier, bail out.
Hal Finkel66cd3f12013-11-17 02:06:35 +00001643
Meador Ingef8e72502012-11-29 15:45:43 +00001644 // These optimizations require DataLayout.
Chris Bienemanad070d02014-09-17 20:55:46 +00001645 if (!DL)
Craig Topperf40110f2014-04-25 05:29:35 +00001646 return nullptr;
Meador Ingef8e72502012-11-29 15:45:43 +00001647
Chris Bienemanad070d02014-09-17 20:55:46 +00001648 // sprintf(str, fmt) -> llvm.memcpy(str, fmt, strlen(fmt)+1, 1)
1649 B.CreateMemCpy(
1650 CI->getArgOperand(0), CI->getArgOperand(1),
1651 ConstantInt::get(DL->getIntPtrType(CI->getContext()),
1652 FormatStr.size() + 1),
1653 1); // Copy the null byte.
1654 return ConstantInt::get(CI->getType(), FormatStr.size());
Meador Ingef8e72502012-11-29 15:45:43 +00001655 }
Meador Ingef8e72502012-11-29 15:45:43 +00001656
Chris Bienemanad070d02014-09-17 20:55:46 +00001657 // The remaining optimizations require the format string to be "%s" or "%c"
1658 // and have an extra operand.
1659 if (FormatStr.size() != 2 || FormatStr[0] != '%' ||
1660 CI->getNumArgOperands() < 3)
Craig Topperf40110f2014-04-25 05:29:35 +00001661 return nullptr;
Meador Inge75798bb2012-11-29 19:15:17 +00001662
Chris Bienemanad070d02014-09-17 20:55:46 +00001663 // Decode the second character of the format string.
1664 if (FormatStr[1] == 'c') {
1665 // sprintf(dst, "%c", chr) --> *(i8*)dst = chr; *((i8*)dst+1) = 0
1666 if (!CI->getArgOperand(2)->getType()->isIntegerTy())
1667 return nullptr;
1668 Value *V = B.CreateTrunc(CI->getArgOperand(2), B.getInt8Ty(), "char");
1669 Value *Ptr = CastToCStr(CI->getArgOperand(0), B);
1670 B.CreateStore(V, Ptr);
1671 Ptr = B.CreateGEP(Ptr, B.getInt32(1), "nul");
1672 B.CreateStore(B.getInt8(0), Ptr);
Meador Ingedf796f82012-10-13 16:45:24 +00001673
Chris Bienemanad070d02014-09-17 20:55:46 +00001674 return ConstantInt::get(CI->getType(), 1);
Meador Ingedf796f82012-10-13 16:45:24 +00001675 }
1676
Chris Bienemanad070d02014-09-17 20:55:46 +00001677 if (FormatStr[1] == 's') {
1678 // These optimizations require DataLayout.
1679 if (!DL)
1680 return nullptr;
Meador Ingedf796f82012-10-13 16:45:24 +00001681
Chris Bienemanad070d02014-09-17 20:55:46 +00001682 // sprintf(dest, "%s", str) -> llvm.memcpy(dest, str, strlen(str)+1, 1)
1683 if (!CI->getArgOperand(2)->getType()->isPointerTy())
1684 return nullptr;
1685
1686 Value *Len = EmitStrLen(CI->getArgOperand(2), B, DL, TLI);
1687 if (!Len)
1688 return nullptr;
1689 Value *IncLen =
1690 B.CreateAdd(Len, ConstantInt::get(Len->getType(), 1), "leninc");
1691 B.CreateMemCpy(CI->getArgOperand(0), CI->getArgOperand(2), IncLen, 1);
1692
1693 // The sprintf result is the unincremented number of bytes in the string.
1694 return B.CreateIntCast(Len, CI->getType(), false);
1695 }
1696 return nullptr;
1697}
1698
1699Value *LibCallSimplifier::optimizeSPrintF(CallInst *CI, IRBuilder<> &B) {
1700 Function *Callee = CI->getCalledFunction();
1701 // Require two fixed pointer arguments and an integer result.
1702 FunctionType *FT = Callee->getFunctionType();
1703 if (FT->getNumParams() != 2 || !FT->getParamType(0)->isPointerTy() ||
1704 !FT->getParamType(1)->isPointerTy() ||
1705 !FT->getReturnType()->isIntegerTy())
1706 return nullptr;
1707
1708 if (Value *V = optimizeSPrintFString(CI, B)) {
1709 return V;
1710 }
1711
1712 // sprintf(str, format, ...) -> siprintf(str, format, ...) if no floating
1713 // point arguments.
1714 if (TLI->has(LibFunc::siprintf) && !callHasFloatingPointArgument(CI)) {
1715 Module *M = B.GetInsertBlock()->getParent()->getParent();
1716 Constant *SIPrintFFn =
1717 M->getOrInsertFunction("siprintf", FT, Callee->getAttributes());
1718 CallInst *New = cast<CallInst>(CI->clone());
1719 New->setCalledFunction(SIPrintFFn);
1720 B.Insert(New);
1721 return New;
1722 }
1723 return nullptr;
1724}
1725
1726Value *LibCallSimplifier::optimizeFPrintFString(CallInst *CI, IRBuilder<> &B) {
1727 optimizeErrorReporting(CI, B, 0);
1728
1729 // All the optimizations depend on the format string.
1730 StringRef FormatStr;
1731 if (!getConstantStringInfo(CI->getArgOperand(1), FormatStr))
1732 return nullptr;
1733
1734 // Do not do any of the following transformations if the fprintf return
1735 // value is used, in general the fprintf return value is not compatible
1736 // with fwrite(), fputc() or fputs().
1737 if (!CI->use_empty())
1738 return nullptr;
1739
1740 // fprintf(F, "foo") --> fwrite("foo", 3, 1, F)
1741 if (CI->getNumArgOperands() == 2) {
1742 for (unsigned i = 0, e = FormatStr.size(); i != e; ++i)
1743 if (FormatStr[i] == '%') // Could handle %% -> % if we cared.
1744 return nullptr; // We found a format specifier.
1745
1746 // These optimizations require DataLayout.
1747 if (!DL)
1748 return nullptr;
1749
1750 return EmitFWrite(
1751 CI->getArgOperand(1),
1752 ConstantInt::get(DL->getIntPtrType(CI->getContext()), FormatStr.size()),
1753 CI->getArgOperand(0), B, DL, TLI);
1754 }
1755
1756 // The remaining optimizations require the format string to be "%s" or "%c"
1757 // and have an extra operand.
1758 if (FormatStr.size() != 2 || FormatStr[0] != '%' ||
1759 CI->getNumArgOperands() < 3)
1760 return nullptr;
1761
1762 // Decode the second character of the format string.
1763 if (FormatStr[1] == 'c') {
1764 // fprintf(F, "%c", chr) --> fputc(chr, F)
1765 if (!CI->getArgOperand(2)->getType()->isIntegerTy())
1766 return nullptr;
1767 return EmitFPutC(CI->getArgOperand(2), CI->getArgOperand(0), B, DL, TLI);
1768 }
1769
1770 if (FormatStr[1] == 's') {
1771 // fprintf(F, "%s", str) --> fputs(str, F)
1772 if (!CI->getArgOperand(2)->getType()->isPointerTy())
1773 return nullptr;
1774 return EmitFPutS(CI->getArgOperand(2), CI->getArgOperand(0), B, DL, TLI);
1775 }
1776 return nullptr;
1777}
1778
1779Value *LibCallSimplifier::optimizeFPrintF(CallInst *CI, IRBuilder<> &B) {
1780 Function *Callee = CI->getCalledFunction();
1781 // Require two fixed paramters as pointers and integer result.
1782 FunctionType *FT = Callee->getFunctionType();
1783 if (FT->getNumParams() != 2 || !FT->getParamType(0)->isPointerTy() ||
1784 !FT->getParamType(1)->isPointerTy() ||
1785 !FT->getReturnType()->isIntegerTy())
1786 return nullptr;
1787
1788 if (Value *V = optimizeFPrintFString(CI, B)) {
1789 return V;
1790 }
1791
1792 // fprintf(stream, format, ...) -> fiprintf(stream, format, ...) if no
1793 // floating point arguments.
1794 if (TLI->has(LibFunc::fiprintf) && !callHasFloatingPointArgument(CI)) {
1795 Module *M = B.GetInsertBlock()->getParent()->getParent();
1796 Constant *FIPrintFFn =
1797 M->getOrInsertFunction("fiprintf", FT, Callee->getAttributes());
1798 CallInst *New = cast<CallInst>(CI->clone());
1799 New->setCalledFunction(FIPrintFFn);
1800 B.Insert(New);
1801 return New;
1802 }
1803 return nullptr;
1804}
1805
1806Value *LibCallSimplifier::optimizeFWrite(CallInst *CI, IRBuilder<> &B) {
1807 optimizeErrorReporting(CI, B, 3);
1808
1809 Function *Callee = CI->getCalledFunction();
1810 // Require a pointer, an integer, an integer, a pointer, returning integer.
1811 FunctionType *FT = Callee->getFunctionType();
1812 if (FT->getNumParams() != 4 || !FT->getParamType(0)->isPointerTy() ||
1813 !FT->getParamType(1)->isIntegerTy() ||
1814 !FT->getParamType(2)->isIntegerTy() ||
1815 !FT->getParamType(3)->isPointerTy() ||
1816 !FT->getReturnType()->isIntegerTy())
1817 return nullptr;
1818
1819 // Get the element size and count.
1820 ConstantInt *SizeC = dyn_cast<ConstantInt>(CI->getArgOperand(1));
1821 ConstantInt *CountC = dyn_cast<ConstantInt>(CI->getArgOperand(2));
1822 if (!SizeC || !CountC)
1823 return nullptr;
1824 uint64_t Bytes = SizeC->getZExtValue() * CountC->getZExtValue();
1825
1826 // If this is writing zero records, remove the call (it's a noop).
1827 if (Bytes == 0)
1828 return ConstantInt::get(CI->getType(), 0);
1829
1830 // If this is writing one byte, turn it into fputc.
1831 // This optimisation is only valid, if the return value is unused.
1832 if (Bytes == 1 && CI->use_empty()) { // fwrite(S,1,1,F) -> fputc(S[0],F)
1833 Value *Char = B.CreateLoad(CastToCStr(CI->getArgOperand(0), B), "char");
1834 Value *NewCI = EmitFPutC(Char, CI->getArgOperand(3), B, DL, TLI);
1835 return NewCI ? ConstantInt::get(CI->getType(), 1) : nullptr;
1836 }
1837
1838 return nullptr;
1839}
1840
1841Value *LibCallSimplifier::optimizeFPuts(CallInst *CI, IRBuilder<> &B) {
1842 optimizeErrorReporting(CI, B, 1);
1843
1844 Function *Callee = CI->getCalledFunction();
1845
1846 // These optimizations require DataLayout.
1847 if (!DL)
1848 return nullptr;
1849
1850 // Require two pointers. Also, we can't optimize if return value is used.
1851 FunctionType *FT = Callee->getFunctionType();
1852 if (FT->getNumParams() != 2 || !FT->getParamType(0)->isPointerTy() ||
1853 !FT->getParamType(1)->isPointerTy() || !CI->use_empty())
1854 return nullptr;
1855
1856 // fputs(s,F) --> fwrite(s,1,strlen(s),F)
1857 uint64_t Len = GetStringLength(CI->getArgOperand(0));
1858 if (!Len)
1859 return nullptr;
1860
1861 // Known to have no uses (see above).
1862 return EmitFWrite(
1863 CI->getArgOperand(0),
1864 ConstantInt::get(DL->getIntPtrType(CI->getContext()), Len - 1),
1865 CI->getArgOperand(1), B, DL, TLI);
1866}
1867
1868Value *LibCallSimplifier::optimizePuts(CallInst *CI, IRBuilder<> &B) {
1869 Function *Callee = CI->getCalledFunction();
1870 // Require one fixed pointer argument and an integer/void result.
1871 FunctionType *FT = Callee->getFunctionType();
1872 if (FT->getNumParams() < 1 || !FT->getParamType(0)->isPointerTy() ||
1873 !(FT->getReturnType()->isIntegerTy() || FT->getReturnType()->isVoidTy()))
1874 return nullptr;
1875
1876 // Check for a constant string.
1877 StringRef Str;
1878 if (!getConstantStringInfo(CI->getArgOperand(0), Str))
1879 return nullptr;
1880
1881 if (Str.empty() && CI->use_empty()) {
1882 // puts("") -> putchar('\n')
1883 Value *Res = EmitPutChar(B.getInt32('\n'), B, DL, TLI);
1884 if (CI->use_empty() || !Res)
1885 return Res;
1886 return B.CreateIntCast(Res, CI->getType(), true);
1887 }
1888
1889 return nullptr;
1890}
1891
1892bool LibCallSimplifier::hasFloatVersion(StringRef FuncName) {
Meador Inge20255ef2013-03-12 00:08:29 +00001893 LibFunc::Func Func;
1894 SmallString<20> FloatFuncName = FuncName;
1895 FloatFuncName += 'f';
1896 if (TLI->getLibFunc(FloatFuncName, Func))
1897 return TLI->has(Func);
1898 return false;
1899}
Meador Inge7fb2f732012-10-13 16:45:32 +00001900
Chris Bienemanad070d02014-09-17 20:55:46 +00001901Value *LibCallSimplifier::optimizeCall(CallInst *CI) {
1902 if (CI->isNoBuiltin())
1903 return nullptr;
Meador Inge4d2827c2012-11-11 05:11:20 +00001904
Meador Inge20255ef2013-03-12 00:08:29 +00001905 LibFunc::Func Func;
1906 Function *Callee = CI->getCalledFunction();
1907 StringRef FuncName = Callee->getName();
Chris Bienemanad070d02014-09-17 20:55:46 +00001908 IRBuilder<> Builder(CI);
1909 bool isCallingConvC = CI->getCallingConv() == llvm::CallingConv::C;
Meador Inge20255ef2013-03-12 00:08:29 +00001910
1911 // Next check for intrinsics.
1912 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(CI)) {
Chris Bienemanad070d02014-09-17 20:55:46 +00001913 if (!isCallingConvC)
1914 return nullptr;
Meador Inge20255ef2013-03-12 00:08:29 +00001915 switch (II->getIntrinsicID()) {
1916 case Intrinsic::pow:
Chris Bienemanad070d02014-09-17 20:55:46 +00001917 return optimizePow(CI, Builder);
Meador Inge20255ef2013-03-12 00:08:29 +00001918 case Intrinsic::exp2:
Chris Bienemanad070d02014-09-17 20:55:46 +00001919 return optimizeExp2(CI, Builder);
Sanjay Patel0ca42bb2014-10-14 20:43:11 +00001920 case Intrinsic::fabs:
1921 return optimizeFabs(CI, Builder);
Meador Inge20255ef2013-03-12 00:08:29 +00001922 default:
Chris Bienemanad070d02014-09-17 20:55:46 +00001923 return nullptr;
Meador Inge20255ef2013-03-12 00:08:29 +00001924 }
1925 }
1926
1927 // Then check for known library functions.
1928 if (TLI->getLibFunc(FuncName, Func) && TLI->has(Func)) {
Chris Bienemanad070d02014-09-17 20:55:46 +00001929 // We never change the calling convention.
1930 if (!ignoreCallingConv(Func) && !isCallingConvC)
1931 return nullptr;
Meador Inge20255ef2013-03-12 00:08:29 +00001932 switch (Func) {
Chris Bienemanad070d02014-09-17 20:55:46 +00001933 case LibFunc::strcat:
1934 return optimizeStrCat(CI, Builder);
1935 case LibFunc::strncat:
1936 return optimizeStrNCat(CI, Builder);
1937 case LibFunc::strchr:
1938 return optimizeStrChr(CI, Builder);
1939 case LibFunc::strrchr:
1940 return optimizeStrRChr(CI, Builder);
1941 case LibFunc::strcmp:
1942 return optimizeStrCmp(CI, Builder);
1943 case LibFunc::strncmp:
1944 return optimizeStrNCmp(CI, Builder);
1945 case LibFunc::strcpy:
1946 return optimizeStrCpy(CI, Builder);
1947 case LibFunc::stpcpy:
1948 return optimizeStpCpy(CI, Builder);
1949 case LibFunc::strncpy:
1950 return optimizeStrNCpy(CI, Builder);
1951 case LibFunc::strlen:
1952 return optimizeStrLen(CI, Builder);
1953 case LibFunc::strpbrk:
1954 return optimizeStrPBrk(CI, Builder);
1955 case LibFunc::strtol:
1956 case LibFunc::strtod:
1957 case LibFunc::strtof:
1958 case LibFunc::strtoul:
1959 case LibFunc::strtoll:
1960 case LibFunc::strtold:
1961 case LibFunc::strtoull:
1962 return optimizeStrTo(CI, Builder);
1963 case LibFunc::strspn:
1964 return optimizeStrSpn(CI, Builder);
1965 case LibFunc::strcspn:
1966 return optimizeStrCSpn(CI, Builder);
1967 case LibFunc::strstr:
1968 return optimizeStrStr(CI, Builder);
1969 case LibFunc::memcmp:
1970 return optimizeMemCmp(CI, Builder);
1971 case LibFunc::memcpy:
1972 return optimizeMemCpy(CI, Builder);
1973 case LibFunc::memmove:
1974 return optimizeMemMove(CI, Builder);
1975 case LibFunc::memset:
1976 return optimizeMemSet(CI, Builder);
1977 case LibFunc::cosf:
1978 case LibFunc::cos:
1979 case LibFunc::cosl:
1980 return optimizeCos(CI, Builder);
1981 case LibFunc::sinpif:
1982 case LibFunc::sinpi:
1983 case LibFunc::cospif:
1984 case LibFunc::cospi:
1985 return optimizeSinCosPi(CI, Builder);
1986 case LibFunc::powf:
1987 case LibFunc::pow:
1988 case LibFunc::powl:
1989 return optimizePow(CI, Builder);
1990 case LibFunc::exp2l:
1991 case LibFunc::exp2:
1992 case LibFunc::exp2f:
1993 return optimizeExp2(CI, Builder);
Sanjay Patel0ca42bb2014-10-14 20:43:11 +00001994 case LibFunc::fabsf:
1995 case LibFunc::fabs:
1996 case LibFunc::fabsl:
1997 return optimizeFabs(CI, Builder);
Chris Bienemanad070d02014-09-17 20:55:46 +00001998 case LibFunc::ffs:
1999 case LibFunc::ffsl:
2000 case LibFunc::ffsll:
2001 return optimizeFFS(CI, Builder);
2002 case LibFunc::abs:
2003 case LibFunc::labs:
2004 case LibFunc::llabs:
2005 return optimizeAbs(CI, Builder);
2006 case LibFunc::isdigit:
2007 return optimizeIsDigit(CI, Builder);
2008 case LibFunc::isascii:
2009 return optimizeIsAscii(CI, Builder);
2010 case LibFunc::toascii:
2011 return optimizeToAscii(CI, Builder);
2012 case LibFunc::printf:
2013 return optimizePrintF(CI, Builder);
2014 case LibFunc::sprintf:
2015 return optimizeSPrintF(CI, Builder);
2016 case LibFunc::fprintf:
2017 return optimizeFPrintF(CI, Builder);
2018 case LibFunc::fwrite:
2019 return optimizeFWrite(CI, Builder);
2020 case LibFunc::fputs:
2021 return optimizeFPuts(CI, Builder);
2022 case LibFunc::puts:
2023 return optimizePuts(CI, Builder);
2024 case LibFunc::perror:
2025 return optimizeErrorReporting(CI, Builder);
2026 case LibFunc::vfprintf:
2027 case LibFunc::fiprintf:
2028 return optimizeErrorReporting(CI, Builder, 0);
2029 case LibFunc::fputc:
2030 return optimizeErrorReporting(CI, Builder, 1);
2031 case LibFunc::ceil:
Chris Bienemanad070d02014-09-17 20:55:46 +00002032 case LibFunc::floor:
2033 case LibFunc::rint:
2034 case LibFunc::round:
2035 case LibFunc::nearbyint:
2036 case LibFunc::trunc:
2037 if (hasFloatVersion(FuncName))
2038 return optimizeUnaryDoubleFP(CI, Builder, false);
2039 return nullptr;
2040 case LibFunc::acos:
2041 case LibFunc::acosh:
2042 case LibFunc::asin:
2043 case LibFunc::asinh:
2044 case LibFunc::atan:
2045 case LibFunc::atanh:
2046 case LibFunc::cbrt:
2047 case LibFunc::cosh:
2048 case LibFunc::exp:
2049 case LibFunc::exp10:
2050 case LibFunc::expm1:
2051 case LibFunc::log:
2052 case LibFunc::log10:
2053 case LibFunc::log1p:
2054 case LibFunc::log2:
2055 case LibFunc::logb:
2056 case LibFunc::sin:
2057 case LibFunc::sinh:
2058 case LibFunc::sqrt:
2059 case LibFunc::tan:
2060 case LibFunc::tanh:
2061 if (UnsafeFPShrink && hasFloatVersion(FuncName))
2062 return optimizeUnaryDoubleFP(CI, Builder, true);
2063 return nullptr;
2064 case LibFunc::fmin:
2065 case LibFunc::fmax:
2066 if (hasFloatVersion(FuncName))
2067 return optimizeBinaryDoubleFP(CI, Builder);
2068 return nullptr;
2069 case LibFunc::memcpy_chk:
2070 return optimizeMemCpyChk(CI, Builder);
2071 default:
2072 return nullptr;
2073 }
Meador Inge20255ef2013-03-12 00:08:29 +00002074 }
2075
Chris Bienemanad070d02014-09-17 20:55:46 +00002076 if (!isCallingConvC)
2077 return nullptr;
2078
Meador Inge20255ef2013-03-12 00:08:29 +00002079 // Finally check for fortified library calls.
2080 if (FuncName.endswith("_chk")) {
2081 if (FuncName == "__memmove_chk")
Chris Bienemanad070d02014-09-17 20:55:46 +00002082 return optimizeMemMoveChk(CI, Builder);
Meador Inge20255ef2013-03-12 00:08:29 +00002083 else if (FuncName == "__memset_chk")
Chris Bienemanad070d02014-09-17 20:55:46 +00002084 return optimizeMemSetChk(CI, Builder);
Meador Inge20255ef2013-03-12 00:08:29 +00002085 else if (FuncName == "__strcpy_chk")
Chris Bienemanad070d02014-09-17 20:55:46 +00002086 return optimizeStrCpyChk(CI, Builder);
Meador Inge20255ef2013-03-12 00:08:29 +00002087 else if (FuncName == "__stpcpy_chk")
Chris Bienemanad070d02014-09-17 20:55:46 +00002088 return optimizeStpCpyChk(CI, Builder);
Meador Inge20255ef2013-03-12 00:08:29 +00002089 else if (FuncName == "__strncpy_chk")
Chris Bienemanad070d02014-09-17 20:55:46 +00002090 return optimizeStrNCpyChk(CI, Builder);
Meador Inge20255ef2013-03-12 00:08:29 +00002091 else if (FuncName == "__stpncpy_chk")
Chris Bienemanad070d02014-09-17 20:55:46 +00002092 return optimizeStrNCpyChk(CI, Builder);
Meador Inge20255ef2013-03-12 00:08:29 +00002093 }
2094
Craig Topperf40110f2014-04-25 05:29:35 +00002095 return nullptr;
Meador Ingedf796f82012-10-13 16:45:24 +00002096}
2097
Rafael Espindola37dc9e12014-02-21 00:06:31 +00002098LibCallSimplifier::LibCallSimplifier(const DataLayout *DL,
Meador Inge193e0352012-11-13 04:16:17 +00002099 const TargetLibraryInfo *TLI,
Chris Bienemanad070d02014-09-17 20:55:46 +00002100 bool UnsafeFPShrink) :
2101 DL(DL),
2102 TLI(TLI),
2103 UnsafeFPShrink(UnsafeFPShrink) {
Meador Ingedf796f82012-10-13 16:45:24 +00002104}
2105
Meador Inge76fc1a42012-11-11 03:51:43 +00002106void LibCallSimplifier::replaceAllUsesWith(Instruction *I, Value *With) const {
2107 I->replaceAllUsesWith(With);
2108 I->eraseFromParent();
2109}
2110
Meador Ingedfb08a22013-06-20 19:48:07 +00002111// TODO:
2112// Additional cases that we need to add to this file:
2113//
2114// cbrt:
2115// * cbrt(expN(X)) -> expN(x/3)
2116// * cbrt(sqrt(x)) -> pow(x,1/6)
2117// * cbrt(sqrt(x)) -> pow(x,1/9)
2118//
2119// exp, expf, expl:
2120// * exp(log(x)) -> x
2121//
2122// log, logf, logl:
2123// * log(exp(x)) -> x
2124// * log(x**y) -> y*log(x)
2125// * log(exp(y)) -> y*log(e)
2126// * log(exp2(y)) -> y*log(2)
2127// * log(exp10(y)) -> y*log(10)
2128// * log(sqrt(x)) -> 0.5*log(x)
2129// * log(pow(x,y)) -> y*log(x)
2130//
2131// lround, lroundf, lroundl:
2132// * lround(cnst) -> cnst'
2133//
2134// pow, powf, powl:
2135// * pow(exp(x),y) -> exp(x*y)
2136// * pow(sqrt(x),y) -> pow(x,y*0.5)
2137// * pow(pow(x,y),z)-> pow(x,y*z)
2138//
2139// round, roundf, roundl:
2140// * round(cnst) -> cnst'
2141//
2142// signbit:
2143// * signbit(cnst) -> cnst'
2144// * signbit(nncst) -> 0 (if pstv is a non-negative constant)
2145//
2146// sqrt, sqrtf, sqrtl:
2147// * sqrt(expN(x)) -> expN(x*0.5)
2148// * sqrt(Nroot(x)) -> pow(x,1/(2*N))
2149// * sqrt(pow(x,y)) -> pow(|x|,y*0.5)
2150//
Meador Ingedfb08a22013-06-20 19:48:07 +00002151// tan, tanf, tanl:
2152// * tan(atan(x)) -> x
2153//
2154// trunc, truncf, truncl:
2155// * trunc(cnst) -> cnst'
2156//
2157//