blob: 2d76afc2071eb3a38721374ba0577b0d2e3bdae8 [file] [log] [blame]
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001//===- SimplifyLibCalls.cpp - Optimize specific well-known library calls --===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file implements a simple pass that applies a variety of small
11// optimizations for calls to specific well-known function calls (e.g. runtime
Chris Lattnere9f9a7e2009-09-03 05:19:59 +000012// library functions). Any optimization that takes the very simple form
13// "replace call to library function with simpler code that provides the same
14// result" belongs in this file.
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +000015//
16//===----------------------------------------------------------------------===//
17
18#define DEBUG_TYPE "simplify-libcalls"
19#include "llvm/Transforms/Scalar.h"
Eric Christopherb6174e32010-03-05 22:25:30 +000020#include "llvm/Transforms/Utils/BuildLibCalls.h"
Chandler Carruth06cb8ed2012-06-29 12:38:19 +000021#include "llvm/IRBuilder.h"
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +000022#include "llvm/Intrinsics.h"
Owen Andersonfa5cbd62009-07-03 19:42:02 +000023#include "llvm/LLVMContext.h"
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +000024#include "llvm/Module.h"
25#include "llvm/Pass.h"
Daniel Dunbar473955f2009-07-29 22:00:43 +000026#include "llvm/ADT/STLExtras.h"
Chandler Carruth06cb8ed2012-06-29 12:38:19 +000027#include "llvm/ADT/SmallPtrSet.h"
28#include "llvm/ADT/Statistic.h"
29#include "llvm/ADT/StringMap.h"
30#include "llvm/Analysis/ValueTracking.h"
Chris Lattner56b4f2b2008-05-01 06:39:12 +000031#include "llvm/Support/Debug.h"
Daniel Dunbarf0443c12009-07-26 08:34:35 +000032#include "llvm/Support/raw_ostream.h"
Chandler Carruth06cb8ed2012-06-29 12:38:19 +000033#include "llvm/Target/TargetData.h"
34#include "llvm/Target/TargetLibraryInfo.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}
Nadav Rotema94d6e82012-07-24 10:51:42 +0000103
Richard Osborne36498242011-03-03 13:17:51 +0000104static 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.
Nuno Lopes51004df2012-07-25 16:46:31 +0000167 Value *DstLen = EmitStrLen(Dst, B, TD, TLI);
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),
Nuno Lopes51004df2012-07-25 16:46:31 +0000257 B, TD, TLI);
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000258 }
Nadav Rotema94d6e82012-07-24 10:51:42 +0000259
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000260 // Otherwise, the character is a constant, see if the first argument is
261 // a string literal. If so, we can constant fold.
Chris Lattner18c7f802012-02-05 02:29:43 +0000262 StringRef 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 Lattner18c7f802012-02-05 02:29:43 +0000266 // Compute the offset, make sure to handle the case when we're searching for
267 // zero (a weird way to spell strlen).
268 size_t I = CharC->getSExtValue() == 0 ?
269 Str.size() : Str.find(CharC->getSExtValue());
270 if (I == StringRef::npos) // Didn't find the char. strchr returns null.
Benjamin Kramere2609902010-09-29 22:29:12 +0000271 return Constant::getNullValue(CI->getType());
Eric Christopher37c8b862009-10-07 21:14:25 +0000272
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000273 // strchr(s+n,c) -> gep(s+n+i,c)
Benjamin Kramera1bf4ca2010-12-27 00:16:46 +0000274 return B.CreateGEP(SrcStr, B.getInt64(I), "strchr");
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000275 }
276};
277
278//===---------------------------------------===//
Benjamin Kramer06f25cf2010-09-29 21:50:51 +0000279// 'strrchr' Optimizations
280
281struct StrRChrOpt : public LibCallOptimization {
282 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
283 // Verify the "strrchr" function prototype.
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000284 FunctionType *FT = Callee->getFunctionType();
Benjamin Kramer06f25cf2010-09-29 21:50:51 +0000285 if (FT->getNumParams() != 2 ||
Benjamin Kramera1bf4ca2010-12-27 00:16:46 +0000286 FT->getReturnType() != B.getInt8PtrTy() ||
Benjamin Kramer4c756792010-09-30 11:21:59 +0000287 FT->getParamType(0) != FT->getReturnType() ||
288 !FT->getParamType(1)->isIntegerTy(32))
Benjamin Kramer06f25cf2010-09-29 21:50:51 +0000289 return 0;
290
291 Value *SrcStr = CI->getArgOperand(0);
292 ConstantInt *CharC = dyn_cast<ConstantInt>(CI->getArgOperand(1));
293
294 // Cannot fold anything if we're not looking for a constant.
295 if (!CharC)
296 return 0;
297
Chris Lattner18c7f802012-02-05 02:29:43 +0000298 StringRef Str;
299 if (!getConstantStringInfo(SrcStr, Str)) {
Benjamin Kramer06f25cf2010-09-29 21:50:51 +0000300 // strrchr(s, 0) -> strchr(s, 0)
301 if (TD && CharC->isZero())
Nuno Lopes51004df2012-07-25 16:46:31 +0000302 return EmitStrChr(SrcStr, '\0', B, TD, TLI);
Benjamin Kramer06f25cf2010-09-29 21:50:51 +0000303 return 0;
304 }
305
Benjamin Kramer06f25cf2010-09-29 21:50:51 +0000306 // Compute the offset.
Chris Lattner18c7f802012-02-05 02:29:43 +0000307 size_t I = CharC->getSExtValue() == 0 ?
308 Str.size() : Str.rfind(CharC->getSExtValue());
309 if (I == StringRef::npos) // Didn't find the char. Return null.
Benjamin Kramer06f25cf2010-09-29 21:50:51 +0000310 return Constant::getNullValue(CI->getType());
311
312 // strrchr(s+n,c) -> gep(s+n+i,c)
Benjamin Kramera1bf4ca2010-12-27 00:16:46 +0000313 return B.CreateGEP(SrcStr, B.getInt64(I), "strrchr");
Benjamin Kramer06f25cf2010-09-29 21:50:51 +0000314 }
315};
316
317//===---------------------------------------===//
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000318// 'strcmp' Optimizations
319
Chris Lattner3e8b6632009-09-02 06:11:42 +0000320struct StrCmpOpt : public LibCallOptimization {
Eric Christopher7a61d702008-08-08 19:39:37 +0000321 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000322 // Verify the "strcmp" function prototype.
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000323 FunctionType *FT = Callee->getFunctionType();
Eric Christopher37c8b862009-10-07 21:14:25 +0000324 if (FT->getNumParams() != 2 ||
Nick Lewycky10d2f4d2010-07-06 03:53:43 +0000325 !FT->getReturnType()->isIntegerTy(32) ||
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000326 FT->getParamType(0) != FT->getParamType(1) ||
Benjamin Kramera1bf4ca2010-12-27 00:16:46 +0000327 FT->getParamType(0) != B.getInt8PtrTy())
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000328 return 0;
Eric Christopher37c8b862009-10-07 21:14:25 +0000329
Gabor Greifaee5dc12010-06-24 10:42:46 +0000330 Value *Str1P = CI->getArgOperand(0), *Str2P = CI->getArgOperand(1);
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000331 if (Str1P == Str2P) // strcmp(x,x) -> 0
Owen Andersoneed707b2009-07-24 23:12:02 +0000332 return ConstantInt::get(CI->getType(), 0);
Eric Christopher37c8b862009-10-07 21:14:25 +0000333
Chris Lattner18c7f802012-02-05 02:29:43 +0000334 StringRef Str1, Str2;
335 bool HasStr1 = getConstantStringInfo(Str1P, Str1);
336 bool HasStr2 = getConstantStringInfo(Str2P, Str2);
Eric Christopher37c8b862009-10-07 21:14:25 +0000337
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000338 // strcmp(x, y) -> cnst (if both x and y are constant strings)
Bill Wendling0582ae92009-03-13 04:39:26 +0000339 if (HasStr1 && HasStr2)
Chris Lattner18c7f802012-02-05 02:29:43 +0000340 return ConstantInt::get(CI->getType(), Str1.compare(Str2));
Eli Friedman79286082011-10-05 22:27:16 +0000341
342 if (HasStr1 && Str1.empty()) // strcmp("", x) -> -*x
343 return B.CreateNeg(B.CreateZExt(B.CreateLoad(Str2P, "strcmpload"),
344 CI->getType()));
345
346 if (HasStr2 && Str2.empty()) // strcmp(x,"") -> *x
347 return B.CreateZExt(B.CreateLoad(Str1P, "strcmpload"), CI->getType());
Nick Lewycky13a09e22008-12-21 00:19:21 +0000348
349 // strcmp(P, "x") -> memcmp(P, "x", 2)
350 uint64_t Len1 = GetStringLength(Str1P);
351 uint64_t Len2 = GetStringLength(Str2P);
Chris Lattner849832c2009-06-19 04:17:36 +0000352 if (Len1 && Len2) {
Dan Gohmanf14d9192009-08-18 00:48:13 +0000353 // These optimizations require TargetData.
354 if (!TD) return 0;
355
Nick Lewycky13a09e22008-12-21 00:19:21 +0000356 return EmitMemCmp(Str1P, Str2P,
Owen Anderson1d0be152009-08-13 21:58:54 +0000357 ConstantInt::get(TD->getIntPtrType(*Context),
Nuno Lopes51004df2012-07-25 16:46:31 +0000358 std::min(Len1, Len2)), B, TD, TLI);
Nick Lewycky13a09e22008-12-21 00:19:21 +0000359 }
360
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000361 return 0;
362 }
363};
364
365//===---------------------------------------===//
366// 'strncmp' Optimizations
367
Chris Lattner3e8b6632009-09-02 06:11:42 +0000368struct StrNCmpOpt : public LibCallOptimization {
Eric Christopher7a61d702008-08-08 19:39:37 +0000369 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000370 // Verify the "strncmp" function prototype.
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000371 FunctionType *FT = Callee->getFunctionType();
Eric Christopher37c8b862009-10-07 21:14:25 +0000372 if (FT->getNumParams() != 3 ||
Nick Lewycky10d2f4d2010-07-06 03:53:43 +0000373 !FT->getReturnType()->isIntegerTy(32) ||
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000374 FT->getParamType(0) != FT->getParamType(1) ||
Benjamin Kramera1bf4ca2010-12-27 00:16:46 +0000375 FT->getParamType(0) != B.getInt8PtrTy() ||
Duncan Sands1df98592010-02-16 11:11:14 +0000376 !FT->getParamType(2)->isIntegerTy())
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000377 return 0;
Eric Christopher37c8b862009-10-07 21:14:25 +0000378
Gabor Greifaee5dc12010-06-24 10:42:46 +0000379 Value *Str1P = CI->getArgOperand(0), *Str2P = CI->getArgOperand(1);
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000380 if (Str1P == Str2P) // strncmp(x,x,n) -> 0
Owen Andersoneed707b2009-07-24 23:12:02 +0000381 return ConstantInt::get(CI->getType(), 0);
Eric Christopher37c8b862009-10-07 21:14:25 +0000382
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000383 // Get the length argument if it is constant.
384 uint64_t Length;
Gabor Greifaee5dc12010-06-24 10:42:46 +0000385 if (ConstantInt *LengthArg = dyn_cast<ConstantInt>(CI->getArgOperand(2)))
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000386 Length = LengthArg->getZExtValue();
387 else
388 return 0;
Eric Christopher37c8b862009-10-07 21:14:25 +0000389
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000390 if (Length == 0) // strncmp(x,y,0) -> 0
Owen Andersoneed707b2009-07-24 23:12:02 +0000391 return ConstantInt::get(CI->getType(), 0);
Eric Christopher37c8b862009-10-07 21:14:25 +0000392
Benjamin Kramerea9ca022010-06-16 10:30:29 +0000393 if (TD && Length == 1) // strncmp(x,y,1) -> memcmp(x,y,1)
Nuno Lopes51004df2012-07-25 16:46:31 +0000394 return EmitMemCmp(Str1P, Str2P, CI->getArgOperand(2), B, TD, TLI);
Benjamin Kramerea9ca022010-06-16 10:30:29 +0000395
Chris Lattner18c7f802012-02-05 02:29:43 +0000396 StringRef Str1, Str2;
397 bool HasStr1 = getConstantStringInfo(Str1P, Str1);
398 bool HasStr2 = getConstantStringInfo(Str2P, Str2);
Eric Christopher37c8b862009-10-07 21:14:25 +0000399
Eli Friedman79286082011-10-05 22:27:16 +0000400 // strncmp(x, y) -> cnst (if both x and y are constant strings)
401 if (HasStr1 && HasStr2) {
Chris Lattner18c7f802012-02-05 02:29:43 +0000402 StringRef SubStr1 = Str1.substr(0, Length);
403 StringRef SubStr2 = Str2.substr(0, Length);
Eli Friedman79286082011-10-05 22:27:16 +0000404 return ConstantInt::get(CI->getType(), SubStr1.compare(SubStr2));
405 }
406
407 if (HasStr1 && Str1.empty()) // strncmp("", x, n) -> -*x
408 return B.CreateNeg(B.CreateZExt(B.CreateLoad(Str2P, "strcmpload"),
409 CI->getType()));
Eric Christopher37c8b862009-10-07 21:14:25 +0000410
Bill Wendling0582ae92009-03-13 04:39:26 +0000411 if (HasStr2 && Str2.empty()) // strncmp(x, "", n) -> *x
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000412 return B.CreateZExt(B.CreateLoad(Str1P, "strcmpload"), CI->getType());
Eric Christopher37c8b862009-10-07 21:14:25 +0000413
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000414 return 0;
415 }
416};
417
418
419//===---------------------------------------===//
420// 'strcpy' Optimizations
421
Chris Lattner3e8b6632009-09-02 06:11:42 +0000422struct StrCpyOpt : public LibCallOptimization {
Evan Chengeb8c6452010-03-24 20:19:04 +0000423 bool OptChkCall; // True if it's optimizing a __strcpy_chk libcall.
424
425 StrCpyOpt(bool c) : OptChkCall(c) {}
426
Eric Christopher7a61d702008-08-08 19:39:37 +0000427 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000428 // Verify the "strcpy" function prototype.
Evan Cheng0289b412010-03-23 15:48:04 +0000429 unsigned NumParams = OptChkCall ? 3 : 2;
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000430 FunctionType *FT = Callee->getFunctionType();
Evan Cheng0289b412010-03-23 15:48:04 +0000431 if (FT->getNumParams() != NumParams ||
432 FT->getReturnType() != FT->getParamType(0) ||
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000433 FT->getParamType(0) != FT->getParamType(1) ||
Benjamin Kramera1bf4ca2010-12-27 00:16:46 +0000434 FT->getParamType(0) != B.getInt8PtrTy())
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000435 return 0;
Eric Christopher37c8b862009-10-07 21:14:25 +0000436
Gabor Greifaee5dc12010-06-24 10:42:46 +0000437 Value *Dst = CI->getArgOperand(0), *Src = CI->getArgOperand(1);
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000438 if (Dst == Src) // strcpy(x,x) -> x
439 return Src;
Eric Christopher37c8b862009-10-07 21:14:25 +0000440
Dan Gohmanf14d9192009-08-18 00:48:13 +0000441 // These optimizations require TargetData.
442 if (!TD) return 0;
443
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000444 // See if we can get the length of the input string.
445 uint64_t Len = GetStringLength(Src);
Chris Lattner56b4f2b2008-05-01 06:39:12 +0000446 if (Len == 0) return 0;
Eric Christopher37c8b862009-10-07 21:14:25 +0000447
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000448 // We have enough information to now generate the memcpy call to do the
449 // concatenation for us. Make a memcpy to copy the nul byte with align = 1.
Evan Cheng0289b412010-03-23 15:48:04 +0000450 if (OptChkCall)
451 EmitMemCpyChk(Dst, Src,
452 ConstantInt::get(TD->getIntPtrType(*Context), Len),
Nuno Lopes51004df2012-07-25 16:46:31 +0000453 CI->getArgOperand(2), B, TD, TLI);
Evan Cheng0289b412010-03-23 15:48:04 +0000454 else
Benjamin Kramera1bf4ca2010-12-27 00:16:46 +0000455 B.CreateMemCpy(Dst, Src,
456 ConstantInt::get(TD->getIntPtrType(*Context), Len), 1);
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000457 return Dst;
458 }
459};
460
Chris Lattnerf5b6bc72009-04-12 05:06:39 +0000461//===---------------------------------------===//
David Majnemerac782662012-05-15 11:46:21 +0000462// 'stpcpy' Optimizations
463
464struct StpCpyOpt: public LibCallOptimization {
465 bool OptChkCall; // True if it's optimizing a __stpcpy_chk libcall.
466
467 StpCpyOpt(bool c) : OptChkCall(c) {}
468
469 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
470 // Verify the "stpcpy" function prototype.
471 unsigned NumParams = OptChkCall ? 3 : 2;
472 FunctionType *FT = Callee->getFunctionType();
473 if (FT->getNumParams() != NumParams ||
474 FT->getReturnType() != FT->getParamType(0) ||
475 FT->getParamType(0) != FT->getParamType(1) ||
476 FT->getParamType(0) != B.getInt8PtrTy())
477 return 0;
478
479 // These optimizations require TargetData.
480 if (!TD) return 0;
481
482 Value *Dst = CI->getArgOperand(0), *Src = CI->getArgOperand(1);
Nuno Lopes51004df2012-07-25 16:46:31 +0000483 if (Dst == Src) { // stpcpy(x,x) -> x+strlen(x)
484 Value *StrLen = EmitStrLen(Src, B, TD, TLI);
485 return StrLen ? B.CreateInBoundsGEP(Dst, StrLen) : 0;
486 }
David Majnemerac782662012-05-15 11:46:21 +0000487
488 // See if we can get the length of the input string.
489 uint64_t Len = GetStringLength(Src);
490 if (Len == 0) return 0;
491
492 Value *LenV = ConstantInt::get(TD->getIntPtrType(*Context), Len);
493 Value *DstEnd = B.CreateGEP(Dst,
494 ConstantInt::get(TD->getIntPtrType(*Context),
495 Len - 1));
496
497 // We have enough information to now generate the memcpy call to do the
498 // copy for us. Make a memcpy to copy the nul byte with align = 1.
499 if (OptChkCall)
Nuno Lopes51004df2012-07-25 16:46:31 +0000500 EmitMemCpyChk(Dst, Src, LenV, CI->getArgOperand(2), B, TD, TLI);
David Majnemerac782662012-05-15 11:46:21 +0000501 else
502 B.CreateMemCpy(Dst, Src, LenV, 1);
503 return DstEnd;
504 }
505};
506
507//===---------------------------------------===//
Chris Lattnerf5b6bc72009-04-12 05:06:39 +0000508// 'strncpy' Optimizations
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000509
Chris Lattner3e8b6632009-09-02 06:11:42 +0000510struct StrNCpyOpt : public LibCallOptimization {
Chris Lattnerf5b6bc72009-04-12 05:06:39 +0000511 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000512 FunctionType *FT = Callee->getFunctionType();
Chris Lattnerf5b6bc72009-04-12 05:06:39 +0000513 if (FT->getNumParams() != 3 || FT->getReturnType() != FT->getParamType(0) ||
514 FT->getParamType(0) != FT->getParamType(1) ||
Benjamin Kramera1bf4ca2010-12-27 00:16:46 +0000515 FT->getParamType(0) != B.getInt8PtrTy() ||
Duncan Sands1df98592010-02-16 11:11:14 +0000516 !FT->getParamType(2)->isIntegerTy())
Chris Lattnerf5b6bc72009-04-12 05:06:39 +0000517 return 0;
518
Gabor Greifaee5dc12010-06-24 10:42:46 +0000519 Value *Dst = CI->getArgOperand(0);
520 Value *Src = CI->getArgOperand(1);
521 Value *LenOp = CI->getArgOperand(2);
Chris Lattnerf5b6bc72009-04-12 05:06:39 +0000522
523 // See if we can get the length of the input string.
524 uint64_t SrcLen = GetStringLength(Src);
525 if (SrcLen == 0) return 0;
526 --SrcLen;
527
528 if (SrcLen == 0) {
529 // strncpy(x, "", y) -> memset(x, '\0', y, 1)
Benjamin Kramera1bf4ca2010-12-27 00:16:46 +0000530 B.CreateMemSet(Dst, B.getInt8('\0'), LenOp, 1);
Chris Lattnerf5b6bc72009-04-12 05:06:39 +0000531 return Dst;
532 }
533
534 uint64_t Len;
535 if (ConstantInt *LengthArg = dyn_cast<ConstantInt>(LenOp))
536 Len = LengthArg->getZExtValue();
537 else
538 return 0;
539
540 if (Len == 0) return Dst; // strncpy(x, y, 0) -> x
541
Dan Gohmanf14d9192009-08-18 00:48:13 +0000542 // These optimizations require TargetData.
543 if (!TD) return 0;
544
Chris Lattnerf5b6bc72009-04-12 05:06:39 +0000545 // Let strncpy handle the zero padding
546 if (Len > SrcLen+1) return 0;
547
548 // strncpy(x, s, c) -> memcpy(x, s, c, 1) [s and c are constant]
Benjamin Kramera1bf4ca2010-12-27 00:16:46 +0000549 B.CreateMemCpy(Dst, Src,
550 ConstantInt::get(TD->getIntPtrType(*Context), Len), 1);
Chris Lattnerf5b6bc72009-04-12 05:06:39 +0000551
552 return Dst;
553 }
554};
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000555
556//===---------------------------------------===//
557// 'strlen' Optimizations
558
Chris Lattner3e8b6632009-09-02 06:11:42 +0000559struct StrLenOpt : public LibCallOptimization {
Eric Christopher7a61d702008-08-08 19:39:37 +0000560 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000561 FunctionType *FT = Callee->getFunctionType();
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000562 if (FT->getNumParams() != 1 ||
Benjamin Kramera1bf4ca2010-12-27 00:16:46 +0000563 FT->getParamType(0) != B.getInt8PtrTy() ||
Duncan Sands1df98592010-02-16 11:11:14 +0000564 !FT->getReturnType()->isIntegerTy())
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000565 return 0;
Eric Christopher37c8b862009-10-07 21:14:25 +0000566
Gabor Greifaee5dc12010-06-24 10:42:46 +0000567 Value *Src = CI->getArgOperand(0);
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000568
569 // Constant folding: strlen("xyz") -> 3
570 if (uint64_t Len = GetStringLength(Src))
Owen Andersoneed707b2009-07-24 23:12:02 +0000571 return ConstantInt::get(CI->getType(), Len-1);
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000572
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000573 // strlen(x) != 0 --> *x != 0
574 // strlen(x) == 0 --> *x == 0
Chris Lattner98d67d72009-12-23 23:24:51 +0000575 if (IsOnlyUsedInZeroEqualityComparison(CI))
576 return B.CreateZExt(B.CreateLoad(Src, "strlenfirst"), CI->getType());
577 return 0;
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000578 }
579};
580
Benjamin Kramer05f585e2010-09-29 23:52:12 +0000581
582//===---------------------------------------===//
583// 'strpbrk' Optimizations
584
585struct StrPBrkOpt : public LibCallOptimization {
586 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000587 FunctionType *FT = Callee->getFunctionType();
Benjamin Kramer05f585e2010-09-29 23:52:12 +0000588 if (FT->getNumParams() != 2 ||
Benjamin Kramera1bf4ca2010-12-27 00:16:46 +0000589 FT->getParamType(0) != B.getInt8PtrTy() ||
Benjamin Kramer05f585e2010-09-29 23:52:12 +0000590 FT->getParamType(1) != FT->getParamType(0) ||
591 FT->getReturnType() != FT->getParamType(0))
592 return 0;
593
Chris Lattner18c7f802012-02-05 02:29:43 +0000594 StringRef S1, S2;
595 bool HasS1 = getConstantStringInfo(CI->getArgOperand(0), S1);
596 bool HasS2 = getConstantStringInfo(CI->getArgOperand(1), S2);
Benjamin Kramer05f585e2010-09-29 23:52:12 +0000597
598 // strpbrk(s, "") -> NULL
599 // strpbrk("", s) -> NULL
600 if ((HasS1 && S1.empty()) || (HasS2 && S2.empty()))
601 return Constant::getNullValue(CI->getType());
602
603 // Constant folding.
604 if (HasS1 && HasS2) {
605 size_t I = S1.find_first_of(S2);
606 if (I == std::string::npos) // No match.
607 return Constant::getNullValue(CI->getType());
608
Benjamin Kramera1bf4ca2010-12-27 00:16:46 +0000609 return B.CreateGEP(CI->getArgOperand(0), B.getInt64(I), "strpbrk");
Benjamin Kramer05f585e2010-09-29 23:52:12 +0000610 }
611
612 // strpbrk(s, "a") -> strchr(s, 'a')
613 if (TD && HasS2 && S2.size() == 1)
Nuno Lopes51004df2012-07-25 16:46:31 +0000614 return EmitStrChr(CI->getArgOperand(0), S2[0], B, TD, TLI);
Benjamin Kramer05f585e2010-09-29 23:52:12 +0000615
616 return 0;
617 }
618};
619
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000620//===---------------------------------------===//
Chris Lattner24604112009-12-16 09:32:05 +0000621// 'strto*' Optimizations. This handles strtol, strtod, strtof, strtoul, etc.
Nick Lewycky4c498412009-02-13 15:31:46 +0000622
Chris Lattner3e8b6632009-09-02 06:11:42 +0000623struct StrToOpt : public LibCallOptimization {
Nick Lewycky4c498412009-02-13 15:31:46 +0000624 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000625 FunctionType *FT = Callee->getFunctionType();
Nick Lewycky4c498412009-02-13 15:31:46 +0000626 if ((FT->getNumParams() != 2 && FT->getNumParams() != 3) ||
Duncan Sands1df98592010-02-16 11:11:14 +0000627 !FT->getParamType(0)->isPointerTy() ||
628 !FT->getParamType(1)->isPointerTy())
Nick Lewycky4c498412009-02-13 15:31:46 +0000629 return 0;
630
Gabor Greifaee5dc12010-06-24 10:42:46 +0000631 Value *EndPtr = CI->getArgOperand(1);
Nick Lewycky02b6a6a2009-02-13 17:08:33 +0000632 if (isa<ConstantPointerNull>(EndPtr)) {
Dan Gohmanc32046e2010-12-17 01:09:43 +0000633 // With a null EndPtr, this function won't capture the main argument.
634 // It would be readonly too, except that it still may write to errno.
Nick Lewycky4c498412009-02-13 15:31:46 +0000635 CI->addAttribute(1, Attribute::NoCapture);
Nick Lewycky02b6a6a2009-02-13 17:08:33 +0000636 }
Nick Lewycky4c498412009-02-13 15:31:46 +0000637
638 return 0;
639 }
640};
641
Chris Lattner24604112009-12-16 09:32:05 +0000642//===---------------------------------------===//
Benjamin Kramer9510a252010-09-30 00:58:35 +0000643// 'strspn' Optimizations
644
645struct StrSpnOpt : public LibCallOptimization {
646 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000647 FunctionType *FT = Callee->getFunctionType();
Benjamin Kramer9510a252010-09-30 00:58:35 +0000648 if (FT->getNumParams() != 2 ||
Benjamin Kramera1bf4ca2010-12-27 00:16:46 +0000649 FT->getParamType(0) != B.getInt8PtrTy() ||
Benjamin Kramer9510a252010-09-30 00:58:35 +0000650 FT->getParamType(1) != FT->getParamType(0) ||
651 !FT->getReturnType()->isIntegerTy())
652 return 0;
653
Chris Lattner18c7f802012-02-05 02:29:43 +0000654 StringRef S1, S2;
655 bool HasS1 = getConstantStringInfo(CI->getArgOperand(0), S1);
656 bool HasS2 = getConstantStringInfo(CI->getArgOperand(1), S2);
Benjamin Kramer9510a252010-09-30 00:58:35 +0000657
658 // strspn(s, "") -> 0
659 // strspn("", s) -> 0
660 if ((HasS1 && S1.empty()) || (HasS2 && S2.empty()))
661 return Constant::getNullValue(CI->getType());
662
663 // Constant folding.
Chris Lattner18c7f802012-02-05 02:29:43 +0000664 if (HasS1 && HasS2) {
665 size_t Pos = S1.find_first_not_of(S2);
666 if (Pos == StringRef::npos) Pos = S1.size();
667 return ConstantInt::get(CI->getType(), Pos);
668 }
Benjamin Kramer9510a252010-09-30 00:58:35 +0000669
670 return 0;
671 }
672};
673
674//===---------------------------------------===//
675// 'strcspn' Optimizations
676
677struct StrCSpnOpt : public LibCallOptimization {
678 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000679 FunctionType *FT = Callee->getFunctionType();
Benjamin Kramer9510a252010-09-30 00:58:35 +0000680 if (FT->getNumParams() != 2 ||
Benjamin Kramera1bf4ca2010-12-27 00:16:46 +0000681 FT->getParamType(0) != B.getInt8PtrTy() ||
Benjamin Kramer9510a252010-09-30 00:58:35 +0000682 FT->getParamType(1) != FT->getParamType(0) ||
683 !FT->getReturnType()->isIntegerTy())
684 return 0;
685
Chris Lattner18c7f802012-02-05 02:29:43 +0000686 StringRef S1, S2;
687 bool HasS1 = getConstantStringInfo(CI->getArgOperand(0), S1);
688 bool HasS2 = getConstantStringInfo(CI->getArgOperand(1), S2);
Benjamin Kramer9510a252010-09-30 00:58:35 +0000689
690 // strcspn("", s) -> 0
691 if (HasS1 && S1.empty())
692 return Constant::getNullValue(CI->getType());
693
694 // Constant folding.
Chris Lattner18c7f802012-02-05 02:29:43 +0000695 if (HasS1 && HasS2) {
696 size_t Pos = S1.find_first_of(S2);
697 if (Pos == StringRef::npos) Pos = S1.size();
698 return ConstantInt::get(CI->getType(), Pos);
699 }
Benjamin Kramer9510a252010-09-30 00:58:35 +0000700
701 // strcspn(s, "") -> strlen(s)
702 if (TD && HasS2 && S2.empty())
Nuno Lopes51004df2012-07-25 16:46:31 +0000703 return EmitStrLen(CI->getArgOperand(0), B, TD, TLI);
Benjamin Kramer9510a252010-09-30 00:58:35 +0000704
705 return 0;
706 }
707};
708
709//===---------------------------------------===//
Chris Lattner24604112009-12-16 09:32:05 +0000710// 'strstr' Optimizations
711
712struct StrStrOpt : public LibCallOptimization {
713 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000714 FunctionType *FT = Callee->getFunctionType();
Chris Lattner24604112009-12-16 09:32:05 +0000715 if (FT->getNumParams() != 2 ||
Duncan Sands1df98592010-02-16 11:11:14 +0000716 !FT->getParamType(0)->isPointerTy() ||
717 !FT->getParamType(1)->isPointerTy() ||
718 !FT->getReturnType()->isPointerTy())
Chris Lattner24604112009-12-16 09:32:05 +0000719 return 0;
720
721 // fold strstr(x, x) -> x.
Gabor Greifaee5dc12010-06-24 10:42:46 +0000722 if (CI->getArgOperand(0) == CI->getArgOperand(1))
723 return B.CreateBitCast(CI->getArgOperand(0), CI->getType());
Mikhail Glushenkoved5cb592010-01-04 07:55:25 +0000724
Benjamin Kramer386e9182010-06-15 21:34:25 +0000725 // fold strstr(a, b) == a -> strncmp(a, b, strlen(b)) == 0
Gabor Greif8e1ebff2010-06-30 12:42:43 +0000726 if (TD && IsOnlyUsedInEqualityComparison(CI, CI->getArgOperand(0))) {
Nuno Lopes51004df2012-07-25 16:46:31 +0000727 Value *StrLen = EmitStrLen(CI->getArgOperand(1), B, TD, TLI);
728 if (!StrLen)
729 return 0;
Gabor Greif8e1ebff2010-06-30 12:42:43 +0000730 Value *StrNCmp = EmitStrNCmp(CI->getArgOperand(0), CI->getArgOperand(1),
Nuno Lopes51004df2012-07-25 16:46:31 +0000731 StrLen, B, TD, TLI);
732 if (!StrNCmp)
733 return 0;
Benjamin Kramer386e9182010-06-15 21:34:25 +0000734 for (Value::use_iterator UI = CI->use_begin(), UE = CI->use_end();
735 UI != UE; ) {
Gabor Greif96f1d8e2010-07-22 13:36:47 +0000736 ICmpInst *Old = cast<ICmpInst>(*UI++);
Benjamin Kramer386e9182010-06-15 21:34:25 +0000737 Value *Cmp = B.CreateICmp(Old->getPredicate(), StrNCmp,
738 ConstantInt::getNullValue(StrNCmp->getType()),
739 "cmp");
740 Old->replaceAllUsesWith(Cmp);
741 Old->eraseFromParent();
742 }
743 return CI;
744 }
745
Chris Lattner24604112009-12-16 09:32:05 +0000746 // See if either input string is a constant string.
Chris Lattner18c7f802012-02-05 02:29:43 +0000747 StringRef SearchStr, ToFindStr;
748 bool HasStr1 = getConstantStringInfo(CI->getArgOperand(0), SearchStr);
749 bool HasStr2 = getConstantStringInfo(CI->getArgOperand(1), ToFindStr);
Mikhail Glushenkoved5cb592010-01-04 07:55:25 +0000750
Chris Lattner24604112009-12-16 09:32:05 +0000751 // fold strstr(x, "") -> x.
752 if (HasStr2 && ToFindStr.empty())
Gabor Greifaee5dc12010-06-24 10:42:46 +0000753 return B.CreateBitCast(CI->getArgOperand(0), CI->getType());
Mikhail Glushenkoved5cb592010-01-04 07:55:25 +0000754
Chris Lattner24604112009-12-16 09:32:05 +0000755 // If both strings are known, constant fold it.
756 if (HasStr1 && HasStr2) {
757 std::string::size_type Offset = SearchStr.find(ToFindStr);
Mikhail Glushenkoved5cb592010-01-04 07:55:25 +0000758
Chris Lattner18c7f802012-02-05 02:29:43 +0000759 if (Offset == StringRef::npos) // strstr("foo", "bar") -> null
Chris Lattner24604112009-12-16 09:32:05 +0000760 return Constant::getNullValue(CI->getType());
761
762 // strstr("abcd", "bc") -> gep((char*)"abcd", 1)
Gabor Greifaee5dc12010-06-24 10:42:46 +0000763 Value *Result = CastToCStr(CI->getArgOperand(0), B);
Chris Lattner24604112009-12-16 09:32:05 +0000764 Result = B.CreateConstInBoundsGEP1_64(Result, Offset, "strstr");
765 return B.CreateBitCast(Result, CI->getType());
766 }
Mikhail Glushenkoved5cb592010-01-04 07:55:25 +0000767
Chris Lattner24604112009-12-16 09:32:05 +0000768 // fold strstr(x, "y") -> strchr(x, 'y').
Nuno Lopes51004df2012-07-25 16:46:31 +0000769 if (HasStr2 && ToFindStr.size() == 1) {
770 Value *StrChr= EmitStrChr(CI->getArgOperand(0), ToFindStr[0], B, TD, TLI);
771 return StrChr ? B.CreateBitCast(StrChr, CI->getType()) : 0;
772 }
Chris Lattner24604112009-12-16 09:32:05 +0000773 return 0;
774 }
775};
Mikhail Glushenkoved5cb592010-01-04 07:55:25 +0000776
Nick Lewycky4c498412009-02-13 15:31:46 +0000777
778//===---------------------------------------===//
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000779// 'memcmp' Optimizations
780
Chris Lattner3e8b6632009-09-02 06:11:42 +0000781struct MemCmpOpt : public LibCallOptimization {
Eric Christopher7a61d702008-08-08 19:39:37 +0000782 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000783 FunctionType *FT = Callee->getFunctionType();
Duncan Sands1df98592010-02-16 11:11:14 +0000784 if (FT->getNumParams() != 3 || !FT->getParamType(0)->isPointerTy() ||
785 !FT->getParamType(1)->isPointerTy() ||
Duncan Sandsb0bc6c32010-02-15 16:12:20 +0000786 !FT->getReturnType()->isIntegerTy(32))
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000787 return 0;
Duncan Sandsec00fcb2008-05-19 09:27:24 +0000788
Gabor Greifaee5dc12010-06-24 10:42:46 +0000789 Value *LHS = CI->getArgOperand(0), *RHS = CI->getArgOperand(1);
Duncan Sandsec00fcb2008-05-19 09:27:24 +0000790
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000791 if (LHS == RHS) // memcmp(s,s,x) -> 0
Owen Andersona7235ea2009-07-31 20:28:14 +0000792 return Constant::getNullValue(CI->getType());
Duncan Sandsec00fcb2008-05-19 09:27:24 +0000793
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000794 // Make sure we have a constant length.
Gabor Greifaee5dc12010-06-24 10:42:46 +0000795 ConstantInt *LenC = dyn_cast<ConstantInt>(CI->getArgOperand(2));
Chris Lattner56b4f2b2008-05-01 06:39:12 +0000796 if (!LenC) return 0;
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000797 uint64_t Len = LenC->getZExtValue();
Duncan Sandsec00fcb2008-05-19 09:27:24 +0000798
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000799 if (Len == 0) // memcmp(s1,s2,0) -> 0
Owen Andersona7235ea2009-07-31 20:28:14 +0000800 return Constant::getNullValue(CI->getType());
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000801
Benjamin Kramer48aefe12010-05-25 22:53:43 +0000802 // memcmp(S1,S2,1) -> *(unsigned char*)LHS - *(unsigned char*)RHS
803 if (Len == 1) {
804 Value *LHSV = B.CreateZExt(B.CreateLoad(CastToCStr(LHS, B), "lhsc"),
805 CI->getType(), "lhsv");
806 Value *RHSV = B.CreateZExt(B.CreateLoad(CastToCStr(RHS, B), "rhsc"),
807 CI->getType(), "rhsv");
Benjamin Kramer1464c1d2010-05-26 09:45:04 +0000808 return B.CreateSub(LHSV, RHSV, "chardiff");
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000809 }
Duncan Sandsec00fcb2008-05-19 09:27:24 +0000810
Benjamin Kramer992a6372009-11-05 17:44:22 +0000811 // Constant folding: memcmp(x, y, l) -> cnst (all arguments are constant)
Chris Lattner18c7f802012-02-05 02:29:43 +0000812 StringRef LHSStr, RHSStr;
813 if (getConstantStringInfo(LHS, LHSStr) &&
814 getConstantStringInfo(RHS, RHSStr)) {
Benjamin Kramer992a6372009-11-05 17:44:22 +0000815 // Make sure we're not reading out-of-bounds memory.
Chris Lattner18c7f802012-02-05 02:29:43 +0000816 if (Len > LHSStr.size() || Len > RHSStr.size())
Benjamin Kramer992a6372009-11-05 17:44:22 +0000817 return 0;
818 uint64_t Ret = memcmp(LHSStr.data(), RHSStr.data(), Len);
819 return ConstantInt::get(CI->getType(), Ret);
820 }
821
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000822 return 0;
823 }
824};
825
826//===---------------------------------------===//
827// 'memcpy' Optimizations
828
Chris Lattner3e8b6632009-09-02 06:11:42 +0000829struct MemCpyOpt : public LibCallOptimization {
Eric Christopher7a61d702008-08-08 19:39:37 +0000830 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
Dan Gohmanf14d9192009-08-18 00:48:13 +0000831 // These optimizations require TargetData.
832 if (!TD) return 0;
833
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000834 FunctionType *FT = Callee->getFunctionType();
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000835 if (FT->getNumParams() != 3 || FT->getReturnType() != FT->getParamType(0) ||
Duncan Sands1df98592010-02-16 11:11:14 +0000836 !FT->getParamType(0)->isPointerTy() ||
837 !FT->getParamType(1)->isPointerTy() ||
Owen Anderson1d0be152009-08-13 21:58:54 +0000838 FT->getParamType(2) != TD->getIntPtrType(*Context))
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000839 return 0;
840
841 // memcpy(x, y, n) -> llvm.memcpy(x, y, n, 1)
Benjamin Kramera1bf4ca2010-12-27 00:16:46 +0000842 B.CreateMemCpy(CI->getArgOperand(0), CI->getArgOperand(1),
843 CI->getArgOperand(2), 1);
Gabor Greifaee5dc12010-06-24 10:42:46 +0000844 return CI->getArgOperand(0);
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000845 }
846};
847
Eli Friedmand83ae7d2008-11-30 08:32:11 +0000848//===---------------------------------------===//
849// 'memmove' Optimizations
850
Chris Lattner3e8b6632009-09-02 06:11:42 +0000851struct MemMoveOpt : public LibCallOptimization {
Eli Friedmand83ae7d2008-11-30 08:32:11 +0000852 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
Dan Gohmanf14d9192009-08-18 00:48:13 +0000853 // These optimizations require TargetData.
854 if (!TD) return 0;
855
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000856 FunctionType *FT = Callee->getFunctionType();
Eli Friedmand83ae7d2008-11-30 08:32:11 +0000857 if (FT->getNumParams() != 3 || FT->getReturnType() != FT->getParamType(0) ||
Duncan Sands1df98592010-02-16 11:11:14 +0000858 !FT->getParamType(0)->isPointerTy() ||
859 !FT->getParamType(1)->isPointerTy() ||
Owen Anderson1d0be152009-08-13 21:58:54 +0000860 FT->getParamType(2) != TD->getIntPtrType(*Context))
Eli Friedmand83ae7d2008-11-30 08:32:11 +0000861 return 0;
862
863 // memmove(x, y, n) -> llvm.memmove(x, y, n, 1)
Benjamin Kramera1bf4ca2010-12-27 00:16:46 +0000864 B.CreateMemMove(CI->getArgOperand(0), CI->getArgOperand(1),
865 CI->getArgOperand(2), 1);
Gabor Greifaee5dc12010-06-24 10:42:46 +0000866 return CI->getArgOperand(0);
Eli Friedmand83ae7d2008-11-30 08:32:11 +0000867 }
868};
869
870//===---------------------------------------===//
871// 'memset' Optimizations
872
Chris Lattner3e8b6632009-09-02 06:11:42 +0000873struct MemSetOpt : public LibCallOptimization {
Eli Friedmand83ae7d2008-11-30 08:32:11 +0000874 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
Dan Gohmanf14d9192009-08-18 00:48:13 +0000875 // These optimizations require TargetData.
876 if (!TD) return 0;
877
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000878 FunctionType *FT = Callee->getFunctionType();
Eli Friedmand83ae7d2008-11-30 08:32:11 +0000879 if (FT->getNumParams() != 3 || FT->getReturnType() != FT->getParamType(0) ||
Duncan Sands1df98592010-02-16 11:11:14 +0000880 !FT->getParamType(0)->isPointerTy() ||
881 !FT->getParamType(1)->isIntegerTy() ||
Owen Anderson1d0be152009-08-13 21:58:54 +0000882 FT->getParamType(2) != TD->getIntPtrType(*Context))
Eli Friedmand83ae7d2008-11-30 08:32:11 +0000883 return 0;
884
885 // memset(p, v, n) -> llvm.memset(p, v, n, 1)
Benjamin Kramera1bf4ca2010-12-27 00:16:46 +0000886 Value *Val = B.CreateIntCast(CI->getArgOperand(1), B.getInt8Ty(), false);
887 B.CreateMemSet(CI->getArgOperand(0), Val, CI->getArgOperand(2), 1);
Gabor Greifaee5dc12010-06-24 10:42:46 +0000888 return CI->getArgOperand(0);
Eli Friedmand83ae7d2008-11-30 08:32:11 +0000889 }
890};
891
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000892//===----------------------------------------------------------------------===//
893// Math Library Optimizations
894//===----------------------------------------------------------------------===//
895
896//===---------------------------------------===//
Nick Lewyckya6b21ea2011-12-27 18:25:50 +0000897// 'cos*' Optimizations
898
899struct CosOpt : public LibCallOptimization {
900 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
901 FunctionType *FT = Callee->getFunctionType();
902 // Just make sure this has 1 argument of FP type, which matches the
903 // result type.
904 if (FT->getNumParams() != 1 || FT->getReturnType() != FT->getParamType(0) ||
905 !FT->getParamType(0)->isFloatingPointTy())
906 return 0;
907
908 // cos(-x) -> cos(x)
909 Value *Op1 = CI->getArgOperand(0);
910 if (BinaryOperator::isFNeg(Op1)) {
911 BinaryOperator *BinExpr = cast<BinaryOperator>(Op1);
912 return B.CreateCall(Callee, BinExpr->getOperand(1), "cos");
913 }
914 return 0;
915 }
916};
917
918//===---------------------------------------===//
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000919// 'pow*' Optimizations
920
Chris Lattner3e8b6632009-09-02 06:11:42 +0000921struct PowOpt : public LibCallOptimization {
Eric Christopher7a61d702008-08-08 19:39:37 +0000922 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000923 FunctionType *FT = Callee->getFunctionType();
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000924 // Just make sure this has 2 arguments of the same FP type, which match the
925 // result type.
926 if (FT->getNumParams() != 2 || FT->getReturnType() != FT->getParamType(0) ||
927 FT->getParamType(0) != FT->getParamType(1) ||
Duncan Sandsb0bc6c32010-02-15 16:12:20 +0000928 !FT->getParamType(0)->isFloatingPointTy())
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000929 return 0;
Eric Christopher37c8b862009-10-07 21:14:25 +0000930
Gabor Greifaee5dc12010-06-24 10:42:46 +0000931 Value *Op1 = CI->getArgOperand(0), *Op2 = CI->getArgOperand(1);
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000932 if (ConstantFP *Op1C = dyn_cast<ConstantFP>(Op1)) {
933 if (Op1C->isExactlyValue(1.0)) // pow(1.0, x) -> 1.0
934 return Op1C;
935 if (Op1C->isExactlyValue(2.0)) // pow(2.0, x) -> exp2(x)
Dan Gohman76926b62009-09-26 18:10:13 +0000936 return EmitUnaryFloatFnCall(Op2, "exp2", B, Callee->getAttributes());
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000937 }
Eric Christopher37c8b862009-10-07 21:14:25 +0000938
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000939 ConstantFP *Op2C = dyn_cast<ConstantFP>(Op2);
940 if (Op2C == 0) return 0;
Eric Christopher37c8b862009-10-07 21:14:25 +0000941
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000942 if (Op2C->getValueAPF().isZero()) // pow(x, 0.0) -> 1.0
Owen Anderson6f83c9c2009-07-27 20:59:43 +0000943 return ConstantFP::get(CI->getType(), 1.0);
Eric Christopher37c8b862009-10-07 21:14:25 +0000944
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000945 if (Op2C->isExactlyValue(0.5)) {
Dan Gohman79cb8402009-09-25 23:10:17 +0000946 // Expand pow(x, 0.5) to (x == -infinity ? +infinity : fabs(sqrt(x))).
947 // This is faster than calling pow, and still handles negative zero
Nick Lewyckya6b21ea2011-12-27 18:25:50 +0000948 // and negative infinity correctly.
Dan Gohman79cb8402009-09-25 23:10:17 +0000949 // TODO: In fast-math mode, this could be just sqrt(x).
950 // TODO: In finite-only mode, this could be just fabs(sqrt(x)).
Dan Gohmana23643d2009-09-25 23:40:21 +0000951 Value *Inf = ConstantFP::getInfinity(CI->getType());
952 Value *NegInf = ConstantFP::getInfinity(CI->getType(), true);
Dan Gohman76926b62009-09-26 18:10:13 +0000953 Value *Sqrt = EmitUnaryFloatFnCall(Op1, "sqrt", B,
954 Callee->getAttributes());
955 Value *FAbs = EmitUnaryFloatFnCall(Sqrt, "fabs", B,
956 Callee->getAttributes());
Benjamin Kramera9390a42011-09-27 20:39:19 +0000957 Value *FCmp = B.CreateFCmpOEQ(Op1, NegInf);
958 Value *Sel = B.CreateSelect(FCmp, Inf, FAbs);
Dan Gohman79cb8402009-09-25 23:10:17 +0000959 return Sel;
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000960 }
Eric Christopher37c8b862009-10-07 21:14:25 +0000961
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000962 if (Op2C->isExactlyValue(1.0)) // pow(x, 1.0) -> x
963 return Op1;
964 if (Op2C->isExactlyValue(2.0)) // pow(x, 2.0) -> x*x
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000965 return B.CreateFMul(Op1, Op1, "pow2");
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000966 if (Op2C->isExactlyValue(-1.0)) // pow(x, -1.0) -> 1.0/x
Owen Anderson6f83c9c2009-07-27 20:59:43 +0000967 return B.CreateFDiv(ConstantFP::get(CI->getType(), 1.0),
Owen Andersonfa5cbd62009-07-03 19:42:02 +0000968 Op1, "powrecip");
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000969 return 0;
970 }
971};
972
973//===---------------------------------------===//
Chris Lattnere818f772008-05-02 18:43:35 +0000974// 'exp2' Optimizations
975
Chris Lattner3e8b6632009-09-02 06:11:42 +0000976struct Exp2Opt : public LibCallOptimization {
Eric Christopher7a61d702008-08-08 19:39:37 +0000977 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000978 FunctionType *FT = Callee->getFunctionType();
Chris Lattnere818f772008-05-02 18:43:35 +0000979 // Just make sure this has 1 argument of FP type, which matches the
980 // result type.
981 if (FT->getNumParams() != 1 || FT->getReturnType() != FT->getParamType(0) ||
Duncan Sandsb0bc6c32010-02-15 16:12:20 +0000982 !FT->getParamType(0)->isFloatingPointTy())
Chris Lattnere818f772008-05-02 18:43:35 +0000983 return 0;
Eric Christopher37c8b862009-10-07 21:14:25 +0000984
Gabor Greifaee5dc12010-06-24 10:42:46 +0000985 Value *Op = CI->getArgOperand(0);
Chris Lattnere818f772008-05-02 18:43:35 +0000986 // Turn exp2(sitofp(x)) -> ldexp(1.0, sext(x)) if sizeof(x) <= 32
987 // Turn exp2(uitofp(x)) -> ldexp(1.0, zext(x)) if sizeof(x) < 32
988 Value *LdExpArg = 0;
989 if (SIToFPInst *OpC = dyn_cast<SIToFPInst>(Op)) {
990 if (OpC->getOperand(0)->getType()->getPrimitiveSizeInBits() <= 32)
Benjamin Kramera9390a42011-09-27 20:39:19 +0000991 LdExpArg = B.CreateSExt(OpC->getOperand(0), B.getInt32Ty());
Chris Lattnere818f772008-05-02 18:43:35 +0000992 } else if (UIToFPInst *OpC = dyn_cast<UIToFPInst>(Op)) {
993 if (OpC->getOperand(0)->getType()->getPrimitiveSizeInBits() < 32)
Benjamin Kramera9390a42011-09-27 20:39:19 +0000994 LdExpArg = B.CreateZExt(OpC->getOperand(0), B.getInt32Ty());
Chris Lattnere818f772008-05-02 18:43:35 +0000995 }
Anton Korobeynikov9547cdf2009-06-18 20:05:31 +0000996
Chris Lattnere818f772008-05-02 18:43:35 +0000997 if (LdExpArg) {
998 const char *Name;
Chris Lattnercf0fe8d2009-10-05 05:54:46 +0000999 if (Op->getType()->isFloatTy())
Chris Lattnere818f772008-05-02 18:43:35 +00001000 Name = "ldexpf";
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001001 else if (Op->getType()->isDoubleTy())
Chris Lattnere818f772008-05-02 18:43:35 +00001002 Name = "ldexp";
1003 else
1004 Name = "ldexpl";
1005
Owen Anderson6f83c9c2009-07-27 20:59:43 +00001006 Constant *One = ConstantFP::get(*Context, APFloat(1.0f));
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001007 if (!Op->getType()->isFloatTy())
Owen Andersonbaf3c402009-07-29 18:55:55 +00001008 One = ConstantExpr::getFPExtend(One, Op->getType());
Chris Lattnere818f772008-05-02 18:43:35 +00001009
1010 Module *M = Caller->getParent();
1011 Value *Callee = M->getOrInsertFunction(Name, Op->getType(),
Eric Christopher37c8b862009-10-07 21:14:25 +00001012 Op->getType(),
Benjamin Kramera1bf4ca2010-12-27 00:16:46 +00001013 B.getInt32Ty(), NULL);
Anton Korobeynikov9547cdf2009-06-18 20:05:31 +00001014 CallInst *CI = B.CreateCall2(Callee, One, LdExpArg);
1015 if (const Function *F = dyn_cast<Function>(Callee->stripPointerCasts()))
1016 CI->setCallingConv(F->getCallingConv());
1017
1018 return CI;
Chris Lattnere818f772008-05-02 18:43:35 +00001019 }
1020 return 0;
1021 }
1022};
Chris Lattnere818f772008-05-02 18:43:35 +00001023
1024//===---------------------------------------===//
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001025// Double -> Float Shrinking Optimizations for Unary Functions like 'floor'
1026
Chris Lattner3e8b6632009-09-02 06:11:42 +00001027struct UnaryDoubleFPOpt : public LibCallOptimization {
Eric Christopher7a61d702008-08-08 19:39:37 +00001028 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001029 FunctionType *FT = Callee->getFunctionType();
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001030 if (FT->getNumParams() != 1 || !FT->getReturnType()->isDoubleTy() ||
1031 !FT->getParamType(0)->isDoubleTy())
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001032 return 0;
Anton Korobeynikov9547cdf2009-06-18 20:05:31 +00001033
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001034 // If this is something like 'floor((double)floatval)', convert to floorf.
Gabor Greifaee5dc12010-06-24 10:42:46 +00001035 FPExtInst *Cast = dyn_cast<FPExtInst>(CI->getArgOperand(0));
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001036 if (Cast == 0 || !Cast->getOperand(0)->getType()->isFloatTy())
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001037 return 0;
1038
1039 // floor((double)floatval) -> (double)floorf(floatval)
1040 Value *V = Cast->getOperand(0);
Benjamin Kramerb5ccb252011-11-15 19:12:09 +00001041 V = EmitUnaryFloatFnCall(V, Callee->getName(), B, Callee->getAttributes());
Benjamin Kramera1bf4ca2010-12-27 00:16:46 +00001042 return B.CreateFPExt(V, B.getDoubleTy());
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001043 }
1044};
1045
1046//===----------------------------------------------------------------------===//
1047// Integer Optimizations
1048//===----------------------------------------------------------------------===//
1049
1050//===---------------------------------------===//
1051// 'ffs*' Optimizations
1052
Chris Lattner3e8b6632009-09-02 06:11:42 +00001053struct FFSOpt : public LibCallOptimization {
Eric Christopher7a61d702008-08-08 19:39:37 +00001054 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001055 FunctionType *FT = Callee->getFunctionType();
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001056 // Just make sure this has 2 arguments of the same FP type, which match the
1057 // result type.
Eric Christopher37c8b862009-10-07 21:14:25 +00001058 if (FT->getNumParams() != 1 ||
Nick Lewycky10d2f4d2010-07-06 03:53:43 +00001059 !FT->getReturnType()->isIntegerTy(32) ||
Duncan Sands1df98592010-02-16 11:11:14 +00001060 !FT->getParamType(0)->isIntegerTy())
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001061 return 0;
Eric Christopher37c8b862009-10-07 21:14:25 +00001062
Gabor Greifaee5dc12010-06-24 10:42:46 +00001063 Value *Op = CI->getArgOperand(0);
Eric Christopher37c8b862009-10-07 21:14:25 +00001064
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001065 // Constant fold.
1066 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op)) {
1067 if (CI->getValue() == 0) // ffs(0) -> 0.
Owen Andersona7235ea2009-07-31 20:28:14 +00001068 return Constant::getNullValue(CI->getType());
Benjamin Kramera1bf4ca2010-12-27 00:16:46 +00001069 // ffs(c) -> cttz(c)+1
1070 return B.getInt32(CI->getValue().countTrailingZeros() + 1);
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001071 }
Eric Christopher37c8b862009-10-07 21:14:25 +00001072
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001073 // ffs(x) -> x != 0 ? (i32)llvm.cttz(x)+1 : 0
Jay Foad5fdd6c82011-07-12 14:06:48 +00001074 Type *ArgType = Op->getType();
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001075 Value *F = Intrinsic::getDeclaration(Callee->getParent(),
Benjamin Kramereb9a85f2011-07-14 17:45:39 +00001076 Intrinsic::cttz, ArgType);
Chandler Carruthccbf1e32011-12-12 04:26:04 +00001077 Value *V = B.CreateCall2(F, Op, B.getFalse(), "cttz");
Benjamin Kramera9390a42011-09-27 20:39:19 +00001078 V = B.CreateAdd(V, ConstantInt::get(V->getType(), 1));
1079 V = B.CreateIntCast(V, B.getInt32Ty(), false);
Eric Christopher37c8b862009-10-07 21:14:25 +00001080
Benjamin Kramera9390a42011-09-27 20:39:19 +00001081 Value *Cond = B.CreateICmpNE(Op, Constant::getNullValue(ArgType));
Benjamin Kramera1bf4ca2010-12-27 00:16:46 +00001082 return B.CreateSelect(Cond, V, B.getInt32(0));
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001083 }
1084};
1085
1086//===---------------------------------------===//
1087// 'isdigit' Optimizations
1088
Chris Lattner3e8b6632009-09-02 06:11:42 +00001089struct IsDigitOpt : public LibCallOptimization {
Eric Christopher7a61d702008-08-08 19:39:37 +00001090 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001091 FunctionType *FT = Callee->getFunctionType();
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001092 // We require integer(i32)
Duncan Sands1df98592010-02-16 11:11:14 +00001093 if (FT->getNumParams() != 1 || !FT->getReturnType()->isIntegerTy() ||
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00001094 !FT->getParamType(0)->isIntegerTy(32))
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001095 return 0;
Eric Christopher37c8b862009-10-07 21:14:25 +00001096
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001097 // isdigit(c) -> (c-'0') <u 10
Gabor Greifaee5dc12010-06-24 10:42:46 +00001098 Value *Op = CI->getArgOperand(0);
Benjamin Kramera1bf4ca2010-12-27 00:16:46 +00001099 Op = B.CreateSub(Op, B.getInt32('0'), "isdigittmp");
1100 Op = B.CreateICmpULT(Op, B.getInt32(10), "isdigit");
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001101 return B.CreateZExt(Op, CI->getType());
1102 }
1103};
1104
1105//===---------------------------------------===//
1106// 'isascii' Optimizations
1107
Chris Lattner3e8b6632009-09-02 06:11:42 +00001108struct IsAsciiOpt : public LibCallOptimization {
Eric Christopher7a61d702008-08-08 19:39:37 +00001109 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001110 FunctionType *FT = Callee->getFunctionType();
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001111 // We require integer(i32)
Duncan Sands1df98592010-02-16 11:11:14 +00001112 if (FT->getNumParams() != 1 || !FT->getReturnType()->isIntegerTy() ||
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00001113 !FT->getParamType(0)->isIntegerTy(32))
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001114 return 0;
Eric Christopher37c8b862009-10-07 21:14:25 +00001115
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001116 // isascii(c) -> c <u 128
Gabor Greifaee5dc12010-06-24 10:42:46 +00001117 Value *Op = CI->getArgOperand(0);
Benjamin Kramera1bf4ca2010-12-27 00:16:46 +00001118 Op = B.CreateICmpULT(Op, B.getInt32(128), "isascii");
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001119 return B.CreateZExt(Op, CI->getType());
1120 }
1121};
Eric Christopher37c8b862009-10-07 21:14:25 +00001122
Chris Lattner313f0e62008-06-09 08:26:51 +00001123//===---------------------------------------===//
1124// 'abs', 'labs', 'llabs' Optimizations
1125
Chris Lattner3e8b6632009-09-02 06:11:42 +00001126struct AbsOpt : public LibCallOptimization {
Eric Christopher7a61d702008-08-08 19:39:37 +00001127 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001128 FunctionType *FT = Callee->getFunctionType();
Chris Lattner313f0e62008-06-09 08:26:51 +00001129 // We require integer(integer) where the types agree.
Duncan Sands1df98592010-02-16 11:11:14 +00001130 if (FT->getNumParams() != 1 || !FT->getReturnType()->isIntegerTy() ||
Chris Lattner313f0e62008-06-09 08:26:51 +00001131 FT->getParamType(0) != FT->getReturnType())
1132 return 0;
Eric Christopher37c8b862009-10-07 21:14:25 +00001133
Chris Lattner313f0e62008-06-09 08:26:51 +00001134 // abs(x) -> x >s -1 ? x : -x
Gabor Greifaee5dc12010-06-24 10:42:46 +00001135 Value *Op = CI->getArgOperand(0);
Benjamin Kramera1bf4ca2010-12-27 00:16:46 +00001136 Value *Pos = B.CreateICmpSGT(Op, Constant::getAllOnesValue(Op->getType()),
Chris Lattner313f0e62008-06-09 08:26:51 +00001137 "ispos");
1138 Value *Neg = B.CreateNeg(Op, "neg");
1139 return B.CreateSelect(Pos, Op, Neg);
1140 }
1141};
Eric Christopher37c8b862009-10-07 21:14:25 +00001142
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001143
1144//===---------------------------------------===//
1145// 'toascii' Optimizations
1146
Chris Lattner3e8b6632009-09-02 06:11:42 +00001147struct ToAsciiOpt : public LibCallOptimization {
Eric Christopher7a61d702008-08-08 19:39:37 +00001148 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001149 FunctionType *FT = Callee->getFunctionType();
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001150 // We require i32(i32)
1151 if (FT->getNumParams() != 1 || FT->getReturnType() != FT->getParamType(0) ||
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00001152 !FT->getParamType(0)->isIntegerTy(32))
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001153 return 0;
Eric Christopher37c8b862009-10-07 21:14:25 +00001154
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001155 // isascii(c) -> c & 0x7f
Gabor Greifaee5dc12010-06-24 10:42:46 +00001156 return B.CreateAnd(CI->getArgOperand(0),
Owen Andersoneed707b2009-07-24 23:12:02 +00001157 ConstantInt::get(CI->getType(),0x7F));
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001158 }
1159};
1160
1161//===----------------------------------------------------------------------===//
1162// Formatting and IO Optimizations
1163//===----------------------------------------------------------------------===//
1164
1165//===---------------------------------------===//
1166// 'printf' Optimizations
1167
Chris Lattner3e8b6632009-09-02 06:11:42 +00001168struct PrintFOpt : public LibCallOptimization {
Richard Osborne36498242011-03-03 13:17:51 +00001169 Value *OptimizeFixedFormatString(Function *Callee, CallInst *CI,
1170 IRBuilder<> &B) {
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001171 // Check for a fixed format string.
Chris Lattner18c7f802012-02-05 02:29:43 +00001172 StringRef FormatStr;
1173 if (!getConstantStringInfo(CI->getArgOperand(0), FormatStr))
Bill Wendling0582ae92009-03-13 04:39:26 +00001174 return 0;
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001175
1176 // Empty format string -> noop.
1177 if (FormatStr.empty()) // Tolerate printf's declared void.
Eric Christopher37c8b862009-10-07 21:14:25 +00001178 return CI->use_empty() ? (Value*)CI :
Owen Andersoneed707b2009-07-24 23:12:02 +00001179 ConstantInt::get(CI->getType(), 0);
Eric Christopher37c8b862009-10-07 21:14:25 +00001180
Daniel Dunbard02be242011-02-12 18:19:57 +00001181 // Do not do any of the following transformations if the printf return value
1182 // is used, in general the printf return value is not compatible with either
1183 // putchar() or puts().
1184 if (!CI->use_empty())
1185 return 0;
1186
1187 // printf("x") -> putchar('x'), even for '%'.
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001188 if (FormatStr.size() == 1) {
Nuno Lopes51004df2012-07-25 16:46:31 +00001189 Value *Res = EmitPutChar(B.getInt32(FormatStr[0]), B, TD, TLI);
Chris Lattner74965f22009-11-09 04:57:04 +00001190 if (CI->use_empty()) return CI;
1191 return B.CreateIntCast(Res, CI->getType(), true);
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001192 }
Eric Christopher37c8b862009-10-07 21:14:25 +00001193
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001194 // printf("foo\n") --> puts("foo")
1195 if (FormatStr[FormatStr.size()-1] == '\n' &&
1196 FormatStr.find('%') == std::string::npos) { // no format characters.
1197 // Create a string literal with no \n on it. We expect the constant merge
1198 // pass to be run after this pass, to merge duplicate strings.
Chris Lattner18c7f802012-02-05 02:29:43 +00001199 FormatStr = FormatStr.drop_back();
Benjamin Kramer59e43bd2011-10-29 19:43:31 +00001200 Value *GV = B.CreateGlobalString(FormatStr, "str");
Nuno Lopes51004df2012-07-25 16:46:31 +00001201 Value *NewCI = EmitPutS(GV, B, TD, TLI);
1202 return (CI->use_empty() || !NewCI) ?
1203 NewCI :
1204 ConstantInt::get(CI->getType(), FormatStr.size()+1);
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001205 }
Eric Christopher37c8b862009-10-07 21:14:25 +00001206
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001207 // Optimize specific format strings.
Gabor Greifaee5dc12010-06-24 10:42:46 +00001208 // printf("%c", chr) --> putchar(chr)
Gabor Greif8e1ebff2010-06-30 12:42:43 +00001209 if (FormatStr == "%c" && CI->getNumArgOperands() > 1 &&
Gabor Greifaee5dc12010-06-24 10:42:46 +00001210 CI->getArgOperand(1)->getType()->isIntegerTy()) {
Nuno Lopes51004df2012-07-25 16:46:31 +00001211 Value *Res = EmitPutChar(CI->getArgOperand(1), B, TD, TLI);
Eric Christopher80bf1d52009-11-21 01:01:30 +00001212
Chris Lattner74965f22009-11-09 04:57:04 +00001213 if (CI->use_empty()) return CI;
1214 return B.CreateIntCast(Res, CI->getType(), true);
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001215 }
Eric Christopher37c8b862009-10-07 21:14:25 +00001216
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001217 // printf("%s\n", str) --> puts(str)
Gabor Greif8e1ebff2010-06-30 12:42:43 +00001218 if (FormatStr == "%s\n" && CI->getNumArgOperands() > 1 &&
Daniel Dunbard02be242011-02-12 18:19:57 +00001219 CI->getArgOperand(1)->getType()->isPointerTy()) {
Nuno Lopes51004df2012-07-25 16:46:31 +00001220 return EmitPutS(CI->getArgOperand(1), B, TD, TLI);
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001221 }
1222 return 0;
1223 }
Richard Osborne36498242011-03-03 13:17:51 +00001224
1225 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
1226 // Require one fixed pointer argument and an integer/void result.
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001227 FunctionType *FT = Callee->getFunctionType();
Richard Osborne36498242011-03-03 13:17:51 +00001228 if (FT->getNumParams() < 1 || !FT->getParamType(0)->isPointerTy() ||
1229 !(FT->getReturnType()->isIntegerTy() ||
1230 FT->getReturnType()->isVoidTy()))
1231 return 0;
1232
1233 if (Value *V = OptimizeFixedFormatString(Callee, CI, B)) {
1234 return V;
1235 }
1236
1237 // printf(format, ...) -> iprintf(format, ...) if no floating point
1238 // arguments.
1239 if (TLI->has(LibFunc::iprintf) && !CallHasFloatingPointArgument(CI)) {
1240 Module *M = B.GetInsertBlock()->getParent()->getParent();
1241 Constant *IPrintFFn =
1242 M->getOrInsertFunction("iprintf", FT, Callee->getAttributes());
1243 CallInst *New = cast<CallInst>(CI->clone());
1244 New->setCalledFunction(IPrintFFn);
1245 B.Insert(New);
1246 return New;
1247 }
1248 return 0;
1249 }
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001250};
1251
1252//===---------------------------------------===//
1253// 'sprintf' Optimizations
1254
Chris Lattner3e8b6632009-09-02 06:11:42 +00001255struct SPrintFOpt : public LibCallOptimization {
Richard Osborne419454a2011-03-03 14:09:28 +00001256 Value *OptimizeFixedFormatString(Function *Callee, CallInst *CI,
1257 IRBuilder<> &B) {
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001258 // Check for a fixed format string.
Chris Lattner18c7f802012-02-05 02:29:43 +00001259 StringRef FormatStr;
1260 if (!getConstantStringInfo(CI->getArgOperand(1), FormatStr))
Bill Wendling0582ae92009-03-13 04:39:26 +00001261 return 0;
Eric Christopher37c8b862009-10-07 21:14:25 +00001262
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001263 // If we just have a format string (nothing else crazy) transform it.
Gabor Greif8e1ebff2010-06-30 12:42:43 +00001264 if (CI->getNumArgOperands() == 2) {
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001265 // Make sure there's no % in the constant array. We could try to handle
1266 // %% -> % in the future if we cared.
1267 for (unsigned i = 0, e = FormatStr.size(); i != e; ++i)
1268 if (FormatStr[i] == '%')
1269 return 0; // we found a format specifier, bail out.
Dan Gohmanf14d9192009-08-18 00:48:13 +00001270
1271 // These optimizations require TargetData.
1272 if (!TD) return 0;
1273
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001274 // sprintf(str, fmt) -> llvm.memcpy(str, fmt, strlen(fmt)+1, 1)
Benjamin Kramera1bf4ca2010-12-27 00:16:46 +00001275 B.CreateMemCpy(CI->getArgOperand(0), CI->getArgOperand(1),
1276 ConstantInt::get(TD->getIntPtrType(*Context), // Copy the
1277 FormatStr.size() + 1), 1); // nul byte.
Owen Andersoneed707b2009-07-24 23:12:02 +00001278 return ConstantInt::get(CI->getType(), FormatStr.size());
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001279 }
Eric Christopher37c8b862009-10-07 21:14:25 +00001280
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001281 // The remaining optimizations require the format string to be "%s" or "%c"
1282 // and have an extra operand.
Gabor Greif8e1ebff2010-06-30 12:42:43 +00001283 if (FormatStr.size() != 2 || FormatStr[0] != '%' ||
1284 CI->getNumArgOperands() < 3)
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001285 return 0;
Eric Christopher37c8b862009-10-07 21:14:25 +00001286
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001287 // Decode the second character of the format string.
1288 if (FormatStr[1] == 'c') {
Chris Lattner56b4f2b2008-05-01 06:39:12 +00001289 // sprintf(dst, "%c", chr) --> *(i8*)dst = chr; *((i8*)dst+1) = 0
Gabor Greifaee5dc12010-06-24 10:42:46 +00001290 if (!CI->getArgOperand(2)->getType()->isIntegerTy()) return 0;
Benjamin Kramera1bf4ca2010-12-27 00:16:46 +00001291 Value *V = B.CreateTrunc(CI->getArgOperand(2), B.getInt8Ty(), "char");
Gabor Greifaee5dc12010-06-24 10:42:46 +00001292 Value *Ptr = CastToCStr(CI->getArgOperand(0), B);
Chris Lattner56b4f2b2008-05-01 06:39:12 +00001293 B.CreateStore(V, Ptr);
Benjamin Kramera1bf4ca2010-12-27 00:16:46 +00001294 Ptr = B.CreateGEP(Ptr, B.getInt32(1), "nul");
1295 B.CreateStore(B.getInt8(0), Ptr);
Eric Christopher37c8b862009-10-07 21:14:25 +00001296
Owen Andersoneed707b2009-07-24 23:12:02 +00001297 return ConstantInt::get(CI->getType(), 1);
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001298 }
Eric Christopher37c8b862009-10-07 21:14:25 +00001299
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001300 if (FormatStr[1] == 's') {
Dan Gohmanf14d9192009-08-18 00:48:13 +00001301 // These optimizations require TargetData.
1302 if (!TD) return 0;
1303
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001304 // sprintf(dest, "%s", str) -> llvm.memcpy(dest, str, strlen(str)+1, 1)
Gabor Greifaee5dc12010-06-24 10:42:46 +00001305 if (!CI->getArgOperand(2)->getType()->isPointerTy()) return 0;
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001306
Nuno Lopes51004df2012-07-25 16:46:31 +00001307 Value *Len = EmitStrLen(CI->getArgOperand(2), B, TD, TLI);
1308 if (!Len)
1309 return 0;
Owen Andersonfa5cbd62009-07-03 19:42:02 +00001310 Value *IncLen = B.CreateAdd(Len,
Owen Andersoneed707b2009-07-24 23:12:02 +00001311 ConstantInt::get(Len->getType(), 1),
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001312 "leninc");
Benjamin Kramera1bf4ca2010-12-27 00:16:46 +00001313 B.CreateMemCpy(CI->getArgOperand(0), CI->getArgOperand(2), IncLen, 1);
Eric Christopher37c8b862009-10-07 21:14:25 +00001314
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001315 // The sprintf result is the unincremented number of bytes in the string.
1316 return B.CreateIntCast(Len, CI->getType(), false);
1317 }
1318 return 0;
1319 }
Richard Osborne419454a2011-03-03 14:09:28 +00001320
1321 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
1322 // Require two fixed pointer arguments and an integer result.
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001323 FunctionType *FT = Callee->getFunctionType();
Richard Osborne419454a2011-03-03 14:09:28 +00001324 if (FT->getNumParams() != 2 || !FT->getParamType(0)->isPointerTy() ||
1325 !FT->getParamType(1)->isPointerTy() ||
1326 !FT->getReturnType()->isIntegerTy())
1327 return 0;
1328
1329 if (Value *V = OptimizeFixedFormatString(Callee, CI, B)) {
1330 return V;
1331 }
1332
Richard Osborneea2578c2011-03-03 14:21:22 +00001333 // sprintf(str, format, ...) -> siprintf(str, format, ...) if no floating
Richard Osborne419454a2011-03-03 14:09:28 +00001334 // point arguments.
1335 if (TLI->has(LibFunc::siprintf) && !CallHasFloatingPointArgument(CI)) {
1336 Module *M = B.GetInsertBlock()->getParent()->getParent();
1337 Constant *SIPrintFFn =
1338 M->getOrInsertFunction("siprintf", FT, Callee->getAttributes());
1339 CallInst *New = cast<CallInst>(CI->clone());
1340 New->setCalledFunction(SIPrintFFn);
1341 B.Insert(New);
1342 return New;
1343 }
1344 return 0;
1345 }
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001346};
1347
1348//===---------------------------------------===//
1349// 'fwrite' Optimizations
1350
Chris Lattner3e8b6632009-09-02 06:11:42 +00001351struct FWriteOpt : public LibCallOptimization {
Eric Christopher7a61d702008-08-08 19:39:37 +00001352 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001353 // Require a pointer, an integer, an integer, a pointer, returning integer.
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001354 FunctionType *FT = Callee->getFunctionType();
Duncan Sands1df98592010-02-16 11:11:14 +00001355 if (FT->getNumParams() != 4 || !FT->getParamType(0)->isPointerTy() ||
1356 !FT->getParamType(1)->isIntegerTy() ||
1357 !FT->getParamType(2)->isIntegerTy() ||
1358 !FT->getParamType(3)->isPointerTy() ||
1359 !FT->getReturnType()->isIntegerTy())
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001360 return 0;
Eric Christopher37c8b862009-10-07 21:14:25 +00001361
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001362 // Get the element size and count.
Gabor Greifaee5dc12010-06-24 10:42:46 +00001363 ConstantInt *SizeC = dyn_cast<ConstantInt>(CI->getArgOperand(1));
1364 ConstantInt *CountC = dyn_cast<ConstantInt>(CI->getArgOperand(2));
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001365 if (!SizeC || !CountC) return 0;
1366 uint64_t Bytes = SizeC->getZExtValue()*CountC->getZExtValue();
Eric Christopher37c8b862009-10-07 21:14:25 +00001367
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001368 // If this is writing zero records, remove the call (it's a noop).
1369 if (Bytes == 0)
Owen Andersoneed707b2009-07-24 23:12:02 +00001370 return ConstantInt::get(CI->getType(), 0);
Eric Christopher37c8b862009-10-07 21:14:25 +00001371
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001372 // If this is writing one byte, turn it into fputc.
Joerg Sonnenberger127a6692011-12-12 20:18:31 +00001373 // This optimisation is only valid, if the return value is unused.
1374 if (Bytes == 1 && CI->use_empty()) { // fwrite(S,1,1,F) -> fputc(S[0],F)
Gabor Greifaee5dc12010-06-24 10:42:46 +00001375 Value *Char = B.CreateLoad(CastToCStr(CI->getArgOperand(0), B), "char");
Nuno Lopes51004df2012-07-25 16:46:31 +00001376 Value *NewCI = EmitFPutC(Char, CI->getArgOperand(3), B, TD, TLI);
1377 return NewCI ? ConstantInt::get(CI->getType(), 1) : 0;
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001378 }
1379
1380 return 0;
1381 }
1382};
1383
1384//===---------------------------------------===//
1385// 'fputs' Optimizations
1386
Chris Lattner3e8b6632009-09-02 06:11:42 +00001387struct FPutsOpt : public LibCallOptimization {
Eric Christopher7a61d702008-08-08 19:39:37 +00001388 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
Dan Gohmanf14d9192009-08-18 00:48:13 +00001389 // These optimizations require TargetData.
1390 if (!TD) return 0;
1391
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001392 // Require two pointers. Also, we can't optimize if return value is used.
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001393 FunctionType *FT = Callee->getFunctionType();
Duncan Sands1df98592010-02-16 11:11:14 +00001394 if (FT->getNumParams() != 2 || !FT->getParamType(0)->isPointerTy() ||
1395 !FT->getParamType(1)->isPointerTy() ||
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001396 !CI->use_empty())
1397 return 0;
Eric Christopher37c8b862009-10-07 21:14:25 +00001398
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001399 // fputs(s,F) --> fwrite(s,1,strlen(s),F)
Gabor Greifaee5dc12010-06-24 10:42:46 +00001400 uint64_t Len = GetStringLength(CI->getArgOperand(0));
Chris Lattner56b4f2b2008-05-01 06:39:12 +00001401 if (!Len) return 0;
Nuno Lopes51004df2012-07-25 16:46:31 +00001402 // Known to have no uses (see above).
1403 return EmitFWrite(CI->getArgOperand(0),
1404 ConstantInt::get(TD->getIntPtrType(*Context), Len-1),
1405 CI->getArgOperand(1), B, TD, TLI);
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001406 }
1407};
1408
1409//===---------------------------------------===//
1410// 'fprintf' Optimizations
1411
Chris Lattner3e8b6632009-09-02 06:11:42 +00001412struct FPrintFOpt : public LibCallOptimization {
Richard Osborne022708f2011-03-03 14:20:22 +00001413 Value *OptimizeFixedFormatString(Function *Callee, CallInst *CI,
1414 IRBuilder<> &B) {
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001415 // All the optimizations depend on the format string.
Chris Lattner18c7f802012-02-05 02:29:43 +00001416 StringRef FormatStr;
1417 if (!getConstantStringInfo(CI->getArgOperand(1), FormatStr))
Bill Wendling0582ae92009-03-13 04:39:26 +00001418 return 0;
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001419
1420 // fprintf(F, "foo") --> fwrite("foo", 3, 1, F)
Gabor Greif8e1ebff2010-06-30 12:42:43 +00001421 if (CI->getNumArgOperands() == 2) {
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001422 for (unsigned i = 0, e = FormatStr.size(); i != e; ++i)
1423 if (FormatStr[i] == '%') // Could handle %% -> % if we cared.
Chris Lattner56b4f2b2008-05-01 06:39:12 +00001424 return 0; // We found a format specifier.
Dan Gohmanf14d9192009-08-18 00:48:13 +00001425
1426 // These optimizations require TargetData.
1427 if (!TD) return 0;
1428
Nuno Lopes51004df2012-07-25 16:46:31 +00001429 Value *NewCI = EmitFWrite(CI->getArgOperand(1),
1430 ConstantInt::get(TD->getIntPtrType(*Context),
1431 FormatStr.size()),
1432 CI->getArgOperand(0), B, TD, TLI);
1433 return NewCI ? ConstantInt::get(CI->getType(), FormatStr.size()) : 0;
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001434 }
Eric Christopher37c8b862009-10-07 21:14:25 +00001435
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001436 // The remaining optimizations require the format string to be "%s" or "%c"
1437 // and have an extra operand.
Gabor Greif8e1ebff2010-06-30 12:42:43 +00001438 if (FormatStr.size() != 2 || FormatStr[0] != '%' ||
1439 CI->getNumArgOperands() < 3)
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001440 return 0;
Eric Christopher37c8b862009-10-07 21:14:25 +00001441
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001442 // Decode the second character of the format string.
1443 if (FormatStr[1] == 'c') {
Gabor Greifaee5dc12010-06-24 10:42:46 +00001444 // fprintf(F, "%c", chr) --> fputc(chr, F)
1445 if (!CI->getArgOperand(2)->getType()->isIntegerTy()) return 0;
Nuno Lopes51004df2012-07-25 16:46:31 +00001446 Value *NewCI = EmitFPutC(CI->getArgOperand(2), CI->getArgOperand(0), B,
1447 TD, TLI);
1448 return NewCI ? ConstantInt::get(CI->getType(), 1) : 0;
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001449 }
Eric Christopher37c8b862009-10-07 21:14:25 +00001450
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001451 if (FormatStr[1] == 's') {
Gabor Greifaee5dc12010-06-24 10:42:46 +00001452 // fprintf(F, "%s", str) --> fputs(str, F)
1453 if (!CI->getArgOperand(2)->getType()->isPointerTy() || !CI->use_empty())
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001454 return 0;
Nuno Lopes51004df2012-07-25 16:46:31 +00001455 return EmitFPutS(CI->getArgOperand(2), CI->getArgOperand(0), B, TD, TLI);
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001456 }
1457 return 0;
1458 }
Richard Osborne022708f2011-03-03 14:20:22 +00001459
1460 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
1461 // Require two fixed paramters as pointers and integer result.
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001462 FunctionType *FT = Callee->getFunctionType();
Richard Osborne022708f2011-03-03 14:20:22 +00001463 if (FT->getNumParams() != 2 || !FT->getParamType(0)->isPointerTy() ||
1464 !FT->getParamType(1)->isPointerTy() ||
1465 !FT->getReturnType()->isIntegerTy())
1466 return 0;
1467
1468 if (Value *V = OptimizeFixedFormatString(Callee, CI, B)) {
1469 return V;
1470 }
1471
1472 // fprintf(stream, format, ...) -> fiprintf(stream, format, ...) if no
1473 // floating point arguments.
1474 if (TLI->has(LibFunc::fiprintf) && !CallHasFloatingPointArgument(CI)) {
1475 Module *M = B.GetInsertBlock()->getParent()->getParent();
1476 Constant *FIPrintFFn =
1477 M->getOrInsertFunction("fiprintf", FT, Callee->getAttributes());
1478 CallInst *New = cast<CallInst>(CI->clone());
1479 New->setCalledFunction(FIPrintFFn);
1480 B.Insert(New);
1481 return New;
1482 }
1483 return 0;
1484 }
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001485};
1486
Anders Carlsson303023d2010-11-30 06:19:18 +00001487//===---------------------------------------===//
1488// 'puts' Optimizations
1489
1490struct PutsOpt : public LibCallOptimization {
1491 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
1492 // Require one fixed pointer argument and an integer/void result.
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001493 FunctionType *FT = Callee->getFunctionType();
Anders Carlsson303023d2010-11-30 06:19:18 +00001494 if (FT->getNumParams() < 1 || !FT->getParamType(0)->isPointerTy() ||
1495 !(FT->getReturnType()->isIntegerTy() ||
1496 FT->getReturnType()->isVoidTy()))
1497 return 0;
1498
1499 // Check for a constant string.
Chris Lattner18c7f802012-02-05 02:29:43 +00001500 StringRef Str;
1501 if (!getConstantStringInfo(CI->getArgOperand(0), Str))
Anders Carlsson303023d2010-11-30 06:19:18 +00001502 return 0;
1503
Daniel Dunbard02be242011-02-12 18:19:57 +00001504 if (Str.empty() && CI->use_empty()) {
Anders Carlsson303023d2010-11-30 06:19:18 +00001505 // puts("") -> putchar('\n')
Nuno Lopes51004df2012-07-25 16:46:31 +00001506 Value *Res = EmitPutChar(B.getInt32('\n'), B, TD, TLI);
1507 if (!Res) return 0;
Anders Carlsson303023d2010-11-30 06:19:18 +00001508 if (CI->use_empty()) return CI;
1509 return B.CreateIntCast(Res, CI->getType(), true);
1510 }
1511
1512 return 0;
1513 }
1514};
1515
Bill Wendlingac178222008-05-05 21:37:59 +00001516} // end anonymous namespace.
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001517
1518//===----------------------------------------------------------------------===//
1519// SimplifyLibCalls Pass Implementation
1520//===----------------------------------------------------------------------===//
1521
1522namespace {
1523 /// This pass optimizes well known library functions from libc and libm.
1524 ///
Chris Lattner3e8b6632009-09-02 06:11:42 +00001525 class SimplifyLibCalls : public FunctionPass {
Chris Lattnerafbf4832011-02-24 07:16:14 +00001526 TargetLibraryInfo *TLI;
Nadav Rotema94d6e82012-07-24 10:51:42 +00001527
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001528 StringMap<LibCallOptimization*> Optimizations;
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001529 // String and Memory LibCall Optimizations
Benjamin Kramer06f25cf2010-09-29 21:50:51 +00001530 StrCatOpt StrCat; StrNCatOpt StrNCat; StrChrOpt StrChr; StrRChrOpt StrRChr;
David Majnemerac782662012-05-15 11:46:21 +00001531 StrCmpOpt StrCmp; StrNCmpOpt StrNCmp;
1532 StrCpyOpt StrCpy; StrCpyOpt StrCpyChk;
1533 StpCpyOpt StpCpy; StpCpyOpt StpCpyChk;
1534 StrNCpyOpt StrNCpy;
1535 StrLenOpt StrLen; StrPBrkOpt StrPBrk;
Benjamin Kramer9510a252010-09-30 00:58:35 +00001536 StrToOpt StrTo; StrSpnOpt StrSpn; StrCSpnOpt StrCSpn; StrStrOpt StrStr;
Chris Lattner24604112009-12-16 09:32:05 +00001537 MemCmpOpt MemCmp; MemCpyOpt MemCpy; MemMoveOpt MemMove; MemSetOpt MemSet;
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001538 // Math Library Optimizations
Nick Lewyckya6b21ea2011-12-27 18:25:50 +00001539 CosOpt Cos; PowOpt Pow; Exp2Opt Exp2; UnaryDoubleFPOpt UnaryDoubleFP;
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001540 // Integer Optimizations
Chris Lattner313f0e62008-06-09 08:26:51 +00001541 FFSOpt FFS; AbsOpt Abs; IsDigitOpt IsDigit; IsAsciiOpt IsAscii;
1542 ToAsciiOpt ToAscii;
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001543 // Formatting and IO Optimizations
1544 SPrintFOpt SPrintF; PrintFOpt PrintF;
1545 FWriteOpt FWrite; FPutsOpt FPuts; FPrintFOpt FPrintF;
Anders Carlsson303023d2010-11-30 06:19:18 +00001546 PutsOpt Puts;
Nadav Rotema94d6e82012-07-24 10:51:42 +00001547
Nick Lewycky6cd0c042009-01-05 00:07:50 +00001548 bool Modified; // This is only used by doInitialization.
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001549 public:
1550 static char ID; // Pass identification
David Majnemerac782662012-05-15 11:46:21 +00001551 SimplifyLibCalls() : FunctionPass(ID), StrCpy(false), StrCpyChk(true),
1552 StpCpy(false), StpCpyChk(true) {
Owen Anderson081c34b2010-10-19 17:21:58 +00001553 initializeSimplifyLibCallsPass(*PassRegistry::getPassRegistry());
1554 }
Eli Friedman9d434db2011-11-17 01:27:36 +00001555 void AddOpt(LibFunc::Func F, LibCallOptimization* Opt);
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001556 void InitOptimizations();
1557 bool runOnFunction(Function &F);
1558
Nick Lewycky0f8df9a2009-01-04 20:27:34 +00001559 void setDoesNotAccessMemory(Function &F);
1560 void setOnlyReadsMemory(Function &F);
1561 void setDoesNotThrow(Function &F);
1562 void setDoesNotCapture(Function &F, unsigned n);
1563 void setDoesNotAlias(Function &F, unsigned n);
Nick Lewycky6cd0c042009-01-05 00:07:50 +00001564 bool doInitialization(Module &M);
Nick Lewycky0f8df9a2009-01-04 20:27:34 +00001565
Chris Lattnere265ad82011-02-24 07:12:12 +00001566 void inferPrototypeAttributes(Function &F);
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001567 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
Chris Lattnerafbf4832011-02-24 07:16:14 +00001568 AU.addRequired<TargetLibraryInfo>();
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001569 }
1570 };
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001571} // end anonymous namespace.
1572
Chris Lattnerafbf4832011-02-24 07:16:14 +00001573char SimplifyLibCalls::ID = 0;
1574
1575INITIALIZE_PASS_BEGIN(SimplifyLibCalls, "simplify-libcalls",
1576 "Simplify well-known library calls", false, false)
1577INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfo)
1578INITIALIZE_PASS_END(SimplifyLibCalls, "simplify-libcalls",
1579 "Simplify well-known library calls", false, false)
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001580
1581// Public interface to the Simplify LibCalls pass.
1582FunctionPass *llvm::createSimplifyLibCallsPass() {
Eric Christopher37c8b862009-10-07 21:14:25 +00001583 return new SimplifyLibCalls();
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001584}
1585
Eli Friedman9d434db2011-11-17 01:27:36 +00001586void SimplifyLibCalls::AddOpt(LibFunc::Func F, LibCallOptimization* Opt) {
1587 if (TLI->has(F))
1588 Optimizations[TLI->getName(F)] = Opt;
1589}
1590
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001591/// Optimizations - Populate the Optimizations map with all the optimizations
1592/// we know.
1593void SimplifyLibCalls::InitOptimizations() {
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001594 // String and Memory LibCall Optimizations
1595 Optimizations["strcat"] = &StrCat;
Chris Lattnerf5b6bc72009-04-12 05:06:39 +00001596 Optimizations["strncat"] = &StrNCat;
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001597 Optimizations["strchr"] = &StrChr;
Benjamin Kramer06f25cf2010-09-29 21:50:51 +00001598 Optimizations["strrchr"] = &StrRChr;
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001599 Optimizations["strcmp"] = &StrCmp;
1600 Optimizations["strncmp"] = &StrNCmp;
1601 Optimizations["strcpy"] = &StrCpy;
Chris Lattnerf5b6bc72009-04-12 05:06:39 +00001602 Optimizations["strncpy"] = &StrNCpy;
David Majnemerac782662012-05-15 11:46:21 +00001603 Optimizations["stpcpy"] = &StpCpy;
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001604 Optimizations["strlen"] = &StrLen;
Benjamin Kramer05f585e2010-09-29 23:52:12 +00001605 Optimizations["strpbrk"] = &StrPBrk;
Nick Lewycky4c498412009-02-13 15:31:46 +00001606 Optimizations["strtol"] = &StrTo;
1607 Optimizations["strtod"] = &StrTo;
1608 Optimizations["strtof"] = &StrTo;
1609 Optimizations["strtoul"] = &StrTo;
1610 Optimizations["strtoll"] = &StrTo;
1611 Optimizations["strtold"] = &StrTo;
1612 Optimizations["strtoull"] = &StrTo;
Benjamin Kramer9510a252010-09-30 00:58:35 +00001613 Optimizations["strspn"] = &StrSpn;
1614 Optimizations["strcspn"] = &StrCSpn;
Chris Lattner24604112009-12-16 09:32:05 +00001615 Optimizations["strstr"] = &StrStr;
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001616 Optimizations["memcmp"] = &MemCmp;
Eli Friedman9d434db2011-11-17 01:27:36 +00001617 AddOpt(LibFunc::memcpy, &MemCpy);
Eli Friedmand83ae7d2008-11-30 08:32:11 +00001618 Optimizations["memmove"] = &MemMove;
Eli Friedman9d434db2011-11-17 01:27:36 +00001619 AddOpt(LibFunc::memset, &MemSet);
Eric Christopher37c8b862009-10-07 21:14:25 +00001620
Evan Cheng0289b412010-03-23 15:48:04 +00001621 // _chk variants of String and Memory LibCall Optimizations.
Evan Cheng0289b412010-03-23 15:48:04 +00001622 Optimizations["__strcpy_chk"] = &StrCpyChk;
David Majnemerac782662012-05-15 11:46:21 +00001623 Optimizations["__stpcpy_chk"] = &StpCpyChk;
Evan Cheng0289b412010-03-23 15:48:04 +00001624
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001625 // Math Library Optimizations
Nick Lewyckya6b21ea2011-12-27 18:25:50 +00001626 Optimizations["cosf"] = &Cos;
1627 Optimizations["cos"] = &Cos;
1628 Optimizations["cosl"] = &Cos;
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001629 Optimizations["powf"] = &Pow;
1630 Optimizations["pow"] = &Pow;
1631 Optimizations["powl"] = &Pow;
Dale Johannesen53bfbbc2008-09-04 18:30:46 +00001632 Optimizations["llvm.pow.f32"] = &Pow;
1633 Optimizations["llvm.pow.f64"] = &Pow;
1634 Optimizations["llvm.pow.f80"] = &Pow;
1635 Optimizations["llvm.pow.f128"] = &Pow;
1636 Optimizations["llvm.pow.ppcf128"] = &Pow;
Chris Lattnere818f772008-05-02 18:43:35 +00001637 Optimizations["exp2l"] = &Exp2;
1638 Optimizations["exp2"] = &Exp2;
1639 Optimizations["exp2f"] = &Exp2;
Dale Johannesen53bfbbc2008-09-04 18:30:46 +00001640 Optimizations["llvm.exp2.ppcf128"] = &Exp2;
1641 Optimizations["llvm.exp2.f128"] = &Exp2;
1642 Optimizations["llvm.exp2.f80"] = &Exp2;
1643 Optimizations["llvm.exp2.f64"] = &Exp2;
1644 Optimizations["llvm.exp2.f32"] = &Exp2;
Eric Christopher37c8b862009-10-07 21:14:25 +00001645
Joe Groffd5bda5e2012-04-17 23:05:54 +00001646 if (TLI->has(LibFunc::floor) && TLI->has(LibFunc::floorf))
1647 Optimizations["floor"] = &UnaryDoubleFP;
1648 if (TLI->has(LibFunc::ceil) && TLI->has(LibFunc::ceilf))
1649 Optimizations["ceil"] = &UnaryDoubleFP;
1650 if (TLI->has(LibFunc::round) && TLI->has(LibFunc::roundf))
1651 Optimizations["round"] = &UnaryDoubleFP;
1652 if (TLI->has(LibFunc::rint) && TLI->has(LibFunc::rintf))
1653 Optimizations["rint"] = &UnaryDoubleFP;
1654 if (TLI->has(LibFunc::nearbyint) && TLI->has(LibFunc::nearbyintf))
1655 Optimizations["nearbyint"] = &UnaryDoubleFP;
Eric Christopher37c8b862009-10-07 21:14:25 +00001656
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001657 // Integer Optimizations
1658 Optimizations["ffs"] = &FFS;
1659 Optimizations["ffsl"] = &FFS;
1660 Optimizations["ffsll"] = &FFS;
Chris Lattner313f0e62008-06-09 08:26:51 +00001661 Optimizations["abs"] = &Abs;
1662 Optimizations["labs"] = &Abs;
1663 Optimizations["llabs"] = &Abs;
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001664 Optimizations["isdigit"] = &IsDigit;
1665 Optimizations["isascii"] = &IsAscii;
1666 Optimizations["toascii"] = &ToAscii;
Eric Christopher37c8b862009-10-07 21:14:25 +00001667
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001668 // Formatting and IO Optimizations
1669 Optimizations["sprintf"] = &SPrintF;
1670 Optimizations["printf"] = &PrintF;
Eli Friedman9d434db2011-11-17 01:27:36 +00001671 AddOpt(LibFunc::fwrite, &FWrite);
1672 AddOpt(LibFunc::fputs, &FPuts);
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001673 Optimizations["fprintf"] = &FPrintF;
Anders Carlsson303023d2010-11-30 06:19:18 +00001674 Optimizations["puts"] = &Puts;
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001675}
1676
1677
1678/// runOnFunction - Top level algorithm.
1679///
1680bool SimplifyLibCalls::runOnFunction(Function &F) {
Chris Lattnerafbf4832011-02-24 07:16:14 +00001681 TLI = &getAnalysis<TargetLibraryInfo>();
1682
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001683 if (Optimizations.empty())
1684 InitOptimizations();
Eric Christopher37c8b862009-10-07 21:14:25 +00001685
Dan Gohmanf14d9192009-08-18 00:48:13 +00001686 const TargetData *TD = getAnalysisIfAvailable<TargetData>();
Eric Christopher37c8b862009-10-07 21:14:25 +00001687
Owen Andersone922c022009-07-22 00:24:57 +00001688 IRBuilder<> Builder(F.getContext());
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001689
1690 bool Changed = false;
1691 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB) {
1692 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ) {
1693 // Ignore non-calls.
1694 CallInst *CI = dyn_cast<CallInst>(I++);
1695 if (!CI) continue;
Eric Christopher37c8b862009-10-07 21:14:25 +00001696
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001697 // Ignore indirect calls and calls to non-external functions.
1698 Function *Callee = CI->getCalledFunction();
1699 if (Callee == 0 || !Callee->isDeclaration() ||
1700 !(Callee->hasExternalLinkage() || Callee->hasDLLImportLinkage()))
1701 continue;
Eric Christopher37c8b862009-10-07 21:14:25 +00001702
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001703 // Ignore unknown calls.
Daniel Dunbarf0443c12009-07-26 08:34:35 +00001704 LibCallOptimization *LCO = Optimizations.lookup(Callee->getName());
1705 if (!LCO) continue;
Eric Christopher37c8b862009-10-07 21:14:25 +00001706
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001707 // Set the builder to the instruction after the call.
1708 Builder.SetInsertPoint(BB, I);
Eric Christopher37c8b862009-10-07 21:14:25 +00001709
Devang Patela2ab3992011-03-09 21:27:52 +00001710 // Use debug location of CI for all new instructions.
1711 Builder.SetCurrentDebugLocation(CI->getDebugLoc());
1712
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001713 // Try to optimize this call.
Richard Osborne36498242011-03-03 13:17:51 +00001714 Value *Result = LCO->OptimizeCall(CI, TD, TLI, Builder);
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001715 if (Result == 0) continue;
1716
David Greene6a6b90e2010-01-05 01:27:21 +00001717 DEBUG(dbgs() << "SimplifyLibCalls simplified: " << *CI;
1718 dbgs() << " into: " << *Result << "\n");
Eric Christopher37c8b862009-10-07 21:14:25 +00001719
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001720 // Something changed!
1721 Changed = true;
1722 ++NumSimplified;
Eric Christopher37c8b862009-10-07 21:14:25 +00001723
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001724 // Inspect the instruction after the call (which was potentially just
1725 // added) next.
1726 I = CI; ++I;
Eric Christopher37c8b862009-10-07 21:14:25 +00001727
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001728 if (CI != Result && !CI->use_empty()) {
1729 CI->replaceAllUsesWith(Result);
1730 if (!Result->hasName())
1731 Result->takeName(CI);
1732 }
1733 CI->eraseFromParent();
1734 }
1735 }
1736 return Changed;
1737}
1738
Nick Lewycky6cd0c042009-01-05 00:07:50 +00001739// Utility methods for doInitialization.
Nick Lewycky0f8df9a2009-01-04 20:27:34 +00001740
1741void SimplifyLibCalls::setDoesNotAccessMemory(Function &F) {
1742 if (!F.doesNotAccessMemory()) {
1743 F.setDoesNotAccessMemory();
1744 ++NumAnnotated;
1745 Modified = true;
1746 }
1747}
1748void SimplifyLibCalls::setOnlyReadsMemory(Function &F) {
1749 if (!F.onlyReadsMemory()) {
1750 F.setOnlyReadsMemory();
1751 ++NumAnnotated;
1752 Modified = true;
1753 }
1754}
1755void SimplifyLibCalls::setDoesNotThrow(Function &F) {
1756 if (!F.doesNotThrow()) {
1757 F.setDoesNotThrow();
1758 ++NumAnnotated;
1759 Modified = true;
1760 }
1761}
1762void SimplifyLibCalls::setDoesNotCapture(Function &F, unsigned n) {
1763 if (!F.doesNotCapture(n)) {
1764 F.setDoesNotCapture(n);
1765 ++NumAnnotated;
1766 Modified = true;
1767 }
1768}
1769void SimplifyLibCalls::setDoesNotAlias(Function &F, unsigned n) {
1770 if (!F.doesNotAlias(n)) {
1771 F.setDoesNotAlias(n);
1772 ++NumAnnotated;
1773 Modified = true;
1774 }
1775}
1776
Chris Lattnere265ad82011-02-24 07:12:12 +00001777
1778void SimplifyLibCalls::inferPrototypeAttributes(Function &F) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001779 FunctionType *FTy = F.getFunctionType();
Nadav Rotema94d6e82012-07-24 10:51:42 +00001780
Chris Lattnere265ad82011-02-24 07:12:12 +00001781 StringRef Name = F.getName();
1782 switch (Name[0]) {
1783 case 's':
1784 if (Name == "strlen") {
1785 if (FTy->getNumParams() != 1 || !FTy->getParamType(0)->isPointerTy())
1786 return;
1787 setOnlyReadsMemory(F);
1788 setDoesNotThrow(F);
1789 setDoesNotCapture(F, 1);
1790 } else if (Name == "strchr" ||
1791 Name == "strrchr") {
1792 if (FTy->getNumParams() != 2 ||
1793 !FTy->getParamType(0)->isPointerTy() ||
1794 !FTy->getParamType(1)->isIntegerTy())
1795 return;
1796 setOnlyReadsMemory(F);
1797 setDoesNotThrow(F);
1798 } else if (Name == "strcpy" ||
1799 Name == "stpcpy" ||
1800 Name == "strcat" ||
1801 Name == "strtol" ||
1802 Name == "strtod" ||
1803 Name == "strtof" ||
1804 Name == "strtoul" ||
1805 Name == "strtoll" ||
1806 Name == "strtold" ||
1807 Name == "strncat" ||
1808 Name == "strncpy" ||
David Majnemerac782662012-05-15 11:46:21 +00001809 Name == "stpncpy" ||
Chris Lattnere265ad82011-02-24 07:12:12 +00001810 Name == "strtoull") {
1811 if (FTy->getNumParams() < 2 ||
1812 !FTy->getParamType(1)->isPointerTy())
1813 return;
1814 setDoesNotThrow(F);
1815 setDoesNotCapture(F, 2);
1816 } else if (Name == "strxfrm") {
1817 if (FTy->getNumParams() != 3 ||
1818 !FTy->getParamType(0)->isPointerTy() ||
1819 !FTy->getParamType(1)->isPointerTy())
1820 return;
1821 setDoesNotThrow(F);
1822 setDoesNotCapture(F, 1);
1823 setDoesNotCapture(F, 2);
1824 } else if (Name == "strcmp" ||
1825 Name == "strspn" ||
1826 Name == "strncmp" ||
1827 Name == "strcspn" ||
1828 Name == "strcoll" ||
1829 Name == "strcasecmp" ||
1830 Name == "strncasecmp") {
1831 if (FTy->getNumParams() < 2 ||
1832 !FTy->getParamType(0)->isPointerTy() ||
1833 !FTy->getParamType(1)->isPointerTy())
1834 return;
1835 setOnlyReadsMemory(F);
1836 setDoesNotThrow(F);
1837 setDoesNotCapture(F, 1);
1838 setDoesNotCapture(F, 2);
1839 } else if (Name == "strstr" ||
1840 Name == "strpbrk") {
1841 if (FTy->getNumParams() != 2 || !FTy->getParamType(1)->isPointerTy())
1842 return;
1843 setOnlyReadsMemory(F);
1844 setDoesNotThrow(F);
1845 setDoesNotCapture(F, 2);
1846 } else if (Name == "strtok" ||
1847 Name == "strtok_r") {
1848 if (FTy->getNumParams() < 2 || !FTy->getParamType(1)->isPointerTy())
1849 return;
1850 setDoesNotThrow(F);
1851 setDoesNotCapture(F, 2);
1852 } else if (Name == "scanf" ||
1853 Name == "setbuf" ||
1854 Name == "setvbuf") {
1855 if (FTy->getNumParams() < 1 || !FTy->getParamType(0)->isPointerTy())
1856 return;
1857 setDoesNotThrow(F);
1858 setDoesNotCapture(F, 1);
1859 } else if (Name == "strdup" ||
1860 Name == "strndup") {
1861 if (FTy->getNumParams() < 1 || !FTy->getReturnType()->isPointerTy() ||
1862 !FTy->getParamType(0)->isPointerTy())
1863 return;
1864 setDoesNotThrow(F);
1865 setDoesNotAlias(F, 0);
1866 setDoesNotCapture(F, 1);
1867 } else if (Name == "stat" ||
1868 Name == "sscanf" ||
1869 Name == "sprintf" ||
1870 Name == "statvfs") {
1871 if (FTy->getNumParams() < 2 ||
1872 !FTy->getParamType(0)->isPointerTy() ||
1873 !FTy->getParamType(1)->isPointerTy())
1874 return;
1875 setDoesNotThrow(F);
1876 setDoesNotCapture(F, 1);
1877 setDoesNotCapture(F, 2);
1878 } else if (Name == "snprintf") {
1879 if (FTy->getNumParams() != 3 ||
1880 !FTy->getParamType(0)->isPointerTy() ||
1881 !FTy->getParamType(2)->isPointerTy())
1882 return;
1883 setDoesNotThrow(F);
1884 setDoesNotCapture(F, 1);
1885 setDoesNotCapture(F, 3);
1886 } else if (Name == "setitimer") {
1887 if (FTy->getNumParams() != 3 ||
1888 !FTy->getParamType(1)->isPointerTy() ||
1889 !FTy->getParamType(2)->isPointerTy())
1890 return;
1891 setDoesNotThrow(F);
1892 setDoesNotCapture(F, 2);
1893 setDoesNotCapture(F, 3);
1894 } else if (Name == "system") {
1895 if (FTy->getNumParams() != 1 ||
1896 !FTy->getParamType(0)->isPointerTy())
1897 return;
1898 // May throw; "system" is a valid pthread cancellation point.
1899 setDoesNotCapture(F, 1);
1900 }
1901 break;
1902 case 'm':
1903 if (Name == "malloc") {
1904 if (FTy->getNumParams() != 1 ||
1905 !FTy->getReturnType()->isPointerTy())
1906 return;
1907 setDoesNotThrow(F);
1908 setDoesNotAlias(F, 0);
1909 } else if (Name == "memcmp") {
1910 if (FTy->getNumParams() != 3 ||
1911 !FTy->getParamType(0)->isPointerTy() ||
1912 !FTy->getParamType(1)->isPointerTy())
1913 return;
1914 setOnlyReadsMemory(F);
1915 setDoesNotThrow(F);
1916 setDoesNotCapture(F, 1);
1917 setDoesNotCapture(F, 2);
1918 } else if (Name == "memchr" ||
1919 Name == "memrchr") {
1920 if (FTy->getNumParams() != 3)
1921 return;
1922 setOnlyReadsMemory(F);
1923 setDoesNotThrow(F);
1924 } else if (Name == "modf" ||
1925 Name == "modff" ||
1926 Name == "modfl" ||
1927 Name == "memcpy" ||
1928 Name == "memccpy" ||
1929 Name == "memmove") {
1930 if (FTy->getNumParams() < 2 ||
1931 !FTy->getParamType(1)->isPointerTy())
1932 return;
1933 setDoesNotThrow(F);
1934 setDoesNotCapture(F, 2);
1935 } else if (Name == "memalign") {
1936 if (!FTy->getReturnType()->isPointerTy())
1937 return;
1938 setDoesNotAlias(F, 0);
1939 } else if (Name == "mkdir" ||
1940 Name == "mktime") {
1941 if (FTy->getNumParams() == 0 ||
1942 !FTy->getParamType(0)->isPointerTy())
1943 return;
1944 setDoesNotThrow(F);
1945 setDoesNotCapture(F, 1);
1946 }
1947 break;
1948 case 'r':
1949 if (Name == "realloc") {
1950 if (FTy->getNumParams() != 2 ||
1951 !FTy->getParamType(0)->isPointerTy() ||
1952 !FTy->getReturnType()->isPointerTy())
1953 return;
1954 setDoesNotThrow(F);
Nuno Lopesfd99cab2012-06-25 23:26:10 +00001955 setDoesNotAlias(F, 0);
Chris Lattnere265ad82011-02-24 07:12:12 +00001956 setDoesNotCapture(F, 1);
1957 } else if (Name == "read") {
1958 if (FTy->getNumParams() != 3 ||
1959 !FTy->getParamType(1)->isPointerTy())
1960 return;
1961 // May throw; "read" is a valid pthread cancellation point.
1962 setDoesNotCapture(F, 2);
1963 } else if (Name == "rmdir" ||
1964 Name == "rewind" ||
1965 Name == "remove" ||
1966 Name == "realpath") {
1967 if (FTy->getNumParams() < 1 ||
1968 !FTy->getParamType(0)->isPointerTy())
1969 return;
1970 setDoesNotThrow(F);
1971 setDoesNotCapture(F, 1);
1972 } else if (Name == "rename" ||
1973 Name == "readlink") {
1974 if (FTy->getNumParams() < 2 ||
1975 !FTy->getParamType(0)->isPointerTy() ||
1976 !FTy->getParamType(1)->isPointerTy())
1977 return;
1978 setDoesNotThrow(F);
1979 setDoesNotCapture(F, 1);
1980 setDoesNotCapture(F, 2);
1981 }
1982 break;
1983 case 'w':
1984 if (Name == "write") {
1985 if (FTy->getNumParams() != 3 || !FTy->getParamType(1)->isPointerTy())
1986 return;
1987 // May throw; "write" is a valid pthread cancellation point.
1988 setDoesNotCapture(F, 2);
1989 }
1990 break;
1991 case 'b':
1992 if (Name == "bcopy") {
1993 if (FTy->getNumParams() != 3 ||
1994 !FTy->getParamType(0)->isPointerTy() ||
1995 !FTy->getParamType(1)->isPointerTy())
1996 return;
1997 setDoesNotThrow(F);
1998 setDoesNotCapture(F, 1);
1999 setDoesNotCapture(F, 2);
2000 } else if (Name == "bcmp") {
2001 if (FTy->getNumParams() != 3 ||
2002 !FTy->getParamType(0)->isPointerTy() ||
2003 !FTy->getParamType(1)->isPointerTy())
2004 return;
2005 setDoesNotThrow(F);
2006 setOnlyReadsMemory(F);
2007 setDoesNotCapture(F, 1);
2008 setDoesNotCapture(F, 2);
2009 } else if (Name == "bzero") {
2010 if (FTy->getNumParams() != 2 || !FTy->getParamType(0)->isPointerTy())
2011 return;
2012 setDoesNotThrow(F);
2013 setDoesNotCapture(F, 1);
2014 }
2015 break;
2016 case 'c':
2017 if (Name == "calloc") {
2018 if (FTy->getNumParams() != 2 ||
2019 !FTy->getReturnType()->isPointerTy())
2020 return;
2021 setDoesNotThrow(F);
2022 setDoesNotAlias(F, 0);
2023 } else if (Name == "chmod" ||
2024 Name == "chown" ||
2025 Name == "ctermid" ||
2026 Name == "clearerr" ||
2027 Name == "closedir") {
2028 if (FTy->getNumParams() == 0 || !FTy->getParamType(0)->isPointerTy())
2029 return;
2030 setDoesNotThrow(F);
2031 setDoesNotCapture(F, 1);
2032 }
2033 break;
2034 case 'a':
2035 if (Name == "atoi" ||
2036 Name == "atol" ||
2037 Name == "atof" ||
2038 Name == "atoll") {
2039 if (FTy->getNumParams() != 1 || !FTy->getParamType(0)->isPointerTy())
2040 return;
2041 setDoesNotThrow(F);
2042 setOnlyReadsMemory(F);
2043 setDoesNotCapture(F, 1);
2044 } else if (Name == "access") {
2045 if (FTy->getNumParams() != 2 || !FTy->getParamType(0)->isPointerTy())
2046 return;
2047 setDoesNotThrow(F);
2048 setDoesNotCapture(F, 1);
2049 }
2050 break;
2051 case 'f':
2052 if (Name == "fopen") {
2053 if (FTy->getNumParams() != 2 ||
2054 !FTy->getReturnType()->isPointerTy() ||
2055 !FTy->getParamType(0)->isPointerTy() ||
2056 !FTy->getParamType(1)->isPointerTy())
2057 return;
2058 setDoesNotThrow(F);
2059 setDoesNotAlias(F, 0);
2060 setDoesNotCapture(F, 1);
2061 setDoesNotCapture(F, 2);
2062 } else if (Name == "fdopen") {
2063 if (FTy->getNumParams() != 2 ||
2064 !FTy->getReturnType()->isPointerTy() ||
2065 !FTy->getParamType(1)->isPointerTy())
2066 return;
2067 setDoesNotThrow(F);
2068 setDoesNotAlias(F, 0);
2069 setDoesNotCapture(F, 2);
2070 } else if (Name == "feof" ||
2071 Name == "free" ||
2072 Name == "fseek" ||
2073 Name == "ftell" ||
2074 Name == "fgetc" ||
2075 Name == "fseeko" ||
2076 Name == "ftello" ||
2077 Name == "fileno" ||
2078 Name == "fflush" ||
2079 Name == "fclose" ||
2080 Name == "fsetpos" ||
2081 Name == "flockfile" ||
2082 Name == "funlockfile" ||
2083 Name == "ftrylockfile") {
2084 if (FTy->getNumParams() == 0 || !FTy->getParamType(0)->isPointerTy())
2085 return;
2086 setDoesNotThrow(F);
2087 setDoesNotCapture(F, 1);
2088 } else if (Name == "ferror") {
2089 if (FTy->getNumParams() != 1 || !FTy->getParamType(0)->isPointerTy())
2090 return;
2091 setDoesNotThrow(F);
2092 setDoesNotCapture(F, 1);
2093 setOnlyReadsMemory(F);
2094 } else if (Name == "fputc" ||
2095 Name == "fstat" ||
2096 Name == "frexp" ||
2097 Name == "frexpf" ||
2098 Name == "frexpl" ||
2099 Name == "fstatvfs") {
2100 if (FTy->getNumParams() != 2 || !FTy->getParamType(1)->isPointerTy())
2101 return;
2102 setDoesNotThrow(F);
2103 setDoesNotCapture(F, 2);
2104 } else if (Name == "fgets") {
2105 if (FTy->getNumParams() != 3 ||
2106 !FTy->getParamType(0)->isPointerTy() ||
2107 !FTy->getParamType(2)->isPointerTy())
2108 return;
2109 setDoesNotThrow(F);
2110 setDoesNotCapture(F, 3);
2111 } else if (Name == "fread" ||
2112 Name == "fwrite") {
2113 if (FTy->getNumParams() != 4 ||
2114 !FTy->getParamType(0)->isPointerTy() ||
2115 !FTy->getParamType(3)->isPointerTy())
2116 return;
2117 setDoesNotThrow(F);
2118 setDoesNotCapture(F, 1);
2119 setDoesNotCapture(F, 4);
2120 } else if (Name == "fputs" ||
2121 Name == "fscanf" ||
2122 Name == "fprintf" ||
2123 Name == "fgetpos") {
2124 if (FTy->getNumParams() < 2 ||
2125 !FTy->getParamType(0)->isPointerTy() ||
2126 !FTy->getParamType(1)->isPointerTy())
2127 return;
2128 setDoesNotThrow(F);
2129 setDoesNotCapture(F, 1);
2130 setDoesNotCapture(F, 2);
2131 }
2132 break;
2133 case 'g':
2134 if (Name == "getc" ||
2135 Name == "getlogin_r" ||
2136 Name == "getc_unlocked") {
2137 if (FTy->getNumParams() == 0 || !FTy->getParamType(0)->isPointerTy())
2138 return;
2139 setDoesNotThrow(F);
2140 setDoesNotCapture(F, 1);
2141 } else if (Name == "getenv") {
2142 if (FTy->getNumParams() != 1 || !FTy->getParamType(0)->isPointerTy())
2143 return;
2144 setDoesNotThrow(F);
2145 setOnlyReadsMemory(F);
2146 setDoesNotCapture(F, 1);
2147 } else if (Name == "gets" ||
2148 Name == "getchar") {
2149 setDoesNotThrow(F);
2150 } else if (Name == "getitimer") {
2151 if (FTy->getNumParams() != 2 || !FTy->getParamType(1)->isPointerTy())
2152 return;
2153 setDoesNotThrow(F);
2154 setDoesNotCapture(F, 2);
2155 } else if (Name == "getpwnam") {
2156 if (FTy->getNumParams() != 1 || !FTy->getParamType(0)->isPointerTy())
2157 return;
2158 setDoesNotThrow(F);
2159 setDoesNotCapture(F, 1);
2160 }
2161 break;
2162 case 'u':
2163 if (Name == "ungetc") {
2164 if (FTy->getNumParams() != 2 || !FTy->getParamType(1)->isPointerTy())
2165 return;
2166 setDoesNotThrow(F);
2167 setDoesNotCapture(F, 2);
2168 } else if (Name == "uname" ||
2169 Name == "unlink" ||
2170 Name == "unsetenv") {
2171 if (FTy->getNumParams() != 1 || !FTy->getParamType(0)->isPointerTy())
2172 return;
2173 setDoesNotThrow(F);
2174 setDoesNotCapture(F, 1);
2175 } else if (Name == "utime" ||
2176 Name == "utimes") {
2177 if (FTy->getNumParams() != 2 ||
2178 !FTy->getParamType(0)->isPointerTy() ||
2179 !FTy->getParamType(1)->isPointerTy())
2180 return;
2181 setDoesNotThrow(F);
2182 setDoesNotCapture(F, 1);
2183 setDoesNotCapture(F, 2);
2184 }
2185 break;
2186 case 'p':
2187 if (Name == "putc") {
2188 if (FTy->getNumParams() != 2 || !FTy->getParamType(1)->isPointerTy())
2189 return;
2190 setDoesNotThrow(F);
2191 setDoesNotCapture(F, 2);
2192 } else if (Name == "puts" ||
2193 Name == "printf" ||
2194 Name == "perror") {
2195 if (FTy->getNumParams() != 1 || !FTy->getParamType(0)->isPointerTy())
2196 return;
2197 setDoesNotThrow(F);
2198 setDoesNotCapture(F, 1);
2199 } else if (Name == "pread" ||
2200 Name == "pwrite") {
2201 if (FTy->getNumParams() != 4 || !FTy->getParamType(1)->isPointerTy())
2202 return;
2203 // May throw; these are valid pthread cancellation points.
2204 setDoesNotCapture(F, 2);
2205 } else if (Name == "putchar") {
2206 setDoesNotThrow(F);
2207 } else if (Name == "popen") {
2208 if (FTy->getNumParams() != 2 ||
2209 !FTy->getReturnType()->isPointerTy() ||
2210 !FTy->getParamType(0)->isPointerTy() ||
2211 !FTy->getParamType(1)->isPointerTy())
2212 return;
2213 setDoesNotThrow(F);
2214 setDoesNotAlias(F, 0);
2215 setDoesNotCapture(F, 1);
2216 setDoesNotCapture(F, 2);
2217 } else if (Name == "pclose") {
2218 if (FTy->getNumParams() != 1 || !FTy->getParamType(0)->isPointerTy())
2219 return;
2220 setDoesNotThrow(F);
2221 setDoesNotCapture(F, 1);
2222 }
2223 break;
2224 case 'v':
2225 if (Name == "vscanf") {
2226 if (FTy->getNumParams() != 2 || !FTy->getParamType(1)->isPointerTy())
2227 return;
2228 setDoesNotThrow(F);
2229 setDoesNotCapture(F, 1);
2230 } else if (Name == "vsscanf" ||
2231 Name == "vfscanf") {
2232 if (FTy->getNumParams() != 3 ||
2233 !FTy->getParamType(1)->isPointerTy() ||
2234 !FTy->getParamType(2)->isPointerTy())
2235 return;
2236 setDoesNotThrow(F);
2237 setDoesNotCapture(F, 1);
2238 setDoesNotCapture(F, 2);
2239 } else if (Name == "valloc") {
2240 if (!FTy->getReturnType()->isPointerTy())
2241 return;
2242 setDoesNotThrow(F);
2243 setDoesNotAlias(F, 0);
2244 } else if (Name == "vprintf") {
2245 if (FTy->getNumParams() != 2 || !FTy->getParamType(0)->isPointerTy())
2246 return;
2247 setDoesNotThrow(F);
2248 setDoesNotCapture(F, 1);
2249 } else if (Name == "vfprintf" ||
2250 Name == "vsprintf") {
2251 if (FTy->getNumParams() != 3 ||
2252 !FTy->getParamType(0)->isPointerTy() ||
2253 !FTy->getParamType(1)->isPointerTy())
2254 return;
2255 setDoesNotThrow(F);
2256 setDoesNotCapture(F, 1);
2257 setDoesNotCapture(F, 2);
2258 } else if (Name == "vsnprintf") {
2259 if (FTy->getNumParams() != 4 ||
2260 !FTy->getParamType(0)->isPointerTy() ||
2261 !FTy->getParamType(2)->isPointerTy())
2262 return;
2263 setDoesNotThrow(F);
2264 setDoesNotCapture(F, 1);
2265 setDoesNotCapture(F, 3);
2266 }
2267 break;
2268 case 'o':
2269 if (Name == "open") {
2270 if (FTy->getNumParams() < 2 || !FTy->getParamType(0)->isPointerTy())
2271 return;
2272 // May throw; "open" is a valid pthread cancellation point.
2273 setDoesNotCapture(F, 1);
2274 } else if (Name == "opendir") {
2275 if (FTy->getNumParams() != 1 ||
2276 !FTy->getReturnType()->isPointerTy() ||
2277 !FTy->getParamType(0)->isPointerTy())
2278 return;
2279 setDoesNotThrow(F);
2280 setDoesNotAlias(F, 0);
2281 setDoesNotCapture(F, 1);
2282 }
2283 break;
2284 case 't':
2285 if (Name == "tmpfile") {
2286 if (!FTy->getReturnType()->isPointerTy())
2287 return;
2288 setDoesNotThrow(F);
2289 setDoesNotAlias(F, 0);
2290 } else if (Name == "times") {
2291 if (FTy->getNumParams() != 1 || !FTy->getParamType(0)->isPointerTy())
2292 return;
2293 setDoesNotThrow(F);
2294 setDoesNotCapture(F, 1);
2295 }
2296 break;
2297 case 'h':
2298 if (Name == "htonl" ||
2299 Name == "htons") {
2300 setDoesNotThrow(F);
2301 setDoesNotAccessMemory(F);
2302 }
2303 break;
2304 case 'n':
2305 if (Name == "ntohl" ||
2306 Name == "ntohs") {
2307 setDoesNotThrow(F);
2308 setDoesNotAccessMemory(F);
2309 }
2310 break;
2311 case 'l':
2312 if (Name == "lstat") {
2313 if (FTy->getNumParams() != 2 ||
2314 !FTy->getParamType(0)->isPointerTy() ||
2315 !FTy->getParamType(1)->isPointerTy())
2316 return;
2317 setDoesNotThrow(F);
2318 setDoesNotCapture(F, 1);
2319 setDoesNotCapture(F, 2);
2320 } else if (Name == "lchown") {
2321 if (FTy->getNumParams() != 3 || !FTy->getParamType(0)->isPointerTy())
2322 return;
2323 setDoesNotThrow(F);
2324 setDoesNotCapture(F, 1);
2325 }
2326 break;
2327 case 'q':
2328 if (Name == "qsort") {
2329 if (FTy->getNumParams() != 4 || !FTy->getParamType(3)->isPointerTy())
2330 return;
2331 // May throw; places call through function pointer.
2332 setDoesNotCapture(F, 4);
2333 }
2334 break;
2335 case '_':
2336 if (Name == "__strdup" ||
2337 Name == "__strndup") {
2338 if (FTy->getNumParams() < 1 ||
2339 !FTy->getReturnType()->isPointerTy() ||
2340 !FTy->getParamType(0)->isPointerTy())
2341 return;
2342 setDoesNotThrow(F);
2343 setDoesNotAlias(F, 0);
2344 setDoesNotCapture(F, 1);
2345 } else if (Name == "__strtok_r") {
2346 if (FTy->getNumParams() != 3 ||
2347 !FTy->getParamType(1)->isPointerTy())
2348 return;
2349 setDoesNotThrow(F);
2350 setDoesNotCapture(F, 2);
2351 } else if (Name == "_IO_getc") {
2352 if (FTy->getNumParams() != 1 || !FTy->getParamType(0)->isPointerTy())
2353 return;
2354 setDoesNotThrow(F);
2355 setDoesNotCapture(F, 1);
2356 } else if (Name == "_IO_putc") {
2357 if (FTy->getNumParams() != 2 || !FTy->getParamType(1)->isPointerTy())
2358 return;
2359 setDoesNotThrow(F);
2360 setDoesNotCapture(F, 2);
2361 }
2362 break;
2363 case 1:
2364 if (Name == "\1__isoc99_scanf") {
2365 if (FTy->getNumParams() < 1 ||
2366 !FTy->getParamType(0)->isPointerTy())
2367 return;
2368 setDoesNotThrow(F);
2369 setDoesNotCapture(F, 1);
2370 } else if (Name == "\1stat64" ||
2371 Name == "\1lstat64" ||
2372 Name == "\1statvfs64" ||
2373 Name == "\1__isoc99_sscanf") {
2374 if (FTy->getNumParams() < 1 ||
2375 !FTy->getParamType(0)->isPointerTy() ||
2376 !FTy->getParamType(1)->isPointerTy())
2377 return;
2378 setDoesNotThrow(F);
2379 setDoesNotCapture(F, 1);
2380 setDoesNotCapture(F, 2);
2381 } else if (Name == "\1fopen64") {
2382 if (FTy->getNumParams() != 2 ||
2383 !FTy->getReturnType()->isPointerTy() ||
2384 !FTy->getParamType(0)->isPointerTy() ||
2385 !FTy->getParamType(1)->isPointerTy())
2386 return;
2387 setDoesNotThrow(F);
2388 setDoesNotAlias(F, 0);
2389 setDoesNotCapture(F, 1);
2390 setDoesNotCapture(F, 2);
2391 } else if (Name == "\1fseeko64" ||
2392 Name == "\1ftello64") {
2393 if (FTy->getNumParams() == 0 || !FTy->getParamType(0)->isPointerTy())
2394 return;
2395 setDoesNotThrow(F);
2396 setDoesNotCapture(F, 1);
2397 } else if (Name == "\1tmpfile64") {
2398 if (!FTy->getReturnType()->isPointerTy())
2399 return;
2400 setDoesNotThrow(F);
2401 setDoesNotAlias(F, 0);
2402 } else if (Name == "\1fstat64" ||
2403 Name == "\1fstatvfs64") {
2404 if (FTy->getNumParams() != 2 || !FTy->getParamType(1)->isPointerTy())
2405 return;
2406 setDoesNotThrow(F);
2407 setDoesNotCapture(F, 2);
2408 } else if (Name == "\1open64") {
2409 if (FTy->getNumParams() < 2 || !FTy->getParamType(0)->isPointerTy())
2410 return;
2411 // May throw; "open" is a valid pthread cancellation point.
2412 setDoesNotCapture(F, 1);
2413 }
2414 break;
2415 }
2416}
2417
Nick Lewycky6cd0c042009-01-05 00:07:50 +00002418/// doInitialization - Add attributes to well-known functions.
Nick Lewycky0f8df9a2009-01-04 20:27:34 +00002419///
Nick Lewycky6cd0c042009-01-05 00:07:50 +00002420bool SimplifyLibCalls::doInitialization(Module &M) {
Nick Lewycky0f8df9a2009-01-04 20:27:34 +00002421 Modified = false;
2422 for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I) {
2423 Function &F = *I;
Chris Lattnere265ad82011-02-24 07:12:12 +00002424 if (F.isDeclaration() && F.hasName())
2425 inferPrototypeAttributes(F);
Nick Lewycky0f8df9a2009-01-04 20:27:34 +00002426 }
2427 return Modified;
2428}
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00002429
2430// TODO:
2431// Additional cases that we need to add to this file:
2432//
2433// cbrt:
2434// * cbrt(expN(X)) -> expN(x/3)
2435// * cbrt(sqrt(x)) -> pow(x,1/6)
2436// * cbrt(sqrt(x)) -> pow(x,1/9)
2437//
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00002438// exp, expf, expl:
2439// * exp(log(x)) -> x
2440//
2441// log, logf, logl:
2442// * log(exp(x)) -> x
2443// * log(x**y) -> y*log(x)
2444// * log(exp(y)) -> y*log(e)
2445// * log(exp2(y)) -> y*log(2)
2446// * log(exp10(y)) -> y*log(10)
2447// * log(sqrt(x)) -> 0.5*log(x)
2448// * log(pow(x,y)) -> y*log(x)
2449//
2450// lround, lroundf, lroundl:
2451// * lround(cnst) -> cnst'
2452//
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00002453// pow, powf, powl:
2454// * pow(exp(x),y) -> exp(x*y)
2455// * pow(sqrt(x),y) -> pow(x,y*0.5)
2456// * pow(pow(x,y),z)-> pow(x,y*z)
2457//
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00002458// round, roundf, roundl:
2459// * round(cnst) -> cnst'
2460//
2461// signbit:
2462// * signbit(cnst) -> cnst'
2463// * signbit(nncst) -> 0 (if pstv is a non-negative constant)
2464//
2465// sqrt, sqrtf, sqrtl:
2466// * sqrt(expN(x)) -> expN(x*0.5)
2467// * sqrt(Nroot(x)) -> pow(x,1/(2*N))
2468// * sqrt(pow(x,y)) -> pow(|x|,y*0.5)
2469//
Chris Lattner18c7f802012-02-05 02:29:43 +00002470// strchr:
2471// * strchr(p, 0) -> strlen(p)
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00002472// tan, tanf, tanl:
2473// * tan(atan(x)) -> x
2474//
2475// trunc, truncf, truncl:
2476// * trunc(cnst) -> cnst'
2477//
2478//