blob: cb4b09cbaf040c56e667a90ce3a262d3f7e56351 [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
1233static bool isTrigLibCall(CallInst *CI);
1234static void insertSinCosCall(IRBuilder<> &B, Function *OrigCallee, Value *Arg,
1235 bool UseFloat, Value *&Sin, Value *&Cos,
1236 Value *&SinCos);
1237
1238Value *LibCallSimplifier::optimizeSinCosPi(CallInst *CI, IRBuilder<> &B) {
1239
1240 // Make sure the prototype is as expected, otherwise the rest of the
1241 // function is probably invalid and likely to abort.
1242 if (!isTrigLibCall(CI))
1243 return nullptr;
1244
1245 Value *Arg = CI->getArgOperand(0);
1246 SmallVector<CallInst *, 1> SinCalls;
1247 SmallVector<CallInst *, 1> CosCalls;
1248 SmallVector<CallInst *, 1> SinCosCalls;
1249
1250 bool IsFloat = Arg->getType()->isFloatTy();
1251
1252 // Look for all compatible sinpi, cospi and sincospi calls with the same
1253 // argument. If there are enough (in some sense) we can make the
1254 // substitution.
1255 for (User *U : Arg->users())
1256 classifyArgUse(U, CI->getParent(), IsFloat, SinCalls, CosCalls,
1257 SinCosCalls);
1258
1259 // It's only worthwhile if both sinpi and cospi are actually used.
1260 if (SinCosCalls.empty() && (SinCalls.empty() || CosCalls.empty()))
1261 return nullptr;
1262
1263 Value *Sin, *Cos, *SinCos;
1264 insertSinCosCall(B, CI->getCalledFunction(), Arg, IsFloat, Sin, Cos, SinCos);
1265
1266 replaceTrigInsts(SinCalls, Sin);
1267 replaceTrigInsts(CosCalls, Cos);
1268 replaceTrigInsts(SinCosCalls, SinCos);
1269
1270 return nullptr;
1271}
1272
1273static bool isTrigLibCall(CallInst *CI) {
1274 Function *Callee = CI->getCalledFunction();
1275 FunctionType *FT = Callee->getFunctionType();
1276
1277 // We can only hope to do anything useful if we can ignore things like errno
1278 // and floating-point exceptions.
1279 bool AttributesSafe =
1280 CI->hasFnAttr(Attribute::NoUnwind) && CI->hasFnAttr(Attribute::ReadNone);
1281
1282 // Other than that we need float(float) or double(double)
1283 return AttributesSafe && FT->getNumParams() == 1 &&
1284 FT->getReturnType() == FT->getParamType(0) &&
1285 (FT->getParamType(0)->isFloatTy() ||
1286 FT->getParamType(0)->isDoubleTy());
1287}
1288
1289void
1290LibCallSimplifier::classifyArgUse(Value *Val, BasicBlock *BB, bool IsFloat,
1291 SmallVectorImpl<CallInst *> &SinCalls,
1292 SmallVectorImpl<CallInst *> &CosCalls,
1293 SmallVectorImpl<CallInst *> &SinCosCalls) {
1294 CallInst *CI = dyn_cast<CallInst>(Val);
1295
1296 if (!CI)
1297 return;
1298
1299 Function *Callee = CI->getCalledFunction();
1300 StringRef FuncName = Callee->getName();
1301 LibFunc::Func Func;
1302 if (!TLI->getLibFunc(FuncName, Func) || !TLI->has(Func) || !isTrigLibCall(CI))
1303 return;
1304
1305 if (IsFloat) {
1306 if (Func == LibFunc::sinpif)
1307 SinCalls.push_back(CI);
1308 else if (Func == LibFunc::cospif)
1309 CosCalls.push_back(CI);
1310 else if (Func == LibFunc::sincospif_stret)
1311 SinCosCalls.push_back(CI);
1312 } else {
1313 if (Func == LibFunc::sinpi)
1314 SinCalls.push_back(CI);
1315 else if (Func == LibFunc::cospi)
1316 CosCalls.push_back(CI);
1317 else if (Func == LibFunc::sincospi_stret)
1318 SinCosCalls.push_back(CI);
1319 }
1320}
1321
1322void LibCallSimplifier::replaceTrigInsts(SmallVectorImpl<CallInst *> &Calls,
1323 Value *Res) {
1324 for (SmallVectorImpl<CallInst *>::iterator I = Calls.begin(), E = Calls.end();
1325 I != E; ++I) {
1326 replaceAllUsesWith(*I, Res);
1327 }
1328}
1329
1330void insertSinCosCall(IRBuilder<> &B, Function *OrigCallee, Value *Arg,
1331 bool UseFloat, Value *&Sin, Value *&Cos, Value *&SinCos) {
1332 Type *ArgTy = Arg->getType();
1333 Type *ResTy;
1334 StringRef Name;
1335
1336 Triple T(OrigCallee->getParent()->getTargetTriple());
1337 if (UseFloat) {
1338 Name = "__sincospif_stret";
1339
1340 assert(T.getArch() != Triple::x86 && "x86 messy and unsupported for now");
1341 // x86_64 can't use {float, float} since that would be returned in both
1342 // xmm0 and xmm1, which isn't what a real struct would do.
1343 ResTy = T.getArch() == Triple::x86_64
1344 ? static_cast<Type *>(VectorType::get(ArgTy, 2))
1345 : static_cast<Type *>(StructType::get(ArgTy, ArgTy, NULL));
1346 } else {
1347 Name = "__sincospi_stret";
1348 ResTy = StructType::get(ArgTy, ArgTy, NULL);
1349 }
1350
1351 Module *M = OrigCallee->getParent();
1352 Value *Callee = M->getOrInsertFunction(Name, OrigCallee->getAttributes(),
1353 ResTy, ArgTy, NULL);
1354
1355 if (Instruction *ArgInst = dyn_cast<Instruction>(Arg)) {
1356 // If the argument is an instruction, it must dominate all uses so put our
1357 // sincos call there.
1358 BasicBlock::iterator Loc = ArgInst;
1359 B.SetInsertPoint(ArgInst->getParent(), ++Loc);
1360 } else {
1361 // Otherwise (e.g. for a constant) the beginning of the function is as
1362 // good a place as any.
1363 BasicBlock &EntryBB = B.GetInsertBlock()->getParent()->getEntryBlock();
1364 B.SetInsertPoint(&EntryBB, EntryBB.begin());
1365 }
1366
1367 SinCos = B.CreateCall(Callee, Arg, "sincospi");
1368
1369 if (SinCos->getType()->isStructTy()) {
1370 Sin = B.CreateExtractValue(SinCos, 0, "sinpi");
1371 Cos = B.CreateExtractValue(SinCos, 1, "cospi");
1372 } else {
1373 Sin = B.CreateExtractElement(SinCos, ConstantInt::get(B.getInt32Ty(), 0),
1374 "sinpi");
1375 Cos = B.CreateExtractElement(SinCos, ConstantInt::get(B.getInt32Ty(), 1),
1376 "cospi");
1377 }
1378}
Bob Wilsond8d92d92013-11-03 06:48:38 +00001379
Meador Inge7415f842012-11-25 20:45:27 +00001380//===----------------------------------------------------------------------===//
1381// Integer Library Call Optimizations
1382//===----------------------------------------------------------------------===//
1383
Chris Bienemanad070d02014-09-17 20:55:46 +00001384Value *LibCallSimplifier::optimizeFFS(CallInst *CI, IRBuilder<> &B) {
1385 Function *Callee = CI->getCalledFunction();
1386 FunctionType *FT = Callee->getFunctionType();
1387 // Just make sure this has 2 arguments of the same FP type, which match the
1388 // result type.
1389 if (FT->getNumParams() != 1 || !FT->getReturnType()->isIntegerTy(32) ||
1390 !FT->getParamType(0)->isIntegerTy())
1391 return nullptr;
Meador Inge7415f842012-11-25 20:45:27 +00001392
Chris Bienemanad070d02014-09-17 20:55:46 +00001393 Value *Op = CI->getArgOperand(0);
Meador Inge7415f842012-11-25 20:45:27 +00001394
Chris Bienemanad070d02014-09-17 20:55:46 +00001395 // Constant fold.
1396 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op)) {
1397 if (CI->isZero()) // ffs(0) -> 0.
1398 return B.getInt32(0);
1399 // ffs(c) -> cttz(c)+1
1400 return B.getInt32(CI->getValue().countTrailingZeros() + 1);
Meador Inge7415f842012-11-25 20:45:27 +00001401 }
Meador Inge7415f842012-11-25 20:45:27 +00001402
Chris Bienemanad070d02014-09-17 20:55:46 +00001403 // ffs(x) -> x != 0 ? (i32)llvm.cttz(x)+1 : 0
1404 Type *ArgType = Op->getType();
1405 Value *F =
1406 Intrinsic::getDeclaration(Callee->getParent(), Intrinsic::cttz, ArgType);
1407 Value *V = B.CreateCall2(F, Op, B.getFalse(), "cttz");
1408 V = B.CreateAdd(V, ConstantInt::get(V->getType(), 1));
1409 V = B.CreateIntCast(V, B.getInt32Ty(), false);
Meador Ingea0b6d872012-11-26 00:24:07 +00001410
Chris Bienemanad070d02014-09-17 20:55:46 +00001411 Value *Cond = B.CreateICmpNE(Op, Constant::getNullValue(ArgType));
1412 return B.CreateSelect(Cond, V, B.getInt32(0));
1413}
Meador Ingea0b6d872012-11-26 00:24:07 +00001414
Chris Bienemanad070d02014-09-17 20:55:46 +00001415Value *LibCallSimplifier::optimizeAbs(CallInst *CI, IRBuilder<> &B) {
1416 Function *Callee = CI->getCalledFunction();
1417 FunctionType *FT = Callee->getFunctionType();
1418 // We require integer(integer) where the types agree.
1419 if (FT->getNumParams() != 1 || !FT->getReturnType()->isIntegerTy() ||
1420 FT->getParamType(0) != FT->getReturnType())
1421 return nullptr;
Meador Inge9a59ab62012-11-26 02:31:59 +00001422
Chris Bienemanad070d02014-09-17 20:55:46 +00001423 // abs(x) -> x >s -1 ? x : -x
1424 Value *Op = CI->getArgOperand(0);
1425 Value *Pos =
1426 B.CreateICmpSGT(Op, Constant::getAllOnesValue(Op->getType()), "ispos");
1427 Value *Neg = B.CreateNeg(Op, "neg");
1428 return B.CreateSelect(Pos, Op, Neg);
1429}
Meador Inge9a59ab62012-11-26 02:31:59 +00001430
Chris Bienemanad070d02014-09-17 20:55:46 +00001431Value *LibCallSimplifier::optimizeIsDigit(CallInst *CI, IRBuilder<> &B) {
1432 Function *Callee = CI->getCalledFunction();
1433 FunctionType *FT = Callee->getFunctionType();
1434 // We require integer(i32)
1435 if (FT->getNumParams() != 1 || !FT->getReturnType()->isIntegerTy() ||
1436 !FT->getParamType(0)->isIntegerTy(32))
1437 return nullptr;
Meador Ingea62a39e2012-11-26 03:10:07 +00001438
Chris Bienemanad070d02014-09-17 20:55:46 +00001439 // isdigit(c) -> (c-'0') <u 10
1440 Value *Op = CI->getArgOperand(0);
1441 Op = B.CreateSub(Op, B.getInt32('0'), "isdigittmp");
1442 Op = B.CreateICmpULT(Op, B.getInt32(10), "isdigit");
1443 return B.CreateZExt(Op, CI->getType());
1444}
Meador Ingea62a39e2012-11-26 03:10:07 +00001445
Chris Bienemanad070d02014-09-17 20:55:46 +00001446Value *LibCallSimplifier::optimizeIsAscii(CallInst *CI, IRBuilder<> &B) {
1447 Function *Callee = CI->getCalledFunction();
1448 FunctionType *FT = Callee->getFunctionType();
1449 // We require integer(i32)
1450 if (FT->getNumParams() != 1 || !FT->getReturnType()->isIntegerTy() ||
1451 !FT->getParamType(0)->isIntegerTy(32))
1452 return nullptr;
Meador Inge604937d2012-11-26 03:38:52 +00001453
Chris Bienemanad070d02014-09-17 20:55:46 +00001454 // isascii(c) -> c <u 128
1455 Value *Op = CI->getArgOperand(0);
1456 Op = B.CreateICmpULT(Op, B.getInt32(128), "isascii");
1457 return B.CreateZExt(Op, CI->getType());
1458}
1459
1460Value *LibCallSimplifier::optimizeToAscii(CallInst *CI, IRBuilder<> &B) {
1461 Function *Callee = CI->getCalledFunction();
1462 FunctionType *FT = Callee->getFunctionType();
1463 // We require i32(i32)
1464 if (FT->getNumParams() != 1 || FT->getReturnType() != FT->getParamType(0) ||
1465 !FT->getParamType(0)->isIntegerTy(32))
1466 return nullptr;
1467
1468 // toascii(c) -> c & 0x7f
1469 return B.CreateAnd(CI->getArgOperand(0),
1470 ConstantInt::get(CI->getType(), 0x7F));
1471}
Meador Inge604937d2012-11-26 03:38:52 +00001472
Meador Inge08ca1152012-11-26 20:37:20 +00001473//===----------------------------------------------------------------------===//
1474// Formatting and IO Library Call Optimizations
1475//===----------------------------------------------------------------------===//
1476
Chris Bienemanad070d02014-09-17 20:55:46 +00001477static bool isReportingError(Function *Callee, CallInst *CI, int StreamArg);
Hal Finkel66cd3f12013-11-17 02:06:35 +00001478
Chris Bienemanad070d02014-09-17 20:55:46 +00001479Value *LibCallSimplifier::optimizeErrorReporting(CallInst *CI, IRBuilder<> &B,
1480 int StreamArg) {
1481 // Error reporting calls should be cold, mark them as such.
1482 // This applies even to non-builtin calls: it is only a hint and applies to
1483 // functions that the frontend might not understand as builtins.
Hal Finkel66cd3f12013-11-17 02:06:35 +00001484
Chris Bienemanad070d02014-09-17 20:55:46 +00001485 // This heuristic was suggested in:
1486 // Improving Static Branch Prediction in a Compiler
1487 // Brian L. Deitrich, Ben-Chung Cheng, Wen-mei W. Hwu
1488 // Proceedings of PACT'98, Oct. 1998, IEEE
1489 Function *Callee = CI->getCalledFunction();
Hal Finkel66cd3f12013-11-17 02:06:35 +00001490
Chris Bienemanad070d02014-09-17 20:55:46 +00001491 if (!CI->hasFnAttr(Attribute::Cold) &&
1492 isReportingError(Callee, CI, StreamArg)) {
1493 CI->addAttribute(AttributeSet::FunctionIndex, Attribute::Cold);
1494 }
Hal Finkel66cd3f12013-11-17 02:06:35 +00001495
Chris Bienemanad070d02014-09-17 20:55:46 +00001496 return nullptr;
1497}
1498
1499static bool isReportingError(Function *Callee, CallInst *CI, int StreamArg) {
1500 if (!ColdErrorCalls)
1501 return false;
1502
1503 if (!Callee || !Callee->isDeclaration())
1504 return false;
1505
1506 if (StreamArg < 0)
1507 return true;
1508
1509 // These functions might be considered cold, but only if their stream
1510 // argument is stderr.
1511
1512 if (StreamArg >= (int)CI->getNumArgOperands())
1513 return false;
1514 LoadInst *LI = dyn_cast<LoadInst>(CI->getArgOperand(StreamArg));
1515 if (!LI)
1516 return false;
1517 GlobalVariable *GV = dyn_cast<GlobalVariable>(LI->getPointerOperand());
1518 if (!GV || !GV->isDeclaration())
1519 return false;
1520 return GV->getName() == "stderr";
1521}
1522
1523Value *LibCallSimplifier::optimizePrintFString(CallInst *CI, IRBuilder<> &B) {
1524 // Check for a fixed format string.
1525 StringRef FormatStr;
1526 if (!getConstantStringInfo(CI->getArgOperand(0), FormatStr))
Craig Topperf40110f2014-04-25 05:29:35 +00001527 return nullptr;
Hal Finkel66cd3f12013-11-17 02:06:35 +00001528
Chris Bienemanad070d02014-09-17 20:55:46 +00001529 // Empty format string -> noop.
1530 if (FormatStr.empty()) // Tolerate printf's declared void.
1531 return CI->use_empty() ? (Value *)CI : ConstantInt::get(CI->getType(), 0);
Hal Finkel66cd3f12013-11-17 02:06:35 +00001532
Chris Bienemanad070d02014-09-17 20:55:46 +00001533 // Do not do any of the following transformations if the printf return value
1534 // is used, in general the printf return value is not compatible with either
1535 // putchar() or puts().
1536 if (!CI->use_empty())
Craig Topperf40110f2014-04-25 05:29:35 +00001537 return nullptr;
Chris Bienemanad070d02014-09-17 20:55:46 +00001538
1539 // printf("x") -> putchar('x'), even for '%'.
1540 if (FormatStr.size() == 1) {
1541 Value *Res = EmitPutChar(B.getInt32(FormatStr[0]), B, DL, TLI);
1542 if (CI->use_empty() || !Res)
1543 return Res;
1544 return B.CreateIntCast(Res, CI->getType(), true);
Meador Inge08ca1152012-11-26 20:37:20 +00001545 }
1546
Chris Bienemanad070d02014-09-17 20:55:46 +00001547 // printf("foo\n") --> puts("foo")
1548 if (FormatStr[FormatStr.size() - 1] == '\n' &&
1549 FormatStr.find('%') == StringRef::npos) { // No format characters.
1550 // Create a string literal with no \n on it. We expect the constant merge
1551 // pass to be run after this pass, to merge duplicate strings.
1552 FormatStr = FormatStr.drop_back();
1553 Value *GV = B.CreateGlobalString(FormatStr, "str");
1554 Value *NewCI = EmitPutS(GV, B, DL, TLI);
1555 return (CI->use_empty() || !NewCI)
1556 ? NewCI
1557 : ConstantInt::get(CI->getType(), FormatStr.size() + 1);
1558 }
Meador Inge08ca1152012-11-26 20:37:20 +00001559
Chris Bienemanad070d02014-09-17 20:55:46 +00001560 // Optimize specific format strings.
1561 // printf("%c", chr) --> putchar(chr)
1562 if (FormatStr == "%c" && CI->getNumArgOperands() > 1 &&
1563 CI->getArgOperand(1)->getType()->isIntegerTy()) {
1564 Value *Res = EmitPutChar(CI->getArgOperand(1), B, DL, TLI);
Meador Inge08ca1152012-11-26 20:37:20 +00001565
Chris Bienemanad070d02014-09-17 20:55:46 +00001566 if (CI->use_empty() || !Res)
1567 return Res;
1568 return B.CreateIntCast(Res, CI->getType(), true);
1569 }
1570
1571 // printf("%s\n", str) --> puts(str)
1572 if (FormatStr == "%s\n" && CI->getNumArgOperands() > 1 &&
1573 CI->getArgOperand(1)->getType()->isPointerTy()) {
1574 return EmitPutS(CI->getArgOperand(1), B, DL, TLI);
1575 }
1576 return nullptr;
1577}
1578
1579Value *LibCallSimplifier::optimizePrintF(CallInst *CI, IRBuilder<> &B) {
1580
1581 Function *Callee = CI->getCalledFunction();
1582 // Require one fixed pointer argument and an integer/void result.
1583 FunctionType *FT = Callee->getFunctionType();
1584 if (FT->getNumParams() < 1 || !FT->getParamType(0)->isPointerTy() ||
1585 !(FT->getReturnType()->isIntegerTy() || FT->getReturnType()->isVoidTy()))
1586 return nullptr;
1587
1588 if (Value *V = optimizePrintFString(CI, B)) {
1589 return V;
1590 }
1591
1592 // printf(format, ...) -> iprintf(format, ...) if no floating point
1593 // arguments.
1594 if (TLI->has(LibFunc::iprintf) && !callHasFloatingPointArgument(CI)) {
1595 Module *M = B.GetInsertBlock()->getParent()->getParent();
1596 Constant *IPrintFFn =
Meador Inge08ca1152012-11-26 20:37:20 +00001597 M->getOrInsertFunction("iprintf", FT, Callee->getAttributes());
Chris Bienemanad070d02014-09-17 20:55:46 +00001598 CallInst *New = cast<CallInst>(CI->clone());
1599 New->setCalledFunction(IPrintFFn);
1600 B.Insert(New);
1601 return New;
Meador Inge08ca1152012-11-26 20:37:20 +00001602 }
Chris Bienemanad070d02014-09-17 20:55:46 +00001603 return nullptr;
1604}
Meador Inge08ca1152012-11-26 20:37:20 +00001605
Chris Bienemanad070d02014-09-17 20:55:46 +00001606Value *LibCallSimplifier::optimizeSPrintFString(CallInst *CI, IRBuilder<> &B) {
1607 // Check for a fixed format string.
1608 StringRef FormatStr;
1609 if (!getConstantStringInfo(CI->getArgOperand(1), FormatStr))
Craig Topperf40110f2014-04-25 05:29:35 +00001610 return nullptr;
Meador Inge25c9b3b2012-11-27 05:57:54 +00001611
Chris Bienemanad070d02014-09-17 20:55:46 +00001612 // If we just have a format string (nothing else crazy) transform it.
1613 if (CI->getNumArgOperands() == 2) {
1614 // Make sure there's no % in the constant array. We could try to handle
1615 // %% -> % in the future if we cared.
1616 for (unsigned i = 0, e = FormatStr.size(); i != e; ++i)
1617 if (FormatStr[i] == '%')
1618 return nullptr; // we found a format specifier, bail out.
Hal Finkel66cd3f12013-11-17 02:06:35 +00001619
Meador Ingef8e72502012-11-29 15:45:43 +00001620 // These optimizations require DataLayout.
Chris Bienemanad070d02014-09-17 20:55:46 +00001621 if (!DL)
Craig Topperf40110f2014-04-25 05:29:35 +00001622 return nullptr;
Meador Ingef8e72502012-11-29 15:45:43 +00001623
Chris Bienemanad070d02014-09-17 20:55:46 +00001624 // sprintf(str, fmt) -> llvm.memcpy(str, fmt, strlen(fmt)+1, 1)
1625 B.CreateMemCpy(
1626 CI->getArgOperand(0), CI->getArgOperand(1),
1627 ConstantInt::get(DL->getIntPtrType(CI->getContext()),
1628 FormatStr.size() + 1),
1629 1); // Copy the null byte.
1630 return ConstantInt::get(CI->getType(), FormatStr.size());
Meador Ingef8e72502012-11-29 15:45:43 +00001631 }
Meador Ingef8e72502012-11-29 15:45:43 +00001632
Chris Bienemanad070d02014-09-17 20:55:46 +00001633 // The remaining optimizations require the format string to be "%s" or "%c"
1634 // and have an extra operand.
1635 if (FormatStr.size() != 2 || FormatStr[0] != '%' ||
1636 CI->getNumArgOperands() < 3)
Craig Topperf40110f2014-04-25 05:29:35 +00001637 return nullptr;
Meador Inge75798bb2012-11-29 19:15:17 +00001638
Chris Bienemanad070d02014-09-17 20:55:46 +00001639 // Decode the second character of the format string.
1640 if (FormatStr[1] == 'c') {
1641 // sprintf(dst, "%c", chr) --> *(i8*)dst = chr; *((i8*)dst+1) = 0
1642 if (!CI->getArgOperand(2)->getType()->isIntegerTy())
1643 return nullptr;
1644 Value *V = B.CreateTrunc(CI->getArgOperand(2), B.getInt8Ty(), "char");
1645 Value *Ptr = CastToCStr(CI->getArgOperand(0), B);
1646 B.CreateStore(V, Ptr);
1647 Ptr = B.CreateGEP(Ptr, B.getInt32(1), "nul");
1648 B.CreateStore(B.getInt8(0), Ptr);
Meador Ingedf796f82012-10-13 16:45:24 +00001649
Chris Bienemanad070d02014-09-17 20:55:46 +00001650 return ConstantInt::get(CI->getType(), 1);
Meador Ingedf796f82012-10-13 16:45:24 +00001651 }
1652
Chris Bienemanad070d02014-09-17 20:55:46 +00001653 if (FormatStr[1] == 's') {
1654 // These optimizations require DataLayout.
1655 if (!DL)
1656 return nullptr;
Meador Ingedf796f82012-10-13 16:45:24 +00001657
Chris Bienemanad070d02014-09-17 20:55:46 +00001658 // sprintf(dest, "%s", str) -> llvm.memcpy(dest, str, strlen(str)+1, 1)
1659 if (!CI->getArgOperand(2)->getType()->isPointerTy())
1660 return nullptr;
1661
1662 Value *Len = EmitStrLen(CI->getArgOperand(2), B, DL, TLI);
1663 if (!Len)
1664 return nullptr;
1665 Value *IncLen =
1666 B.CreateAdd(Len, ConstantInt::get(Len->getType(), 1), "leninc");
1667 B.CreateMemCpy(CI->getArgOperand(0), CI->getArgOperand(2), IncLen, 1);
1668
1669 // The sprintf result is the unincremented number of bytes in the string.
1670 return B.CreateIntCast(Len, CI->getType(), false);
1671 }
1672 return nullptr;
1673}
1674
1675Value *LibCallSimplifier::optimizeSPrintF(CallInst *CI, IRBuilder<> &B) {
1676 Function *Callee = CI->getCalledFunction();
1677 // Require two fixed pointer arguments and an integer result.
1678 FunctionType *FT = Callee->getFunctionType();
1679 if (FT->getNumParams() != 2 || !FT->getParamType(0)->isPointerTy() ||
1680 !FT->getParamType(1)->isPointerTy() ||
1681 !FT->getReturnType()->isIntegerTy())
1682 return nullptr;
1683
1684 if (Value *V = optimizeSPrintFString(CI, B)) {
1685 return V;
1686 }
1687
1688 // sprintf(str, format, ...) -> siprintf(str, format, ...) if no floating
1689 // point arguments.
1690 if (TLI->has(LibFunc::siprintf) && !callHasFloatingPointArgument(CI)) {
1691 Module *M = B.GetInsertBlock()->getParent()->getParent();
1692 Constant *SIPrintFFn =
1693 M->getOrInsertFunction("siprintf", FT, Callee->getAttributes());
1694 CallInst *New = cast<CallInst>(CI->clone());
1695 New->setCalledFunction(SIPrintFFn);
1696 B.Insert(New);
1697 return New;
1698 }
1699 return nullptr;
1700}
1701
1702Value *LibCallSimplifier::optimizeFPrintFString(CallInst *CI, IRBuilder<> &B) {
1703 optimizeErrorReporting(CI, B, 0);
1704
1705 // All the optimizations depend on the format string.
1706 StringRef FormatStr;
1707 if (!getConstantStringInfo(CI->getArgOperand(1), FormatStr))
1708 return nullptr;
1709
1710 // Do not do any of the following transformations if the fprintf return
1711 // value is used, in general the fprintf return value is not compatible
1712 // with fwrite(), fputc() or fputs().
1713 if (!CI->use_empty())
1714 return nullptr;
1715
1716 // fprintf(F, "foo") --> fwrite("foo", 3, 1, F)
1717 if (CI->getNumArgOperands() == 2) {
1718 for (unsigned i = 0, e = FormatStr.size(); i != e; ++i)
1719 if (FormatStr[i] == '%') // Could handle %% -> % if we cared.
1720 return nullptr; // We found a format specifier.
1721
1722 // These optimizations require DataLayout.
1723 if (!DL)
1724 return nullptr;
1725
1726 return EmitFWrite(
1727 CI->getArgOperand(1),
1728 ConstantInt::get(DL->getIntPtrType(CI->getContext()), FormatStr.size()),
1729 CI->getArgOperand(0), B, DL, TLI);
1730 }
1731
1732 // The remaining optimizations require the format string to be "%s" or "%c"
1733 // and have an extra operand.
1734 if (FormatStr.size() != 2 || FormatStr[0] != '%' ||
1735 CI->getNumArgOperands() < 3)
1736 return nullptr;
1737
1738 // Decode the second character of the format string.
1739 if (FormatStr[1] == 'c') {
1740 // fprintf(F, "%c", chr) --> fputc(chr, F)
1741 if (!CI->getArgOperand(2)->getType()->isIntegerTy())
1742 return nullptr;
1743 return EmitFPutC(CI->getArgOperand(2), CI->getArgOperand(0), B, DL, TLI);
1744 }
1745
1746 if (FormatStr[1] == 's') {
1747 // fprintf(F, "%s", str) --> fputs(str, F)
1748 if (!CI->getArgOperand(2)->getType()->isPointerTy())
1749 return nullptr;
1750 return EmitFPutS(CI->getArgOperand(2), CI->getArgOperand(0), B, DL, TLI);
1751 }
1752 return nullptr;
1753}
1754
1755Value *LibCallSimplifier::optimizeFPrintF(CallInst *CI, IRBuilder<> &B) {
1756 Function *Callee = CI->getCalledFunction();
1757 // Require two fixed paramters as pointers and integer result.
1758 FunctionType *FT = Callee->getFunctionType();
1759 if (FT->getNumParams() != 2 || !FT->getParamType(0)->isPointerTy() ||
1760 !FT->getParamType(1)->isPointerTy() ||
1761 !FT->getReturnType()->isIntegerTy())
1762 return nullptr;
1763
1764 if (Value *V = optimizeFPrintFString(CI, B)) {
1765 return V;
1766 }
1767
1768 // fprintf(stream, format, ...) -> fiprintf(stream, format, ...) if no
1769 // floating point arguments.
1770 if (TLI->has(LibFunc::fiprintf) && !callHasFloatingPointArgument(CI)) {
1771 Module *M = B.GetInsertBlock()->getParent()->getParent();
1772 Constant *FIPrintFFn =
1773 M->getOrInsertFunction("fiprintf", FT, Callee->getAttributes());
1774 CallInst *New = cast<CallInst>(CI->clone());
1775 New->setCalledFunction(FIPrintFFn);
1776 B.Insert(New);
1777 return New;
1778 }
1779 return nullptr;
1780}
1781
1782Value *LibCallSimplifier::optimizeFWrite(CallInst *CI, IRBuilder<> &B) {
1783 optimizeErrorReporting(CI, B, 3);
1784
1785 Function *Callee = CI->getCalledFunction();
1786 // Require a pointer, an integer, an integer, a pointer, returning integer.
1787 FunctionType *FT = Callee->getFunctionType();
1788 if (FT->getNumParams() != 4 || !FT->getParamType(0)->isPointerTy() ||
1789 !FT->getParamType(1)->isIntegerTy() ||
1790 !FT->getParamType(2)->isIntegerTy() ||
1791 !FT->getParamType(3)->isPointerTy() ||
1792 !FT->getReturnType()->isIntegerTy())
1793 return nullptr;
1794
1795 // Get the element size and count.
1796 ConstantInt *SizeC = dyn_cast<ConstantInt>(CI->getArgOperand(1));
1797 ConstantInt *CountC = dyn_cast<ConstantInt>(CI->getArgOperand(2));
1798 if (!SizeC || !CountC)
1799 return nullptr;
1800 uint64_t Bytes = SizeC->getZExtValue() * CountC->getZExtValue();
1801
1802 // If this is writing zero records, remove the call (it's a noop).
1803 if (Bytes == 0)
1804 return ConstantInt::get(CI->getType(), 0);
1805
1806 // If this is writing one byte, turn it into fputc.
1807 // This optimisation is only valid, if the return value is unused.
1808 if (Bytes == 1 && CI->use_empty()) { // fwrite(S,1,1,F) -> fputc(S[0],F)
1809 Value *Char = B.CreateLoad(CastToCStr(CI->getArgOperand(0), B), "char");
1810 Value *NewCI = EmitFPutC(Char, CI->getArgOperand(3), B, DL, TLI);
1811 return NewCI ? ConstantInt::get(CI->getType(), 1) : nullptr;
1812 }
1813
1814 return nullptr;
1815}
1816
1817Value *LibCallSimplifier::optimizeFPuts(CallInst *CI, IRBuilder<> &B) {
1818 optimizeErrorReporting(CI, B, 1);
1819
1820 Function *Callee = CI->getCalledFunction();
1821
1822 // These optimizations require DataLayout.
1823 if (!DL)
1824 return nullptr;
1825
1826 // Require two pointers. Also, we can't optimize if return value is used.
1827 FunctionType *FT = Callee->getFunctionType();
1828 if (FT->getNumParams() != 2 || !FT->getParamType(0)->isPointerTy() ||
1829 !FT->getParamType(1)->isPointerTy() || !CI->use_empty())
1830 return nullptr;
1831
1832 // fputs(s,F) --> fwrite(s,1,strlen(s),F)
1833 uint64_t Len = GetStringLength(CI->getArgOperand(0));
1834 if (!Len)
1835 return nullptr;
1836
1837 // Known to have no uses (see above).
1838 return EmitFWrite(
1839 CI->getArgOperand(0),
1840 ConstantInt::get(DL->getIntPtrType(CI->getContext()), Len - 1),
1841 CI->getArgOperand(1), B, DL, TLI);
1842}
1843
1844Value *LibCallSimplifier::optimizePuts(CallInst *CI, IRBuilder<> &B) {
1845 Function *Callee = CI->getCalledFunction();
1846 // Require one fixed pointer argument and an integer/void result.
1847 FunctionType *FT = Callee->getFunctionType();
1848 if (FT->getNumParams() < 1 || !FT->getParamType(0)->isPointerTy() ||
1849 !(FT->getReturnType()->isIntegerTy() || FT->getReturnType()->isVoidTy()))
1850 return nullptr;
1851
1852 // Check for a constant string.
1853 StringRef Str;
1854 if (!getConstantStringInfo(CI->getArgOperand(0), Str))
1855 return nullptr;
1856
1857 if (Str.empty() && CI->use_empty()) {
1858 // puts("") -> putchar('\n')
1859 Value *Res = EmitPutChar(B.getInt32('\n'), B, DL, TLI);
1860 if (CI->use_empty() || !Res)
1861 return Res;
1862 return B.CreateIntCast(Res, CI->getType(), true);
1863 }
1864
1865 return nullptr;
1866}
1867
1868bool LibCallSimplifier::hasFloatVersion(StringRef FuncName) {
Meador Inge20255ef2013-03-12 00:08:29 +00001869 LibFunc::Func Func;
1870 SmallString<20> FloatFuncName = FuncName;
1871 FloatFuncName += 'f';
1872 if (TLI->getLibFunc(FloatFuncName, Func))
1873 return TLI->has(Func);
1874 return false;
1875}
Meador Inge7fb2f732012-10-13 16:45:32 +00001876
Chris Bienemanad070d02014-09-17 20:55:46 +00001877Value *LibCallSimplifier::optimizeCall(CallInst *CI) {
1878 if (CI->isNoBuiltin())
1879 return nullptr;
Meador Inge4d2827c2012-11-11 05:11:20 +00001880
Meador Inge20255ef2013-03-12 00:08:29 +00001881 LibFunc::Func Func;
1882 Function *Callee = CI->getCalledFunction();
1883 StringRef FuncName = Callee->getName();
Chris Bienemanad070d02014-09-17 20:55:46 +00001884 IRBuilder<> Builder(CI);
1885 bool isCallingConvC = CI->getCallingConv() == llvm::CallingConv::C;
Meador Inge20255ef2013-03-12 00:08:29 +00001886
1887 // Next check for intrinsics.
1888 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(CI)) {
Chris Bienemanad070d02014-09-17 20:55:46 +00001889 if (!isCallingConvC)
1890 return nullptr;
Meador Inge20255ef2013-03-12 00:08:29 +00001891 switch (II->getIntrinsicID()) {
1892 case Intrinsic::pow:
Chris Bienemanad070d02014-09-17 20:55:46 +00001893 return optimizePow(CI, Builder);
Meador Inge20255ef2013-03-12 00:08:29 +00001894 case Intrinsic::exp2:
Chris Bienemanad070d02014-09-17 20:55:46 +00001895 return optimizeExp2(CI, Builder);
Meador Inge20255ef2013-03-12 00:08:29 +00001896 default:
Chris Bienemanad070d02014-09-17 20:55:46 +00001897 return nullptr;
Meador Inge20255ef2013-03-12 00:08:29 +00001898 }
1899 }
1900
1901 // Then check for known library functions.
1902 if (TLI->getLibFunc(FuncName, Func) && TLI->has(Func)) {
Chris Bienemanad070d02014-09-17 20:55:46 +00001903 // We never change the calling convention.
1904 if (!ignoreCallingConv(Func) && !isCallingConvC)
1905 return nullptr;
Meador Inge20255ef2013-03-12 00:08:29 +00001906 switch (Func) {
Chris Bienemanad070d02014-09-17 20:55:46 +00001907 case LibFunc::strcat:
1908 return optimizeStrCat(CI, Builder);
1909 case LibFunc::strncat:
1910 return optimizeStrNCat(CI, Builder);
1911 case LibFunc::strchr:
1912 return optimizeStrChr(CI, Builder);
1913 case LibFunc::strrchr:
1914 return optimizeStrRChr(CI, Builder);
1915 case LibFunc::strcmp:
1916 return optimizeStrCmp(CI, Builder);
1917 case LibFunc::strncmp:
1918 return optimizeStrNCmp(CI, Builder);
1919 case LibFunc::strcpy:
1920 return optimizeStrCpy(CI, Builder);
1921 case LibFunc::stpcpy:
1922 return optimizeStpCpy(CI, Builder);
1923 case LibFunc::strncpy:
1924 return optimizeStrNCpy(CI, Builder);
1925 case LibFunc::strlen:
1926 return optimizeStrLen(CI, Builder);
1927 case LibFunc::strpbrk:
1928 return optimizeStrPBrk(CI, Builder);
1929 case LibFunc::strtol:
1930 case LibFunc::strtod:
1931 case LibFunc::strtof:
1932 case LibFunc::strtoul:
1933 case LibFunc::strtoll:
1934 case LibFunc::strtold:
1935 case LibFunc::strtoull:
1936 return optimizeStrTo(CI, Builder);
1937 case LibFunc::strspn:
1938 return optimizeStrSpn(CI, Builder);
1939 case LibFunc::strcspn:
1940 return optimizeStrCSpn(CI, Builder);
1941 case LibFunc::strstr:
1942 return optimizeStrStr(CI, Builder);
1943 case LibFunc::memcmp:
1944 return optimizeMemCmp(CI, Builder);
1945 case LibFunc::memcpy:
1946 return optimizeMemCpy(CI, Builder);
1947 case LibFunc::memmove:
1948 return optimizeMemMove(CI, Builder);
1949 case LibFunc::memset:
1950 return optimizeMemSet(CI, Builder);
1951 case LibFunc::cosf:
1952 case LibFunc::cos:
1953 case LibFunc::cosl:
1954 return optimizeCos(CI, Builder);
1955 case LibFunc::sinpif:
1956 case LibFunc::sinpi:
1957 case LibFunc::cospif:
1958 case LibFunc::cospi:
1959 return optimizeSinCosPi(CI, Builder);
1960 case LibFunc::powf:
1961 case LibFunc::pow:
1962 case LibFunc::powl:
1963 return optimizePow(CI, Builder);
1964 case LibFunc::exp2l:
1965 case LibFunc::exp2:
1966 case LibFunc::exp2f:
1967 return optimizeExp2(CI, Builder);
1968 case LibFunc::ffs:
1969 case LibFunc::ffsl:
1970 case LibFunc::ffsll:
1971 return optimizeFFS(CI, Builder);
1972 case LibFunc::abs:
1973 case LibFunc::labs:
1974 case LibFunc::llabs:
1975 return optimizeAbs(CI, Builder);
1976 case LibFunc::isdigit:
1977 return optimizeIsDigit(CI, Builder);
1978 case LibFunc::isascii:
1979 return optimizeIsAscii(CI, Builder);
1980 case LibFunc::toascii:
1981 return optimizeToAscii(CI, Builder);
1982 case LibFunc::printf:
1983 return optimizePrintF(CI, Builder);
1984 case LibFunc::sprintf:
1985 return optimizeSPrintF(CI, Builder);
1986 case LibFunc::fprintf:
1987 return optimizeFPrintF(CI, Builder);
1988 case LibFunc::fwrite:
1989 return optimizeFWrite(CI, Builder);
1990 case LibFunc::fputs:
1991 return optimizeFPuts(CI, Builder);
1992 case LibFunc::puts:
1993 return optimizePuts(CI, Builder);
1994 case LibFunc::perror:
1995 return optimizeErrorReporting(CI, Builder);
1996 case LibFunc::vfprintf:
1997 case LibFunc::fiprintf:
1998 return optimizeErrorReporting(CI, Builder, 0);
1999 case LibFunc::fputc:
2000 return optimizeErrorReporting(CI, Builder, 1);
2001 case LibFunc::ceil:
2002 case LibFunc::fabs:
2003 case LibFunc::floor:
2004 case LibFunc::rint:
2005 case LibFunc::round:
2006 case LibFunc::nearbyint:
2007 case LibFunc::trunc:
2008 if (hasFloatVersion(FuncName))
2009 return optimizeUnaryDoubleFP(CI, Builder, false);
2010 return nullptr;
2011 case LibFunc::acos:
2012 case LibFunc::acosh:
2013 case LibFunc::asin:
2014 case LibFunc::asinh:
2015 case LibFunc::atan:
2016 case LibFunc::atanh:
2017 case LibFunc::cbrt:
2018 case LibFunc::cosh:
2019 case LibFunc::exp:
2020 case LibFunc::exp10:
2021 case LibFunc::expm1:
2022 case LibFunc::log:
2023 case LibFunc::log10:
2024 case LibFunc::log1p:
2025 case LibFunc::log2:
2026 case LibFunc::logb:
2027 case LibFunc::sin:
2028 case LibFunc::sinh:
2029 case LibFunc::sqrt:
2030 case LibFunc::tan:
2031 case LibFunc::tanh:
2032 if (UnsafeFPShrink && hasFloatVersion(FuncName))
2033 return optimizeUnaryDoubleFP(CI, Builder, true);
2034 return nullptr;
2035 case LibFunc::fmin:
2036 case LibFunc::fmax:
2037 if (hasFloatVersion(FuncName))
2038 return optimizeBinaryDoubleFP(CI, Builder);
2039 return nullptr;
2040 case LibFunc::memcpy_chk:
2041 return optimizeMemCpyChk(CI, Builder);
2042 default:
2043 return nullptr;
2044 }
Meador Inge20255ef2013-03-12 00:08:29 +00002045 }
2046
Chris Bienemanad070d02014-09-17 20:55:46 +00002047 if (!isCallingConvC)
2048 return nullptr;
2049
Meador Inge20255ef2013-03-12 00:08:29 +00002050 // Finally check for fortified library calls.
2051 if (FuncName.endswith("_chk")) {
2052 if (FuncName == "__memmove_chk")
Chris Bienemanad070d02014-09-17 20:55:46 +00002053 return optimizeMemMoveChk(CI, Builder);
Meador Inge20255ef2013-03-12 00:08:29 +00002054 else if (FuncName == "__memset_chk")
Chris Bienemanad070d02014-09-17 20:55:46 +00002055 return optimizeMemSetChk(CI, Builder);
Meador Inge20255ef2013-03-12 00:08:29 +00002056 else if (FuncName == "__strcpy_chk")
Chris Bienemanad070d02014-09-17 20:55:46 +00002057 return optimizeStrCpyChk(CI, Builder);
Meador Inge20255ef2013-03-12 00:08:29 +00002058 else if (FuncName == "__stpcpy_chk")
Chris Bienemanad070d02014-09-17 20:55:46 +00002059 return optimizeStpCpyChk(CI, Builder);
Meador Inge20255ef2013-03-12 00:08:29 +00002060 else if (FuncName == "__strncpy_chk")
Chris Bienemanad070d02014-09-17 20:55:46 +00002061 return optimizeStrNCpyChk(CI, Builder);
Meador Inge20255ef2013-03-12 00:08:29 +00002062 else if (FuncName == "__stpncpy_chk")
Chris Bienemanad070d02014-09-17 20:55:46 +00002063 return optimizeStrNCpyChk(CI, Builder);
Meador Inge20255ef2013-03-12 00:08:29 +00002064 }
2065
Craig Topperf40110f2014-04-25 05:29:35 +00002066 return nullptr;
Meador Ingedf796f82012-10-13 16:45:24 +00002067}
2068
Rafael Espindola37dc9e12014-02-21 00:06:31 +00002069LibCallSimplifier::LibCallSimplifier(const DataLayout *DL,
Meador Inge193e0352012-11-13 04:16:17 +00002070 const TargetLibraryInfo *TLI,
Chris Bienemanad070d02014-09-17 20:55:46 +00002071 bool UnsafeFPShrink) :
2072 DL(DL),
2073 TLI(TLI),
2074 UnsafeFPShrink(UnsafeFPShrink) {
Meador Ingedf796f82012-10-13 16:45:24 +00002075}
2076
Meador Inge76fc1a42012-11-11 03:51:43 +00002077void LibCallSimplifier::replaceAllUsesWith(Instruction *I, Value *With) const {
2078 I->replaceAllUsesWith(With);
2079 I->eraseFromParent();
2080}
2081
Meador Ingedfb08a22013-06-20 19:48:07 +00002082// TODO:
2083// Additional cases that we need to add to this file:
2084//
2085// cbrt:
2086// * cbrt(expN(X)) -> expN(x/3)
2087// * cbrt(sqrt(x)) -> pow(x,1/6)
2088// * cbrt(sqrt(x)) -> pow(x,1/9)
2089//
2090// exp, expf, expl:
2091// * exp(log(x)) -> x
2092//
2093// log, logf, logl:
2094// * log(exp(x)) -> x
2095// * log(x**y) -> y*log(x)
2096// * log(exp(y)) -> y*log(e)
2097// * log(exp2(y)) -> y*log(2)
2098// * log(exp10(y)) -> y*log(10)
2099// * log(sqrt(x)) -> 0.5*log(x)
2100// * log(pow(x,y)) -> y*log(x)
2101//
2102// lround, lroundf, lroundl:
2103// * lround(cnst) -> cnst'
2104//
2105// pow, powf, powl:
2106// * pow(exp(x),y) -> exp(x*y)
2107// * pow(sqrt(x),y) -> pow(x,y*0.5)
2108// * pow(pow(x,y),z)-> pow(x,y*z)
2109//
2110// round, roundf, roundl:
2111// * round(cnst) -> cnst'
2112//
2113// signbit:
2114// * signbit(cnst) -> cnst'
2115// * signbit(nncst) -> 0 (if pstv is a non-negative constant)
2116//
2117// sqrt, sqrtf, sqrtl:
2118// * sqrt(expN(x)) -> expN(x*0.5)
2119// * sqrt(Nroot(x)) -> pow(x,1/(2*N))
2120// * sqrt(pow(x,y)) -> pow(|x|,y*0.5)
2121//
Meador Ingedfb08a22013-06-20 19:48:07 +00002122// tan, tanf, tanl:
2123// * tan(atan(x)) -> x
2124//
2125// trunc, truncf, truncl:
2126// * trunc(cnst) -> cnst'
2127//
2128//