blob: 2a00ae1093ba7439c5bd55c6c3a3d668b09b3e1d [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.
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000137 FunctionType *FT = Callee->getFunctionType();
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000138 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.
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000187 FunctionType *FT = Callee->getFunctionType();
Chris Lattnerf5b6bc72009-04-12 05:06:39 +0000188 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.
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000235 FunctionType *FT = Callee->getFunctionType();
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000236 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.
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000285 FunctionType *FT = Callee->getFunctionType();
Benjamin Kramer06f25cf2010-09-29 21:50:51 +0000286 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.
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000326 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
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000341 // strcmp(x, y) -> cnst (if both x and y are constant strings)
Bill Wendling0582ae92009-03-13 04:39:26 +0000342 if (HasStr1 && HasStr2)
Eric Christopher37c8b862009-10-07 21:14:25 +0000343 return ConstantInt::get(CI->getType(),
Eli Friedman79286082011-10-05 22:27:16 +0000344 StringRef(Str1).compare(Str2));
345
346 if (HasStr1 && Str1.empty()) // strcmp("", x) -> -*x
347 return B.CreateNeg(B.CreateZExt(B.CreateLoad(Str2P, "strcmpload"),
348 CI->getType()));
349
350 if (HasStr2 && Str2.empty()) // strcmp(x,"") -> *x
351 return B.CreateZExt(B.CreateLoad(Str1P, "strcmpload"), CI->getType());
Nick Lewycky13a09e22008-12-21 00:19:21 +0000352
353 // strcmp(P, "x") -> memcmp(P, "x", 2)
354 uint64_t Len1 = GetStringLength(Str1P);
355 uint64_t Len2 = GetStringLength(Str2P);
Chris Lattner849832c2009-06-19 04:17:36 +0000356 if (Len1 && Len2) {
Dan Gohmanf14d9192009-08-18 00:48:13 +0000357 // These optimizations require TargetData.
358 if (!TD) return 0;
359
Nick Lewycky13a09e22008-12-21 00:19:21 +0000360 return EmitMemCmp(Str1P, Str2P,
Owen Anderson1d0be152009-08-13 21:58:54 +0000361 ConstantInt::get(TD->getIntPtrType(*Context),
Eric Christopherb6174e32010-03-05 22:25:30 +0000362 std::min(Len1, Len2)), B, TD);
Nick Lewycky13a09e22008-12-21 00:19:21 +0000363 }
364
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000365 return 0;
366 }
367};
368
369//===---------------------------------------===//
370// 'strncmp' Optimizations
371
Chris Lattner3e8b6632009-09-02 06:11:42 +0000372struct StrNCmpOpt : public LibCallOptimization {
Eric Christopher7a61d702008-08-08 19:39:37 +0000373 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000374 // Verify the "strncmp" function prototype.
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000375 FunctionType *FT = Callee->getFunctionType();
Eric Christopher37c8b862009-10-07 21:14:25 +0000376 if (FT->getNumParams() != 3 ||
Nick Lewycky10d2f4d2010-07-06 03:53:43 +0000377 !FT->getReturnType()->isIntegerTy(32) ||
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000378 FT->getParamType(0) != FT->getParamType(1) ||
Benjamin Kramera1bf4ca2010-12-27 00:16:46 +0000379 FT->getParamType(0) != B.getInt8PtrTy() ||
Duncan Sands1df98592010-02-16 11:11:14 +0000380 !FT->getParamType(2)->isIntegerTy())
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000381 return 0;
Eric Christopher37c8b862009-10-07 21:14:25 +0000382
Gabor Greifaee5dc12010-06-24 10:42:46 +0000383 Value *Str1P = CI->getArgOperand(0), *Str2P = CI->getArgOperand(1);
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000384 if (Str1P == Str2P) // strncmp(x,x,n) -> 0
Owen Andersoneed707b2009-07-24 23:12:02 +0000385 return ConstantInt::get(CI->getType(), 0);
Eric Christopher37c8b862009-10-07 21:14:25 +0000386
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000387 // Get the length argument if it is constant.
388 uint64_t Length;
Gabor Greifaee5dc12010-06-24 10:42:46 +0000389 if (ConstantInt *LengthArg = dyn_cast<ConstantInt>(CI->getArgOperand(2)))
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000390 Length = LengthArg->getZExtValue();
391 else
392 return 0;
Eric Christopher37c8b862009-10-07 21:14:25 +0000393
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000394 if (Length == 0) // strncmp(x,y,0) -> 0
Owen Andersoneed707b2009-07-24 23:12:02 +0000395 return ConstantInt::get(CI->getType(), 0);
Eric Christopher37c8b862009-10-07 21:14:25 +0000396
Benjamin Kramerea9ca022010-06-16 10:30:29 +0000397 if (TD && Length == 1) // strncmp(x,y,1) -> memcmp(x,y,1)
Gabor Greif8e1ebff2010-06-30 12:42:43 +0000398 return EmitMemCmp(Str1P, Str2P, CI->getArgOperand(2), B, TD);
Benjamin Kramerea9ca022010-06-16 10:30:29 +0000399
Bill Wendling0582ae92009-03-13 04:39:26 +0000400 std::string Str1, Str2;
401 bool HasStr1 = GetConstantStringInfo(Str1P, Str1);
402 bool HasStr2 = GetConstantStringInfo(Str2P, Str2);
Eric Christopher37c8b862009-10-07 21:14:25 +0000403
Eli Friedman79286082011-10-05 22:27:16 +0000404 // strncmp(x, y) -> cnst (if both x and y are constant strings)
405 if (HasStr1 && HasStr2) {
406 StringRef SubStr1 = StringRef(Str1).substr(0, Length);
407 StringRef SubStr2 = StringRef(Str2).substr(0, Length);
408 return ConstantInt::get(CI->getType(), SubStr1.compare(SubStr2));
409 }
410
411 if (HasStr1 && Str1.empty()) // strncmp("", x, n) -> -*x
412 return B.CreateNeg(B.CreateZExt(B.CreateLoad(Str2P, "strcmpload"),
413 CI->getType()));
Eric Christopher37c8b862009-10-07 21:14:25 +0000414
Bill Wendling0582ae92009-03-13 04:39:26 +0000415 if (HasStr2 && Str2.empty()) // strncmp(x, "", n) -> *x
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000416 return B.CreateZExt(B.CreateLoad(Str1P, "strcmpload"), CI->getType());
Eric Christopher37c8b862009-10-07 21:14:25 +0000417
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000418 return 0;
419 }
420};
421
422
423//===---------------------------------------===//
424// 'strcpy' Optimizations
425
Chris Lattner3e8b6632009-09-02 06:11:42 +0000426struct StrCpyOpt : public LibCallOptimization {
Evan Chengeb8c6452010-03-24 20:19:04 +0000427 bool OptChkCall; // True if it's optimizing a __strcpy_chk libcall.
428
429 StrCpyOpt(bool c) : OptChkCall(c) {}
430
Eric Christopher7a61d702008-08-08 19:39:37 +0000431 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000432 // Verify the "strcpy" function prototype.
Evan Cheng0289b412010-03-23 15:48:04 +0000433 unsigned NumParams = OptChkCall ? 3 : 2;
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000434 FunctionType *FT = Callee->getFunctionType();
Evan Cheng0289b412010-03-23 15:48:04 +0000435 if (FT->getNumParams() != NumParams ||
436 FT->getReturnType() != FT->getParamType(0) ||
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000437 FT->getParamType(0) != FT->getParamType(1) ||
Benjamin Kramera1bf4ca2010-12-27 00:16:46 +0000438 FT->getParamType(0) != B.getInt8PtrTy())
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000439 return 0;
Eric Christopher37c8b862009-10-07 21:14:25 +0000440
Gabor Greifaee5dc12010-06-24 10:42:46 +0000441 Value *Dst = CI->getArgOperand(0), *Src = CI->getArgOperand(1);
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000442 if (Dst == Src) // strcpy(x,x) -> x
443 return Src;
Eric Christopher37c8b862009-10-07 21:14:25 +0000444
Dan Gohmanf14d9192009-08-18 00:48:13 +0000445 // These optimizations require TargetData.
446 if (!TD) return 0;
447
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000448 // See if we can get the length of the input string.
449 uint64_t Len = GetStringLength(Src);
Chris Lattner56b4f2b2008-05-01 06:39:12 +0000450 if (Len == 0) return 0;
Eric Christopher37c8b862009-10-07 21:14:25 +0000451
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000452 // We have enough information to now generate the memcpy call to do the
453 // concatenation for us. Make a memcpy to copy the nul byte with align = 1.
Evan Cheng0289b412010-03-23 15:48:04 +0000454 if (OptChkCall)
455 EmitMemCpyChk(Dst, Src,
456 ConstantInt::get(TD->getIntPtrType(*Context), Len),
Gabor Greifaee5dc12010-06-24 10:42:46 +0000457 CI->getArgOperand(2), B, TD);
Evan Cheng0289b412010-03-23 15:48:04 +0000458 else
Benjamin Kramera1bf4ca2010-12-27 00:16:46 +0000459 B.CreateMemCpy(Dst, Src,
460 ConstantInt::get(TD->getIntPtrType(*Context), Len), 1);
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000461 return Dst;
462 }
463};
464
Chris Lattnerf5b6bc72009-04-12 05:06:39 +0000465//===---------------------------------------===//
466// 'strncpy' Optimizations
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000467
Chris Lattner3e8b6632009-09-02 06:11:42 +0000468struct StrNCpyOpt : public LibCallOptimization {
Chris Lattnerf5b6bc72009-04-12 05:06:39 +0000469 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000470 FunctionType *FT = Callee->getFunctionType();
Chris Lattnerf5b6bc72009-04-12 05:06:39 +0000471 if (FT->getNumParams() != 3 || FT->getReturnType() != FT->getParamType(0) ||
472 FT->getParamType(0) != FT->getParamType(1) ||
Benjamin Kramera1bf4ca2010-12-27 00:16:46 +0000473 FT->getParamType(0) != B.getInt8PtrTy() ||
Duncan Sands1df98592010-02-16 11:11:14 +0000474 !FT->getParamType(2)->isIntegerTy())
Chris Lattnerf5b6bc72009-04-12 05:06:39 +0000475 return 0;
476
Gabor Greifaee5dc12010-06-24 10:42:46 +0000477 Value *Dst = CI->getArgOperand(0);
478 Value *Src = CI->getArgOperand(1);
479 Value *LenOp = CI->getArgOperand(2);
Chris Lattnerf5b6bc72009-04-12 05:06:39 +0000480
481 // See if we can get the length of the input string.
482 uint64_t SrcLen = GetStringLength(Src);
483 if (SrcLen == 0) return 0;
484 --SrcLen;
485
486 if (SrcLen == 0) {
487 // strncpy(x, "", y) -> memset(x, '\0', y, 1)
Benjamin Kramera1bf4ca2010-12-27 00:16:46 +0000488 B.CreateMemSet(Dst, B.getInt8('\0'), LenOp, 1);
Chris Lattnerf5b6bc72009-04-12 05:06:39 +0000489 return Dst;
490 }
491
492 uint64_t Len;
493 if (ConstantInt *LengthArg = dyn_cast<ConstantInt>(LenOp))
494 Len = LengthArg->getZExtValue();
495 else
496 return 0;
497
498 if (Len == 0) return Dst; // strncpy(x, y, 0) -> x
499
Dan Gohmanf14d9192009-08-18 00:48:13 +0000500 // These optimizations require TargetData.
501 if (!TD) return 0;
502
Chris Lattnerf5b6bc72009-04-12 05:06:39 +0000503 // Let strncpy handle the zero padding
504 if (Len > SrcLen+1) return 0;
505
506 // strncpy(x, s, c) -> memcpy(x, s, c, 1) [s and c are constant]
Benjamin Kramera1bf4ca2010-12-27 00:16:46 +0000507 B.CreateMemCpy(Dst, Src,
508 ConstantInt::get(TD->getIntPtrType(*Context), Len), 1);
Chris Lattnerf5b6bc72009-04-12 05:06:39 +0000509
510 return Dst;
511 }
512};
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000513
514//===---------------------------------------===//
515// 'strlen' Optimizations
516
Chris Lattner3e8b6632009-09-02 06:11:42 +0000517struct StrLenOpt : public LibCallOptimization {
Eric Christopher7a61d702008-08-08 19:39:37 +0000518 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000519 FunctionType *FT = Callee->getFunctionType();
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000520 if (FT->getNumParams() != 1 ||
Benjamin Kramera1bf4ca2010-12-27 00:16:46 +0000521 FT->getParamType(0) != B.getInt8PtrTy() ||
Duncan Sands1df98592010-02-16 11:11:14 +0000522 !FT->getReturnType()->isIntegerTy())
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000523 return 0;
Eric Christopher37c8b862009-10-07 21:14:25 +0000524
Gabor Greifaee5dc12010-06-24 10:42:46 +0000525 Value *Src = CI->getArgOperand(0);
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000526
527 // Constant folding: strlen("xyz") -> 3
528 if (uint64_t Len = GetStringLength(Src))
Owen Andersoneed707b2009-07-24 23:12:02 +0000529 return ConstantInt::get(CI->getType(), Len-1);
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000530
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000531 // strlen(x) != 0 --> *x != 0
532 // strlen(x) == 0 --> *x == 0
Chris Lattner98d67d72009-12-23 23:24:51 +0000533 if (IsOnlyUsedInZeroEqualityComparison(CI))
534 return B.CreateZExt(B.CreateLoad(Src, "strlenfirst"), CI->getType());
535 return 0;
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000536 }
537};
538
Benjamin Kramer05f585e2010-09-29 23:52:12 +0000539
540//===---------------------------------------===//
541// 'strpbrk' Optimizations
542
543struct StrPBrkOpt : public LibCallOptimization {
544 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000545 FunctionType *FT = Callee->getFunctionType();
Benjamin Kramer05f585e2010-09-29 23:52:12 +0000546 if (FT->getNumParams() != 2 ||
Benjamin Kramera1bf4ca2010-12-27 00:16:46 +0000547 FT->getParamType(0) != B.getInt8PtrTy() ||
Benjamin Kramer05f585e2010-09-29 23:52:12 +0000548 FT->getParamType(1) != FT->getParamType(0) ||
549 FT->getReturnType() != FT->getParamType(0))
550 return 0;
551
552 std::string S1, S2;
553 bool HasS1 = GetConstantStringInfo(CI->getArgOperand(0), S1);
554 bool HasS2 = GetConstantStringInfo(CI->getArgOperand(1), S2);
555
556 // strpbrk(s, "") -> NULL
557 // strpbrk("", s) -> NULL
558 if ((HasS1 && S1.empty()) || (HasS2 && S2.empty()))
559 return Constant::getNullValue(CI->getType());
560
561 // Constant folding.
562 if (HasS1 && HasS2) {
563 size_t I = S1.find_first_of(S2);
564 if (I == std::string::npos) // No match.
565 return Constant::getNullValue(CI->getType());
566
Benjamin Kramera1bf4ca2010-12-27 00:16:46 +0000567 return B.CreateGEP(CI->getArgOperand(0), B.getInt64(I), "strpbrk");
Benjamin Kramer05f585e2010-09-29 23:52:12 +0000568 }
569
570 // strpbrk(s, "a") -> strchr(s, 'a')
571 if (TD && HasS2 && S2.size() == 1)
572 return EmitStrChr(CI->getArgOperand(0), S2[0], B, TD);
573
574 return 0;
575 }
576};
577
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000578//===---------------------------------------===//
Chris Lattner24604112009-12-16 09:32:05 +0000579// 'strto*' Optimizations. This handles strtol, strtod, strtof, strtoul, etc.
Nick Lewycky4c498412009-02-13 15:31:46 +0000580
Chris Lattner3e8b6632009-09-02 06:11:42 +0000581struct StrToOpt : public LibCallOptimization {
Nick Lewycky4c498412009-02-13 15:31:46 +0000582 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000583 FunctionType *FT = Callee->getFunctionType();
Nick Lewycky4c498412009-02-13 15:31:46 +0000584 if ((FT->getNumParams() != 2 && FT->getNumParams() != 3) ||
Duncan Sands1df98592010-02-16 11:11:14 +0000585 !FT->getParamType(0)->isPointerTy() ||
586 !FT->getParamType(1)->isPointerTy())
Nick Lewycky4c498412009-02-13 15:31:46 +0000587 return 0;
588
Gabor Greifaee5dc12010-06-24 10:42:46 +0000589 Value *EndPtr = CI->getArgOperand(1);
Nick Lewycky02b6a6a2009-02-13 17:08:33 +0000590 if (isa<ConstantPointerNull>(EndPtr)) {
Dan Gohmanc32046e2010-12-17 01:09:43 +0000591 // With a null EndPtr, this function won't capture the main argument.
592 // It would be readonly too, except that it still may write to errno.
Nick Lewycky4c498412009-02-13 15:31:46 +0000593 CI->addAttribute(1, Attribute::NoCapture);
Nick Lewycky02b6a6a2009-02-13 17:08:33 +0000594 }
Nick Lewycky4c498412009-02-13 15:31:46 +0000595
596 return 0;
597 }
598};
599
Chris Lattner24604112009-12-16 09:32:05 +0000600//===---------------------------------------===//
Benjamin Kramer9510a252010-09-30 00:58:35 +0000601// 'strspn' Optimizations
602
603struct StrSpnOpt : public LibCallOptimization {
604 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000605 FunctionType *FT = Callee->getFunctionType();
Benjamin Kramer9510a252010-09-30 00:58:35 +0000606 if (FT->getNumParams() != 2 ||
Benjamin Kramera1bf4ca2010-12-27 00:16:46 +0000607 FT->getParamType(0) != B.getInt8PtrTy() ||
Benjamin Kramer9510a252010-09-30 00:58:35 +0000608 FT->getParamType(1) != FT->getParamType(0) ||
609 !FT->getReturnType()->isIntegerTy())
610 return 0;
611
612 std::string S1, S2;
613 bool HasS1 = GetConstantStringInfo(CI->getArgOperand(0), S1);
614 bool HasS2 = GetConstantStringInfo(CI->getArgOperand(1), S2);
615
616 // strspn(s, "") -> 0
617 // strspn("", s) -> 0
618 if ((HasS1 && S1.empty()) || (HasS2 && S2.empty()))
619 return Constant::getNullValue(CI->getType());
620
621 // Constant folding.
622 if (HasS1 && HasS2)
623 return ConstantInt::get(CI->getType(), strspn(S1.c_str(), S2.c_str()));
624
625 return 0;
626 }
627};
628
629//===---------------------------------------===//
630// 'strcspn' Optimizations
631
632struct StrCSpnOpt : public LibCallOptimization {
633 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000634 FunctionType *FT = Callee->getFunctionType();
Benjamin Kramer9510a252010-09-30 00:58:35 +0000635 if (FT->getNumParams() != 2 ||
Benjamin Kramera1bf4ca2010-12-27 00:16:46 +0000636 FT->getParamType(0) != B.getInt8PtrTy() ||
Benjamin Kramer9510a252010-09-30 00:58:35 +0000637 FT->getParamType(1) != FT->getParamType(0) ||
638 !FT->getReturnType()->isIntegerTy())
639 return 0;
640
641 std::string S1, S2;
642 bool HasS1 = GetConstantStringInfo(CI->getArgOperand(0), S1);
643 bool HasS2 = GetConstantStringInfo(CI->getArgOperand(1), S2);
644
645 // strcspn("", s) -> 0
646 if (HasS1 && S1.empty())
647 return Constant::getNullValue(CI->getType());
648
649 // Constant folding.
650 if (HasS1 && HasS2)
651 return ConstantInt::get(CI->getType(), strcspn(S1.c_str(), S2.c_str()));
652
653 // strcspn(s, "") -> strlen(s)
654 if (TD && HasS2 && S2.empty())
655 return EmitStrLen(CI->getArgOperand(0), B, TD);
656
657 return 0;
658 }
659};
660
661//===---------------------------------------===//
Chris Lattner24604112009-12-16 09:32:05 +0000662// 'strstr' Optimizations
663
664struct StrStrOpt : public LibCallOptimization {
665 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000666 FunctionType *FT = Callee->getFunctionType();
Chris Lattner24604112009-12-16 09:32:05 +0000667 if (FT->getNumParams() != 2 ||
Duncan Sands1df98592010-02-16 11:11:14 +0000668 !FT->getParamType(0)->isPointerTy() ||
669 !FT->getParamType(1)->isPointerTy() ||
670 !FT->getReturnType()->isPointerTy())
Chris Lattner24604112009-12-16 09:32:05 +0000671 return 0;
672
673 // fold strstr(x, x) -> x.
Gabor Greifaee5dc12010-06-24 10:42:46 +0000674 if (CI->getArgOperand(0) == CI->getArgOperand(1))
675 return B.CreateBitCast(CI->getArgOperand(0), CI->getType());
Mikhail Glushenkoved5cb592010-01-04 07:55:25 +0000676
Benjamin Kramer386e9182010-06-15 21:34:25 +0000677 // fold strstr(a, b) == a -> strncmp(a, b, strlen(b)) == 0
Gabor Greif8e1ebff2010-06-30 12:42:43 +0000678 if (TD && IsOnlyUsedInEqualityComparison(CI, CI->getArgOperand(0))) {
679 Value *StrLen = EmitStrLen(CI->getArgOperand(1), B, TD);
680 Value *StrNCmp = EmitStrNCmp(CI->getArgOperand(0), CI->getArgOperand(1),
Benjamin Kramer386e9182010-06-15 21:34:25 +0000681 StrLen, B, TD);
682 for (Value::use_iterator UI = CI->use_begin(), UE = CI->use_end();
683 UI != UE; ) {
Gabor Greif96f1d8e2010-07-22 13:36:47 +0000684 ICmpInst *Old = cast<ICmpInst>(*UI++);
Benjamin Kramer386e9182010-06-15 21:34:25 +0000685 Value *Cmp = B.CreateICmp(Old->getPredicate(), StrNCmp,
686 ConstantInt::getNullValue(StrNCmp->getType()),
687 "cmp");
688 Old->replaceAllUsesWith(Cmp);
689 Old->eraseFromParent();
690 }
691 return CI;
692 }
693
Chris Lattner24604112009-12-16 09:32:05 +0000694 // See if either input string is a constant string.
695 std::string SearchStr, ToFindStr;
Gabor Greifaee5dc12010-06-24 10:42:46 +0000696 bool HasStr1 = GetConstantStringInfo(CI->getArgOperand(0), SearchStr);
697 bool HasStr2 = GetConstantStringInfo(CI->getArgOperand(1), ToFindStr);
Mikhail Glushenkoved5cb592010-01-04 07:55:25 +0000698
Chris Lattner24604112009-12-16 09:32:05 +0000699 // fold strstr(x, "") -> x.
700 if (HasStr2 && ToFindStr.empty())
Gabor Greifaee5dc12010-06-24 10:42:46 +0000701 return B.CreateBitCast(CI->getArgOperand(0), CI->getType());
Mikhail Glushenkoved5cb592010-01-04 07:55:25 +0000702
Chris Lattner24604112009-12-16 09:32:05 +0000703 // If both strings are known, constant fold it.
704 if (HasStr1 && HasStr2) {
705 std::string::size_type Offset = SearchStr.find(ToFindStr);
Mikhail Glushenkoved5cb592010-01-04 07:55:25 +0000706
Chris Lattner24604112009-12-16 09:32:05 +0000707 if (Offset == std::string::npos) // strstr("foo", "bar") -> null
708 return Constant::getNullValue(CI->getType());
709
710 // strstr("abcd", "bc") -> gep((char*)"abcd", 1)
Gabor Greifaee5dc12010-06-24 10:42:46 +0000711 Value *Result = CastToCStr(CI->getArgOperand(0), B);
Chris Lattner24604112009-12-16 09:32:05 +0000712 Result = B.CreateConstInBoundsGEP1_64(Result, Offset, "strstr");
713 return B.CreateBitCast(Result, CI->getType());
714 }
Mikhail Glushenkoved5cb592010-01-04 07:55:25 +0000715
Chris Lattner24604112009-12-16 09:32:05 +0000716 // fold strstr(x, "y") -> strchr(x, 'y').
717 if (HasStr2 && ToFindStr.size() == 1)
Gabor Greifa3997812010-07-22 10:37:47 +0000718 return B.CreateBitCast(EmitStrChr(CI->getArgOperand(0),
719 ToFindStr[0], B, TD), CI->getType());
Chris Lattner24604112009-12-16 09:32:05 +0000720 return 0;
721 }
722};
Mikhail Glushenkoved5cb592010-01-04 07:55:25 +0000723
Nick Lewycky4c498412009-02-13 15:31:46 +0000724
725//===---------------------------------------===//
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000726// 'memcmp' Optimizations
727
Chris Lattner3e8b6632009-09-02 06:11:42 +0000728struct MemCmpOpt : public LibCallOptimization {
Eric Christopher7a61d702008-08-08 19:39:37 +0000729 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000730 FunctionType *FT = Callee->getFunctionType();
Duncan Sands1df98592010-02-16 11:11:14 +0000731 if (FT->getNumParams() != 3 || !FT->getParamType(0)->isPointerTy() ||
732 !FT->getParamType(1)->isPointerTy() ||
Duncan Sandsb0bc6c32010-02-15 16:12:20 +0000733 !FT->getReturnType()->isIntegerTy(32))
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000734 return 0;
Duncan Sandsec00fcb2008-05-19 09:27:24 +0000735
Gabor Greifaee5dc12010-06-24 10:42:46 +0000736 Value *LHS = CI->getArgOperand(0), *RHS = CI->getArgOperand(1);
Duncan Sandsec00fcb2008-05-19 09:27:24 +0000737
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000738 if (LHS == RHS) // memcmp(s,s,x) -> 0
Owen Andersona7235ea2009-07-31 20:28:14 +0000739 return Constant::getNullValue(CI->getType());
Duncan Sandsec00fcb2008-05-19 09:27:24 +0000740
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000741 // Make sure we have a constant length.
Gabor Greifaee5dc12010-06-24 10:42:46 +0000742 ConstantInt *LenC = dyn_cast<ConstantInt>(CI->getArgOperand(2));
Chris Lattner56b4f2b2008-05-01 06:39:12 +0000743 if (!LenC) return 0;
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000744 uint64_t Len = LenC->getZExtValue();
Duncan Sandsec00fcb2008-05-19 09:27:24 +0000745
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000746 if (Len == 0) // memcmp(s1,s2,0) -> 0
Owen Andersona7235ea2009-07-31 20:28:14 +0000747 return Constant::getNullValue(CI->getType());
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000748
Benjamin Kramer48aefe12010-05-25 22:53:43 +0000749 // memcmp(S1,S2,1) -> *(unsigned char*)LHS - *(unsigned char*)RHS
750 if (Len == 1) {
751 Value *LHSV = B.CreateZExt(B.CreateLoad(CastToCStr(LHS, B), "lhsc"),
752 CI->getType(), "lhsv");
753 Value *RHSV = B.CreateZExt(B.CreateLoad(CastToCStr(RHS, B), "rhsc"),
754 CI->getType(), "rhsv");
Benjamin Kramer1464c1d2010-05-26 09:45:04 +0000755 return B.CreateSub(LHSV, RHSV, "chardiff");
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000756 }
Duncan Sandsec00fcb2008-05-19 09:27:24 +0000757
Benjamin Kramer992a6372009-11-05 17:44:22 +0000758 // Constant folding: memcmp(x, y, l) -> cnst (all arguments are constant)
759 std::string LHSStr, RHSStr;
760 if (GetConstantStringInfo(LHS, LHSStr) &&
761 GetConstantStringInfo(RHS, RHSStr)) {
762 // Make sure we're not reading out-of-bounds memory.
763 if (Len > LHSStr.length() || Len > RHSStr.length())
764 return 0;
765 uint64_t Ret = memcmp(LHSStr.data(), RHSStr.data(), Len);
766 return ConstantInt::get(CI->getType(), Ret);
767 }
768
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000769 return 0;
770 }
771};
772
773//===---------------------------------------===//
774// 'memcpy' Optimizations
775
Chris Lattner3e8b6632009-09-02 06:11:42 +0000776struct MemCpyOpt : public LibCallOptimization {
Eric Christopher7a61d702008-08-08 19:39:37 +0000777 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
Dan Gohmanf14d9192009-08-18 00:48:13 +0000778 // These optimizations require TargetData.
779 if (!TD) return 0;
780
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000781 FunctionType *FT = Callee->getFunctionType();
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000782 if (FT->getNumParams() != 3 || FT->getReturnType() != FT->getParamType(0) ||
Duncan Sands1df98592010-02-16 11:11:14 +0000783 !FT->getParamType(0)->isPointerTy() ||
784 !FT->getParamType(1)->isPointerTy() ||
Owen Anderson1d0be152009-08-13 21:58:54 +0000785 FT->getParamType(2) != TD->getIntPtrType(*Context))
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000786 return 0;
787
788 // memcpy(x, y, n) -> llvm.memcpy(x, y, n, 1)
Benjamin Kramera1bf4ca2010-12-27 00:16:46 +0000789 B.CreateMemCpy(CI->getArgOperand(0), CI->getArgOperand(1),
790 CI->getArgOperand(2), 1);
Gabor Greifaee5dc12010-06-24 10:42:46 +0000791 return CI->getArgOperand(0);
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000792 }
793};
794
Eli Friedmand83ae7d2008-11-30 08:32:11 +0000795//===---------------------------------------===//
796// 'memmove' Optimizations
797
Chris Lattner3e8b6632009-09-02 06:11:42 +0000798struct MemMoveOpt : public LibCallOptimization {
Eli Friedmand83ae7d2008-11-30 08:32:11 +0000799 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
Dan Gohmanf14d9192009-08-18 00:48:13 +0000800 // These optimizations require TargetData.
801 if (!TD) return 0;
802
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000803 FunctionType *FT = Callee->getFunctionType();
Eli Friedmand83ae7d2008-11-30 08:32:11 +0000804 if (FT->getNumParams() != 3 || FT->getReturnType() != FT->getParamType(0) ||
Duncan Sands1df98592010-02-16 11:11:14 +0000805 !FT->getParamType(0)->isPointerTy() ||
806 !FT->getParamType(1)->isPointerTy() ||
Owen Anderson1d0be152009-08-13 21:58:54 +0000807 FT->getParamType(2) != TD->getIntPtrType(*Context))
Eli Friedmand83ae7d2008-11-30 08:32:11 +0000808 return 0;
809
810 // memmove(x, y, n) -> llvm.memmove(x, y, n, 1)
Benjamin Kramera1bf4ca2010-12-27 00:16:46 +0000811 B.CreateMemMove(CI->getArgOperand(0), CI->getArgOperand(1),
812 CI->getArgOperand(2), 1);
Gabor Greifaee5dc12010-06-24 10:42:46 +0000813 return CI->getArgOperand(0);
Eli Friedmand83ae7d2008-11-30 08:32:11 +0000814 }
815};
816
817//===---------------------------------------===//
818// 'memset' Optimizations
819
Chris Lattner3e8b6632009-09-02 06:11:42 +0000820struct MemSetOpt : public LibCallOptimization {
Eli Friedmand83ae7d2008-11-30 08:32:11 +0000821 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
Dan Gohmanf14d9192009-08-18 00:48:13 +0000822 // These optimizations require TargetData.
823 if (!TD) return 0;
824
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000825 FunctionType *FT = Callee->getFunctionType();
Eli Friedmand83ae7d2008-11-30 08:32:11 +0000826 if (FT->getNumParams() != 3 || FT->getReturnType() != FT->getParamType(0) ||
Duncan Sands1df98592010-02-16 11:11:14 +0000827 !FT->getParamType(0)->isPointerTy() ||
828 !FT->getParamType(1)->isIntegerTy() ||
Owen Anderson1d0be152009-08-13 21:58:54 +0000829 FT->getParamType(2) != TD->getIntPtrType(*Context))
Eli Friedmand83ae7d2008-11-30 08:32:11 +0000830 return 0;
831
832 // memset(p, v, n) -> llvm.memset(p, v, n, 1)
Benjamin Kramera1bf4ca2010-12-27 00:16:46 +0000833 Value *Val = B.CreateIntCast(CI->getArgOperand(1), B.getInt8Ty(), false);
834 B.CreateMemSet(CI->getArgOperand(0), Val, CI->getArgOperand(2), 1);
Gabor Greifaee5dc12010-06-24 10:42:46 +0000835 return CI->getArgOperand(0);
Eli Friedmand83ae7d2008-11-30 08:32:11 +0000836 }
837};
838
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000839//===----------------------------------------------------------------------===//
840// Math Library Optimizations
841//===----------------------------------------------------------------------===//
842
843//===---------------------------------------===//
844// 'pow*' Optimizations
845
Chris Lattner3e8b6632009-09-02 06:11:42 +0000846struct PowOpt : public LibCallOptimization {
Eric Christopher7a61d702008-08-08 19:39:37 +0000847 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000848 FunctionType *FT = Callee->getFunctionType();
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000849 // Just make sure this has 2 arguments of the same FP type, which match the
850 // result type.
851 if (FT->getNumParams() != 2 || FT->getReturnType() != FT->getParamType(0) ||
852 FT->getParamType(0) != FT->getParamType(1) ||
Duncan Sandsb0bc6c32010-02-15 16:12:20 +0000853 !FT->getParamType(0)->isFloatingPointTy())
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000854 return 0;
Eric Christopher37c8b862009-10-07 21:14:25 +0000855
Gabor Greifaee5dc12010-06-24 10:42:46 +0000856 Value *Op1 = CI->getArgOperand(0), *Op2 = CI->getArgOperand(1);
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000857 if (ConstantFP *Op1C = dyn_cast<ConstantFP>(Op1)) {
858 if (Op1C->isExactlyValue(1.0)) // pow(1.0, x) -> 1.0
859 return Op1C;
860 if (Op1C->isExactlyValue(2.0)) // pow(2.0, x) -> exp2(x)
Dan Gohman76926b62009-09-26 18:10:13 +0000861 return EmitUnaryFloatFnCall(Op2, "exp2", B, Callee->getAttributes());
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000862 }
Eric Christopher37c8b862009-10-07 21:14:25 +0000863
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000864 ConstantFP *Op2C = dyn_cast<ConstantFP>(Op2);
865 if (Op2C == 0) return 0;
Eric Christopher37c8b862009-10-07 21:14:25 +0000866
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000867 if (Op2C->getValueAPF().isZero()) // pow(x, 0.0) -> 1.0
Owen Anderson6f83c9c2009-07-27 20:59:43 +0000868 return ConstantFP::get(CI->getType(), 1.0);
Eric Christopher37c8b862009-10-07 21:14:25 +0000869
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000870 if (Op2C->isExactlyValue(0.5)) {
Dan Gohman79cb8402009-09-25 23:10:17 +0000871 // Expand pow(x, 0.5) to (x == -infinity ? +infinity : fabs(sqrt(x))).
872 // This is faster than calling pow, and still handles negative zero
873 // and negative infinite correctly.
874 // TODO: In fast-math mode, this could be just sqrt(x).
875 // TODO: In finite-only mode, this could be just fabs(sqrt(x)).
Dan Gohmana23643d2009-09-25 23:40:21 +0000876 Value *Inf = ConstantFP::getInfinity(CI->getType());
877 Value *NegInf = ConstantFP::getInfinity(CI->getType(), true);
Dan Gohman76926b62009-09-26 18:10:13 +0000878 Value *Sqrt = EmitUnaryFloatFnCall(Op1, "sqrt", B,
879 Callee->getAttributes());
880 Value *FAbs = EmitUnaryFloatFnCall(Sqrt, "fabs", B,
881 Callee->getAttributes());
Benjamin Kramera9390a42011-09-27 20:39:19 +0000882 Value *FCmp = B.CreateFCmpOEQ(Op1, NegInf);
883 Value *Sel = B.CreateSelect(FCmp, Inf, FAbs);
Dan Gohman79cb8402009-09-25 23:10:17 +0000884 return Sel;
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000885 }
Eric Christopher37c8b862009-10-07 21:14:25 +0000886
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000887 if (Op2C->isExactlyValue(1.0)) // pow(x, 1.0) -> x
888 return Op1;
889 if (Op2C->isExactlyValue(2.0)) // pow(x, 2.0) -> x*x
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000890 return B.CreateFMul(Op1, Op1, "pow2");
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000891 if (Op2C->isExactlyValue(-1.0)) // pow(x, -1.0) -> 1.0/x
Owen Anderson6f83c9c2009-07-27 20:59:43 +0000892 return B.CreateFDiv(ConstantFP::get(CI->getType(), 1.0),
Owen Andersonfa5cbd62009-07-03 19:42:02 +0000893 Op1, "powrecip");
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000894 return 0;
895 }
896};
897
898//===---------------------------------------===//
Chris Lattnere818f772008-05-02 18:43:35 +0000899// 'exp2' Optimizations
900
Chris Lattner3e8b6632009-09-02 06:11:42 +0000901struct Exp2Opt : public LibCallOptimization {
Eric Christopher7a61d702008-08-08 19:39:37 +0000902 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000903 FunctionType *FT = Callee->getFunctionType();
Chris Lattnere818f772008-05-02 18:43:35 +0000904 // Just make sure this has 1 argument of FP type, which matches the
905 // result type.
906 if (FT->getNumParams() != 1 || FT->getReturnType() != FT->getParamType(0) ||
Duncan Sandsb0bc6c32010-02-15 16:12:20 +0000907 !FT->getParamType(0)->isFloatingPointTy())
Chris Lattnere818f772008-05-02 18:43:35 +0000908 return 0;
Eric Christopher37c8b862009-10-07 21:14:25 +0000909
Gabor Greifaee5dc12010-06-24 10:42:46 +0000910 Value *Op = CI->getArgOperand(0);
Chris Lattnere818f772008-05-02 18:43:35 +0000911 // Turn exp2(sitofp(x)) -> ldexp(1.0, sext(x)) if sizeof(x) <= 32
912 // Turn exp2(uitofp(x)) -> ldexp(1.0, zext(x)) if sizeof(x) < 32
913 Value *LdExpArg = 0;
914 if (SIToFPInst *OpC = dyn_cast<SIToFPInst>(Op)) {
915 if (OpC->getOperand(0)->getType()->getPrimitiveSizeInBits() <= 32)
Benjamin Kramera9390a42011-09-27 20:39:19 +0000916 LdExpArg = B.CreateSExt(OpC->getOperand(0), B.getInt32Ty());
Chris Lattnere818f772008-05-02 18:43:35 +0000917 } else if (UIToFPInst *OpC = dyn_cast<UIToFPInst>(Op)) {
918 if (OpC->getOperand(0)->getType()->getPrimitiveSizeInBits() < 32)
Benjamin Kramera9390a42011-09-27 20:39:19 +0000919 LdExpArg = B.CreateZExt(OpC->getOperand(0), B.getInt32Ty());
Chris Lattnere818f772008-05-02 18:43:35 +0000920 }
Anton Korobeynikov9547cdf2009-06-18 20:05:31 +0000921
Chris Lattnere818f772008-05-02 18:43:35 +0000922 if (LdExpArg) {
923 const char *Name;
Chris Lattnercf0fe8d2009-10-05 05:54:46 +0000924 if (Op->getType()->isFloatTy())
Chris Lattnere818f772008-05-02 18:43:35 +0000925 Name = "ldexpf";
Chris Lattnercf0fe8d2009-10-05 05:54:46 +0000926 else if (Op->getType()->isDoubleTy())
Chris Lattnere818f772008-05-02 18:43:35 +0000927 Name = "ldexp";
928 else
929 Name = "ldexpl";
930
Owen Anderson6f83c9c2009-07-27 20:59:43 +0000931 Constant *One = ConstantFP::get(*Context, APFloat(1.0f));
Chris Lattnercf0fe8d2009-10-05 05:54:46 +0000932 if (!Op->getType()->isFloatTy())
Owen Andersonbaf3c402009-07-29 18:55:55 +0000933 One = ConstantExpr::getFPExtend(One, Op->getType());
Chris Lattnere818f772008-05-02 18:43:35 +0000934
935 Module *M = Caller->getParent();
936 Value *Callee = M->getOrInsertFunction(Name, Op->getType(),
Eric Christopher37c8b862009-10-07 21:14:25 +0000937 Op->getType(),
Benjamin Kramera1bf4ca2010-12-27 00:16:46 +0000938 B.getInt32Ty(), NULL);
Anton Korobeynikov9547cdf2009-06-18 20:05:31 +0000939 CallInst *CI = B.CreateCall2(Callee, One, LdExpArg);
940 if (const Function *F = dyn_cast<Function>(Callee->stripPointerCasts()))
941 CI->setCallingConv(F->getCallingConv());
942
943 return CI;
Chris Lattnere818f772008-05-02 18:43:35 +0000944 }
945 return 0;
946 }
947};
Chris Lattnere818f772008-05-02 18:43:35 +0000948
949//===---------------------------------------===//
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000950// Double -> Float Shrinking Optimizations for Unary Functions like 'floor'
951
Chris Lattner3e8b6632009-09-02 06:11:42 +0000952struct UnaryDoubleFPOpt : public LibCallOptimization {
Eric Christopher7a61d702008-08-08 19:39:37 +0000953 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000954 FunctionType *FT = Callee->getFunctionType();
Chris Lattnercf0fe8d2009-10-05 05:54:46 +0000955 if (FT->getNumParams() != 1 || !FT->getReturnType()->isDoubleTy() ||
956 !FT->getParamType(0)->isDoubleTy())
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000957 return 0;
Anton Korobeynikov9547cdf2009-06-18 20:05:31 +0000958
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000959 // If this is something like 'floor((double)floatval)', convert to floorf.
Gabor Greifaee5dc12010-06-24 10:42:46 +0000960 FPExtInst *Cast = dyn_cast<FPExtInst>(CI->getArgOperand(0));
Chris Lattnercf0fe8d2009-10-05 05:54:46 +0000961 if (Cast == 0 || !Cast->getOperand(0)->getType()->isFloatTy())
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000962 return 0;
963
964 // floor((double)floatval) -> (double)floorf(floatval)
965 Value *V = Cast->getOperand(0);
Dan Gohman76926b62009-09-26 18:10:13 +0000966 V = EmitUnaryFloatFnCall(V, Callee->getName().data(), B,
967 Callee->getAttributes());
Benjamin Kramera1bf4ca2010-12-27 00:16:46 +0000968 return B.CreateFPExt(V, B.getDoubleTy());
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000969 }
970};
971
972//===----------------------------------------------------------------------===//
973// Integer Optimizations
974//===----------------------------------------------------------------------===//
975
976//===---------------------------------------===//
977// 'ffs*' Optimizations
978
Chris Lattner3e8b6632009-09-02 06:11:42 +0000979struct FFSOpt : public LibCallOptimization {
Eric Christopher7a61d702008-08-08 19:39:37 +0000980 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000981 FunctionType *FT = Callee->getFunctionType();
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000982 // Just make sure this has 2 arguments of the same FP type, which match the
983 // result type.
Eric Christopher37c8b862009-10-07 21:14:25 +0000984 if (FT->getNumParams() != 1 ||
Nick Lewycky10d2f4d2010-07-06 03:53:43 +0000985 !FT->getReturnType()->isIntegerTy(32) ||
Duncan Sands1df98592010-02-16 11:11:14 +0000986 !FT->getParamType(0)->isIntegerTy())
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000987 return 0;
Eric Christopher37c8b862009-10-07 21:14:25 +0000988
Gabor Greifaee5dc12010-06-24 10:42:46 +0000989 Value *Op = CI->getArgOperand(0);
Eric Christopher37c8b862009-10-07 21:14:25 +0000990
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000991 // Constant fold.
992 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op)) {
993 if (CI->getValue() == 0) // ffs(0) -> 0.
Owen Andersona7235ea2009-07-31 20:28:14 +0000994 return Constant::getNullValue(CI->getType());
Benjamin Kramera1bf4ca2010-12-27 00:16:46 +0000995 // ffs(c) -> cttz(c)+1
996 return B.getInt32(CI->getValue().countTrailingZeros() + 1);
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000997 }
Eric Christopher37c8b862009-10-07 21:14:25 +0000998
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000999 // ffs(x) -> x != 0 ? (i32)llvm.cttz(x)+1 : 0
Jay Foad5fdd6c82011-07-12 14:06:48 +00001000 Type *ArgType = Op->getType();
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001001 Value *F = Intrinsic::getDeclaration(Callee->getParent(),
Benjamin Kramereb9a85f2011-07-14 17:45:39 +00001002 Intrinsic::cttz, ArgType);
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001003 Value *V = B.CreateCall(F, Op, "cttz");
Benjamin Kramera9390a42011-09-27 20:39:19 +00001004 V = B.CreateAdd(V, ConstantInt::get(V->getType(), 1));
1005 V = B.CreateIntCast(V, B.getInt32Ty(), false);
Eric Christopher37c8b862009-10-07 21:14:25 +00001006
Benjamin Kramera9390a42011-09-27 20:39:19 +00001007 Value *Cond = B.CreateICmpNE(Op, Constant::getNullValue(ArgType));
Benjamin Kramera1bf4ca2010-12-27 00:16:46 +00001008 return B.CreateSelect(Cond, V, B.getInt32(0));
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001009 }
1010};
1011
1012//===---------------------------------------===//
1013// 'isdigit' Optimizations
1014
Chris Lattner3e8b6632009-09-02 06:11:42 +00001015struct IsDigitOpt : public LibCallOptimization {
Eric Christopher7a61d702008-08-08 19:39:37 +00001016 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001017 FunctionType *FT = Callee->getFunctionType();
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001018 // We require integer(i32)
Duncan Sands1df98592010-02-16 11:11:14 +00001019 if (FT->getNumParams() != 1 || !FT->getReturnType()->isIntegerTy() ||
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00001020 !FT->getParamType(0)->isIntegerTy(32))
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001021 return 0;
Eric Christopher37c8b862009-10-07 21:14:25 +00001022
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001023 // isdigit(c) -> (c-'0') <u 10
Gabor Greifaee5dc12010-06-24 10:42:46 +00001024 Value *Op = CI->getArgOperand(0);
Benjamin Kramera1bf4ca2010-12-27 00:16:46 +00001025 Op = B.CreateSub(Op, B.getInt32('0'), "isdigittmp");
1026 Op = B.CreateICmpULT(Op, B.getInt32(10), "isdigit");
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001027 return B.CreateZExt(Op, CI->getType());
1028 }
1029};
1030
1031//===---------------------------------------===//
1032// 'isascii' Optimizations
1033
Chris Lattner3e8b6632009-09-02 06:11:42 +00001034struct IsAsciiOpt : public LibCallOptimization {
Eric Christopher7a61d702008-08-08 19:39:37 +00001035 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001036 FunctionType *FT = Callee->getFunctionType();
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001037 // We require integer(i32)
Duncan Sands1df98592010-02-16 11:11:14 +00001038 if (FT->getNumParams() != 1 || !FT->getReturnType()->isIntegerTy() ||
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00001039 !FT->getParamType(0)->isIntegerTy(32))
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001040 return 0;
Eric Christopher37c8b862009-10-07 21:14:25 +00001041
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001042 // isascii(c) -> c <u 128
Gabor Greifaee5dc12010-06-24 10:42:46 +00001043 Value *Op = CI->getArgOperand(0);
Benjamin Kramera1bf4ca2010-12-27 00:16:46 +00001044 Op = B.CreateICmpULT(Op, B.getInt32(128), "isascii");
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001045 return B.CreateZExt(Op, CI->getType());
1046 }
1047};
Eric Christopher37c8b862009-10-07 21:14:25 +00001048
Chris Lattner313f0e62008-06-09 08:26:51 +00001049//===---------------------------------------===//
1050// 'abs', 'labs', 'llabs' Optimizations
1051
Chris Lattner3e8b6632009-09-02 06:11:42 +00001052struct AbsOpt : public LibCallOptimization {
Eric Christopher7a61d702008-08-08 19:39:37 +00001053 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001054 FunctionType *FT = Callee->getFunctionType();
Chris Lattner313f0e62008-06-09 08:26:51 +00001055 // We require integer(integer) where the types agree.
Duncan Sands1df98592010-02-16 11:11:14 +00001056 if (FT->getNumParams() != 1 || !FT->getReturnType()->isIntegerTy() ||
Chris Lattner313f0e62008-06-09 08:26:51 +00001057 FT->getParamType(0) != FT->getReturnType())
1058 return 0;
Eric Christopher37c8b862009-10-07 21:14:25 +00001059
Chris Lattner313f0e62008-06-09 08:26:51 +00001060 // abs(x) -> x >s -1 ? x : -x
Gabor Greifaee5dc12010-06-24 10:42:46 +00001061 Value *Op = CI->getArgOperand(0);
Benjamin Kramera1bf4ca2010-12-27 00:16:46 +00001062 Value *Pos = B.CreateICmpSGT(Op, Constant::getAllOnesValue(Op->getType()),
Chris Lattner313f0e62008-06-09 08:26:51 +00001063 "ispos");
1064 Value *Neg = B.CreateNeg(Op, "neg");
1065 return B.CreateSelect(Pos, Op, Neg);
1066 }
1067};
Eric Christopher37c8b862009-10-07 21:14:25 +00001068
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001069
1070//===---------------------------------------===//
1071// 'toascii' Optimizations
1072
Chris Lattner3e8b6632009-09-02 06:11:42 +00001073struct ToAsciiOpt : public LibCallOptimization {
Eric Christopher7a61d702008-08-08 19:39:37 +00001074 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001075 FunctionType *FT = Callee->getFunctionType();
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001076 // We require i32(i32)
1077 if (FT->getNumParams() != 1 || FT->getReturnType() != FT->getParamType(0) ||
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00001078 !FT->getParamType(0)->isIntegerTy(32))
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001079 return 0;
Eric Christopher37c8b862009-10-07 21:14:25 +00001080
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001081 // isascii(c) -> c & 0x7f
Gabor Greifaee5dc12010-06-24 10:42:46 +00001082 return B.CreateAnd(CI->getArgOperand(0),
Owen Andersoneed707b2009-07-24 23:12:02 +00001083 ConstantInt::get(CI->getType(),0x7F));
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001084 }
1085};
1086
1087//===----------------------------------------------------------------------===//
1088// Formatting and IO Optimizations
1089//===----------------------------------------------------------------------===//
1090
1091//===---------------------------------------===//
1092// 'printf' Optimizations
1093
Chris Lattner3e8b6632009-09-02 06:11:42 +00001094struct PrintFOpt : public LibCallOptimization {
Richard Osborne36498242011-03-03 13:17:51 +00001095 Value *OptimizeFixedFormatString(Function *Callee, CallInst *CI,
1096 IRBuilder<> &B) {
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001097 // Check for a fixed format string.
Bill Wendling0582ae92009-03-13 04:39:26 +00001098 std::string FormatStr;
Gabor Greifaee5dc12010-06-24 10:42:46 +00001099 if (!GetConstantStringInfo(CI->getArgOperand(0), FormatStr))
Bill Wendling0582ae92009-03-13 04:39:26 +00001100 return 0;
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001101
1102 // Empty format string -> noop.
1103 if (FormatStr.empty()) // Tolerate printf's declared void.
Eric Christopher37c8b862009-10-07 21:14:25 +00001104 return CI->use_empty() ? (Value*)CI :
Owen Andersoneed707b2009-07-24 23:12:02 +00001105 ConstantInt::get(CI->getType(), 0);
Eric Christopher37c8b862009-10-07 21:14:25 +00001106
Daniel Dunbard02be242011-02-12 18:19:57 +00001107 // Do not do any of the following transformations if the printf return value
1108 // is used, in general the printf return value is not compatible with either
1109 // putchar() or puts().
1110 if (!CI->use_empty())
1111 return 0;
1112
1113 // printf("x") -> putchar('x'), even for '%'.
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001114 if (FormatStr.size() == 1) {
Benjamin Kramera1bf4ca2010-12-27 00:16:46 +00001115 Value *Res = EmitPutChar(B.getInt32(FormatStr[0]), B, TD);
Chris Lattner74965f22009-11-09 04:57:04 +00001116 if (CI->use_empty()) return CI;
1117 return B.CreateIntCast(Res, CI->getType(), true);
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001118 }
Eric Christopher37c8b862009-10-07 21:14:25 +00001119
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001120 // printf("foo\n") --> puts("foo")
1121 if (FormatStr[FormatStr.size()-1] == '\n' &&
1122 FormatStr.find('%') == std::string::npos) { // no format characters.
1123 // Create a string literal with no \n on it. We expect the constant merge
1124 // pass to be run after this pass, to merge duplicate strings.
1125 FormatStr.erase(FormatStr.end()-1);
Benjamin Kramer59e43bd2011-10-29 19:43:31 +00001126 Value *GV = B.CreateGlobalString(FormatStr, "str");
1127 EmitPutS(GV, B, TD);
Eric Christopher37c8b862009-10-07 21:14:25 +00001128 return CI->use_empty() ? (Value*)CI :
Owen Andersoneed707b2009-07-24 23:12:02 +00001129 ConstantInt::get(CI->getType(), FormatStr.size()+1);
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001130 }
Eric Christopher37c8b862009-10-07 21:14:25 +00001131
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001132 // Optimize specific format strings.
Gabor Greifaee5dc12010-06-24 10:42:46 +00001133 // printf("%c", chr) --> putchar(chr)
Gabor Greif8e1ebff2010-06-30 12:42:43 +00001134 if (FormatStr == "%c" && CI->getNumArgOperands() > 1 &&
Gabor Greifaee5dc12010-06-24 10:42:46 +00001135 CI->getArgOperand(1)->getType()->isIntegerTy()) {
1136 Value *Res = EmitPutChar(CI->getArgOperand(1), B, TD);
Eric Christopher80bf1d52009-11-21 01:01:30 +00001137
Chris Lattner74965f22009-11-09 04:57:04 +00001138 if (CI->use_empty()) return CI;
1139 return B.CreateIntCast(Res, CI->getType(), true);
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001140 }
Eric Christopher37c8b862009-10-07 21:14:25 +00001141
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001142 // printf("%s\n", str) --> puts(str)
Gabor Greif8e1ebff2010-06-30 12:42:43 +00001143 if (FormatStr == "%s\n" && CI->getNumArgOperands() > 1 &&
Daniel Dunbard02be242011-02-12 18:19:57 +00001144 CI->getArgOperand(1)->getType()->isPointerTy()) {
Gabor Greifaee5dc12010-06-24 10:42:46 +00001145 EmitPutS(CI->getArgOperand(1), B, TD);
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001146 return CI;
1147 }
1148 return 0;
1149 }
Richard Osborne36498242011-03-03 13:17:51 +00001150
1151 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
1152 // Require one fixed pointer argument and an integer/void result.
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001153 FunctionType *FT = Callee->getFunctionType();
Richard Osborne36498242011-03-03 13:17:51 +00001154 if (FT->getNumParams() < 1 || !FT->getParamType(0)->isPointerTy() ||
1155 !(FT->getReturnType()->isIntegerTy() ||
1156 FT->getReturnType()->isVoidTy()))
1157 return 0;
1158
1159 if (Value *V = OptimizeFixedFormatString(Callee, CI, B)) {
1160 return V;
1161 }
1162
1163 // printf(format, ...) -> iprintf(format, ...) if no floating point
1164 // arguments.
1165 if (TLI->has(LibFunc::iprintf) && !CallHasFloatingPointArgument(CI)) {
1166 Module *M = B.GetInsertBlock()->getParent()->getParent();
1167 Constant *IPrintFFn =
1168 M->getOrInsertFunction("iprintf", FT, Callee->getAttributes());
1169 CallInst *New = cast<CallInst>(CI->clone());
1170 New->setCalledFunction(IPrintFFn);
1171 B.Insert(New);
1172 return New;
1173 }
1174 return 0;
1175 }
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001176};
1177
1178//===---------------------------------------===//
1179// 'sprintf' Optimizations
1180
Chris Lattner3e8b6632009-09-02 06:11:42 +00001181struct SPrintFOpt : public LibCallOptimization {
Richard Osborne419454a2011-03-03 14:09:28 +00001182 Value *OptimizeFixedFormatString(Function *Callee, CallInst *CI,
1183 IRBuilder<> &B) {
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001184 // Check for a fixed format string.
Bill Wendling0582ae92009-03-13 04:39:26 +00001185 std::string FormatStr;
Gabor Greifaee5dc12010-06-24 10:42:46 +00001186 if (!GetConstantStringInfo(CI->getArgOperand(1), FormatStr))
Bill Wendling0582ae92009-03-13 04:39:26 +00001187 return 0;
Eric Christopher37c8b862009-10-07 21:14:25 +00001188
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001189 // If we just have a format string (nothing else crazy) transform it.
Gabor Greif8e1ebff2010-06-30 12:42:43 +00001190 if (CI->getNumArgOperands() == 2) {
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001191 // Make sure there's no % in the constant array. We could try to handle
1192 // %% -> % in the future if we cared.
1193 for (unsigned i = 0, e = FormatStr.size(); i != e; ++i)
1194 if (FormatStr[i] == '%')
1195 return 0; // we found a format specifier, bail out.
Dan Gohmanf14d9192009-08-18 00:48:13 +00001196
1197 // These optimizations require TargetData.
1198 if (!TD) return 0;
1199
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001200 // sprintf(str, fmt) -> llvm.memcpy(str, fmt, strlen(fmt)+1, 1)
Benjamin Kramera1bf4ca2010-12-27 00:16:46 +00001201 B.CreateMemCpy(CI->getArgOperand(0), CI->getArgOperand(1),
1202 ConstantInt::get(TD->getIntPtrType(*Context), // Copy the
1203 FormatStr.size() + 1), 1); // nul byte.
Owen Andersoneed707b2009-07-24 23:12:02 +00001204 return ConstantInt::get(CI->getType(), FormatStr.size());
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001205 }
Eric Christopher37c8b862009-10-07 21:14:25 +00001206
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001207 // The remaining optimizations require the format string to be "%s" or "%c"
1208 // and have an extra operand.
Gabor Greif8e1ebff2010-06-30 12:42:43 +00001209 if (FormatStr.size() != 2 || FormatStr[0] != '%' ||
1210 CI->getNumArgOperands() < 3)
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001211 return 0;
Eric Christopher37c8b862009-10-07 21:14:25 +00001212
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001213 // Decode the second character of the format string.
1214 if (FormatStr[1] == 'c') {
Chris Lattner56b4f2b2008-05-01 06:39:12 +00001215 // sprintf(dst, "%c", chr) --> *(i8*)dst = chr; *((i8*)dst+1) = 0
Gabor Greifaee5dc12010-06-24 10:42:46 +00001216 if (!CI->getArgOperand(2)->getType()->isIntegerTy()) return 0;
Benjamin Kramera1bf4ca2010-12-27 00:16:46 +00001217 Value *V = B.CreateTrunc(CI->getArgOperand(2), B.getInt8Ty(), "char");
Gabor Greifaee5dc12010-06-24 10:42:46 +00001218 Value *Ptr = CastToCStr(CI->getArgOperand(0), B);
Chris Lattner56b4f2b2008-05-01 06:39:12 +00001219 B.CreateStore(V, Ptr);
Benjamin Kramera1bf4ca2010-12-27 00:16:46 +00001220 Ptr = B.CreateGEP(Ptr, B.getInt32(1), "nul");
1221 B.CreateStore(B.getInt8(0), Ptr);
Eric Christopher37c8b862009-10-07 21:14:25 +00001222
Owen Andersoneed707b2009-07-24 23:12:02 +00001223 return ConstantInt::get(CI->getType(), 1);
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001224 }
Eric Christopher37c8b862009-10-07 21:14:25 +00001225
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001226 if (FormatStr[1] == 's') {
Dan Gohmanf14d9192009-08-18 00:48:13 +00001227 // These optimizations require TargetData.
1228 if (!TD) return 0;
1229
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001230 // sprintf(dest, "%s", str) -> llvm.memcpy(dest, str, strlen(str)+1, 1)
Gabor Greifaee5dc12010-06-24 10:42:46 +00001231 if (!CI->getArgOperand(2)->getType()->isPointerTy()) return 0;
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001232
Gabor Greifaee5dc12010-06-24 10:42:46 +00001233 Value *Len = EmitStrLen(CI->getArgOperand(2), B, TD);
Owen Andersonfa5cbd62009-07-03 19:42:02 +00001234 Value *IncLen = B.CreateAdd(Len,
Owen Andersoneed707b2009-07-24 23:12:02 +00001235 ConstantInt::get(Len->getType(), 1),
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001236 "leninc");
Benjamin Kramera1bf4ca2010-12-27 00:16:46 +00001237 B.CreateMemCpy(CI->getArgOperand(0), CI->getArgOperand(2), IncLen, 1);
Eric Christopher37c8b862009-10-07 21:14:25 +00001238
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001239 // The sprintf result is the unincremented number of bytes in the string.
1240 return B.CreateIntCast(Len, CI->getType(), false);
1241 }
1242 return 0;
1243 }
Richard Osborne419454a2011-03-03 14:09:28 +00001244
1245 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
1246 // Require two fixed pointer arguments and an integer result.
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001247 FunctionType *FT = Callee->getFunctionType();
Richard Osborne419454a2011-03-03 14:09:28 +00001248 if (FT->getNumParams() != 2 || !FT->getParamType(0)->isPointerTy() ||
1249 !FT->getParamType(1)->isPointerTy() ||
1250 !FT->getReturnType()->isIntegerTy())
1251 return 0;
1252
1253 if (Value *V = OptimizeFixedFormatString(Callee, CI, B)) {
1254 return V;
1255 }
1256
Richard Osborneea2578c2011-03-03 14:21:22 +00001257 // sprintf(str, format, ...) -> siprintf(str, format, ...) if no floating
Richard Osborne419454a2011-03-03 14:09:28 +00001258 // point arguments.
1259 if (TLI->has(LibFunc::siprintf) && !CallHasFloatingPointArgument(CI)) {
1260 Module *M = B.GetInsertBlock()->getParent()->getParent();
1261 Constant *SIPrintFFn =
1262 M->getOrInsertFunction("siprintf", FT, Callee->getAttributes());
1263 CallInst *New = cast<CallInst>(CI->clone());
1264 New->setCalledFunction(SIPrintFFn);
1265 B.Insert(New);
1266 return New;
1267 }
1268 return 0;
1269 }
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001270};
1271
1272//===---------------------------------------===//
1273// 'fwrite' Optimizations
1274
Chris Lattner3e8b6632009-09-02 06:11:42 +00001275struct FWriteOpt : public LibCallOptimization {
Eric Christopher7a61d702008-08-08 19:39:37 +00001276 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001277 // Require a pointer, an integer, an integer, a pointer, returning integer.
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001278 FunctionType *FT = Callee->getFunctionType();
Duncan Sands1df98592010-02-16 11:11:14 +00001279 if (FT->getNumParams() != 4 || !FT->getParamType(0)->isPointerTy() ||
1280 !FT->getParamType(1)->isIntegerTy() ||
1281 !FT->getParamType(2)->isIntegerTy() ||
1282 !FT->getParamType(3)->isPointerTy() ||
1283 !FT->getReturnType()->isIntegerTy())
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001284 return 0;
Eric Christopher37c8b862009-10-07 21:14:25 +00001285
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001286 // Get the element size and count.
Gabor Greifaee5dc12010-06-24 10:42:46 +00001287 ConstantInt *SizeC = dyn_cast<ConstantInt>(CI->getArgOperand(1));
1288 ConstantInt *CountC = dyn_cast<ConstantInt>(CI->getArgOperand(2));
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001289 if (!SizeC || !CountC) return 0;
1290 uint64_t Bytes = SizeC->getZExtValue()*CountC->getZExtValue();
Eric Christopher37c8b862009-10-07 21:14:25 +00001291
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001292 // If this is writing zero records, remove the call (it's a noop).
1293 if (Bytes == 0)
Owen Andersoneed707b2009-07-24 23:12:02 +00001294 return ConstantInt::get(CI->getType(), 0);
Eric Christopher37c8b862009-10-07 21:14:25 +00001295
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001296 // If this is writing one byte, turn it into fputc.
1297 if (Bytes == 1) { // fwrite(S,1,1,F) -> fputc(S[0],F)
Gabor Greifaee5dc12010-06-24 10:42:46 +00001298 Value *Char = B.CreateLoad(CastToCStr(CI->getArgOperand(0), B), "char");
1299 EmitFPutC(Char, CI->getArgOperand(3), B, TD);
Owen Andersoneed707b2009-07-24 23:12:02 +00001300 return ConstantInt::get(CI->getType(), 1);
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001301 }
1302
1303 return 0;
1304 }
1305};
1306
1307//===---------------------------------------===//
1308// 'fputs' Optimizations
1309
Chris Lattner3e8b6632009-09-02 06:11:42 +00001310struct FPutsOpt : public LibCallOptimization {
Eric Christopher7a61d702008-08-08 19:39:37 +00001311 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
Dan Gohmanf14d9192009-08-18 00:48:13 +00001312 // These optimizations require TargetData.
1313 if (!TD) return 0;
1314
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001315 // Require two pointers. Also, we can't optimize if return value is used.
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001316 FunctionType *FT = Callee->getFunctionType();
Duncan Sands1df98592010-02-16 11:11:14 +00001317 if (FT->getNumParams() != 2 || !FT->getParamType(0)->isPointerTy() ||
1318 !FT->getParamType(1)->isPointerTy() ||
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001319 !CI->use_empty())
1320 return 0;
Eric Christopher37c8b862009-10-07 21:14:25 +00001321
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001322 // fputs(s,F) --> fwrite(s,1,strlen(s),F)
Gabor Greifaee5dc12010-06-24 10:42:46 +00001323 uint64_t Len = GetStringLength(CI->getArgOperand(0));
Chris Lattner56b4f2b2008-05-01 06:39:12 +00001324 if (!Len) return 0;
Gabor Greifaee5dc12010-06-24 10:42:46 +00001325 EmitFWrite(CI->getArgOperand(0),
Owen Anderson1d0be152009-08-13 21:58:54 +00001326 ConstantInt::get(TD->getIntPtrType(*Context), Len-1),
Gabor Greifaee5dc12010-06-24 10:42:46 +00001327 CI->getArgOperand(1), B, TD);
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001328 return CI; // Known to have no uses (see above).
1329 }
1330};
1331
1332//===---------------------------------------===//
1333// 'fprintf' Optimizations
1334
Chris Lattner3e8b6632009-09-02 06:11:42 +00001335struct FPrintFOpt : public LibCallOptimization {
Richard Osborne022708f2011-03-03 14:20:22 +00001336 Value *OptimizeFixedFormatString(Function *Callee, CallInst *CI,
1337 IRBuilder<> &B) {
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001338 // All the optimizations depend on the format string.
Bill Wendling0582ae92009-03-13 04:39:26 +00001339 std::string FormatStr;
Gabor Greifaee5dc12010-06-24 10:42:46 +00001340 if (!GetConstantStringInfo(CI->getArgOperand(1), FormatStr))
Bill Wendling0582ae92009-03-13 04:39:26 +00001341 return 0;
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001342
1343 // fprintf(F, "foo") --> fwrite("foo", 3, 1, F)
Gabor Greif8e1ebff2010-06-30 12:42:43 +00001344 if (CI->getNumArgOperands() == 2) {
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001345 for (unsigned i = 0, e = FormatStr.size(); i != e; ++i)
1346 if (FormatStr[i] == '%') // Could handle %% -> % if we cared.
Chris Lattner56b4f2b2008-05-01 06:39:12 +00001347 return 0; // We found a format specifier.
Dan Gohmanf14d9192009-08-18 00:48:13 +00001348
1349 // These optimizations require TargetData.
1350 if (!TD) return 0;
1351
Gabor Greifaee5dc12010-06-24 10:42:46 +00001352 EmitFWrite(CI->getArgOperand(1),
Mikhail Glushenkoved5cb592010-01-04 07:55:25 +00001353 ConstantInt::get(TD->getIntPtrType(*Context),
1354 FormatStr.size()),
Gabor Greifaee5dc12010-06-24 10:42:46 +00001355 CI->getArgOperand(0), B, TD);
Owen Andersoneed707b2009-07-24 23:12:02 +00001356 return ConstantInt::get(CI->getType(), FormatStr.size());
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001357 }
Eric Christopher37c8b862009-10-07 21:14:25 +00001358
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001359 // The remaining optimizations require the format string to be "%s" or "%c"
1360 // and have an extra operand.
Gabor Greif8e1ebff2010-06-30 12:42:43 +00001361 if (FormatStr.size() != 2 || FormatStr[0] != '%' ||
1362 CI->getNumArgOperands() < 3)
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001363 return 0;
Eric Christopher37c8b862009-10-07 21:14:25 +00001364
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001365 // Decode the second character of the format string.
1366 if (FormatStr[1] == 'c') {
Gabor Greifaee5dc12010-06-24 10:42:46 +00001367 // fprintf(F, "%c", chr) --> fputc(chr, F)
1368 if (!CI->getArgOperand(2)->getType()->isIntegerTy()) return 0;
1369 EmitFPutC(CI->getArgOperand(2), CI->getArgOperand(0), B, TD);
Owen Andersoneed707b2009-07-24 23:12:02 +00001370 return ConstantInt::get(CI->getType(), 1);
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001371 }
Eric Christopher37c8b862009-10-07 21:14:25 +00001372
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001373 if (FormatStr[1] == 's') {
Gabor Greifaee5dc12010-06-24 10:42:46 +00001374 // fprintf(F, "%s", str) --> fputs(str, F)
1375 if (!CI->getArgOperand(2)->getType()->isPointerTy() || !CI->use_empty())
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001376 return 0;
Gabor Greifaee5dc12010-06-24 10:42:46 +00001377 EmitFPutS(CI->getArgOperand(2), CI->getArgOperand(0), B, TD);
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001378 return CI;
1379 }
1380 return 0;
1381 }
Richard Osborne022708f2011-03-03 14:20:22 +00001382
1383 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
1384 // Require two fixed paramters as pointers and integer result.
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001385 FunctionType *FT = Callee->getFunctionType();
Richard Osborne022708f2011-03-03 14:20:22 +00001386 if (FT->getNumParams() != 2 || !FT->getParamType(0)->isPointerTy() ||
1387 !FT->getParamType(1)->isPointerTy() ||
1388 !FT->getReturnType()->isIntegerTy())
1389 return 0;
1390
1391 if (Value *V = OptimizeFixedFormatString(Callee, CI, B)) {
1392 return V;
1393 }
1394
1395 // fprintf(stream, format, ...) -> fiprintf(stream, format, ...) if no
1396 // floating point arguments.
1397 if (TLI->has(LibFunc::fiprintf) && !CallHasFloatingPointArgument(CI)) {
1398 Module *M = B.GetInsertBlock()->getParent()->getParent();
1399 Constant *FIPrintFFn =
1400 M->getOrInsertFunction("fiprintf", FT, Callee->getAttributes());
1401 CallInst *New = cast<CallInst>(CI->clone());
1402 New->setCalledFunction(FIPrintFFn);
1403 B.Insert(New);
1404 return New;
1405 }
1406 return 0;
1407 }
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001408};
1409
Anders Carlsson303023d2010-11-30 06:19:18 +00001410//===---------------------------------------===//
1411// 'puts' Optimizations
1412
1413struct PutsOpt : public LibCallOptimization {
1414 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
1415 // Require one fixed pointer argument and an integer/void result.
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001416 FunctionType *FT = Callee->getFunctionType();
Anders Carlsson303023d2010-11-30 06:19:18 +00001417 if (FT->getNumParams() < 1 || !FT->getParamType(0)->isPointerTy() ||
1418 !(FT->getReturnType()->isIntegerTy() ||
1419 FT->getReturnType()->isVoidTy()))
1420 return 0;
1421
1422 // Check for a constant string.
1423 std::string Str;
1424 if (!GetConstantStringInfo(CI->getArgOperand(0), Str))
1425 return 0;
1426
Daniel Dunbard02be242011-02-12 18:19:57 +00001427 if (Str.empty() && CI->use_empty()) {
Anders Carlsson303023d2010-11-30 06:19:18 +00001428 // puts("") -> putchar('\n')
1429 Value *Res = EmitPutChar(B.getInt32('\n'), B, TD);
1430 if (CI->use_empty()) return CI;
1431 return B.CreateIntCast(Res, CI->getType(), true);
1432 }
1433
1434 return 0;
1435 }
1436};
1437
Bill Wendlingac178222008-05-05 21:37:59 +00001438} // end anonymous namespace.
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001439
1440//===----------------------------------------------------------------------===//
1441// SimplifyLibCalls Pass Implementation
1442//===----------------------------------------------------------------------===//
1443
1444namespace {
1445 /// This pass optimizes well known library functions from libc and libm.
1446 ///
Chris Lattner3e8b6632009-09-02 06:11:42 +00001447 class SimplifyLibCalls : public FunctionPass {
Chris Lattnerafbf4832011-02-24 07:16:14 +00001448 TargetLibraryInfo *TLI;
1449
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001450 StringMap<LibCallOptimization*> Optimizations;
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001451 // String and Memory LibCall Optimizations
Benjamin Kramer06f25cf2010-09-29 21:50:51 +00001452 StrCatOpt StrCat; StrNCatOpt StrNCat; StrChrOpt StrChr; StrRChrOpt StrRChr;
1453 StrCmpOpt StrCmp; StrNCmpOpt StrNCmp; StrCpyOpt StrCpy; StrCpyOpt StrCpyChk;
Benjamin Kramer05f585e2010-09-29 23:52:12 +00001454 StrNCpyOpt StrNCpy; StrLenOpt StrLen; StrPBrkOpt StrPBrk;
Benjamin Kramer9510a252010-09-30 00:58:35 +00001455 StrToOpt StrTo; StrSpnOpt StrSpn; StrCSpnOpt StrCSpn; StrStrOpt StrStr;
Chris Lattner24604112009-12-16 09:32:05 +00001456 MemCmpOpt MemCmp; MemCpyOpt MemCpy; MemMoveOpt MemMove; MemSetOpt MemSet;
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001457 // Math Library Optimizations
Chris Lattnere818f772008-05-02 18:43:35 +00001458 PowOpt Pow; Exp2Opt Exp2; UnaryDoubleFPOpt UnaryDoubleFP;
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001459 // Integer Optimizations
Chris Lattner313f0e62008-06-09 08:26:51 +00001460 FFSOpt FFS; AbsOpt Abs; IsDigitOpt IsDigit; IsAsciiOpt IsAscii;
1461 ToAsciiOpt ToAscii;
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001462 // Formatting and IO Optimizations
1463 SPrintFOpt SPrintF; PrintFOpt PrintF;
1464 FWriteOpt FWrite; FPutsOpt FPuts; FPrintFOpt FPrintF;
Anders Carlsson303023d2010-11-30 06:19:18 +00001465 PutsOpt Puts;
Chris Lattnerafbf4832011-02-24 07:16:14 +00001466
Nick Lewycky6cd0c042009-01-05 00:07:50 +00001467 bool Modified; // This is only used by doInitialization.
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001468 public:
1469 static char ID; // Pass identification
Owen Anderson081c34b2010-10-19 17:21:58 +00001470 SimplifyLibCalls() : FunctionPass(ID), StrCpy(false), StrCpyChk(true) {
1471 initializeSimplifyLibCallsPass(*PassRegistry::getPassRegistry());
1472 }
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001473 void InitOptimizations();
1474 bool runOnFunction(Function &F);
1475
Nick Lewycky0f8df9a2009-01-04 20:27:34 +00001476 void setDoesNotAccessMemory(Function &F);
1477 void setOnlyReadsMemory(Function &F);
1478 void setDoesNotThrow(Function &F);
1479 void setDoesNotCapture(Function &F, unsigned n);
1480 void setDoesNotAlias(Function &F, unsigned n);
Nick Lewycky6cd0c042009-01-05 00:07:50 +00001481 bool doInitialization(Module &M);
Nick Lewycky0f8df9a2009-01-04 20:27:34 +00001482
Chris Lattnere265ad82011-02-24 07:12:12 +00001483 void inferPrototypeAttributes(Function &F);
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001484 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
Chris Lattnerafbf4832011-02-24 07:16:14 +00001485 AU.addRequired<TargetLibraryInfo>();
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001486 }
1487 };
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001488} // end anonymous namespace.
1489
Chris Lattnerafbf4832011-02-24 07:16:14 +00001490char SimplifyLibCalls::ID = 0;
1491
1492INITIALIZE_PASS_BEGIN(SimplifyLibCalls, "simplify-libcalls",
1493 "Simplify well-known library calls", false, false)
1494INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfo)
1495INITIALIZE_PASS_END(SimplifyLibCalls, "simplify-libcalls",
1496 "Simplify well-known library calls", false, false)
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001497
1498// Public interface to the Simplify LibCalls pass.
1499FunctionPass *llvm::createSimplifyLibCallsPass() {
Eric Christopher37c8b862009-10-07 21:14:25 +00001500 return new SimplifyLibCalls();
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001501}
1502
1503/// Optimizations - Populate the Optimizations map with all the optimizations
1504/// we know.
1505void SimplifyLibCalls::InitOptimizations() {
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001506 // String and Memory LibCall Optimizations
1507 Optimizations["strcat"] = &StrCat;
Chris Lattnerf5b6bc72009-04-12 05:06:39 +00001508 Optimizations["strncat"] = &StrNCat;
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001509 Optimizations["strchr"] = &StrChr;
Benjamin Kramer06f25cf2010-09-29 21:50:51 +00001510 Optimizations["strrchr"] = &StrRChr;
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001511 Optimizations["strcmp"] = &StrCmp;
1512 Optimizations["strncmp"] = &StrNCmp;
1513 Optimizations["strcpy"] = &StrCpy;
Chris Lattnerf5b6bc72009-04-12 05:06:39 +00001514 Optimizations["strncpy"] = &StrNCpy;
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001515 Optimizations["strlen"] = &StrLen;
Benjamin Kramer05f585e2010-09-29 23:52:12 +00001516 Optimizations["strpbrk"] = &StrPBrk;
Nick Lewycky4c498412009-02-13 15:31:46 +00001517 Optimizations["strtol"] = &StrTo;
1518 Optimizations["strtod"] = &StrTo;
1519 Optimizations["strtof"] = &StrTo;
1520 Optimizations["strtoul"] = &StrTo;
1521 Optimizations["strtoll"] = &StrTo;
1522 Optimizations["strtold"] = &StrTo;
1523 Optimizations["strtoull"] = &StrTo;
Benjamin Kramer9510a252010-09-30 00:58:35 +00001524 Optimizations["strspn"] = &StrSpn;
1525 Optimizations["strcspn"] = &StrCSpn;
Chris Lattner24604112009-12-16 09:32:05 +00001526 Optimizations["strstr"] = &StrStr;
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001527 Optimizations["memcmp"] = &MemCmp;
Chris Lattnerafbf4832011-02-24 07:16:14 +00001528 if (TLI->has(LibFunc::memcpy)) Optimizations["memcpy"] = &MemCpy;
Eli Friedmand83ae7d2008-11-30 08:32:11 +00001529 Optimizations["memmove"] = &MemMove;
Chris Lattnerafbf4832011-02-24 07:16:14 +00001530 if (TLI->has(LibFunc::memset)) Optimizations["memset"] = &MemSet;
Eric Christopher37c8b862009-10-07 21:14:25 +00001531
Evan Cheng0289b412010-03-23 15:48:04 +00001532 // _chk variants of String and Memory LibCall Optimizations.
Evan Cheng0289b412010-03-23 15:48:04 +00001533 Optimizations["__strcpy_chk"] = &StrCpyChk;
1534
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001535 // Math Library Optimizations
1536 Optimizations["powf"] = &Pow;
1537 Optimizations["pow"] = &Pow;
1538 Optimizations["powl"] = &Pow;
Dale Johannesen53bfbbc2008-09-04 18:30:46 +00001539 Optimizations["llvm.pow.f32"] = &Pow;
1540 Optimizations["llvm.pow.f64"] = &Pow;
1541 Optimizations["llvm.pow.f80"] = &Pow;
1542 Optimizations["llvm.pow.f128"] = &Pow;
1543 Optimizations["llvm.pow.ppcf128"] = &Pow;
Chris Lattnere818f772008-05-02 18:43:35 +00001544 Optimizations["exp2l"] = &Exp2;
1545 Optimizations["exp2"] = &Exp2;
1546 Optimizations["exp2f"] = &Exp2;
Dale Johannesen53bfbbc2008-09-04 18:30:46 +00001547 Optimizations["llvm.exp2.ppcf128"] = &Exp2;
1548 Optimizations["llvm.exp2.f128"] = &Exp2;
1549 Optimizations["llvm.exp2.f80"] = &Exp2;
1550 Optimizations["llvm.exp2.f64"] = &Exp2;
1551 Optimizations["llvm.exp2.f32"] = &Exp2;
Eric Christopher37c8b862009-10-07 21:14:25 +00001552
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001553#ifdef HAVE_FLOORF
1554 Optimizations["floor"] = &UnaryDoubleFP;
1555#endif
1556#ifdef HAVE_CEILF
1557 Optimizations["ceil"] = &UnaryDoubleFP;
1558#endif
1559#ifdef HAVE_ROUNDF
1560 Optimizations["round"] = &UnaryDoubleFP;
1561#endif
1562#ifdef HAVE_RINTF
1563 Optimizations["rint"] = &UnaryDoubleFP;
1564#endif
1565#ifdef HAVE_NEARBYINTF
1566 Optimizations["nearbyint"] = &UnaryDoubleFP;
1567#endif
Eric Christopher37c8b862009-10-07 21:14:25 +00001568
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001569 // Integer Optimizations
1570 Optimizations["ffs"] = &FFS;
1571 Optimizations["ffsl"] = &FFS;
1572 Optimizations["ffsll"] = &FFS;
Chris Lattner313f0e62008-06-09 08:26:51 +00001573 Optimizations["abs"] = &Abs;
1574 Optimizations["labs"] = &Abs;
1575 Optimizations["llabs"] = &Abs;
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001576 Optimizations["isdigit"] = &IsDigit;
1577 Optimizations["isascii"] = &IsAscii;
1578 Optimizations["toascii"] = &ToAscii;
Eric Christopher37c8b862009-10-07 21:14:25 +00001579
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001580 // Formatting and IO Optimizations
1581 Optimizations["sprintf"] = &SPrintF;
1582 Optimizations["printf"] = &PrintF;
1583 Optimizations["fwrite"] = &FWrite;
1584 Optimizations["fputs"] = &FPuts;
1585 Optimizations["fprintf"] = &FPrintF;
Anders Carlsson303023d2010-11-30 06:19:18 +00001586 Optimizations["puts"] = &Puts;
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001587}
1588
1589
1590/// runOnFunction - Top level algorithm.
1591///
1592bool SimplifyLibCalls::runOnFunction(Function &F) {
Chris Lattnerafbf4832011-02-24 07:16:14 +00001593 TLI = &getAnalysis<TargetLibraryInfo>();
1594
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001595 if (Optimizations.empty())
1596 InitOptimizations();
Eric Christopher37c8b862009-10-07 21:14:25 +00001597
Dan Gohmanf14d9192009-08-18 00:48:13 +00001598 const TargetData *TD = getAnalysisIfAvailable<TargetData>();
Eric Christopher37c8b862009-10-07 21:14:25 +00001599
Owen Andersone922c022009-07-22 00:24:57 +00001600 IRBuilder<> Builder(F.getContext());
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001601
1602 bool Changed = false;
1603 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB) {
1604 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ) {
1605 // Ignore non-calls.
1606 CallInst *CI = dyn_cast<CallInst>(I++);
1607 if (!CI) continue;
Eric Christopher37c8b862009-10-07 21:14:25 +00001608
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001609 // Ignore indirect calls and calls to non-external functions.
1610 Function *Callee = CI->getCalledFunction();
1611 if (Callee == 0 || !Callee->isDeclaration() ||
1612 !(Callee->hasExternalLinkage() || Callee->hasDLLImportLinkage()))
1613 continue;
Eric Christopher37c8b862009-10-07 21:14:25 +00001614
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001615 // Ignore unknown calls.
Daniel Dunbarf0443c12009-07-26 08:34:35 +00001616 LibCallOptimization *LCO = Optimizations.lookup(Callee->getName());
1617 if (!LCO) continue;
Eric Christopher37c8b862009-10-07 21:14:25 +00001618
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001619 // Set the builder to the instruction after the call.
1620 Builder.SetInsertPoint(BB, I);
Eric Christopher37c8b862009-10-07 21:14:25 +00001621
Devang Patela2ab3992011-03-09 21:27:52 +00001622 // Use debug location of CI for all new instructions.
1623 Builder.SetCurrentDebugLocation(CI->getDebugLoc());
1624
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001625 // Try to optimize this call.
Richard Osborne36498242011-03-03 13:17:51 +00001626 Value *Result = LCO->OptimizeCall(CI, TD, TLI, Builder);
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001627 if (Result == 0) continue;
1628
David Greene6a6b90e2010-01-05 01:27:21 +00001629 DEBUG(dbgs() << "SimplifyLibCalls simplified: " << *CI;
1630 dbgs() << " into: " << *Result << "\n");
Eric Christopher37c8b862009-10-07 21:14:25 +00001631
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001632 // Something changed!
1633 Changed = true;
1634 ++NumSimplified;
Eric Christopher37c8b862009-10-07 21:14:25 +00001635
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001636 // Inspect the instruction after the call (which was potentially just
1637 // added) next.
1638 I = CI; ++I;
Eric Christopher37c8b862009-10-07 21:14:25 +00001639
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001640 if (CI != Result && !CI->use_empty()) {
1641 CI->replaceAllUsesWith(Result);
1642 if (!Result->hasName())
1643 Result->takeName(CI);
1644 }
1645 CI->eraseFromParent();
1646 }
1647 }
1648 return Changed;
1649}
1650
Nick Lewycky6cd0c042009-01-05 00:07:50 +00001651// Utility methods for doInitialization.
Nick Lewycky0f8df9a2009-01-04 20:27:34 +00001652
1653void SimplifyLibCalls::setDoesNotAccessMemory(Function &F) {
1654 if (!F.doesNotAccessMemory()) {
1655 F.setDoesNotAccessMemory();
1656 ++NumAnnotated;
1657 Modified = true;
1658 }
1659}
1660void SimplifyLibCalls::setOnlyReadsMemory(Function &F) {
1661 if (!F.onlyReadsMemory()) {
1662 F.setOnlyReadsMemory();
1663 ++NumAnnotated;
1664 Modified = true;
1665 }
1666}
1667void SimplifyLibCalls::setDoesNotThrow(Function &F) {
1668 if (!F.doesNotThrow()) {
1669 F.setDoesNotThrow();
1670 ++NumAnnotated;
1671 Modified = true;
1672 }
1673}
1674void SimplifyLibCalls::setDoesNotCapture(Function &F, unsigned n) {
1675 if (!F.doesNotCapture(n)) {
1676 F.setDoesNotCapture(n);
1677 ++NumAnnotated;
1678 Modified = true;
1679 }
1680}
1681void SimplifyLibCalls::setDoesNotAlias(Function &F, unsigned n) {
1682 if (!F.doesNotAlias(n)) {
1683 F.setDoesNotAlias(n);
1684 ++NumAnnotated;
1685 Modified = true;
1686 }
1687}
1688
Chris Lattnere265ad82011-02-24 07:12:12 +00001689
1690void SimplifyLibCalls::inferPrototypeAttributes(Function &F) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001691 FunctionType *FTy = F.getFunctionType();
Chris Lattnere265ad82011-02-24 07:12:12 +00001692
1693 StringRef Name = F.getName();
1694 switch (Name[0]) {
1695 case 's':
1696 if (Name == "strlen") {
1697 if (FTy->getNumParams() != 1 || !FTy->getParamType(0)->isPointerTy())
1698 return;
1699 setOnlyReadsMemory(F);
1700 setDoesNotThrow(F);
1701 setDoesNotCapture(F, 1);
1702 } else if (Name == "strchr" ||
1703 Name == "strrchr") {
1704 if (FTy->getNumParams() != 2 ||
1705 !FTy->getParamType(0)->isPointerTy() ||
1706 !FTy->getParamType(1)->isIntegerTy())
1707 return;
1708 setOnlyReadsMemory(F);
1709 setDoesNotThrow(F);
1710 } else if (Name == "strcpy" ||
1711 Name == "stpcpy" ||
1712 Name == "strcat" ||
1713 Name == "strtol" ||
1714 Name == "strtod" ||
1715 Name == "strtof" ||
1716 Name == "strtoul" ||
1717 Name == "strtoll" ||
1718 Name == "strtold" ||
1719 Name == "strncat" ||
1720 Name == "strncpy" ||
1721 Name == "strtoull") {
1722 if (FTy->getNumParams() < 2 ||
1723 !FTy->getParamType(1)->isPointerTy())
1724 return;
1725 setDoesNotThrow(F);
1726 setDoesNotCapture(F, 2);
1727 } else if (Name == "strxfrm") {
1728 if (FTy->getNumParams() != 3 ||
1729 !FTy->getParamType(0)->isPointerTy() ||
1730 !FTy->getParamType(1)->isPointerTy())
1731 return;
1732 setDoesNotThrow(F);
1733 setDoesNotCapture(F, 1);
1734 setDoesNotCapture(F, 2);
1735 } else if (Name == "strcmp" ||
1736 Name == "strspn" ||
1737 Name == "strncmp" ||
1738 Name == "strcspn" ||
1739 Name == "strcoll" ||
1740 Name == "strcasecmp" ||
1741 Name == "strncasecmp") {
1742 if (FTy->getNumParams() < 2 ||
1743 !FTy->getParamType(0)->isPointerTy() ||
1744 !FTy->getParamType(1)->isPointerTy())
1745 return;
1746 setOnlyReadsMemory(F);
1747 setDoesNotThrow(F);
1748 setDoesNotCapture(F, 1);
1749 setDoesNotCapture(F, 2);
1750 } else if (Name == "strstr" ||
1751 Name == "strpbrk") {
1752 if (FTy->getNumParams() != 2 || !FTy->getParamType(1)->isPointerTy())
1753 return;
1754 setOnlyReadsMemory(F);
1755 setDoesNotThrow(F);
1756 setDoesNotCapture(F, 2);
1757 } else if (Name == "strtok" ||
1758 Name == "strtok_r") {
1759 if (FTy->getNumParams() < 2 || !FTy->getParamType(1)->isPointerTy())
1760 return;
1761 setDoesNotThrow(F);
1762 setDoesNotCapture(F, 2);
1763 } else if (Name == "scanf" ||
1764 Name == "setbuf" ||
1765 Name == "setvbuf") {
1766 if (FTy->getNumParams() < 1 || !FTy->getParamType(0)->isPointerTy())
1767 return;
1768 setDoesNotThrow(F);
1769 setDoesNotCapture(F, 1);
1770 } else if (Name == "strdup" ||
1771 Name == "strndup") {
1772 if (FTy->getNumParams() < 1 || !FTy->getReturnType()->isPointerTy() ||
1773 !FTy->getParamType(0)->isPointerTy())
1774 return;
1775 setDoesNotThrow(F);
1776 setDoesNotAlias(F, 0);
1777 setDoesNotCapture(F, 1);
1778 } else if (Name == "stat" ||
1779 Name == "sscanf" ||
1780 Name == "sprintf" ||
1781 Name == "statvfs") {
1782 if (FTy->getNumParams() < 2 ||
1783 !FTy->getParamType(0)->isPointerTy() ||
1784 !FTy->getParamType(1)->isPointerTy())
1785 return;
1786 setDoesNotThrow(F);
1787 setDoesNotCapture(F, 1);
1788 setDoesNotCapture(F, 2);
1789 } else if (Name == "snprintf") {
1790 if (FTy->getNumParams() != 3 ||
1791 !FTy->getParamType(0)->isPointerTy() ||
1792 !FTy->getParamType(2)->isPointerTy())
1793 return;
1794 setDoesNotThrow(F);
1795 setDoesNotCapture(F, 1);
1796 setDoesNotCapture(F, 3);
1797 } else if (Name == "setitimer") {
1798 if (FTy->getNumParams() != 3 ||
1799 !FTy->getParamType(1)->isPointerTy() ||
1800 !FTy->getParamType(2)->isPointerTy())
1801 return;
1802 setDoesNotThrow(F);
1803 setDoesNotCapture(F, 2);
1804 setDoesNotCapture(F, 3);
1805 } else if (Name == "system") {
1806 if (FTy->getNumParams() != 1 ||
1807 !FTy->getParamType(0)->isPointerTy())
1808 return;
1809 // May throw; "system" is a valid pthread cancellation point.
1810 setDoesNotCapture(F, 1);
1811 }
1812 break;
1813 case 'm':
1814 if (Name == "malloc") {
1815 if (FTy->getNumParams() != 1 ||
1816 !FTy->getReturnType()->isPointerTy())
1817 return;
1818 setDoesNotThrow(F);
1819 setDoesNotAlias(F, 0);
1820 } else if (Name == "memcmp") {
1821 if (FTy->getNumParams() != 3 ||
1822 !FTy->getParamType(0)->isPointerTy() ||
1823 !FTy->getParamType(1)->isPointerTy())
1824 return;
1825 setOnlyReadsMemory(F);
1826 setDoesNotThrow(F);
1827 setDoesNotCapture(F, 1);
1828 setDoesNotCapture(F, 2);
1829 } else if (Name == "memchr" ||
1830 Name == "memrchr") {
1831 if (FTy->getNumParams() != 3)
1832 return;
1833 setOnlyReadsMemory(F);
1834 setDoesNotThrow(F);
1835 } else if (Name == "modf" ||
1836 Name == "modff" ||
1837 Name == "modfl" ||
1838 Name == "memcpy" ||
1839 Name == "memccpy" ||
1840 Name == "memmove") {
1841 if (FTy->getNumParams() < 2 ||
1842 !FTy->getParamType(1)->isPointerTy())
1843 return;
1844 setDoesNotThrow(F);
1845 setDoesNotCapture(F, 2);
1846 } else if (Name == "memalign") {
1847 if (!FTy->getReturnType()->isPointerTy())
1848 return;
1849 setDoesNotAlias(F, 0);
1850 } else if (Name == "mkdir" ||
1851 Name == "mktime") {
1852 if (FTy->getNumParams() == 0 ||
1853 !FTy->getParamType(0)->isPointerTy())
1854 return;
1855 setDoesNotThrow(F);
1856 setDoesNotCapture(F, 1);
1857 }
1858 break;
1859 case 'r':
1860 if (Name == "realloc") {
1861 if (FTy->getNumParams() != 2 ||
1862 !FTy->getParamType(0)->isPointerTy() ||
1863 !FTy->getReturnType()->isPointerTy())
1864 return;
1865 setDoesNotThrow(F);
1866 setDoesNotAlias(F, 0);
1867 setDoesNotCapture(F, 1);
1868 } else if (Name == "read") {
1869 if (FTy->getNumParams() != 3 ||
1870 !FTy->getParamType(1)->isPointerTy())
1871 return;
1872 // May throw; "read" is a valid pthread cancellation point.
1873 setDoesNotCapture(F, 2);
1874 } else if (Name == "rmdir" ||
1875 Name == "rewind" ||
1876 Name == "remove" ||
1877 Name == "realpath") {
1878 if (FTy->getNumParams() < 1 ||
1879 !FTy->getParamType(0)->isPointerTy())
1880 return;
1881 setDoesNotThrow(F);
1882 setDoesNotCapture(F, 1);
1883 } else if (Name == "rename" ||
1884 Name == "readlink") {
1885 if (FTy->getNumParams() < 2 ||
1886 !FTy->getParamType(0)->isPointerTy() ||
1887 !FTy->getParamType(1)->isPointerTy())
1888 return;
1889 setDoesNotThrow(F);
1890 setDoesNotCapture(F, 1);
1891 setDoesNotCapture(F, 2);
1892 }
1893 break;
1894 case 'w':
1895 if (Name == "write") {
1896 if (FTy->getNumParams() != 3 || !FTy->getParamType(1)->isPointerTy())
1897 return;
1898 // May throw; "write" is a valid pthread cancellation point.
1899 setDoesNotCapture(F, 2);
1900 }
1901 break;
1902 case 'b':
1903 if (Name == "bcopy") {
1904 if (FTy->getNumParams() != 3 ||
1905 !FTy->getParamType(0)->isPointerTy() ||
1906 !FTy->getParamType(1)->isPointerTy())
1907 return;
1908 setDoesNotThrow(F);
1909 setDoesNotCapture(F, 1);
1910 setDoesNotCapture(F, 2);
1911 } else if (Name == "bcmp") {
1912 if (FTy->getNumParams() != 3 ||
1913 !FTy->getParamType(0)->isPointerTy() ||
1914 !FTy->getParamType(1)->isPointerTy())
1915 return;
1916 setDoesNotThrow(F);
1917 setOnlyReadsMemory(F);
1918 setDoesNotCapture(F, 1);
1919 setDoesNotCapture(F, 2);
1920 } else if (Name == "bzero") {
1921 if (FTy->getNumParams() != 2 || !FTy->getParamType(0)->isPointerTy())
1922 return;
1923 setDoesNotThrow(F);
1924 setDoesNotCapture(F, 1);
1925 }
1926 break;
1927 case 'c':
1928 if (Name == "calloc") {
1929 if (FTy->getNumParams() != 2 ||
1930 !FTy->getReturnType()->isPointerTy())
1931 return;
1932 setDoesNotThrow(F);
1933 setDoesNotAlias(F, 0);
1934 } else if (Name == "chmod" ||
1935 Name == "chown" ||
1936 Name == "ctermid" ||
1937 Name == "clearerr" ||
1938 Name == "closedir") {
1939 if (FTy->getNumParams() == 0 || !FTy->getParamType(0)->isPointerTy())
1940 return;
1941 setDoesNotThrow(F);
1942 setDoesNotCapture(F, 1);
1943 }
1944 break;
1945 case 'a':
1946 if (Name == "atoi" ||
1947 Name == "atol" ||
1948 Name == "atof" ||
1949 Name == "atoll") {
1950 if (FTy->getNumParams() != 1 || !FTy->getParamType(0)->isPointerTy())
1951 return;
1952 setDoesNotThrow(F);
1953 setOnlyReadsMemory(F);
1954 setDoesNotCapture(F, 1);
1955 } else if (Name == "access") {
1956 if (FTy->getNumParams() != 2 || !FTy->getParamType(0)->isPointerTy())
1957 return;
1958 setDoesNotThrow(F);
1959 setDoesNotCapture(F, 1);
1960 }
1961 break;
1962 case 'f':
1963 if (Name == "fopen") {
1964 if (FTy->getNumParams() != 2 ||
1965 !FTy->getReturnType()->isPointerTy() ||
1966 !FTy->getParamType(0)->isPointerTy() ||
1967 !FTy->getParamType(1)->isPointerTy())
1968 return;
1969 setDoesNotThrow(F);
1970 setDoesNotAlias(F, 0);
1971 setDoesNotCapture(F, 1);
1972 setDoesNotCapture(F, 2);
1973 } else if (Name == "fdopen") {
1974 if (FTy->getNumParams() != 2 ||
1975 !FTy->getReturnType()->isPointerTy() ||
1976 !FTy->getParamType(1)->isPointerTy())
1977 return;
1978 setDoesNotThrow(F);
1979 setDoesNotAlias(F, 0);
1980 setDoesNotCapture(F, 2);
1981 } else if (Name == "feof" ||
1982 Name == "free" ||
1983 Name == "fseek" ||
1984 Name == "ftell" ||
1985 Name == "fgetc" ||
1986 Name == "fseeko" ||
1987 Name == "ftello" ||
1988 Name == "fileno" ||
1989 Name == "fflush" ||
1990 Name == "fclose" ||
1991 Name == "fsetpos" ||
1992 Name == "flockfile" ||
1993 Name == "funlockfile" ||
1994 Name == "ftrylockfile") {
1995 if (FTy->getNumParams() == 0 || !FTy->getParamType(0)->isPointerTy())
1996 return;
1997 setDoesNotThrow(F);
1998 setDoesNotCapture(F, 1);
1999 } else if (Name == "ferror") {
2000 if (FTy->getNumParams() != 1 || !FTy->getParamType(0)->isPointerTy())
2001 return;
2002 setDoesNotThrow(F);
2003 setDoesNotCapture(F, 1);
2004 setOnlyReadsMemory(F);
2005 } else if (Name == "fputc" ||
2006 Name == "fstat" ||
2007 Name == "frexp" ||
2008 Name == "frexpf" ||
2009 Name == "frexpl" ||
2010 Name == "fstatvfs") {
2011 if (FTy->getNumParams() != 2 || !FTy->getParamType(1)->isPointerTy())
2012 return;
2013 setDoesNotThrow(F);
2014 setDoesNotCapture(F, 2);
2015 } else if (Name == "fgets") {
2016 if (FTy->getNumParams() != 3 ||
2017 !FTy->getParamType(0)->isPointerTy() ||
2018 !FTy->getParamType(2)->isPointerTy())
2019 return;
2020 setDoesNotThrow(F);
2021 setDoesNotCapture(F, 3);
2022 } else if (Name == "fread" ||
2023 Name == "fwrite") {
2024 if (FTy->getNumParams() != 4 ||
2025 !FTy->getParamType(0)->isPointerTy() ||
2026 !FTy->getParamType(3)->isPointerTy())
2027 return;
2028 setDoesNotThrow(F);
2029 setDoesNotCapture(F, 1);
2030 setDoesNotCapture(F, 4);
2031 } else if (Name == "fputs" ||
2032 Name == "fscanf" ||
2033 Name == "fprintf" ||
2034 Name == "fgetpos") {
2035 if (FTy->getNumParams() < 2 ||
2036 !FTy->getParamType(0)->isPointerTy() ||
2037 !FTy->getParamType(1)->isPointerTy())
2038 return;
2039 setDoesNotThrow(F);
2040 setDoesNotCapture(F, 1);
2041 setDoesNotCapture(F, 2);
2042 }
2043 break;
2044 case 'g':
2045 if (Name == "getc" ||
2046 Name == "getlogin_r" ||
2047 Name == "getc_unlocked") {
2048 if (FTy->getNumParams() == 0 || !FTy->getParamType(0)->isPointerTy())
2049 return;
2050 setDoesNotThrow(F);
2051 setDoesNotCapture(F, 1);
2052 } else if (Name == "getenv") {
2053 if (FTy->getNumParams() != 1 || !FTy->getParamType(0)->isPointerTy())
2054 return;
2055 setDoesNotThrow(F);
2056 setOnlyReadsMemory(F);
2057 setDoesNotCapture(F, 1);
2058 } else if (Name == "gets" ||
2059 Name == "getchar") {
2060 setDoesNotThrow(F);
2061 } else if (Name == "getitimer") {
2062 if (FTy->getNumParams() != 2 || !FTy->getParamType(1)->isPointerTy())
2063 return;
2064 setDoesNotThrow(F);
2065 setDoesNotCapture(F, 2);
2066 } else if (Name == "getpwnam") {
2067 if (FTy->getNumParams() != 1 || !FTy->getParamType(0)->isPointerTy())
2068 return;
2069 setDoesNotThrow(F);
2070 setDoesNotCapture(F, 1);
2071 }
2072 break;
2073 case 'u':
2074 if (Name == "ungetc") {
2075 if (FTy->getNumParams() != 2 || !FTy->getParamType(1)->isPointerTy())
2076 return;
2077 setDoesNotThrow(F);
2078 setDoesNotCapture(F, 2);
2079 } else if (Name == "uname" ||
2080 Name == "unlink" ||
2081 Name == "unsetenv") {
2082 if (FTy->getNumParams() != 1 || !FTy->getParamType(0)->isPointerTy())
2083 return;
2084 setDoesNotThrow(F);
2085 setDoesNotCapture(F, 1);
2086 } else if (Name == "utime" ||
2087 Name == "utimes") {
2088 if (FTy->getNumParams() != 2 ||
2089 !FTy->getParamType(0)->isPointerTy() ||
2090 !FTy->getParamType(1)->isPointerTy())
2091 return;
2092 setDoesNotThrow(F);
2093 setDoesNotCapture(F, 1);
2094 setDoesNotCapture(F, 2);
2095 }
2096 break;
2097 case 'p':
2098 if (Name == "putc") {
2099 if (FTy->getNumParams() != 2 || !FTy->getParamType(1)->isPointerTy())
2100 return;
2101 setDoesNotThrow(F);
2102 setDoesNotCapture(F, 2);
2103 } else if (Name == "puts" ||
2104 Name == "printf" ||
2105 Name == "perror") {
2106 if (FTy->getNumParams() != 1 || !FTy->getParamType(0)->isPointerTy())
2107 return;
2108 setDoesNotThrow(F);
2109 setDoesNotCapture(F, 1);
2110 } else if (Name == "pread" ||
2111 Name == "pwrite") {
2112 if (FTy->getNumParams() != 4 || !FTy->getParamType(1)->isPointerTy())
2113 return;
2114 // May throw; these are valid pthread cancellation points.
2115 setDoesNotCapture(F, 2);
2116 } else if (Name == "putchar") {
2117 setDoesNotThrow(F);
2118 } else if (Name == "popen") {
2119 if (FTy->getNumParams() != 2 ||
2120 !FTy->getReturnType()->isPointerTy() ||
2121 !FTy->getParamType(0)->isPointerTy() ||
2122 !FTy->getParamType(1)->isPointerTy())
2123 return;
2124 setDoesNotThrow(F);
2125 setDoesNotAlias(F, 0);
2126 setDoesNotCapture(F, 1);
2127 setDoesNotCapture(F, 2);
2128 } else if (Name == "pclose") {
2129 if (FTy->getNumParams() != 1 || !FTy->getParamType(0)->isPointerTy())
2130 return;
2131 setDoesNotThrow(F);
2132 setDoesNotCapture(F, 1);
2133 }
2134 break;
2135 case 'v':
2136 if (Name == "vscanf") {
2137 if (FTy->getNumParams() != 2 || !FTy->getParamType(1)->isPointerTy())
2138 return;
2139 setDoesNotThrow(F);
2140 setDoesNotCapture(F, 1);
2141 } else if (Name == "vsscanf" ||
2142 Name == "vfscanf") {
2143 if (FTy->getNumParams() != 3 ||
2144 !FTy->getParamType(1)->isPointerTy() ||
2145 !FTy->getParamType(2)->isPointerTy())
2146 return;
2147 setDoesNotThrow(F);
2148 setDoesNotCapture(F, 1);
2149 setDoesNotCapture(F, 2);
2150 } else if (Name == "valloc") {
2151 if (!FTy->getReturnType()->isPointerTy())
2152 return;
2153 setDoesNotThrow(F);
2154 setDoesNotAlias(F, 0);
2155 } else if (Name == "vprintf") {
2156 if (FTy->getNumParams() != 2 || !FTy->getParamType(0)->isPointerTy())
2157 return;
2158 setDoesNotThrow(F);
2159 setDoesNotCapture(F, 1);
2160 } else if (Name == "vfprintf" ||
2161 Name == "vsprintf") {
2162 if (FTy->getNumParams() != 3 ||
2163 !FTy->getParamType(0)->isPointerTy() ||
2164 !FTy->getParamType(1)->isPointerTy())
2165 return;
2166 setDoesNotThrow(F);
2167 setDoesNotCapture(F, 1);
2168 setDoesNotCapture(F, 2);
2169 } else if (Name == "vsnprintf") {
2170 if (FTy->getNumParams() != 4 ||
2171 !FTy->getParamType(0)->isPointerTy() ||
2172 !FTy->getParamType(2)->isPointerTy())
2173 return;
2174 setDoesNotThrow(F);
2175 setDoesNotCapture(F, 1);
2176 setDoesNotCapture(F, 3);
2177 }
2178 break;
2179 case 'o':
2180 if (Name == "open") {
2181 if (FTy->getNumParams() < 2 || !FTy->getParamType(0)->isPointerTy())
2182 return;
2183 // May throw; "open" is a valid pthread cancellation point.
2184 setDoesNotCapture(F, 1);
2185 } else if (Name == "opendir") {
2186 if (FTy->getNumParams() != 1 ||
2187 !FTy->getReturnType()->isPointerTy() ||
2188 !FTy->getParamType(0)->isPointerTy())
2189 return;
2190 setDoesNotThrow(F);
2191 setDoesNotAlias(F, 0);
2192 setDoesNotCapture(F, 1);
2193 }
2194 break;
2195 case 't':
2196 if (Name == "tmpfile") {
2197 if (!FTy->getReturnType()->isPointerTy())
2198 return;
2199 setDoesNotThrow(F);
2200 setDoesNotAlias(F, 0);
2201 } else if (Name == "times") {
2202 if (FTy->getNumParams() != 1 || !FTy->getParamType(0)->isPointerTy())
2203 return;
2204 setDoesNotThrow(F);
2205 setDoesNotCapture(F, 1);
2206 }
2207 break;
2208 case 'h':
2209 if (Name == "htonl" ||
2210 Name == "htons") {
2211 setDoesNotThrow(F);
2212 setDoesNotAccessMemory(F);
2213 }
2214 break;
2215 case 'n':
2216 if (Name == "ntohl" ||
2217 Name == "ntohs") {
2218 setDoesNotThrow(F);
2219 setDoesNotAccessMemory(F);
2220 }
2221 break;
2222 case 'l':
2223 if (Name == "lstat") {
2224 if (FTy->getNumParams() != 2 ||
2225 !FTy->getParamType(0)->isPointerTy() ||
2226 !FTy->getParamType(1)->isPointerTy())
2227 return;
2228 setDoesNotThrow(F);
2229 setDoesNotCapture(F, 1);
2230 setDoesNotCapture(F, 2);
2231 } else if (Name == "lchown") {
2232 if (FTy->getNumParams() != 3 || !FTy->getParamType(0)->isPointerTy())
2233 return;
2234 setDoesNotThrow(F);
2235 setDoesNotCapture(F, 1);
2236 }
2237 break;
2238 case 'q':
2239 if (Name == "qsort") {
2240 if (FTy->getNumParams() != 4 || !FTy->getParamType(3)->isPointerTy())
2241 return;
2242 // May throw; places call through function pointer.
2243 setDoesNotCapture(F, 4);
2244 }
2245 break;
2246 case '_':
2247 if (Name == "__strdup" ||
2248 Name == "__strndup") {
2249 if (FTy->getNumParams() < 1 ||
2250 !FTy->getReturnType()->isPointerTy() ||
2251 !FTy->getParamType(0)->isPointerTy())
2252 return;
2253 setDoesNotThrow(F);
2254 setDoesNotAlias(F, 0);
2255 setDoesNotCapture(F, 1);
2256 } else if (Name == "__strtok_r") {
2257 if (FTy->getNumParams() != 3 ||
2258 !FTy->getParamType(1)->isPointerTy())
2259 return;
2260 setDoesNotThrow(F);
2261 setDoesNotCapture(F, 2);
2262 } else if (Name == "_IO_getc") {
2263 if (FTy->getNumParams() != 1 || !FTy->getParamType(0)->isPointerTy())
2264 return;
2265 setDoesNotThrow(F);
2266 setDoesNotCapture(F, 1);
2267 } else if (Name == "_IO_putc") {
2268 if (FTy->getNumParams() != 2 || !FTy->getParamType(1)->isPointerTy())
2269 return;
2270 setDoesNotThrow(F);
2271 setDoesNotCapture(F, 2);
2272 }
2273 break;
2274 case 1:
2275 if (Name == "\1__isoc99_scanf") {
2276 if (FTy->getNumParams() < 1 ||
2277 !FTy->getParamType(0)->isPointerTy())
2278 return;
2279 setDoesNotThrow(F);
2280 setDoesNotCapture(F, 1);
2281 } else if (Name == "\1stat64" ||
2282 Name == "\1lstat64" ||
2283 Name == "\1statvfs64" ||
2284 Name == "\1__isoc99_sscanf") {
2285 if (FTy->getNumParams() < 1 ||
2286 !FTy->getParamType(0)->isPointerTy() ||
2287 !FTy->getParamType(1)->isPointerTy())
2288 return;
2289 setDoesNotThrow(F);
2290 setDoesNotCapture(F, 1);
2291 setDoesNotCapture(F, 2);
2292 } else if (Name == "\1fopen64") {
2293 if (FTy->getNumParams() != 2 ||
2294 !FTy->getReturnType()->isPointerTy() ||
2295 !FTy->getParamType(0)->isPointerTy() ||
2296 !FTy->getParamType(1)->isPointerTy())
2297 return;
2298 setDoesNotThrow(F);
2299 setDoesNotAlias(F, 0);
2300 setDoesNotCapture(F, 1);
2301 setDoesNotCapture(F, 2);
2302 } else if (Name == "\1fseeko64" ||
2303 Name == "\1ftello64") {
2304 if (FTy->getNumParams() == 0 || !FTy->getParamType(0)->isPointerTy())
2305 return;
2306 setDoesNotThrow(F);
2307 setDoesNotCapture(F, 1);
2308 } else if (Name == "\1tmpfile64") {
2309 if (!FTy->getReturnType()->isPointerTy())
2310 return;
2311 setDoesNotThrow(F);
2312 setDoesNotAlias(F, 0);
2313 } else if (Name == "\1fstat64" ||
2314 Name == "\1fstatvfs64") {
2315 if (FTy->getNumParams() != 2 || !FTy->getParamType(1)->isPointerTy())
2316 return;
2317 setDoesNotThrow(F);
2318 setDoesNotCapture(F, 2);
2319 } else if (Name == "\1open64") {
2320 if (FTy->getNumParams() < 2 || !FTy->getParamType(0)->isPointerTy())
2321 return;
2322 // May throw; "open" is a valid pthread cancellation point.
2323 setDoesNotCapture(F, 1);
2324 }
2325 break;
2326 }
2327}
2328
Nick Lewycky6cd0c042009-01-05 00:07:50 +00002329/// doInitialization - Add attributes to well-known functions.
Nick Lewycky0f8df9a2009-01-04 20:27:34 +00002330///
Nick Lewycky6cd0c042009-01-05 00:07:50 +00002331bool SimplifyLibCalls::doInitialization(Module &M) {
Nick Lewycky0f8df9a2009-01-04 20:27:34 +00002332 Modified = false;
2333 for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I) {
2334 Function &F = *I;
Chris Lattnere265ad82011-02-24 07:12:12 +00002335 if (F.isDeclaration() && F.hasName())
2336 inferPrototypeAttributes(F);
Nick Lewycky0f8df9a2009-01-04 20:27:34 +00002337 }
2338 return Modified;
2339}
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00002340
2341// TODO:
2342// Additional cases that we need to add to this file:
2343//
2344// cbrt:
2345// * cbrt(expN(X)) -> expN(x/3)
2346// * cbrt(sqrt(x)) -> pow(x,1/6)
2347// * cbrt(sqrt(x)) -> pow(x,1/9)
2348//
2349// cos, cosf, cosl:
2350// * cos(-x) -> cos(x)
2351//
2352// exp, expf, expl:
2353// * exp(log(x)) -> x
2354//
2355// log, logf, logl:
2356// * log(exp(x)) -> x
2357// * log(x**y) -> y*log(x)
2358// * log(exp(y)) -> y*log(e)
2359// * log(exp2(y)) -> y*log(2)
2360// * log(exp10(y)) -> y*log(10)
2361// * log(sqrt(x)) -> 0.5*log(x)
2362// * log(pow(x,y)) -> y*log(x)
2363//
2364// lround, lroundf, lroundl:
2365// * lround(cnst) -> cnst'
2366//
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00002367// pow, powf, powl:
2368// * pow(exp(x),y) -> exp(x*y)
2369// * pow(sqrt(x),y) -> pow(x,y*0.5)
2370// * pow(pow(x,y),z)-> pow(x,y*z)
2371//
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00002372// round, roundf, roundl:
2373// * round(cnst) -> cnst'
2374//
2375// signbit:
2376// * signbit(cnst) -> cnst'
2377// * signbit(nncst) -> 0 (if pstv is a non-negative constant)
2378//
2379// sqrt, sqrtf, sqrtl:
2380// * sqrt(expN(x)) -> expN(x*0.5)
2381// * sqrt(Nroot(x)) -> pow(x,1/(2*N))
2382// * sqrt(pow(x,y)) -> pow(|x|,y*0.5)
2383//
2384// stpcpy:
2385// * stpcpy(str, "literal") ->
2386// llvm.memcpy(str,"literal",strlen("literal")+1,1)
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00002387//
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00002388// tan, tanf, tanl:
2389// * tan(atan(x)) -> x
2390//
2391// trunc, truncf, truncl:
2392// * trunc(cnst) -> cnst'
2393//
2394//