blob: 8f31cd11c7dba18f6c56505692a3f74402a48490 [file] [log] [blame]
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001//===- SimplifyLibCalls.cpp - Optimize specific well-known library calls --===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file implements a simple pass that applies a variety of small
11// optimizations for calls to specific well-known function calls (e.g. runtime
Chris Lattnere9f9a7e2009-09-03 05:19:59 +000012// library functions). Any optimization that takes the very simple form
13// "replace call to library function with simpler code that provides the same
14// result" belongs in this file.
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +000015//
16//===----------------------------------------------------------------------===//
17
18#define DEBUG_TYPE "simplify-libcalls"
19#include "llvm/Transforms/Scalar.h"
Eric Christopherb6174e32010-03-05 22:25:30 +000020#include "llvm/Transforms/Utils/BuildLibCalls.h"
Chandler Carruth06cb8ed2012-06-29 12:38:19 +000021#include "llvm/IRBuilder.h"
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +000022#include "llvm/Intrinsics.h"
Owen Andersonfa5cbd62009-07-03 19:42:02 +000023#include "llvm/LLVMContext.h"
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +000024#include "llvm/Module.h"
25#include "llvm/Pass.h"
Daniel Dunbar473955f2009-07-29 22:00:43 +000026#include "llvm/ADT/STLExtras.h"
Chandler Carruth06cb8ed2012-06-29 12:38:19 +000027#include "llvm/ADT/SmallPtrSet.h"
28#include "llvm/ADT/Statistic.h"
29#include "llvm/ADT/StringMap.h"
30#include "llvm/Analysis/ValueTracking.h"
Chad Rosierec7e92a2012-08-22 17:22:33 +000031#include "llvm/Support/CommandLine.h"
Chris Lattner56b4f2b2008-05-01 06:39:12 +000032#include "llvm/Support/Debug.h"
Daniel Dunbarf0443c12009-07-26 08:34:35 +000033#include "llvm/Support/raw_ostream.h"
Micah Villmow3574eca2012-10-08 16:38:25 +000034#include "llvm/DataLayout.h"
Chandler Carruth06cb8ed2012-06-29 12:38:19 +000035#include "llvm/Target/TargetLibraryInfo.h"
Chris Lattnerafbf4832011-02-24 07:16:14 +000036#include "llvm/Config/config.h" // FIXME: Shouldn't depend on host!
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +000037using namespace llvm;
38
39STATISTIC(NumSimplified, "Number of library calls simplified");
Nick Lewycky0f8df9a2009-01-04 20:27:34 +000040STATISTIC(NumAnnotated, "Number of attributes added to library functions");
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +000041
42//===----------------------------------------------------------------------===//
43// Optimizer Base Class
44//===----------------------------------------------------------------------===//
45
46/// This class is the abstract base class for the set of optimizations that
47/// corresponds to one library call.
48namespace {
Chris Lattner3e8b6632009-09-02 06:11:42 +000049class LibCallOptimization {
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +000050protected:
51 Function *Caller;
Micah Villmow3574eca2012-10-08 16:38:25 +000052 const DataLayout *TD;
Richard Osborne36498242011-03-03 13:17:51 +000053 const TargetLibraryInfo *TLI;
Owen Andersonfa5cbd62009-07-03 19:42:02 +000054 LLVMContext* Context;
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +000055public:
Evan Chengeb8c6452010-03-24 20:19:04 +000056 LibCallOptimization() { }
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +000057 virtual ~LibCallOptimization() {}
58
59 /// CallOptimizer - This pure virtual method is implemented by base classes to
60 /// do various optimizations. If this returns null then no transformation was
61 /// performed. If it returns CI, then it transformed the call and CI is to be
62 /// deleted. If it returns something else, replace CI with the new value and
63 /// delete CI.
Eric Christopher37c8b862009-10-07 21:14:25 +000064 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B)
Eric Christopher7a61d702008-08-08 19:39:37 +000065 =0;
Eric Christopher37c8b862009-10-07 21:14:25 +000066
Micah Villmow3574eca2012-10-08 16:38:25 +000067 Value *OptimizeCall(CallInst *CI, const DataLayout *TD,
Richard Osborne36498242011-03-03 13:17:51 +000068 const TargetLibraryInfo *TLI, IRBuilder<> &B) {
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +000069 Caller = CI->getParent()->getParent();
Dan Gohmanf14d9192009-08-18 00:48:13 +000070 this->TD = TD;
Richard Osborne36498242011-03-03 13:17:51 +000071 this->TLI = TLI;
Owen Andersonfa5cbd62009-07-03 19:42:02 +000072 if (CI->getCalledFunction())
Owen Andersone922c022009-07-22 00:24:57 +000073 Context = &CI->getCalledFunction()->getContext();
Rafael Espindolae96af562010-06-16 19:34:01 +000074
75 // We never change the calling convention.
76 if (CI->getCallingConv() != llvm::CallingConv::C)
77 return NULL;
78
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +000079 return CallOptimizer(CI->getCalledFunction(), CI, B);
80 }
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +000081};
82} // End anonymous namespace.
83
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +000084
85//===----------------------------------------------------------------------===//
86// Helper Functions
87//===----------------------------------------------------------------------===//
88
Richard Osborne36498242011-03-03 13:17:51 +000089static bool CallHasFloatingPointArgument(const CallInst *CI) {
90 for (CallInst::const_op_iterator it = CI->op_begin(), e = CI->op_end();
91 it != e; ++it) {
92 if ((*it)->getType()->isFloatingPointTy())
93 return true;
94 }
95 return false;
96}
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +000097
Chris Lattnere9f9a7e2009-09-03 05:19:59 +000098namespace {
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +000099//===----------------------------------------------------------------------===//
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000100// Integer Optimizations
101//===----------------------------------------------------------------------===//
102
103//===---------------------------------------===//
104// 'ffs*' Optimizations
105
Chris Lattner3e8b6632009-09-02 06:11:42 +0000106struct FFSOpt : public LibCallOptimization {
Eric Christopher7a61d702008-08-08 19:39:37 +0000107 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000108 FunctionType *FT = Callee->getFunctionType();
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000109 // Just make sure this has 2 arguments of the same FP type, which match the
110 // result type.
Eric Christopher37c8b862009-10-07 21:14:25 +0000111 if (FT->getNumParams() != 1 ||
Nick Lewycky10d2f4d2010-07-06 03:53:43 +0000112 !FT->getReturnType()->isIntegerTy(32) ||
Duncan Sands1df98592010-02-16 11:11:14 +0000113 !FT->getParamType(0)->isIntegerTy())
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000114 return 0;
Eric Christopher37c8b862009-10-07 21:14:25 +0000115
Gabor Greifaee5dc12010-06-24 10:42:46 +0000116 Value *Op = CI->getArgOperand(0);
Eric Christopher37c8b862009-10-07 21:14:25 +0000117
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000118 // Constant fold.
119 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op)) {
Benjamin Kramer0aae4bd2012-10-19 20:43:44 +0000120 if (CI->isZero()) // ffs(0) -> 0.
121 return B.getInt32(0);
Benjamin Kramera1bf4ca2010-12-27 00:16:46 +0000122 // ffs(c) -> cttz(c)+1
123 return B.getInt32(CI->getValue().countTrailingZeros() + 1);
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000124 }
Eric Christopher37c8b862009-10-07 21:14:25 +0000125
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000126 // ffs(x) -> x != 0 ? (i32)llvm.cttz(x)+1 : 0
Jay Foad5fdd6c82011-07-12 14:06:48 +0000127 Type *ArgType = Op->getType();
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000128 Value *F = Intrinsic::getDeclaration(Callee->getParent(),
Benjamin Kramereb9a85f2011-07-14 17:45:39 +0000129 Intrinsic::cttz, ArgType);
Chandler Carruthccbf1e32011-12-12 04:26:04 +0000130 Value *V = B.CreateCall2(F, Op, B.getFalse(), "cttz");
Benjamin Kramera9390a42011-09-27 20:39:19 +0000131 V = B.CreateAdd(V, ConstantInt::get(V->getType(), 1));
132 V = B.CreateIntCast(V, B.getInt32Ty(), false);
Eric Christopher37c8b862009-10-07 21:14:25 +0000133
Benjamin Kramera9390a42011-09-27 20:39:19 +0000134 Value *Cond = B.CreateICmpNE(Op, Constant::getNullValue(ArgType));
Benjamin Kramera1bf4ca2010-12-27 00:16:46 +0000135 return B.CreateSelect(Cond, V, B.getInt32(0));
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000136 }
137};
138
139//===---------------------------------------===//
140// 'isdigit' Optimizations
141
Chris Lattner3e8b6632009-09-02 06:11:42 +0000142struct IsDigitOpt : public LibCallOptimization {
Eric Christopher7a61d702008-08-08 19:39:37 +0000143 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000144 FunctionType *FT = Callee->getFunctionType();
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000145 // We require integer(i32)
Duncan Sands1df98592010-02-16 11:11:14 +0000146 if (FT->getNumParams() != 1 || !FT->getReturnType()->isIntegerTy() ||
Duncan Sandsb0bc6c32010-02-15 16:12:20 +0000147 !FT->getParamType(0)->isIntegerTy(32))
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000148 return 0;
Eric Christopher37c8b862009-10-07 21:14:25 +0000149
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000150 // isdigit(c) -> (c-'0') <u 10
Gabor Greifaee5dc12010-06-24 10:42:46 +0000151 Value *Op = CI->getArgOperand(0);
Benjamin Kramera1bf4ca2010-12-27 00:16:46 +0000152 Op = B.CreateSub(Op, B.getInt32('0'), "isdigittmp");
153 Op = B.CreateICmpULT(Op, B.getInt32(10), "isdigit");
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000154 return B.CreateZExt(Op, CI->getType());
155 }
156};
157
158//===---------------------------------------===//
159// 'isascii' Optimizations
160
Chris Lattner3e8b6632009-09-02 06:11:42 +0000161struct IsAsciiOpt : public LibCallOptimization {
Eric Christopher7a61d702008-08-08 19:39:37 +0000162 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000163 FunctionType *FT = Callee->getFunctionType();
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000164 // We require integer(i32)
Duncan Sands1df98592010-02-16 11:11:14 +0000165 if (FT->getNumParams() != 1 || !FT->getReturnType()->isIntegerTy() ||
Duncan Sandsb0bc6c32010-02-15 16:12:20 +0000166 !FT->getParamType(0)->isIntegerTy(32))
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000167 return 0;
Eric Christopher37c8b862009-10-07 21:14:25 +0000168
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000169 // isascii(c) -> c <u 128
Gabor Greifaee5dc12010-06-24 10:42:46 +0000170 Value *Op = CI->getArgOperand(0);
Benjamin Kramera1bf4ca2010-12-27 00:16:46 +0000171 Op = B.CreateICmpULT(Op, B.getInt32(128), "isascii");
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000172 return B.CreateZExt(Op, CI->getType());
173 }
174};
Eric Christopher37c8b862009-10-07 21:14:25 +0000175
Chris Lattner313f0e62008-06-09 08:26:51 +0000176//===---------------------------------------===//
177// 'abs', 'labs', 'llabs' Optimizations
178
Chris Lattner3e8b6632009-09-02 06:11:42 +0000179struct AbsOpt : public LibCallOptimization {
Eric Christopher7a61d702008-08-08 19:39:37 +0000180 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000181 FunctionType *FT = Callee->getFunctionType();
Chris Lattner313f0e62008-06-09 08:26:51 +0000182 // We require integer(integer) where the types agree.
Duncan Sands1df98592010-02-16 11:11:14 +0000183 if (FT->getNumParams() != 1 || !FT->getReturnType()->isIntegerTy() ||
Chris Lattner313f0e62008-06-09 08:26:51 +0000184 FT->getParamType(0) != FT->getReturnType())
185 return 0;
Eric Christopher37c8b862009-10-07 21:14:25 +0000186
Chris Lattner313f0e62008-06-09 08:26:51 +0000187 // abs(x) -> x >s -1 ? x : -x
Gabor Greifaee5dc12010-06-24 10:42:46 +0000188 Value *Op = CI->getArgOperand(0);
Benjamin Kramera1bf4ca2010-12-27 00:16:46 +0000189 Value *Pos = B.CreateICmpSGT(Op, Constant::getAllOnesValue(Op->getType()),
Chris Lattner313f0e62008-06-09 08:26:51 +0000190 "ispos");
191 Value *Neg = B.CreateNeg(Op, "neg");
192 return B.CreateSelect(Pos, Op, Neg);
193 }
194};
Eric Christopher37c8b862009-10-07 21:14:25 +0000195
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000196
197//===---------------------------------------===//
198// 'toascii' Optimizations
199
Chris Lattner3e8b6632009-09-02 06:11:42 +0000200struct ToAsciiOpt : public LibCallOptimization {
Eric Christopher7a61d702008-08-08 19:39:37 +0000201 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000202 FunctionType *FT = Callee->getFunctionType();
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000203 // We require i32(i32)
204 if (FT->getNumParams() != 1 || FT->getReturnType() != FT->getParamType(0) ||
Duncan Sandsb0bc6c32010-02-15 16:12:20 +0000205 !FT->getParamType(0)->isIntegerTy(32))
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000206 return 0;
Eric Christopher37c8b862009-10-07 21:14:25 +0000207
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000208 // isascii(c) -> c & 0x7f
Gabor Greifaee5dc12010-06-24 10:42:46 +0000209 return B.CreateAnd(CI->getArgOperand(0),
Owen Andersoneed707b2009-07-24 23:12:02 +0000210 ConstantInt::get(CI->getType(),0x7F));
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000211 }
212};
213
214//===----------------------------------------------------------------------===//
215// Formatting and IO Optimizations
216//===----------------------------------------------------------------------===//
217
218//===---------------------------------------===//
219// 'printf' Optimizations
220
Chris Lattner3e8b6632009-09-02 06:11:42 +0000221struct PrintFOpt : public LibCallOptimization {
Richard Osborne36498242011-03-03 13:17:51 +0000222 Value *OptimizeFixedFormatString(Function *Callee, CallInst *CI,
223 IRBuilder<> &B) {
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000224 // Check for a fixed format string.
Chris Lattner18c7f802012-02-05 02:29:43 +0000225 StringRef FormatStr;
226 if (!getConstantStringInfo(CI->getArgOperand(0), FormatStr))
Bill Wendling0582ae92009-03-13 04:39:26 +0000227 return 0;
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000228
229 // Empty format string -> noop.
230 if (FormatStr.empty()) // Tolerate printf's declared void.
Eric Christopher37c8b862009-10-07 21:14:25 +0000231 return CI->use_empty() ? (Value*)CI :
Owen Andersoneed707b2009-07-24 23:12:02 +0000232 ConstantInt::get(CI->getType(), 0);
Eric Christopher37c8b862009-10-07 21:14:25 +0000233
Daniel Dunbard02be242011-02-12 18:19:57 +0000234 // Do not do any of the following transformations if the printf return value
235 // is used, in general the printf return value is not compatible with either
236 // putchar() or puts().
237 if (!CI->use_empty())
238 return 0;
239
240 // printf("x") -> putchar('x'), even for '%'.
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000241 if (FormatStr.size() == 1) {
Nuno Lopes51004df2012-07-25 16:46:31 +0000242 Value *Res = EmitPutChar(B.getInt32(FormatStr[0]), B, TD, TLI);
Nuno Lopescd31fc72012-07-26 17:10:46 +0000243 if (CI->use_empty() || !Res) return Res;
Chris Lattner74965f22009-11-09 04:57:04 +0000244 return B.CreateIntCast(Res, CI->getType(), true);
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000245 }
Eric Christopher37c8b862009-10-07 21:14:25 +0000246
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000247 // printf("foo\n") --> puts("foo")
248 if (FormatStr[FormatStr.size()-1] == '\n' &&
249 FormatStr.find('%') == std::string::npos) { // no format characters.
250 // Create a string literal with no \n on it. We expect the constant merge
251 // pass to be run after this pass, to merge duplicate strings.
Chris Lattner18c7f802012-02-05 02:29:43 +0000252 FormatStr = FormatStr.drop_back();
Benjamin Kramer59e43bd2011-10-29 19:43:31 +0000253 Value *GV = B.CreateGlobalString(FormatStr, "str");
Nuno Lopes51004df2012-07-25 16:46:31 +0000254 Value *NewCI = EmitPutS(GV, B, TD, TLI);
255 return (CI->use_empty() || !NewCI) ?
256 NewCI :
257 ConstantInt::get(CI->getType(), FormatStr.size()+1);
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000258 }
Eric Christopher37c8b862009-10-07 21:14:25 +0000259
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000260 // Optimize specific format strings.
Gabor Greifaee5dc12010-06-24 10:42:46 +0000261 // printf("%c", chr) --> putchar(chr)
Gabor Greif8e1ebff2010-06-30 12:42:43 +0000262 if (FormatStr == "%c" && CI->getNumArgOperands() > 1 &&
Gabor Greifaee5dc12010-06-24 10:42:46 +0000263 CI->getArgOperand(1)->getType()->isIntegerTy()) {
Nuno Lopes51004df2012-07-25 16:46:31 +0000264 Value *Res = EmitPutChar(CI->getArgOperand(1), B, TD, TLI);
Eric Christopher80bf1d52009-11-21 01:01:30 +0000265
Nuno Lopescd31fc72012-07-26 17:10:46 +0000266 if (CI->use_empty() || !Res) return Res;
Chris Lattner74965f22009-11-09 04:57:04 +0000267 return B.CreateIntCast(Res, CI->getType(), true);
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000268 }
Eric Christopher37c8b862009-10-07 21:14:25 +0000269
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000270 // printf("%s\n", str) --> puts(str)
Gabor Greif8e1ebff2010-06-30 12:42:43 +0000271 if (FormatStr == "%s\n" && CI->getNumArgOperands() > 1 &&
Daniel Dunbard02be242011-02-12 18:19:57 +0000272 CI->getArgOperand(1)->getType()->isPointerTy()) {
Nuno Lopes51004df2012-07-25 16:46:31 +0000273 return EmitPutS(CI->getArgOperand(1), B, TD, TLI);
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000274 }
275 return 0;
276 }
Richard Osborne36498242011-03-03 13:17:51 +0000277
278 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
279 // Require one fixed pointer argument and an integer/void result.
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000280 FunctionType *FT = Callee->getFunctionType();
Richard Osborne36498242011-03-03 13:17:51 +0000281 if (FT->getNumParams() < 1 || !FT->getParamType(0)->isPointerTy() ||
282 !(FT->getReturnType()->isIntegerTy() ||
283 FT->getReturnType()->isVoidTy()))
284 return 0;
285
286 if (Value *V = OptimizeFixedFormatString(Callee, CI, B)) {
287 return V;
288 }
289
290 // printf(format, ...) -> iprintf(format, ...) if no floating point
291 // arguments.
292 if (TLI->has(LibFunc::iprintf) && !CallHasFloatingPointArgument(CI)) {
293 Module *M = B.GetInsertBlock()->getParent()->getParent();
294 Constant *IPrintFFn =
295 M->getOrInsertFunction("iprintf", FT, Callee->getAttributes());
296 CallInst *New = cast<CallInst>(CI->clone());
297 New->setCalledFunction(IPrintFFn);
298 B.Insert(New);
299 return New;
300 }
301 return 0;
302 }
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000303};
304
305//===---------------------------------------===//
306// 'sprintf' Optimizations
307
Chris Lattner3e8b6632009-09-02 06:11:42 +0000308struct SPrintFOpt : public LibCallOptimization {
Richard Osborne419454a2011-03-03 14:09:28 +0000309 Value *OptimizeFixedFormatString(Function *Callee, CallInst *CI,
310 IRBuilder<> &B) {
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000311 // Check for a fixed format string.
Chris Lattner18c7f802012-02-05 02:29:43 +0000312 StringRef FormatStr;
313 if (!getConstantStringInfo(CI->getArgOperand(1), FormatStr))
Bill Wendling0582ae92009-03-13 04:39:26 +0000314 return 0;
Eric Christopher37c8b862009-10-07 21:14:25 +0000315
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000316 // If we just have a format string (nothing else crazy) transform it.
Gabor Greif8e1ebff2010-06-30 12:42:43 +0000317 if (CI->getNumArgOperands() == 2) {
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000318 // Make sure there's no % in the constant array. We could try to handle
319 // %% -> % in the future if we cared.
320 for (unsigned i = 0, e = FormatStr.size(); i != e; ++i)
321 if (FormatStr[i] == '%')
322 return 0; // we found a format specifier, bail out.
Dan Gohmanf14d9192009-08-18 00:48:13 +0000323
Micah Villmow3574eca2012-10-08 16:38:25 +0000324 // These optimizations require DataLayout.
Dan Gohmanf14d9192009-08-18 00:48:13 +0000325 if (!TD) return 0;
326
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000327 // sprintf(str, fmt) -> llvm.memcpy(str, fmt, strlen(fmt)+1, 1)
Benjamin Kramera1bf4ca2010-12-27 00:16:46 +0000328 B.CreateMemCpy(CI->getArgOperand(0), CI->getArgOperand(1),
Chandler Carruthece6c6b2012-11-01 08:07:29 +0000329 ConstantInt::get(TD->getIntPtrType(*Context), // Copy the
Benjamin Kramera1bf4ca2010-12-27 00:16:46 +0000330 FormatStr.size() + 1), 1); // nul byte.
Owen Andersoneed707b2009-07-24 23:12:02 +0000331 return ConstantInt::get(CI->getType(), FormatStr.size());
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000332 }
Eric Christopher37c8b862009-10-07 21:14:25 +0000333
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000334 // The remaining optimizations require the format string to be "%s" or "%c"
335 // and have an extra operand.
Gabor Greif8e1ebff2010-06-30 12:42:43 +0000336 if (FormatStr.size() != 2 || FormatStr[0] != '%' ||
337 CI->getNumArgOperands() < 3)
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000338 return 0;
Eric Christopher37c8b862009-10-07 21:14:25 +0000339
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000340 // Decode the second character of the format string.
341 if (FormatStr[1] == 'c') {
Chris Lattner56b4f2b2008-05-01 06:39:12 +0000342 // sprintf(dst, "%c", chr) --> *(i8*)dst = chr; *((i8*)dst+1) = 0
Gabor Greifaee5dc12010-06-24 10:42:46 +0000343 if (!CI->getArgOperand(2)->getType()->isIntegerTy()) return 0;
Benjamin Kramera1bf4ca2010-12-27 00:16:46 +0000344 Value *V = B.CreateTrunc(CI->getArgOperand(2), B.getInt8Ty(), "char");
Gabor Greifaee5dc12010-06-24 10:42:46 +0000345 Value *Ptr = CastToCStr(CI->getArgOperand(0), B);
Chris Lattner56b4f2b2008-05-01 06:39:12 +0000346 B.CreateStore(V, Ptr);
Benjamin Kramera1bf4ca2010-12-27 00:16:46 +0000347 Ptr = B.CreateGEP(Ptr, B.getInt32(1), "nul");
348 B.CreateStore(B.getInt8(0), Ptr);
Eric Christopher37c8b862009-10-07 21:14:25 +0000349
Owen Andersoneed707b2009-07-24 23:12:02 +0000350 return ConstantInt::get(CI->getType(), 1);
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000351 }
Eric Christopher37c8b862009-10-07 21:14:25 +0000352
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000353 if (FormatStr[1] == 's') {
Micah Villmow3574eca2012-10-08 16:38:25 +0000354 // These optimizations require DataLayout.
Dan Gohmanf14d9192009-08-18 00:48:13 +0000355 if (!TD) return 0;
356
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000357 // sprintf(dest, "%s", str) -> llvm.memcpy(dest, str, strlen(str)+1, 1)
Gabor Greifaee5dc12010-06-24 10:42:46 +0000358 if (!CI->getArgOperand(2)->getType()->isPointerTy()) return 0;
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000359
Nuno Lopes51004df2012-07-25 16:46:31 +0000360 Value *Len = EmitStrLen(CI->getArgOperand(2), B, TD, TLI);
361 if (!Len)
362 return 0;
Owen Andersonfa5cbd62009-07-03 19:42:02 +0000363 Value *IncLen = B.CreateAdd(Len,
Owen Andersoneed707b2009-07-24 23:12:02 +0000364 ConstantInt::get(Len->getType(), 1),
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000365 "leninc");
Benjamin Kramera1bf4ca2010-12-27 00:16:46 +0000366 B.CreateMemCpy(CI->getArgOperand(0), CI->getArgOperand(2), IncLen, 1);
Eric Christopher37c8b862009-10-07 21:14:25 +0000367
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000368 // The sprintf result is the unincremented number of bytes in the string.
369 return B.CreateIntCast(Len, CI->getType(), false);
370 }
371 return 0;
372 }
Richard Osborne419454a2011-03-03 14:09:28 +0000373
374 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
375 // Require two fixed pointer arguments and an integer result.
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000376 FunctionType *FT = Callee->getFunctionType();
Richard Osborne419454a2011-03-03 14:09:28 +0000377 if (FT->getNumParams() != 2 || !FT->getParamType(0)->isPointerTy() ||
378 !FT->getParamType(1)->isPointerTy() ||
379 !FT->getReturnType()->isIntegerTy())
380 return 0;
381
382 if (Value *V = OptimizeFixedFormatString(Callee, CI, B)) {
383 return V;
384 }
385
Richard Osborneea2578c2011-03-03 14:21:22 +0000386 // sprintf(str, format, ...) -> siprintf(str, format, ...) if no floating
Richard Osborne419454a2011-03-03 14:09:28 +0000387 // point arguments.
388 if (TLI->has(LibFunc::siprintf) && !CallHasFloatingPointArgument(CI)) {
389 Module *M = B.GetInsertBlock()->getParent()->getParent();
390 Constant *SIPrintFFn =
391 M->getOrInsertFunction("siprintf", FT, Callee->getAttributes());
392 CallInst *New = cast<CallInst>(CI->clone());
393 New->setCalledFunction(SIPrintFFn);
394 B.Insert(New);
395 return New;
396 }
397 return 0;
398 }
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000399};
400
401//===---------------------------------------===//
402// 'fwrite' Optimizations
403
Chris Lattner3e8b6632009-09-02 06:11:42 +0000404struct FWriteOpt : public LibCallOptimization {
Eric Christopher7a61d702008-08-08 19:39:37 +0000405 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000406 // Require a pointer, an integer, an integer, a pointer, returning integer.
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000407 FunctionType *FT = Callee->getFunctionType();
Duncan Sands1df98592010-02-16 11:11:14 +0000408 if (FT->getNumParams() != 4 || !FT->getParamType(0)->isPointerTy() ||
409 !FT->getParamType(1)->isIntegerTy() ||
410 !FT->getParamType(2)->isIntegerTy() ||
411 !FT->getParamType(3)->isPointerTy() ||
412 !FT->getReturnType()->isIntegerTy())
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000413 return 0;
Eric Christopher37c8b862009-10-07 21:14:25 +0000414
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000415 // Get the element size and count.
Gabor Greifaee5dc12010-06-24 10:42:46 +0000416 ConstantInt *SizeC = dyn_cast<ConstantInt>(CI->getArgOperand(1));
417 ConstantInt *CountC = dyn_cast<ConstantInt>(CI->getArgOperand(2));
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000418 if (!SizeC || !CountC) return 0;
419 uint64_t Bytes = SizeC->getZExtValue()*CountC->getZExtValue();
Eric Christopher37c8b862009-10-07 21:14:25 +0000420
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000421 // If this is writing zero records, remove the call (it's a noop).
422 if (Bytes == 0)
Owen Andersoneed707b2009-07-24 23:12:02 +0000423 return ConstantInt::get(CI->getType(), 0);
Eric Christopher37c8b862009-10-07 21:14:25 +0000424
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000425 // If this is writing one byte, turn it into fputc.
Joerg Sonnenberger127a6692011-12-12 20:18:31 +0000426 // This optimisation is only valid, if the return value is unused.
427 if (Bytes == 1 && CI->use_empty()) { // fwrite(S,1,1,F) -> fputc(S[0],F)
Gabor Greifaee5dc12010-06-24 10:42:46 +0000428 Value *Char = B.CreateLoad(CastToCStr(CI->getArgOperand(0), B), "char");
Nuno Lopes51004df2012-07-25 16:46:31 +0000429 Value *NewCI = EmitFPutC(Char, CI->getArgOperand(3), B, TD, TLI);
430 return NewCI ? ConstantInt::get(CI->getType(), 1) : 0;
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000431 }
432
433 return 0;
434 }
435};
436
437//===---------------------------------------===//
438// 'fputs' Optimizations
439
Chris Lattner3e8b6632009-09-02 06:11:42 +0000440struct FPutsOpt : public LibCallOptimization {
Eric Christopher7a61d702008-08-08 19:39:37 +0000441 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
Micah Villmow3574eca2012-10-08 16:38:25 +0000442 // These optimizations require DataLayout.
Dan Gohmanf14d9192009-08-18 00:48:13 +0000443 if (!TD) return 0;
444
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000445 // Require two pointers. Also, we can't optimize if return value is used.
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000446 FunctionType *FT = Callee->getFunctionType();
Duncan Sands1df98592010-02-16 11:11:14 +0000447 if (FT->getNumParams() != 2 || !FT->getParamType(0)->isPointerTy() ||
448 !FT->getParamType(1)->isPointerTy() ||
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000449 !CI->use_empty())
450 return 0;
Eric Christopher37c8b862009-10-07 21:14:25 +0000451
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000452 // fputs(s,F) --> fwrite(s,1,strlen(s),F)
Gabor Greifaee5dc12010-06-24 10:42:46 +0000453 uint64_t Len = GetStringLength(CI->getArgOperand(0));
Chris Lattner56b4f2b2008-05-01 06:39:12 +0000454 if (!Len) return 0;
Nuno Lopes51004df2012-07-25 16:46:31 +0000455 // Known to have no uses (see above).
456 return EmitFWrite(CI->getArgOperand(0),
Chandler Carruthece6c6b2012-11-01 08:07:29 +0000457 ConstantInt::get(TD->getIntPtrType(*Context), Len-1),
Nuno Lopes51004df2012-07-25 16:46:31 +0000458 CI->getArgOperand(1), B, TD, TLI);
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000459 }
460};
461
462//===---------------------------------------===//
463// 'fprintf' Optimizations
464
Chris Lattner3e8b6632009-09-02 06:11:42 +0000465struct FPrintFOpt : public LibCallOptimization {
Richard Osborne022708f2011-03-03 14:20:22 +0000466 Value *OptimizeFixedFormatString(Function *Callee, CallInst *CI,
467 IRBuilder<> &B) {
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000468 // All the optimizations depend on the format string.
Chris Lattner18c7f802012-02-05 02:29:43 +0000469 StringRef FormatStr;
470 if (!getConstantStringInfo(CI->getArgOperand(1), FormatStr))
Bill Wendling0582ae92009-03-13 04:39:26 +0000471 return 0;
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000472
473 // fprintf(F, "foo") --> fwrite("foo", 3, 1, F)
Gabor Greif8e1ebff2010-06-30 12:42:43 +0000474 if (CI->getNumArgOperands() == 2) {
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000475 for (unsigned i = 0, e = FormatStr.size(); i != e; ++i)
476 if (FormatStr[i] == '%') // Could handle %% -> % if we cared.
Chris Lattner56b4f2b2008-05-01 06:39:12 +0000477 return 0; // We found a format specifier.
Dan Gohmanf14d9192009-08-18 00:48:13 +0000478
Micah Villmow3574eca2012-10-08 16:38:25 +0000479 // These optimizations require DataLayout.
Dan Gohmanf14d9192009-08-18 00:48:13 +0000480 if (!TD) return 0;
481
Nuno Lopes51004df2012-07-25 16:46:31 +0000482 Value *NewCI = EmitFWrite(CI->getArgOperand(1),
Chandler Carruthece6c6b2012-11-01 08:07:29 +0000483 ConstantInt::get(TD->getIntPtrType(*Context),
Nuno Lopes51004df2012-07-25 16:46:31 +0000484 FormatStr.size()),
485 CI->getArgOperand(0), B, TD, TLI);
486 return NewCI ? ConstantInt::get(CI->getType(), FormatStr.size()) : 0;
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000487 }
Eric Christopher37c8b862009-10-07 21:14:25 +0000488
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000489 // The remaining optimizations require the format string to be "%s" or "%c"
490 // and have an extra operand.
Gabor Greif8e1ebff2010-06-30 12:42:43 +0000491 if (FormatStr.size() != 2 || FormatStr[0] != '%' ||
492 CI->getNumArgOperands() < 3)
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000493 return 0;
Eric Christopher37c8b862009-10-07 21:14:25 +0000494
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000495 // Decode the second character of the format string.
496 if (FormatStr[1] == 'c') {
Gabor Greifaee5dc12010-06-24 10:42:46 +0000497 // fprintf(F, "%c", chr) --> fputc(chr, F)
498 if (!CI->getArgOperand(2)->getType()->isIntegerTy()) return 0;
Nuno Lopes51004df2012-07-25 16:46:31 +0000499 Value *NewCI = EmitFPutC(CI->getArgOperand(2), CI->getArgOperand(0), B,
500 TD, TLI);
501 return NewCI ? ConstantInt::get(CI->getType(), 1) : 0;
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000502 }
Eric Christopher37c8b862009-10-07 21:14:25 +0000503
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000504 if (FormatStr[1] == 's') {
Gabor Greifaee5dc12010-06-24 10:42:46 +0000505 // fprintf(F, "%s", str) --> fputs(str, F)
506 if (!CI->getArgOperand(2)->getType()->isPointerTy() || !CI->use_empty())
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000507 return 0;
Nuno Lopes51004df2012-07-25 16:46:31 +0000508 return EmitFPutS(CI->getArgOperand(2), CI->getArgOperand(0), B, TD, TLI);
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000509 }
510 return 0;
511 }
Richard Osborne022708f2011-03-03 14:20:22 +0000512
513 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
514 // Require two fixed paramters as pointers and integer result.
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000515 FunctionType *FT = Callee->getFunctionType();
Richard Osborne022708f2011-03-03 14:20:22 +0000516 if (FT->getNumParams() != 2 || !FT->getParamType(0)->isPointerTy() ||
517 !FT->getParamType(1)->isPointerTy() ||
518 !FT->getReturnType()->isIntegerTy())
519 return 0;
520
521 if (Value *V = OptimizeFixedFormatString(Callee, CI, B)) {
522 return V;
523 }
524
525 // fprintf(stream, format, ...) -> fiprintf(stream, format, ...) if no
526 // floating point arguments.
527 if (TLI->has(LibFunc::fiprintf) && !CallHasFloatingPointArgument(CI)) {
528 Module *M = B.GetInsertBlock()->getParent()->getParent();
529 Constant *FIPrintFFn =
530 M->getOrInsertFunction("fiprintf", FT, Callee->getAttributes());
531 CallInst *New = cast<CallInst>(CI->clone());
532 New->setCalledFunction(FIPrintFFn);
533 B.Insert(New);
534 return New;
535 }
536 return 0;
537 }
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000538};
539
Anders Carlsson303023d2010-11-30 06:19:18 +0000540//===---------------------------------------===//
541// 'puts' Optimizations
542
543struct PutsOpt : public LibCallOptimization {
544 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
545 // Require one fixed pointer argument and an integer/void result.
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000546 FunctionType *FT = Callee->getFunctionType();
Anders Carlsson303023d2010-11-30 06:19:18 +0000547 if (FT->getNumParams() < 1 || !FT->getParamType(0)->isPointerTy() ||
548 !(FT->getReturnType()->isIntegerTy() ||
549 FT->getReturnType()->isVoidTy()))
550 return 0;
551
552 // Check for a constant string.
Chris Lattner18c7f802012-02-05 02:29:43 +0000553 StringRef Str;
554 if (!getConstantStringInfo(CI->getArgOperand(0), Str))
Anders Carlsson303023d2010-11-30 06:19:18 +0000555 return 0;
556
Daniel Dunbard02be242011-02-12 18:19:57 +0000557 if (Str.empty() && CI->use_empty()) {
Anders Carlsson303023d2010-11-30 06:19:18 +0000558 // puts("") -> putchar('\n')
Nuno Lopes51004df2012-07-25 16:46:31 +0000559 Value *Res = EmitPutChar(B.getInt32('\n'), B, TD, TLI);
Nuno Lopescd31fc72012-07-26 17:10:46 +0000560 if (CI->use_empty() || !Res) return Res;
Anders Carlsson303023d2010-11-30 06:19:18 +0000561 return B.CreateIntCast(Res, CI->getType(), true);
562 }
563
564 return 0;
565 }
566};
567
Bill Wendlingac178222008-05-05 21:37:59 +0000568} // end anonymous namespace.
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000569
570//===----------------------------------------------------------------------===//
571// SimplifyLibCalls Pass Implementation
572//===----------------------------------------------------------------------===//
573
574namespace {
575 /// This pass optimizes well known library functions from libc and libm.
576 ///
Chris Lattner3e8b6632009-09-02 06:11:42 +0000577 class SimplifyLibCalls : public FunctionPass {
Chris Lattnerafbf4832011-02-24 07:16:14 +0000578 TargetLibraryInfo *TLI;
Nadav Rotema94d6e82012-07-24 10:51:42 +0000579
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000580 StringMap<LibCallOptimization*> Optimizations;
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000581 // Integer Optimizations
Chris Lattner313f0e62008-06-09 08:26:51 +0000582 FFSOpt FFS; AbsOpt Abs; IsDigitOpt IsDigit; IsAsciiOpt IsAscii;
583 ToAsciiOpt ToAscii;
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000584 // Formatting and IO Optimizations
585 SPrintFOpt SPrintF; PrintFOpt PrintF;
586 FWriteOpt FWrite; FPutsOpt FPuts; FPrintFOpt FPrintF;
Anders Carlsson303023d2010-11-30 06:19:18 +0000587 PutsOpt Puts;
Nadav Rotema94d6e82012-07-24 10:51:42 +0000588
Nick Lewycky6cd0c042009-01-05 00:07:50 +0000589 bool Modified; // This is only used by doInitialization.
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000590 public:
591 static char ID; // Pass identification
Meador Inge2920a712012-11-13 04:16:17 +0000592 SimplifyLibCalls() : FunctionPass(ID) {
Owen Anderson081c34b2010-10-19 17:21:58 +0000593 initializeSimplifyLibCallsPass(*PassRegistry::getPassRegistry());
594 }
Eli Friedman9d434db2011-11-17 01:27:36 +0000595 void AddOpt(LibFunc::Func F, LibCallOptimization* Opt);
Chad Rosierd7e25252012-08-22 16:52:57 +0000596 void AddOpt(LibFunc::Func F1, LibFunc::Func F2, LibCallOptimization* Opt);
597
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000598 void InitOptimizations();
599 bool runOnFunction(Function &F);
600
Nick Lewycky0f8df9a2009-01-04 20:27:34 +0000601 void setDoesNotAccessMemory(Function &F);
602 void setOnlyReadsMemory(Function &F);
603 void setDoesNotThrow(Function &F);
604 void setDoesNotCapture(Function &F, unsigned n);
605 void setDoesNotAlias(Function &F, unsigned n);
Nick Lewycky6cd0c042009-01-05 00:07:50 +0000606 bool doInitialization(Module &M);
Nick Lewycky0f8df9a2009-01-04 20:27:34 +0000607
Chris Lattnere265ad82011-02-24 07:12:12 +0000608 void inferPrototypeAttributes(Function &F);
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000609 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
Chris Lattnerafbf4832011-02-24 07:16:14 +0000610 AU.addRequired<TargetLibraryInfo>();
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000611 }
612 };
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000613} // end anonymous namespace.
614
Chris Lattnerafbf4832011-02-24 07:16:14 +0000615char SimplifyLibCalls::ID = 0;
616
617INITIALIZE_PASS_BEGIN(SimplifyLibCalls, "simplify-libcalls",
618 "Simplify well-known library calls", false, false)
619INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfo)
620INITIALIZE_PASS_END(SimplifyLibCalls, "simplify-libcalls",
621 "Simplify well-known library calls", false, false)
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000622
623// Public interface to the Simplify LibCalls pass.
624FunctionPass *llvm::createSimplifyLibCallsPass() {
Eric Christopher37c8b862009-10-07 21:14:25 +0000625 return new SimplifyLibCalls();
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000626}
627
Eli Friedman9d434db2011-11-17 01:27:36 +0000628void SimplifyLibCalls::AddOpt(LibFunc::Func F, LibCallOptimization* Opt) {
629 if (TLI->has(F))
630 Optimizations[TLI->getName(F)] = Opt;
631}
632
Chad Rosierd7e25252012-08-22 16:52:57 +0000633void SimplifyLibCalls::AddOpt(LibFunc::Func F1, LibFunc::Func F2,
634 LibCallOptimization* Opt) {
635 if (TLI->has(F1) && TLI->has(F2))
636 Optimizations[TLI->getName(F1)] = Opt;
637}
638
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000639/// Optimizations - Populate the Optimizations map with all the optimizations
640/// we know.
641void SimplifyLibCalls::InitOptimizations() {
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000642 // Integer Optimizations
643 Optimizations["ffs"] = &FFS;
644 Optimizations["ffsl"] = &FFS;
645 Optimizations["ffsll"] = &FFS;
Chris Lattner313f0e62008-06-09 08:26:51 +0000646 Optimizations["abs"] = &Abs;
647 Optimizations["labs"] = &Abs;
648 Optimizations["llabs"] = &Abs;
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000649 Optimizations["isdigit"] = &IsDigit;
650 Optimizations["isascii"] = &IsAscii;
651 Optimizations["toascii"] = &ToAscii;
Eric Christopher37c8b862009-10-07 21:14:25 +0000652
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000653 // Formatting and IO Optimizations
654 Optimizations["sprintf"] = &SPrintF;
655 Optimizations["printf"] = &PrintF;
Eli Friedman9d434db2011-11-17 01:27:36 +0000656 AddOpt(LibFunc::fwrite, &FWrite);
657 AddOpt(LibFunc::fputs, &FPuts);
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000658 Optimizations["fprintf"] = &FPrintF;
Anders Carlsson303023d2010-11-30 06:19:18 +0000659 Optimizations["puts"] = &Puts;
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000660}
661
662
663/// runOnFunction - Top level algorithm.
664///
665bool SimplifyLibCalls::runOnFunction(Function &F) {
Chris Lattnerafbf4832011-02-24 07:16:14 +0000666 TLI = &getAnalysis<TargetLibraryInfo>();
667
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000668 if (Optimizations.empty())
669 InitOptimizations();
Eric Christopher37c8b862009-10-07 21:14:25 +0000670
Micah Villmow3574eca2012-10-08 16:38:25 +0000671 const DataLayout *TD = getAnalysisIfAvailable<DataLayout>();
Eric Christopher37c8b862009-10-07 21:14:25 +0000672
Owen Andersone922c022009-07-22 00:24:57 +0000673 IRBuilder<> Builder(F.getContext());
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000674
675 bool Changed = false;
676 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB) {
677 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ) {
678 // Ignore non-calls.
679 CallInst *CI = dyn_cast<CallInst>(I++);
680 if (!CI) continue;
Eric Christopher37c8b862009-10-07 21:14:25 +0000681
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000682 // Ignore indirect calls and calls to non-external functions.
683 Function *Callee = CI->getCalledFunction();
684 if (Callee == 0 || !Callee->isDeclaration() ||
685 !(Callee->hasExternalLinkage() || Callee->hasDLLImportLinkage()))
686 continue;
Eric Christopher37c8b862009-10-07 21:14:25 +0000687
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000688 // Ignore unknown calls.
Daniel Dunbarf0443c12009-07-26 08:34:35 +0000689 LibCallOptimization *LCO = Optimizations.lookup(Callee->getName());
690 if (!LCO) continue;
Eric Christopher37c8b862009-10-07 21:14:25 +0000691
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000692 // Set the builder to the instruction after the call.
693 Builder.SetInsertPoint(BB, I);
Eric Christopher37c8b862009-10-07 21:14:25 +0000694
Devang Patela2ab3992011-03-09 21:27:52 +0000695 // Use debug location of CI for all new instructions.
696 Builder.SetCurrentDebugLocation(CI->getDebugLoc());
697
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000698 // Try to optimize this call.
Richard Osborne36498242011-03-03 13:17:51 +0000699 Value *Result = LCO->OptimizeCall(CI, TD, TLI, Builder);
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000700 if (Result == 0) continue;
701
David Greene6a6b90e2010-01-05 01:27:21 +0000702 DEBUG(dbgs() << "SimplifyLibCalls simplified: " << *CI;
703 dbgs() << " into: " << *Result << "\n");
Eric Christopher37c8b862009-10-07 21:14:25 +0000704
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000705 // Something changed!
706 Changed = true;
707 ++NumSimplified;
Eric Christopher37c8b862009-10-07 21:14:25 +0000708
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000709 // Inspect the instruction after the call (which was potentially just
710 // added) next.
711 I = CI; ++I;
Eric Christopher37c8b862009-10-07 21:14:25 +0000712
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000713 if (CI != Result && !CI->use_empty()) {
714 CI->replaceAllUsesWith(Result);
715 if (!Result->hasName())
716 Result->takeName(CI);
717 }
718 CI->eraseFromParent();
719 }
720 }
721 return Changed;
722}
723
Nick Lewycky6cd0c042009-01-05 00:07:50 +0000724// Utility methods for doInitialization.
Nick Lewycky0f8df9a2009-01-04 20:27:34 +0000725
726void SimplifyLibCalls::setDoesNotAccessMemory(Function &F) {
727 if (!F.doesNotAccessMemory()) {
728 F.setDoesNotAccessMemory();
729 ++NumAnnotated;
730 Modified = true;
731 }
732}
733void SimplifyLibCalls::setOnlyReadsMemory(Function &F) {
734 if (!F.onlyReadsMemory()) {
735 F.setOnlyReadsMemory();
736 ++NumAnnotated;
737 Modified = true;
738 }
739}
740void SimplifyLibCalls::setDoesNotThrow(Function &F) {
741 if (!F.doesNotThrow()) {
742 F.setDoesNotThrow();
743 ++NumAnnotated;
744 Modified = true;
745 }
746}
747void SimplifyLibCalls::setDoesNotCapture(Function &F, unsigned n) {
748 if (!F.doesNotCapture(n)) {
749 F.setDoesNotCapture(n);
750 ++NumAnnotated;
751 Modified = true;
752 }
753}
754void SimplifyLibCalls::setDoesNotAlias(Function &F, unsigned n) {
755 if (!F.doesNotAlias(n)) {
756 F.setDoesNotAlias(n);
757 ++NumAnnotated;
758 Modified = true;
759 }
760}
761
Chris Lattnere265ad82011-02-24 07:12:12 +0000762
763void SimplifyLibCalls::inferPrototypeAttributes(Function &F) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000764 FunctionType *FTy = F.getFunctionType();
Nadav Rotema94d6e82012-07-24 10:51:42 +0000765
Chris Lattnere265ad82011-02-24 07:12:12 +0000766 StringRef Name = F.getName();
767 switch (Name[0]) {
768 case 's':
769 if (Name == "strlen") {
770 if (FTy->getNumParams() != 1 || !FTy->getParamType(0)->isPointerTy())
771 return;
772 setOnlyReadsMemory(F);
773 setDoesNotThrow(F);
774 setDoesNotCapture(F, 1);
775 } else if (Name == "strchr" ||
776 Name == "strrchr") {
777 if (FTy->getNumParams() != 2 ||
778 !FTy->getParamType(0)->isPointerTy() ||
779 !FTy->getParamType(1)->isIntegerTy())
780 return;
781 setOnlyReadsMemory(F);
782 setDoesNotThrow(F);
783 } else if (Name == "strcpy" ||
784 Name == "stpcpy" ||
785 Name == "strcat" ||
786 Name == "strtol" ||
787 Name == "strtod" ||
788 Name == "strtof" ||
789 Name == "strtoul" ||
790 Name == "strtoll" ||
791 Name == "strtold" ||
792 Name == "strncat" ||
793 Name == "strncpy" ||
David Majnemerac782662012-05-15 11:46:21 +0000794 Name == "stpncpy" ||
Chris Lattnere265ad82011-02-24 07:12:12 +0000795 Name == "strtoull") {
796 if (FTy->getNumParams() < 2 ||
797 !FTy->getParamType(1)->isPointerTy())
798 return;
799 setDoesNotThrow(F);
800 setDoesNotCapture(F, 2);
801 } else if (Name == "strxfrm") {
802 if (FTy->getNumParams() != 3 ||
803 !FTy->getParamType(0)->isPointerTy() ||
804 !FTy->getParamType(1)->isPointerTy())
805 return;
806 setDoesNotThrow(F);
807 setDoesNotCapture(F, 1);
808 setDoesNotCapture(F, 2);
809 } else if (Name == "strcmp" ||
810 Name == "strspn" ||
811 Name == "strncmp" ||
812 Name == "strcspn" ||
813 Name == "strcoll" ||
814 Name == "strcasecmp" ||
815 Name == "strncasecmp") {
816 if (FTy->getNumParams() < 2 ||
817 !FTy->getParamType(0)->isPointerTy() ||
818 !FTy->getParamType(1)->isPointerTy())
819 return;
820 setOnlyReadsMemory(F);
821 setDoesNotThrow(F);
822 setDoesNotCapture(F, 1);
823 setDoesNotCapture(F, 2);
824 } else if (Name == "strstr" ||
825 Name == "strpbrk") {
826 if (FTy->getNumParams() != 2 || !FTy->getParamType(1)->isPointerTy())
827 return;
828 setOnlyReadsMemory(F);
829 setDoesNotThrow(F);
830 setDoesNotCapture(F, 2);
831 } else if (Name == "strtok" ||
832 Name == "strtok_r") {
833 if (FTy->getNumParams() < 2 || !FTy->getParamType(1)->isPointerTy())
834 return;
835 setDoesNotThrow(F);
836 setDoesNotCapture(F, 2);
837 } else if (Name == "scanf" ||
838 Name == "setbuf" ||
839 Name == "setvbuf") {
840 if (FTy->getNumParams() < 1 || !FTy->getParamType(0)->isPointerTy())
841 return;
842 setDoesNotThrow(F);
843 setDoesNotCapture(F, 1);
844 } else if (Name == "strdup" ||
845 Name == "strndup") {
846 if (FTy->getNumParams() < 1 || !FTy->getReturnType()->isPointerTy() ||
847 !FTy->getParamType(0)->isPointerTy())
848 return;
849 setDoesNotThrow(F);
850 setDoesNotAlias(F, 0);
851 setDoesNotCapture(F, 1);
852 } else if (Name == "stat" ||
853 Name == "sscanf" ||
854 Name == "sprintf" ||
855 Name == "statvfs") {
856 if (FTy->getNumParams() < 2 ||
857 !FTy->getParamType(0)->isPointerTy() ||
858 !FTy->getParamType(1)->isPointerTy())
859 return;
860 setDoesNotThrow(F);
861 setDoesNotCapture(F, 1);
862 setDoesNotCapture(F, 2);
863 } else if (Name == "snprintf") {
864 if (FTy->getNumParams() != 3 ||
865 !FTy->getParamType(0)->isPointerTy() ||
866 !FTy->getParamType(2)->isPointerTy())
867 return;
868 setDoesNotThrow(F);
869 setDoesNotCapture(F, 1);
870 setDoesNotCapture(F, 3);
871 } else if (Name == "setitimer") {
872 if (FTy->getNumParams() != 3 ||
873 !FTy->getParamType(1)->isPointerTy() ||
874 !FTy->getParamType(2)->isPointerTy())
875 return;
876 setDoesNotThrow(F);
877 setDoesNotCapture(F, 2);
878 setDoesNotCapture(F, 3);
879 } else if (Name == "system") {
880 if (FTy->getNumParams() != 1 ||
881 !FTy->getParamType(0)->isPointerTy())
882 return;
883 // May throw; "system" is a valid pthread cancellation point.
884 setDoesNotCapture(F, 1);
885 }
886 break;
887 case 'm':
888 if (Name == "malloc") {
889 if (FTy->getNumParams() != 1 ||
890 !FTy->getReturnType()->isPointerTy())
891 return;
892 setDoesNotThrow(F);
893 setDoesNotAlias(F, 0);
894 } else if (Name == "memcmp") {
895 if (FTy->getNumParams() != 3 ||
896 !FTy->getParamType(0)->isPointerTy() ||
897 !FTy->getParamType(1)->isPointerTy())
898 return;
899 setOnlyReadsMemory(F);
900 setDoesNotThrow(F);
901 setDoesNotCapture(F, 1);
902 setDoesNotCapture(F, 2);
903 } else if (Name == "memchr" ||
904 Name == "memrchr") {
905 if (FTy->getNumParams() != 3)
906 return;
907 setOnlyReadsMemory(F);
908 setDoesNotThrow(F);
909 } else if (Name == "modf" ||
910 Name == "modff" ||
911 Name == "modfl" ||
912 Name == "memcpy" ||
913 Name == "memccpy" ||
914 Name == "memmove") {
915 if (FTy->getNumParams() < 2 ||
916 !FTy->getParamType(1)->isPointerTy())
917 return;
918 setDoesNotThrow(F);
919 setDoesNotCapture(F, 2);
920 } else if (Name == "memalign") {
921 if (!FTy->getReturnType()->isPointerTy())
922 return;
923 setDoesNotAlias(F, 0);
924 } else if (Name == "mkdir" ||
925 Name == "mktime") {
926 if (FTy->getNumParams() == 0 ||
927 !FTy->getParamType(0)->isPointerTy())
928 return;
929 setDoesNotThrow(F);
930 setDoesNotCapture(F, 1);
931 }
932 break;
933 case 'r':
934 if (Name == "realloc") {
935 if (FTy->getNumParams() != 2 ||
936 !FTy->getParamType(0)->isPointerTy() ||
937 !FTy->getReturnType()->isPointerTy())
938 return;
939 setDoesNotThrow(F);
Nuno Lopesfd99cab2012-06-25 23:26:10 +0000940 setDoesNotAlias(F, 0);
Chris Lattnere265ad82011-02-24 07:12:12 +0000941 setDoesNotCapture(F, 1);
942 } else if (Name == "read") {
943 if (FTy->getNumParams() != 3 ||
944 !FTy->getParamType(1)->isPointerTy())
945 return;
946 // May throw; "read" is a valid pthread cancellation point.
947 setDoesNotCapture(F, 2);
948 } else if (Name == "rmdir" ||
949 Name == "rewind" ||
950 Name == "remove" ||
951 Name == "realpath") {
952 if (FTy->getNumParams() < 1 ||
953 !FTy->getParamType(0)->isPointerTy())
954 return;
955 setDoesNotThrow(F);
956 setDoesNotCapture(F, 1);
957 } else if (Name == "rename" ||
958 Name == "readlink") {
959 if (FTy->getNumParams() < 2 ||
960 !FTy->getParamType(0)->isPointerTy() ||
961 !FTy->getParamType(1)->isPointerTy())
962 return;
963 setDoesNotThrow(F);
964 setDoesNotCapture(F, 1);
965 setDoesNotCapture(F, 2);
966 }
967 break;
968 case 'w':
969 if (Name == "write") {
970 if (FTy->getNumParams() != 3 || !FTy->getParamType(1)->isPointerTy())
971 return;
972 // May throw; "write" is a valid pthread cancellation point.
973 setDoesNotCapture(F, 2);
974 }
975 break;
976 case 'b':
977 if (Name == "bcopy") {
978 if (FTy->getNumParams() != 3 ||
979 !FTy->getParamType(0)->isPointerTy() ||
980 !FTy->getParamType(1)->isPointerTy())
981 return;
982 setDoesNotThrow(F);
983 setDoesNotCapture(F, 1);
984 setDoesNotCapture(F, 2);
985 } else if (Name == "bcmp") {
986 if (FTy->getNumParams() != 3 ||
987 !FTy->getParamType(0)->isPointerTy() ||
988 !FTy->getParamType(1)->isPointerTy())
989 return;
990 setDoesNotThrow(F);
991 setOnlyReadsMemory(F);
992 setDoesNotCapture(F, 1);
993 setDoesNotCapture(F, 2);
994 } else if (Name == "bzero") {
995 if (FTy->getNumParams() != 2 || !FTy->getParamType(0)->isPointerTy())
996 return;
997 setDoesNotThrow(F);
998 setDoesNotCapture(F, 1);
999 }
1000 break;
1001 case 'c':
1002 if (Name == "calloc") {
1003 if (FTy->getNumParams() != 2 ||
1004 !FTy->getReturnType()->isPointerTy())
1005 return;
1006 setDoesNotThrow(F);
1007 setDoesNotAlias(F, 0);
1008 } else if (Name == "chmod" ||
1009 Name == "chown" ||
1010 Name == "ctermid" ||
1011 Name == "clearerr" ||
1012 Name == "closedir") {
1013 if (FTy->getNumParams() == 0 || !FTy->getParamType(0)->isPointerTy())
1014 return;
1015 setDoesNotThrow(F);
1016 setDoesNotCapture(F, 1);
1017 }
1018 break;
1019 case 'a':
1020 if (Name == "atoi" ||
1021 Name == "atol" ||
1022 Name == "atof" ||
1023 Name == "atoll") {
1024 if (FTy->getNumParams() != 1 || !FTy->getParamType(0)->isPointerTy())
1025 return;
1026 setDoesNotThrow(F);
1027 setOnlyReadsMemory(F);
1028 setDoesNotCapture(F, 1);
1029 } else if (Name == "access") {
1030 if (FTy->getNumParams() != 2 || !FTy->getParamType(0)->isPointerTy())
1031 return;
1032 setDoesNotThrow(F);
1033 setDoesNotCapture(F, 1);
1034 }
1035 break;
1036 case 'f':
1037 if (Name == "fopen") {
1038 if (FTy->getNumParams() != 2 ||
1039 !FTy->getReturnType()->isPointerTy() ||
1040 !FTy->getParamType(0)->isPointerTy() ||
1041 !FTy->getParamType(1)->isPointerTy())
1042 return;
1043 setDoesNotThrow(F);
1044 setDoesNotAlias(F, 0);
1045 setDoesNotCapture(F, 1);
1046 setDoesNotCapture(F, 2);
1047 } else if (Name == "fdopen") {
1048 if (FTy->getNumParams() != 2 ||
1049 !FTy->getReturnType()->isPointerTy() ||
1050 !FTy->getParamType(1)->isPointerTy())
1051 return;
1052 setDoesNotThrow(F);
1053 setDoesNotAlias(F, 0);
1054 setDoesNotCapture(F, 2);
1055 } else if (Name == "feof" ||
1056 Name == "free" ||
1057 Name == "fseek" ||
1058 Name == "ftell" ||
1059 Name == "fgetc" ||
1060 Name == "fseeko" ||
1061 Name == "ftello" ||
1062 Name == "fileno" ||
1063 Name == "fflush" ||
1064 Name == "fclose" ||
1065 Name == "fsetpos" ||
1066 Name == "flockfile" ||
1067 Name == "funlockfile" ||
1068 Name == "ftrylockfile") {
1069 if (FTy->getNumParams() == 0 || !FTy->getParamType(0)->isPointerTy())
1070 return;
1071 setDoesNotThrow(F);
1072 setDoesNotCapture(F, 1);
1073 } else if (Name == "ferror") {
1074 if (FTy->getNumParams() != 1 || !FTy->getParamType(0)->isPointerTy())
1075 return;
1076 setDoesNotThrow(F);
1077 setDoesNotCapture(F, 1);
1078 setOnlyReadsMemory(F);
1079 } else if (Name == "fputc" ||
1080 Name == "fstat" ||
1081 Name == "frexp" ||
1082 Name == "frexpf" ||
1083 Name == "frexpl" ||
1084 Name == "fstatvfs") {
1085 if (FTy->getNumParams() != 2 || !FTy->getParamType(1)->isPointerTy())
1086 return;
1087 setDoesNotThrow(F);
1088 setDoesNotCapture(F, 2);
1089 } else if (Name == "fgets") {
1090 if (FTy->getNumParams() != 3 ||
1091 !FTy->getParamType(0)->isPointerTy() ||
1092 !FTy->getParamType(2)->isPointerTy())
1093 return;
1094 setDoesNotThrow(F);
1095 setDoesNotCapture(F, 3);
1096 } else if (Name == "fread" ||
1097 Name == "fwrite") {
1098 if (FTy->getNumParams() != 4 ||
1099 !FTy->getParamType(0)->isPointerTy() ||
1100 !FTy->getParamType(3)->isPointerTy())
1101 return;
1102 setDoesNotThrow(F);
1103 setDoesNotCapture(F, 1);
1104 setDoesNotCapture(F, 4);
1105 } else if (Name == "fputs" ||
1106 Name == "fscanf" ||
1107 Name == "fprintf" ||
1108 Name == "fgetpos") {
1109 if (FTy->getNumParams() < 2 ||
1110 !FTy->getParamType(0)->isPointerTy() ||
1111 !FTy->getParamType(1)->isPointerTy())
1112 return;
1113 setDoesNotThrow(F);
1114 setDoesNotCapture(F, 1);
1115 setDoesNotCapture(F, 2);
1116 }
1117 break;
1118 case 'g':
1119 if (Name == "getc" ||
1120 Name == "getlogin_r" ||
1121 Name == "getc_unlocked") {
1122 if (FTy->getNumParams() == 0 || !FTy->getParamType(0)->isPointerTy())
1123 return;
1124 setDoesNotThrow(F);
1125 setDoesNotCapture(F, 1);
1126 } else if (Name == "getenv") {
1127 if (FTy->getNumParams() != 1 || !FTy->getParamType(0)->isPointerTy())
1128 return;
1129 setDoesNotThrow(F);
1130 setOnlyReadsMemory(F);
1131 setDoesNotCapture(F, 1);
1132 } else if (Name == "gets" ||
1133 Name == "getchar") {
1134 setDoesNotThrow(F);
1135 } else if (Name == "getitimer") {
1136 if (FTy->getNumParams() != 2 || !FTy->getParamType(1)->isPointerTy())
1137 return;
1138 setDoesNotThrow(F);
1139 setDoesNotCapture(F, 2);
1140 } else if (Name == "getpwnam") {
1141 if (FTy->getNumParams() != 1 || !FTy->getParamType(0)->isPointerTy())
1142 return;
1143 setDoesNotThrow(F);
1144 setDoesNotCapture(F, 1);
1145 }
1146 break;
1147 case 'u':
1148 if (Name == "ungetc") {
1149 if (FTy->getNumParams() != 2 || !FTy->getParamType(1)->isPointerTy())
1150 return;
1151 setDoesNotThrow(F);
1152 setDoesNotCapture(F, 2);
1153 } else if (Name == "uname" ||
1154 Name == "unlink" ||
1155 Name == "unsetenv") {
1156 if (FTy->getNumParams() != 1 || !FTy->getParamType(0)->isPointerTy())
1157 return;
1158 setDoesNotThrow(F);
1159 setDoesNotCapture(F, 1);
1160 } else if (Name == "utime" ||
1161 Name == "utimes") {
1162 if (FTy->getNumParams() != 2 ||
1163 !FTy->getParamType(0)->isPointerTy() ||
1164 !FTy->getParamType(1)->isPointerTy())
1165 return;
1166 setDoesNotThrow(F);
1167 setDoesNotCapture(F, 1);
1168 setDoesNotCapture(F, 2);
1169 }
1170 break;
1171 case 'p':
1172 if (Name == "putc") {
1173 if (FTy->getNumParams() != 2 || !FTy->getParamType(1)->isPointerTy())
1174 return;
1175 setDoesNotThrow(F);
1176 setDoesNotCapture(F, 2);
1177 } else if (Name == "puts" ||
1178 Name == "printf" ||
1179 Name == "perror") {
1180 if (FTy->getNumParams() != 1 || !FTy->getParamType(0)->isPointerTy())
1181 return;
1182 setDoesNotThrow(F);
1183 setDoesNotCapture(F, 1);
1184 } else if (Name == "pread" ||
1185 Name == "pwrite") {
1186 if (FTy->getNumParams() != 4 || !FTy->getParamType(1)->isPointerTy())
1187 return;
1188 // May throw; these are valid pthread cancellation points.
1189 setDoesNotCapture(F, 2);
1190 } else if (Name == "putchar") {
1191 setDoesNotThrow(F);
1192 } else if (Name == "popen") {
1193 if (FTy->getNumParams() != 2 ||
1194 !FTy->getReturnType()->isPointerTy() ||
1195 !FTy->getParamType(0)->isPointerTy() ||
1196 !FTy->getParamType(1)->isPointerTy())
1197 return;
1198 setDoesNotThrow(F);
1199 setDoesNotAlias(F, 0);
1200 setDoesNotCapture(F, 1);
1201 setDoesNotCapture(F, 2);
1202 } else if (Name == "pclose") {
1203 if (FTy->getNumParams() != 1 || !FTy->getParamType(0)->isPointerTy())
1204 return;
1205 setDoesNotThrow(F);
1206 setDoesNotCapture(F, 1);
1207 }
1208 break;
1209 case 'v':
1210 if (Name == "vscanf") {
1211 if (FTy->getNumParams() != 2 || !FTy->getParamType(1)->isPointerTy())
1212 return;
1213 setDoesNotThrow(F);
1214 setDoesNotCapture(F, 1);
1215 } else if (Name == "vsscanf" ||
1216 Name == "vfscanf") {
1217 if (FTy->getNumParams() != 3 ||
1218 !FTy->getParamType(1)->isPointerTy() ||
1219 !FTy->getParamType(2)->isPointerTy())
1220 return;
1221 setDoesNotThrow(F);
1222 setDoesNotCapture(F, 1);
1223 setDoesNotCapture(F, 2);
1224 } else if (Name == "valloc") {
1225 if (!FTy->getReturnType()->isPointerTy())
1226 return;
1227 setDoesNotThrow(F);
1228 setDoesNotAlias(F, 0);
1229 } else if (Name == "vprintf") {
1230 if (FTy->getNumParams() != 2 || !FTy->getParamType(0)->isPointerTy())
1231 return;
1232 setDoesNotThrow(F);
1233 setDoesNotCapture(F, 1);
1234 } else if (Name == "vfprintf" ||
1235 Name == "vsprintf") {
1236 if (FTy->getNumParams() != 3 ||
1237 !FTy->getParamType(0)->isPointerTy() ||
1238 !FTy->getParamType(1)->isPointerTy())
1239 return;
1240 setDoesNotThrow(F);
1241 setDoesNotCapture(F, 1);
1242 setDoesNotCapture(F, 2);
1243 } else if (Name == "vsnprintf") {
1244 if (FTy->getNumParams() != 4 ||
1245 !FTy->getParamType(0)->isPointerTy() ||
1246 !FTy->getParamType(2)->isPointerTy())
1247 return;
1248 setDoesNotThrow(F);
1249 setDoesNotCapture(F, 1);
1250 setDoesNotCapture(F, 3);
1251 }
1252 break;
1253 case 'o':
1254 if (Name == "open") {
1255 if (FTy->getNumParams() < 2 || !FTy->getParamType(0)->isPointerTy())
1256 return;
1257 // May throw; "open" is a valid pthread cancellation point.
1258 setDoesNotCapture(F, 1);
1259 } else if (Name == "opendir") {
1260 if (FTy->getNumParams() != 1 ||
1261 !FTy->getReturnType()->isPointerTy() ||
1262 !FTy->getParamType(0)->isPointerTy())
1263 return;
1264 setDoesNotThrow(F);
1265 setDoesNotAlias(F, 0);
1266 setDoesNotCapture(F, 1);
1267 }
1268 break;
1269 case 't':
1270 if (Name == "tmpfile") {
1271 if (!FTy->getReturnType()->isPointerTy())
1272 return;
1273 setDoesNotThrow(F);
1274 setDoesNotAlias(F, 0);
1275 } else if (Name == "times") {
1276 if (FTy->getNumParams() != 1 || !FTy->getParamType(0)->isPointerTy())
1277 return;
1278 setDoesNotThrow(F);
1279 setDoesNotCapture(F, 1);
1280 }
1281 break;
1282 case 'h':
1283 if (Name == "htonl" ||
1284 Name == "htons") {
1285 setDoesNotThrow(F);
1286 setDoesNotAccessMemory(F);
1287 }
1288 break;
1289 case 'n':
1290 if (Name == "ntohl" ||
1291 Name == "ntohs") {
1292 setDoesNotThrow(F);
1293 setDoesNotAccessMemory(F);
1294 }
1295 break;
1296 case 'l':
1297 if (Name == "lstat") {
1298 if (FTy->getNumParams() != 2 ||
1299 !FTy->getParamType(0)->isPointerTy() ||
1300 !FTy->getParamType(1)->isPointerTy())
1301 return;
1302 setDoesNotThrow(F);
1303 setDoesNotCapture(F, 1);
1304 setDoesNotCapture(F, 2);
1305 } else if (Name == "lchown") {
1306 if (FTy->getNumParams() != 3 || !FTy->getParamType(0)->isPointerTy())
1307 return;
1308 setDoesNotThrow(F);
1309 setDoesNotCapture(F, 1);
1310 }
1311 break;
1312 case 'q':
1313 if (Name == "qsort") {
1314 if (FTy->getNumParams() != 4 || !FTy->getParamType(3)->isPointerTy())
1315 return;
1316 // May throw; places call through function pointer.
1317 setDoesNotCapture(F, 4);
1318 }
1319 break;
1320 case '_':
1321 if (Name == "__strdup" ||
1322 Name == "__strndup") {
1323 if (FTy->getNumParams() < 1 ||
1324 !FTy->getReturnType()->isPointerTy() ||
1325 !FTy->getParamType(0)->isPointerTy())
1326 return;
1327 setDoesNotThrow(F);
1328 setDoesNotAlias(F, 0);
1329 setDoesNotCapture(F, 1);
1330 } else if (Name == "__strtok_r") {
1331 if (FTy->getNumParams() != 3 ||
1332 !FTy->getParamType(1)->isPointerTy())
1333 return;
1334 setDoesNotThrow(F);
1335 setDoesNotCapture(F, 2);
1336 } else if (Name == "_IO_getc") {
1337 if (FTy->getNumParams() != 1 || !FTy->getParamType(0)->isPointerTy())
1338 return;
1339 setDoesNotThrow(F);
1340 setDoesNotCapture(F, 1);
1341 } else if (Name == "_IO_putc") {
1342 if (FTy->getNumParams() != 2 || !FTy->getParamType(1)->isPointerTy())
1343 return;
1344 setDoesNotThrow(F);
1345 setDoesNotCapture(F, 2);
1346 }
1347 break;
1348 case 1:
1349 if (Name == "\1__isoc99_scanf") {
1350 if (FTy->getNumParams() < 1 ||
1351 !FTy->getParamType(0)->isPointerTy())
1352 return;
1353 setDoesNotThrow(F);
1354 setDoesNotCapture(F, 1);
1355 } else if (Name == "\1stat64" ||
1356 Name == "\1lstat64" ||
1357 Name == "\1statvfs64" ||
1358 Name == "\1__isoc99_sscanf") {
1359 if (FTy->getNumParams() < 1 ||
1360 !FTy->getParamType(0)->isPointerTy() ||
1361 !FTy->getParamType(1)->isPointerTy())
1362 return;
1363 setDoesNotThrow(F);
1364 setDoesNotCapture(F, 1);
1365 setDoesNotCapture(F, 2);
1366 } else if (Name == "\1fopen64") {
1367 if (FTy->getNumParams() != 2 ||
1368 !FTy->getReturnType()->isPointerTy() ||
1369 !FTy->getParamType(0)->isPointerTy() ||
1370 !FTy->getParamType(1)->isPointerTy())
1371 return;
1372 setDoesNotThrow(F);
1373 setDoesNotAlias(F, 0);
1374 setDoesNotCapture(F, 1);
1375 setDoesNotCapture(F, 2);
1376 } else if (Name == "\1fseeko64" ||
1377 Name == "\1ftello64") {
1378 if (FTy->getNumParams() == 0 || !FTy->getParamType(0)->isPointerTy())
1379 return;
1380 setDoesNotThrow(F);
1381 setDoesNotCapture(F, 1);
1382 } else if (Name == "\1tmpfile64") {
1383 if (!FTy->getReturnType()->isPointerTy())
1384 return;
1385 setDoesNotThrow(F);
1386 setDoesNotAlias(F, 0);
1387 } else if (Name == "\1fstat64" ||
1388 Name == "\1fstatvfs64") {
1389 if (FTy->getNumParams() != 2 || !FTy->getParamType(1)->isPointerTy())
1390 return;
1391 setDoesNotThrow(F);
1392 setDoesNotCapture(F, 2);
1393 } else if (Name == "\1open64") {
1394 if (FTy->getNumParams() < 2 || !FTy->getParamType(0)->isPointerTy())
1395 return;
1396 // May throw; "open" is a valid pthread cancellation point.
1397 setDoesNotCapture(F, 1);
1398 }
1399 break;
1400 }
1401}
1402
Nick Lewycky6cd0c042009-01-05 00:07:50 +00001403/// doInitialization - Add attributes to well-known functions.
Nick Lewycky0f8df9a2009-01-04 20:27:34 +00001404///
Nick Lewycky6cd0c042009-01-05 00:07:50 +00001405bool SimplifyLibCalls::doInitialization(Module &M) {
Nick Lewycky0f8df9a2009-01-04 20:27:34 +00001406 Modified = false;
1407 for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I) {
1408 Function &F = *I;
Chris Lattnere265ad82011-02-24 07:12:12 +00001409 if (F.isDeclaration() && F.hasName())
1410 inferPrototypeAttributes(F);
Nick Lewycky0f8df9a2009-01-04 20:27:34 +00001411 }
1412 return Modified;
1413}
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001414
1415// TODO:
1416// Additional cases that we need to add to this file:
1417//
1418// cbrt:
1419// * cbrt(expN(X)) -> expN(x/3)
1420// * cbrt(sqrt(x)) -> pow(x,1/6)
1421// * cbrt(sqrt(x)) -> pow(x,1/9)
1422//
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001423// exp, expf, expl:
1424// * exp(log(x)) -> x
1425//
1426// log, logf, logl:
1427// * log(exp(x)) -> x
1428// * log(x**y) -> y*log(x)
1429// * log(exp(y)) -> y*log(e)
1430// * log(exp2(y)) -> y*log(2)
1431// * log(exp10(y)) -> y*log(10)
1432// * log(sqrt(x)) -> 0.5*log(x)
1433// * log(pow(x,y)) -> y*log(x)
1434//
1435// lround, lroundf, lroundl:
1436// * lround(cnst) -> cnst'
1437//
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001438// pow, powf, powl:
1439// * pow(exp(x),y) -> exp(x*y)
1440// * pow(sqrt(x),y) -> pow(x,y*0.5)
1441// * pow(pow(x,y),z)-> pow(x,y*z)
1442//
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001443// round, roundf, roundl:
1444// * round(cnst) -> cnst'
1445//
1446// signbit:
1447// * signbit(cnst) -> cnst'
1448// * signbit(nncst) -> 0 (if pstv is a non-negative constant)
1449//
1450// sqrt, sqrtf, sqrtl:
1451// * sqrt(expN(x)) -> expN(x*0.5)
1452// * sqrt(Nroot(x)) -> pow(x,1/(2*N))
1453// * sqrt(pow(x,y)) -> pow(|x|,y*0.5)
1454//
Chris Lattner18c7f802012-02-05 02:29:43 +00001455// strchr:
1456// * strchr(p, 0) -> strlen(p)
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001457// tan, tanf, tanl:
1458// * tan(atan(x)) -> x
1459//
1460// trunc, truncf, truncl:
1461// * trunc(cnst) -> cnst'
1462//
1463//