blob: 54eaada3e4325a39517531375423a727a7dc96a6 [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"
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +000021#include "llvm/Intrinsics.h"
Owen Andersonfa5cbd62009-07-03 19:42:02 +000022#include "llvm/LLVMContext.h"
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +000023#include "llvm/Module.h"
24#include "llvm/Pass.h"
25#include "llvm/Support/IRBuilder.h"
Evan Cheng0ff39b32008-06-30 07:31:25 +000026#include "llvm/Analysis/ValueTracking.h"
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +000027#include "llvm/Target/TargetData.h"
Chris Lattnerafbf4832011-02-24 07:16:14 +000028#include "llvm/Target/TargetLibraryInfo.h"
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +000029#include "llvm/ADT/SmallPtrSet.h"
30#include "llvm/ADT/StringMap.h"
31#include "llvm/ADT/Statistic.h"
Daniel Dunbar473955f2009-07-29 22:00:43 +000032#include "llvm/ADT/STLExtras.h"
Chris Lattner56b4f2b2008-05-01 06:39:12 +000033#include "llvm/Support/Debug.h"
Daniel Dunbarf0443c12009-07-26 08:34:35 +000034#include "llvm/Support/raw_ostream.h"
Chris Lattnerafbf4832011-02-24 07:16:14 +000035#include "llvm/Config/config.h" // FIXME: Shouldn't depend on host!
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +000036using namespace llvm;
37
38STATISTIC(NumSimplified, "Number of library calls simplified");
Nick Lewycky0f8df9a2009-01-04 20:27:34 +000039STATISTIC(NumAnnotated, "Number of attributes added to library functions");
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +000040
41//===----------------------------------------------------------------------===//
42// Optimizer Base Class
43//===----------------------------------------------------------------------===//
44
45/// This class is the abstract base class for the set of optimizations that
46/// corresponds to one library call.
47namespace {
Chris Lattner3e8b6632009-09-02 06:11:42 +000048class LibCallOptimization {
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +000049protected:
50 Function *Caller;
51 const TargetData *TD;
Richard Osborne36498242011-03-03 13:17:51 +000052 const TargetLibraryInfo *TLI;
Owen Andersonfa5cbd62009-07-03 19:42:02 +000053 LLVMContext* Context;
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +000054public:
Evan Chengeb8c6452010-03-24 20:19:04 +000055 LibCallOptimization() { }
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +000056 virtual ~LibCallOptimization() {}
57
58 /// CallOptimizer - This pure virtual method is implemented by base classes to
59 /// do various optimizations. If this returns null then no transformation was
60 /// performed. If it returns CI, then it transformed the call and CI is to be
61 /// deleted. If it returns something else, replace CI with the new value and
62 /// delete CI.
Eric Christopher37c8b862009-10-07 21:14:25 +000063 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B)
Eric Christopher7a61d702008-08-08 19:39:37 +000064 =0;
Eric Christopher37c8b862009-10-07 21:14:25 +000065
Richard Osborne36498242011-03-03 13:17:51 +000066 Value *OptimizeCall(CallInst *CI, const TargetData *TD,
67 const TargetLibraryInfo *TLI, IRBuilder<> &B) {
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +000068 Caller = CI->getParent()->getParent();
Dan Gohmanf14d9192009-08-18 00:48:13 +000069 this->TD = TD;
Richard Osborne36498242011-03-03 13:17:51 +000070 this->TLI = TLI;
Owen Andersonfa5cbd62009-07-03 19:42:02 +000071 if (CI->getCalledFunction())
Owen Andersone922c022009-07-22 00:24:57 +000072 Context = &CI->getCalledFunction()->getContext();
Rafael Espindolae96af562010-06-16 19:34:01 +000073
74 // We never change the calling convention.
75 if (CI->getCallingConv() != llvm::CallingConv::C)
76 return NULL;
77
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +000078 return CallOptimizer(CI->getCalledFunction(), CI, B);
79 }
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +000080};
81} // End anonymous namespace.
82
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +000083
84//===----------------------------------------------------------------------===//
85// Helper Functions
86//===----------------------------------------------------------------------===//
87
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +000088/// IsOnlyUsedInZeroEqualityComparison - Return true if it only matters that the
Eric Christopher37c8b862009-10-07 21:14:25 +000089/// value is equal or not-equal to zero.
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +000090static bool IsOnlyUsedInZeroEqualityComparison(Value *V) {
91 for (Value::use_iterator UI = V->use_begin(), E = V->use_end();
92 UI != E; ++UI) {
93 if (ICmpInst *IC = dyn_cast<ICmpInst>(*UI))
94 if (IC->isEquality())
95 if (Constant *C = dyn_cast<Constant>(IC->getOperand(1)))
96 if (C->isNullValue())
97 continue;
98 // Unknown instruction.
99 return false;
100 }
101 return true;
102}
Richard Osborne36498242011-03-03 13:17:51 +0000103
104static bool CallHasFloatingPointArgument(const CallInst *CI) {
105 for (CallInst::const_op_iterator it = CI->op_begin(), e = CI->op_end();
106 it != e; ++it) {
107 if ((*it)->getType()->isFloatingPointTy())
108 return true;
109 }
110 return false;
111}
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000112
Benjamin Kramer386e9182010-06-15 21:34:25 +0000113/// IsOnlyUsedInEqualityComparison - Return true if it is only used in equality
114/// comparisons with With.
115static bool IsOnlyUsedInEqualityComparison(Value *V, Value *With) {
116 for (Value::use_iterator UI = V->use_begin(), E = V->use_end();
117 UI != E; ++UI) {
118 if (ICmpInst *IC = dyn_cast<ICmpInst>(*UI))
119 if (IC->isEquality() && IC->getOperand(1) == With)
120 continue;
121 // Unknown instruction.
122 return false;
123 }
124 return true;
125}
126
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000127//===----------------------------------------------------------------------===//
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000128// String and Memory LibCall Optimizations
129//===----------------------------------------------------------------------===//
130
131//===---------------------------------------===//
132// 'strcat' Optimizations
Chris Lattnere9f9a7e2009-09-03 05:19:59 +0000133namespace {
Chris Lattner3e8b6632009-09-02 06:11:42 +0000134struct StrCatOpt : public LibCallOptimization {
Eric Christopher7a61d702008-08-08 19:39:37 +0000135 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000136 // Verify the "strcat" function prototype.
137 const FunctionType *FT = Callee->getFunctionType();
138 if (FT->getNumParams() != 2 ||
Benjamin Kramera1bf4ca2010-12-27 00:16:46 +0000139 FT->getReturnType() != B.getInt8PtrTy() ||
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000140 FT->getParamType(0) != FT->getReturnType() ||
141 FT->getParamType(1) != FT->getReturnType())
142 return 0;
Eric Christopher37c8b862009-10-07 21:14:25 +0000143
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000144 // Extract some information from the instruction
Gabor Greifaee5dc12010-06-24 10:42:46 +0000145 Value *Dst = CI->getArgOperand(0);
146 Value *Src = CI->getArgOperand(1);
Eric Christopher37c8b862009-10-07 21:14:25 +0000147
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000148 // See if we can get the length of the input string.
149 uint64_t Len = GetStringLength(Src);
Chris Lattner56b4f2b2008-05-01 06:39:12 +0000150 if (Len == 0) return 0;
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000151 --Len; // Unbias length.
Eric Christopher37c8b862009-10-07 21:14:25 +0000152
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000153 // Handle the simple, do-nothing case: strcat(x, "") -> x
154 if (Len == 0)
155 return Dst;
Dan Gohmanf14d9192009-08-18 00:48:13 +0000156
157 // These optimizations require TargetData.
158 if (!TD) return 0;
159
Chris Lattnerf5b6bc72009-04-12 05:06:39 +0000160 EmitStrLenMemCpy(Src, Dst, Len, B);
161 return Dst;
162 }
163
164 void EmitStrLenMemCpy(Value *Src, Value *Dst, uint64_t Len, IRBuilder<> &B) {
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000165 // We need to find the end of the destination string. That's where the
166 // memory is to be moved to. We just generate a call to strlen.
Eric Christopherb6174e32010-03-05 22:25:30 +0000167 Value *DstLen = EmitStrLen(Dst, B, TD);
Eric Christopher37c8b862009-10-07 21:14:25 +0000168
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000169 // Now that we have the destination's length, we must index into the
170 // destination's pointer to get the actual memcpy destination (end of
171 // the string .. we're concatenating).
Ed Schoutenb5e0a962009-04-06 13:06:48 +0000172 Value *CpyDst = B.CreateGEP(Dst, DstLen, "endptr");
Eric Christopher37c8b862009-10-07 21:14:25 +0000173
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000174 // We have enough information to now generate the memcpy call to do the
175 // concatenation for us. Make a memcpy to copy the nul byte with align = 1.
Benjamin Kramera1bf4ca2010-12-27 00:16:46 +0000176 B.CreateMemCpy(CpyDst, Src,
177 ConstantInt::get(TD->getIntPtrType(*Context), Len + 1), 1);
Chris Lattnerf5b6bc72009-04-12 05:06:39 +0000178 }
179};
180
181//===---------------------------------------===//
182// 'strncat' Optimizations
183
Chris Lattner3e8b6632009-09-02 06:11:42 +0000184struct StrNCatOpt : public StrCatOpt {
Chris Lattnerf5b6bc72009-04-12 05:06:39 +0000185 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
186 // Verify the "strncat" function prototype.
187 const FunctionType *FT = Callee->getFunctionType();
188 if (FT->getNumParams() != 3 ||
Benjamin Kramera1bf4ca2010-12-27 00:16:46 +0000189 FT->getReturnType() != B.getInt8PtrTy() ||
Chris Lattnerf5b6bc72009-04-12 05:06:39 +0000190 FT->getParamType(0) != FT->getReturnType() ||
191 FT->getParamType(1) != FT->getReturnType() ||
Duncan Sands1df98592010-02-16 11:11:14 +0000192 !FT->getParamType(2)->isIntegerTy())
Chris Lattnerf5b6bc72009-04-12 05:06:39 +0000193 return 0;
194
195 // Extract some information from the instruction
Gabor Greifaee5dc12010-06-24 10:42:46 +0000196 Value *Dst = CI->getArgOperand(0);
197 Value *Src = CI->getArgOperand(1);
Chris Lattnerf5b6bc72009-04-12 05:06:39 +0000198 uint64_t Len;
199
200 // We don't do anything if length is not constant
Gabor Greifaee5dc12010-06-24 10:42:46 +0000201 if (ConstantInt *LengthArg = dyn_cast<ConstantInt>(CI->getArgOperand(2)))
Chris Lattnerf5b6bc72009-04-12 05:06:39 +0000202 Len = LengthArg->getZExtValue();
203 else
204 return 0;
205
206 // See if we can get the length of the input string.
207 uint64_t SrcLen = GetStringLength(Src);
208 if (SrcLen == 0) return 0;
209 --SrcLen; // Unbias length.
210
211 // Handle the simple, do-nothing cases:
212 // strncat(x, "", c) -> x
213 // strncat(x, c, 0) -> x
214 if (SrcLen == 0 || Len == 0) return Dst;
215
Dan Gohmanf14d9192009-08-18 00:48:13 +0000216 // These optimizations require TargetData.
217 if (!TD) return 0;
218
Chris Lattnerf5b6bc72009-04-12 05:06:39 +0000219 // We don't optimize this case
220 if (Len < SrcLen) return 0;
221
222 // strncat(x, s, c) -> strcat(x, s)
223 // s is constant so the strcat can be optimized further
Chris Lattner5db4cdf2009-04-12 18:22:33 +0000224 EmitStrLenMemCpy(Src, Dst, SrcLen, B);
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000225 return Dst;
226 }
227};
228
229//===---------------------------------------===//
230// 'strchr' Optimizations
231
Chris Lattner3e8b6632009-09-02 06:11:42 +0000232struct StrChrOpt : public LibCallOptimization {
Eric Christopher7a61d702008-08-08 19:39:37 +0000233 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000234 // Verify the "strchr" function prototype.
235 const FunctionType *FT = Callee->getFunctionType();
236 if (FT->getNumParams() != 2 ||
Benjamin Kramera1bf4ca2010-12-27 00:16:46 +0000237 FT->getReturnType() != B.getInt8PtrTy() ||
Benjamin Kramer4c756792010-09-30 11:21:59 +0000238 FT->getParamType(0) != FT->getReturnType() ||
239 !FT->getParamType(1)->isIntegerTy(32))
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000240 return 0;
Eric Christopher37c8b862009-10-07 21:14:25 +0000241
Gabor Greifaee5dc12010-06-24 10:42:46 +0000242 Value *SrcStr = CI->getArgOperand(0);
Eric Christopher37c8b862009-10-07 21:14:25 +0000243
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000244 // If the second operand is non-constant, see if we can compute the length
245 // of the input string and turn this into memchr.
Gabor Greifaee5dc12010-06-24 10:42:46 +0000246 ConstantInt *CharC = dyn_cast<ConstantInt>(CI->getArgOperand(1));
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000247 if (CharC == 0) {
Dan Gohmanf14d9192009-08-18 00:48:13 +0000248 // These optimizations require TargetData.
249 if (!TD) return 0;
250
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000251 uint64_t Len = GetStringLength(SrcStr);
Duncan Sandsb0bc6c32010-02-15 16:12:20 +0000252 if (Len == 0 || !FT->getParamType(1)->isIntegerTy(32))// memchr needs i32.
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000253 return 0;
Eric Christopher37c8b862009-10-07 21:14:25 +0000254
Gabor Greifaee5dc12010-06-24 10:42:46 +0000255 return EmitMemChr(SrcStr, CI->getArgOperand(1), // include nul.
Eric Christopherb6174e32010-03-05 22:25:30 +0000256 ConstantInt::get(TD->getIntPtrType(*Context), Len),
257 B, TD);
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000258 }
259
260 // Otherwise, the character is a constant, see if the first argument is
261 // a string literal. If so, we can constant fold.
Bill Wendling0582ae92009-03-13 04:39:26 +0000262 std::string Str;
263 if (!GetConstantStringInfo(SrcStr, Str))
Chris Lattner56b4f2b2008-05-01 06:39:12 +0000264 return 0;
Eric Christopher37c8b862009-10-07 21:14:25 +0000265
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000266 // strchr can find the nul character.
267 Str += '\0';
Eric Christopher37c8b862009-10-07 21:14:25 +0000268
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000269 // Compute the offset.
Benjamin Kramere2609902010-09-29 22:29:12 +0000270 size_t I = Str.find(CharC->getSExtValue());
271 if (I == std::string::npos) // Didn't find the char. strchr returns null.
272 return Constant::getNullValue(CI->getType());
Eric Christopher37c8b862009-10-07 21:14:25 +0000273
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000274 // strchr(s+n,c) -> gep(s+n+i,c)
Benjamin Kramera1bf4ca2010-12-27 00:16:46 +0000275 return B.CreateGEP(SrcStr, B.getInt64(I), "strchr");
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000276 }
277};
278
279//===---------------------------------------===//
Benjamin Kramer06f25cf2010-09-29 21:50:51 +0000280// 'strrchr' Optimizations
281
282struct StrRChrOpt : public LibCallOptimization {
283 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
284 // Verify the "strrchr" function prototype.
285 const FunctionType *FT = Callee->getFunctionType();
286 if (FT->getNumParams() != 2 ||
Benjamin Kramera1bf4ca2010-12-27 00:16:46 +0000287 FT->getReturnType() != B.getInt8PtrTy() ||
Benjamin Kramer4c756792010-09-30 11:21:59 +0000288 FT->getParamType(0) != FT->getReturnType() ||
289 !FT->getParamType(1)->isIntegerTy(32))
Benjamin Kramer06f25cf2010-09-29 21:50:51 +0000290 return 0;
291
292 Value *SrcStr = CI->getArgOperand(0);
293 ConstantInt *CharC = dyn_cast<ConstantInt>(CI->getArgOperand(1));
294
295 // Cannot fold anything if we're not looking for a constant.
296 if (!CharC)
297 return 0;
298
299 std::string Str;
300 if (!GetConstantStringInfo(SrcStr, Str)) {
301 // strrchr(s, 0) -> strchr(s, 0)
302 if (TD && CharC->isZero())
303 return EmitStrChr(SrcStr, '\0', B, TD);
304 return 0;
305 }
306
307 // strrchr can find the nul character.
308 Str += '\0';
309
310 // Compute the offset.
311 size_t I = Str.rfind(CharC->getSExtValue());
312 if (I == std::string::npos) // Didn't find the char. Return null.
313 return Constant::getNullValue(CI->getType());
314
315 // strrchr(s+n,c) -> gep(s+n+i,c)
Benjamin Kramera1bf4ca2010-12-27 00:16:46 +0000316 return B.CreateGEP(SrcStr, B.getInt64(I), "strrchr");
Benjamin Kramer06f25cf2010-09-29 21:50:51 +0000317 }
318};
319
320//===---------------------------------------===//
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000321// 'strcmp' Optimizations
322
Chris Lattner3e8b6632009-09-02 06:11:42 +0000323struct StrCmpOpt : public LibCallOptimization {
Eric Christopher7a61d702008-08-08 19:39:37 +0000324 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000325 // Verify the "strcmp" function prototype.
326 const FunctionType *FT = Callee->getFunctionType();
Eric Christopher37c8b862009-10-07 21:14:25 +0000327 if (FT->getNumParams() != 2 ||
Nick Lewycky10d2f4d2010-07-06 03:53:43 +0000328 !FT->getReturnType()->isIntegerTy(32) ||
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000329 FT->getParamType(0) != FT->getParamType(1) ||
Benjamin Kramera1bf4ca2010-12-27 00:16:46 +0000330 FT->getParamType(0) != B.getInt8PtrTy())
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000331 return 0;
Eric Christopher37c8b862009-10-07 21:14:25 +0000332
Gabor Greifaee5dc12010-06-24 10:42:46 +0000333 Value *Str1P = CI->getArgOperand(0), *Str2P = CI->getArgOperand(1);
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000334 if (Str1P == Str2P) // strcmp(x,x) -> 0
Owen Andersoneed707b2009-07-24 23:12:02 +0000335 return ConstantInt::get(CI->getType(), 0);
Eric Christopher37c8b862009-10-07 21:14:25 +0000336
Bill Wendling0582ae92009-03-13 04:39:26 +0000337 std::string Str1, Str2;
338 bool HasStr1 = GetConstantStringInfo(Str1P, Str1);
339 bool HasStr2 = GetConstantStringInfo(Str2P, Str2);
Eric Christopher37c8b862009-10-07 21:14:25 +0000340
Bill Wendling0582ae92009-03-13 04:39:26 +0000341 if (HasStr1 && Str1.empty()) // strcmp("", x) -> *x
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000342 return B.CreateZExt(B.CreateLoad(Str2P, "strcmpload"), CI->getType());
Eric Christopher37c8b862009-10-07 21:14:25 +0000343
Bill Wendling0582ae92009-03-13 04:39:26 +0000344 if (HasStr2 && Str2.empty()) // strcmp(x,"") -> *x
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000345 return B.CreateZExt(B.CreateLoad(Str1P, "strcmpload"), CI->getType());
Eric Christopher37c8b862009-10-07 21:14:25 +0000346
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000347 // strcmp(x, y) -> cnst (if both x and y are constant strings)
Bill Wendling0582ae92009-03-13 04:39:26 +0000348 if (HasStr1 && HasStr2)
Eric Christopher37c8b862009-10-07 21:14:25 +0000349 return ConstantInt::get(CI->getType(),
Owen Andersonfa5cbd62009-07-03 19:42:02 +0000350 strcmp(Str1.c_str(),Str2.c_str()));
Nick Lewycky13a09e22008-12-21 00:19:21 +0000351
352 // strcmp(P, "x") -> memcmp(P, "x", 2)
353 uint64_t Len1 = GetStringLength(Str1P);
354 uint64_t Len2 = GetStringLength(Str2P);
Chris Lattner849832c2009-06-19 04:17:36 +0000355 if (Len1 && Len2) {
Dan Gohmanf14d9192009-08-18 00:48:13 +0000356 // These optimizations require TargetData.
357 if (!TD) return 0;
358
Nick Lewycky13a09e22008-12-21 00:19:21 +0000359 return EmitMemCmp(Str1P, Str2P,
Owen Anderson1d0be152009-08-13 21:58:54 +0000360 ConstantInt::get(TD->getIntPtrType(*Context),
Eric Christopherb6174e32010-03-05 22:25:30 +0000361 std::min(Len1, Len2)), B, TD);
Nick Lewycky13a09e22008-12-21 00:19:21 +0000362 }
363
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000364 return 0;
365 }
366};
367
368//===---------------------------------------===//
369// 'strncmp' Optimizations
370
Chris Lattner3e8b6632009-09-02 06:11:42 +0000371struct StrNCmpOpt : public LibCallOptimization {
Eric Christopher7a61d702008-08-08 19:39:37 +0000372 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000373 // Verify the "strncmp" function prototype.
374 const FunctionType *FT = Callee->getFunctionType();
Eric Christopher37c8b862009-10-07 21:14:25 +0000375 if (FT->getNumParams() != 3 ||
Nick Lewycky10d2f4d2010-07-06 03:53:43 +0000376 !FT->getReturnType()->isIntegerTy(32) ||
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000377 FT->getParamType(0) != FT->getParamType(1) ||
Benjamin Kramera1bf4ca2010-12-27 00:16:46 +0000378 FT->getParamType(0) != B.getInt8PtrTy() ||
Duncan Sands1df98592010-02-16 11:11:14 +0000379 !FT->getParamType(2)->isIntegerTy())
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000380 return 0;
Eric Christopher37c8b862009-10-07 21:14:25 +0000381
Gabor Greifaee5dc12010-06-24 10:42:46 +0000382 Value *Str1P = CI->getArgOperand(0), *Str2P = CI->getArgOperand(1);
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000383 if (Str1P == Str2P) // strncmp(x,x,n) -> 0
Owen Andersoneed707b2009-07-24 23:12:02 +0000384 return ConstantInt::get(CI->getType(), 0);
Eric Christopher37c8b862009-10-07 21:14:25 +0000385
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000386 // Get the length argument if it is constant.
387 uint64_t Length;
Gabor Greifaee5dc12010-06-24 10:42:46 +0000388 if (ConstantInt *LengthArg = dyn_cast<ConstantInt>(CI->getArgOperand(2)))
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000389 Length = LengthArg->getZExtValue();
390 else
391 return 0;
Eric Christopher37c8b862009-10-07 21:14:25 +0000392
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000393 if (Length == 0) // strncmp(x,y,0) -> 0
Owen Andersoneed707b2009-07-24 23:12:02 +0000394 return ConstantInt::get(CI->getType(), 0);
Eric Christopher37c8b862009-10-07 21:14:25 +0000395
Benjamin Kramerea9ca022010-06-16 10:30:29 +0000396 if (TD && Length == 1) // strncmp(x,y,1) -> memcmp(x,y,1)
Gabor Greif8e1ebff2010-06-30 12:42:43 +0000397 return EmitMemCmp(Str1P, Str2P, CI->getArgOperand(2), B, TD);
Benjamin Kramerea9ca022010-06-16 10:30:29 +0000398
Bill Wendling0582ae92009-03-13 04:39:26 +0000399 std::string Str1, Str2;
400 bool HasStr1 = GetConstantStringInfo(Str1P, Str1);
401 bool HasStr2 = GetConstantStringInfo(Str2P, Str2);
Eric Christopher37c8b862009-10-07 21:14:25 +0000402
Bill Wendling0582ae92009-03-13 04:39:26 +0000403 if (HasStr1 && Str1.empty()) // strncmp("", x, n) -> *x
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000404 return B.CreateZExt(B.CreateLoad(Str2P, "strcmpload"), CI->getType());
Eric Christopher37c8b862009-10-07 21:14:25 +0000405
Bill Wendling0582ae92009-03-13 04:39:26 +0000406 if (HasStr2 && Str2.empty()) // strncmp(x, "", n) -> *x
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000407 return B.CreateZExt(B.CreateLoad(Str1P, "strcmpload"), CI->getType());
Eric Christopher37c8b862009-10-07 21:14:25 +0000408
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000409 // strncmp(x, y) -> cnst (if both x and y are constant strings)
Bill Wendling0582ae92009-03-13 04:39:26 +0000410 if (HasStr1 && HasStr2)
Owen Andersoneed707b2009-07-24 23:12:02 +0000411 return ConstantInt::get(CI->getType(),
Bill Wendling0582ae92009-03-13 04:39:26 +0000412 strncmp(Str1.c_str(), Str2.c_str(), Length));
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000413 return 0;
414 }
415};
416
417
418//===---------------------------------------===//
419// 'strcpy' Optimizations
420
Chris Lattner3e8b6632009-09-02 06:11:42 +0000421struct StrCpyOpt : public LibCallOptimization {
Evan Chengeb8c6452010-03-24 20:19:04 +0000422 bool OptChkCall; // True if it's optimizing a __strcpy_chk libcall.
423
424 StrCpyOpt(bool c) : OptChkCall(c) {}
425
Eric Christopher7a61d702008-08-08 19:39:37 +0000426 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000427 // Verify the "strcpy" function prototype.
Evan Cheng0289b412010-03-23 15:48:04 +0000428 unsigned NumParams = OptChkCall ? 3 : 2;
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000429 const FunctionType *FT = Callee->getFunctionType();
Evan Cheng0289b412010-03-23 15:48:04 +0000430 if (FT->getNumParams() != NumParams ||
431 FT->getReturnType() != FT->getParamType(0) ||
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000432 FT->getParamType(0) != FT->getParamType(1) ||
Benjamin Kramera1bf4ca2010-12-27 00:16:46 +0000433 FT->getParamType(0) != B.getInt8PtrTy())
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000434 return 0;
Eric Christopher37c8b862009-10-07 21:14:25 +0000435
Gabor Greifaee5dc12010-06-24 10:42:46 +0000436 Value *Dst = CI->getArgOperand(0), *Src = CI->getArgOperand(1);
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000437 if (Dst == Src) // strcpy(x,x) -> x
438 return Src;
Eric Christopher37c8b862009-10-07 21:14:25 +0000439
Dan Gohmanf14d9192009-08-18 00:48:13 +0000440 // These optimizations require TargetData.
441 if (!TD) return 0;
442
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000443 // See if we can get the length of the input string.
444 uint64_t Len = GetStringLength(Src);
Chris Lattner56b4f2b2008-05-01 06:39:12 +0000445 if (Len == 0) return 0;
Eric Christopher37c8b862009-10-07 21:14:25 +0000446
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000447 // We have enough information to now generate the memcpy call to do the
448 // concatenation for us. Make a memcpy to copy the nul byte with align = 1.
Evan Cheng0289b412010-03-23 15:48:04 +0000449 if (OptChkCall)
450 EmitMemCpyChk(Dst, Src,
451 ConstantInt::get(TD->getIntPtrType(*Context), Len),
Gabor Greifaee5dc12010-06-24 10:42:46 +0000452 CI->getArgOperand(2), B, TD);
Evan Cheng0289b412010-03-23 15:48:04 +0000453 else
Benjamin Kramera1bf4ca2010-12-27 00:16:46 +0000454 B.CreateMemCpy(Dst, Src,
455 ConstantInt::get(TD->getIntPtrType(*Context), Len), 1);
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000456 return Dst;
457 }
458};
459
Chris Lattnerf5b6bc72009-04-12 05:06:39 +0000460//===---------------------------------------===//
461// 'strncpy' Optimizations
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000462
Chris Lattner3e8b6632009-09-02 06:11:42 +0000463struct StrNCpyOpt : public LibCallOptimization {
Chris Lattnerf5b6bc72009-04-12 05:06:39 +0000464 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
465 const FunctionType *FT = Callee->getFunctionType();
466 if (FT->getNumParams() != 3 || FT->getReturnType() != FT->getParamType(0) ||
467 FT->getParamType(0) != FT->getParamType(1) ||
Benjamin Kramera1bf4ca2010-12-27 00:16:46 +0000468 FT->getParamType(0) != B.getInt8PtrTy() ||
Duncan Sands1df98592010-02-16 11:11:14 +0000469 !FT->getParamType(2)->isIntegerTy())
Chris Lattnerf5b6bc72009-04-12 05:06:39 +0000470 return 0;
471
Gabor Greifaee5dc12010-06-24 10:42:46 +0000472 Value *Dst = CI->getArgOperand(0);
473 Value *Src = CI->getArgOperand(1);
474 Value *LenOp = CI->getArgOperand(2);
Chris Lattnerf5b6bc72009-04-12 05:06:39 +0000475
476 // See if we can get the length of the input string.
477 uint64_t SrcLen = GetStringLength(Src);
478 if (SrcLen == 0) return 0;
479 --SrcLen;
480
481 if (SrcLen == 0) {
482 // strncpy(x, "", y) -> memset(x, '\0', y, 1)
Benjamin Kramera1bf4ca2010-12-27 00:16:46 +0000483 B.CreateMemSet(Dst, B.getInt8('\0'), LenOp, 1);
Chris Lattnerf5b6bc72009-04-12 05:06:39 +0000484 return Dst;
485 }
486
487 uint64_t Len;
488 if (ConstantInt *LengthArg = dyn_cast<ConstantInt>(LenOp))
489 Len = LengthArg->getZExtValue();
490 else
491 return 0;
492
493 if (Len == 0) return Dst; // strncpy(x, y, 0) -> x
494
Dan Gohmanf14d9192009-08-18 00:48:13 +0000495 // These optimizations require TargetData.
496 if (!TD) return 0;
497
Chris Lattnerf5b6bc72009-04-12 05:06:39 +0000498 // Let strncpy handle the zero padding
499 if (Len > SrcLen+1) return 0;
500
501 // strncpy(x, s, c) -> memcpy(x, s, c, 1) [s and c are constant]
Benjamin Kramera1bf4ca2010-12-27 00:16:46 +0000502 B.CreateMemCpy(Dst, Src,
503 ConstantInt::get(TD->getIntPtrType(*Context), Len), 1);
Chris Lattnerf5b6bc72009-04-12 05:06:39 +0000504
505 return Dst;
506 }
507};
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000508
509//===---------------------------------------===//
510// 'strlen' Optimizations
511
Chris Lattner3e8b6632009-09-02 06:11:42 +0000512struct StrLenOpt : public LibCallOptimization {
Eric Christopher7a61d702008-08-08 19:39:37 +0000513 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000514 const FunctionType *FT = Callee->getFunctionType();
515 if (FT->getNumParams() != 1 ||
Benjamin Kramera1bf4ca2010-12-27 00:16:46 +0000516 FT->getParamType(0) != B.getInt8PtrTy() ||
Duncan Sands1df98592010-02-16 11:11:14 +0000517 !FT->getReturnType()->isIntegerTy())
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000518 return 0;
Eric Christopher37c8b862009-10-07 21:14:25 +0000519
Gabor Greifaee5dc12010-06-24 10:42:46 +0000520 Value *Src = CI->getArgOperand(0);
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000521
522 // Constant folding: strlen("xyz") -> 3
523 if (uint64_t Len = GetStringLength(Src))
Owen Andersoneed707b2009-07-24 23:12:02 +0000524 return ConstantInt::get(CI->getType(), Len-1);
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000525
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000526 // strlen(x) != 0 --> *x != 0
527 // strlen(x) == 0 --> *x == 0
Chris Lattner98d67d72009-12-23 23:24:51 +0000528 if (IsOnlyUsedInZeroEqualityComparison(CI))
529 return B.CreateZExt(B.CreateLoad(Src, "strlenfirst"), CI->getType());
530 return 0;
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000531 }
532};
533
Benjamin Kramer05f585e2010-09-29 23:52:12 +0000534
535//===---------------------------------------===//
536// 'strpbrk' Optimizations
537
538struct StrPBrkOpt : public LibCallOptimization {
539 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
540 const FunctionType *FT = Callee->getFunctionType();
541 if (FT->getNumParams() != 2 ||
Benjamin Kramera1bf4ca2010-12-27 00:16:46 +0000542 FT->getParamType(0) != B.getInt8PtrTy() ||
Benjamin Kramer05f585e2010-09-29 23:52:12 +0000543 FT->getParamType(1) != FT->getParamType(0) ||
544 FT->getReturnType() != FT->getParamType(0))
545 return 0;
546
547 std::string S1, S2;
548 bool HasS1 = GetConstantStringInfo(CI->getArgOperand(0), S1);
549 bool HasS2 = GetConstantStringInfo(CI->getArgOperand(1), S2);
550
551 // strpbrk(s, "") -> NULL
552 // strpbrk("", s) -> NULL
553 if ((HasS1 && S1.empty()) || (HasS2 && S2.empty()))
554 return Constant::getNullValue(CI->getType());
555
556 // Constant folding.
557 if (HasS1 && HasS2) {
558 size_t I = S1.find_first_of(S2);
559 if (I == std::string::npos) // No match.
560 return Constant::getNullValue(CI->getType());
561
Benjamin Kramera1bf4ca2010-12-27 00:16:46 +0000562 return B.CreateGEP(CI->getArgOperand(0), B.getInt64(I), "strpbrk");
Benjamin Kramer05f585e2010-09-29 23:52:12 +0000563 }
564
565 // strpbrk(s, "a") -> strchr(s, 'a')
566 if (TD && HasS2 && S2.size() == 1)
567 return EmitStrChr(CI->getArgOperand(0), S2[0], B, TD);
568
569 return 0;
570 }
571};
572
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000573//===---------------------------------------===//
Chris Lattner24604112009-12-16 09:32:05 +0000574// 'strto*' Optimizations. This handles strtol, strtod, strtof, strtoul, etc.
Nick Lewycky4c498412009-02-13 15:31:46 +0000575
Chris Lattner3e8b6632009-09-02 06:11:42 +0000576struct StrToOpt : public LibCallOptimization {
Nick Lewycky4c498412009-02-13 15:31:46 +0000577 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
578 const FunctionType *FT = Callee->getFunctionType();
579 if ((FT->getNumParams() != 2 && FT->getNumParams() != 3) ||
Duncan Sands1df98592010-02-16 11:11:14 +0000580 !FT->getParamType(0)->isPointerTy() ||
581 !FT->getParamType(1)->isPointerTy())
Nick Lewycky4c498412009-02-13 15:31:46 +0000582 return 0;
583
Gabor Greifaee5dc12010-06-24 10:42:46 +0000584 Value *EndPtr = CI->getArgOperand(1);
Nick Lewycky02b6a6a2009-02-13 17:08:33 +0000585 if (isa<ConstantPointerNull>(EndPtr)) {
Dan Gohmanc32046e2010-12-17 01:09:43 +0000586 // With a null EndPtr, this function won't capture the main argument.
587 // It would be readonly too, except that it still may write to errno.
Nick Lewycky4c498412009-02-13 15:31:46 +0000588 CI->addAttribute(1, Attribute::NoCapture);
Nick Lewycky02b6a6a2009-02-13 17:08:33 +0000589 }
Nick Lewycky4c498412009-02-13 15:31:46 +0000590
591 return 0;
592 }
593};
594
Chris Lattner24604112009-12-16 09:32:05 +0000595//===---------------------------------------===//
Benjamin Kramer9510a252010-09-30 00:58:35 +0000596// 'strspn' Optimizations
597
598struct StrSpnOpt : public LibCallOptimization {
599 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
600 const FunctionType *FT = Callee->getFunctionType();
601 if (FT->getNumParams() != 2 ||
Benjamin Kramera1bf4ca2010-12-27 00:16:46 +0000602 FT->getParamType(0) != B.getInt8PtrTy() ||
Benjamin Kramer9510a252010-09-30 00:58:35 +0000603 FT->getParamType(1) != FT->getParamType(0) ||
604 !FT->getReturnType()->isIntegerTy())
605 return 0;
606
607 std::string S1, S2;
608 bool HasS1 = GetConstantStringInfo(CI->getArgOperand(0), S1);
609 bool HasS2 = GetConstantStringInfo(CI->getArgOperand(1), S2);
610
611 // strspn(s, "") -> 0
612 // strspn("", s) -> 0
613 if ((HasS1 && S1.empty()) || (HasS2 && S2.empty()))
614 return Constant::getNullValue(CI->getType());
615
616 // Constant folding.
617 if (HasS1 && HasS2)
618 return ConstantInt::get(CI->getType(), strspn(S1.c_str(), S2.c_str()));
619
620 return 0;
621 }
622};
623
624//===---------------------------------------===//
625// 'strcspn' Optimizations
626
627struct StrCSpnOpt : public LibCallOptimization {
628 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
629 const FunctionType *FT = Callee->getFunctionType();
630 if (FT->getNumParams() != 2 ||
Benjamin Kramera1bf4ca2010-12-27 00:16:46 +0000631 FT->getParamType(0) != B.getInt8PtrTy() ||
Benjamin Kramer9510a252010-09-30 00:58:35 +0000632 FT->getParamType(1) != FT->getParamType(0) ||
633 !FT->getReturnType()->isIntegerTy())
634 return 0;
635
636 std::string S1, S2;
637 bool HasS1 = GetConstantStringInfo(CI->getArgOperand(0), S1);
638 bool HasS2 = GetConstantStringInfo(CI->getArgOperand(1), S2);
639
640 // strcspn("", s) -> 0
641 if (HasS1 && S1.empty())
642 return Constant::getNullValue(CI->getType());
643
644 // Constant folding.
645 if (HasS1 && HasS2)
646 return ConstantInt::get(CI->getType(), strcspn(S1.c_str(), S2.c_str()));
647
648 // strcspn(s, "") -> strlen(s)
649 if (TD && HasS2 && S2.empty())
650 return EmitStrLen(CI->getArgOperand(0), B, TD);
651
652 return 0;
653 }
654};
655
656//===---------------------------------------===//
Chris Lattner24604112009-12-16 09:32:05 +0000657// 'strstr' Optimizations
658
659struct StrStrOpt : public LibCallOptimization {
660 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
661 const FunctionType *FT = Callee->getFunctionType();
662 if (FT->getNumParams() != 2 ||
Duncan Sands1df98592010-02-16 11:11:14 +0000663 !FT->getParamType(0)->isPointerTy() ||
664 !FT->getParamType(1)->isPointerTy() ||
665 !FT->getReturnType()->isPointerTy())
Chris Lattner24604112009-12-16 09:32:05 +0000666 return 0;
667
668 // fold strstr(x, x) -> x.
Gabor Greifaee5dc12010-06-24 10:42:46 +0000669 if (CI->getArgOperand(0) == CI->getArgOperand(1))
670 return B.CreateBitCast(CI->getArgOperand(0), CI->getType());
Mikhail Glushenkoved5cb592010-01-04 07:55:25 +0000671
Benjamin Kramer386e9182010-06-15 21:34:25 +0000672 // fold strstr(a, b) == a -> strncmp(a, b, strlen(b)) == 0
Gabor Greif8e1ebff2010-06-30 12:42:43 +0000673 if (TD && IsOnlyUsedInEqualityComparison(CI, CI->getArgOperand(0))) {
674 Value *StrLen = EmitStrLen(CI->getArgOperand(1), B, TD);
675 Value *StrNCmp = EmitStrNCmp(CI->getArgOperand(0), CI->getArgOperand(1),
Benjamin Kramer386e9182010-06-15 21:34:25 +0000676 StrLen, B, TD);
677 for (Value::use_iterator UI = CI->use_begin(), UE = CI->use_end();
678 UI != UE; ) {
Gabor Greif96f1d8e2010-07-22 13:36:47 +0000679 ICmpInst *Old = cast<ICmpInst>(*UI++);
Benjamin Kramer386e9182010-06-15 21:34:25 +0000680 Value *Cmp = B.CreateICmp(Old->getPredicate(), StrNCmp,
681 ConstantInt::getNullValue(StrNCmp->getType()),
682 "cmp");
683 Old->replaceAllUsesWith(Cmp);
684 Old->eraseFromParent();
685 }
686 return CI;
687 }
688
Chris Lattner24604112009-12-16 09:32:05 +0000689 // See if either input string is a constant string.
690 std::string SearchStr, ToFindStr;
Gabor Greifaee5dc12010-06-24 10:42:46 +0000691 bool HasStr1 = GetConstantStringInfo(CI->getArgOperand(0), SearchStr);
692 bool HasStr2 = GetConstantStringInfo(CI->getArgOperand(1), ToFindStr);
Mikhail Glushenkoved5cb592010-01-04 07:55:25 +0000693
Chris Lattner24604112009-12-16 09:32:05 +0000694 // fold strstr(x, "") -> x.
695 if (HasStr2 && ToFindStr.empty())
Gabor Greifaee5dc12010-06-24 10:42:46 +0000696 return B.CreateBitCast(CI->getArgOperand(0), CI->getType());
Mikhail Glushenkoved5cb592010-01-04 07:55:25 +0000697
Chris Lattner24604112009-12-16 09:32:05 +0000698 // If both strings are known, constant fold it.
699 if (HasStr1 && HasStr2) {
700 std::string::size_type Offset = SearchStr.find(ToFindStr);
Mikhail Glushenkoved5cb592010-01-04 07:55:25 +0000701
Chris Lattner24604112009-12-16 09:32:05 +0000702 if (Offset == std::string::npos) // strstr("foo", "bar") -> null
703 return Constant::getNullValue(CI->getType());
704
705 // strstr("abcd", "bc") -> gep((char*)"abcd", 1)
Gabor Greifaee5dc12010-06-24 10:42:46 +0000706 Value *Result = CastToCStr(CI->getArgOperand(0), B);
Chris Lattner24604112009-12-16 09:32:05 +0000707 Result = B.CreateConstInBoundsGEP1_64(Result, Offset, "strstr");
708 return B.CreateBitCast(Result, CI->getType());
709 }
Mikhail Glushenkoved5cb592010-01-04 07:55:25 +0000710
Chris Lattner24604112009-12-16 09:32:05 +0000711 // fold strstr(x, "y") -> strchr(x, 'y').
712 if (HasStr2 && ToFindStr.size() == 1)
Gabor Greifa3997812010-07-22 10:37:47 +0000713 return B.CreateBitCast(EmitStrChr(CI->getArgOperand(0),
714 ToFindStr[0], B, TD), CI->getType());
Chris Lattner24604112009-12-16 09:32:05 +0000715 return 0;
716 }
717};
Mikhail Glushenkoved5cb592010-01-04 07:55:25 +0000718
Nick Lewycky4c498412009-02-13 15:31:46 +0000719
720//===---------------------------------------===//
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000721// 'memcmp' Optimizations
722
Chris Lattner3e8b6632009-09-02 06:11:42 +0000723struct MemCmpOpt : public LibCallOptimization {
Eric Christopher7a61d702008-08-08 19:39:37 +0000724 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000725 const FunctionType *FT = Callee->getFunctionType();
Duncan Sands1df98592010-02-16 11:11:14 +0000726 if (FT->getNumParams() != 3 || !FT->getParamType(0)->isPointerTy() ||
727 !FT->getParamType(1)->isPointerTy() ||
Duncan Sandsb0bc6c32010-02-15 16:12:20 +0000728 !FT->getReturnType()->isIntegerTy(32))
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000729 return 0;
Duncan Sandsec00fcb2008-05-19 09:27:24 +0000730
Gabor Greifaee5dc12010-06-24 10:42:46 +0000731 Value *LHS = CI->getArgOperand(0), *RHS = CI->getArgOperand(1);
Duncan Sandsec00fcb2008-05-19 09:27:24 +0000732
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000733 if (LHS == RHS) // memcmp(s,s,x) -> 0
Owen Andersona7235ea2009-07-31 20:28:14 +0000734 return Constant::getNullValue(CI->getType());
Duncan Sandsec00fcb2008-05-19 09:27:24 +0000735
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000736 // Make sure we have a constant length.
Gabor Greifaee5dc12010-06-24 10:42:46 +0000737 ConstantInt *LenC = dyn_cast<ConstantInt>(CI->getArgOperand(2));
Chris Lattner56b4f2b2008-05-01 06:39:12 +0000738 if (!LenC) return 0;
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000739 uint64_t Len = LenC->getZExtValue();
Duncan Sandsec00fcb2008-05-19 09:27:24 +0000740
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000741 if (Len == 0) // memcmp(s1,s2,0) -> 0
Owen Andersona7235ea2009-07-31 20:28:14 +0000742 return Constant::getNullValue(CI->getType());
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000743
Benjamin Kramer48aefe12010-05-25 22:53:43 +0000744 // memcmp(S1,S2,1) -> *(unsigned char*)LHS - *(unsigned char*)RHS
745 if (Len == 1) {
746 Value *LHSV = B.CreateZExt(B.CreateLoad(CastToCStr(LHS, B), "lhsc"),
747 CI->getType(), "lhsv");
748 Value *RHSV = B.CreateZExt(B.CreateLoad(CastToCStr(RHS, B), "rhsc"),
749 CI->getType(), "rhsv");
Benjamin Kramer1464c1d2010-05-26 09:45:04 +0000750 return B.CreateSub(LHSV, RHSV, "chardiff");
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000751 }
Duncan Sandsec00fcb2008-05-19 09:27:24 +0000752
Benjamin Kramer992a6372009-11-05 17:44:22 +0000753 // Constant folding: memcmp(x, y, l) -> cnst (all arguments are constant)
754 std::string LHSStr, RHSStr;
755 if (GetConstantStringInfo(LHS, LHSStr) &&
756 GetConstantStringInfo(RHS, RHSStr)) {
757 // Make sure we're not reading out-of-bounds memory.
758 if (Len > LHSStr.length() || Len > RHSStr.length())
759 return 0;
760 uint64_t Ret = memcmp(LHSStr.data(), RHSStr.data(), Len);
761 return ConstantInt::get(CI->getType(), Ret);
762 }
763
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000764 return 0;
765 }
766};
767
768//===---------------------------------------===//
769// 'memcpy' Optimizations
770
Chris Lattner3e8b6632009-09-02 06:11:42 +0000771struct MemCpyOpt : public LibCallOptimization {
Eric Christopher7a61d702008-08-08 19:39:37 +0000772 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
Dan Gohmanf14d9192009-08-18 00:48:13 +0000773 // These optimizations require TargetData.
774 if (!TD) return 0;
775
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000776 const FunctionType *FT = Callee->getFunctionType();
777 if (FT->getNumParams() != 3 || FT->getReturnType() != FT->getParamType(0) ||
Duncan Sands1df98592010-02-16 11:11:14 +0000778 !FT->getParamType(0)->isPointerTy() ||
779 !FT->getParamType(1)->isPointerTy() ||
Owen Anderson1d0be152009-08-13 21:58:54 +0000780 FT->getParamType(2) != TD->getIntPtrType(*Context))
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000781 return 0;
782
783 // memcpy(x, y, n) -> llvm.memcpy(x, y, n, 1)
Benjamin Kramera1bf4ca2010-12-27 00:16:46 +0000784 B.CreateMemCpy(CI->getArgOperand(0), CI->getArgOperand(1),
785 CI->getArgOperand(2), 1);
Gabor Greifaee5dc12010-06-24 10:42:46 +0000786 return CI->getArgOperand(0);
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000787 }
788};
789
Eli Friedmand83ae7d2008-11-30 08:32:11 +0000790//===---------------------------------------===//
791// 'memmove' Optimizations
792
Chris Lattner3e8b6632009-09-02 06:11:42 +0000793struct MemMoveOpt : public LibCallOptimization {
Eli Friedmand83ae7d2008-11-30 08:32:11 +0000794 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
Dan Gohmanf14d9192009-08-18 00:48:13 +0000795 // These optimizations require TargetData.
796 if (!TD) return 0;
797
Eli Friedmand83ae7d2008-11-30 08:32:11 +0000798 const FunctionType *FT = Callee->getFunctionType();
799 if (FT->getNumParams() != 3 || FT->getReturnType() != FT->getParamType(0) ||
Duncan Sands1df98592010-02-16 11:11:14 +0000800 !FT->getParamType(0)->isPointerTy() ||
801 !FT->getParamType(1)->isPointerTy() ||
Owen Anderson1d0be152009-08-13 21:58:54 +0000802 FT->getParamType(2) != TD->getIntPtrType(*Context))
Eli Friedmand83ae7d2008-11-30 08:32:11 +0000803 return 0;
804
805 // memmove(x, y, n) -> llvm.memmove(x, y, n, 1)
Benjamin Kramera1bf4ca2010-12-27 00:16:46 +0000806 B.CreateMemMove(CI->getArgOperand(0), CI->getArgOperand(1),
807 CI->getArgOperand(2), 1);
Gabor Greifaee5dc12010-06-24 10:42:46 +0000808 return CI->getArgOperand(0);
Eli Friedmand83ae7d2008-11-30 08:32:11 +0000809 }
810};
811
812//===---------------------------------------===//
813// 'memset' Optimizations
814
Chris Lattner3e8b6632009-09-02 06:11:42 +0000815struct MemSetOpt : public LibCallOptimization {
Eli Friedmand83ae7d2008-11-30 08:32:11 +0000816 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
Dan Gohmanf14d9192009-08-18 00:48:13 +0000817 // These optimizations require TargetData.
818 if (!TD) return 0;
819
Eli Friedmand83ae7d2008-11-30 08:32:11 +0000820 const FunctionType *FT = Callee->getFunctionType();
821 if (FT->getNumParams() != 3 || FT->getReturnType() != FT->getParamType(0) ||
Duncan Sands1df98592010-02-16 11:11:14 +0000822 !FT->getParamType(0)->isPointerTy() ||
823 !FT->getParamType(1)->isIntegerTy() ||
Owen Anderson1d0be152009-08-13 21:58:54 +0000824 FT->getParamType(2) != TD->getIntPtrType(*Context))
Eli Friedmand83ae7d2008-11-30 08:32:11 +0000825 return 0;
826
827 // memset(p, v, n) -> llvm.memset(p, v, n, 1)
Benjamin Kramera1bf4ca2010-12-27 00:16:46 +0000828 Value *Val = B.CreateIntCast(CI->getArgOperand(1), B.getInt8Ty(), false);
829 B.CreateMemSet(CI->getArgOperand(0), Val, CI->getArgOperand(2), 1);
Gabor Greifaee5dc12010-06-24 10:42:46 +0000830 return CI->getArgOperand(0);
Eli Friedmand83ae7d2008-11-30 08:32:11 +0000831 }
832};
833
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000834//===----------------------------------------------------------------------===//
835// Math Library Optimizations
836//===----------------------------------------------------------------------===//
837
838//===---------------------------------------===//
839// 'pow*' Optimizations
840
Chris Lattner3e8b6632009-09-02 06:11:42 +0000841struct PowOpt : public LibCallOptimization {
Eric Christopher7a61d702008-08-08 19:39:37 +0000842 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000843 const FunctionType *FT = Callee->getFunctionType();
844 // Just make sure this has 2 arguments of the same FP type, which match the
845 // result type.
846 if (FT->getNumParams() != 2 || FT->getReturnType() != FT->getParamType(0) ||
847 FT->getParamType(0) != FT->getParamType(1) ||
Duncan Sandsb0bc6c32010-02-15 16:12:20 +0000848 !FT->getParamType(0)->isFloatingPointTy())
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000849 return 0;
Eric Christopher37c8b862009-10-07 21:14:25 +0000850
Gabor Greifaee5dc12010-06-24 10:42:46 +0000851 Value *Op1 = CI->getArgOperand(0), *Op2 = CI->getArgOperand(1);
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000852 if (ConstantFP *Op1C = dyn_cast<ConstantFP>(Op1)) {
853 if (Op1C->isExactlyValue(1.0)) // pow(1.0, x) -> 1.0
854 return Op1C;
855 if (Op1C->isExactlyValue(2.0)) // pow(2.0, x) -> exp2(x)
Dan Gohman76926b62009-09-26 18:10:13 +0000856 return EmitUnaryFloatFnCall(Op2, "exp2", B, Callee->getAttributes());
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000857 }
Eric Christopher37c8b862009-10-07 21:14:25 +0000858
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000859 ConstantFP *Op2C = dyn_cast<ConstantFP>(Op2);
860 if (Op2C == 0) return 0;
Eric Christopher37c8b862009-10-07 21:14:25 +0000861
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000862 if (Op2C->getValueAPF().isZero()) // pow(x, 0.0) -> 1.0
Owen Anderson6f83c9c2009-07-27 20:59:43 +0000863 return ConstantFP::get(CI->getType(), 1.0);
Eric Christopher37c8b862009-10-07 21:14:25 +0000864
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000865 if (Op2C->isExactlyValue(0.5)) {
Dan Gohman79cb8402009-09-25 23:10:17 +0000866 // Expand pow(x, 0.5) to (x == -infinity ? +infinity : fabs(sqrt(x))).
867 // This is faster than calling pow, and still handles negative zero
868 // and negative infinite correctly.
869 // TODO: In fast-math mode, this could be just sqrt(x).
870 // TODO: In finite-only mode, this could be just fabs(sqrt(x)).
Dan Gohmana23643d2009-09-25 23:40:21 +0000871 Value *Inf = ConstantFP::getInfinity(CI->getType());
872 Value *NegInf = ConstantFP::getInfinity(CI->getType(), true);
Dan Gohman76926b62009-09-26 18:10:13 +0000873 Value *Sqrt = EmitUnaryFloatFnCall(Op1, "sqrt", B,
874 Callee->getAttributes());
875 Value *FAbs = EmitUnaryFloatFnCall(Sqrt, "fabs", B,
876 Callee->getAttributes());
Dan Gohman79cb8402009-09-25 23:10:17 +0000877 Value *FCmp = B.CreateFCmpOEQ(Op1, NegInf, "tmp");
878 Value *Sel = B.CreateSelect(FCmp, Inf, FAbs, "tmp");
879 return Sel;
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000880 }
Eric Christopher37c8b862009-10-07 21:14:25 +0000881
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000882 if (Op2C->isExactlyValue(1.0)) // pow(x, 1.0) -> x
883 return Op1;
884 if (Op2C->isExactlyValue(2.0)) // pow(x, 2.0) -> x*x
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000885 return B.CreateFMul(Op1, Op1, "pow2");
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000886 if (Op2C->isExactlyValue(-1.0)) // pow(x, -1.0) -> 1.0/x
Owen Anderson6f83c9c2009-07-27 20:59:43 +0000887 return B.CreateFDiv(ConstantFP::get(CI->getType(), 1.0),
Owen Andersonfa5cbd62009-07-03 19:42:02 +0000888 Op1, "powrecip");
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000889 return 0;
890 }
891};
892
893//===---------------------------------------===//
Chris Lattnere818f772008-05-02 18:43:35 +0000894// 'exp2' Optimizations
895
Chris Lattner3e8b6632009-09-02 06:11:42 +0000896struct Exp2Opt : public LibCallOptimization {
Eric Christopher7a61d702008-08-08 19:39:37 +0000897 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
Chris Lattnere818f772008-05-02 18:43:35 +0000898 const FunctionType *FT = Callee->getFunctionType();
899 // Just make sure this has 1 argument of FP type, which matches the
900 // result type.
901 if (FT->getNumParams() != 1 || FT->getReturnType() != FT->getParamType(0) ||
Duncan Sandsb0bc6c32010-02-15 16:12:20 +0000902 !FT->getParamType(0)->isFloatingPointTy())
Chris Lattnere818f772008-05-02 18:43:35 +0000903 return 0;
Eric Christopher37c8b862009-10-07 21:14:25 +0000904
Gabor Greifaee5dc12010-06-24 10:42:46 +0000905 Value *Op = CI->getArgOperand(0);
Chris Lattnere818f772008-05-02 18:43:35 +0000906 // Turn exp2(sitofp(x)) -> ldexp(1.0, sext(x)) if sizeof(x) <= 32
907 // Turn exp2(uitofp(x)) -> ldexp(1.0, zext(x)) if sizeof(x) < 32
908 Value *LdExpArg = 0;
909 if (SIToFPInst *OpC = dyn_cast<SIToFPInst>(Op)) {
910 if (OpC->getOperand(0)->getType()->getPrimitiveSizeInBits() <= 32)
Benjamin Kramera1bf4ca2010-12-27 00:16:46 +0000911 LdExpArg = B.CreateSExt(OpC->getOperand(0), B.getInt32Ty(), "tmp");
Chris Lattnere818f772008-05-02 18:43:35 +0000912 } else if (UIToFPInst *OpC = dyn_cast<UIToFPInst>(Op)) {
913 if (OpC->getOperand(0)->getType()->getPrimitiveSizeInBits() < 32)
Benjamin Kramera1bf4ca2010-12-27 00:16:46 +0000914 LdExpArg = B.CreateZExt(OpC->getOperand(0), B.getInt32Ty(), "tmp");
Chris Lattnere818f772008-05-02 18:43:35 +0000915 }
Anton Korobeynikov9547cdf2009-06-18 20:05:31 +0000916
Chris Lattnere818f772008-05-02 18:43:35 +0000917 if (LdExpArg) {
918 const char *Name;
Chris Lattnercf0fe8d2009-10-05 05:54:46 +0000919 if (Op->getType()->isFloatTy())
Chris Lattnere818f772008-05-02 18:43:35 +0000920 Name = "ldexpf";
Chris Lattnercf0fe8d2009-10-05 05:54:46 +0000921 else if (Op->getType()->isDoubleTy())
Chris Lattnere818f772008-05-02 18:43:35 +0000922 Name = "ldexp";
923 else
924 Name = "ldexpl";
925
Owen Anderson6f83c9c2009-07-27 20:59:43 +0000926 Constant *One = ConstantFP::get(*Context, APFloat(1.0f));
Chris Lattnercf0fe8d2009-10-05 05:54:46 +0000927 if (!Op->getType()->isFloatTy())
Owen Andersonbaf3c402009-07-29 18:55:55 +0000928 One = ConstantExpr::getFPExtend(One, Op->getType());
Chris Lattnere818f772008-05-02 18:43:35 +0000929
930 Module *M = Caller->getParent();
931 Value *Callee = M->getOrInsertFunction(Name, Op->getType(),
Eric Christopher37c8b862009-10-07 21:14:25 +0000932 Op->getType(),
Benjamin Kramera1bf4ca2010-12-27 00:16:46 +0000933 B.getInt32Ty(), NULL);
Anton Korobeynikov9547cdf2009-06-18 20:05:31 +0000934 CallInst *CI = B.CreateCall2(Callee, One, LdExpArg);
935 if (const Function *F = dyn_cast<Function>(Callee->stripPointerCasts()))
936 CI->setCallingConv(F->getCallingConv());
937
938 return CI;
Chris Lattnere818f772008-05-02 18:43:35 +0000939 }
940 return 0;
941 }
942};
Chris Lattnere818f772008-05-02 18:43:35 +0000943
944//===---------------------------------------===//
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000945// Double -> Float Shrinking Optimizations for Unary Functions like 'floor'
946
Chris Lattner3e8b6632009-09-02 06:11:42 +0000947struct UnaryDoubleFPOpt : public LibCallOptimization {
Eric Christopher7a61d702008-08-08 19:39:37 +0000948 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000949 const FunctionType *FT = Callee->getFunctionType();
Chris Lattnercf0fe8d2009-10-05 05:54:46 +0000950 if (FT->getNumParams() != 1 || !FT->getReturnType()->isDoubleTy() ||
951 !FT->getParamType(0)->isDoubleTy())
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000952 return 0;
Anton Korobeynikov9547cdf2009-06-18 20:05:31 +0000953
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000954 // If this is something like 'floor((double)floatval)', convert to floorf.
Gabor Greifaee5dc12010-06-24 10:42:46 +0000955 FPExtInst *Cast = dyn_cast<FPExtInst>(CI->getArgOperand(0));
Chris Lattnercf0fe8d2009-10-05 05:54:46 +0000956 if (Cast == 0 || !Cast->getOperand(0)->getType()->isFloatTy())
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000957 return 0;
958
959 // floor((double)floatval) -> (double)floorf(floatval)
960 Value *V = Cast->getOperand(0);
Dan Gohman76926b62009-09-26 18:10:13 +0000961 V = EmitUnaryFloatFnCall(V, Callee->getName().data(), B,
962 Callee->getAttributes());
Benjamin Kramera1bf4ca2010-12-27 00:16:46 +0000963 return B.CreateFPExt(V, B.getDoubleTy());
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000964 }
965};
966
967//===----------------------------------------------------------------------===//
968// Integer Optimizations
969//===----------------------------------------------------------------------===//
970
971//===---------------------------------------===//
972// 'ffs*' Optimizations
973
Chris Lattner3e8b6632009-09-02 06:11:42 +0000974struct FFSOpt : public LibCallOptimization {
Eric Christopher7a61d702008-08-08 19:39:37 +0000975 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000976 const FunctionType *FT = Callee->getFunctionType();
977 // Just make sure this has 2 arguments of the same FP type, which match the
978 // result type.
Eric Christopher37c8b862009-10-07 21:14:25 +0000979 if (FT->getNumParams() != 1 ||
Nick Lewycky10d2f4d2010-07-06 03:53:43 +0000980 !FT->getReturnType()->isIntegerTy(32) ||
Duncan Sands1df98592010-02-16 11:11:14 +0000981 !FT->getParamType(0)->isIntegerTy())
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000982 return 0;
Eric Christopher37c8b862009-10-07 21:14:25 +0000983
Gabor Greifaee5dc12010-06-24 10:42:46 +0000984 Value *Op = CI->getArgOperand(0);
Eric Christopher37c8b862009-10-07 21:14:25 +0000985
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000986 // Constant fold.
987 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op)) {
988 if (CI->getValue() == 0) // ffs(0) -> 0.
Owen Andersona7235ea2009-07-31 20:28:14 +0000989 return Constant::getNullValue(CI->getType());
Benjamin Kramera1bf4ca2010-12-27 00:16:46 +0000990 // ffs(c) -> cttz(c)+1
991 return B.getInt32(CI->getValue().countTrailingZeros() + 1);
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000992 }
Eric Christopher37c8b862009-10-07 21:14:25 +0000993
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000994 // ffs(x) -> x != 0 ? (i32)llvm.cttz(x)+1 : 0
995 const Type *ArgType = Op->getType();
996 Value *F = Intrinsic::getDeclaration(Callee->getParent(),
997 Intrinsic::cttz, &ArgType, 1);
998 Value *V = B.CreateCall(F, Op, "cttz");
Owen Andersoneed707b2009-07-24 23:12:02 +0000999 V = B.CreateAdd(V, ConstantInt::get(V->getType(), 1), "tmp");
Benjamin Kramera1bf4ca2010-12-27 00:16:46 +00001000 V = B.CreateIntCast(V, B.getInt32Ty(), false, "tmp");
Eric Christopher37c8b862009-10-07 21:14:25 +00001001
Owen Andersona7235ea2009-07-31 20:28:14 +00001002 Value *Cond = B.CreateICmpNE(Op, Constant::getNullValue(ArgType), "tmp");
Benjamin Kramera1bf4ca2010-12-27 00:16:46 +00001003 return B.CreateSelect(Cond, V, B.getInt32(0));
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001004 }
1005};
1006
1007//===---------------------------------------===//
1008// 'isdigit' Optimizations
1009
Chris Lattner3e8b6632009-09-02 06:11:42 +00001010struct IsDigitOpt : public LibCallOptimization {
Eric Christopher7a61d702008-08-08 19:39:37 +00001011 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001012 const FunctionType *FT = Callee->getFunctionType();
1013 // We require integer(i32)
Duncan Sands1df98592010-02-16 11:11:14 +00001014 if (FT->getNumParams() != 1 || !FT->getReturnType()->isIntegerTy() ||
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00001015 !FT->getParamType(0)->isIntegerTy(32))
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001016 return 0;
Eric Christopher37c8b862009-10-07 21:14:25 +00001017
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001018 // isdigit(c) -> (c-'0') <u 10
Gabor Greifaee5dc12010-06-24 10:42:46 +00001019 Value *Op = CI->getArgOperand(0);
Benjamin Kramera1bf4ca2010-12-27 00:16:46 +00001020 Op = B.CreateSub(Op, B.getInt32('0'), "isdigittmp");
1021 Op = B.CreateICmpULT(Op, B.getInt32(10), "isdigit");
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001022 return B.CreateZExt(Op, CI->getType());
1023 }
1024};
1025
1026//===---------------------------------------===//
1027// 'isascii' Optimizations
1028
Chris Lattner3e8b6632009-09-02 06:11:42 +00001029struct IsAsciiOpt : public LibCallOptimization {
Eric Christopher7a61d702008-08-08 19:39:37 +00001030 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001031 const FunctionType *FT = Callee->getFunctionType();
1032 // We require integer(i32)
Duncan Sands1df98592010-02-16 11:11:14 +00001033 if (FT->getNumParams() != 1 || !FT->getReturnType()->isIntegerTy() ||
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00001034 !FT->getParamType(0)->isIntegerTy(32))
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001035 return 0;
Eric Christopher37c8b862009-10-07 21:14:25 +00001036
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001037 // isascii(c) -> c <u 128
Gabor Greifaee5dc12010-06-24 10:42:46 +00001038 Value *Op = CI->getArgOperand(0);
Benjamin Kramera1bf4ca2010-12-27 00:16:46 +00001039 Op = B.CreateICmpULT(Op, B.getInt32(128), "isascii");
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001040 return B.CreateZExt(Op, CI->getType());
1041 }
1042};
Eric Christopher37c8b862009-10-07 21:14:25 +00001043
Chris Lattner313f0e62008-06-09 08:26:51 +00001044//===---------------------------------------===//
1045// 'abs', 'labs', 'llabs' Optimizations
1046
Chris Lattner3e8b6632009-09-02 06:11:42 +00001047struct AbsOpt : public LibCallOptimization {
Eric Christopher7a61d702008-08-08 19:39:37 +00001048 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
Chris Lattner313f0e62008-06-09 08:26:51 +00001049 const FunctionType *FT = Callee->getFunctionType();
1050 // We require integer(integer) where the types agree.
Duncan Sands1df98592010-02-16 11:11:14 +00001051 if (FT->getNumParams() != 1 || !FT->getReturnType()->isIntegerTy() ||
Chris Lattner313f0e62008-06-09 08:26:51 +00001052 FT->getParamType(0) != FT->getReturnType())
1053 return 0;
Eric Christopher37c8b862009-10-07 21:14:25 +00001054
Chris Lattner313f0e62008-06-09 08:26:51 +00001055 // abs(x) -> x >s -1 ? x : -x
Gabor Greifaee5dc12010-06-24 10:42:46 +00001056 Value *Op = CI->getArgOperand(0);
Benjamin Kramera1bf4ca2010-12-27 00:16:46 +00001057 Value *Pos = B.CreateICmpSGT(Op, Constant::getAllOnesValue(Op->getType()),
Chris Lattner313f0e62008-06-09 08:26:51 +00001058 "ispos");
1059 Value *Neg = B.CreateNeg(Op, "neg");
1060 return B.CreateSelect(Pos, Op, Neg);
1061 }
1062};
Eric Christopher37c8b862009-10-07 21:14:25 +00001063
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001064
1065//===---------------------------------------===//
1066// 'toascii' Optimizations
1067
Chris Lattner3e8b6632009-09-02 06:11:42 +00001068struct ToAsciiOpt : public LibCallOptimization {
Eric Christopher7a61d702008-08-08 19:39:37 +00001069 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001070 const FunctionType *FT = Callee->getFunctionType();
1071 // We require i32(i32)
1072 if (FT->getNumParams() != 1 || FT->getReturnType() != FT->getParamType(0) ||
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00001073 !FT->getParamType(0)->isIntegerTy(32))
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001074 return 0;
Eric Christopher37c8b862009-10-07 21:14:25 +00001075
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001076 // isascii(c) -> c & 0x7f
Gabor Greifaee5dc12010-06-24 10:42:46 +00001077 return B.CreateAnd(CI->getArgOperand(0),
Owen Andersoneed707b2009-07-24 23:12:02 +00001078 ConstantInt::get(CI->getType(),0x7F));
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001079 }
1080};
1081
1082//===----------------------------------------------------------------------===//
1083// Formatting and IO Optimizations
1084//===----------------------------------------------------------------------===//
1085
1086//===---------------------------------------===//
1087// 'printf' Optimizations
1088
Chris Lattner3e8b6632009-09-02 06:11:42 +00001089struct PrintFOpt : public LibCallOptimization {
Richard Osborne36498242011-03-03 13:17:51 +00001090 Value *OptimizeFixedFormatString(Function *Callee, CallInst *CI,
1091 IRBuilder<> &B) {
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001092 // Check for a fixed format string.
Bill Wendling0582ae92009-03-13 04:39:26 +00001093 std::string FormatStr;
Gabor Greifaee5dc12010-06-24 10:42:46 +00001094 if (!GetConstantStringInfo(CI->getArgOperand(0), FormatStr))
Bill Wendling0582ae92009-03-13 04:39:26 +00001095 return 0;
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001096
1097 // Empty format string -> noop.
1098 if (FormatStr.empty()) // Tolerate printf's declared void.
Eric Christopher37c8b862009-10-07 21:14:25 +00001099 return CI->use_empty() ? (Value*)CI :
Owen Andersoneed707b2009-07-24 23:12:02 +00001100 ConstantInt::get(CI->getType(), 0);
Eric Christopher37c8b862009-10-07 21:14:25 +00001101
Daniel Dunbard02be242011-02-12 18:19:57 +00001102 // Do not do any of the following transformations if the printf return value
1103 // is used, in general the printf return value is not compatible with either
1104 // putchar() or puts().
1105 if (!CI->use_empty())
1106 return 0;
1107
1108 // printf("x") -> putchar('x'), even for '%'.
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001109 if (FormatStr.size() == 1) {
Benjamin Kramera1bf4ca2010-12-27 00:16:46 +00001110 Value *Res = EmitPutChar(B.getInt32(FormatStr[0]), B, TD);
Chris Lattner74965f22009-11-09 04:57:04 +00001111 if (CI->use_empty()) return CI;
1112 return B.CreateIntCast(Res, CI->getType(), true);
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001113 }
Eric Christopher37c8b862009-10-07 21:14:25 +00001114
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001115 // printf("foo\n") --> puts("foo")
1116 if (FormatStr[FormatStr.size()-1] == '\n' &&
1117 FormatStr.find('%') == std::string::npos) { // no format characters.
1118 // Create a string literal with no \n on it. We expect the constant merge
1119 // pass to be run after this pass, to merge duplicate strings.
1120 FormatStr.erase(FormatStr.end()-1);
Owen Anderson1d0be152009-08-13 21:58:54 +00001121 Constant *C = ConstantArray::get(*Context, FormatStr, true);
Owen Andersone9b11b42009-07-08 19:03:57 +00001122 C = new GlobalVariable(*Callee->getParent(), C->getType(), true,
1123 GlobalVariable::InternalLinkage, C, "str");
Eric Christopherb6174e32010-03-05 22:25:30 +00001124 EmitPutS(C, B, TD);
Eric Christopher37c8b862009-10-07 21:14:25 +00001125 return CI->use_empty() ? (Value*)CI :
Owen Andersoneed707b2009-07-24 23:12:02 +00001126 ConstantInt::get(CI->getType(), FormatStr.size()+1);
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001127 }
Eric Christopher37c8b862009-10-07 21:14:25 +00001128
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001129 // Optimize specific format strings.
Gabor Greifaee5dc12010-06-24 10:42:46 +00001130 // printf("%c", chr) --> putchar(chr)
Gabor Greif8e1ebff2010-06-30 12:42:43 +00001131 if (FormatStr == "%c" && CI->getNumArgOperands() > 1 &&
Gabor Greifaee5dc12010-06-24 10:42:46 +00001132 CI->getArgOperand(1)->getType()->isIntegerTy()) {
1133 Value *Res = EmitPutChar(CI->getArgOperand(1), B, TD);
Eric Christopher80bf1d52009-11-21 01:01:30 +00001134
Chris Lattner74965f22009-11-09 04:57:04 +00001135 if (CI->use_empty()) return CI;
1136 return B.CreateIntCast(Res, CI->getType(), true);
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001137 }
Eric Christopher37c8b862009-10-07 21:14:25 +00001138
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001139 // printf("%s\n", str) --> puts(str)
Gabor Greif8e1ebff2010-06-30 12:42:43 +00001140 if (FormatStr == "%s\n" && CI->getNumArgOperands() > 1 &&
Daniel Dunbard02be242011-02-12 18:19:57 +00001141 CI->getArgOperand(1)->getType()->isPointerTy()) {
Gabor Greifaee5dc12010-06-24 10:42:46 +00001142 EmitPutS(CI->getArgOperand(1), B, TD);
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001143 return CI;
1144 }
1145 return 0;
1146 }
Richard Osborne36498242011-03-03 13:17:51 +00001147
1148 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
1149 // Require one fixed pointer argument and an integer/void result.
1150 const FunctionType *FT = Callee->getFunctionType();
1151 if (FT->getNumParams() < 1 || !FT->getParamType(0)->isPointerTy() ||
1152 !(FT->getReturnType()->isIntegerTy() ||
1153 FT->getReturnType()->isVoidTy()))
1154 return 0;
1155
1156 if (Value *V = OptimizeFixedFormatString(Callee, CI, B)) {
1157 return V;
1158 }
1159
1160 // printf(format, ...) -> iprintf(format, ...) if no floating point
1161 // arguments.
1162 if (TLI->has(LibFunc::iprintf) && !CallHasFloatingPointArgument(CI)) {
1163 Module *M = B.GetInsertBlock()->getParent()->getParent();
1164 Constant *IPrintFFn =
1165 M->getOrInsertFunction("iprintf", FT, Callee->getAttributes());
1166 CallInst *New = cast<CallInst>(CI->clone());
1167 New->setCalledFunction(IPrintFFn);
1168 B.Insert(New);
1169 return New;
1170 }
1171 return 0;
1172 }
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001173};
1174
1175//===---------------------------------------===//
1176// 'sprintf' Optimizations
1177
Chris Lattner3e8b6632009-09-02 06:11:42 +00001178struct SPrintFOpt : public LibCallOptimization {
Richard Osborne419454a2011-03-03 14:09:28 +00001179 Value *OptimizeFixedFormatString(Function *Callee, CallInst *CI,
1180 IRBuilder<> &B) {
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001181 // Check for a fixed format string.
Bill Wendling0582ae92009-03-13 04:39:26 +00001182 std::string FormatStr;
Gabor Greifaee5dc12010-06-24 10:42:46 +00001183 if (!GetConstantStringInfo(CI->getArgOperand(1), FormatStr))
Bill Wendling0582ae92009-03-13 04:39:26 +00001184 return 0;
Eric Christopher37c8b862009-10-07 21:14:25 +00001185
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001186 // If we just have a format string (nothing else crazy) transform it.
Gabor Greif8e1ebff2010-06-30 12:42:43 +00001187 if (CI->getNumArgOperands() == 2) {
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001188 // Make sure there's no % in the constant array. We could try to handle
1189 // %% -> % in the future if we cared.
1190 for (unsigned i = 0, e = FormatStr.size(); i != e; ++i)
1191 if (FormatStr[i] == '%')
1192 return 0; // we found a format specifier, bail out.
Dan Gohmanf14d9192009-08-18 00:48:13 +00001193
1194 // These optimizations require TargetData.
1195 if (!TD) return 0;
1196
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001197 // sprintf(str, fmt) -> llvm.memcpy(str, fmt, strlen(fmt)+1, 1)
Benjamin Kramera1bf4ca2010-12-27 00:16:46 +00001198 B.CreateMemCpy(CI->getArgOperand(0), CI->getArgOperand(1),
1199 ConstantInt::get(TD->getIntPtrType(*Context), // Copy the
1200 FormatStr.size() + 1), 1); // nul byte.
Owen Andersoneed707b2009-07-24 23:12:02 +00001201 return ConstantInt::get(CI->getType(), FormatStr.size());
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001202 }
Eric Christopher37c8b862009-10-07 21:14:25 +00001203
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001204 // The remaining optimizations require the format string to be "%s" or "%c"
1205 // and have an extra operand.
Gabor Greif8e1ebff2010-06-30 12:42:43 +00001206 if (FormatStr.size() != 2 || FormatStr[0] != '%' ||
1207 CI->getNumArgOperands() < 3)
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001208 return 0;
Eric Christopher37c8b862009-10-07 21:14:25 +00001209
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001210 // Decode the second character of the format string.
1211 if (FormatStr[1] == 'c') {
Chris Lattner56b4f2b2008-05-01 06:39:12 +00001212 // sprintf(dst, "%c", chr) --> *(i8*)dst = chr; *((i8*)dst+1) = 0
Gabor Greifaee5dc12010-06-24 10:42:46 +00001213 if (!CI->getArgOperand(2)->getType()->isIntegerTy()) return 0;
Benjamin Kramera1bf4ca2010-12-27 00:16:46 +00001214 Value *V = B.CreateTrunc(CI->getArgOperand(2), B.getInt8Ty(), "char");
Gabor Greifaee5dc12010-06-24 10:42:46 +00001215 Value *Ptr = CastToCStr(CI->getArgOperand(0), B);
Chris Lattner56b4f2b2008-05-01 06:39:12 +00001216 B.CreateStore(V, Ptr);
Benjamin Kramera1bf4ca2010-12-27 00:16:46 +00001217 Ptr = B.CreateGEP(Ptr, B.getInt32(1), "nul");
1218 B.CreateStore(B.getInt8(0), Ptr);
Eric Christopher37c8b862009-10-07 21:14:25 +00001219
Owen Andersoneed707b2009-07-24 23:12:02 +00001220 return ConstantInt::get(CI->getType(), 1);
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001221 }
Eric Christopher37c8b862009-10-07 21:14:25 +00001222
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001223 if (FormatStr[1] == 's') {
Dan Gohmanf14d9192009-08-18 00:48:13 +00001224 // These optimizations require TargetData.
1225 if (!TD) return 0;
1226
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001227 // sprintf(dest, "%s", str) -> llvm.memcpy(dest, str, strlen(str)+1, 1)
Gabor Greifaee5dc12010-06-24 10:42:46 +00001228 if (!CI->getArgOperand(2)->getType()->isPointerTy()) return 0;
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001229
Gabor Greifaee5dc12010-06-24 10:42:46 +00001230 Value *Len = EmitStrLen(CI->getArgOperand(2), B, TD);
Owen Andersonfa5cbd62009-07-03 19:42:02 +00001231 Value *IncLen = B.CreateAdd(Len,
Owen Andersoneed707b2009-07-24 23:12:02 +00001232 ConstantInt::get(Len->getType(), 1),
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001233 "leninc");
Benjamin Kramera1bf4ca2010-12-27 00:16:46 +00001234 B.CreateMemCpy(CI->getArgOperand(0), CI->getArgOperand(2), IncLen, 1);
Eric Christopher37c8b862009-10-07 21:14:25 +00001235
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001236 // The sprintf result is the unincremented number of bytes in the string.
1237 return B.CreateIntCast(Len, CI->getType(), false);
1238 }
1239 return 0;
1240 }
Richard Osborne419454a2011-03-03 14:09:28 +00001241
1242 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
1243 // Require two fixed pointer arguments and an integer result.
1244 const FunctionType *FT = Callee->getFunctionType();
1245 if (FT->getNumParams() != 2 || !FT->getParamType(0)->isPointerTy() ||
1246 !FT->getParamType(1)->isPointerTy() ||
1247 !FT->getReturnType()->isIntegerTy())
1248 return 0;
1249
1250 if (Value *V = OptimizeFixedFormatString(Callee, CI, B)) {
1251 return V;
1252 }
1253
Richard Osborneea2578c2011-03-03 14:21:22 +00001254 // sprintf(str, format, ...) -> siprintf(str, format, ...) if no floating
Richard Osborne419454a2011-03-03 14:09:28 +00001255 // point arguments.
1256 if (TLI->has(LibFunc::siprintf) && !CallHasFloatingPointArgument(CI)) {
1257 Module *M = B.GetInsertBlock()->getParent()->getParent();
1258 Constant *SIPrintFFn =
1259 M->getOrInsertFunction("siprintf", FT, Callee->getAttributes());
1260 CallInst *New = cast<CallInst>(CI->clone());
1261 New->setCalledFunction(SIPrintFFn);
1262 B.Insert(New);
1263 return New;
1264 }
1265 return 0;
1266 }
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001267};
1268
1269//===---------------------------------------===//
1270// 'fwrite' Optimizations
1271
Chris Lattner3e8b6632009-09-02 06:11:42 +00001272struct FWriteOpt : public LibCallOptimization {
Eric Christopher7a61d702008-08-08 19:39:37 +00001273 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001274 // Require a pointer, an integer, an integer, a pointer, returning integer.
1275 const FunctionType *FT = Callee->getFunctionType();
Duncan Sands1df98592010-02-16 11:11:14 +00001276 if (FT->getNumParams() != 4 || !FT->getParamType(0)->isPointerTy() ||
1277 !FT->getParamType(1)->isIntegerTy() ||
1278 !FT->getParamType(2)->isIntegerTy() ||
1279 !FT->getParamType(3)->isPointerTy() ||
1280 !FT->getReturnType()->isIntegerTy())
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001281 return 0;
Eric Christopher37c8b862009-10-07 21:14:25 +00001282
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001283 // Get the element size and count.
Gabor Greifaee5dc12010-06-24 10:42:46 +00001284 ConstantInt *SizeC = dyn_cast<ConstantInt>(CI->getArgOperand(1));
1285 ConstantInt *CountC = dyn_cast<ConstantInt>(CI->getArgOperand(2));
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001286 if (!SizeC || !CountC) return 0;
1287 uint64_t Bytes = SizeC->getZExtValue()*CountC->getZExtValue();
Eric Christopher37c8b862009-10-07 21:14:25 +00001288
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001289 // If this is writing zero records, remove the call (it's a noop).
1290 if (Bytes == 0)
Owen Andersoneed707b2009-07-24 23:12:02 +00001291 return ConstantInt::get(CI->getType(), 0);
Eric Christopher37c8b862009-10-07 21:14:25 +00001292
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001293 // If this is writing one byte, turn it into fputc.
1294 if (Bytes == 1) { // fwrite(S,1,1,F) -> fputc(S[0],F)
Gabor Greifaee5dc12010-06-24 10:42:46 +00001295 Value *Char = B.CreateLoad(CastToCStr(CI->getArgOperand(0), B), "char");
1296 EmitFPutC(Char, CI->getArgOperand(3), B, TD);
Owen Andersoneed707b2009-07-24 23:12:02 +00001297 return ConstantInt::get(CI->getType(), 1);
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001298 }
1299
1300 return 0;
1301 }
1302};
1303
1304//===---------------------------------------===//
1305// 'fputs' Optimizations
1306
Chris Lattner3e8b6632009-09-02 06:11:42 +00001307struct FPutsOpt : public LibCallOptimization {
Eric Christopher7a61d702008-08-08 19:39:37 +00001308 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
Dan Gohmanf14d9192009-08-18 00:48:13 +00001309 // These optimizations require TargetData.
1310 if (!TD) return 0;
1311
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001312 // Require two pointers. Also, we can't optimize if return value is used.
1313 const FunctionType *FT = Callee->getFunctionType();
Duncan Sands1df98592010-02-16 11:11:14 +00001314 if (FT->getNumParams() != 2 || !FT->getParamType(0)->isPointerTy() ||
1315 !FT->getParamType(1)->isPointerTy() ||
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001316 !CI->use_empty())
1317 return 0;
Eric Christopher37c8b862009-10-07 21:14:25 +00001318
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001319 // fputs(s,F) --> fwrite(s,1,strlen(s),F)
Gabor Greifaee5dc12010-06-24 10:42:46 +00001320 uint64_t Len = GetStringLength(CI->getArgOperand(0));
Chris Lattner56b4f2b2008-05-01 06:39:12 +00001321 if (!Len) return 0;
Gabor Greifaee5dc12010-06-24 10:42:46 +00001322 EmitFWrite(CI->getArgOperand(0),
Owen Anderson1d0be152009-08-13 21:58:54 +00001323 ConstantInt::get(TD->getIntPtrType(*Context), Len-1),
Gabor Greifaee5dc12010-06-24 10:42:46 +00001324 CI->getArgOperand(1), B, TD);
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001325 return CI; // Known to have no uses (see above).
1326 }
1327};
1328
1329//===---------------------------------------===//
1330// 'fprintf' Optimizations
1331
Chris Lattner3e8b6632009-09-02 06:11:42 +00001332struct FPrintFOpt : public LibCallOptimization {
Richard Osborne022708f2011-03-03 14:20:22 +00001333 Value *OptimizeFixedFormatString(Function *Callee, CallInst *CI,
1334 IRBuilder<> &B) {
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001335 // All the optimizations depend on the format string.
Bill Wendling0582ae92009-03-13 04:39:26 +00001336 std::string FormatStr;
Gabor Greifaee5dc12010-06-24 10:42:46 +00001337 if (!GetConstantStringInfo(CI->getArgOperand(1), FormatStr))
Bill Wendling0582ae92009-03-13 04:39:26 +00001338 return 0;
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001339
1340 // fprintf(F, "foo") --> fwrite("foo", 3, 1, F)
Gabor Greif8e1ebff2010-06-30 12:42:43 +00001341 if (CI->getNumArgOperands() == 2) {
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001342 for (unsigned i = 0, e = FormatStr.size(); i != e; ++i)
1343 if (FormatStr[i] == '%') // Could handle %% -> % if we cared.
Chris Lattner56b4f2b2008-05-01 06:39:12 +00001344 return 0; // We found a format specifier.
Dan Gohmanf14d9192009-08-18 00:48:13 +00001345
1346 // These optimizations require TargetData.
1347 if (!TD) return 0;
1348
Gabor Greifaee5dc12010-06-24 10:42:46 +00001349 EmitFWrite(CI->getArgOperand(1),
Mikhail Glushenkoved5cb592010-01-04 07:55:25 +00001350 ConstantInt::get(TD->getIntPtrType(*Context),
1351 FormatStr.size()),
Gabor Greifaee5dc12010-06-24 10:42:46 +00001352 CI->getArgOperand(0), B, TD);
Owen Andersoneed707b2009-07-24 23:12:02 +00001353 return ConstantInt::get(CI->getType(), FormatStr.size());
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001354 }
Eric Christopher37c8b862009-10-07 21:14:25 +00001355
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001356 // The remaining optimizations require the format string to be "%s" or "%c"
1357 // and have an extra operand.
Gabor Greif8e1ebff2010-06-30 12:42:43 +00001358 if (FormatStr.size() != 2 || FormatStr[0] != '%' ||
1359 CI->getNumArgOperands() < 3)
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001360 return 0;
Eric Christopher37c8b862009-10-07 21:14:25 +00001361
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001362 // Decode the second character of the format string.
1363 if (FormatStr[1] == 'c') {
Gabor Greifaee5dc12010-06-24 10:42:46 +00001364 // fprintf(F, "%c", chr) --> fputc(chr, F)
1365 if (!CI->getArgOperand(2)->getType()->isIntegerTy()) return 0;
1366 EmitFPutC(CI->getArgOperand(2), CI->getArgOperand(0), B, TD);
Owen Andersoneed707b2009-07-24 23:12:02 +00001367 return ConstantInt::get(CI->getType(), 1);
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001368 }
Eric Christopher37c8b862009-10-07 21:14:25 +00001369
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001370 if (FormatStr[1] == 's') {
Gabor Greifaee5dc12010-06-24 10:42:46 +00001371 // fprintf(F, "%s", str) --> fputs(str, F)
1372 if (!CI->getArgOperand(2)->getType()->isPointerTy() || !CI->use_empty())
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001373 return 0;
Gabor Greifaee5dc12010-06-24 10:42:46 +00001374 EmitFPutS(CI->getArgOperand(2), CI->getArgOperand(0), B, TD);
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001375 return CI;
1376 }
1377 return 0;
1378 }
Richard Osborne022708f2011-03-03 14:20:22 +00001379
1380 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
1381 // Require two fixed paramters as pointers and integer result.
1382 const FunctionType *FT = Callee->getFunctionType();
1383 if (FT->getNumParams() != 2 || !FT->getParamType(0)->isPointerTy() ||
1384 !FT->getParamType(1)->isPointerTy() ||
1385 !FT->getReturnType()->isIntegerTy())
1386 return 0;
1387
1388 if (Value *V = OptimizeFixedFormatString(Callee, CI, B)) {
1389 return V;
1390 }
1391
1392 // fprintf(stream, format, ...) -> fiprintf(stream, format, ...) if no
1393 // floating point arguments.
1394 if (TLI->has(LibFunc::fiprintf) && !CallHasFloatingPointArgument(CI)) {
1395 Module *M = B.GetInsertBlock()->getParent()->getParent();
1396 Constant *FIPrintFFn =
1397 M->getOrInsertFunction("fiprintf", FT, Callee->getAttributes());
1398 CallInst *New = cast<CallInst>(CI->clone());
1399 New->setCalledFunction(FIPrintFFn);
1400 B.Insert(New);
1401 return New;
1402 }
1403 return 0;
1404 }
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001405};
1406
Anders Carlsson303023d2010-11-30 06:19:18 +00001407//===---------------------------------------===//
1408// 'puts' Optimizations
1409
1410struct PutsOpt : public LibCallOptimization {
1411 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
1412 // Require one fixed pointer argument and an integer/void result.
1413 const FunctionType *FT = Callee->getFunctionType();
1414 if (FT->getNumParams() < 1 || !FT->getParamType(0)->isPointerTy() ||
1415 !(FT->getReturnType()->isIntegerTy() ||
1416 FT->getReturnType()->isVoidTy()))
1417 return 0;
1418
1419 // Check for a constant string.
1420 std::string Str;
1421 if (!GetConstantStringInfo(CI->getArgOperand(0), Str))
1422 return 0;
1423
Daniel Dunbard02be242011-02-12 18:19:57 +00001424 if (Str.empty() && CI->use_empty()) {
Anders Carlsson303023d2010-11-30 06:19:18 +00001425 // puts("") -> putchar('\n')
1426 Value *Res = EmitPutChar(B.getInt32('\n'), B, TD);
1427 if (CI->use_empty()) return CI;
1428 return B.CreateIntCast(Res, CI->getType(), true);
1429 }
1430
1431 return 0;
1432 }
1433};
1434
Bill Wendlingac178222008-05-05 21:37:59 +00001435} // end anonymous namespace.
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001436
1437//===----------------------------------------------------------------------===//
1438// SimplifyLibCalls Pass Implementation
1439//===----------------------------------------------------------------------===//
1440
1441namespace {
1442 /// This pass optimizes well known library functions from libc and libm.
1443 ///
Chris Lattner3e8b6632009-09-02 06:11:42 +00001444 class SimplifyLibCalls : public FunctionPass {
Chris Lattnerafbf4832011-02-24 07:16:14 +00001445 TargetLibraryInfo *TLI;
1446
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001447 StringMap<LibCallOptimization*> Optimizations;
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001448 // String and Memory LibCall Optimizations
Benjamin Kramer06f25cf2010-09-29 21:50:51 +00001449 StrCatOpt StrCat; StrNCatOpt StrNCat; StrChrOpt StrChr; StrRChrOpt StrRChr;
1450 StrCmpOpt StrCmp; StrNCmpOpt StrNCmp; StrCpyOpt StrCpy; StrCpyOpt StrCpyChk;
Benjamin Kramer05f585e2010-09-29 23:52:12 +00001451 StrNCpyOpt StrNCpy; StrLenOpt StrLen; StrPBrkOpt StrPBrk;
Benjamin Kramer9510a252010-09-30 00:58:35 +00001452 StrToOpt StrTo; StrSpnOpt StrSpn; StrCSpnOpt StrCSpn; StrStrOpt StrStr;
Chris Lattner24604112009-12-16 09:32:05 +00001453 MemCmpOpt MemCmp; MemCpyOpt MemCpy; MemMoveOpt MemMove; MemSetOpt MemSet;
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001454 // Math Library Optimizations
Chris Lattnere818f772008-05-02 18:43:35 +00001455 PowOpt Pow; Exp2Opt Exp2; UnaryDoubleFPOpt UnaryDoubleFP;
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001456 // Integer Optimizations
Chris Lattner313f0e62008-06-09 08:26:51 +00001457 FFSOpt FFS; AbsOpt Abs; IsDigitOpt IsDigit; IsAsciiOpt IsAscii;
1458 ToAsciiOpt ToAscii;
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001459 // Formatting and IO Optimizations
1460 SPrintFOpt SPrintF; PrintFOpt PrintF;
1461 FWriteOpt FWrite; FPutsOpt FPuts; FPrintFOpt FPrintF;
Anders Carlsson303023d2010-11-30 06:19:18 +00001462 PutsOpt Puts;
Chris Lattnerafbf4832011-02-24 07:16:14 +00001463
Nick Lewycky6cd0c042009-01-05 00:07:50 +00001464 bool Modified; // This is only used by doInitialization.
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001465 public:
1466 static char ID; // Pass identification
Owen Anderson081c34b2010-10-19 17:21:58 +00001467 SimplifyLibCalls() : FunctionPass(ID), StrCpy(false), StrCpyChk(true) {
1468 initializeSimplifyLibCallsPass(*PassRegistry::getPassRegistry());
1469 }
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001470 void InitOptimizations();
1471 bool runOnFunction(Function &F);
1472
Nick Lewycky0f8df9a2009-01-04 20:27:34 +00001473 void setDoesNotAccessMemory(Function &F);
1474 void setOnlyReadsMemory(Function &F);
1475 void setDoesNotThrow(Function &F);
1476 void setDoesNotCapture(Function &F, unsigned n);
1477 void setDoesNotAlias(Function &F, unsigned n);
Nick Lewycky6cd0c042009-01-05 00:07:50 +00001478 bool doInitialization(Module &M);
Nick Lewycky0f8df9a2009-01-04 20:27:34 +00001479
Chris Lattnere265ad82011-02-24 07:12:12 +00001480 void inferPrototypeAttributes(Function &F);
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001481 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
Chris Lattnerafbf4832011-02-24 07:16:14 +00001482 AU.addRequired<TargetLibraryInfo>();
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001483 }
1484 };
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001485} // end anonymous namespace.
1486
Chris Lattnerafbf4832011-02-24 07:16:14 +00001487char SimplifyLibCalls::ID = 0;
1488
1489INITIALIZE_PASS_BEGIN(SimplifyLibCalls, "simplify-libcalls",
1490 "Simplify well-known library calls", false, false)
1491INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfo)
1492INITIALIZE_PASS_END(SimplifyLibCalls, "simplify-libcalls",
1493 "Simplify well-known library calls", false, false)
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001494
1495// Public interface to the Simplify LibCalls pass.
1496FunctionPass *llvm::createSimplifyLibCallsPass() {
Eric Christopher37c8b862009-10-07 21:14:25 +00001497 return new SimplifyLibCalls();
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001498}
1499
1500/// Optimizations - Populate the Optimizations map with all the optimizations
1501/// we know.
1502void SimplifyLibCalls::InitOptimizations() {
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001503 // String and Memory LibCall Optimizations
1504 Optimizations["strcat"] = &StrCat;
Chris Lattnerf5b6bc72009-04-12 05:06:39 +00001505 Optimizations["strncat"] = &StrNCat;
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001506 Optimizations["strchr"] = &StrChr;
Benjamin Kramer06f25cf2010-09-29 21:50:51 +00001507 Optimizations["strrchr"] = &StrRChr;
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001508 Optimizations["strcmp"] = &StrCmp;
1509 Optimizations["strncmp"] = &StrNCmp;
1510 Optimizations["strcpy"] = &StrCpy;
Chris Lattnerf5b6bc72009-04-12 05:06:39 +00001511 Optimizations["strncpy"] = &StrNCpy;
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001512 Optimizations["strlen"] = &StrLen;
Benjamin Kramer05f585e2010-09-29 23:52:12 +00001513 Optimizations["strpbrk"] = &StrPBrk;
Nick Lewycky4c498412009-02-13 15:31:46 +00001514 Optimizations["strtol"] = &StrTo;
1515 Optimizations["strtod"] = &StrTo;
1516 Optimizations["strtof"] = &StrTo;
1517 Optimizations["strtoul"] = &StrTo;
1518 Optimizations["strtoll"] = &StrTo;
1519 Optimizations["strtold"] = &StrTo;
1520 Optimizations["strtoull"] = &StrTo;
Benjamin Kramer9510a252010-09-30 00:58:35 +00001521 Optimizations["strspn"] = &StrSpn;
1522 Optimizations["strcspn"] = &StrCSpn;
Chris Lattner24604112009-12-16 09:32:05 +00001523 Optimizations["strstr"] = &StrStr;
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001524 Optimizations["memcmp"] = &MemCmp;
Chris Lattnerafbf4832011-02-24 07:16:14 +00001525 if (TLI->has(LibFunc::memcpy)) Optimizations["memcpy"] = &MemCpy;
Eli Friedmand83ae7d2008-11-30 08:32:11 +00001526 Optimizations["memmove"] = &MemMove;
Chris Lattnerafbf4832011-02-24 07:16:14 +00001527 if (TLI->has(LibFunc::memset)) Optimizations["memset"] = &MemSet;
Eric Christopher37c8b862009-10-07 21:14:25 +00001528
Evan Cheng0289b412010-03-23 15:48:04 +00001529 // _chk variants of String and Memory LibCall Optimizations.
Evan Cheng0289b412010-03-23 15:48:04 +00001530 Optimizations["__strcpy_chk"] = &StrCpyChk;
1531
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001532 // Math Library Optimizations
1533 Optimizations["powf"] = &Pow;
1534 Optimizations["pow"] = &Pow;
1535 Optimizations["powl"] = &Pow;
Dale Johannesen53bfbbc2008-09-04 18:30:46 +00001536 Optimizations["llvm.pow.f32"] = &Pow;
1537 Optimizations["llvm.pow.f64"] = &Pow;
1538 Optimizations["llvm.pow.f80"] = &Pow;
1539 Optimizations["llvm.pow.f128"] = &Pow;
1540 Optimizations["llvm.pow.ppcf128"] = &Pow;
Chris Lattnere818f772008-05-02 18:43:35 +00001541 Optimizations["exp2l"] = &Exp2;
1542 Optimizations["exp2"] = &Exp2;
1543 Optimizations["exp2f"] = &Exp2;
Dale Johannesen53bfbbc2008-09-04 18:30:46 +00001544 Optimizations["llvm.exp2.ppcf128"] = &Exp2;
1545 Optimizations["llvm.exp2.f128"] = &Exp2;
1546 Optimizations["llvm.exp2.f80"] = &Exp2;
1547 Optimizations["llvm.exp2.f64"] = &Exp2;
1548 Optimizations["llvm.exp2.f32"] = &Exp2;
Eric Christopher37c8b862009-10-07 21:14:25 +00001549
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001550#ifdef HAVE_FLOORF
1551 Optimizations["floor"] = &UnaryDoubleFP;
1552#endif
1553#ifdef HAVE_CEILF
1554 Optimizations["ceil"] = &UnaryDoubleFP;
1555#endif
1556#ifdef HAVE_ROUNDF
1557 Optimizations["round"] = &UnaryDoubleFP;
1558#endif
1559#ifdef HAVE_RINTF
1560 Optimizations["rint"] = &UnaryDoubleFP;
1561#endif
1562#ifdef HAVE_NEARBYINTF
1563 Optimizations["nearbyint"] = &UnaryDoubleFP;
1564#endif
Eric Christopher37c8b862009-10-07 21:14:25 +00001565
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001566 // Integer Optimizations
1567 Optimizations["ffs"] = &FFS;
1568 Optimizations["ffsl"] = &FFS;
1569 Optimizations["ffsll"] = &FFS;
Chris Lattner313f0e62008-06-09 08:26:51 +00001570 Optimizations["abs"] = &Abs;
1571 Optimizations["labs"] = &Abs;
1572 Optimizations["llabs"] = &Abs;
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001573 Optimizations["isdigit"] = &IsDigit;
1574 Optimizations["isascii"] = &IsAscii;
1575 Optimizations["toascii"] = &ToAscii;
Eric Christopher37c8b862009-10-07 21:14:25 +00001576
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001577 // Formatting and IO Optimizations
1578 Optimizations["sprintf"] = &SPrintF;
1579 Optimizations["printf"] = &PrintF;
1580 Optimizations["fwrite"] = &FWrite;
1581 Optimizations["fputs"] = &FPuts;
1582 Optimizations["fprintf"] = &FPrintF;
Anders Carlsson303023d2010-11-30 06:19:18 +00001583 Optimizations["puts"] = &Puts;
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001584}
1585
1586
1587/// runOnFunction - Top level algorithm.
1588///
1589bool SimplifyLibCalls::runOnFunction(Function &F) {
Chris Lattnerafbf4832011-02-24 07:16:14 +00001590 TLI = &getAnalysis<TargetLibraryInfo>();
1591
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001592 if (Optimizations.empty())
1593 InitOptimizations();
Eric Christopher37c8b862009-10-07 21:14:25 +00001594
Dan Gohmanf14d9192009-08-18 00:48:13 +00001595 const TargetData *TD = getAnalysisIfAvailable<TargetData>();
Eric Christopher37c8b862009-10-07 21:14:25 +00001596
Owen Andersone922c022009-07-22 00:24:57 +00001597 IRBuilder<> Builder(F.getContext());
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001598
1599 bool Changed = false;
1600 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB) {
1601 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ) {
1602 // Ignore non-calls.
1603 CallInst *CI = dyn_cast<CallInst>(I++);
1604 if (!CI) continue;
Eric Christopher37c8b862009-10-07 21:14:25 +00001605
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001606 // Ignore indirect calls and calls to non-external functions.
1607 Function *Callee = CI->getCalledFunction();
1608 if (Callee == 0 || !Callee->isDeclaration() ||
1609 !(Callee->hasExternalLinkage() || Callee->hasDLLImportLinkage()))
1610 continue;
Eric Christopher37c8b862009-10-07 21:14:25 +00001611
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001612 // Ignore unknown calls.
Daniel Dunbarf0443c12009-07-26 08:34:35 +00001613 LibCallOptimization *LCO = Optimizations.lookup(Callee->getName());
1614 if (!LCO) continue;
Eric Christopher37c8b862009-10-07 21:14:25 +00001615
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001616 // Set the builder to the instruction after the call.
1617 Builder.SetInsertPoint(BB, I);
Eric Christopher37c8b862009-10-07 21:14:25 +00001618
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001619 // Try to optimize this call.
Richard Osborne36498242011-03-03 13:17:51 +00001620 Value *Result = LCO->OptimizeCall(CI, TD, TLI, Builder);
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001621 if (Result == 0) continue;
1622
David Greene6a6b90e2010-01-05 01:27:21 +00001623 DEBUG(dbgs() << "SimplifyLibCalls simplified: " << *CI;
1624 dbgs() << " into: " << *Result << "\n");
Eric Christopher37c8b862009-10-07 21:14:25 +00001625
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001626 // Something changed!
1627 Changed = true;
1628 ++NumSimplified;
Eric Christopher37c8b862009-10-07 21:14:25 +00001629
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001630 // Inspect the instruction after the call (which was potentially just
1631 // added) next.
1632 I = CI; ++I;
Eric Christopher37c8b862009-10-07 21:14:25 +00001633
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001634 if (CI != Result && !CI->use_empty()) {
1635 CI->replaceAllUsesWith(Result);
1636 if (!Result->hasName())
1637 Result->takeName(CI);
1638 }
1639 CI->eraseFromParent();
1640 }
1641 }
1642 return Changed;
1643}
1644
Nick Lewycky6cd0c042009-01-05 00:07:50 +00001645// Utility methods for doInitialization.
Nick Lewycky0f8df9a2009-01-04 20:27:34 +00001646
1647void SimplifyLibCalls::setDoesNotAccessMemory(Function &F) {
1648 if (!F.doesNotAccessMemory()) {
1649 F.setDoesNotAccessMemory();
1650 ++NumAnnotated;
1651 Modified = true;
1652 }
1653}
1654void SimplifyLibCalls::setOnlyReadsMemory(Function &F) {
1655 if (!F.onlyReadsMemory()) {
1656 F.setOnlyReadsMemory();
1657 ++NumAnnotated;
1658 Modified = true;
1659 }
1660}
1661void SimplifyLibCalls::setDoesNotThrow(Function &F) {
1662 if (!F.doesNotThrow()) {
1663 F.setDoesNotThrow();
1664 ++NumAnnotated;
1665 Modified = true;
1666 }
1667}
1668void SimplifyLibCalls::setDoesNotCapture(Function &F, unsigned n) {
1669 if (!F.doesNotCapture(n)) {
1670 F.setDoesNotCapture(n);
1671 ++NumAnnotated;
1672 Modified = true;
1673 }
1674}
1675void SimplifyLibCalls::setDoesNotAlias(Function &F, unsigned n) {
1676 if (!F.doesNotAlias(n)) {
1677 F.setDoesNotAlias(n);
1678 ++NumAnnotated;
1679 Modified = true;
1680 }
1681}
1682
Chris Lattnere265ad82011-02-24 07:12:12 +00001683
1684void SimplifyLibCalls::inferPrototypeAttributes(Function &F) {
1685 const FunctionType *FTy = F.getFunctionType();
1686
1687 StringRef Name = F.getName();
1688 switch (Name[0]) {
1689 case 's':
1690 if (Name == "strlen") {
1691 if (FTy->getNumParams() != 1 || !FTy->getParamType(0)->isPointerTy())
1692 return;
1693 setOnlyReadsMemory(F);
1694 setDoesNotThrow(F);
1695 setDoesNotCapture(F, 1);
1696 } else if (Name == "strchr" ||
1697 Name == "strrchr") {
1698 if (FTy->getNumParams() != 2 ||
1699 !FTy->getParamType(0)->isPointerTy() ||
1700 !FTy->getParamType(1)->isIntegerTy())
1701 return;
1702 setOnlyReadsMemory(F);
1703 setDoesNotThrow(F);
1704 } else if (Name == "strcpy" ||
1705 Name == "stpcpy" ||
1706 Name == "strcat" ||
1707 Name == "strtol" ||
1708 Name == "strtod" ||
1709 Name == "strtof" ||
1710 Name == "strtoul" ||
1711 Name == "strtoll" ||
1712 Name == "strtold" ||
1713 Name == "strncat" ||
1714 Name == "strncpy" ||
1715 Name == "strtoull") {
1716 if (FTy->getNumParams() < 2 ||
1717 !FTy->getParamType(1)->isPointerTy())
1718 return;
1719 setDoesNotThrow(F);
1720 setDoesNotCapture(F, 2);
1721 } else if (Name == "strxfrm") {
1722 if (FTy->getNumParams() != 3 ||
1723 !FTy->getParamType(0)->isPointerTy() ||
1724 !FTy->getParamType(1)->isPointerTy())
1725 return;
1726 setDoesNotThrow(F);
1727 setDoesNotCapture(F, 1);
1728 setDoesNotCapture(F, 2);
1729 } else if (Name == "strcmp" ||
1730 Name == "strspn" ||
1731 Name == "strncmp" ||
1732 Name == "strcspn" ||
1733 Name == "strcoll" ||
1734 Name == "strcasecmp" ||
1735 Name == "strncasecmp") {
1736 if (FTy->getNumParams() < 2 ||
1737 !FTy->getParamType(0)->isPointerTy() ||
1738 !FTy->getParamType(1)->isPointerTy())
1739 return;
1740 setOnlyReadsMemory(F);
1741 setDoesNotThrow(F);
1742 setDoesNotCapture(F, 1);
1743 setDoesNotCapture(F, 2);
1744 } else if (Name == "strstr" ||
1745 Name == "strpbrk") {
1746 if (FTy->getNumParams() != 2 || !FTy->getParamType(1)->isPointerTy())
1747 return;
1748 setOnlyReadsMemory(F);
1749 setDoesNotThrow(F);
1750 setDoesNotCapture(F, 2);
1751 } else if (Name == "strtok" ||
1752 Name == "strtok_r") {
1753 if (FTy->getNumParams() < 2 || !FTy->getParamType(1)->isPointerTy())
1754 return;
1755 setDoesNotThrow(F);
1756 setDoesNotCapture(F, 2);
1757 } else if (Name == "scanf" ||
1758 Name == "setbuf" ||
1759 Name == "setvbuf") {
1760 if (FTy->getNumParams() < 1 || !FTy->getParamType(0)->isPointerTy())
1761 return;
1762 setDoesNotThrow(F);
1763 setDoesNotCapture(F, 1);
1764 } else if (Name == "strdup" ||
1765 Name == "strndup") {
1766 if (FTy->getNumParams() < 1 || !FTy->getReturnType()->isPointerTy() ||
1767 !FTy->getParamType(0)->isPointerTy())
1768 return;
1769 setDoesNotThrow(F);
1770 setDoesNotAlias(F, 0);
1771 setDoesNotCapture(F, 1);
1772 } else if (Name == "stat" ||
1773 Name == "sscanf" ||
1774 Name == "sprintf" ||
1775 Name == "statvfs") {
1776 if (FTy->getNumParams() < 2 ||
1777 !FTy->getParamType(0)->isPointerTy() ||
1778 !FTy->getParamType(1)->isPointerTy())
1779 return;
1780 setDoesNotThrow(F);
1781 setDoesNotCapture(F, 1);
1782 setDoesNotCapture(F, 2);
1783 } else if (Name == "snprintf") {
1784 if (FTy->getNumParams() != 3 ||
1785 !FTy->getParamType(0)->isPointerTy() ||
1786 !FTy->getParamType(2)->isPointerTy())
1787 return;
1788 setDoesNotThrow(F);
1789 setDoesNotCapture(F, 1);
1790 setDoesNotCapture(F, 3);
1791 } else if (Name == "setitimer") {
1792 if (FTy->getNumParams() != 3 ||
1793 !FTy->getParamType(1)->isPointerTy() ||
1794 !FTy->getParamType(2)->isPointerTy())
1795 return;
1796 setDoesNotThrow(F);
1797 setDoesNotCapture(F, 2);
1798 setDoesNotCapture(F, 3);
1799 } else if (Name == "system") {
1800 if (FTy->getNumParams() != 1 ||
1801 !FTy->getParamType(0)->isPointerTy())
1802 return;
1803 // May throw; "system" is a valid pthread cancellation point.
1804 setDoesNotCapture(F, 1);
1805 }
1806 break;
1807 case 'm':
1808 if (Name == "malloc") {
1809 if (FTy->getNumParams() != 1 ||
1810 !FTy->getReturnType()->isPointerTy())
1811 return;
1812 setDoesNotThrow(F);
1813 setDoesNotAlias(F, 0);
1814 } else if (Name == "memcmp") {
1815 if (FTy->getNumParams() != 3 ||
1816 !FTy->getParamType(0)->isPointerTy() ||
1817 !FTy->getParamType(1)->isPointerTy())
1818 return;
1819 setOnlyReadsMemory(F);
1820 setDoesNotThrow(F);
1821 setDoesNotCapture(F, 1);
1822 setDoesNotCapture(F, 2);
1823 } else if (Name == "memchr" ||
1824 Name == "memrchr") {
1825 if (FTy->getNumParams() != 3)
1826 return;
1827 setOnlyReadsMemory(F);
1828 setDoesNotThrow(F);
1829 } else if (Name == "modf" ||
1830 Name == "modff" ||
1831 Name == "modfl" ||
1832 Name == "memcpy" ||
1833 Name == "memccpy" ||
1834 Name == "memmove") {
1835 if (FTy->getNumParams() < 2 ||
1836 !FTy->getParamType(1)->isPointerTy())
1837 return;
1838 setDoesNotThrow(F);
1839 setDoesNotCapture(F, 2);
1840 } else if (Name == "memalign") {
1841 if (!FTy->getReturnType()->isPointerTy())
1842 return;
1843 setDoesNotAlias(F, 0);
1844 } else if (Name == "mkdir" ||
1845 Name == "mktime") {
1846 if (FTy->getNumParams() == 0 ||
1847 !FTy->getParamType(0)->isPointerTy())
1848 return;
1849 setDoesNotThrow(F);
1850 setDoesNotCapture(F, 1);
1851 }
1852 break;
1853 case 'r':
1854 if (Name == "realloc") {
1855 if (FTy->getNumParams() != 2 ||
1856 !FTy->getParamType(0)->isPointerTy() ||
1857 !FTy->getReturnType()->isPointerTy())
1858 return;
1859 setDoesNotThrow(F);
1860 setDoesNotAlias(F, 0);
1861 setDoesNotCapture(F, 1);
1862 } else if (Name == "read") {
1863 if (FTy->getNumParams() != 3 ||
1864 !FTy->getParamType(1)->isPointerTy())
1865 return;
1866 // May throw; "read" is a valid pthread cancellation point.
1867 setDoesNotCapture(F, 2);
1868 } else if (Name == "rmdir" ||
1869 Name == "rewind" ||
1870 Name == "remove" ||
1871 Name == "realpath") {
1872 if (FTy->getNumParams() < 1 ||
1873 !FTy->getParamType(0)->isPointerTy())
1874 return;
1875 setDoesNotThrow(F);
1876 setDoesNotCapture(F, 1);
1877 } else if (Name == "rename" ||
1878 Name == "readlink") {
1879 if (FTy->getNumParams() < 2 ||
1880 !FTy->getParamType(0)->isPointerTy() ||
1881 !FTy->getParamType(1)->isPointerTy())
1882 return;
1883 setDoesNotThrow(F);
1884 setDoesNotCapture(F, 1);
1885 setDoesNotCapture(F, 2);
1886 }
1887 break;
1888 case 'w':
1889 if (Name == "write") {
1890 if (FTy->getNumParams() != 3 || !FTy->getParamType(1)->isPointerTy())
1891 return;
1892 // May throw; "write" is a valid pthread cancellation point.
1893 setDoesNotCapture(F, 2);
1894 }
1895 break;
1896 case 'b':
1897 if (Name == "bcopy") {
1898 if (FTy->getNumParams() != 3 ||
1899 !FTy->getParamType(0)->isPointerTy() ||
1900 !FTy->getParamType(1)->isPointerTy())
1901 return;
1902 setDoesNotThrow(F);
1903 setDoesNotCapture(F, 1);
1904 setDoesNotCapture(F, 2);
1905 } else if (Name == "bcmp") {
1906 if (FTy->getNumParams() != 3 ||
1907 !FTy->getParamType(0)->isPointerTy() ||
1908 !FTy->getParamType(1)->isPointerTy())
1909 return;
1910 setDoesNotThrow(F);
1911 setOnlyReadsMemory(F);
1912 setDoesNotCapture(F, 1);
1913 setDoesNotCapture(F, 2);
1914 } else if (Name == "bzero") {
1915 if (FTy->getNumParams() != 2 || !FTy->getParamType(0)->isPointerTy())
1916 return;
1917 setDoesNotThrow(F);
1918 setDoesNotCapture(F, 1);
1919 }
1920 break;
1921 case 'c':
1922 if (Name == "calloc") {
1923 if (FTy->getNumParams() != 2 ||
1924 !FTy->getReturnType()->isPointerTy())
1925 return;
1926 setDoesNotThrow(F);
1927 setDoesNotAlias(F, 0);
1928 } else if (Name == "chmod" ||
1929 Name == "chown" ||
1930 Name == "ctermid" ||
1931 Name == "clearerr" ||
1932 Name == "closedir") {
1933 if (FTy->getNumParams() == 0 || !FTy->getParamType(0)->isPointerTy())
1934 return;
1935 setDoesNotThrow(F);
1936 setDoesNotCapture(F, 1);
1937 }
1938 break;
1939 case 'a':
1940 if (Name == "atoi" ||
1941 Name == "atol" ||
1942 Name == "atof" ||
1943 Name == "atoll") {
1944 if (FTy->getNumParams() != 1 || !FTy->getParamType(0)->isPointerTy())
1945 return;
1946 setDoesNotThrow(F);
1947 setOnlyReadsMemory(F);
1948 setDoesNotCapture(F, 1);
1949 } else if (Name == "access") {
1950 if (FTy->getNumParams() != 2 || !FTy->getParamType(0)->isPointerTy())
1951 return;
1952 setDoesNotThrow(F);
1953 setDoesNotCapture(F, 1);
1954 }
1955 break;
1956 case 'f':
1957 if (Name == "fopen") {
1958 if (FTy->getNumParams() != 2 ||
1959 !FTy->getReturnType()->isPointerTy() ||
1960 !FTy->getParamType(0)->isPointerTy() ||
1961 !FTy->getParamType(1)->isPointerTy())
1962 return;
1963 setDoesNotThrow(F);
1964 setDoesNotAlias(F, 0);
1965 setDoesNotCapture(F, 1);
1966 setDoesNotCapture(F, 2);
1967 } else if (Name == "fdopen") {
1968 if (FTy->getNumParams() != 2 ||
1969 !FTy->getReturnType()->isPointerTy() ||
1970 !FTy->getParamType(1)->isPointerTy())
1971 return;
1972 setDoesNotThrow(F);
1973 setDoesNotAlias(F, 0);
1974 setDoesNotCapture(F, 2);
1975 } else if (Name == "feof" ||
1976 Name == "free" ||
1977 Name == "fseek" ||
1978 Name == "ftell" ||
1979 Name == "fgetc" ||
1980 Name == "fseeko" ||
1981 Name == "ftello" ||
1982 Name == "fileno" ||
1983 Name == "fflush" ||
1984 Name == "fclose" ||
1985 Name == "fsetpos" ||
1986 Name == "flockfile" ||
1987 Name == "funlockfile" ||
1988 Name == "ftrylockfile") {
1989 if (FTy->getNumParams() == 0 || !FTy->getParamType(0)->isPointerTy())
1990 return;
1991 setDoesNotThrow(F);
1992 setDoesNotCapture(F, 1);
1993 } else if (Name == "ferror") {
1994 if (FTy->getNumParams() != 1 || !FTy->getParamType(0)->isPointerTy())
1995 return;
1996 setDoesNotThrow(F);
1997 setDoesNotCapture(F, 1);
1998 setOnlyReadsMemory(F);
1999 } else if (Name == "fputc" ||
2000 Name == "fstat" ||
2001 Name == "frexp" ||
2002 Name == "frexpf" ||
2003 Name == "frexpl" ||
2004 Name == "fstatvfs") {
2005 if (FTy->getNumParams() != 2 || !FTy->getParamType(1)->isPointerTy())
2006 return;
2007 setDoesNotThrow(F);
2008 setDoesNotCapture(F, 2);
2009 } else if (Name == "fgets") {
2010 if (FTy->getNumParams() != 3 ||
2011 !FTy->getParamType(0)->isPointerTy() ||
2012 !FTy->getParamType(2)->isPointerTy())
2013 return;
2014 setDoesNotThrow(F);
2015 setDoesNotCapture(F, 3);
2016 } else if (Name == "fread" ||
2017 Name == "fwrite") {
2018 if (FTy->getNumParams() != 4 ||
2019 !FTy->getParamType(0)->isPointerTy() ||
2020 !FTy->getParamType(3)->isPointerTy())
2021 return;
2022 setDoesNotThrow(F);
2023 setDoesNotCapture(F, 1);
2024 setDoesNotCapture(F, 4);
2025 } else if (Name == "fputs" ||
2026 Name == "fscanf" ||
2027 Name == "fprintf" ||
2028 Name == "fgetpos") {
2029 if (FTy->getNumParams() < 2 ||
2030 !FTy->getParamType(0)->isPointerTy() ||
2031 !FTy->getParamType(1)->isPointerTy())
2032 return;
2033 setDoesNotThrow(F);
2034 setDoesNotCapture(F, 1);
2035 setDoesNotCapture(F, 2);
2036 }
2037 break;
2038 case 'g':
2039 if (Name == "getc" ||
2040 Name == "getlogin_r" ||
2041 Name == "getc_unlocked") {
2042 if (FTy->getNumParams() == 0 || !FTy->getParamType(0)->isPointerTy())
2043 return;
2044 setDoesNotThrow(F);
2045 setDoesNotCapture(F, 1);
2046 } else if (Name == "getenv") {
2047 if (FTy->getNumParams() != 1 || !FTy->getParamType(0)->isPointerTy())
2048 return;
2049 setDoesNotThrow(F);
2050 setOnlyReadsMemory(F);
2051 setDoesNotCapture(F, 1);
2052 } else if (Name == "gets" ||
2053 Name == "getchar") {
2054 setDoesNotThrow(F);
2055 } else if (Name == "getitimer") {
2056 if (FTy->getNumParams() != 2 || !FTy->getParamType(1)->isPointerTy())
2057 return;
2058 setDoesNotThrow(F);
2059 setDoesNotCapture(F, 2);
2060 } else if (Name == "getpwnam") {
2061 if (FTy->getNumParams() != 1 || !FTy->getParamType(0)->isPointerTy())
2062 return;
2063 setDoesNotThrow(F);
2064 setDoesNotCapture(F, 1);
2065 }
2066 break;
2067 case 'u':
2068 if (Name == "ungetc") {
2069 if (FTy->getNumParams() != 2 || !FTy->getParamType(1)->isPointerTy())
2070 return;
2071 setDoesNotThrow(F);
2072 setDoesNotCapture(F, 2);
2073 } else if (Name == "uname" ||
2074 Name == "unlink" ||
2075 Name == "unsetenv") {
2076 if (FTy->getNumParams() != 1 || !FTy->getParamType(0)->isPointerTy())
2077 return;
2078 setDoesNotThrow(F);
2079 setDoesNotCapture(F, 1);
2080 } else if (Name == "utime" ||
2081 Name == "utimes") {
2082 if (FTy->getNumParams() != 2 ||
2083 !FTy->getParamType(0)->isPointerTy() ||
2084 !FTy->getParamType(1)->isPointerTy())
2085 return;
2086 setDoesNotThrow(F);
2087 setDoesNotCapture(F, 1);
2088 setDoesNotCapture(F, 2);
2089 }
2090 break;
2091 case 'p':
2092 if (Name == "putc") {
2093 if (FTy->getNumParams() != 2 || !FTy->getParamType(1)->isPointerTy())
2094 return;
2095 setDoesNotThrow(F);
2096 setDoesNotCapture(F, 2);
2097 } else if (Name == "puts" ||
2098 Name == "printf" ||
2099 Name == "perror") {
2100 if (FTy->getNumParams() != 1 || !FTy->getParamType(0)->isPointerTy())
2101 return;
2102 setDoesNotThrow(F);
2103 setDoesNotCapture(F, 1);
2104 } else if (Name == "pread" ||
2105 Name == "pwrite") {
2106 if (FTy->getNumParams() != 4 || !FTy->getParamType(1)->isPointerTy())
2107 return;
2108 // May throw; these are valid pthread cancellation points.
2109 setDoesNotCapture(F, 2);
2110 } else if (Name == "putchar") {
2111 setDoesNotThrow(F);
2112 } else if (Name == "popen") {
2113 if (FTy->getNumParams() != 2 ||
2114 !FTy->getReturnType()->isPointerTy() ||
2115 !FTy->getParamType(0)->isPointerTy() ||
2116 !FTy->getParamType(1)->isPointerTy())
2117 return;
2118 setDoesNotThrow(F);
2119 setDoesNotAlias(F, 0);
2120 setDoesNotCapture(F, 1);
2121 setDoesNotCapture(F, 2);
2122 } else if (Name == "pclose") {
2123 if (FTy->getNumParams() != 1 || !FTy->getParamType(0)->isPointerTy())
2124 return;
2125 setDoesNotThrow(F);
2126 setDoesNotCapture(F, 1);
2127 }
2128 break;
2129 case 'v':
2130 if (Name == "vscanf") {
2131 if (FTy->getNumParams() != 2 || !FTy->getParamType(1)->isPointerTy())
2132 return;
2133 setDoesNotThrow(F);
2134 setDoesNotCapture(F, 1);
2135 } else if (Name == "vsscanf" ||
2136 Name == "vfscanf") {
2137 if (FTy->getNumParams() != 3 ||
2138 !FTy->getParamType(1)->isPointerTy() ||
2139 !FTy->getParamType(2)->isPointerTy())
2140 return;
2141 setDoesNotThrow(F);
2142 setDoesNotCapture(F, 1);
2143 setDoesNotCapture(F, 2);
2144 } else if (Name == "valloc") {
2145 if (!FTy->getReturnType()->isPointerTy())
2146 return;
2147 setDoesNotThrow(F);
2148 setDoesNotAlias(F, 0);
2149 } else if (Name == "vprintf") {
2150 if (FTy->getNumParams() != 2 || !FTy->getParamType(0)->isPointerTy())
2151 return;
2152 setDoesNotThrow(F);
2153 setDoesNotCapture(F, 1);
2154 } else if (Name == "vfprintf" ||
2155 Name == "vsprintf") {
2156 if (FTy->getNumParams() != 3 ||
2157 !FTy->getParamType(0)->isPointerTy() ||
2158 !FTy->getParamType(1)->isPointerTy())
2159 return;
2160 setDoesNotThrow(F);
2161 setDoesNotCapture(F, 1);
2162 setDoesNotCapture(F, 2);
2163 } else if (Name == "vsnprintf") {
2164 if (FTy->getNumParams() != 4 ||
2165 !FTy->getParamType(0)->isPointerTy() ||
2166 !FTy->getParamType(2)->isPointerTy())
2167 return;
2168 setDoesNotThrow(F);
2169 setDoesNotCapture(F, 1);
2170 setDoesNotCapture(F, 3);
2171 }
2172 break;
2173 case 'o':
2174 if (Name == "open") {
2175 if (FTy->getNumParams() < 2 || !FTy->getParamType(0)->isPointerTy())
2176 return;
2177 // May throw; "open" is a valid pthread cancellation point.
2178 setDoesNotCapture(F, 1);
2179 } else if (Name == "opendir") {
2180 if (FTy->getNumParams() != 1 ||
2181 !FTy->getReturnType()->isPointerTy() ||
2182 !FTy->getParamType(0)->isPointerTy())
2183 return;
2184 setDoesNotThrow(F);
2185 setDoesNotAlias(F, 0);
2186 setDoesNotCapture(F, 1);
2187 }
2188 break;
2189 case 't':
2190 if (Name == "tmpfile") {
2191 if (!FTy->getReturnType()->isPointerTy())
2192 return;
2193 setDoesNotThrow(F);
2194 setDoesNotAlias(F, 0);
2195 } else if (Name == "times") {
2196 if (FTy->getNumParams() != 1 || !FTy->getParamType(0)->isPointerTy())
2197 return;
2198 setDoesNotThrow(F);
2199 setDoesNotCapture(F, 1);
2200 }
2201 break;
2202 case 'h':
2203 if (Name == "htonl" ||
2204 Name == "htons") {
2205 setDoesNotThrow(F);
2206 setDoesNotAccessMemory(F);
2207 }
2208 break;
2209 case 'n':
2210 if (Name == "ntohl" ||
2211 Name == "ntohs") {
2212 setDoesNotThrow(F);
2213 setDoesNotAccessMemory(F);
2214 }
2215 break;
2216 case 'l':
2217 if (Name == "lstat") {
2218 if (FTy->getNumParams() != 2 ||
2219 !FTy->getParamType(0)->isPointerTy() ||
2220 !FTy->getParamType(1)->isPointerTy())
2221 return;
2222 setDoesNotThrow(F);
2223 setDoesNotCapture(F, 1);
2224 setDoesNotCapture(F, 2);
2225 } else if (Name == "lchown") {
2226 if (FTy->getNumParams() != 3 || !FTy->getParamType(0)->isPointerTy())
2227 return;
2228 setDoesNotThrow(F);
2229 setDoesNotCapture(F, 1);
2230 }
2231 break;
2232 case 'q':
2233 if (Name == "qsort") {
2234 if (FTy->getNumParams() != 4 || !FTy->getParamType(3)->isPointerTy())
2235 return;
2236 // May throw; places call through function pointer.
2237 setDoesNotCapture(F, 4);
2238 }
2239 break;
2240 case '_':
2241 if (Name == "__strdup" ||
2242 Name == "__strndup") {
2243 if (FTy->getNumParams() < 1 ||
2244 !FTy->getReturnType()->isPointerTy() ||
2245 !FTy->getParamType(0)->isPointerTy())
2246 return;
2247 setDoesNotThrow(F);
2248 setDoesNotAlias(F, 0);
2249 setDoesNotCapture(F, 1);
2250 } else if (Name == "__strtok_r") {
2251 if (FTy->getNumParams() != 3 ||
2252 !FTy->getParamType(1)->isPointerTy())
2253 return;
2254 setDoesNotThrow(F);
2255 setDoesNotCapture(F, 2);
2256 } else if (Name == "_IO_getc") {
2257 if (FTy->getNumParams() != 1 || !FTy->getParamType(0)->isPointerTy())
2258 return;
2259 setDoesNotThrow(F);
2260 setDoesNotCapture(F, 1);
2261 } else if (Name == "_IO_putc") {
2262 if (FTy->getNumParams() != 2 || !FTy->getParamType(1)->isPointerTy())
2263 return;
2264 setDoesNotThrow(F);
2265 setDoesNotCapture(F, 2);
2266 }
2267 break;
2268 case 1:
2269 if (Name == "\1__isoc99_scanf") {
2270 if (FTy->getNumParams() < 1 ||
2271 !FTy->getParamType(0)->isPointerTy())
2272 return;
2273 setDoesNotThrow(F);
2274 setDoesNotCapture(F, 1);
2275 } else if (Name == "\1stat64" ||
2276 Name == "\1lstat64" ||
2277 Name == "\1statvfs64" ||
2278 Name == "\1__isoc99_sscanf") {
2279 if (FTy->getNumParams() < 1 ||
2280 !FTy->getParamType(0)->isPointerTy() ||
2281 !FTy->getParamType(1)->isPointerTy())
2282 return;
2283 setDoesNotThrow(F);
2284 setDoesNotCapture(F, 1);
2285 setDoesNotCapture(F, 2);
2286 } else if (Name == "\1fopen64") {
2287 if (FTy->getNumParams() != 2 ||
2288 !FTy->getReturnType()->isPointerTy() ||
2289 !FTy->getParamType(0)->isPointerTy() ||
2290 !FTy->getParamType(1)->isPointerTy())
2291 return;
2292 setDoesNotThrow(F);
2293 setDoesNotAlias(F, 0);
2294 setDoesNotCapture(F, 1);
2295 setDoesNotCapture(F, 2);
2296 } else if (Name == "\1fseeko64" ||
2297 Name == "\1ftello64") {
2298 if (FTy->getNumParams() == 0 || !FTy->getParamType(0)->isPointerTy())
2299 return;
2300 setDoesNotThrow(F);
2301 setDoesNotCapture(F, 1);
2302 } else if (Name == "\1tmpfile64") {
2303 if (!FTy->getReturnType()->isPointerTy())
2304 return;
2305 setDoesNotThrow(F);
2306 setDoesNotAlias(F, 0);
2307 } else if (Name == "\1fstat64" ||
2308 Name == "\1fstatvfs64") {
2309 if (FTy->getNumParams() != 2 || !FTy->getParamType(1)->isPointerTy())
2310 return;
2311 setDoesNotThrow(F);
2312 setDoesNotCapture(F, 2);
2313 } else if (Name == "\1open64") {
2314 if (FTy->getNumParams() < 2 || !FTy->getParamType(0)->isPointerTy())
2315 return;
2316 // May throw; "open" is a valid pthread cancellation point.
2317 setDoesNotCapture(F, 1);
2318 }
2319 break;
2320 }
2321}
2322
Nick Lewycky6cd0c042009-01-05 00:07:50 +00002323/// doInitialization - Add attributes to well-known functions.
Nick Lewycky0f8df9a2009-01-04 20:27:34 +00002324///
Nick Lewycky6cd0c042009-01-05 00:07:50 +00002325bool SimplifyLibCalls::doInitialization(Module &M) {
Nick Lewycky0f8df9a2009-01-04 20:27:34 +00002326 Modified = false;
2327 for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I) {
2328 Function &F = *I;
Chris Lattnere265ad82011-02-24 07:12:12 +00002329 if (F.isDeclaration() && F.hasName())
2330 inferPrototypeAttributes(F);
Nick Lewycky0f8df9a2009-01-04 20:27:34 +00002331 }
2332 return Modified;
2333}
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00002334
2335// TODO:
2336// Additional cases that we need to add to this file:
2337//
2338// cbrt:
2339// * cbrt(expN(X)) -> expN(x/3)
2340// * cbrt(sqrt(x)) -> pow(x,1/6)
2341// * cbrt(sqrt(x)) -> pow(x,1/9)
2342//
2343// cos, cosf, cosl:
2344// * cos(-x) -> cos(x)
2345//
2346// exp, expf, expl:
2347// * exp(log(x)) -> x
2348//
2349// log, logf, logl:
2350// * log(exp(x)) -> x
2351// * log(x**y) -> y*log(x)
2352// * log(exp(y)) -> y*log(e)
2353// * log(exp2(y)) -> y*log(2)
2354// * log(exp10(y)) -> y*log(10)
2355// * log(sqrt(x)) -> 0.5*log(x)
2356// * log(pow(x,y)) -> y*log(x)
2357//
2358// lround, lroundf, lroundl:
2359// * lround(cnst) -> cnst'
2360//
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00002361// pow, powf, powl:
2362// * pow(exp(x),y) -> exp(x*y)
2363// * pow(sqrt(x),y) -> pow(x,y*0.5)
2364// * pow(pow(x,y),z)-> pow(x,y*z)
2365//
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00002366// round, roundf, roundl:
2367// * round(cnst) -> cnst'
2368//
2369// signbit:
2370// * signbit(cnst) -> cnst'
2371// * signbit(nncst) -> 0 (if pstv is a non-negative constant)
2372//
2373// sqrt, sqrtf, sqrtl:
2374// * sqrt(expN(x)) -> expN(x*0.5)
2375// * sqrt(Nroot(x)) -> pow(x,1/(2*N))
2376// * sqrt(pow(x,y)) -> pow(|x|,y*0.5)
2377//
2378// stpcpy:
2379// * stpcpy(str, "literal") ->
2380// llvm.memcpy(str,"literal",strlen("literal")+1,1)
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00002381//
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00002382// tan, tanf, tanl:
2383// * tan(atan(x)) -> x
2384//
2385// trunc, truncf, truncl:
2386// * trunc(cnst) -> cnst'
2387//
2388//