blob: 6add97625a8c9de1eddad48ccc62da03555184f4 [file] [log] [blame]
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001//===- SimplifyLibCalls.cpp - Optimize specific well-known library calls --===//
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 file implements a simple pass that applies a variety of small
11// optimizations for calls to specific well-known function calls (e.g. runtime
Chris Lattnere9f9a7e2009-09-03 05:19:59 +000012// library functions). Any optimization that takes the very simple form
13// "replace call to library function with simpler code that provides the same
14// result" belongs in this file.
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +000015//
16//===----------------------------------------------------------------------===//
17
18#define DEBUG_TYPE "simplify-libcalls"
19#include "llvm/Transforms/Scalar.h"
Eric Christopherb6174e32010-03-05 22:25:30 +000020#include "llvm/Transforms/Utils/BuildLibCalls.h"
Chandler Carruth06cb8ed2012-06-29 12:38:19 +000021#include "llvm/IRBuilder.h"
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +000022#include "llvm/Intrinsics.h"
Owen Andersonfa5cbd62009-07-03 19:42:02 +000023#include "llvm/LLVMContext.h"
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +000024#include "llvm/Module.h"
25#include "llvm/Pass.h"
Daniel Dunbar473955f2009-07-29 22:00:43 +000026#include "llvm/ADT/STLExtras.h"
Chandler Carruth06cb8ed2012-06-29 12:38:19 +000027#include "llvm/ADT/SmallPtrSet.h"
28#include "llvm/ADT/Statistic.h"
29#include "llvm/ADT/StringMap.h"
30#include "llvm/Analysis/ValueTracking.h"
Chad Rosierec7e92a2012-08-22 17:22:33 +000031#include "llvm/Support/CommandLine.h"
Chris Lattner56b4f2b2008-05-01 06:39:12 +000032#include "llvm/Support/Debug.h"
Daniel Dunbarf0443c12009-07-26 08:34:35 +000033#include "llvm/Support/raw_ostream.h"
Chandler Carruth06cb8ed2012-06-29 12:38:19 +000034#include "llvm/Target/TargetData.h"
35#include "llvm/Target/TargetLibraryInfo.h"
Chris Lattnerafbf4832011-02-24 07:16:14 +000036#include "llvm/Config/config.h" // FIXME: Shouldn't depend on host!
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +000037using namespace llvm;
38
39STATISTIC(NumSimplified, "Number of library calls simplified");
Nick Lewycky0f8df9a2009-01-04 20:27:34 +000040STATISTIC(NumAnnotated, "Number of attributes added to library functions");
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +000041
Chad Rosierec7e92a2012-08-22 17:22:33 +000042static cl::opt<bool> UnsafeFPShrink("enable-double-float-shrink", cl::Hidden,
43 cl::init(false),
44 cl::desc("Enable unsafe double to float "
45 "shrinking for math lib calls"));
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +000046//===----------------------------------------------------------------------===//
47// Optimizer Base Class
48//===----------------------------------------------------------------------===//
49
50/// This class is the abstract base class for the set of optimizations that
51/// corresponds to one library call.
52namespace {
Chris Lattner3e8b6632009-09-02 06:11:42 +000053class LibCallOptimization {
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +000054protected:
55 Function *Caller;
56 const TargetData *TD;
Richard Osborne36498242011-03-03 13:17:51 +000057 const TargetLibraryInfo *TLI;
Owen Andersonfa5cbd62009-07-03 19:42:02 +000058 LLVMContext* Context;
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +000059public:
Evan Chengeb8c6452010-03-24 20:19:04 +000060 LibCallOptimization() { }
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +000061 virtual ~LibCallOptimization() {}
62
63 /// CallOptimizer - This pure virtual method is implemented by base classes to
64 /// do various optimizations. If this returns null then no transformation was
65 /// performed. If it returns CI, then it transformed the call and CI is to be
66 /// deleted. If it returns something else, replace CI with the new value and
67 /// delete CI.
Eric Christopher37c8b862009-10-07 21:14:25 +000068 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B)
Eric Christopher7a61d702008-08-08 19:39:37 +000069 =0;
Eric Christopher37c8b862009-10-07 21:14:25 +000070
Richard Osborne36498242011-03-03 13:17:51 +000071 Value *OptimizeCall(CallInst *CI, const TargetData *TD,
72 const TargetLibraryInfo *TLI, IRBuilder<> &B) {
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +000073 Caller = CI->getParent()->getParent();
Dan Gohmanf14d9192009-08-18 00:48:13 +000074 this->TD = TD;
Richard Osborne36498242011-03-03 13:17:51 +000075 this->TLI = TLI;
Owen Andersonfa5cbd62009-07-03 19:42:02 +000076 if (CI->getCalledFunction())
Owen Andersone922c022009-07-22 00:24:57 +000077 Context = &CI->getCalledFunction()->getContext();
Rafael Espindolae96af562010-06-16 19:34:01 +000078
79 // We never change the calling convention.
80 if (CI->getCallingConv() != llvm::CallingConv::C)
81 return NULL;
82
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +000083 return CallOptimizer(CI->getCalledFunction(), CI, B);
84 }
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +000085};
86} // End anonymous namespace.
87
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +000088
89//===----------------------------------------------------------------------===//
90// Helper Functions
91//===----------------------------------------------------------------------===//
92
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +000093/// IsOnlyUsedInZeroEqualityComparison - Return true if it only matters that the
Eric Christopher37c8b862009-10-07 21:14:25 +000094/// value is equal or not-equal to zero.
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +000095static bool IsOnlyUsedInZeroEqualityComparison(Value *V) {
96 for (Value::use_iterator UI = V->use_begin(), E = V->use_end();
97 UI != E; ++UI) {
98 if (ICmpInst *IC = dyn_cast<ICmpInst>(*UI))
99 if (IC->isEquality())
100 if (Constant *C = dyn_cast<Constant>(IC->getOperand(1)))
101 if (C->isNullValue())
102 continue;
103 // Unknown instruction.
104 return false;
105 }
106 return true;
107}
Nadav Rotema94d6e82012-07-24 10:51:42 +0000108
Richard Osborne36498242011-03-03 13:17:51 +0000109static bool CallHasFloatingPointArgument(const CallInst *CI) {
110 for (CallInst::const_op_iterator it = CI->op_begin(), e = CI->op_end();
111 it != e; ++it) {
112 if ((*it)->getType()->isFloatingPointTy())
113 return true;
114 }
115 return false;
116}
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000117
Benjamin Kramer386e9182010-06-15 21:34:25 +0000118/// IsOnlyUsedInEqualityComparison - Return true if it is only used in equality
119/// comparisons with With.
120static bool IsOnlyUsedInEqualityComparison(Value *V, Value *With) {
121 for (Value::use_iterator UI = V->use_begin(), E = V->use_end();
122 UI != E; ++UI) {
123 if (ICmpInst *IC = dyn_cast<ICmpInst>(*UI))
124 if (IC->isEquality() && IC->getOperand(1) == With)
125 continue;
126 // Unknown instruction.
127 return false;
128 }
129 return true;
130}
131
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000132//===----------------------------------------------------------------------===//
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000133// String and Memory LibCall Optimizations
134//===----------------------------------------------------------------------===//
135
136//===---------------------------------------===//
137// 'strcat' Optimizations
Chris Lattnere9f9a7e2009-09-03 05:19:59 +0000138namespace {
Chris Lattner3e8b6632009-09-02 06:11:42 +0000139struct StrCatOpt : public LibCallOptimization {
Eric Christopher7a61d702008-08-08 19:39:37 +0000140 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000141 // Verify the "strcat" function prototype.
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000142 FunctionType *FT = Callee->getFunctionType();
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000143 if (FT->getNumParams() != 2 ||
Benjamin Kramera1bf4ca2010-12-27 00:16:46 +0000144 FT->getReturnType() != B.getInt8PtrTy() ||
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000145 FT->getParamType(0) != FT->getReturnType() ||
146 FT->getParamType(1) != FT->getReturnType())
147 return 0;
Eric Christopher37c8b862009-10-07 21:14:25 +0000148
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000149 // Extract some information from the instruction
Gabor Greifaee5dc12010-06-24 10:42:46 +0000150 Value *Dst = CI->getArgOperand(0);
151 Value *Src = CI->getArgOperand(1);
Eric Christopher37c8b862009-10-07 21:14:25 +0000152
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000153 // See if we can get the length of the input string.
154 uint64_t Len = GetStringLength(Src);
Chris Lattner56b4f2b2008-05-01 06:39:12 +0000155 if (Len == 0) return 0;
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000156 --Len; // Unbias length.
Eric Christopher37c8b862009-10-07 21:14:25 +0000157
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000158 // Handle the simple, do-nothing case: strcat(x, "") -> x
159 if (Len == 0)
160 return Dst;
Dan Gohmanf14d9192009-08-18 00:48:13 +0000161
162 // These optimizations require TargetData.
163 if (!TD) return 0;
164
Nuno Lopescd31fc72012-07-26 17:10:46 +0000165 return EmitStrLenMemCpy(Src, Dst, Len, B);
Chris Lattnerf5b6bc72009-04-12 05:06:39 +0000166 }
167
Nuno Lopescd31fc72012-07-26 17:10:46 +0000168 Value *EmitStrLenMemCpy(Value *Src, Value *Dst, uint64_t Len, IRBuilder<> &B) {
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000169 // We need to find the end of the destination string. That's where the
170 // memory is to be moved to. We just generate a call to strlen.
Nuno Lopes51004df2012-07-25 16:46:31 +0000171 Value *DstLen = EmitStrLen(Dst, B, TD, TLI);
Nuno Lopescd31fc72012-07-26 17:10:46 +0000172 if (!DstLen)
173 return 0;
Eric Christopher37c8b862009-10-07 21:14:25 +0000174
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000175 // Now that we have the destination's length, we must index into the
176 // destination's pointer to get the actual memcpy destination (end of
177 // the string .. we're concatenating).
Ed Schoutenb5e0a962009-04-06 13:06:48 +0000178 Value *CpyDst = B.CreateGEP(Dst, DstLen, "endptr");
Eric Christopher37c8b862009-10-07 21:14:25 +0000179
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000180 // We have enough information to now generate the memcpy call to do the
181 // concatenation for us. Make a memcpy to copy the nul byte with align = 1.
Benjamin Kramera1bf4ca2010-12-27 00:16:46 +0000182 B.CreateMemCpy(CpyDst, Src,
183 ConstantInt::get(TD->getIntPtrType(*Context), Len + 1), 1);
Nuno Lopescd31fc72012-07-26 17:10:46 +0000184 return Dst;
Chris Lattnerf5b6bc72009-04-12 05:06:39 +0000185 }
186};
187
188//===---------------------------------------===//
189// 'strncat' Optimizations
190
Chris Lattner3e8b6632009-09-02 06:11:42 +0000191struct StrNCatOpt : public StrCatOpt {
Chris Lattnerf5b6bc72009-04-12 05:06:39 +0000192 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
193 // Verify the "strncat" function prototype.
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000194 FunctionType *FT = Callee->getFunctionType();
Chris Lattnerf5b6bc72009-04-12 05:06:39 +0000195 if (FT->getNumParams() != 3 ||
Benjamin Kramera1bf4ca2010-12-27 00:16:46 +0000196 FT->getReturnType() != B.getInt8PtrTy() ||
Chris Lattnerf5b6bc72009-04-12 05:06:39 +0000197 FT->getParamType(0) != FT->getReturnType() ||
198 FT->getParamType(1) != FT->getReturnType() ||
Duncan Sands1df98592010-02-16 11:11:14 +0000199 !FT->getParamType(2)->isIntegerTy())
Chris Lattnerf5b6bc72009-04-12 05:06:39 +0000200 return 0;
201
202 // Extract some information from the instruction
Gabor Greifaee5dc12010-06-24 10:42:46 +0000203 Value *Dst = CI->getArgOperand(0);
204 Value *Src = CI->getArgOperand(1);
Chris Lattnerf5b6bc72009-04-12 05:06:39 +0000205 uint64_t Len;
206
207 // We don't do anything if length is not constant
Gabor Greifaee5dc12010-06-24 10:42:46 +0000208 if (ConstantInt *LengthArg = dyn_cast<ConstantInt>(CI->getArgOperand(2)))
Chris Lattnerf5b6bc72009-04-12 05:06:39 +0000209 Len = LengthArg->getZExtValue();
210 else
211 return 0;
212
213 // See if we can get the length of the input string.
214 uint64_t SrcLen = GetStringLength(Src);
215 if (SrcLen == 0) return 0;
216 --SrcLen; // Unbias length.
217
218 // Handle the simple, do-nothing cases:
219 // strncat(x, "", c) -> x
220 // strncat(x, c, 0) -> x
221 if (SrcLen == 0 || Len == 0) return Dst;
222
Dan Gohmanf14d9192009-08-18 00:48:13 +0000223 // These optimizations require TargetData.
224 if (!TD) return 0;
225
Chris Lattnerf5b6bc72009-04-12 05:06:39 +0000226 // We don't optimize this case
227 if (Len < SrcLen) return 0;
228
229 // strncat(x, s, c) -> strcat(x, s)
230 // s is constant so the strcat can be optimized further
Nuno Lopescd31fc72012-07-26 17:10:46 +0000231 return EmitStrLenMemCpy(Src, Dst, SrcLen, B);
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000232 }
233};
234
235//===---------------------------------------===//
236// 'strchr' Optimizations
237
Chris Lattner3e8b6632009-09-02 06:11:42 +0000238struct StrChrOpt : public LibCallOptimization {
Eric Christopher7a61d702008-08-08 19:39:37 +0000239 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000240 // Verify the "strchr" function prototype.
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000241 FunctionType *FT = Callee->getFunctionType();
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000242 if (FT->getNumParams() != 2 ||
Benjamin Kramera1bf4ca2010-12-27 00:16:46 +0000243 FT->getReturnType() != B.getInt8PtrTy() ||
Benjamin Kramer4c756792010-09-30 11:21:59 +0000244 FT->getParamType(0) != FT->getReturnType() ||
245 !FT->getParamType(1)->isIntegerTy(32))
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000246 return 0;
Eric Christopher37c8b862009-10-07 21:14:25 +0000247
Gabor Greifaee5dc12010-06-24 10:42:46 +0000248 Value *SrcStr = CI->getArgOperand(0);
Eric Christopher37c8b862009-10-07 21:14:25 +0000249
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000250 // If the second operand is non-constant, see if we can compute the length
251 // of the input string and turn this into memchr.
Gabor Greifaee5dc12010-06-24 10:42:46 +0000252 ConstantInt *CharC = dyn_cast<ConstantInt>(CI->getArgOperand(1));
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000253 if (CharC == 0) {
Dan Gohmanf14d9192009-08-18 00:48:13 +0000254 // These optimizations require TargetData.
255 if (!TD) return 0;
256
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000257 uint64_t Len = GetStringLength(SrcStr);
Duncan Sandsb0bc6c32010-02-15 16:12:20 +0000258 if (Len == 0 || !FT->getParamType(1)->isIntegerTy(32))// memchr needs i32.
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000259 return 0;
Eric Christopher37c8b862009-10-07 21:14:25 +0000260
Gabor Greifaee5dc12010-06-24 10:42:46 +0000261 return EmitMemChr(SrcStr, CI->getArgOperand(1), // include nul.
Eric Christopherb6174e32010-03-05 22:25:30 +0000262 ConstantInt::get(TD->getIntPtrType(*Context), Len),
Nuno Lopes51004df2012-07-25 16:46:31 +0000263 B, TD, TLI);
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000264 }
Nadav Rotema94d6e82012-07-24 10:51:42 +0000265
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000266 // Otherwise, the character is a constant, see if the first argument is
267 // a string literal. If so, we can constant fold.
Chris Lattner18c7f802012-02-05 02:29:43 +0000268 StringRef Str;
269 if (!getConstantStringInfo(SrcStr, Str))
Chris Lattner56b4f2b2008-05-01 06:39:12 +0000270 return 0;
Eric Christopher37c8b862009-10-07 21:14:25 +0000271
Chris Lattner18c7f802012-02-05 02:29:43 +0000272 // Compute the offset, make sure to handle the case when we're searching for
273 // zero (a weird way to spell strlen).
274 size_t I = CharC->getSExtValue() == 0 ?
275 Str.size() : Str.find(CharC->getSExtValue());
276 if (I == StringRef::npos) // Didn't find the char. strchr returns null.
Benjamin Kramere2609902010-09-29 22:29:12 +0000277 return Constant::getNullValue(CI->getType());
Eric Christopher37c8b862009-10-07 21:14:25 +0000278
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000279 // strchr(s+n,c) -> gep(s+n+i,c)
Benjamin Kramera1bf4ca2010-12-27 00:16:46 +0000280 return B.CreateGEP(SrcStr, B.getInt64(I), "strchr");
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000281 }
282};
283
284//===---------------------------------------===//
Benjamin Kramer06f25cf2010-09-29 21:50:51 +0000285// 'strrchr' Optimizations
286
287struct StrRChrOpt : public LibCallOptimization {
288 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
289 // Verify the "strrchr" function prototype.
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000290 FunctionType *FT = Callee->getFunctionType();
Benjamin Kramer06f25cf2010-09-29 21:50:51 +0000291 if (FT->getNumParams() != 2 ||
Benjamin Kramera1bf4ca2010-12-27 00:16:46 +0000292 FT->getReturnType() != B.getInt8PtrTy() ||
Benjamin Kramer4c756792010-09-30 11:21:59 +0000293 FT->getParamType(0) != FT->getReturnType() ||
294 !FT->getParamType(1)->isIntegerTy(32))
Benjamin Kramer06f25cf2010-09-29 21:50:51 +0000295 return 0;
296
297 Value *SrcStr = CI->getArgOperand(0);
298 ConstantInt *CharC = dyn_cast<ConstantInt>(CI->getArgOperand(1));
299
300 // Cannot fold anything if we're not looking for a constant.
301 if (!CharC)
302 return 0;
303
Chris Lattner18c7f802012-02-05 02:29:43 +0000304 StringRef Str;
305 if (!getConstantStringInfo(SrcStr, Str)) {
Benjamin Kramer06f25cf2010-09-29 21:50:51 +0000306 // strrchr(s, 0) -> strchr(s, 0)
307 if (TD && CharC->isZero())
Nuno Lopes51004df2012-07-25 16:46:31 +0000308 return EmitStrChr(SrcStr, '\0', B, TD, TLI);
Benjamin Kramer06f25cf2010-09-29 21:50:51 +0000309 return 0;
310 }
311
Benjamin Kramer06f25cf2010-09-29 21:50:51 +0000312 // Compute the offset.
Chris Lattner18c7f802012-02-05 02:29:43 +0000313 size_t I = CharC->getSExtValue() == 0 ?
314 Str.size() : Str.rfind(CharC->getSExtValue());
315 if (I == StringRef::npos) // Didn't find the char. Return null.
Benjamin Kramer06f25cf2010-09-29 21:50:51 +0000316 return Constant::getNullValue(CI->getType());
317
318 // strrchr(s+n,c) -> gep(s+n+i,c)
Benjamin Kramera1bf4ca2010-12-27 00:16:46 +0000319 return B.CreateGEP(SrcStr, B.getInt64(I), "strrchr");
Benjamin Kramer06f25cf2010-09-29 21:50:51 +0000320 }
321};
322
323//===---------------------------------------===//
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000324// 'strcmp' Optimizations
325
Chris Lattner3e8b6632009-09-02 06:11:42 +0000326struct StrCmpOpt : public LibCallOptimization {
Eric Christopher7a61d702008-08-08 19:39:37 +0000327 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000328 // Verify the "strcmp" function prototype.
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000329 FunctionType *FT = Callee->getFunctionType();
Eric Christopher37c8b862009-10-07 21:14:25 +0000330 if (FT->getNumParams() != 2 ||
Nick Lewycky10d2f4d2010-07-06 03:53:43 +0000331 !FT->getReturnType()->isIntegerTy(32) ||
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000332 FT->getParamType(0) != FT->getParamType(1) ||
Benjamin Kramera1bf4ca2010-12-27 00:16:46 +0000333 FT->getParamType(0) != B.getInt8PtrTy())
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000334 return 0;
Eric Christopher37c8b862009-10-07 21:14:25 +0000335
Gabor Greifaee5dc12010-06-24 10:42:46 +0000336 Value *Str1P = CI->getArgOperand(0), *Str2P = CI->getArgOperand(1);
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000337 if (Str1P == Str2P) // strcmp(x,x) -> 0
Owen Andersoneed707b2009-07-24 23:12:02 +0000338 return ConstantInt::get(CI->getType(), 0);
Eric Christopher37c8b862009-10-07 21:14:25 +0000339
Chris Lattner18c7f802012-02-05 02:29:43 +0000340 StringRef Str1, Str2;
341 bool HasStr1 = getConstantStringInfo(Str1P, Str1);
342 bool HasStr2 = getConstantStringInfo(Str2P, Str2);
Eric Christopher37c8b862009-10-07 21:14:25 +0000343
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000344 // strcmp(x, y) -> cnst (if both x and y are constant strings)
Bill Wendling0582ae92009-03-13 04:39:26 +0000345 if (HasStr1 && HasStr2)
Chris Lattner18c7f802012-02-05 02:29:43 +0000346 return ConstantInt::get(CI->getType(), Str1.compare(Str2));
Eli Friedman79286082011-10-05 22:27:16 +0000347
348 if (HasStr1 && Str1.empty()) // strcmp("", x) -> -*x
349 return B.CreateNeg(B.CreateZExt(B.CreateLoad(Str2P, "strcmpload"),
350 CI->getType()));
351
352 if (HasStr2 && Str2.empty()) // strcmp(x,"") -> *x
353 return B.CreateZExt(B.CreateLoad(Str1P, "strcmpload"), CI->getType());
Nick Lewycky13a09e22008-12-21 00:19:21 +0000354
355 // strcmp(P, "x") -> memcmp(P, "x", 2)
356 uint64_t Len1 = GetStringLength(Str1P);
357 uint64_t Len2 = GetStringLength(Str2P);
Chris Lattner849832c2009-06-19 04:17:36 +0000358 if (Len1 && Len2) {
Dan Gohmanf14d9192009-08-18 00:48:13 +0000359 // These optimizations require TargetData.
360 if (!TD) return 0;
361
Nick Lewycky13a09e22008-12-21 00:19:21 +0000362 return EmitMemCmp(Str1P, Str2P,
Owen Anderson1d0be152009-08-13 21:58:54 +0000363 ConstantInt::get(TD->getIntPtrType(*Context),
Nuno Lopes51004df2012-07-25 16:46:31 +0000364 std::min(Len1, Len2)), B, TD, TLI);
Nick Lewycky13a09e22008-12-21 00:19:21 +0000365 }
366
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000367 return 0;
368 }
369};
370
371//===---------------------------------------===//
372// 'strncmp' Optimizations
373
Chris Lattner3e8b6632009-09-02 06:11:42 +0000374struct StrNCmpOpt : public LibCallOptimization {
Eric Christopher7a61d702008-08-08 19:39:37 +0000375 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000376 // Verify the "strncmp" function prototype.
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000377 FunctionType *FT = Callee->getFunctionType();
Eric Christopher37c8b862009-10-07 21:14:25 +0000378 if (FT->getNumParams() != 3 ||
Nick Lewycky10d2f4d2010-07-06 03:53:43 +0000379 !FT->getReturnType()->isIntegerTy(32) ||
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000380 FT->getParamType(0) != FT->getParamType(1) ||
Benjamin Kramera1bf4ca2010-12-27 00:16:46 +0000381 FT->getParamType(0) != B.getInt8PtrTy() ||
Duncan Sands1df98592010-02-16 11:11:14 +0000382 !FT->getParamType(2)->isIntegerTy())
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000383 return 0;
Eric Christopher37c8b862009-10-07 21:14:25 +0000384
Gabor Greifaee5dc12010-06-24 10:42:46 +0000385 Value *Str1P = CI->getArgOperand(0), *Str2P = CI->getArgOperand(1);
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000386 if (Str1P == Str2P) // strncmp(x,x,n) -> 0
Owen Andersoneed707b2009-07-24 23:12:02 +0000387 return ConstantInt::get(CI->getType(), 0);
Eric Christopher37c8b862009-10-07 21:14:25 +0000388
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000389 // Get the length argument if it is constant.
390 uint64_t Length;
Gabor Greifaee5dc12010-06-24 10:42:46 +0000391 if (ConstantInt *LengthArg = dyn_cast<ConstantInt>(CI->getArgOperand(2)))
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000392 Length = LengthArg->getZExtValue();
393 else
394 return 0;
Eric Christopher37c8b862009-10-07 21:14:25 +0000395
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000396 if (Length == 0) // strncmp(x,y,0) -> 0
Owen Andersoneed707b2009-07-24 23:12:02 +0000397 return ConstantInt::get(CI->getType(), 0);
Eric Christopher37c8b862009-10-07 21:14:25 +0000398
Benjamin Kramerea9ca022010-06-16 10:30:29 +0000399 if (TD && Length == 1) // strncmp(x,y,1) -> memcmp(x,y,1)
Nuno Lopes51004df2012-07-25 16:46:31 +0000400 return EmitMemCmp(Str1P, Str2P, CI->getArgOperand(2), B, TD, TLI);
Benjamin Kramerea9ca022010-06-16 10:30:29 +0000401
Chris Lattner18c7f802012-02-05 02:29:43 +0000402 StringRef Str1, Str2;
403 bool HasStr1 = getConstantStringInfo(Str1P, Str1);
404 bool HasStr2 = getConstantStringInfo(Str2P, Str2);
Eric Christopher37c8b862009-10-07 21:14:25 +0000405
Eli Friedman79286082011-10-05 22:27:16 +0000406 // strncmp(x, y) -> cnst (if both x and y are constant strings)
407 if (HasStr1 && HasStr2) {
Chris Lattner18c7f802012-02-05 02:29:43 +0000408 StringRef SubStr1 = Str1.substr(0, Length);
409 StringRef SubStr2 = Str2.substr(0, Length);
Eli Friedman79286082011-10-05 22:27:16 +0000410 return ConstantInt::get(CI->getType(), SubStr1.compare(SubStr2));
411 }
412
413 if (HasStr1 && Str1.empty()) // strncmp("", x, n) -> -*x
414 return B.CreateNeg(B.CreateZExt(B.CreateLoad(Str2P, "strcmpload"),
415 CI->getType()));
Eric Christopher37c8b862009-10-07 21:14:25 +0000416
Bill Wendling0582ae92009-03-13 04:39:26 +0000417 if (HasStr2 && Str2.empty()) // strncmp(x, "", n) -> *x
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000418 return B.CreateZExt(B.CreateLoad(Str1P, "strcmpload"), CI->getType());
Eric Christopher37c8b862009-10-07 21:14:25 +0000419
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000420 return 0;
421 }
422};
423
424
425//===---------------------------------------===//
426// 'strcpy' Optimizations
427
Chris Lattner3e8b6632009-09-02 06:11:42 +0000428struct StrCpyOpt : public LibCallOptimization {
Evan Chengeb8c6452010-03-24 20:19:04 +0000429 bool OptChkCall; // True if it's optimizing a __strcpy_chk libcall.
430
431 StrCpyOpt(bool c) : OptChkCall(c) {}
432
Eric Christopher7a61d702008-08-08 19:39:37 +0000433 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000434 // Verify the "strcpy" function prototype.
Evan Cheng0289b412010-03-23 15:48:04 +0000435 unsigned NumParams = OptChkCall ? 3 : 2;
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000436 FunctionType *FT = Callee->getFunctionType();
Evan Cheng0289b412010-03-23 15:48:04 +0000437 if (FT->getNumParams() != NumParams ||
438 FT->getReturnType() != FT->getParamType(0) ||
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000439 FT->getParamType(0) != FT->getParamType(1) ||
Benjamin Kramera1bf4ca2010-12-27 00:16:46 +0000440 FT->getParamType(0) != B.getInt8PtrTy())
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000441 return 0;
Eric Christopher37c8b862009-10-07 21:14:25 +0000442
Gabor Greifaee5dc12010-06-24 10:42:46 +0000443 Value *Dst = CI->getArgOperand(0), *Src = CI->getArgOperand(1);
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000444 if (Dst == Src) // strcpy(x,x) -> x
445 return Src;
Eric Christopher37c8b862009-10-07 21:14:25 +0000446
Dan Gohmanf14d9192009-08-18 00:48:13 +0000447 // These optimizations require TargetData.
448 if (!TD) return 0;
449
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000450 // See if we can get the length of the input string.
451 uint64_t Len = GetStringLength(Src);
Chris Lattner56b4f2b2008-05-01 06:39:12 +0000452 if (Len == 0) return 0;
Eric Christopher37c8b862009-10-07 21:14:25 +0000453
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000454 // We have enough information to now generate the memcpy call to do the
455 // concatenation for us. Make a memcpy to copy the nul byte with align = 1.
Nuno Lopescd31fc72012-07-26 17:10:46 +0000456 if (!OptChkCall ||
457 !EmitMemCpyChk(Dst, Src,
458 ConstantInt::get(TD->getIntPtrType(*Context), Len),
459 CI->getArgOperand(2), B, TD, TLI))
Benjamin Kramera1bf4ca2010-12-27 00:16:46 +0000460 B.CreateMemCpy(Dst, Src,
461 ConstantInt::get(TD->getIntPtrType(*Context), Len), 1);
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000462 return Dst;
463 }
464};
465
Chris Lattnerf5b6bc72009-04-12 05:06:39 +0000466//===---------------------------------------===//
David Majnemerac782662012-05-15 11:46:21 +0000467// 'stpcpy' Optimizations
468
469struct StpCpyOpt: public LibCallOptimization {
470 bool OptChkCall; // True if it's optimizing a __stpcpy_chk libcall.
471
472 StpCpyOpt(bool c) : OptChkCall(c) {}
473
474 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
475 // Verify the "stpcpy" function prototype.
476 unsigned NumParams = OptChkCall ? 3 : 2;
477 FunctionType *FT = Callee->getFunctionType();
478 if (FT->getNumParams() != NumParams ||
479 FT->getReturnType() != FT->getParamType(0) ||
480 FT->getParamType(0) != FT->getParamType(1) ||
481 FT->getParamType(0) != B.getInt8PtrTy())
482 return 0;
483
484 // These optimizations require TargetData.
485 if (!TD) return 0;
486
487 Value *Dst = CI->getArgOperand(0), *Src = CI->getArgOperand(1);
Nuno Lopes51004df2012-07-25 16:46:31 +0000488 if (Dst == Src) { // stpcpy(x,x) -> x+strlen(x)
489 Value *StrLen = EmitStrLen(Src, B, TD, TLI);
490 return StrLen ? B.CreateInBoundsGEP(Dst, StrLen) : 0;
491 }
David Majnemerac782662012-05-15 11:46:21 +0000492
493 // See if we can get the length of the input string.
494 uint64_t Len = GetStringLength(Src);
495 if (Len == 0) return 0;
496
497 Value *LenV = ConstantInt::get(TD->getIntPtrType(*Context), Len);
498 Value *DstEnd = B.CreateGEP(Dst,
499 ConstantInt::get(TD->getIntPtrType(*Context),
500 Len - 1));
501
502 // We have enough information to now generate the memcpy call to do the
503 // copy for us. Make a memcpy to copy the nul byte with align = 1.
Nuno Lopescd31fc72012-07-26 17:10:46 +0000504 if (!OptChkCall || !EmitMemCpyChk(Dst, Src, LenV, CI->getArgOperand(2), B,
505 TD, TLI))
David Majnemerac782662012-05-15 11:46:21 +0000506 B.CreateMemCpy(Dst, Src, LenV, 1);
507 return DstEnd;
508 }
509};
510
511//===---------------------------------------===//
Chris Lattnerf5b6bc72009-04-12 05:06:39 +0000512// 'strncpy' Optimizations
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000513
Chris Lattner3e8b6632009-09-02 06:11:42 +0000514struct StrNCpyOpt : public LibCallOptimization {
Chris Lattnerf5b6bc72009-04-12 05:06:39 +0000515 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000516 FunctionType *FT = Callee->getFunctionType();
Chris Lattnerf5b6bc72009-04-12 05:06:39 +0000517 if (FT->getNumParams() != 3 || FT->getReturnType() != FT->getParamType(0) ||
518 FT->getParamType(0) != FT->getParamType(1) ||
Benjamin Kramera1bf4ca2010-12-27 00:16:46 +0000519 FT->getParamType(0) != B.getInt8PtrTy() ||
Duncan Sands1df98592010-02-16 11:11:14 +0000520 !FT->getParamType(2)->isIntegerTy())
Chris Lattnerf5b6bc72009-04-12 05:06:39 +0000521 return 0;
522
Gabor Greifaee5dc12010-06-24 10:42:46 +0000523 Value *Dst = CI->getArgOperand(0);
524 Value *Src = CI->getArgOperand(1);
525 Value *LenOp = CI->getArgOperand(2);
Chris Lattnerf5b6bc72009-04-12 05:06:39 +0000526
527 // See if we can get the length of the input string.
528 uint64_t SrcLen = GetStringLength(Src);
529 if (SrcLen == 0) return 0;
530 --SrcLen;
531
532 if (SrcLen == 0) {
533 // strncpy(x, "", y) -> memset(x, '\0', y, 1)
Benjamin Kramera1bf4ca2010-12-27 00:16:46 +0000534 B.CreateMemSet(Dst, B.getInt8('\0'), LenOp, 1);
Chris Lattnerf5b6bc72009-04-12 05:06:39 +0000535 return Dst;
536 }
537
538 uint64_t Len;
539 if (ConstantInt *LengthArg = dyn_cast<ConstantInt>(LenOp))
540 Len = LengthArg->getZExtValue();
541 else
542 return 0;
543
544 if (Len == 0) return Dst; // strncpy(x, y, 0) -> x
545
Dan Gohmanf14d9192009-08-18 00:48:13 +0000546 // These optimizations require TargetData.
547 if (!TD) return 0;
548
Chris Lattnerf5b6bc72009-04-12 05:06:39 +0000549 // Let strncpy handle the zero padding
550 if (Len > SrcLen+1) return 0;
551
552 // strncpy(x, s, c) -> memcpy(x, s, c, 1) [s and c are constant]
Benjamin Kramera1bf4ca2010-12-27 00:16:46 +0000553 B.CreateMemCpy(Dst, Src,
554 ConstantInt::get(TD->getIntPtrType(*Context), Len), 1);
Chris Lattnerf5b6bc72009-04-12 05:06:39 +0000555
556 return Dst;
557 }
558};
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000559
560//===---------------------------------------===//
561// 'strlen' Optimizations
562
Chris Lattner3e8b6632009-09-02 06:11:42 +0000563struct StrLenOpt : public LibCallOptimization {
Eric Christopher7a61d702008-08-08 19:39:37 +0000564 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000565 FunctionType *FT = Callee->getFunctionType();
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000566 if (FT->getNumParams() != 1 ||
Benjamin Kramera1bf4ca2010-12-27 00:16:46 +0000567 FT->getParamType(0) != B.getInt8PtrTy() ||
Duncan Sands1df98592010-02-16 11:11:14 +0000568 !FT->getReturnType()->isIntegerTy())
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000569 return 0;
Eric Christopher37c8b862009-10-07 21:14:25 +0000570
Gabor Greifaee5dc12010-06-24 10:42:46 +0000571 Value *Src = CI->getArgOperand(0);
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000572
573 // Constant folding: strlen("xyz") -> 3
574 if (uint64_t Len = GetStringLength(Src))
Owen Andersoneed707b2009-07-24 23:12:02 +0000575 return ConstantInt::get(CI->getType(), Len-1);
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000576
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000577 // strlen(x) != 0 --> *x != 0
578 // strlen(x) == 0 --> *x == 0
Chris Lattner98d67d72009-12-23 23:24:51 +0000579 if (IsOnlyUsedInZeroEqualityComparison(CI))
580 return B.CreateZExt(B.CreateLoad(Src, "strlenfirst"), CI->getType());
581 return 0;
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000582 }
583};
584
Benjamin Kramer05f585e2010-09-29 23:52:12 +0000585
586//===---------------------------------------===//
587// 'strpbrk' Optimizations
588
589struct StrPBrkOpt : public LibCallOptimization {
590 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000591 FunctionType *FT = Callee->getFunctionType();
Benjamin Kramer05f585e2010-09-29 23:52:12 +0000592 if (FT->getNumParams() != 2 ||
Benjamin Kramera1bf4ca2010-12-27 00:16:46 +0000593 FT->getParamType(0) != B.getInt8PtrTy() ||
Benjamin Kramer05f585e2010-09-29 23:52:12 +0000594 FT->getParamType(1) != FT->getParamType(0) ||
595 FT->getReturnType() != FT->getParamType(0))
596 return 0;
597
Chris Lattner18c7f802012-02-05 02:29:43 +0000598 StringRef S1, S2;
599 bool HasS1 = getConstantStringInfo(CI->getArgOperand(0), S1);
600 bool HasS2 = getConstantStringInfo(CI->getArgOperand(1), S2);
Benjamin Kramer05f585e2010-09-29 23:52:12 +0000601
602 // strpbrk(s, "") -> NULL
603 // strpbrk("", s) -> NULL
604 if ((HasS1 && S1.empty()) || (HasS2 && S2.empty()))
605 return Constant::getNullValue(CI->getType());
606
607 // Constant folding.
608 if (HasS1 && HasS2) {
609 size_t I = S1.find_first_of(S2);
610 if (I == std::string::npos) // No match.
611 return Constant::getNullValue(CI->getType());
612
Benjamin Kramera1bf4ca2010-12-27 00:16:46 +0000613 return B.CreateGEP(CI->getArgOperand(0), B.getInt64(I), "strpbrk");
Benjamin Kramer05f585e2010-09-29 23:52:12 +0000614 }
615
616 // strpbrk(s, "a") -> strchr(s, 'a')
617 if (TD && HasS2 && S2.size() == 1)
Nuno Lopes51004df2012-07-25 16:46:31 +0000618 return EmitStrChr(CI->getArgOperand(0), S2[0], B, TD, TLI);
Benjamin Kramer05f585e2010-09-29 23:52:12 +0000619
620 return 0;
621 }
622};
623
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000624//===---------------------------------------===//
Chris Lattner24604112009-12-16 09:32:05 +0000625// 'strto*' Optimizations. This handles strtol, strtod, strtof, strtoul, etc.
Nick Lewycky4c498412009-02-13 15:31:46 +0000626
Chris Lattner3e8b6632009-09-02 06:11:42 +0000627struct StrToOpt : public LibCallOptimization {
Nick Lewycky4c498412009-02-13 15:31:46 +0000628 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000629 FunctionType *FT = Callee->getFunctionType();
Nick Lewycky4c498412009-02-13 15:31:46 +0000630 if ((FT->getNumParams() != 2 && FT->getNumParams() != 3) ||
Duncan Sands1df98592010-02-16 11:11:14 +0000631 !FT->getParamType(0)->isPointerTy() ||
632 !FT->getParamType(1)->isPointerTy())
Nick Lewycky4c498412009-02-13 15:31:46 +0000633 return 0;
634
Gabor Greifaee5dc12010-06-24 10:42:46 +0000635 Value *EndPtr = CI->getArgOperand(1);
Nick Lewycky02b6a6a2009-02-13 17:08:33 +0000636 if (isa<ConstantPointerNull>(EndPtr)) {
Dan Gohmanc32046e2010-12-17 01:09:43 +0000637 // With a null EndPtr, this function won't capture the main argument.
638 // It would be readonly too, except that it still may write to errno.
Nick Lewycky4c498412009-02-13 15:31:46 +0000639 CI->addAttribute(1, Attribute::NoCapture);
Nick Lewycky02b6a6a2009-02-13 17:08:33 +0000640 }
Nick Lewycky4c498412009-02-13 15:31:46 +0000641
642 return 0;
643 }
644};
645
Chris Lattner24604112009-12-16 09:32:05 +0000646//===---------------------------------------===//
Benjamin Kramer9510a252010-09-30 00:58:35 +0000647// 'strspn' Optimizations
648
649struct StrSpnOpt : public LibCallOptimization {
650 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000651 FunctionType *FT = Callee->getFunctionType();
Benjamin Kramer9510a252010-09-30 00:58:35 +0000652 if (FT->getNumParams() != 2 ||
Benjamin Kramera1bf4ca2010-12-27 00:16:46 +0000653 FT->getParamType(0) != B.getInt8PtrTy() ||
Benjamin Kramer9510a252010-09-30 00:58:35 +0000654 FT->getParamType(1) != FT->getParamType(0) ||
655 !FT->getReturnType()->isIntegerTy())
656 return 0;
657
Chris Lattner18c7f802012-02-05 02:29:43 +0000658 StringRef S1, S2;
659 bool HasS1 = getConstantStringInfo(CI->getArgOperand(0), S1);
660 bool HasS2 = getConstantStringInfo(CI->getArgOperand(1), S2);
Benjamin Kramer9510a252010-09-30 00:58:35 +0000661
662 // strspn(s, "") -> 0
663 // strspn("", s) -> 0
664 if ((HasS1 && S1.empty()) || (HasS2 && S2.empty()))
665 return Constant::getNullValue(CI->getType());
666
667 // Constant folding.
Chris Lattner18c7f802012-02-05 02:29:43 +0000668 if (HasS1 && HasS2) {
669 size_t Pos = S1.find_first_not_of(S2);
670 if (Pos == StringRef::npos) Pos = S1.size();
671 return ConstantInt::get(CI->getType(), Pos);
672 }
Benjamin Kramer9510a252010-09-30 00:58:35 +0000673
674 return 0;
675 }
676};
677
678//===---------------------------------------===//
679// 'strcspn' Optimizations
680
681struct StrCSpnOpt : public LibCallOptimization {
682 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000683 FunctionType *FT = Callee->getFunctionType();
Benjamin Kramer9510a252010-09-30 00:58:35 +0000684 if (FT->getNumParams() != 2 ||
Benjamin Kramera1bf4ca2010-12-27 00:16:46 +0000685 FT->getParamType(0) != B.getInt8PtrTy() ||
Benjamin Kramer9510a252010-09-30 00:58:35 +0000686 FT->getParamType(1) != FT->getParamType(0) ||
687 !FT->getReturnType()->isIntegerTy())
688 return 0;
689
Chris Lattner18c7f802012-02-05 02:29:43 +0000690 StringRef S1, S2;
691 bool HasS1 = getConstantStringInfo(CI->getArgOperand(0), S1);
692 bool HasS2 = getConstantStringInfo(CI->getArgOperand(1), S2);
Benjamin Kramer9510a252010-09-30 00:58:35 +0000693
694 // strcspn("", s) -> 0
695 if (HasS1 && S1.empty())
696 return Constant::getNullValue(CI->getType());
697
698 // Constant folding.
Chris Lattner18c7f802012-02-05 02:29:43 +0000699 if (HasS1 && HasS2) {
700 size_t Pos = S1.find_first_of(S2);
701 if (Pos == StringRef::npos) Pos = S1.size();
702 return ConstantInt::get(CI->getType(), Pos);
703 }
Benjamin Kramer9510a252010-09-30 00:58:35 +0000704
705 // strcspn(s, "") -> strlen(s)
706 if (TD && HasS2 && S2.empty())
Nuno Lopes51004df2012-07-25 16:46:31 +0000707 return EmitStrLen(CI->getArgOperand(0), B, TD, TLI);
Benjamin Kramer9510a252010-09-30 00:58:35 +0000708
709 return 0;
710 }
711};
712
713//===---------------------------------------===//
Chris Lattner24604112009-12-16 09:32:05 +0000714// 'strstr' Optimizations
715
716struct StrStrOpt : public LibCallOptimization {
717 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000718 FunctionType *FT = Callee->getFunctionType();
Chris Lattner24604112009-12-16 09:32:05 +0000719 if (FT->getNumParams() != 2 ||
Duncan Sands1df98592010-02-16 11:11:14 +0000720 !FT->getParamType(0)->isPointerTy() ||
721 !FT->getParamType(1)->isPointerTy() ||
722 !FT->getReturnType()->isPointerTy())
Chris Lattner24604112009-12-16 09:32:05 +0000723 return 0;
724
725 // fold strstr(x, x) -> x.
Gabor Greifaee5dc12010-06-24 10:42:46 +0000726 if (CI->getArgOperand(0) == CI->getArgOperand(1))
727 return B.CreateBitCast(CI->getArgOperand(0), CI->getType());
Mikhail Glushenkoved5cb592010-01-04 07:55:25 +0000728
Benjamin Kramer386e9182010-06-15 21:34:25 +0000729 // fold strstr(a, b) == a -> strncmp(a, b, strlen(b)) == 0
Gabor Greif8e1ebff2010-06-30 12:42:43 +0000730 if (TD && IsOnlyUsedInEqualityComparison(CI, CI->getArgOperand(0))) {
Nuno Lopes51004df2012-07-25 16:46:31 +0000731 Value *StrLen = EmitStrLen(CI->getArgOperand(1), B, TD, TLI);
732 if (!StrLen)
733 return 0;
Gabor Greif8e1ebff2010-06-30 12:42:43 +0000734 Value *StrNCmp = EmitStrNCmp(CI->getArgOperand(0), CI->getArgOperand(1),
Nuno Lopes51004df2012-07-25 16:46:31 +0000735 StrLen, B, TD, TLI);
736 if (!StrNCmp)
737 return 0;
Benjamin Kramer386e9182010-06-15 21:34:25 +0000738 for (Value::use_iterator UI = CI->use_begin(), UE = CI->use_end();
739 UI != UE; ) {
Gabor Greif96f1d8e2010-07-22 13:36:47 +0000740 ICmpInst *Old = cast<ICmpInst>(*UI++);
Benjamin Kramer386e9182010-06-15 21:34:25 +0000741 Value *Cmp = B.CreateICmp(Old->getPredicate(), StrNCmp,
742 ConstantInt::getNullValue(StrNCmp->getType()),
743 "cmp");
744 Old->replaceAllUsesWith(Cmp);
745 Old->eraseFromParent();
746 }
747 return CI;
748 }
749
Chris Lattner24604112009-12-16 09:32:05 +0000750 // See if either input string is a constant string.
Chris Lattner18c7f802012-02-05 02:29:43 +0000751 StringRef SearchStr, ToFindStr;
752 bool HasStr1 = getConstantStringInfo(CI->getArgOperand(0), SearchStr);
753 bool HasStr2 = getConstantStringInfo(CI->getArgOperand(1), ToFindStr);
Mikhail Glushenkoved5cb592010-01-04 07:55:25 +0000754
Chris Lattner24604112009-12-16 09:32:05 +0000755 // fold strstr(x, "") -> x.
756 if (HasStr2 && ToFindStr.empty())
Gabor Greifaee5dc12010-06-24 10:42:46 +0000757 return B.CreateBitCast(CI->getArgOperand(0), CI->getType());
Mikhail Glushenkoved5cb592010-01-04 07:55:25 +0000758
Chris Lattner24604112009-12-16 09:32:05 +0000759 // If both strings are known, constant fold it.
760 if (HasStr1 && HasStr2) {
761 std::string::size_type Offset = SearchStr.find(ToFindStr);
Mikhail Glushenkoved5cb592010-01-04 07:55:25 +0000762
Chris Lattner18c7f802012-02-05 02:29:43 +0000763 if (Offset == StringRef::npos) // strstr("foo", "bar") -> null
Chris Lattner24604112009-12-16 09:32:05 +0000764 return Constant::getNullValue(CI->getType());
765
766 // strstr("abcd", "bc") -> gep((char*)"abcd", 1)
Gabor Greifaee5dc12010-06-24 10:42:46 +0000767 Value *Result = CastToCStr(CI->getArgOperand(0), B);
Chris Lattner24604112009-12-16 09:32:05 +0000768 Result = B.CreateConstInBoundsGEP1_64(Result, Offset, "strstr");
769 return B.CreateBitCast(Result, CI->getType());
770 }
Mikhail Glushenkoved5cb592010-01-04 07:55:25 +0000771
Chris Lattner24604112009-12-16 09:32:05 +0000772 // fold strstr(x, "y") -> strchr(x, 'y').
Nuno Lopes51004df2012-07-25 16:46:31 +0000773 if (HasStr2 && ToFindStr.size() == 1) {
774 Value *StrChr= EmitStrChr(CI->getArgOperand(0), ToFindStr[0], B, TD, TLI);
775 return StrChr ? B.CreateBitCast(StrChr, CI->getType()) : 0;
776 }
Chris Lattner24604112009-12-16 09:32:05 +0000777 return 0;
778 }
779};
Mikhail Glushenkoved5cb592010-01-04 07:55:25 +0000780
Nick Lewycky4c498412009-02-13 15:31:46 +0000781
782//===---------------------------------------===//
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000783// 'memcmp' Optimizations
784
Chris Lattner3e8b6632009-09-02 06:11:42 +0000785struct MemCmpOpt : public LibCallOptimization {
Eric Christopher7a61d702008-08-08 19:39:37 +0000786 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000787 FunctionType *FT = Callee->getFunctionType();
Duncan Sands1df98592010-02-16 11:11:14 +0000788 if (FT->getNumParams() != 3 || !FT->getParamType(0)->isPointerTy() ||
789 !FT->getParamType(1)->isPointerTy() ||
Duncan Sandsb0bc6c32010-02-15 16:12:20 +0000790 !FT->getReturnType()->isIntegerTy(32))
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000791 return 0;
Duncan Sandsec00fcb2008-05-19 09:27:24 +0000792
Gabor Greifaee5dc12010-06-24 10:42:46 +0000793 Value *LHS = CI->getArgOperand(0), *RHS = CI->getArgOperand(1);
Duncan Sandsec00fcb2008-05-19 09:27:24 +0000794
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000795 if (LHS == RHS) // memcmp(s,s,x) -> 0
Owen Andersona7235ea2009-07-31 20:28:14 +0000796 return Constant::getNullValue(CI->getType());
Duncan Sandsec00fcb2008-05-19 09:27:24 +0000797
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000798 // Make sure we have a constant length.
Gabor Greifaee5dc12010-06-24 10:42:46 +0000799 ConstantInt *LenC = dyn_cast<ConstantInt>(CI->getArgOperand(2));
Chris Lattner56b4f2b2008-05-01 06:39:12 +0000800 if (!LenC) return 0;
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000801 uint64_t Len = LenC->getZExtValue();
Duncan Sandsec00fcb2008-05-19 09:27:24 +0000802
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000803 if (Len == 0) // memcmp(s1,s2,0) -> 0
Owen Andersona7235ea2009-07-31 20:28:14 +0000804 return Constant::getNullValue(CI->getType());
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000805
Benjamin Kramer48aefe12010-05-25 22:53:43 +0000806 // memcmp(S1,S2,1) -> *(unsigned char*)LHS - *(unsigned char*)RHS
807 if (Len == 1) {
808 Value *LHSV = B.CreateZExt(B.CreateLoad(CastToCStr(LHS, B), "lhsc"),
809 CI->getType(), "lhsv");
810 Value *RHSV = B.CreateZExt(B.CreateLoad(CastToCStr(RHS, B), "rhsc"),
811 CI->getType(), "rhsv");
Benjamin Kramer1464c1d2010-05-26 09:45:04 +0000812 return B.CreateSub(LHSV, RHSV, "chardiff");
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000813 }
Duncan Sandsec00fcb2008-05-19 09:27:24 +0000814
Benjamin Kramer992a6372009-11-05 17:44:22 +0000815 // Constant folding: memcmp(x, y, l) -> cnst (all arguments are constant)
Chris Lattner18c7f802012-02-05 02:29:43 +0000816 StringRef LHSStr, RHSStr;
817 if (getConstantStringInfo(LHS, LHSStr) &&
818 getConstantStringInfo(RHS, RHSStr)) {
Benjamin Kramer992a6372009-11-05 17:44:22 +0000819 // Make sure we're not reading out-of-bounds memory.
Chris Lattner18c7f802012-02-05 02:29:43 +0000820 if (Len > LHSStr.size() || Len > RHSStr.size())
Benjamin Kramer992a6372009-11-05 17:44:22 +0000821 return 0;
822 uint64_t Ret = memcmp(LHSStr.data(), RHSStr.data(), Len);
823 return ConstantInt::get(CI->getType(), Ret);
824 }
825
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000826 return 0;
827 }
828};
829
830//===---------------------------------------===//
831// 'memcpy' Optimizations
832
Chris Lattner3e8b6632009-09-02 06:11:42 +0000833struct MemCpyOpt : public LibCallOptimization {
Eric Christopher7a61d702008-08-08 19:39:37 +0000834 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
Dan Gohmanf14d9192009-08-18 00:48:13 +0000835 // These optimizations require TargetData.
836 if (!TD) return 0;
837
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000838 FunctionType *FT = Callee->getFunctionType();
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000839 if (FT->getNumParams() != 3 || FT->getReturnType() != FT->getParamType(0) ||
Duncan Sands1df98592010-02-16 11:11:14 +0000840 !FT->getParamType(0)->isPointerTy() ||
841 !FT->getParamType(1)->isPointerTy() ||
Owen Anderson1d0be152009-08-13 21:58:54 +0000842 FT->getParamType(2) != TD->getIntPtrType(*Context))
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000843 return 0;
844
845 // memcpy(x, y, n) -> llvm.memcpy(x, y, n, 1)
Benjamin Kramera1bf4ca2010-12-27 00:16:46 +0000846 B.CreateMemCpy(CI->getArgOperand(0), CI->getArgOperand(1),
847 CI->getArgOperand(2), 1);
Gabor Greifaee5dc12010-06-24 10:42:46 +0000848 return CI->getArgOperand(0);
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000849 }
850};
851
Eli Friedmand83ae7d2008-11-30 08:32:11 +0000852//===---------------------------------------===//
853// 'memmove' Optimizations
854
Chris Lattner3e8b6632009-09-02 06:11:42 +0000855struct MemMoveOpt : public LibCallOptimization {
Eli Friedmand83ae7d2008-11-30 08:32:11 +0000856 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
Dan Gohmanf14d9192009-08-18 00:48:13 +0000857 // These optimizations require TargetData.
858 if (!TD) return 0;
859
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000860 FunctionType *FT = Callee->getFunctionType();
Eli Friedmand83ae7d2008-11-30 08:32:11 +0000861 if (FT->getNumParams() != 3 || FT->getReturnType() != FT->getParamType(0) ||
Duncan Sands1df98592010-02-16 11:11:14 +0000862 !FT->getParamType(0)->isPointerTy() ||
863 !FT->getParamType(1)->isPointerTy() ||
Owen Anderson1d0be152009-08-13 21:58:54 +0000864 FT->getParamType(2) != TD->getIntPtrType(*Context))
Eli Friedmand83ae7d2008-11-30 08:32:11 +0000865 return 0;
866
867 // memmove(x, y, n) -> llvm.memmove(x, y, n, 1)
Benjamin Kramera1bf4ca2010-12-27 00:16:46 +0000868 B.CreateMemMove(CI->getArgOperand(0), CI->getArgOperand(1),
869 CI->getArgOperand(2), 1);
Gabor Greifaee5dc12010-06-24 10:42:46 +0000870 return CI->getArgOperand(0);
Eli Friedmand83ae7d2008-11-30 08:32:11 +0000871 }
872};
873
874//===---------------------------------------===//
875// 'memset' Optimizations
876
Chris Lattner3e8b6632009-09-02 06:11:42 +0000877struct MemSetOpt : public LibCallOptimization {
Eli Friedmand83ae7d2008-11-30 08:32:11 +0000878 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
Dan Gohmanf14d9192009-08-18 00:48:13 +0000879 // These optimizations require TargetData.
880 if (!TD) return 0;
881
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000882 FunctionType *FT = Callee->getFunctionType();
Eli Friedmand83ae7d2008-11-30 08:32:11 +0000883 if (FT->getNumParams() != 3 || FT->getReturnType() != FT->getParamType(0) ||
Duncan Sands1df98592010-02-16 11:11:14 +0000884 !FT->getParamType(0)->isPointerTy() ||
885 !FT->getParamType(1)->isIntegerTy() ||
Owen Anderson1d0be152009-08-13 21:58:54 +0000886 FT->getParamType(2) != TD->getIntPtrType(*Context))
Eli Friedmand83ae7d2008-11-30 08:32:11 +0000887 return 0;
888
889 // memset(p, v, n) -> llvm.memset(p, v, n, 1)
Benjamin Kramera1bf4ca2010-12-27 00:16:46 +0000890 Value *Val = B.CreateIntCast(CI->getArgOperand(1), B.getInt8Ty(), false);
891 B.CreateMemSet(CI->getArgOperand(0), Val, CI->getArgOperand(2), 1);
Gabor Greifaee5dc12010-06-24 10:42:46 +0000892 return CI->getArgOperand(0);
Eli Friedmand83ae7d2008-11-30 08:32:11 +0000893 }
894};
895
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000896//===----------------------------------------------------------------------===//
897// Math Library Optimizations
898//===----------------------------------------------------------------------===//
899
900//===---------------------------------------===//
Chad Rosierec7e92a2012-08-22 17:22:33 +0000901// Double -> Float Shrinking Optimizations for Unary Functions like 'floor'
Nick Lewyckya6b21ea2011-12-27 18:25:50 +0000902
Chad Rosierec7e92a2012-08-22 17:22:33 +0000903struct UnaryDoubleFPOpt : public LibCallOptimization {
904 bool CheckRetType;
905 UnaryDoubleFPOpt(bool CheckReturnType): CheckRetType(CheckReturnType) {}
906 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
907 FunctionType *FT = Callee->getFunctionType();
908 if (FT->getNumParams() != 1 || !FT->getReturnType()->isDoubleTy() ||
909 !FT->getParamType(0)->isDoubleTy())
910 return 0;
911
912 if (CheckRetType) {
913 // Check if all the uses for function like 'sin' are converted to float.
914 for (Value::use_iterator UseI = CI->use_begin(); UseI != CI->use_end();
915 ++UseI) {
916 FPTruncInst *Cast = dyn_cast<FPTruncInst>(*UseI);
917 if (Cast == 0 || !Cast->getType()->isFloatTy())
918 return 0;
919 }
920 }
921
922 // If this is something like 'floor((double)floatval)', convert to floorf.
923 FPExtInst *Cast = dyn_cast<FPExtInst>(CI->getArgOperand(0));
924 if (Cast == 0 || !Cast->getOperand(0)->getType()->isFloatTy())
925 return 0;
926
927 // floor((double)floatval) -> (double)floorf(floatval)
928 Value *V = Cast->getOperand(0);
929 V = EmitUnaryFloatFnCall(V, Callee->getName(), B, Callee->getAttributes());
930 return B.CreateFPExt(V, B.getDoubleTy());
931 }
932};
933
934//===---------------------------------------===//
935// 'cos*' Optimizations
Nick Lewyckya6b21ea2011-12-27 18:25:50 +0000936struct CosOpt : public LibCallOptimization {
937 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
Chad Rosierec7e92a2012-08-22 17:22:33 +0000938 Value *Ret = NULL;
939 if (UnsafeFPShrink && Callee->getName() == "cos" &&
940 TLI->has(LibFunc::cosf)) {
941 UnaryDoubleFPOpt UnsafeUnaryDoubleFP(true);
942 Ret = UnsafeUnaryDoubleFP.CallOptimizer(Callee, CI, B);
943 }
944
Nick Lewyckya6b21ea2011-12-27 18:25:50 +0000945 FunctionType *FT = Callee->getFunctionType();
946 // Just make sure this has 1 argument of FP type, which matches the
947 // result type.
948 if (FT->getNumParams() != 1 || FT->getReturnType() != FT->getParamType(0) ||
949 !FT->getParamType(0)->isFloatingPointTy())
Chad Rosierec7e92a2012-08-22 17:22:33 +0000950 return Ret;
Nick Lewyckya6b21ea2011-12-27 18:25:50 +0000951
952 // cos(-x) -> cos(x)
953 Value *Op1 = CI->getArgOperand(0);
954 if (BinaryOperator::isFNeg(Op1)) {
955 BinaryOperator *BinExpr = cast<BinaryOperator>(Op1);
956 return B.CreateCall(Callee, BinExpr->getOperand(1), "cos");
957 }
Chad Rosierec7e92a2012-08-22 17:22:33 +0000958 return Ret;
Nick Lewyckya6b21ea2011-12-27 18:25:50 +0000959 }
960};
961
962//===---------------------------------------===//
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000963// 'pow*' Optimizations
964
Chris Lattner3e8b6632009-09-02 06:11:42 +0000965struct PowOpt : public LibCallOptimization {
Eric Christopher7a61d702008-08-08 19:39:37 +0000966 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
Chad Rosierec7e92a2012-08-22 17:22:33 +0000967 Value *Ret = NULL;
968 if (UnsafeFPShrink && Callee->getName() == "pow" &&
969 TLI->has(LibFunc::powf)) {
970 UnaryDoubleFPOpt UnsafeUnaryDoubleFP(true);
971 Ret = UnsafeUnaryDoubleFP.CallOptimizer(Callee, CI, B);
972 }
973
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000974 FunctionType *FT = Callee->getFunctionType();
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000975 // Just make sure this has 2 arguments of the same FP type, which match the
976 // result type.
977 if (FT->getNumParams() != 2 || FT->getReturnType() != FT->getParamType(0) ||
978 FT->getParamType(0) != FT->getParamType(1) ||
Duncan Sandsb0bc6c32010-02-15 16:12:20 +0000979 !FT->getParamType(0)->isFloatingPointTy())
Chad Rosierec7e92a2012-08-22 17:22:33 +0000980 return Ret;
Eric Christopher37c8b862009-10-07 21:14:25 +0000981
Gabor Greifaee5dc12010-06-24 10:42:46 +0000982 Value *Op1 = CI->getArgOperand(0), *Op2 = CI->getArgOperand(1);
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000983 if (ConstantFP *Op1C = dyn_cast<ConstantFP>(Op1)) {
984 if (Op1C->isExactlyValue(1.0)) // pow(1.0, x) -> 1.0
985 return Op1C;
986 if (Op1C->isExactlyValue(2.0)) // pow(2.0, x) -> exp2(x)
Dan Gohman76926b62009-09-26 18:10:13 +0000987 return EmitUnaryFloatFnCall(Op2, "exp2", B, Callee->getAttributes());
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000988 }
Eric Christopher37c8b862009-10-07 21:14:25 +0000989
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000990 ConstantFP *Op2C = dyn_cast<ConstantFP>(Op2);
Chad Rosierec7e92a2012-08-22 17:22:33 +0000991 if (Op2C == 0) return Ret;
Eric Christopher37c8b862009-10-07 21:14:25 +0000992
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000993 if (Op2C->getValueAPF().isZero()) // pow(x, 0.0) -> 1.0
Owen Anderson6f83c9c2009-07-27 20:59:43 +0000994 return ConstantFP::get(CI->getType(), 1.0);
Eric Christopher37c8b862009-10-07 21:14:25 +0000995
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000996 if (Op2C->isExactlyValue(0.5)) {
Dan Gohman79cb8402009-09-25 23:10:17 +0000997 // Expand pow(x, 0.5) to (x == -infinity ? +infinity : fabs(sqrt(x))).
998 // This is faster than calling pow, and still handles negative zero
Nick Lewyckya6b21ea2011-12-27 18:25:50 +0000999 // and negative infinity correctly.
Dan Gohman79cb8402009-09-25 23:10:17 +00001000 // TODO: In fast-math mode, this could be just sqrt(x).
1001 // TODO: In finite-only mode, this could be just fabs(sqrt(x)).
Dan Gohmana23643d2009-09-25 23:40:21 +00001002 Value *Inf = ConstantFP::getInfinity(CI->getType());
1003 Value *NegInf = ConstantFP::getInfinity(CI->getType(), true);
Dan Gohman76926b62009-09-26 18:10:13 +00001004 Value *Sqrt = EmitUnaryFloatFnCall(Op1, "sqrt", B,
1005 Callee->getAttributes());
1006 Value *FAbs = EmitUnaryFloatFnCall(Sqrt, "fabs", B,
1007 Callee->getAttributes());
Benjamin Kramera9390a42011-09-27 20:39:19 +00001008 Value *FCmp = B.CreateFCmpOEQ(Op1, NegInf);
1009 Value *Sel = B.CreateSelect(FCmp, Inf, FAbs);
Dan Gohman79cb8402009-09-25 23:10:17 +00001010 return Sel;
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001011 }
Eric Christopher37c8b862009-10-07 21:14:25 +00001012
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001013 if (Op2C->isExactlyValue(1.0)) // pow(x, 1.0) -> x
1014 return Op1;
1015 if (Op2C->isExactlyValue(2.0)) // pow(x, 2.0) -> x*x
Dan Gohmanae3a0be2009-06-04 22:49:04 +00001016 return B.CreateFMul(Op1, Op1, "pow2");
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001017 if (Op2C->isExactlyValue(-1.0)) // pow(x, -1.0) -> 1.0/x
Owen Anderson6f83c9c2009-07-27 20:59:43 +00001018 return B.CreateFDiv(ConstantFP::get(CI->getType(), 1.0),
Owen Andersonfa5cbd62009-07-03 19:42:02 +00001019 Op1, "powrecip");
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001020 return 0;
1021 }
1022};
1023
1024//===---------------------------------------===//
Chris Lattnere818f772008-05-02 18:43:35 +00001025// 'exp2' Optimizations
1026
Chris Lattner3e8b6632009-09-02 06:11:42 +00001027struct Exp2Opt : public LibCallOptimization {
Eric Christopher7a61d702008-08-08 19:39:37 +00001028 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
Chad Rosierec7e92a2012-08-22 17:22:33 +00001029 Value *Ret = NULL;
1030 if (UnsafeFPShrink && Callee->getName() == "exp2" &&
1031 TLI->has(LibFunc::exp2)) {
1032 UnaryDoubleFPOpt UnsafeUnaryDoubleFP(true);
1033 Ret = UnsafeUnaryDoubleFP.CallOptimizer(Callee, CI, B);
1034 }
1035
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001036 FunctionType *FT = Callee->getFunctionType();
Chris Lattnere818f772008-05-02 18:43:35 +00001037 // Just make sure this has 1 argument of FP type, which matches the
1038 // result type.
1039 if (FT->getNumParams() != 1 || FT->getReturnType() != FT->getParamType(0) ||
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00001040 !FT->getParamType(0)->isFloatingPointTy())
Chad Rosierec7e92a2012-08-22 17:22:33 +00001041 return Ret;
Eric Christopher37c8b862009-10-07 21:14:25 +00001042
Gabor Greifaee5dc12010-06-24 10:42:46 +00001043 Value *Op = CI->getArgOperand(0);
Chris Lattnere818f772008-05-02 18:43:35 +00001044 // Turn exp2(sitofp(x)) -> ldexp(1.0, sext(x)) if sizeof(x) <= 32
1045 // Turn exp2(uitofp(x)) -> ldexp(1.0, zext(x)) if sizeof(x) < 32
1046 Value *LdExpArg = 0;
1047 if (SIToFPInst *OpC = dyn_cast<SIToFPInst>(Op)) {
1048 if (OpC->getOperand(0)->getType()->getPrimitiveSizeInBits() <= 32)
Benjamin Kramera9390a42011-09-27 20:39:19 +00001049 LdExpArg = B.CreateSExt(OpC->getOperand(0), B.getInt32Ty());
Chris Lattnere818f772008-05-02 18:43:35 +00001050 } else if (UIToFPInst *OpC = dyn_cast<UIToFPInst>(Op)) {
1051 if (OpC->getOperand(0)->getType()->getPrimitiveSizeInBits() < 32)
Benjamin Kramera9390a42011-09-27 20:39:19 +00001052 LdExpArg = B.CreateZExt(OpC->getOperand(0), B.getInt32Ty());
Chris Lattnere818f772008-05-02 18:43:35 +00001053 }
Anton Korobeynikov9547cdf2009-06-18 20:05:31 +00001054
Chris Lattnere818f772008-05-02 18:43:35 +00001055 if (LdExpArg) {
1056 const char *Name;
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001057 if (Op->getType()->isFloatTy())
Chris Lattnere818f772008-05-02 18:43:35 +00001058 Name = "ldexpf";
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001059 else if (Op->getType()->isDoubleTy())
Chris Lattnere818f772008-05-02 18:43:35 +00001060 Name = "ldexp";
1061 else
1062 Name = "ldexpl";
1063
Owen Anderson6f83c9c2009-07-27 20:59:43 +00001064 Constant *One = ConstantFP::get(*Context, APFloat(1.0f));
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001065 if (!Op->getType()->isFloatTy())
Owen Andersonbaf3c402009-07-29 18:55:55 +00001066 One = ConstantExpr::getFPExtend(One, Op->getType());
Chris Lattnere818f772008-05-02 18:43:35 +00001067
1068 Module *M = Caller->getParent();
1069 Value *Callee = M->getOrInsertFunction(Name, Op->getType(),
Eric Christopher37c8b862009-10-07 21:14:25 +00001070 Op->getType(),
Benjamin Kramera1bf4ca2010-12-27 00:16:46 +00001071 B.getInt32Ty(), NULL);
Anton Korobeynikov9547cdf2009-06-18 20:05:31 +00001072 CallInst *CI = B.CreateCall2(Callee, One, LdExpArg);
1073 if (const Function *F = dyn_cast<Function>(Callee->stripPointerCasts()))
1074 CI->setCallingConv(F->getCallingConv());
1075
1076 return CI;
Chris Lattnere818f772008-05-02 18:43:35 +00001077 }
Chad Rosierec7e92a2012-08-22 17:22:33 +00001078 return Ret;
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001079 }
1080};
1081
1082//===----------------------------------------------------------------------===//
1083// Integer Optimizations
1084//===----------------------------------------------------------------------===//
1085
1086//===---------------------------------------===//
1087// 'ffs*' Optimizations
1088
Chris Lattner3e8b6632009-09-02 06:11:42 +00001089struct FFSOpt : public LibCallOptimization {
Eric Christopher7a61d702008-08-08 19:39:37 +00001090 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001091 FunctionType *FT = Callee->getFunctionType();
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001092 // Just make sure this has 2 arguments of the same FP type, which match the
1093 // result type.
Eric Christopher37c8b862009-10-07 21:14:25 +00001094 if (FT->getNumParams() != 1 ||
Nick Lewycky10d2f4d2010-07-06 03:53:43 +00001095 !FT->getReturnType()->isIntegerTy(32) ||
Duncan Sands1df98592010-02-16 11:11:14 +00001096 !FT->getParamType(0)->isIntegerTy())
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001097 return 0;
Eric Christopher37c8b862009-10-07 21:14:25 +00001098
Gabor Greifaee5dc12010-06-24 10:42:46 +00001099 Value *Op = CI->getArgOperand(0);
Eric Christopher37c8b862009-10-07 21:14:25 +00001100
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001101 // Constant fold.
1102 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op)) {
1103 if (CI->getValue() == 0) // ffs(0) -> 0.
Owen Andersona7235ea2009-07-31 20:28:14 +00001104 return Constant::getNullValue(CI->getType());
Benjamin Kramera1bf4ca2010-12-27 00:16:46 +00001105 // ffs(c) -> cttz(c)+1
1106 return B.getInt32(CI->getValue().countTrailingZeros() + 1);
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001107 }
Eric Christopher37c8b862009-10-07 21:14:25 +00001108
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001109 // ffs(x) -> x != 0 ? (i32)llvm.cttz(x)+1 : 0
Jay Foad5fdd6c82011-07-12 14:06:48 +00001110 Type *ArgType = Op->getType();
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001111 Value *F = Intrinsic::getDeclaration(Callee->getParent(),
Benjamin Kramereb9a85f2011-07-14 17:45:39 +00001112 Intrinsic::cttz, ArgType);
Chandler Carruthccbf1e32011-12-12 04:26:04 +00001113 Value *V = B.CreateCall2(F, Op, B.getFalse(), "cttz");
Benjamin Kramera9390a42011-09-27 20:39:19 +00001114 V = B.CreateAdd(V, ConstantInt::get(V->getType(), 1));
1115 V = B.CreateIntCast(V, B.getInt32Ty(), false);
Eric Christopher37c8b862009-10-07 21:14:25 +00001116
Benjamin Kramera9390a42011-09-27 20:39:19 +00001117 Value *Cond = B.CreateICmpNE(Op, Constant::getNullValue(ArgType));
Benjamin Kramera1bf4ca2010-12-27 00:16:46 +00001118 return B.CreateSelect(Cond, V, B.getInt32(0));
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001119 }
1120};
1121
1122//===---------------------------------------===//
1123// 'isdigit' Optimizations
1124
Chris Lattner3e8b6632009-09-02 06:11:42 +00001125struct IsDigitOpt : public LibCallOptimization {
Eric Christopher7a61d702008-08-08 19:39:37 +00001126 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001127 FunctionType *FT = Callee->getFunctionType();
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001128 // We require integer(i32)
Duncan Sands1df98592010-02-16 11:11:14 +00001129 if (FT->getNumParams() != 1 || !FT->getReturnType()->isIntegerTy() ||
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00001130 !FT->getParamType(0)->isIntegerTy(32))
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001131 return 0;
Eric Christopher37c8b862009-10-07 21:14:25 +00001132
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001133 // isdigit(c) -> (c-'0') <u 10
Gabor Greifaee5dc12010-06-24 10:42:46 +00001134 Value *Op = CI->getArgOperand(0);
Benjamin Kramera1bf4ca2010-12-27 00:16:46 +00001135 Op = B.CreateSub(Op, B.getInt32('0'), "isdigittmp");
1136 Op = B.CreateICmpULT(Op, B.getInt32(10), "isdigit");
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001137 return B.CreateZExt(Op, CI->getType());
1138 }
1139};
1140
1141//===---------------------------------------===//
1142// 'isascii' Optimizations
1143
Chris Lattner3e8b6632009-09-02 06:11:42 +00001144struct IsAsciiOpt : public LibCallOptimization {
Eric Christopher7a61d702008-08-08 19:39:37 +00001145 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001146 FunctionType *FT = Callee->getFunctionType();
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001147 // We require integer(i32)
Duncan Sands1df98592010-02-16 11:11:14 +00001148 if (FT->getNumParams() != 1 || !FT->getReturnType()->isIntegerTy() ||
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00001149 !FT->getParamType(0)->isIntegerTy(32))
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001150 return 0;
Eric Christopher37c8b862009-10-07 21:14:25 +00001151
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001152 // isascii(c) -> c <u 128
Gabor Greifaee5dc12010-06-24 10:42:46 +00001153 Value *Op = CI->getArgOperand(0);
Benjamin Kramera1bf4ca2010-12-27 00:16:46 +00001154 Op = B.CreateICmpULT(Op, B.getInt32(128), "isascii");
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001155 return B.CreateZExt(Op, CI->getType());
1156 }
1157};
Eric Christopher37c8b862009-10-07 21:14:25 +00001158
Chris Lattner313f0e62008-06-09 08:26:51 +00001159//===---------------------------------------===//
1160// 'abs', 'labs', 'llabs' Optimizations
1161
Chris Lattner3e8b6632009-09-02 06:11:42 +00001162struct AbsOpt : public LibCallOptimization {
Eric Christopher7a61d702008-08-08 19:39:37 +00001163 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001164 FunctionType *FT = Callee->getFunctionType();
Chris Lattner313f0e62008-06-09 08:26:51 +00001165 // We require integer(integer) where the types agree.
Duncan Sands1df98592010-02-16 11:11:14 +00001166 if (FT->getNumParams() != 1 || !FT->getReturnType()->isIntegerTy() ||
Chris Lattner313f0e62008-06-09 08:26:51 +00001167 FT->getParamType(0) != FT->getReturnType())
1168 return 0;
Eric Christopher37c8b862009-10-07 21:14:25 +00001169
Chris Lattner313f0e62008-06-09 08:26:51 +00001170 // abs(x) -> x >s -1 ? x : -x
Gabor Greifaee5dc12010-06-24 10:42:46 +00001171 Value *Op = CI->getArgOperand(0);
Benjamin Kramera1bf4ca2010-12-27 00:16:46 +00001172 Value *Pos = B.CreateICmpSGT(Op, Constant::getAllOnesValue(Op->getType()),
Chris Lattner313f0e62008-06-09 08:26:51 +00001173 "ispos");
1174 Value *Neg = B.CreateNeg(Op, "neg");
1175 return B.CreateSelect(Pos, Op, Neg);
1176 }
1177};
Eric Christopher37c8b862009-10-07 21:14:25 +00001178
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001179
1180//===---------------------------------------===//
1181// 'toascii' Optimizations
1182
Chris Lattner3e8b6632009-09-02 06:11:42 +00001183struct ToAsciiOpt : public LibCallOptimization {
Eric Christopher7a61d702008-08-08 19:39:37 +00001184 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001185 FunctionType *FT = Callee->getFunctionType();
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001186 // We require i32(i32)
1187 if (FT->getNumParams() != 1 || FT->getReturnType() != FT->getParamType(0) ||
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00001188 !FT->getParamType(0)->isIntegerTy(32))
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001189 return 0;
Eric Christopher37c8b862009-10-07 21:14:25 +00001190
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001191 // isascii(c) -> c & 0x7f
Gabor Greifaee5dc12010-06-24 10:42:46 +00001192 return B.CreateAnd(CI->getArgOperand(0),
Owen Andersoneed707b2009-07-24 23:12:02 +00001193 ConstantInt::get(CI->getType(),0x7F));
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001194 }
1195};
1196
1197//===----------------------------------------------------------------------===//
1198// Formatting and IO Optimizations
1199//===----------------------------------------------------------------------===//
1200
1201//===---------------------------------------===//
1202// 'printf' Optimizations
1203
Chris Lattner3e8b6632009-09-02 06:11:42 +00001204struct PrintFOpt : public LibCallOptimization {
Richard Osborne36498242011-03-03 13:17:51 +00001205 Value *OptimizeFixedFormatString(Function *Callee, CallInst *CI,
1206 IRBuilder<> &B) {
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001207 // Check for a fixed format string.
Chris Lattner18c7f802012-02-05 02:29:43 +00001208 StringRef FormatStr;
1209 if (!getConstantStringInfo(CI->getArgOperand(0), FormatStr))
Bill Wendling0582ae92009-03-13 04:39:26 +00001210 return 0;
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001211
1212 // Empty format string -> noop.
1213 if (FormatStr.empty()) // Tolerate printf's declared void.
Eric Christopher37c8b862009-10-07 21:14:25 +00001214 return CI->use_empty() ? (Value*)CI :
Owen Andersoneed707b2009-07-24 23:12:02 +00001215 ConstantInt::get(CI->getType(), 0);
Eric Christopher37c8b862009-10-07 21:14:25 +00001216
Daniel Dunbard02be242011-02-12 18:19:57 +00001217 // Do not do any of the following transformations if the printf return value
1218 // is used, in general the printf return value is not compatible with either
1219 // putchar() or puts().
1220 if (!CI->use_empty())
1221 return 0;
1222
1223 // printf("x") -> putchar('x'), even for '%'.
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001224 if (FormatStr.size() == 1) {
Nuno Lopes51004df2012-07-25 16:46:31 +00001225 Value *Res = EmitPutChar(B.getInt32(FormatStr[0]), B, TD, TLI);
Nuno Lopescd31fc72012-07-26 17:10:46 +00001226 if (CI->use_empty() || !Res) return Res;
Chris Lattner74965f22009-11-09 04:57:04 +00001227 return B.CreateIntCast(Res, CI->getType(), true);
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001228 }
Eric Christopher37c8b862009-10-07 21:14:25 +00001229
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001230 // printf("foo\n") --> puts("foo")
1231 if (FormatStr[FormatStr.size()-1] == '\n' &&
1232 FormatStr.find('%') == std::string::npos) { // no format characters.
1233 // Create a string literal with no \n on it. We expect the constant merge
1234 // pass to be run after this pass, to merge duplicate strings.
Chris Lattner18c7f802012-02-05 02:29:43 +00001235 FormatStr = FormatStr.drop_back();
Benjamin Kramer59e43bd2011-10-29 19:43:31 +00001236 Value *GV = B.CreateGlobalString(FormatStr, "str");
Nuno Lopes51004df2012-07-25 16:46:31 +00001237 Value *NewCI = EmitPutS(GV, B, TD, TLI);
1238 return (CI->use_empty() || !NewCI) ?
1239 NewCI :
1240 ConstantInt::get(CI->getType(), FormatStr.size()+1);
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001241 }
Eric Christopher37c8b862009-10-07 21:14:25 +00001242
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001243 // Optimize specific format strings.
Gabor Greifaee5dc12010-06-24 10:42:46 +00001244 // printf("%c", chr) --> putchar(chr)
Gabor Greif8e1ebff2010-06-30 12:42:43 +00001245 if (FormatStr == "%c" && CI->getNumArgOperands() > 1 &&
Gabor Greifaee5dc12010-06-24 10:42:46 +00001246 CI->getArgOperand(1)->getType()->isIntegerTy()) {
Nuno Lopes51004df2012-07-25 16:46:31 +00001247 Value *Res = EmitPutChar(CI->getArgOperand(1), B, TD, TLI);
Eric Christopher80bf1d52009-11-21 01:01:30 +00001248
Nuno Lopescd31fc72012-07-26 17:10:46 +00001249 if (CI->use_empty() || !Res) return Res;
Chris Lattner74965f22009-11-09 04:57:04 +00001250 return B.CreateIntCast(Res, CI->getType(), true);
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001251 }
Eric Christopher37c8b862009-10-07 21:14:25 +00001252
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001253 // printf("%s\n", str) --> puts(str)
Gabor Greif8e1ebff2010-06-30 12:42:43 +00001254 if (FormatStr == "%s\n" && CI->getNumArgOperands() > 1 &&
Daniel Dunbard02be242011-02-12 18:19:57 +00001255 CI->getArgOperand(1)->getType()->isPointerTy()) {
Nuno Lopes51004df2012-07-25 16:46:31 +00001256 return EmitPutS(CI->getArgOperand(1), B, TD, TLI);
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001257 }
1258 return 0;
1259 }
Richard Osborne36498242011-03-03 13:17:51 +00001260
1261 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
1262 // Require one fixed pointer argument and an integer/void result.
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001263 FunctionType *FT = Callee->getFunctionType();
Richard Osborne36498242011-03-03 13:17:51 +00001264 if (FT->getNumParams() < 1 || !FT->getParamType(0)->isPointerTy() ||
1265 !(FT->getReturnType()->isIntegerTy() ||
1266 FT->getReturnType()->isVoidTy()))
1267 return 0;
1268
1269 if (Value *V = OptimizeFixedFormatString(Callee, CI, B)) {
1270 return V;
1271 }
1272
1273 // printf(format, ...) -> iprintf(format, ...) if no floating point
1274 // arguments.
1275 if (TLI->has(LibFunc::iprintf) && !CallHasFloatingPointArgument(CI)) {
1276 Module *M = B.GetInsertBlock()->getParent()->getParent();
1277 Constant *IPrintFFn =
1278 M->getOrInsertFunction("iprintf", FT, Callee->getAttributes());
1279 CallInst *New = cast<CallInst>(CI->clone());
1280 New->setCalledFunction(IPrintFFn);
1281 B.Insert(New);
1282 return New;
1283 }
1284 return 0;
1285 }
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001286};
1287
1288//===---------------------------------------===//
1289// 'sprintf' Optimizations
1290
Chris Lattner3e8b6632009-09-02 06:11:42 +00001291struct SPrintFOpt : public LibCallOptimization {
Richard Osborne419454a2011-03-03 14:09:28 +00001292 Value *OptimizeFixedFormatString(Function *Callee, CallInst *CI,
1293 IRBuilder<> &B) {
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001294 // Check for a fixed format string.
Chris Lattner18c7f802012-02-05 02:29:43 +00001295 StringRef FormatStr;
1296 if (!getConstantStringInfo(CI->getArgOperand(1), FormatStr))
Bill Wendling0582ae92009-03-13 04:39:26 +00001297 return 0;
Eric Christopher37c8b862009-10-07 21:14:25 +00001298
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001299 // If we just have a format string (nothing else crazy) transform it.
Gabor Greif8e1ebff2010-06-30 12:42:43 +00001300 if (CI->getNumArgOperands() == 2) {
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001301 // Make sure there's no % in the constant array. We could try to handle
1302 // %% -> % in the future if we cared.
1303 for (unsigned i = 0, e = FormatStr.size(); i != e; ++i)
1304 if (FormatStr[i] == '%')
1305 return 0; // we found a format specifier, bail out.
Dan Gohmanf14d9192009-08-18 00:48:13 +00001306
1307 // These optimizations require TargetData.
1308 if (!TD) return 0;
1309
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001310 // sprintf(str, fmt) -> llvm.memcpy(str, fmt, strlen(fmt)+1, 1)
Benjamin Kramera1bf4ca2010-12-27 00:16:46 +00001311 B.CreateMemCpy(CI->getArgOperand(0), CI->getArgOperand(1),
1312 ConstantInt::get(TD->getIntPtrType(*Context), // Copy the
1313 FormatStr.size() + 1), 1); // nul byte.
Owen Andersoneed707b2009-07-24 23:12:02 +00001314 return ConstantInt::get(CI->getType(), FormatStr.size());
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001315 }
Eric Christopher37c8b862009-10-07 21:14:25 +00001316
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001317 // The remaining optimizations require the format string to be "%s" or "%c"
1318 // and have an extra operand.
Gabor Greif8e1ebff2010-06-30 12:42:43 +00001319 if (FormatStr.size() != 2 || FormatStr[0] != '%' ||
1320 CI->getNumArgOperands() < 3)
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001321 return 0;
Eric Christopher37c8b862009-10-07 21:14:25 +00001322
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001323 // Decode the second character of the format string.
1324 if (FormatStr[1] == 'c') {
Chris Lattner56b4f2b2008-05-01 06:39:12 +00001325 // sprintf(dst, "%c", chr) --> *(i8*)dst = chr; *((i8*)dst+1) = 0
Gabor Greifaee5dc12010-06-24 10:42:46 +00001326 if (!CI->getArgOperand(2)->getType()->isIntegerTy()) return 0;
Benjamin Kramera1bf4ca2010-12-27 00:16:46 +00001327 Value *V = B.CreateTrunc(CI->getArgOperand(2), B.getInt8Ty(), "char");
Gabor Greifaee5dc12010-06-24 10:42:46 +00001328 Value *Ptr = CastToCStr(CI->getArgOperand(0), B);
Chris Lattner56b4f2b2008-05-01 06:39:12 +00001329 B.CreateStore(V, Ptr);
Benjamin Kramera1bf4ca2010-12-27 00:16:46 +00001330 Ptr = B.CreateGEP(Ptr, B.getInt32(1), "nul");
1331 B.CreateStore(B.getInt8(0), Ptr);
Eric Christopher37c8b862009-10-07 21:14:25 +00001332
Owen Andersoneed707b2009-07-24 23:12:02 +00001333 return ConstantInt::get(CI->getType(), 1);
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001334 }
Eric Christopher37c8b862009-10-07 21:14:25 +00001335
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001336 if (FormatStr[1] == 's') {
Dan Gohmanf14d9192009-08-18 00:48:13 +00001337 // These optimizations require TargetData.
1338 if (!TD) return 0;
1339
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001340 // sprintf(dest, "%s", str) -> llvm.memcpy(dest, str, strlen(str)+1, 1)
Gabor Greifaee5dc12010-06-24 10:42:46 +00001341 if (!CI->getArgOperand(2)->getType()->isPointerTy()) return 0;
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001342
Nuno Lopes51004df2012-07-25 16:46:31 +00001343 Value *Len = EmitStrLen(CI->getArgOperand(2), B, TD, TLI);
1344 if (!Len)
1345 return 0;
Owen Andersonfa5cbd62009-07-03 19:42:02 +00001346 Value *IncLen = B.CreateAdd(Len,
Owen Andersoneed707b2009-07-24 23:12:02 +00001347 ConstantInt::get(Len->getType(), 1),
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001348 "leninc");
Benjamin Kramera1bf4ca2010-12-27 00:16:46 +00001349 B.CreateMemCpy(CI->getArgOperand(0), CI->getArgOperand(2), IncLen, 1);
Eric Christopher37c8b862009-10-07 21:14:25 +00001350
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001351 // The sprintf result is the unincremented number of bytes in the string.
1352 return B.CreateIntCast(Len, CI->getType(), false);
1353 }
1354 return 0;
1355 }
Richard Osborne419454a2011-03-03 14:09:28 +00001356
1357 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
1358 // Require two fixed pointer arguments and an integer result.
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001359 FunctionType *FT = Callee->getFunctionType();
Richard Osborne419454a2011-03-03 14:09:28 +00001360 if (FT->getNumParams() != 2 || !FT->getParamType(0)->isPointerTy() ||
1361 !FT->getParamType(1)->isPointerTy() ||
1362 !FT->getReturnType()->isIntegerTy())
1363 return 0;
1364
1365 if (Value *V = OptimizeFixedFormatString(Callee, CI, B)) {
1366 return V;
1367 }
1368
Richard Osborneea2578c2011-03-03 14:21:22 +00001369 // sprintf(str, format, ...) -> siprintf(str, format, ...) if no floating
Richard Osborne419454a2011-03-03 14:09:28 +00001370 // point arguments.
1371 if (TLI->has(LibFunc::siprintf) && !CallHasFloatingPointArgument(CI)) {
1372 Module *M = B.GetInsertBlock()->getParent()->getParent();
1373 Constant *SIPrintFFn =
1374 M->getOrInsertFunction("siprintf", FT, Callee->getAttributes());
1375 CallInst *New = cast<CallInst>(CI->clone());
1376 New->setCalledFunction(SIPrintFFn);
1377 B.Insert(New);
1378 return New;
1379 }
1380 return 0;
1381 }
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001382};
1383
1384//===---------------------------------------===//
1385// 'fwrite' Optimizations
1386
Chris Lattner3e8b6632009-09-02 06:11:42 +00001387struct FWriteOpt : public LibCallOptimization {
Eric Christopher7a61d702008-08-08 19:39:37 +00001388 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001389 // Require a pointer, an integer, an integer, a pointer, returning integer.
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001390 FunctionType *FT = Callee->getFunctionType();
Duncan Sands1df98592010-02-16 11:11:14 +00001391 if (FT->getNumParams() != 4 || !FT->getParamType(0)->isPointerTy() ||
1392 !FT->getParamType(1)->isIntegerTy() ||
1393 !FT->getParamType(2)->isIntegerTy() ||
1394 !FT->getParamType(3)->isPointerTy() ||
1395 !FT->getReturnType()->isIntegerTy())
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001396 return 0;
Eric Christopher37c8b862009-10-07 21:14:25 +00001397
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001398 // Get the element size and count.
Gabor Greifaee5dc12010-06-24 10:42:46 +00001399 ConstantInt *SizeC = dyn_cast<ConstantInt>(CI->getArgOperand(1));
1400 ConstantInt *CountC = dyn_cast<ConstantInt>(CI->getArgOperand(2));
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001401 if (!SizeC || !CountC) return 0;
1402 uint64_t Bytes = SizeC->getZExtValue()*CountC->getZExtValue();
Eric Christopher37c8b862009-10-07 21:14:25 +00001403
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001404 // If this is writing zero records, remove the call (it's a noop).
1405 if (Bytes == 0)
Owen Andersoneed707b2009-07-24 23:12:02 +00001406 return ConstantInt::get(CI->getType(), 0);
Eric Christopher37c8b862009-10-07 21:14:25 +00001407
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001408 // If this is writing one byte, turn it into fputc.
Joerg Sonnenberger127a6692011-12-12 20:18:31 +00001409 // This optimisation is only valid, if the return value is unused.
1410 if (Bytes == 1 && CI->use_empty()) { // fwrite(S,1,1,F) -> fputc(S[0],F)
Gabor Greifaee5dc12010-06-24 10:42:46 +00001411 Value *Char = B.CreateLoad(CastToCStr(CI->getArgOperand(0), B), "char");
Nuno Lopes51004df2012-07-25 16:46:31 +00001412 Value *NewCI = EmitFPutC(Char, CI->getArgOperand(3), B, TD, TLI);
1413 return NewCI ? ConstantInt::get(CI->getType(), 1) : 0;
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001414 }
1415
1416 return 0;
1417 }
1418};
1419
1420//===---------------------------------------===//
1421// 'fputs' Optimizations
1422
Chris Lattner3e8b6632009-09-02 06:11:42 +00001423struct FPutsOpt : public LibCallOptimization {
Eric Christopher7a61d702008-08-08 19:39:37 +00001424 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
Dan Gohmanf14d9192009-08-18 00:48:13 +00001425 // These optimizations require TargetData.
1426 if (!TD) return 0;
1427
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001428 // Require two pointers. Also, we can't optimize if return value is used.
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001429 FunctionType *FT = Callee->getFunctionType();
Duncan Sands1df98592010-02-16 11:11:14 +00001430 if (FT->getNumParams() != 2 || !FT->getParamType(0)->isPointerTy() ||
1431 !FT->getParamType(1)->isPointerTy() ||
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001432 !CI->use_empty())
1433 return 0;
Eric Christopher37c8b862009-10-07 21:14:25 +00001434
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001435 // fputs(s,F) --> fwrite(s,1,strlen(s),F)
Gabor Greifaee5dc12010-06-24 10:42:46 +00001436 uint64_t Len = GetStringLength(CI->getArgOperand(0));
Chris Lattner56b4f2b2008-05-01 06:39:12 +00001437 if (!Len) return 0;
Nuno Lopes51004df2012-07-25 16:46:31 +00001438 // Known to have no uses (see above).
1439 return EmitFWrite(CI->getArgOperand(0),
1440 ConstantInt::get(TD->getIntPtrType(*Context), Len-1),
1441 CI->getArgOperand(1), B, TD, TLI);
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001442 }
1443};
1444
1445//===---------------------------------------===//
1446// 'fprintf' Optimizations
1447
Chris Lattner3e8b6632009-09-02 06:11:42 +00001448struct FPrintFOpt : public LibCallOptimization {
Richard Osborne022708f2011-03-03 14:20:22 +00001449 Value *OptimizeFixedFormatString(Function *Callee, CallInst *CI,
1450 IRBuilder<> &B) {
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001451 // All the optimizations depend on the format string.
Chris Lattner18c7f802012-02-05 02:29:43 +00001452 StringRef FormatStr;
1453 if (!getConstantStringInfo(CI->getArgOperand(1), FormatStr))
Bill Wendling0582ae92009-03-13 04:39:26 +00001454 return 0;
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001455
1456 // fprintf(F, "foo") --> fwrite("foo", 3, 1, F)
Gabor Greif8e1ebff2010-06-30 12:42:43 +00001457 if (CI->getNumArgOperands() == 2) {
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001458 for (unsigned i = 0, e = FormatStr.size(); i != e; ++i)
1459 if (FormatStr[i] == '%') // Could handle %% -> % if we cared.
Chris Lattner56b4f2b2008-05-01 06:39:12 +00001460 return 0; // We found a format specifier.
Dan Gohmanf14d9192009-08-18 00:48:13 +00001461
1462 // These optimizations require TargetData.
1463 if (!TD) return 0;
1464
Nuno Lopes51004df2012-07-25 16:46:31 +00001465 Value *NewCI = EmitFWrite(CI->getArgOperand(1),
1466 ConstantInt::get(TD->getIntPtrType(*Context),
1467 FormatStr.size()),
1468 CI->getArgOperand(0), B, TD, TLI);
1469 return NewCI ? ConstantInt::get(CI->getType(), FormatStr.size()) : 0;
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001470 }
Eric Christopher37c8b862009-10-07 21:14:25 +00001471
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001472 // The remaining optimizations require the format string to be "%s" or "%c"
1473 // and have an extra operand.
Gabor Greif8e1ebff2010-06-30 12:42:43 +00001474 if (FormatStr.size() != 2 || FormatStr[0] != '%' ||
1475 CI->getNumArgOperands() < 3)
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001476 return 0;
Eric Christopher37c8b862009-10-07 21:14:25 +00001477
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001478 // Decode the second character of the format string.
1479 if (FormatStr[1] == 'c') {
Gabor Greifaee5dc12010-06-24 10:42:46 +00001480 // fprintf(F, "%c", chr) --> fputc(chr, F)
1481 if (!CI->getArgOperand(2)->getType()->isIntegerTy()) return 0;
Nuno Lopes51004df2012-07-25 16:46:31 +00001482 Value *NewCI = EmitFPutC(CI->getArgOperand(2), CI->getArgOperand(0), B,
1483 TD, TLI);
1484 return NewCI ? ConstantInt::get(CI->getType(), 1) : 0;
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001485 }
Eric Christopher37c8b862009-10-07 21:14:25 +00001486
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001487 if (FormatStr[1] == 's') {
Gabor Greifaee5dc12010-06-24 10:42:46 +00001488 // fprintf(F, "%s", str) --> fputs(str, F)
1489 if (!CI->getArgOperand(2)->getType()->isPointerTy() || !CI->use_empty())
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001490 return 0;
Nuno Lopes51004df2012-07-25 16:46:31 +00001491 return EmitFPutS(CI->getArgOperand(2), CI->getArgOperand(0), B, TD, TLI);
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001492 }
1493 return 0;
1494 }
Richard Osborne022708f2011-03-03 14:20:22 +00001495
1496 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
1497 // Require two fixed paramters as pointers and integer result.
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001498 FunctionType *FT = Callee->getFunctionType();
Richard Osborne022708f2011-03-03 14:20:22 +00001499 if (FT->getNumParams() != 2 || !FT->getParamType(0)->isPointerTy() ||
1500 !FT->getParamType(1)->isPointerTy() ||
1501 !FT->getReturnType()->isIntegerTy())
1502 return 0;
1503
1504 if (Value *V = OptimizeFixedFormatString(Callee, CI, B)) {
1505 return V;
1506 }
1507
1508 // fprintf(stream, format, ...) -> fiprintf(stream, format, ...) if no
1509 // floating point arguments.
1510 if (TLI->has(LibFunc::fiprintf) && !CallHasFloatingPointArgument(CI)) {
1511 Module *M = B.GetInsertBlock()->getParent()->getParent();
1512 Constant *FIPrintFFn =
1513 M->getOrInsertFunction("fiprintf", FT, Callee->getAttributes());
1514 CallInst *New = cast<CallInst>(CI->clone());
1515 New->setCalledFunction(FIPrintFFn);
1516 B.Insert(New);
1517 return New;
1518 }
1519 return 0;
1520 }
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001521};
1522
Anders Carlsson303023d2010-11-30 06:19:18 +00001523//===---------------------------------------===//
1524// 'puts' Optimizations
1525
1526struct PutsOpt : public LibCallOptimization {
1527 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
1528 // Require one fixed pointer argument and an integer/void result.
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001529 FunctionType *FT = Callee->getFunctionType();
Anders Carlsson303023d2010-11-30 06:19:18 +00001530 if (FT->getNumParams() < 1 || !FT->getParamType(0)->isPointerTy() ||
1531 !(FT->getReturnType()->isIntegerTy() ||
1532 FT->getReturnType()->isVoidTy()))
1533 return 0;
1534
1535 // Check for a constant string.
Chris Lattner18c7f802012-02-05 02:29:43 +00001536 StringRef Str;
1537 if (!getConstantStringInfo(CI->getArgOperand(0), Str))
Anders Carlsson303023d2010-11-30 06:19:18 +00001538 return 0;
1539
Daniel Dunbard02be242011-02-12 18:19:57 +00001540 if (Str.empty() && CI->use_empty()) {
Anders Carlsson303023d2010-11-30 06:19:18 +00001541 // puts("") -> putchar('\n')
Nuno Lopes51004df2012-07-25 16:46:31 +00001542 Value *Res = EmitPutChar(B.getInt32('\n'), B, TD, TLI);
Nuno Lopescd31fc72012-07-26 17:10:46 +00001543 if (CI->use_empty() || !Res) return Res;
Anders Carlsson303023d2010-11-30 06:19:18 +00001544 return B.CreateIntCast(Res, CI->getType(), true);
1545 }
1546
1547 return 0;
1548 }
1549};
1550
Bill Wendlingac178222008-05-05 21:37:59 +00001551} // end anonymous namespace.
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001552
1553//===----------------------------------------------------------------------===//
1554// SimplifyLibCalls Pass Implementation
1555//===----------------------------------------------------------------------===//
1556
1557namespace {
1558 /// This pass optimizes well known library functions from libc and libm.
1559 ///
Chris Lattner3e8b6632009-09-02 06:11:42 +00001560 class SimplifyLibCalls : public FunctionPass {
Chris Lattnerafbf4832011-02-24 07:16:14 +00001561 TargetLibraryInfo *TLI;
Nadav Rotema94d6e82012-07-24 10:51:42 +00001562
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001563 StringMap<LibCallOptimization*> Optimizations;
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001564 // String and Memory LibCall Optimizations
Benjamin Kramer06f25cf2010-09-29 21:50:51 +00001565 StrCatOpt StrCat; StrNCatOpt StrNCat; StrChrOpt StrChr; StrRChrOpt StrRChr;
David Majnemerac782662012-05-15 11:46:21 +00001566 StrCmpOpt StrCmp; StrNCmpOpt StrNCmp;
1567 StrCpyOpt StrCpy; StrCpyOpt StrCpyChk;
1568 StpCpyOpt StpCpy; StpCpyOpt StpCpyChk;
1569 StrNCpyOpt StrNCpy;
1570 StrLenOpt StrLen; StrPBrkOpt StrPBrk;
Benjamin Kramer9510a252010-09-30 00:58:35 +00001571 StrToOpt StrTo; StrSpnOpt StrSpn; StrCSpnOpt StrCSpn; StrStrOpt StrStr;
Chris Lattner24604112009-12-16 09:32:05 +00001572 MemCmpOpt MemCmp; MemCpyOpt MemCpy; MemMoveOpt MemMove; MemSetOpt MemSet;
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001573 // Math Library Optimizations
Chad Rosierec7e92a2012-08-22 17:22:33 +00001574 CosOpt Cos; PowOpt Pow; Exp2Opt Exp2;
1575 UnaryDoubleFPOpt UnaryDoubleFP, UnsafeUnaryDoubleFP;
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001576 // Integer Optimizations
Chris Lattner313f0e62008-06-09 08:26:51 +00001577 FFSOpt FFS; AbsOpt Abs; IsDigitOpt IsDigit; IsAsciiOpt IsAscii;
1578 ToAsciiOpt ToAscii;
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001579 // Formatting and IO Optimizations
1580 SPrintFOpt SPrintF; PrintFOpt PrintF;
1581 FWriteOpt FWrite; FPutsOpt FPuts; FPrintFOpt FPrintF;
Anders Carlsson303023d2010-11-30 06:19:18 +00001582 PutsOpt Puts;
Nadav Rotema94d6e82012-07-24 10:51:42 +00001583
Nick Lewycky6cd0c042009-01-05 00:07:50 +00001584 bool Modified; // This is only used by doInitialization.
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001585 public:
1586 static char ID; // Pass identification
David Majnemerac782662012-05-15 11:46:21 +00001587 SimplifyLibCalls() : FunctionPass(ID), StrCpy(false), StrCpyChk(true),
Chad Rosierec7e92a2012-08-22 17:22:33 +00001588 StpCpy(false), StpCpyChk(true),
1589 UnaryDoubleFP(false), UnsafeUnaryDoubleFP(true) {
Owen Anderson081c34b2010-10-19 17:21:58 +00001590 initializeSimplifyLibCallsPass(*PassRegistry::getPassRegistry());
1591 }
Eli Friedman9d434db2011-11-17 01:27:36 +00001592 void AddOpt(LibFunc::Func F, LibCallOptimization* Opt);
Chad Rosierd7e25252012-08-22 16:52:57 +00001593 void AddOpt(LibFunc::Func F1, LibFunc::Func F2, LibCallOptimization* Opt);
1594
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001595 void InitOptimizations();
1596 bool runOnFunction(Function &F);
1597
Nick Lewycky0f8df9a2009-01-04 20:27:34 +00001598 void setDoesNotAccessMemory(Function &F);
1599 void setOnlyReadsMemory(Function &F);
1600 void setDoesNotThrow(Function &F);
1601 void setDoesNotCapture(Function &F, unsigned n);
1602 void setDoesNotAlias(Function &F, unsigned n);
Nick Lewycky6cd0c042009-01-05 00:07:50 +00001603 bool doInitialization(Module &M);
Nick Lewycky0f8df9a2009-01-04 20:27:34 +00001604
Chris Lattnere265ad82011-02-24 07:12:12 +00001605 void inferPrototypeAttributes(Function &F);
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001606 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
Chris Lattnerafbf4832011-02-24 07:16:14 +00001607 AU.addRequired<TargetLibraryInfo>();
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001608 }
1609 };
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001610} // end anonymous namespace.
1611
Chris Lattnerafbf4832011-02-24 07:16:14 +00001612char SimplifyLibCalls::ID = 0;
1613
1614INITIALIZE_PASS_BEGIN(SimplifyLibCalls, "simplify-libcalls",
1615 "Simplify well-known library calls", false, false)
1616INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfo)
1617INITIALIZE_PASS_END(SimplifyLibCalls, "simplify-libcalls",
1618 "Simplify well-known library calls", false, false)
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001619
1620// Public interface to the Simplify LibCalls pass.
1621FunctionPass *llvm::createSimplifyLibCallsPass() {
Eric Christopher37c8b862009-10-07 21:14:25 +00001622 return new SimplifyLibCalls();
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001623}
1624
Eli Friedman9d434db2011-11-17 01:27:36 +00001625void SimplifyLibCalls::AddOpt(LibFunc::Func F, LibCallOptimization* Opt) {
1626 if (TLI->has(F))
1627 Optimizations[TLI->getName(F)] = Opt;
1628}
1629
Chad Rosierd7e25252012-08-22 16:52:57 +00001630void SimplifyLibCalls::AddOpt(LibFunc::Func F1, LibFunc::Func F2,
1631 LibCallOptimization* Opt) {
1632 if (TLI->has(F1) && TLI->has(F2))
1633 Optimizations[TLI->getName(F1)] = Opt;
1634}
1635
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001636/// Optimizations - Populate the Optimizations map with all the optimizations
1637/// we know.
1638void SimplifyLibCalls::InitOptimizations() {
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001639 // String and Memory LibCall Optimizations
1640 Optimizations["strcat"] = &StrCat;
Chris Lattnerf5b6bc72009-04-12 05:06:39 +00001641 Optimizations["strncat"] = &StrNCat;
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001642 Optimizations["strchr"] = &StrChr;
Benjamin Kramer06f25cf2010-09-29 21:50:51 +00001643 Optimizations["strrchr"] = &StrRChr;
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001644 Optimizations["strcmp"] = &StrCmp;
1645 Optimizations["strncmp"] = &StrNCmp;
1646 Optimizations["strcpy"] = &StrCpy;
Chris Lattnerf5b6bc72009-04-12 05:06:39 +00001647 Optimizations["strncpy"] = &StrNCpy;
David Majnemerac782662012-05-15 11:46:21 +00001648 Optimizations["stpcpy"] = &StpCpy;
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001649 Optimizations["strlen"] = &StrLen;
Benjamin Kramer05f585e2010-09-29 23:52:12 +00001650 Optimizations["strpbrk"] = &StrPBrk;
Nick Lewycky4c498412009-02-13 15:31:46 +00001651 Optimizations["strtol"] = &StrTo;
1652 Optimizations["strtod"] = &StrTo;
1653 Optimizations["strtof"] = &StrTo;
1654 Optimizations["strtoul"] = &StrTo;
1655 Optimizations["strtoll"] = &StrTo;
1656 Optimizations["strtold"] = &StrTo;
1657 Optimizations["strtoull"] = &StrTo;
Benjamin Kramer9510a252010-09-30 00:58:35 +00001658 Optimizations["strspn"] = &StrSpn;
1659 Optimizations["strcspn"] = &StrCSpn;
Chris Lattner24604112009-12-16 09:32:05 +00001660 Optimizations["strstr"] = &StrStr;
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001661 Optimizations["memcmp"] = &MemCmp;
Eli Friedman9d434db2011-11-17 01:27:36 +00001662 AddOpt(LibFunc::memcpy, &MemCpy);
Eli Friedmand83ae7d2008-11-30 08:32:11 +00001663 Optimizations["memmove"] = &MemMove;
Eli Friedman9d434db2011-11-17 01:27:36 +00001664 AddOpt(LibFunc::memset, &MemSet);
Eric Christopher37c8b862009-10-07 21:14:25 +00001665
Evan Cheng0289b412010-03-23 15:48:04 +00001666 // _chk variants of String and Memory LibCall Optimizations.
Evan Cheng0289b412010-03-23 15:48:04 +00001667 Optimizations["__strcpy_chk"] = &StrCpyChk;
David Majnemerac782662012-05-15 11:46:21 +00001668 Optimizations["__stpcpy_chk"] = &StpCpyChk;
Evan Cheng0289b412010-03-23 15:48:04 +00001669
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001670 // Math Library Optimizations
Nick Lewyckya6b21ea2011-12-27 18:25:50 +00001671 Optimizations["cosf"] = &Cos;
1672 Optimizations["cos"] = &Cos;
1673 Optimizations["cosl"] = &Cos;
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001674 Optimizations["powf"] = &Pow;
1675 Optimizations["pow"] = &Pow;
1676 Optimizations["powl"] = &Pow;
Dale Johannesen53bfbbc2008-09-04 18:30:46 +00001677 Optimizations["llvm.pow.f32"] = &Pow;
1678 Optimizations["llvm.pow.f64"] = &Pow;
1679 Optimizations["llvm.pow.f80"] = &Pow;
1680 Optimizations["llvm.pow.f128"] = &Pow;
1681 Optimizations["llvm.pow.ppcf128"] = &Pow;
Chris Lattnere818f772008-05-02 18:43:35 +00001682 Optimizations["exp2l"] = &Exp2;
1683 Optimizations["exp2"] = &Exp2;
1684 Optimizations["exp2f"] = &Exp2;
Dale Johannesen53bfbbc2008-09-04 18:30:46 +00001685 Optimizations["llvm.exp2.ppcf128"] = &Exp2;
1686 Optimizations["llvm.exp2.f128"] = &Exp2;
1687 Optimizations["llvm.exp2.f80"] = &Exp2;
1688 Optimizations["llvm.exp2.f64"] = &Exp2;
1689 Optimizations["llvm.exp2.f32"] = &Exp2;
Eric Christopher37c8b862009-10-07 21:14:25 +00001690
Chad Rosierd7e25252012-08-22 16:52:57 +00001691 AddOpt(LibFunc::ceil, LibFunc::ceilf, &UnaryDoubleFP);
1692 AddOpt(LibFunc::fabs, LibFunc::fabsf, &UnaryDoubleFP);
Chad Rosierec7e92a2012-08-22 17:22:33 +00001693 AddOpt(LibFunc::floor, LibFunc::floorf, &UnsafeUnaryDoubleFP);
1694 AddOpt(LibFunc::rint, LibFunc::rintf, &UnsafeUnaryDoubleFP);
1695 AddOpt(LibFunc::round, LibFunc::roundf, &UnsafeUnaryDoubleFP);
1696 AddOpt(LibFunc::nearbyint, LibFunc::nearbyintf, &UnsafeUnaryDoubleFP);
1697 AddOpt(LibFunc::trunc, LibFunc::truncf, &UnsafeUnaryDoubleFP);
1698
1699 if(UnsafeFPShrink) {
1700 AddOpt(LibFunc::acos, LibFunc::acosf, &UnsafeUnaryDoubleFP);
1701 AddOpt(LibFunc::acosh, LibFunc::acoshf, &UnsafeUnaryDoubleFP);
1702 AddOpt(LibFunc::asin, LibFunc::asinf, &UnsafeUnaryDoubleFP);
1703 AddOpt(LibFunc::asinh, LibFunc::asinhf, &UnsafeUnaryDoubleFP);
1704 AddOpt(LibFunc::atan, LibFunc::atanf, &UnsafeUnaryDoubleFP);
1705 AddOpt(LibFunc::atanh, LibFunc::atanhf, &UnsafeUnaryDoubleFP);
1706 AddOpt(LibFunc::cbrt, LibFunc::cbrtf, &UnsafeUnaryDoubleFP);
1707 AddOpt(LibFunc::cosh, LibFunc::coshf, &UnsafeUnaryDoubleFP);
1708 AddOpt(LibFunc::exp, LibFunc::expf, &UnsafeUnaryDoubleFP);
1709 AddOpt(LibFunc::exp10, LibFunc::exp10f, &UnsafeUnaryDoubleFP);
1710 AddOpt(LibFunc::expm1, LibFunc::expm1f, &UnsafeUnaryDoubleFP);
1711 AddOpt(LibFunc::log, LibFunc::logf, &UnsafeUnaryDoubleFP);
1712 AddOpt(LibFunc::log10, LibFunc::log10f, &UnsafeUnaryDoubleFP);
1713 AddOpt(LibFunc::log1p, LibFunc::log1pf, &UnsafeUnaryDoubleFP);
1714 AddOpt(LibFunc::log2, LibFunc::log2f, &UnsafeUnaryDoubleFP);
1715 AddOpt(LibFunc::logb, LibFunc::logbf, &UnsafeUnaryDoubleFP);
1716 AddOpt(LibFunc::sin, LibFunc::sinf, &UnsafeUnaryDoubleFP);
1717 AddOpt(LibFunc::sinh, LibFunc::sinhf, &UnsafeUnaryDoubleFP);
1718 AddOpt(LibFunc::sqrt, LibFunc::sqrtf, &UnsafeUnaryDoubleFP);
1719 AddOpt(LibFunc::tan, LibFunc::tanf, &UnsafeUnaryDoubleFP);
1720 AddOpt(LibFunc::tanh, LibFunc::tanhf, &UnsafeUnaryDoubleFP);
1721 }
Eric Christopher37c8b862009-10-07 21:14:25 +00001722
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001723 // Integer Optimizations
1724 Optimizations["ffs"] = &FFS;
1725 Optimizations["ffsl"] = &FFS;
1726 Optimizations["ffsll"] = &FFS;
Chris Lattner313f0e62008-06-09 08:26:51 +00001727 Optimizations["abs"] = &Abs;
1728 Optimizations["labs"] = &Abs;
1729 Optimizations["llabs"] = &Abs;
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001730 Optimizations["isdigit"] = &IsDigit;
1731 Optimizations["isascii"] = &IsAscii;
1732 Optimizations["toascii"] = &ToAscii;
Eric Christopher37c8b862009-10-07 21:14:25 +00001733
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001734 // Formatting and IO Optimizations
1735 Optimizations["sprintf"] = &SPrintF;
1736 Optimizations["printf"] = &PrintF;
Eli Friedman9d434db2011-11-17 01:27:36 +00001737 AddOpt(LibFunc::fwrite, &FWrite);
1738 AddOpt(LibFunc::fputs, &FPuts);
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001739 Optimizations["fprintf"] = &FPrintF;
Anders Carlsson303023d2010-11-30 06:19:18 +00001740 Optimizations["puts"] = &Puts;
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001741}
1742
1743
1744/// runOnFunction - Top level algorithm.
1745///
1746bool SimplifyLibCalls::runOnFunction(Function &F) {
Chris Lattnerafbf4832011-02-24 07:16:14 +00001747 TLI = &getAnalysis<TargetLibraryInfo>();
1748
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001749 if (Optimizations.empty())
1750 InitOptimizations();
Eric Christopher37c8b862009-10-07 21:14:25 +00001751
Dan Gohmanf14d9192009-08-18 00:48:13 +00001752 const TargetData *TD = getAnalysisIfAvailable<TargetData>();
Eric Christopher37c8b862009-10-07 21:14:25 +00001753
Owen Andersone922c022009-07-22 00:24:57 +00001754 IRBuilder<> Builder(F.getContext());
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001755
1756 bool Changed = false;
1757 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB) {
1758 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ) {
1759 // Ignore non-calls.
1760 CallInst *CI = dyn_cast<CallInst>(I++);
1761 if (!CI) continue;
Eric Christopher37c8b862009-10-07 21:14:25 +00001762
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001763 // Ignore indirect calls and calls to non-external functions.
1764 Function *Callee = CI->getCalledFunction();
1765 if (Callee == 0 || !Callee->isDeclaration() ||
1766 !(Callee->hasExternalLinkage() || Callee->hasDLLImportLinkage()))
1767 continue;
Eric Christopher37c8b862009-10-07 21:14:25 +00001768
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001769 // Ignore unknown calls.
Daniel Dunbarf0443c12009-07-26 08:34:35 +00001770 LibCallOptimization *LCO = Optimizations.lookup(Callee->getName());
1771 if (!LCO) continue;
Eric Christopher37c8b862009-10-07 21:14:25 +00001772
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001773 // Set the builder to the instruction after the call.
1774 Builder.SetInsertPoint(BB, I);
Eric Christopher37c8b862009-10-07 21:14:25 +00001775
Devang Patela2ab3992011-03-09 21:27:52 +00001776 // Use debug location of CI for all new instructions.
1777 Builder.SetCurrentDebugLocation(CI->getDebugLoc());
1778
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001779 // Try to optimize this call.
Richard Osborne36498242011-03-03 13:17:51 +00001780 Value *Result = LCO->OptimizeCall(CI, TD, TLI, Builder);
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001781 if (Result == 0) continue;
1782
David Greene6a6b90e2010-01-05 01:27:21 +00001783 DEBUG(dbgs() << "SimplifyLibCalls simplified: " << *CI;
1784 dbgs() << " into: " << *Result << "\n");
Eric Christopher37c8b862009-10-07 21:14:25 +00001785
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001786 // Something changed!
1787 Changed = true;
1788 ++NumSimplified;
Eric Christopher37c8b862009-10-07 21:14:25 +00001789
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001790 // Inspect the instruction after the call (which was potentially just
1791 // added) next.
1792 I = CI; ++I;
Eric Christopher37c8b862009-10-07 21:14:25 +00001793
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001794 if (CI != Result && !CI->use_empty()) {
1795 CI->replaceAllUsesWith(Result);
1796 if (!Result->hasName())
1797 Result->takeName(CI);
1798 }
1799 CI->eraseFromParent();
1800 }
1801 }
1802 return Changed;
1803}
1804
Nick Lewycky6cd0c042009-01-05 00:07:50 +00001805// Utility methods for doInitialization.
Nick Lewycky0f8df9a2009-01-04 20:27:34 +00001806
1807void SimplifyLibCalls::setDoesNotAccessMemory(Function &F) {
1808 if (!F.doesNotAccessMemory()) {
1809 F.setDoesNotAccessMemory();
1810 ++NumAnnotated;
1811 Modified = true;
1812 }
1813}
1814void SimplifyLibCalls::setOnlyReadsMemory(Function &F) {
1815 if (!F.onlyReadsMemory()) {
1816 F.setOnlyReadsMemory();
1817 ++NumAnnotated;
1818 Modified = true;
1819 }
1820}
1821void SimplifyLibCalls::setDoesNotThrow(Function &F) {
1822 if (!F.doesNotThrow()) {
1823 F.setDoesNotThrow();
1824 ++NumAnnotated;
1825 Modified = true;
1826 }
1827}
1828void SimplifyLibCalls::setDoesNotCapture(Function &F, unsigned n) {
1829 if (!F.doesNotCapture(n)) {
1830 F.setDoesNotCapture(n);
1831 ++NumAnnotated;
1832 Modified = true;
1833 }
1834}
1835void SimplifyLibCalls::setDoesNotAlias(Function &F, unsigned n) {
1836 if (!F.doesNotAlias(n)) {
1837 F.setDoesNotAlias(n);
1838 ++NumAnnotated;
1839 Modified = true;
1840 }
1841}
1842
Chris Lattnere265ad82011-02-24 07:12:12 +00001843
1844void SimplifyLibCalls::inferPrototypeAttributes(Function &F) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001845 FunctionType *FTy = F.getFunctionType();
Nadav Rotema94d6e82012-07-24 10:51:42 +00001846
Chris Lattnere265ad82011-02-24 07:12:12 +00001847 StringRef Name = F.getName();
1848 switch (Name[0]) {
1849 case 's':
1850 if (Name == "strlen") {
1851 if (FTy->getNumParams() != 1 || !FTy->getParamType(0)->isPointerTy())
1852 return;
1853 setOnlyReadsMemory(F);
1854 setDoesNotThrow(F);
1855 setDoesNotCapture(F, 1);
1856 } else if (Name == "strchr" ||
1857 Name == "strrchr") {
1858 if (FTy->getNumParams() != 2 ||
1859 !FTy->getParamType(0)->isPointerTy() ||
1860 !FTy->getParamType(1)->isIntegerTy())
1861 return;
1862 setOnlyReadsMemory(F);
1863 setDoesNotThrow(F);
1864 } else if (Name == "strcpy" ||
1865 Name == "stpcpy" ||
1866 Name == "strcat" ||
1867 Name == "strtol" ||
1868 Name == "strtod" ||
1869 Name == "strtof" ||
1870 Name == "strtoul" ||
1871 Name == "strtoll" ||
1872 Name == "strtold" ||
1873 Name == "strncat" ||
1874 Name == "strncpy" ||
David Majnemerac782662012-05-15 11:46:21 +00001875 Name == "stpncpy" ||
Chris Lattnere265ad82011-02-24 07:12:12 +00001876 Name == "strtoull") {
1877 if (FTy->getNumParams() < 2 ||
1878 !FTy->getParamType(1)->isPointerTy())
1879 return;
1880 setDoesNotThrow(F);
1881 setDoesNotCapture(F, 2);
1882 } else if (Name == "strxfrm") {
1883 if (FTy->getNumParams() != 3 ||
1884 !FTy->getParamType(0)->isPointerTy() ||
1885 !FTy->getParamType(1)->isPointerTy())
1886 return;
1887 setDoesNotThrow(F);
1888 setDoesNotCapture(F, 1);
1889 setDoesNotCapture(F, 2);
1890 } else if (Name == "strcmp" ||
1891 Name == "strspn" ||
1892 Name == "strncmp" ||
1893 Name == "strcspn" ||
1894 Name == "strcoll" ||
1895 Name == "strcasecmp" ||
1896 Name == "strncasecmp") {
1897 if (FTy->getNumParams() < 2 ||
1898 !FTy->getParamType(0)->isPointerTy() ||
1899 !FTy->getParamType(1)->isPointerTy())
1900 return;
1901 setOnlyReadsMemory(F);
1902 setDoesNotThrow(F);
1903 setDoesNotCapture(F, 1);
1904 setDoesNotCapture(F, 2);
1905 } else if (Name == "strstr" ||
1906 Name == "strpbrk") {
1907 if (FTy->getNumParams() != 2 || !FTy->getParamType(1)->isPointerTy())
1908 return;
1909 setOnlyReadsMemory(F);
1910 setDoesNotThrow(F);
1911 setDoesNotCapture(F, 2);
1912 } else if (Name == "strtok" ||
1913 Name == "strtok_r") {
1914 if (FTy->getNumParams() < 2 || !FTy->getParamType(1)->isPointerTy())
1915 return;
1916 setDoesNotThrow(F);
1917 setDoesNotCapture(F, 2);
1918 } else if (Name == "scanf" ||
1919 Name == "setbuf" ||
1920 Name == "setvbuf") {
1921 if (FTy->getNumParams() < 1 || !FTy->getParamType(0)->isPointerTy())
1922 return;
1923 setDoesNotThrow(F);
1924 setDoesNotCapture(F, 1);
1925 } else if (Name == "strdup" ||
1926 Name == "strndup") {
1927 if (FTy->getNumParams() < 1 || !FTy->getReturnType()->isPointerTy() ||
1928 !FTy->getParamType(0)->isPointerTy())
1929 return;
1930 setDoesNotThrow(F);
1931 setDoesNotAlias(F, 0);
1932 setDoesNotCapture(F, 1);
1933 } else if (Name == "stat" ||
1934 Name == "sscanf" ||
1935 Name == "sprintf" ||
1936 Name == "statvfs") {
1937 if (FTy->getNumParams() < 2 ||
1938 !FTy->getParamType(0)->isPointerTy() ||
1939 !FTy->getParamType(1)->isPointerTy())
1940 return;
1941 setDoesNotThrow(F);
1942 setDoesNotCapture(F, 1);
1943 setDoesNotCapture(F, 2);
1944 } else if (Name == "snprintf") {
1945 if (FTy->getNumParams() != 3 ||
1946 !FTy->getParamType(0)->isPointerTy() ||
1947 !FTy->getParamType(2)->isPointerTy())
1948 return;
1949 setDoesNotThrow(F);
1950 setDoesNotCapture(F, 1);
1951 setDoesNotCapture(F, 3);
1952 } else if (Name == "setitimer") {
1953 if (FTy->getNumParams() != 3 ||
1954 !FTy->getParamType(1)->isPointerTy() ||
1955 !FTy->getParamType(2)->isPointerTy())
1956 return;
1957 setDoesNotThrow(F);
1958 setDoesNotCapture(F, 2);
1959 setDoesNotCapture(F, 3);
1960 } else if (Name == "system") {
1961 if (FTy->getNumParams() != 1 ||
1962 !FTy->getParamType(0)->isPointerTy())
1963 return;
1964 // May throw; "system" is a valid pthread cancellation point.
1965 setDoesNotCapture(F, 1);
1966 }
1967 break;
1968 case 'm':
1969 if (Name == "malloc") {
1970 if (FTy->getNumParams() != 1 ||
1971 !FTy->getReturnType()->isPointerTy())
1972 return;
1973 setDoesNotThrow(F);
1974 setDoesNotAlias(F, 0);
1975 } else if (Name == "memcmp") {
1976 if (FTy->getNumParams() != 3 ||
1977 !FTy->getParamType(0)->isPointerTy() ||
1978 !FTy->getParamType(1)->isPointerTy())
1979 return;
1980 setOnlyReadsMemory(F);
1981 setDoesNotThrow(F);
1982 setDoesNotCapture(F, 1);
1983 setDoesNotCapture(F, 2);
1984 } else if (Name == "memchr" ||
1985 Name == "memrchr") {
1986 if (FTy->getNumParams() != 3)
1987 return;
1988 setOnlyReadsMemory(F);
1989 setDoesNotThrow(F);
1990 } else if (Name == "modf" ||
1991 Name == "modff" ||
1992 Name == "modfl" ||
1993 Name == "memcpy" ||
1994 Name == "memccpy" ||
1995 Name == "memmove") {
1996 if (FTy->getNumParams() < 2 ||
1997 !FTy->getParamType(1)->isPointerTy())
1998 return;
1999 setDoesNotThrow(F);
2000 setDoesNotCapture(F, 2);
2001 } else if (Name == "memalign") {
2002 if (!FTy->getReturnType()->isPointerTy())
2003 return;
2004 setDoesNotAlias(F, 0);
2005 } else if (Name == "mkdir" ||
2006 Name == "mktime") {
2007 if (FTy->getNumParams() == 0 ||
2008 !FTy->getParamType(0)->isPointerTy())
2009 return;
2010 setDoesNotThrow(F);
2011 setDoesNotCapture(F, 1);
2012 }
2013 break;
2014 case 'r':
2015 if (Name == "realloc") {
2016 if (FTy->getNumParams() != 2 ||
2017 !FTy->getParamType(0)->isPointerTy() ||
2018 !FTy->getReturnType()->isPointerTy())
2019 return;
2020 setDoesNotThrow(F);
Nuno Lopesfd99cab2012-06-25 23:26:10 +00002021 setDoesNotAlias(F, 0);
Chris Lattnere265ad82011-02-24 07:12:12 +00002022 setDoesNotCapture(F, 1);
2023 } else if (Name == "read") {
2024 if (FTy->getNumParams() != 3 ||
2025 !FTy->getParamType(1)->isPointerTy())
2026 return;
2027 // May throw; "read" is a valid pthread cancellation point.
2028 setDoesNotCapture(F, 2);
2029 } else if (Name == "rmdir" ||
2030 Name == "rewind" ||
2031 Name == "remove" ||
2032 Name == "realpath") {
2033 if (FTy->getNumParams() < 1 ||
2034 !FTy->getParamType(0)->isPointerTy())
2035 return;
2036 setDoesNotThrow(F);
2037 setDoesNotCapture(F, 1);
2038 } else if (Name == "rename" ||
2039 Name == "readlink") {
2040 if (FTy->getNumParams() < 2 ||
2041 !FTy->getParamType(0)->isPointerTy() ||
2042 !FTy->getParamType(1)->isPointerTy())
2043 return;
2044 setDoesNotThrow(F);
2045 setDoesNotCapture(F, 1);
2046 setDoesNotCapture(F, 2);
2047 }
2048 break;
2049 case 'w':
2050 if (Name == "write") {
2051 if (FTy->getNumParams() != 3 || !FTy->getParamType(1)->isPointerTy())
2052 return;
2053 // May throw; "write" is a valid pthread cancellation point.
2054 setDoesNotCapture(F, 2);
2055 }
2056 break;
2057 case 'b':
2058 if (Name == "bcopy") {
2059 if (FTy->getNumParams() != 3 ||
2060 !FTy->getParamType(0)->isPointerTy() ||
2061 !FTy->getParamType(1)->isPointerTy())
2062 return;
2063 setDoesNotThrow(F);
2064 setDoesNotCapture(F, 1);
2065 setDoesNotCapture(F, 2);
2066 } else if (Name == "bcmp") {
2067 if (FTy->getNumParams() != 3 ||
2068 !FTy->getParamType(0)->isPointerTy() ||
2069 !FTy->getParamType(1)->isPointerTy())
2070 return;
2071 setDoesNotThrow(F);
2072 setOnlyReadsMemory(F);
2073 setDoesNotCapture(F, 1);
2074 setDoesNotCapture(F, 2);
2075 } else if (Name == "bzero") {
2076 if (FTy->getNumParams() != 2 || !FTy->getParamType(0)->isPointerTy())
2077 return;
2078 setDoesNotThrow(F);
2079 setDoesNotCapture(F, 1);
2080 }
2081 break;
2082 case 'c':
2083 if (Name == "calloc") {
2084 if (FTy->getNumParams() != 2 ||
2085 !FTy->getReturnType()->isPointerTy())
2086 return;
2087 setDoesNotThrow(F);
2088 setDoesNotAlias(F, 0);
2089 } else if (Name == "chmod" ||
2090 Name == "chown" ||
2091 Name == "ctermid" ||
2092 Name == "clearerr" ||
2093 Name == "closedir") {
2094 if (FTy->getNumParams() == 0 || !FTy->getParamType(0)->isPointerTy())
2095 return;
2096 setDoesNotThrow(F);
2097 setDoesNotCapture(F, 1);
2098 }
2099 break;
2100 case 'a':
2101 if (Name == "atoi" ||
2102 Name == "atol" ||
2103 Name == "atof" ||
2104 Name == "atoll") {
2105 if (FTy->getNumParams() != 1 || !FTy->getParamType(0)->isPointerTy())
2106 return;
2107 setDoesNotThrow(F);
2108 setOnlyReadsMemory(F);
2109 setDoesNotCapture(F, 1);
2110 } else if (Name == "access") {
2111 if (FTy->getNumParams() != 2 || !FTy->getParamType(0)->isPointerTy())
2112 return;
2113 setDoesNotThrow(F);
2114 setDoesNotCapture(F, 1);
2115 }
2116 break;
2117 case 'f':
2118 if (Name == "fopen") {
2119 if (FTy->getNumParams() != 2 ||
2120 !FTy->getReturnType()->isPointerTy() ||
2121 !FTy->getParamType(0)->isPointerTy() ||
2122 !FTy->getParamType(1)->isPointerTy())
2123 return;
2124 setDoesNotThrow(F);
2125 setDoesNotAlias(F, 0);
2126 setDoesNotCapture(F, 1);
2127 setDoesNotCapture(F, 2);
2128 } else if (Name == "fdopen") {
2129 if (FTy->getNumParams() != 2 ||
2130 !FTy->getReturnType()->isPointerTy() ||
2131 !FTy->getParamType(1)->isPointerTy())
2132 return;
2133 setDoesNotThrow(F);
2134 setDoesNotAlias(F, 0);
2135 setDoesNotCapture(F, 2);
2136 } else if (Name == "feof" ||
2137 Name == "free" ||
2138 Name == "fseek" ||
2139 Name == "ftell" ||
2140 Name == "fgetc" ||
2141 Name == "fseeko" ||
2142 Name == "ftello" ||
2143 Name == "fileno" ||
2144 Name == "fflush" ||
2145 Name == "fclose" ||
2146 Name == "fsetpos" ||
2147 Name == "flockfile" ||
2148 Name == "funlockfile" ||
2149 Name == "ftrylockfile") {
2150 if (FTy->getNumParams() == 0 || !FTy->getParamType(0)->isPointerTy())
2151 return;
2152 setDoesNotThrow(F);
2153 setDoesNotCapture(F, 1);
2154 } else if (Name == "ferror") {
2155 if (FTy->getNumParams() != 1 || !FTy->getParamType(0)->isPointerTy())
2156 return;
2157 setDoesNotThrow(F);
2158 setDoesNotCapture(F, 1);
2159 setOnlyReadsMemory(F);
2160 } else if (Name == "fputc" ||
2161 Name == "fstat" ||
2162 Name == "frexp" ||
2163 Name == "frexpf" ||
2164 Name == "frexpl" ||
2165 Name == "fstatvfs") {
2166 if (FTy->getNumParams() != 2 || !FTy->getParamType(1)->isPointerTy())
2167 return;
2168 setDoesNotThrow(F);
2169 setDoesNotCapture(F, 2);
2170 } else if (Name == "fgets") {
2171 if (FTy->getNumParams() != 3 ||
2172 !FTy->getParamType(0)->isPointerTy() ||
2173 !FTy->getParamType(2)->isPointerTy())
2174 return;
2175 setDoesNotThrow(F);
2176 setDoesNotCapture(F, 3);
2177 } else if (Name == "fread" ||
2178 Name == "fwrite") {
2179 if (FTy->getNumParams() != 4 ||
2180 !FTy->getParamType(0)->isPointerTy() ||
2181 !FTy->getParamType(3)->isPointerTy())
2182 return;
2183 setDoesNotThrow(F);
2184 setDoesNotCapture(F, 1);
2185 setDoesNotCapture(F, 4);
2186 } else if (Name == "fputs" ||
2187 Name == "fscanf" ||
2188 Name == "fprintf" ||
2189 Name == "fgetpos") {
2190 if (FTy->getNumParams() < 2 ||
2191 !FTy->getParamType(0)->isPointerTy() ||
2192 !FTy->getParamType(1)->isPointerTy())
2193 return;
2194 setDoesNotThrow(F);
2195 setDoesNotCapture(F, 1);
2196 setDoesNotCapture(F, 2);
2197 }
2198 break;
2199 case 'g':
2200 if (Name == "getc" ||
2201 Name == "getlogin_r" ||
2202 Name == "getc_unlocked") {
2203 if (FTy->getNumParams() == 0 || !FTy->getParamType(0)->isPointerTy())
2204 return;
2205 setDoesNotThrow(F);
2206 setDoesNotCapture(F, 1);
2207 } else if (Name == "getenv") {
2208 if (FTy->getNumParams() != 1 || !FTy->getParamType(0)->isPointerTy())
2209 return;
2210 setDoesNotThrow(F);
2211 setOnlyReadsMemory(F);
2212 setDoesNotCapture(F, 1);
2213 } else if (Name == "gets" ||
2214 Name == "getchar") {
2215 setDoesNotThrow(F);
2216 } else if (Name == "getitimer") {
2217 if (FTy->getNumParams() != 2 || !FTy->getParamType(1)->isPointerTy())
2218 return;
2219 setDoesNotThrow(F);
2220 setDoesNotCapture(F, 2);
2221 } else if (Name == "getpwnam") {
2222 if (FTy->getNumParams() != 1 || !FTy->getParamType(0)->isPointerTy())
2223 return;
2224 setDoesNotThrow(F);
2225 setDoesNotCapture(F, 1);
2226 }
2227 break;
2228 case 'u':
2229 if (Name == "ungetc") {
2230 if (FTy->getNumParams() != 2 || !FTy->getParamType(1)->isPointerTy())
2231 return;
2232 setDoesNotThrow(F);
2233 setDoesNotCapture(F, 2);
2234 } else if (Name == "uname" ||
2235 Name == "unlink" ||
2236 Name == "unsetenv") {
2237 if (FTy->getNumParams() != 1 || !FTy->getParamType(0)->isPointerTy())
2238 return;
2239 setDoesNotThrow(F);
2240 setDoesNotCapture(F, 1);
2241 } else if (Name == "utime" ||
2242 Name == "utimes") {
2243 if (FTy->getNumParams() != 2 ||
2244 !FTy->getParamType(0)->isPointerTy() ||
2245 !FTy->getParamType(1)->isPointerTy())
2246 return;
2247 setDoesNotThrow(F);
2248 setDoesNotCapture(F, 1);
2249 setDoesNotCapture(F, 2);
2250 }
2251 break;
2252 case 'p':
2253 if (Name == "putc") {
2254 if (FTy->getNumParams() != 2 || !FTy->getParamType(1)->isPointerTy())
2255 return;
2256 setDoesNotThrow(F);
2257 setDoesNotCapture(F, 2);
2258 } else if (Name == "puts" ||
2259 Name == "printf" ||
2260 Name == "perror") {
2261 if (FTy->getNumParams() != 1 || !FTy->getParamType(0)->isPointerTy())
2262 return;
2263 setDoesNotThrow(F);
2264 setDoesNotCapture(F, 1);
2265 } else if (Name == "pread" ||
2266 Name == "pwrite") {
2267 if (FTy->getNumParams() != 4 || !FTy->getParamType(1)->isPointerTy())
2268 return;
2269 // May throw; these are valid pthread cancellation points.
2270 setDoesNotCapture(F, 2);
2271 } else if (Name == "putchar") {
2272 setDoesNotThrow(F);
2273 } else if (Name == "popen") {
2274 if (FTy->getNumParams() != 2 ||
2275 !FTy->getReturnType()->isPointerTy() ||
2276 !FTy->getParamType(0)->isPointerTy() ||
2277 !FTy->getParamType(1)->isPointerTy())
2278 return;
2279 setDoesNotThrow(F);
2280 setDoesNotAlias(F, 0);
2281 setDoesNotCapture(F, 1);
2282 setDoesNotCapture(F, 2);
2283 } else if (Name == "pclose") {
2284 if (FTy->getNumParams() != 1 || !FTy->getParamType(0)->isPointerTy())
2285 return;
2286 setDoesNotThrow(F);
2287 setDoesNotCapture(F, 1);
2288 }
2289 break;
2290 case 'v':
2291 if (Name == "vscanf") {
2292 if (FTy->getNumParams() != 2 || !FTy->getParamType(1)->isPointerTy())
2293 return;
2294 setDoesNotThrow(F);
2295 setDoesNotCapture(F, 1);
2296 } else if (Name == "vsscanf" ||
2297 Name == "vfscanf") {
2298 if (FTy->getNumParams() != 3 ||
2299 !FTy->getParamType(1)->isPointerTy() ||
2300 !FTy->getParamType(2)->isPointerTy())
2301 return;
2302 setDoesNotThrow(F);
2303 setDoesNotCapture(F, 1);
2304 setDoesNotCapture(F, 2);
2305 } else if (Name == "valloc") {
2306 if (!FTy->getReturnType()->isPointerTy())
2307 return;
2308 setDoesNotThrow(F);
2309 setDoesNotAlias(F, 0);
2310 } else if (Name == "vprintf") {
2311 if (FTy->getNumParams() != 2 || !FTy->getParamType(0)->isPointerTy())
2312 return;
2313 setDoesNotThrow(F);
2314 setDoesNotCapture(F, 1);
2315 } else if (Name == "vfprintf" ||
2316 Name == "vsprintf") {
2317 if (FTy->getNumParams() != 3 ||
2318 !FTy->getParamType(0)->isPointerTy() ||
2319 !FTy->getParamType(1)->isPointerTy())
2320 return;
2321 setDoesNotThrow(F);
2322 setDoesNotCapture(F, 1);
2323 setDoesNotCapture(F, 2);
2324 } else if (Name == "vsnprintf") {
2325 if (FTy->getNumParams() != 4 ||
2326 !FTy->getParamType(0)->isPointerTy() ||
2327 !FTy->getParamType(2)->isPointerTy())
2328 return;
2329 setDoesNotThrow(F);
2330 setDoesNotCapture(F, 1);
2331 setDoesNotCapture(F, 3);
2332 }
2333 break;
2334 case 'o':
2335 if (Name == "open") {
2336 if (FTy->getNumParams() < 2 || !FTy->getParamType(0)->isPointerTy())
2337 return;
2338 // May throw; "open" is a valid pthread cancellation point.
2339 setDoesNotCapture(F, 1);
2340 } else if (Name == "opendir") {
2341 if (FTy->getNumParams() != 1 ||
2342 !FTy->getReturnType()->isPointerTy() ||
2343 !FTy->getParamType(0)->isPointerTy())
2344 return;
2345 setDoesNotThrow(F);
2346 setDoesNotAlias(F, 0);
2347 setDoesNotCapture(F, 1);
2348 }
2349 break;
2350 case 't':
2351 if (Name == "tmpfile") {
2352 if (!FTy->getReturnType()->isPointerTy())
2353 return;
2354 setDoesNotThrow(F);
2355 setDoesNotAlias(F, 0);
2356 } else if (Name == "times") {
2357 if (FTy->getNumParams() != 1 || !FTy->getParamType(0)->isPointerTy())
2358 return;
2359 setDoesNotThrow(F);
2360 setDoesNotCapture(F, 1);
2361 }
2362 break;
2363 case 'h':
2364 if (Name == "htonl" ||
2365 Name == "htons") {
2366 setDoesNotThrow(F);
2367 setDoesNotAccessMemory(F);
2368 }
2369 break;
2370 case 'n':
2371 if (Name == "ntohl" ||
2372 Name == "ntohs") {
2373 setDoesNotThrow(F);
2374 setDoesNotAccessMemory(F);
2375 }
2376 break;
2377 case 'l':
2378 if (Name == "lstat") {
2379 if (FTy->getNumParams() != 2 ||
2380 !FTy->getParamType(0)->isPointerTy() ||
2381 !FTy->getParamType(1)->isPointerTy())
2382 return;
2383 setDoesNotThrow(F);
2384 setDoesNotCapture(F, 1);
2385 setDoesNotCapture(F, 2);
2386 } else if (Name == "lchown") {
2387 if (FTy->getNumParams() != 3 || !FTy->getParamType(0)->isPointerTy())
2388 return;
2389 setDoesNotThrow(F);
2390 setDoesNotCapture(F, 1);
2391 }
2392 break;
2393 case 'q':
2394 if (Name == "qsort") {
2395 if (FTy->getNumParams() != 4 || !FTy->getParamType(3)->isPointerTy())
2396 return;
2397 // May throw; places call through function pointer.
2398 setDoesNotCapture(F, 4);
2399 }
2400 break;
2401 case '_':
2402 if (Name == "__strdup" ||
2403 Name == "__strndup") {
2404 if (FTy->getNumParams() < 1 ||
2405 !FTy->getReturnType()->isPointerTy() ||
2406 !FTy->getParamType(0)->isPointerTy())
2407 return;
2408 setDoesNotThrow(F);
2409 setDoesNotAlias(F, 0);
2410 setDoesNotCapture(F, 1);
2411 } else if (Name == "__strtok_r") {
2412 if (FTy->getNumParams() != 3 ||
2413 !FTy->getParamType(1)->isPointerTy())
2414 return;
2415 setDoesNotThrow(F);
2416 setDoesNotCapture(F, 2);
2417 } else if (Name == "_IO_getc") {
2418 if (FTy->getNumParams() != 1 || !FTy->getParamType(0)->isPointerTy())
2419 return;
2420 setDoesNotThrow(F);
2421 setDoesNotCapture(F, 1);
2422 } else if (Name == "_IO_putc") {
2423 if (FTy->getNumParams() != 2 || !FTy->getParamType(1)->isPointerTy())
2424 return;
2425 setDoesNotThrow(F);
2426 setDoesNotCapture(F, 2);
2427 }
2428 break;
2429 case 1:
2430 if (Name == "\1__isoc99_scanf") {
2431 if (FTy->getNumParams() < 1 ||
2432 !FTy->getParamType(0)->isPointerTy())
2433 return;
2434 setDoesNotThrow(F);
2435 setDoesNotCapture(F, 1);
2436 } else if (Name == "\1stat64" ||
2437 Name == "\1lstat64" ||
2438 Name == "\1statvfs64" ||
2439 Name == "\1__isoc99_sscanf") {
2440 if (FTy->getNumParams() < 1 ||
2441 !FTy->getParamType(0)->isPointerTy() ||
2442 !FTy->getParamType(1)->isPointerTy())
2443 return;
2444 setDoesNotThrow(F);
2445 setDoesNotCapture(F, 1);
2446 setDoesNotCapture(F, 2);
2447 } else if (Name == "\1fopen64") {
2448 if (FTy->getNumParams() != 2 ||
2449 !FTy->getReturnType()->isPointerTy() ||
2450 !FTy->getParamType(0)->isPointerTy() ||
2451 !FTy->getParamType(1)->isPointerTy())
2452 return;
2453 setDoesNotThrow(F);
2454 setDoesNotAlias(F, 0);
2455 setDoesNotCapture(F, 1);
2456 setDoesNotCapture(F, 2);
2457 } else if (Name == "\1fseeko64" ||
2458 Name == "\1ftello64") {
2459 if (FTy->getNumParams() == 0 || !FTy->getParamType(0)->isPointerTy())
2460 return;
2461 setDoesNotThrow(F);
2462 setDoesNotCapture(F, 1);
2463 } else if (Name == "\1tmpfile64") {
2464 if (!FTy->getReturnType()->isPointerTy())
2465 return;
2466 setDoesNotThrow(F);
2467 setDoesNotAlias(F, 0);
2468 } else if (Name == "\1fstat64" ||
2469 Name == "\1fstatvfs64") {
2470 if (FTy->getNumParams() != 2 || !FTy->getParamType(1)->isPointerTy())
2471 return;
2472 setDoesNotThrow(F);
2473 setDoesNotCapture(F, 2);
2474 } else if (Name == "\1open64") {
2475 if (FTy->getNumParams() < 2 || !FTy->getParamType(0)->isPointerTy())
2476 return;
2477 // May throw; "open" is a valid pthread cancellation point.
2478 setDoesNotCapture(F, 1);
2479 }
2480 break;
2481 }
2482}
2483
Nick Lewycky6cd0c042009-01-05 00:07:50 +00002484/// doInitialization - Add attributes to well-known functions.
Nick Lewycky0f8df9a2009-01-04 20:27:34 +00002485///
Nick Lewycky6cd0c042009-01-05 00:07:50 +00002486bool SimplifyLibCalls::doInitialization(Module &M) {
Nick Lewycky0f8df9a2009-01-04 20:27:34 +00002487 Modified = false;
2488 for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I) {
2489 Function &F = *I;
Chris Lattnere265ad82011-02-24 07:12:12 +00002490 if (F.isDeclaration() && F.hasName())
2491 inferPrototypeAttributes(F);
Nick Lewycky0f8df9a2009-01-04 20:27:34 +00002492 }
2493 return Modified;
2494}
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00002495
2496// TODO:
2497// Additional cases that we need to add to this file:
2498//
2499// cbrt:
2500// * cbrt(expN(X)) -> expN(x/3)
2501// * cbrt(sqrt(x)) -> pow(x,1/6)
2502// * cbrt(sqrt(x)) -> pow(x,1/9)
2503//
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00002504// exp, expf, expl:
2505// * exp(log(x)) -> x
2506//
2507// log, logf, logl:
2508// * log(exp(x)) -> x
2509// * log(x**y) -> y*log(x)
2510// * log(exp(y)) -> y*log(e)
2511// * log(exp2(y)) -> y*log(2)
2512// * log(exp10(y)) -> y*log(10)
2513// * log(sqrt(x)) -> 0.5*log(x)
2514// * log(pow(x,y)) -> y*log(x)
2515//
2516// lround, lroundf, lroundl:
2517// * lround(cnst) -> cnst'
2518//
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00002519// pow, powf, powl:
2520// * pow(exp(x),y) -> exp(x*y)
2521// * pow(sqrt(x),y) -> pow(x,y*0.5)
2522// * pow(pow(x,y),z)-> pow(x,y*z)
2523//
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00002524// round, roundf, roundl:
2525// * round(cnst) -> cnst'
2526//
2527// signbit:
2528// * signbit(cnst) -> cnst'
2529// * signbit(nncst) -> 0 (if pstv is a non-negative constant)
2530//
2531// sqrt, sqrtf, sqrtl:
2532// * sqrt(expN(x)) -> expN(x*0.5)
2533// * sqrt(Nroot(x)) -> pow(x,1/(2*N))
2534// * sqrt(pow(x,y)) -> pow(|x|,y*0.5)
2535//
Chris Lattner18c7f802012-02-05 02:29:43 +00002536// strchr:
2537// * strchr(p, 0) -> strlen(p)
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00002538// tan, tanf, tanl:
2539// * tan(atan(x)) -> x
2540//
2541// trunc, truncf, truncl:
2542// * trunc(cnst) -> cnst'
2543//
2544//