blob: 0fd185816fd5833b0b90c5e965c5b8f40807dc46 [file] [log] [blame]
Meador Ingedf796f82012-10-13 16:45:24 +00001//===------ SimplifyLibCalls.cpp - Library calls simplifier ---------------===//
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 is a utility pass used for testing the InstructionSimplify analysis.
11// The analysis is applied to every instruction, and if it simplifies then the
12// instruction is replaced by the simplification. If you are looking for a pass
13// that performs serious instruction folding, use the instcombine pass instead.
14//
15//===----------------------------------------------------------------------===//
16
17#include "llvm/Transforms/Utils/SimplifyLibCalls.h"
Meador Inge20255ef2013-03-12 00:08:29 +000018#include "llvm/ADT/SmallString.h"
Meador Ingedf796f82012-10-13 16:45:24 +000019#include "llvm/ADT/StringMap.h"
Bob Wilsond8d92d92013-11-03 06:48:38 +000020#include "llvm/ADT/Triple.h"
Meador Ingedf796f82012-10-13 16:45:24 +000021#include "llvm/Analysis/ValueTracking.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000022#include "llvm/IR/DataLayout.h"
23#include "llvm/IR/Function.h"
24#include "llvm/IR/IRBuilder.h"
Meador Inge20255ef2013-03-12 00:08:29 +000025#include "llvm/IR/IntrinsicInst.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000026#include "llvm/IR/Intrinsics.h"
27#include "llvm/IR/LLVMContext.h"
28#include "llvm/IR/Module.h"
Nadav Rotem464e8072013-02-27 05:53:43 +000029#include "llvm/Support/Allocator.h"
Hal Finkel66cd3f12013-11-17 02:06:35 +000030#include "llvm/Support/CommandLine.h"
Meador Ingedf796f82012-10-13 16:45:24 +000031#include "llvm/Target/TargetLibraryInfo.h"
32#include "llvm/Transforms/Utils/BuildLibCalls.h"
33
34using namespace llvm;
35
Hal Finkel66cd3f12013-11-17 02:06:35 +000036static cl::opt<bool>
37ColdErrorCalls("error-reporting-is-cold", cl::init(true),
38 cl::Hidden, cl::desc("Treat error-reporting calls as cold"));
39
Meador Ingedf796f82012-10-13 16:45:24 +000040/// This class is the abstract base class for the set of optimizations that
41/// corresponds to one library call.
42namespace {
43class LibCallOptimization {
44protected:
45 Function *Caller;
Rafael Espindola37dc9e12014-02-21 00:06:31 +000046 const DataLayout *DL;
Meador Ingedf796f82012-10-13 16:45:24 +000047 const TargetLibraryInfo *TLI;
Meador Inge76fc1a42012-11-11 03:51:43 +000048 const LibCallSimplifier *LCS;
Meador Ingedf796f82012-10-13 16:45:24 +000049 LLVMContext* Context;
50public:
51 LibCallOptimization() { }
52 virtual ~LibCallOptimization() {}
53
54 /// callOptimizer - This pure virtual method is implemented by base classes to
55 /// do various optimizations. If this returns null then no transformation was
56 /// performed. If it returns CI, then it transformed the call and CI is to be
57 /// deleted. If it returns something else, replace CI with the new value and
58 /// delete CI.
59 virtual Value *callOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B)
60 =0;
61
Chad Rosier22d275f2013-02-08 18:00:14 +000062 /// ignoreCallingConv - Returns false if this transformation could possibly
63 /// change the calling convention.
64 virtual bool ignoreCallingConv() { return false; }
65
Rafael Espindola37dc9e12014-02-21 00:06:31 +000066 Value *optimizeCall(CallInst *CI, const DataLayout *DL,
Meador Inge76fc1a42012-11-11 03:51:43 +000067 const TargetLibraryInfo *TLI,
68 const LibCallSimplifier *LCS, IRBuilder<> &B) {
Meador Ingedf796f82012-10-13 16:45:24 +000069 Caller = CI->getParent()->getParent();
Rafael Espindola37dc9e12014-02-21 00:06:31 +000070 this->DL = DL;
Meador Ingedf796f82012-10-13 16:45:24 +000071 this->TLI = TLI;
Meador Inge76fc1a42012-11-11 03:51:43 +000072 this->LCS = LCS;
Meador Ingedf796f82012-10-13 16:45:24 +000073 if (CI->getCalledFunction())
74 Context = &CI->getCalledFunction()->getContext();
75
76 // We never change the calling convention.
Chad Rosier22d275f2013-02-08 18:00:14 +000077 if (!ignoreCallingConv() && CI->getCallingConv() != llvm::CallingConv::C)
Craig Topperf40110f2014-04-25 05:29:35 +000078 return nullptr;
Meador Ingedf796f82012-10-13 16:45:24 +000079
80 return callOptimizer(CI->getCalledFunction(), CI, B);
81 }
82};
83
84//===----------------------------------------------------------------------===//
Meador Inged589ac62012-10-31 03:33:06 +000085// Helper Functions
86//===----------------------------------------------------------------------===//
87
88/// isOnlyUsedInZeroEqualityComparison - Return true if it only matters that the
89/// value is equal or not-equal to zero.
90static bool isOnlyUsedInZeroEqualityComparison(Value *V) {
Chandler Carruthcdf47882014-03-09 03:16:01 +000091 for (User *U : V->users()) {
92 if (ICmpInst *IC = dyn_cast<ICmpInst>(U))
Meador Inged589ac62012-10-31 03:33:06 +000093 if (IC->isEquality())
94 if (Constant *C = dyn_cast<Constant>(IC->getOperand(1)))
95 if (C->isNullValue())
96 continue;
97 // Unknown instruction.
98 return false;
99 }
100 return true;
101}
102
Meador Inge56edbc92012-11-11 03:51:48 +0000103/// isOnlyUsedInEqualityComparison - Return true if it is only used in equality
104/// comparisons with With.
105static bool isOnlyUsedInEqualityComparison(Value *V, Value *With) {
Chandler Carruthcdf47882014-03-09 03:16:01 +0000106 for (User *U : V->users()) {
107 if (ICmpInst *IC = dyn_cast<ICmpInst>(U))
Meador Inge56edbc92012-11-11 03:51:48 +0000108 if (IC->isEquality() && IC->getOperand(1) == With)
109 continue;
110 // Unknown instruction.
111 return false;
112 }
113 return true;
114}
115
Meador Inge08ca1152012-11-26 20:37:20 +0000116static bool callHasFloatingPointArgument(const CallInst *CI) {
117 for (CallInst::const_op_iterator it = CI->op_begin(), e = CI->op_end();
118 it != e; ++it) {
119 if ((*it)->getType()->isFloatingPointTy())
120 return true;
121 }
122 return false;
123}
124
Benjamin Kramer2702caa2013-08-31 18:19:35 +0000125/// \brief Check whether the overloaded unary floating point function
126/// corresponing to \a Ty is available.
127static bool hasUnaryFloatFn(const TargetLibraryInfo *TLI, Type *Ty,
128 LibFunc::Func DoubleFn, LibFunc::Func FloatFn,
129 LibFunc::Func LongDoubleFn) {
130 switch (Ty->getTypeID()) {
131 case Type::FloatTyID:
132 return TLI->has(FloatFn);
133 case Type::DoubleTyID:
134 return TLI->has(DoubleFn);
135 default:
136 return TLI->has(LongDoubleFn);
137 }
138}
139
Meador Inged589ac62012-10-31 03:33:06 +0000140//===----------------------------------------------------------------------===//
Meador Ingedf796f82012-10-13 16:45:24 +0000141// Fortified Library Call Optimizations
142//===----------------------------------------------------------------------===//
143
144struct FortifiedLibCallOptimization : public LibCallOptimization {
145protected:
146 virtual bool isFoldable(unsigned SizeCIOp, unsigned SizeArgOp,
147 bool isString) const = 0;
148};
149
150struct InstFortifiedLibCallOptimization : public FortifiedLibCallOptimization {
151 CallInst *CI;
152
Craig Topper3e4c6972014-03-05 09:10:37 +0000153 bool isFoldable(unsigned SizeCIOp, unsigned SizeArgOp,
154 bool isString) const override {
Meador Ingedf796f82012-10-13 16:45:24 +0000155 if (CI->getArgOperand(SizeCIOp) == CI->getArgOperand(SizeArgOp))
156 return true;
157 if (ConstantInt *SizeCI =
158 dyn_cast<ConstantInt>(CI->getArgOperand(SizeCIOp))) {
159 if (SizeCI->isAllOnesValue())
160 return true;
161 if (isString) {
162 uint64_t Len = GetStringLength(CI->getArgOperand(SizeArgOp));
163 // If the length is 0 we don't know how long it is and so we can't
164 // remove the check.
165 if (Len == 0) return false;
166 return SizeCI->getZExtValue() >= Len;
167 }
168 if (ConstantInt *Arg = dyn_cast<ConstantInt>(
169 CI->getArgOperand(SizeArgOp)))
170 return SizeCI->getZExtValue() >= Arg->getZExtValue();
171 }
172 return false;
173 }
174};
175
176struct MemCpyChkOpt : public InstFortifiedLibCallOptimization {
Craig Topper3e4c6972014-03-05 09:10:37 +0000177 Value *callOptimizer(Function *Callee, CallInst *CI,
178 IRBuilder<> &B) override {
Meador Ingedf796f82012-10-13 16:45:24 +0000179 this->CI = CI;
180 FunctionType *FT = Callee->getFunctionType();
Chandler Carruth7ec50852012-11-01 08:07:29 +0000181 LLVMContext &Context = CI->getParent()->getContext();
Meador Ingedf796f82012-10-13 16:45:24 +0000182
183 // Check if this has the right signature.
184 if (FT->getNumParams() != 4 || FT->getReturnType() != FT->getParamType(0) ||
185 !FT->getParamType(0)->isPointerTy() ||
186 !FT->getParamType(1)->isPointerTy() ||
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000187 FT->getParamType(2) != DL->getIntPtrType(Context) ||
188 FT->getParamType(3) != DL->getIntPtrType(Context))
Craig Topperf40110f2014-04-25 05:29:35 +0000189 return nullptr;
Meador Ingedf796f82012-10-13 16:45:24 +0000190
191 if (isFoldable(3, 2, false)) {
192 B.CreateMemCpy(CI->getArgOperand(0), CI->getArgOperand(1),
193 CI->getArgOperand(2), 1);
194 return CI->getArgOperand(0);
195 }
Craig Topperf40110f2014-04-25 05:29:35 +0000196 return nullptr;
Meador Ingedf796f82012-10-13 16:45:24 +0000197 }
198};
199
200struct MemMoveChkOpt : public InstFortifiedLibCallOptimization {
Craig Topper3e4c6972014-03-05 09:10:37 +0000201 Value *callOptimizer(Function *Callee, CallInst *CI,
202 IRBuilder<> &B) override {
Meador Ingedf796f82012-10-13 16:45:24 +0000203 this->CI = CI;
204 FunctionType *FT = Callee->getFunctionType();
Chandler Carruth7ec50852012-11-01 08:07:29 +0000205 LLVMContext &Context = CI->getParent()->getContext();
Meador Ingedf796f82012-10-13 16:45:24 +0000206
207 // Check if this has the right signature.
208 if (FT->getNumParams() != 4 || FT->getReturnType() != FT->getParamType(0) ||
209 !FT->getParamType(0)->isPointerTy() ||
210 !FT->getParamType(1)->isPointerTy() ||
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000211 FT->getParamType(2) != DL->getIntPtrType(Context) ||
212 FT->getParamType(3) != DL->getIntPtrType(Context))
Craig Topperf40110f2014-04-25 05:29:35 +0000213 return nullptr;
Meador Ingedf796f82012-10-13 16:45:24 +0000214
215 if (isFoldable(3, 2, false)) {
216 B.CreateMemMove(CI->getArgOperand(0), CI->getArgOperand(1),
217 CI->getArgOperand(2), 1);
218 return CI->getArgOperand(0);
219 }
Craig Topperf40110f2014-04-25 05:29:35 +0000220 return nullptr;
Meador Ingedf796f82012-10-13 16:45:24 +0000221 }
222};
223
224struct MemSetChkOpt : public InstFortifiedLibCallOptimization {
Craig Topper3e4c6972014-03-05 09:10:37 +0000225 Value *callOptimizer(Function *Callee, CallInst *CI,
226 IRBuilder<> &B) override {
Meador Ingedf796f82012-10-13 16:45:24 +0000227 this->CI = CI;
228 FunctionType *FT = Callee->getFunctionType();
Chandler Carruth7ec50852012-11-01 08:07:29 +0000229 LLVMContext &Context = CI->getParent()->getContext();
Meador Ingedf796f82012-10-13 16:45:24 +0000230
231 // Check if this has the right signature.
232 if (FT->getNumParams() != 4 || FT->getReturnType() != FT->getParamType(0) ||
233 !FT->getParamType(0)->isPointerTy() ||
234 !FT->getParamType(1)->isIntegerTy() ||
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000235 FT->getParamType(2) != DL->getIntPtrType(Context) ||
236 FT->getParamType(3) != DL->getIntPtrType(Context))
Craig Topperf40110f2014-04-25 05:29:35 +0000237 return nullptr;
Meador Ingedf796f82012-10-13 16:45:24 +0000238
239 if (isFoldable(3, 2, false)) {
240 Value *Val = B.CreateIntCast(CI->getArgOperand(1), B.getInt8Ty(),
241 false);
242 B.CreateMemSet(CI->getArgOperand(0), Val, CI->getArgOperand(2), 1);
243 return CI->getArgOperand(0);
244 }
Craig Topperf40110f2014-04-25 05:29:35 +0000245 return nullptr;
Meador Ingedf796f82012-10-13 16:45:24 +0000246 }
247};
248
249struct StrCpyChkOpt : public InstFortifiedLibCallOptimization {
Craig Topper3e4c6972014-03-05 09:10:37 +0000250 Value *callOptimizer(Function *Callee, CallInst *CI,
251 IRBuilder<> &B) override {
Meador Ingedf796f82012-10-13 16:45:24 +0000252 this->CI = CI;
253 StringRef Name = Callee->getName();
254 FunctionType *FT = Callee->getFunctionType();
255 LLVMContext &Context = CI->getParent()->getContext();
256
257 // Check if this has the right signature.
258 if (FT->getNumParams() != 3 ||
259 FT->getReturnType() != FT->getParamType(0) ||
260 FT->getParamType(0) != FT->getParamType(1) ||
261 FT->getParamType(0) != Type::getInt8PtrTy(Context) ||
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000262 FT->getParamType(2) != DL->getIntPtrType(Context))
Craig Topperf40110f2014-04-25 05:29:35 +0000263 return nullptr;
Meador Ingedf796f82012-10-13 16:45:24 +0000264
Meador Inge000dbcc2012-10-18 18:12:40 +0000265 Value *Dst = CI->getArgOperand(0), *Src = CI->getArgOperand(1);
266 if (Dst == Src) // __strcpy_chk(x,x) -> x
267 return Src;
268
Meador Ingedf796f82012-10-13 16:45:24 +0000269 // If a) we don't have any length information, or b) we know this will
Meador Ingecdb2ca52012-10-31 00:20:51 +0000270 // fit then just lower to a plain strcpy. Otherwise we'll keep our
271 // strcpy_chk call which may fail at runtime if the size is too long.
Meador Ingedf796f82012-10-13 16:45:24 +0000272 // TODO: It might be nice to get a maximum length out of the possible
273 // string lengths for varying.
274 if (isFoldable(2, 1, true)) {
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000275 Value *Ret = EmitStrCpy(Dst, Src, B, DL, TLI, Name.substr(2, 6));
Meador Inge000dbcc2012-10-18 18:12:40 +0000276 return Ret;
277 } else {
278 // Maybe we can stil fold __strcpy_chk to __memcpy_chk.
279 uint64_t Len = GetStringLength(Src);
Craig Topperf40110f2014-04-25 05:29:35 +0000280 if (Len == 0) return nullptr;
Meador Inge000dbcc2012-10-18 18:12:40 +0000281
282 // This optimization require DataLayout.
Craig Topperf40110f2014-04-25 05:29:35 +0000283 if (!DL) return nullptr;
Meador Inge000dbcc2012-10-18 18:12:40 +0000284
285 Value *Ret =
286 EmitMemCpyChk(Dst, Src,
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000287 ConstantInt::get(DL->getIntPtrType(Context), Len),
288 CI->getArgOperand(2), B, DL, TLI);
Meador Ingedf796f82012-10-13 16:45:24 +0000289 return Ret;
290 }
Craig Topperf40110f2014-04-25 05:29:35 +0000291 return nullptr;
Meador Ingedf796f82012-10-13 16:45:24 +0000292 }
293};
294
Meador Ingecdb2ca52012-10-31 00:20:51 +0000295struct StpCpyChkOpt : public InstFortifiedLibCallOptimization {
Craig Topper3e4c6972014-03-05 09:10:37 +0000296 Value *callOptimizer(Function *Callee, CallInst *CI,
297 IRBuilder<> &B) override {
Meador Ingecdb2ca52012-10-31 00:20:51 +0000298 this->CI = CI;
299 StringRef Name = Callee->getName();
300 FunctionType *FT = Callee->getFunctionType();
301 LLVMContext &Context = CI->getParent()->getContext();
302
303 // Check if this has the right signature.
304 if (FT->getNumParams() != 3 ||
305 FT->getReturnType() != FT->getParamType(0) ||
306 FT->getParamType(0) != FT->getParamType(1) ||
307 FT->getParamType(0) != Type::getInt8PtrTy(Context) ||
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000308 FT->getParamType(2) != DL->getIntPtrType(FT->getParamType(0)))
Craig Topperf40110f2014-04-25 05:29:35 +0000309 return nullptr;
Meador Ingecdb2ca52012-10-31 00:20:51 +0000310
311 Value *Dst = CI->getArgOperand(0), *Src = CI->getArgOperand(1);
312 if (Dst == Src) { // stpcpy(x,x) -> x+strlen(x)
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000313 Value *StrLen = EmitStrLen(Src, B, DL, TLI);
Craig Topperf40110f2014-04-25 05:29:35 +0000314 return StrLen ? B.CreateInBoundsGEP(Dst, StrLen) : nullptr;
Meador Ingecdb2ca52012-10-31 00:20:51 +0000315 }
316
317 // If a) we don't have any length information, or b) we know this will
318 // fit then just lower to a plain stpcpy. Otherwise we'll keep our
319 // stpcpy_chk call which may fail at runtime if the size is too long.
320 // TODO: It might be nice to get a maximum length out of the possible
321 // string lengths for varying.
322 if (isFoldable(2, 1, true)) {
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000323 Value *Ret = EmitStrCpy(Dst, Src, B, DL, TLI, Name.substr(2, 6));
Meador Ingecdb2ca52012-10-31 00:20:51 +0000324 return Ret;
325 } else {
326 // Maybe we can stil fold __stpcpy_chk to __memcpy_chk.
327 uint64_t Len = GetStringLength(Src);
Craig Topperf40110f2014-04-25 05:29:35 +0000328 if (Len == 0) return nullptr;
Meador Ingecdb2ca52012-10-31 00:20:51 +0000329
330 // This optimization require DataLayout.
Craig Topperf40110f2014-04-25 05:29:35 +0000331 if (!DL) return nullptr;
Meador Ingecdb2ca52012-10-31 00:20:51 +0000332
333 Type *PT = FT->getParamType(0);
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000334 Value *LenV = ConstantInt::get(DL->getIntPtrType(PT), Len);
Meador Ingecdb2ca52012-10-31 00:20:51 +0000335 Value *DstEnd = B.CreateGEP(Dst,
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000336 ConstantInt::get(DL->getIntPtrType(PT),
Meador Ingecdb2ca52012-10-31 00:20:51 +0000337 Len - 1));
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000338 if (!EmitMemCpyChk(Dst, Src, LenV, CI->getArgOperand(2), B, DL, TLI))
Craig Topperf40110f2014-04-25 05:29:35 +0000339 return nullptr;
Meador Ingecdb2ca52012-10-31 00:20:51 +0000340 return DstEnd;
341 }
Craig Topperf40110f2014-04-25 05:29:35 +0000342 return nullptr;
Meador Ingecdb2ca52012-10-31 00:20:51 +0000343 }
344};
345
Meador Ingedf796f82012-10-13 16:45:24 +0000346struct StrNCpyChkOpt : public InstFortifiedLibCallOptimization {
Craig Topper3e4c6972014-03-05 09:10:37 +0000347 Value *callOptimizer(Function *Callee, CallInst *CI,
348 IRBuilder<> &B) override {
Meador Ingedf796f82012-10-13 16:45:24 +0000349 this->CI = CI;
350 StringRef Name = Callee->getName();
351 FunctionType *FT = Callee->getFunctionType();
352 LLVMContext &Context = CI->getParent()->getContext();
353
354 // Check if this has the right signature.
355 if (FT->getNumParams() != 4 || FT->getReturnType() != FT->getParamType(0) ||
356 FT->getParamType(0) != FT->getParamType(1) ||
357 FT->getParamType(0) != Type::getInt8PtrTy(Context) ||
358 !FT->getParamType(2)->isIntegerTy() ||
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000359 FT->getParamType(3) != DL->getIntPtrType(Context))
Craig Topperf40110f2014-04-25 05:29:35 +0000360 return nullptr;
Meador Ingedf796f82012-10-13 16:45:24 +0000361
362 if (isFoldable(3, 2, false)) {
363 Value *Ret = EmitStrNCpy(CI->getArgOperand(0), CI->getArgOperand(1),
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000364 CI->getArgOperand(2), B, DL, TLI,
Meador Ingedf796f82012-10-13 16:45:24 +0000365 Name.substr(2, 7));
366 return Ret;
367 }
Craig Topperf40110f2014-04-25 05:29:35 +0000368 return nullptr;
Meador Ingedf796f82012-10-13 16:45:24 +0000369 }
370};
371
Meador Inge7fb2f732012-10-13 16:45:32 +0000372//===----------------------------------------------------------------------===//
373// String and Memory Library Call Optimizations
374//===----------------------------------------------------------------------===//
375
376struct StrCatOpt : public LibCallOptimization {
Craig Topper3e4c6972014-03-05 09:10:37 +0000377 Value *callOptimizer(Function *Callee, CallInst *CI,
378 IRBuilder<> &B) override {
Meador Inge7fb2f732012-10-13 16:45:32 +0000379 // Verify the "strcat" function prototype.
380 FunctionType *FT = Callee->getFunctionType();
381 if (FT->getNumParams() != 2 ||
382 FT->getReturnType() != B.getInt8PtrTy() ||
383 FT->getParamType(0) != FT->getReturnType() ||
384 FT->getParamType(1) != FT->getReturnType())
Craig Topperf40110f2014-04-25 05:29:35 +0000385 return nullptr;
Meador Inge7fb2f732012-10-13 16:45:32 +0000386
387 // Extract some information from the instruction
388 Value *Dst = CI->getArgOperand(0);
389 Value *Src = CI->getArgOperand(1);
390
391 // See if we can get the length of the input string.
392 uint64_t Len = GetStringLength(Src);
Craig Topperf40110f2014-04-25 05:29:35 +0000393 if (Len == 0) return nullptr;
Meador Inge7fb2f732012-10-13 16:45:32 +0000394 --Len; // Unbias length.
395
396 // Handle the simple, do-nothing case: strcat(x, "") -> x
397 if (Len == 0)
398 return Dst;
399
400 // These optimizations require DataLayout.
Craig Topperf40110f2014-04-25 05:29:35 +0000401 if (!DL) return nullptr;
Meador Inge7fb2f732012-10-13 16:45:32 +0000402
403 return emitStrLenMemCpy(Src, Dst, Len, B);
404 }
405
406 Value *emitStrLenMemCpy(Value *Src, Value *Dst, uint64_t Len,
407 IRBuilder<> &B) {
408 // We need to find the end of the destination string. That's where the
409 // memory is to be moved to. We just generate a call to strlen.
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000410 Value *DstLen = EmitStrLen(Dst, B, DL, TLI);
Meador Inge7fb2f732012-10-13 16:45:32 +0000411 if (!DstLen)
Craig Topperf40110f2014-04-25 05:29:35 +0000412 return nullptr;
Meador Inge7fb2f732012-10-13 16:45:32 +0000413
414 // Now that we have the destination's length, we must index into the
415 // destination's pointer to get the actual memcpy destination (end of
416 // the string .. we're concatenating).
417 Value *CpyDst = B.CreateGEP(Dst, DstLen, "endptr");
418
419 // We have enough information to now generate the memcpy call to do the
420 // concatenation for us. Make a memcpy to copy the nul byte with align = 1.
421 B.CreateMemCpy(CpyDst, Src,
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000422 ConstantInt::get(DL->getIntPtrType(*Context), Len + 1), 1);
Meador Inge7fb2f732012-10-13 16:45:32 +0000423 return Dst;
424 }
425};
426
427struct StrNCatOpt : public StrCatOpt {
Craig Topper3e4c6972014-03-05 09:10:37 +0000428 Value *callOptimizer(Function *Callee, CallInst *CI,
429 IRBuilder<> &B) override {
Meador Inge7fb2f732012-10-13 16:45:32 +0000430 // Verify the "strncat" function prototype.
431 FunctionType *FT = Callee->getFunctionType();
432 if (FT->getNumParams() != 3 ||
433 FT->getReturnType() != B.getInt8PtrTy() ||
434 FT->getParamType(0) != FT->getReturnType() ||
435 FT->getParamType(1) != FT->getReturnType() ||
436 !FT->getParamType(2)->isIntegerTy())
Craig Topperf40110f2014-04-25 05:29:35 +0000437 return nullptr;
Meador Inge7fb2f732012-10-13 16:45:32 +0000438
439 // Extract some information from the instruction
440 Value *Dst = CI->getArgOperand(0);
441 Value *Src = CI->getArgOperand(1);
442 uint64_t Len;
443
444 // We don't do anything if length is not constant
445 if (ConstantInt *LengthArg = dyn_cast<ConstantInt>(CI->getArgOperand(2)))
446 Len = LengthArg->getZExtValue();
447 else
Craig Topperf40110f2014-04-25 05:29:35 +0000448 return nullptr;
Meador Inge7fb2f732012-10-13 16:45:32 +0000449
450 // See if we can get the length of the input string.
451 uint64_t SrcLen = GetStringLength(Src);
Craig Topperf40110f2014-04-25 05:29:35 +0000452 if (SrcLen == 0) return nullptr;
Meador Inge7fb2f732012-10-13 16:45:32 +0000453 --SrcLen; // Unbias length.
454
455 // Handle the simple, do-nothing cases:
456 // strncat(x, "", c) -> x
457 // strncat(x, c, 0) -> x
458 if (SrcLen == 0 || Len == 0) return Dst;
459
460 // These optimizations require DataLayout.
Craig Topperf40110f2014-04-25 05:29:35 +0000461 if (!DL) return nullptr;
Meador Inge7fb2f732012-10-13 16:45:32 +0000462
463 // We don't optimize this case
Craig Topperf40110f2014-04-25 05:29:35 +0000464 if (Len < SrcLen) return nullptr;
Meador Inge7fb2f732012-10-13 16:45:32 +0000465
466 // strncat(x, s, c) -> strcat(x, s)
467 // s is constant so the strcat can be optimized further
468 return emitStrLenMemCpy(Src, Dst, SrcLen, B);
469 }
470};
471
Meador Inge17418502012-10-13 16:45:37 +0000472struct StrChrOpt : public LibCallOptimization {
Craig Topper3e4c6972014-03-05 09:10:37 +0000473 Value *callOptimizer(Function *Callee, CallInst *CI,
474 IRBuilder<> &B) override {
Meador Inge17418502012-10-13 16:45:37 +0000475 // Verify the "strchr" function prototype.
476 FunctionType *FT = Callee->getFunctionType();
477 if (FT->getNumParams() != 2 ||
478 FT->getReturnType() != B.getInt8PtrTy() ||
479 FT->getParamType(0) != FT->getReturnType() ||
480 !FT->getParamType(1)->isIntegerTy(32))
Craig Topperf40110f2014-04-25 05:29:35 +0000481 return nullptr;
Meador Inge17418502012-10-13 16:45:37 +0000482
483 Value *SrcStr = CI->getArgOperand(0);
484
485 // If the second operand is non-constant, see if we can compute the length
486 // of the input string and turn this into memchr.
487 ConstantInt *CharC = dyn_cast<ConstantInt>(CI->getArgOperand(1));
Craig Topperf40110f2014-04-25 05:29:35 +0000488 if (!CharC) {
Meador Inge17418502012-10-13 16:45:37 +0000489 // These optimizations require DataLayout.
Craig Topperf40110f2014-04-25 05:29:35 +0000490 if (!DL) return nullptr;
Meador Inge17418502012-10-13 16:45:37 +0000491
492 uint64_t Len = GetStringLength(SrcStr);
493 if (Len == 0 || !FT->getParamType(1)->isIntegerTy(32))// memchr needs i32.
Craig Topperf40110f2014-04-25 05:29:35 +0000494 return nullptr;
Meador Inge17418502012-10-13 16:45:37 +0000495
496 return EmitMemChr(SrcStr, CI->getArgOperand(1), // include nul.
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000497 ConstantInt::get(DL->getIntPtrType(*Context), Len),
498 B, DL, TLI);
Meador Inge17418502012-10-13 16:45:37 +0000499 }
500
501 // Otherwise, the character is a constant, see if the first argument is
502 // a string literal. If so, we can constant fold.
503 StringRef Str;
Kai Nackea56bb782014-02-04 05:55:16 +0000504 if (!getConstantStringInfo(SrcStr, Str)) {
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000505 if (DL && CharC->isZero()) // strchr(p, 0) -> p + strlen(p)
506 return B.CreateGEP(SrcStr, EmitStrLen(SrcStr, B, DL, TLI), "strchr");
Craig Topperf40110f2014-04-25 05:29:35 +0000507 return nullptr;
Kai Nackea56bb782014-02-04 05:55:16 +0000508 }
Meador Inge17418502012-10-13 16:45:37 +0000509
510 // Compute the offset, make sure to handle the case when we're searching for
511 // zero (a weird way to spell strlen).
Yunzhong Gao05efa232013-08-21 22:11:15 +0000512 size_t I = (0xFF & CharC->getSExtValue()) == 0 ?
Meador Inge17418502012-10-13 16:45:37 +0000513 Str.size() : Str.find(CharC->getSExtValue());
514 if (I == StringRef::npos) // Didn't find the char. strchr returns null.
515 return Constant::getNullValue(CI->getType());
516
517 // strchr(s+n,c) -> gep(s+n+i,c)
518 return B.CreateGEP(SrcStr, B.getInt64(I), "strchr");
519 }
520};
521
522struct StrRChrOpt : public LibCallOptimization {
Craig Topper3e4c6972014-03-05 09:10:37 +0000523 Value *callOptimizer(Function *Callee, CallInst *CI,
524 IRBuilder<> &B) override {
Meador Inge17418502012-10-13 16:45:37 +0000525 // Verify the "strrchr" function prototype.
526 FunctionType *FT = Callee->getFunctionType();
527 if (FT->getNumParams() != 2 ||
528 FT->getReturnType() != B.getInt8PtrTy() ||
529 FT->getParamType(0) != FT->getReturnType() ||
530 !FT->getParamType(1)->isIntegerTy(32))
Craig Topperf40110f2014-04-25 05:29:35 +0000531 return nullptr;
Meador Inge17418502012-10-13 16:45:37 +0000532
533 Value *SrcStr = CI->getArgOperand(0);
534 ConstantInt *CharC = dyn_cast<ConstantInt>(CI->getArgOperand(1));
535
536 // Cannot fold anything if we're not looking for a constant.
537 if (!CharC)
Craig Topperf40110f2014-04-25 05:29:35 +0000538 return nullptr;
Meador Inge17418502012-10-13 16:45:37 +0000539
540 StringRef Str;
541 if (!getConstantStringInfo(SrcStr, Str)) {
542 // strrchr(s, 0) -> strchr(s, 0)
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000543 if (DL && CharC->isZero())
544 return EmitStrChr(SrcStr, '\0', B, DL, TLI);
Craig Topperf40110f2014-04-25 05:29:35 +0000545 return nullptr;
Meador Inge17418502012-10-13 16:45:37 +0000546 }
547
548 // Compute the offset.
Yunzhong Gao05efa232013-08-21 22:11:15 +0000549 size_t I = (0xFF & CharC->getSExtValue()) == 0 ?
Meador Inge17418502012-10-13 16:45:37 +0000550 Str.size() : Str.rfind(CharC->getSExtValue());
551 if (I == StringRef::npos) // Didn't find the char. Return null.
552 return Constant::getNullValue(CI->getType());
553
554 // strrchr(s+n,c) -> gep(s+n+i,c)
555 return B.CreateGEP(SrcStr, B.getInt64(I), "strrchr");
556 }
557};
558
Meador Inge40b6fac2012-10-15 03:47:37 +0000559struct StrCmpOpt : public LibCallOptimization {
Craig Topper3e4c6972014-03-05 09:10:37 +0000560 Value *callOptimizer(Function *Callee, CallInst *CI,
561 IRBuilder<> &B) override {
Meador Inge40b6fac2012-10-15 03:47:37 +0000562 // Verify the "strcmp" function prototype.
563 FunctionType *FT = Callee->getFunctionType();
564 if (FT->getNumParams() != 2 ||
565 !FT->getReturnType()->isIntegerTy(32) ||
566 FT->getParamType(0) != FT->getParamType(1) ||
567 FT->getParamType(0) != B.getInt8PtrTy())
Craig Topperf40110f2014-04-25 05:29:35 +0000568 return nullptr;
Meador Inge40b6fac2012-10-15 03:47:37 +0000569
570 Value *Str1P = CI->getArgOperand(0), *Str2P = CI->getArgOperand(1);
571 if (Str1P == Str2P) // strcmp(x,x) -> 0
572 return ConstantInt::get(CI->getType(), 0);
573
574 StringRef Str1, Str2;
575 bool HasStr1 = getConstantStringInfo(Str1P, Str1);
576 bool HasStr2 = getConstantStringInfo(Str2P, Str2);
577
578 // strcmp(x, y) -> cnst (if both x and y are constant strings)
579 if (HasStr1 && HasStr2)
580 return ConstantInt::get(CI->getType(), Str1.compare(Str2));
581
582 if (HasStr1 && Str1.empty()) // strcmp("", x) -> -*x
583 return B.CreateNeg(B.CreateZExt(B.CreateLoad(Str2P, "strcmpload"),
584 CI->getType()));
585
586 if (HasStr2 && Str2.empty()) // strcmp(x,"") -> *x
587 return B.CreateZExt(B.CreateLoad(Str1P, "strcmpload"), CI->getType());
588
589 // strcmp(P, "x") -> memcmp(P, "x", 2)
590 uint64_t Len1 = GetStringLength(Str1P);
591 uint64_t Len2 = GetStringLength(Str2P);
592 if (Len1 && Len2) {
593 // These optimizations require DataLayout.
Craig Topperf40110f2014-04-25 05:29:35 +0000594 if (!DL) return nullptr;
Meador Inge40b6fac2012-10-15 03:47:37 +0000595
596 return EmitMemCmp(Str1P, Str2P,
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000597 ConstantInt::get(DL->getIntPtrType(*Context),
598 std::min(Len1, Len2)), B, DL, TLI);
Meador Inge40b6fac2012-10-15 03:47:37 +0000599 }
600
Craig Topperf40110f2014-04-25 05:29:35 +0000601 return nullptr;
Meador Inge40b6fac2012-10-15 03:47:37 +0000602 }
603};
604
605struct StrNCmpOpt : public LibCallOptimization {
Craig Topper3e4c6972014-03-05 09:10:37 +0000606 Value *callOptimizer(Function *Callee, CallInst *CI,
607 IRBuilder<> &B) override {
Meador Inge40b6fac2012-10-15 03:47:37 +0000608 // Verify the "strncmp" function prototype.
609 FunctionType *FT = Callee->getFunctionType();
610 if (FT->getNumParams() != 3 ||
611 !FT->getReturnType()->isIntegerTy(32) ||
612 FT->getParamType(0) != FT->getParamType(1) ||
613 FT->getParamType(0) != B.getInt8PtrTy() ||
614 !FT->getParamType(2)->isIntegerTy())
Craig Topperf40110f2014-04-25 05:29:35 +0000615 return nullptr;
Meador Inge40b6fac2012-10-15 03:47:37 +0000616
617 Value *Str1P = CI->getArgOperand(0), *Str2P = CI->getArgOperand(1);
618 if (Str1P == Str2P) // strncmp(x,x,n) -> 0
619 return ConstantInt::get(CI->getType(), 0);
620
621 // Get the length argument if it is constant.
622 uint64_t Length;
623 if (ConstantInt *LengthArg = dyn_cast<ConstantInt>(CI->getArgOperand(2)))
624 Length = LengthArg->getZExtValue();
625 else
Craig Topperf40110f2014-04-25 05:29:35 +0000626 return nullptr;
Meador Inge40b6fac2012-10-15 03:47:37 +0000627
628 if (Length == 0) // strncmp(x,y,0) -> 0
629 return ConstantInt::get(CI->getType(), 0);
630
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000631 if (DL && Length == 1) // strncmp(x,y,1) -> memcmp(x,y,1)
632 return EmitMemCmp(Str1P, Str2P, CI->getArgOperand(2), B, DL, TLI);
Meador Inge40b6fac2012-10-15 03:47:37 +0000633
634 StringRef Str1, Str2;
635 bool HasStr1 = getConstantStringInfo(Str1P, Str1);
636 bool HasStr2 = getConstantStringInfo(Str2P, Str2);
637
638 // strncmp(x, y) -> cnst (if both x and y are constant strings)
639 if (HasStr1 && HasStr2) {
640 StringRef SubStr1 = Str1.substr(0, Length);
641 StringRef SubStr2 = Str2.substr(0, Length);
642 return ConstantInt::get(CI->getType(), SubStr1.compare(SubStr2));
643 }
644
645 if (HasStr1 && Str1.empty()) // strncmp("", x, n) -> -*x
646 return B.CreateNeg(B.CreateZExt(B.CreateLoad(Str2P, "strcmpload"),
647 CI->getType()));
648
649 if (HasStr2 && Str2.empty()) // strncmp(x, "", n) -> *x
650 return B.CreateZExt(B.CreateLoad(Str1P, "strcmpload"), CI->getType());
651
Craig Topperf40110f2014-04-25 05:29:35 +0000652 return nullptr;
Meador Inge40b6fac2012-10-15 03:47:37 +0000653 }
654};
655
Meador Inge000dbcc2012-10-18 18:12:40 +0000656struct StrCpyOpt : public LibCallOptimization {
Craig Topper3e4c6972014-03-05 09:10:37 +0000657 Value *callOptimizer(Function *Callee, CallInst *CI,
658 IRBuilder<> &B) override {
Meador Inge000dbcc2012-10-18 18:12:40 +0000659 // Verify the "strcpy" function prototype.
660 FunctionType *FT = Callee->getFunctionType();
661 if (FT->getNumParams() != 2 ||
662 FT->getReturnType() != FT->getParamType(0) ||
663 FT->getParamType(0) != FT->getParamType(1) ||
664 FT->getParamType(0) != B.getInt8PtrTy())
Craig Topperf40110f2014-04-25 05:29:35 +0000665 return nullptr;
Meador Inge000dbcc2012-10-18 18:12:40 +0000666
667 Value *Dst = CI->getArgOperand(0), *Src = CI->getArgOperand(1);
668 if (Dst == Src) // strcpy(x,x) -> x
669 return Src;
670
671 // These optimizations require DataLayout.
Craig Topperf40110f2014-04-25 05:29:35 +0000672 if (!DL) return nullptr;
Meador Inge000dbcc2012-10-18 18:12:40 +0000673
674 // See if we can get the length of the input string.
675 uint64_t Len = GetStringLength(Src);
Craig Topperf40110f2014-04-25 05:29:35 +0000676 if (Len == 0) return nullptr;
Meador Inge000dbcc2012-10-18 18:12:40 +0000677
678 // We have enough information to now generate the memcpy call to do the
679 // copy for us. Make a memcpy to copy the nul byte with align = 1.
680 B.CreateMemCpy(Dst, Src,
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000681 ConstantInt::get(DL->getIntPtrType(*Context), Len), 1);
Meador Inge000dbcc2012-10-18 18:12:40 +0000682 return Dst;
683 }
684};
685
Meador Inge9a6a1902012-10-31 00:20:56 +0000686struct StpCpyOpt: public LibCallOptimization {
Craig Topper3e4c6972014-03-05 09:10:37 +0000687 Value *callOptimizer(Function *Callee, CallInst *CI,
688 IRBuilder<> &B) override {
Meador Inge9a6a1902012-10-31 00:20:56 +0000689 // Verify the "stpcpy" function prototype.
690 FunctionType *FT = Callee->getFunctionType();
691 if (FT->getNumParams() != 2 ||
692 FT->getReturnType() != FT->getParamType(0) ||
693 FT->getParamType(0) != FT->getParamType(1) ||
694 FT->getParamType(0) != B.getInt8PtrTy())
Craig Topperf40110f2014-04-25 05:29:35 +0000695 return nullptr;
Meador Inge9a6a1902012-10-31 00:20:56 +0000696
697 // These optimizations require DataLayout.
Craig Topperf40110f2014-04-25 05:29:35 +0000698 if (!DL) return nullptr;
Meador Inge9a6a1902012-10-31 00:20:56 +0000699
700 Value *Dst = CI->getArgOperand(0), *Src = CI->getArgOperand(1);
701 if (Dst == Src) { // stpcpy(x,x) -> x+strlen(x)
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000702 Value *StrLen = EmitStrLen(Src, B, DL, TLI);
Craig Topperf40110f2014-04-25 05:29:35 +0000703 return StrLen ? B.CreateInBoundsGEP(Dst, StrLen) : nullptr;
Meador Inge9a6a1902012-10-31 00:20:56 +0000704 }
705
706 // See if we can get the length of the input string.
707 uint64_t Len = GetStringLength(Src);
Craig Topperf40110f2014-04-25 05:29:35 +0000708 if (Len == 0) return nullptr;
Meador Inge9a6a1902012-10-31 00:20:56 +0000709
710 Type *PT = FT->getParamType(0);
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000711 Value *LenV = ConstantInt::get(DL->getIntPtrType(PT), Len);
Meador Inge9a6a1902012-10-31 00:20:56 +0000712 Value *DstEnd = B.CreateGEP(Dst,
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000713 ConstantInt::get(DL->getIntPtrType(PT),
Meador Inge9a6a1902012-10-31 00:20:56 +0000714 Len - 1));
715
716 // We have enough information to now generate the memcpy call to do the
717 // copy for us. Make a memcpy to copy the nul byte with align = 1.
718 B.CreateMemCpy(Dst, Src, LenV, 1);
719 return DstEnd;
720 }
721};
722
Meador Inge067294b2012-10-31 03:33:00 +0000723struct StrNCpyOpt : public LibCallOptimization {
Craig Topper3e4c6972014-03-05 09:10:37 +0000724 Value *callOptimizer(Function *Callee, CallInst *CI,
725 IRBuilder<> &B) override {
Meador Inge067294b2012-10-31 03:33:00 +0000726 FunctionType *FT = Callee->getFunctionType();
727 if (FT->getNumParams() != 3 || FT->getReturnType() != FT->getParamType(0) ||
728 FT->getParamType(0) != FT->getParamType(1) ||
729 FT->getParamType(0) != B.getInt8PtrTy() ||
730 !FT->getParamType(2)->isIntegerTy())
Craig Topperf40110f2014-04-25 05:29:35 +0000731 return nullptr;
Meador Inge067294b2012-10-31 03:33:00 +0000732
733 Value *Dst = CI->getArgOperand(0);
734 Value *Src = CI->getArgOperand(1);
735 Value *LenOp = CI->getArgOperand(2);
736
737 // See if we can get the length of the input string.
738 uint64_t SrcLen = GetStringLength(Src);
Craig Topperf40110f2014-04-25 05:29:35 +0000739 if (SrcLen == 0) return nullptr;
Meador Inge067294b2012-10-31 03:33:00 +0000740 --SrcLen;
741
742 if (SrcLen == 0) {
743 // strncpy(x, "", y) -> memset(x, '\0', y, 1)
744 B.CreateMemSet(Dst, B.getInt8('\0'), LenOp, 1);
745 return Dst;
746 }
747
748 uint64_t Len;
749 if (ConstantInt *LengthArg = dyn_cast<ConstantInt>(LenOp))
750 Len = LengthArg->getZExtValue();
751 else
Craig Topperf40110f2014-04-25 05:29:35 +0000752 return nullptr;
Meador Inge067294b2012-10-31 03:33:00 +0000753
754 if (Len == 0) return Dst; // strncpy(x, y, 0) -> x
755
756 // These optimizations require DataLayout.
Craig Topperf40110f2014-04-25 05:29:35 +0000757 if (!DL) return nullptr;
Meador Inge067294b2012-10-31 03:33:00 +0000758
759 // Let strncpy handle the zero padding
Craig Topperf40110f2014-04-25 05:29:35 +0000760 if (Len > SrcLen+1) return nullptr;
Meador Inge067294b2012-10-31 03:33:00 +0000761
762 Type *PT = FT->getParamType(0);
763 // strncpy(x, s, c) -> memcpy(x, s, c, 1) [s and c are constant]
764 B.CreateMemCpy(Dst, Src,
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000765 ConstantInt::get(DL->getIntPtrType(PT), Len), 1);
Meador Inge067294b2012-10-31 03:33:00 +0000766
767 return Dst;
768 }
769};
770
Meador Inged589ac62012-10-31 03:33:06 +0000771struct StrLenOpt : public LibCallOptimization {
Craig Topper3e4c6972014-03-05 09:10:37 +0000772 bool ignoreCallingConv() override { return true; }
773 Value *callOptimizer(Function *Callee, CallInst *CI,
774 IRBuilder<> &B) override {
Meador Inged589ac62012-10-31 03:33:06 +0000775 FunctionType *FT = Callee->getFunctionType();
776 if (FT->getNumParams() != 1 ||
777 FT->getParamType(0) != B.getInt8PtrTy() ||
778 !FT->getReturnType()->isIntegerTy())
Craig Topperf40110f2014-04-25 05:29:35 +0000779 return nullptr;
Meador Inged589ac62012-10-31 03:33:06 +0000780
781 Value *Src = CI->getArgOperand(0);
782
783 // Constant folding: strlen("xyz") -> 3
784 if (uint64_t Len = GetStringLength(Src))
785 return ConstantInt::get(CI->getType(), Len-1);
786
Nick Lewycky718ada92014-05-02 04:11:45 +0000787 // strlen(x?"foo":"bars") --> x ? 3 : 4
788 if (SelectInst *SI = dyn_cast<SelectInst>(Src)) {
789 uint64_t LenTrue = GetStringLength(SI->getTrueValue());
790 uint64_t LenFalse = GetStringLength(SI->getFalseValue());
791 if (LenTrue && LenFalse) {
792 Context->emitOptimizationRemark(
793 "simplify-libcalls", *Caller, SI->getDebugLoc(),
794 "folded strlen(select) to select of constants");
795 return B.CreateSelect(SI->getCondition(),
796 ConstantInt::get(CI->getType(), LenTrue-1),
797 ConstantInt::get(CI->getType(), LenFalse-1));
798 }
799 }
800
Meador Inged589ac62012-10-31 03:33:06 +0000801 // strlen(x) != 0 --> *x != 0
802 // strlen(x) == 0 --> *x == 0
803 if (isOnlyUsedInZeroEqualityComparison(CI))
804 return B.CreateZExt(B.CreateLoad(Src, "strlenfirst"), CI->getType());
Nick Lewycky718ada92014-05-02 04:11:45 +0000805
Craig Topperf40110f2014-04-25 05:29:35 +0000806 return nullptr;
Meador Inged589ac62012-10-31 03:33:06 +0000807 }
808};
809
Meador Inge6f8e0112012-10-31 04:29:58 +0000810struct StrPBrkOpt : public LibCallOptimization {
Craig Topper3e4c6972014-03-05 09:10:37 +0000811 Value *callOptimizer(Function *Callee, CallInst *CI,
812 IRBuilder<> &B) override {
Meador Inge6f8e0112012-10-31 04:29:58 +0000813 FunctionType *FT = Callee->getFunctionType();
814 if (FT->getNumParams() != 2 ||
815 FT->getParamType(0) != B.getInt8PtrTy() ||
816 FT->getParamType(1) != FT->getParamType(0) ||
817 FT->getReturnType() != FT->getParamType(0))
Craig Topperf40110f2014-04-25 05:29:35 +0000818 return nullptr;
Meador Inge6f8e0112012-10-31 04:29:58 +0000819
820 StringRef S1, S2;
821 bool HasS1 = getConstantStringInfo(CI->getArgOperand(0), S1);
822 bool HasS2 = getConstantStringInfo(CI->getArgOperand(1), S2);
823
824 // strpbrk(s, "") -> NULL
825 // strpbrk("", s) -> NULL
826 if ((HasS1 && S1.empty()) || (HasS2 && S2.empty()))
827 return Constant::getNullValue(CI->getType());
828
829 // Constant folding.
830 if (HasS1 && HasS2) {
831 size_t I = S1.find_first_of(S2);
Matt Arsenaultf631f8c2013-09-10 00:41:53 +0000832 if (I == StringRef::npos) // No match.
Meador Inge6f8e0112012-10-31 04:29:58 +0000833 return Constant::getNullValue(CI->getType());
834
835 return B.CreateGEP(CI->getArgOperand(0), B.getInt64(I), "strpbrk");
836 }
837
838 // strpbrk(s, "a") -> strchr(s, 'a')
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000839 if (DL && HasS2 && S2.size() == 1)
840 return EmitStrChr(CI->getArgOperand(0), S2[0], B, DL, TLI);
Meador Inge6f8e0112012-10-31 04:29:58 +0000841
Craig Topperf40110f2014-04-25 05:29:35 +0000842 return nullptr;
Meador Inge6f8e0112012-10-31 04:29:58 +0000843 }
844};
845
Meador Inge05a625a2012-10-31 14:58:26 +0000846struct StrToOpt : public LibCallOptimization {
Craig Topper3e4c6972014-03-05 09:10:37 +0000847 Value *callOptimizer(Function *Callee, CallInst *CI,
848 IRBuilder<> &B) override {
Meador Inge05a625a2012-10-31 14:58:26 +0000849 FunctionType *FT = Callee->getFunctionType();
850 if ((FT->getNumParams() != 2 && FT->getNumParams() != 3) ||
851 !FT->getParamType(0)->isPointerTy() ||
852 !FT->getParamType(1)->isPointerTy())
Craig Topperf40110f2014-04-25 05:29:35 +0000853 return nullptr;
Meador Inge05a625a2012-10-31 14:58:26 +0000854
855 Value *EndPtr = CI->getArgOperand(1);
856 if (isa<ConstantPointerNull>(EndPtr)) {
857 // With a null EndPtr, this function won't capture the main argument.
858 // It would be readonly too, except that it still may write to errno.
Peter Collingbourne1b97a9c2013-03-02 01:20:18 +0000859 CI->addAttribute(1, Attribute::NoCapture);
Meador Inge05a625a2012-10-31 14:58:26 +0000860 }
861
Craig Topperf40110f2014-04-25 05:29:35 +0000862 return nullptr;
Meador Inge05a625a2012-10-31 14:58:26 +0000863 }
864};
865
Meador Inge489b5d62012-11-08 01:33:50 +0000866struct StrSpnOpt : public LibCallOptimization {
Craig Topper3e4c6972014-03-05 09:10:37 +0000867 Value *callOptimizer(Function *Callee, CallInst *CI,
868 IRBuilder<> &B) override {
Meador Inge489b5d62012-11-08 01:33:50 +0000869 FunctionType *FT = Callee->getFunctionType();
870 if (FT->getNumParams() != 2 ||
871 FT->getParamType(0) != B.getInt8PtrTy() ||
872 FT->getParamType(1) != FT->getParamType(0) ||
873 !FT->getReturnType()->isIntegerTy())
Craig Topperf40110f2014-04-25 05:29:35 +0000874 return nullptr;
Meador Inge489b5d62012-11-08 01:33:50 +0000875
876 StringRef S1, S2;
877 bool HasS1 = getConstantStringInfo(CI->getArgOperand(0), S1);
878 bool HasS2 = getConstantStringInfo(CI->getArgOperand(1), S2);
879
880 // strspn(s, "") -> 0
881 // strspn("", s) -> 0
882 if ((HasS1 && S1.empty()) || (HasS2 && S2.empty()))
883 return Constant::getNullValue(CI->getType());
884
885 // Constant folding.
886 if (HasS1 && HasS2) {
887 size_t Pos = S1.find_first_not_of(S2);
888 if (Pos == StringRef::npos) Pos = S1.size();
889 return ConstantInt::get(CI->getType(), Pos);
890 }
891
Craig Topperf40110f2014-04-25 05:29:35 +0000892 return nullptr;
Meador Inge489b5d62012-11-08 01:33:50 +0000893 }
894};
895
Meador Ingebcd88ef72012-11-10 15:16:48 +0000896struct StrCSpnOpt : public LibCallOptimization {
Craig Topper3e4c6972014-03-05 09:10:37 +0000897 Value *callOptimizer(Function *Callee, CallInst *CI,
898 IRBuilder<> &B) override {
Meador Ingebcd88ef72012-11-10 15:16:48 +0000899 FunctionType *FT = Callee->getFunctionType();
900 if (FT->getNumParams() != 2 ||
901 FT->getParamType(0) != B.getInt8PtrTy() ||
902 FT->getParamType(1) != FT->getParamType(0) ||
903 !FT->getReturnType()->isIntegerTy())
Craig Topperf40110f2014-04-25 05:29:35 +0000904 return nullptr;
Meador Ingebcd88ef72012-11-10 15:16:48 +0000905
906 StringRef S1, S2;
907 bool HasS1 = getConstantStringInfo(CI->getArgOperand(0), S1);
908 bool HasS2 = getConstantStringInfo(CI->getArgOperand(1), S2);
909
910 // strcspn("", s) -> 0
911 if (HasS1 && S1.empty())
912 return Constant::getNullValue(CI->getType());
913
914 // Constant folding.
915 if (HasS1 && HasS2) {
916 size_t Pos = S1.find_first_of(S2);
917 if (Pos == StringRef::npos) Pos = S1.size();
918 return ConstantInt::get(CI->getType(), Pos);
919 }
920
921 // strcspn(s, "") -> strlen(s)
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000922 if (DL && HasS2 && S2.empty())
923 return EmitStrLen(CI->getArgOperand(0), B, DL, TLI);
Meador Ingebcd88ef72012-11-10 15:16:48 +0000924
Craig Topperf40110f2014-04-25 05:29:35 +0000925 return nullptr;
Meador Ingebcd88ef72012-11-10 15:16:48 +0000926 }
927};
928
Meador Inge56edbc92012-11-11 03:51:48 +0000929struct StrStrOpt : public LibCallOptimization {
Craig Topper3e4c6972014-03-05 09:10:37 +0000930 Value *callOptimizer(Function *Callee, CallInst *CI,
931 IRBuilder<> &B) override {
Meador Inge56edbc92012-11-11 03:51:48 +0000932 FunctionType *FT = Callee->getFunctionType();
933 if (FT->getNumParams() != 2 ||
934 !FT->getParamType(0)->isPointerTy() ||
935 !FT->getParamType(1)->isPointerTy() ||
936 !FT->getReturnType()->isPointerTy())
Craig Topperf40110f2014-04-25 05:29:35 +0000937 return nullptr;
Meador Inge56edbc92012-11-11 03:51:48 +0000938
939 // fold strstr(x, x) -> x.
940 if (CI->getArgOperand(0) == CI->getArgOperand(1))
941 return B.CreateBitCast(CI->getArgOperand(0), CI->getType());
942
943 // fold strstr(a, b) == a -> strncmp(a, b, strlen(b)) == 0
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000944 if (DL && isOnlyUsedInEqualityComparison(CI, CI->getArgOperand(0))) {
945 Value *StrLen = EmitStrLen(CI->getArgOperand(1), B, DL, TLI);
Meador Inge56edbc92012-11-11 03:51:48 +0000946 if (!StrLen)
Craig Topperf40110f2014-04-25 05:29:35 +0000947 return nullptr;
Meador Inge56edbc92012-11-11 03:51:48 +0000948 Value *StrNCmp = EmitStrNCmp(CI->getArgOperand(0), CI->getArgOperand(1),
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000949 StrLen, B, DL, TLI);
Meador Inge56edbc92012-11-11 03:51:48 +0000950 if (!StrNCmp)
Craig Topperf40110f2014-04-25 05:29:35 +0000951 return nullptr;
Chandler Carruthcdf47882014-03-09 03:16:01 +0000952 for (auto UI = CI->user_begin(), UE = CI->user_end(); UI != UE;) {
Meador Inge56edbc92012-11-11 03:51:48 +0000953 ICmpInst *Old = cast<ICmpInst>(*UI++);
954 Value *Cmp = B.CreateICmp(Old->getPredicate(), StrNCmp,
955 ConstantInt::getNullValue(StrNCmp->getType()),
956 "cmp");
957 LCS->replaceAllUsesWith(Old, Cmp);
958 }
959 return CI;
960 }
961
962 // See if either input string is a constant string.
963 StringRef SearchStr, ToFindStr;
964 bool HasStr1 = getConstantStringInfo(CI->getArgOperand(0), SearchStr);
965 bool HasStr2 = getConstantStringInfo(CI->getArgOperand(1), ToFindStr);
966
967 // fold strstr(x, "") -> x.
968 if (HasStr2 && ToFindStr.empty())
969 return B.CreateBitCast(CI->getArgOperand(0), CI->getType());
970
971 // If both strings are known, constant fold it.
972 if (HasStr1 && HasStr2) {
Matt Arsenaultf631f8c2013-09-10 00:41:53 +0000973 size_t Offset = SearchStr.find(ToFindStr);
Meador Inge56edbc92012-11-11 03:51:48 +0000974
975 if (Offset == StringRef::npos) // strstr("foo", "bar") -> null
976 return Constant::getNullValue(CI->getType());
977
978 // strstr("abcd", "bc") -> gep((char*)"abcd", 1)
979 Value *Result = CastToCStr(CI->getArgOperand(0), B);
980 Result = B.CreateConstInBoundsGEP1_64(Result, Offset, "strstr");
981 return B.CreateBitCast(Result, CI->getType());
982 }
983
984 // fold strstr(x, "y") -> strchr(x, 'y').
985 if (HasStr2 && ToFindStr.size() == 1) {
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000986 Value *StrChr= EmitStrChr(CI->getArgOperand(0), ToFindStr[0], B, DL, TLI);
Craig Topperf40110f2014-04-25 05:29:35 +0000987 return StrChr ? B.CreateBitCast(StrChr, CI->getType()) : nullptr;
Meador Inge56edbc92012-11-11 03:51:48 +0000988 }
Craig Topperf40110f2014-04-25 05:29:35 +0000989 return nullptr;
Meador Inge56edbc92012-11-11 03:51:48 +0000990 }
991};
992
Meador Inge4d2827c2012-11-11 05:11:20 +0000993struct MemCmpOpt : public LibCallOptimization {
Craig Topper3e4c6972014-03-05 09:10:37 +0000994 Value *callOptimizer(Function *Callee, CallInst *CI,
995 IRBuilder<> &B) override {
Meador Inge4d2827c2012-11-11 05:11:20 +0000996 FunctionType *FT = Callee->getFunctionType();
997 if (FT->getNumParams() != 3 || !FT->getParamType(0)->isPointerTy() ||
998 !FT->getParamType(1)->isPointerTy() ||
999 !FT->getReturnType()->isIntegerTy(32))
Craig Topperf40110f2014-04-25 05:29:35 +00001000 return nullptr;
Meador Inge4d2827c2012-11-11 05:11:20 +00001001
1002 Value *LHS = CI->getArgOperand(0), *RHS = CI->getArgOperand(1);
1003
1004 if (LHS == RHS) // memcmp(s,s,x) -> 0
1005 return Constant::getNullValue(CI->getType());
1006
1007 // Make sure we have a constant length.
1008 ConstantInt *LenC = dyn_cast<ConstantInt>(CI->getArgOperand(2));
Craig Topperf40110f2014-04-25 05:29:35 +00001009 if (!LenC) return nullptr;
Meador Inge4d2827c2012-11-11 05:11:20 +00001010 uint64_t Len = LenC->getZExtValue();
1011
1012 if (Len == 0) // memcmp(s1,s2,0) -> 0
1013 return Constant::getNullValue(CI->getType());
1014
1015 // memcmp(S1,S2,1) -> *(unsigned char*)LHS - *(unsigned char*)RHS
1016 if (Len == 1) {
1017 Value *LHSV = B.CreateZExt(B.CreateLoad(CastToCStr(LHS, B), "lhsc"),
1018 CI->getType(), "lhsv");
1019 Value *RHSV = B.CreateZExt(B.CreateLoad(CastToCStr(RHS, B), "rhsc"),
1020 CI->getType(), "rhsv");
1021 return B.CreateSub(LHSV, RHSV, "chardiff");
1022 }
1023
1024 // Constant folding: memcmp(x, y, l) -> cnst (all arguments are constant)
1025 StringRef LHSStr, RHSStr;
1026 if (getConstantStringInfo(LHS, LHSStr) &&
1027 getConstantStringInfo(RHS, RHSStr)) {
1028 // Make sure we're not reading out-of-bounds memory.
1029 if (Len > LHSStr.size() || Len > RHSStr.size())
Craig Topperf40110f2014-04-25 05:29:35 +00001030 return nullptr;
Meador Ingeb3e91f62012-11-12 14:00:45 +00001031 // Fold the memcmp and normalize the result. This way we get consistent
1032 // results across multiple platforms.
1033 uint64_t Ret = 0;
1034 int Cmp = memcmp(LHSStr.data(), RHSStr.data(), Len);
1035 if (Cmp < 0)
1036 Ret = -1;
1037 else if (Cmp > 0)
1038 Ret = 1;
Meador Inge4d2827c2012-11-11 05:11:20 +00001039 return ConstantInt::get(CI->getType(), Ret);
1040 }
1041
Craig Topperf40110f2014-04-25 05:29:35 +00001042 return nullptr;
Meador Inge4d2827c2012-11-11 05:11:20 +00001043 }
1044};
1045
Meador Ingedd9234a2012-11-11 05:54:34 +00001046struct MemCpyOpt : public LibCallOptimization {
Craig Topper3e4c6972014-03-05 09:10:37 +00001047 Value *callOptimizer(Function *Callee, CallInst *CI,
1048 IRBuilder<> &B) override {
Meador Ingedd9234a2012-11-11 05:54:34 +00001049 // These optimizations require DataLayout.
Craig Topperf40110f2014-04-25 05:29:35 +00001050 if (!DL) return nullptr;
Meador Ingedd9234a2012-11-11 05:54:34 +00001051
1052 FunctionType *FT = Callee->getFunctionType();
1053 if (FT->getNumParams() != 3 || FT->getReturnType() != FT->getParamType(0) ||
1054 !FT->getParamType(0)->isPointerTy() ||
1055 !FT->getParamType(1)->isPointerTy() ||
Rafael Espindola37dc9e12014-02-21 00:06:31 +00001056 FT->getParamType(2) != DL->getIntPtrType(*Context))
Craig Topperf40110f2014-04-25 05:29:35 +00001057 return nullptr;
Meador Ingedd9234a2012-11-11 05:54:34 +00001058
1059 // memcpy(x, y, n) -> llvm.memcpy(x, y, n, 1)
1060 B.CreateMemCpy(CI->getArgOperand(0), CI->getArgOperand(1),
1061 CI->getArgOperand(2), 1);
1062 return CI->getArgOperand(0);
1063 }
1064};
1065
Meador Inge9cf328b2012-11-11 06:22:40 +00001066struct MemMoveOpt : public LibCallOptimization {
Craig Topper3e4c6972014-03-05 09:10:37 +00001067 Value *callOptimizer(Function *Callee, CallInst *CI,
1068 IRBuilder<> &B) override {
Meador Inge9cf328b2012-11-11 06:22:40 +00001069 // These optimizations require DataLayout.
Craig Topperf40110f2014-04-25 05:29:35 +00001070 if (!DL) return nullptr;
Meador Inge9cf328b2012-11-11 06:22:40 +00001071
1072 FunctionType *FT = Callee->getFunctionType();
1073 if (FT->getNumParams() != 3 || FT->getReturnType() != FT->getParamType(0) ||
1074 !FT->getParamType(0)->isPointerTy() ||
1075 !FT->getParamType(1)->isPointerTy() ||
Rafael Espindola37dc9e12014-02-21 00:06:31 +00001076 FT->getParamType(2) != DL->getIntPtrType(*Context))
Craig Topperf40110f2014-04-25 05:29:35 +00001077 return nullptr;
Meador Inge9cf328b2012-11-11 06:22:40 +00001078
1079 // memmove(x, y, n) -> llvm.memmove(x, y, n, 1)
1080 B.CreateMemMove(CI->getArgOperand(0), CI->getArgOperand(1),
1081 CI->getArgOperand(2), 1);
1082 return CI->getArgOperand(0);
1083 }
1084};
1085
Meador Inged4825782012-11-11 06:49:03 +00001086struct MemSetOpt : public LibCallOptimization {
Craig Topper3e4c6972014-03-05 09:10:37 +00001087 Value *callOptimizer(Function *Callee, CallInst *CI,
1088 IRBuilder<> &B) override {
Meador Inged4825782012-11-11 06:49:03 +00001089 // These optimizations require DataLayout.
Craig Topperf40110f2014-04-25 05:29:35 +00001090 if (!DL) return nullptr;
Meador Inged4825782012-11-11 06:49:03 +00001091
1092 FunctionType *FT = Callee->getFunctionType();
1093 if (FT->getNumParams() != 3 || FT->getReturnType() != FT->getParamType(0) ||
1094 !FT->getParamType(0)->isPointerTy() ||
1095 !FT->getParamType(1)->isIntegerTy() ||
Rafael Espindola37dc9e12014-02-21 00:06:31 +00001096 FT->getParamType(2) != DL->getIntPtrType(FT->getParamType(0)))
Craig Topperf40110f2014-04-25 05:29:35 +00001097 return nullptr;
Meador Inged4825782012-11-11 06:49:03 +00001098
1099 // memset(p, v, n) -> llvm.memset(p, v, n, 1)
1100 Value *Val = B.CreateIntCast(CI->getArgOperand(1), B.getInt8Ty(), false);
1101 B.CreateMemSet(CI->getArgOperand(0), Val, CI->getArgOperand(2), 1);
1102 return CI->getArgOperand(0);
1103 }
1104};
1105
Meador Inge193e0352012-11-13 04:16:17 +00001106//===----------------------------------------------------------------------===//
1107// Math Library Optimizations
1108//===----------------------------------------------------------------------===//
1109
1110//===----------------------------------------------------------------------===//
1111// Double -> Float Shrinking Optimizations for Unary Functions like 'floor'
1112
1113struct UnaryDoubleFPOpt : public LibCallOptimization {
1114 bool CheckRetType;
1115 UnaryDoubleFPOpt(bool CheckReturnType): CheckRetType(CheckReturnType) {}
Craig Topper3e4c6972014-03-05 09:10:37 +00001116 Value *callOptimizer(Function *Callee, CallInst *CI,
1117 IRBuilder<> &B) override {
Meador Inge193e0352012-11-13 04:16:17 +00001118 FunctionType *FT = Callee->getFunctionType();
1119 if (FT->getNumParams() != 1 || !FT->getReturnType()->isDoubleTy() ||
1120 !FT->getParamType(0)->isDoubleTy())
Craig Topperf40110f2014-04-25 05:29:35 +00001121 return nullptr;
Meador Inge193e0352012-11-13 04:16:17 +00001122
1123 if (CheckRetType) {
1124 // Check if all the uses for function like 'sin' are converted to float.
Chandler Carruthcdf47882014-03-09 03:16:01 +00001125 for (User *U : CI->users()) {
1126 FPTruncInst *Cast = dyn_cast<FPTruncInst>(U);
Craig Topperf40110f2014-04-25 05:29:35 +00001127 if (!Cast || !Cast->getType()->isFloatTy())
1128 return nullptr;
Meador Inge193e0352012-11-13 04:16:17 +00001129 }
1130 }
1131
1132 // If this is something like 'floor((double)floatval)', convert to floorf.
1133 FPExtInst *Cast = dyn_cast<FPExtInst>(CI->getArgOperand(0));
Craig Topperf40110f2014-04-25 05:29:35 +00001134 if (!Cast || !Cast->getOperand(0)->getType()->isFloatTy())
1135 return nullptr;
Meador Inge193e0352012-11-13 04:16:17 +00001136
1137 // floor((double)floatval) -> (double)floorf(floatval)
1138 Value *V = Cast->getOperand(0);
1139 V = EmitUnaryFloatFnCall(V, Callee->getName(), B, Callee->getAttributes());
1140 return B.CreateFPExt(V, B.getDoubleTy());
1141 }
1142};
1143
Yi Jiang6ab044e2013-12-16 22:42:40 +00001144// Double -> Float Shrinking Optimizations for Binary Functions like 'fmin/fmax'
1145struct BinaryDoubleFPOpt : public LibCallOptimization {
1146 bool CheckRetType;
1147 BinaryDoubleFPOpt(bool CheckReturnType): CheckRetType(CheckReturnType) {}
Craig Topper3e4c6972014-03-05 09:10:37 +00001148 Value *callOptimizer(Function *Callee, CallInst *CI,
1149 IRBuilder<> &B) override {
Yi Jiang6ab044e2013-12-16 22:42:40 +00001150 FunctionType *FT = Callee->getFunctionType();
1151 // Just make sure this has 2 arguments of the same FP type, which match the
1152 // result type.
1153 if (FT->getNumParams() != 2 || FT->getReturnType() != FT->getParamType(0) ||
1154 FT->getParamType(0) != FT->getParamType(1) ||
1155 !FT->getParamType(0)->isFloatingPointTy())
Craig Topperf40110f2014-04-25 05:29:35 +00001156 return nullptr;
Yi Jiang6ab044e2013-12-16 22:42:40 +00001157
1158 if (CheckRetType) {
1159 // Check if all the uses for function like 'fmin/fmax' are converted to
1160 // float.
Chandler Carruthcdf47882014-03-09 03:16:01 +00001161 for (User *U : CI->users()) {
1162 FPTruncInst *Cast = dyn_cast<FPTruncInst>(U);
Craig Topperf40110f2014-04-25 05:29:35 +00001163 if (!Cast || !Cast->getType()->isFloatTy())
1164 return nullptr;
Yi Jiang6ab044e2013-12-16 22:42:40 +00001165 }
1166 }
1167
1168 // If this is something like 'fmin((double)floatval1, (double)floatval2)',
1169 // we convert it to fminf.
1170 FPExtInst *Cast1 = dyn_cast<FPExtInst>(CI->getArgOperand(0));
1171 FPExtInst *Cast2 = dyn_cast<FPExtInst>(CI->getArgOperand(1));
Craig Topperf40110f2014-04-25 05:29:35 +00001172 if (!Cast1 || !Cast1->getOperand(0)->getType()->isFloatTy() ||
1173 !Cast2 || !Cast2->getOperand(0)->getType()->isFloatTy())
1174 return nullptr;
Yi Jiang6ab044e2013-12-16 22:42:40 +00001175
1176 // fmin((double)floatval1, (double)floatval2)
1177 // -> (double)fmin(floatval1, floatval2)
Craig Topperf40110f2014-04-25 05:29:35 +00001178 Value *V = nullptr;
Yi Jiang6ab044e2013-12-16 22:42:40 +00001179 Value *V1 = Cast1->getOperand(0);
1180 Value *V2 = Cast2->getOperand(0);
1181 V = EmitBinaryFloatFnCall(V1, V2, Callee->getName(), B,
1182 Callee->getAttributes());
1183 return B.CreateFPExt(V, B.getDoubleTy());
1184 }
1185};
1186
Meador Inge193e0352012-11-13 04:16:17 +00001187struct UnsafeFPLibCallOptimization : public LibCallOptimization {
1188 bool UnsafeFPShrink;
1189 UnsafeFPLibCallOptimization(bool UnsafeFPShrink) {
1190 this->UnsafeFPShrink = UnsafeFPShrink;
1191 }
1192};
1193
1194struct CosOpt : public UnsafeFPLibCallOptimization {
1195 CosOpt(bool UnsafeFPShrink) : UnsafeFPLibCallOptimization(UnsafeFPShrink) {}
Craig Topper3e4c6972014-03-05 09:10:37 +00001196 Value *callOptimizer(Function *Callee, CallInst *CI,
1197 IRBuilder<> &B) override {
Craig Topperf40110f2014-04-25 05:29:35 +00001198 Value *Ret = nullptr;
Meador Inge193e0352012-11-13 04:16:17 +00001199 if (UnsafeFPShrink && Callee->getName() == "cos" &&
1200 TLI->has(LibFunc::cosf)) {
1201 UnaryDoubleFPOpt UnsafeUnaryDoubleFP(true);
1202 Ret = UnsafeUnaryDoubleFP.callOptimizer(Callee, CI, B);
1203 }
1204
1205 FunctionType *FT = Callee->getFunctionType();
1206 // Just make sure this has 1 argument of FP type, which matches the
1207 // result type.
1208 if (FT->getNumParams() != 1 || FT->getReturnType() != FT->getParamType(0) ||
1209 !FT->getParamType(0)->isFloatingPointTy())
1210 return Ret;
1211
1212 // cos(-x) -> cos(x)
1213 Value *Op1 = CI->getArgOperand(0);
1214 if (BinaryOperator::isFNeg(Op1)) {
1215 BinaryOperator *BinExpr = cast<BinaryOperator>(Op1);
1216 return B.CreateCall(Callee, BinExpr->getOperand(1), "cos");
1217 }
1218 return Ret;
1219 }
1220};
1221
1222struct PowOpt : public UnsafeFPLibCallOptimization {
1223 PowOpt(bool UnsafeFPShrink) : UnsafeFPLibCallOptimization(UnsafeFPShrink) {}
Craig Topper3e4c6972014-03-05 09:10:37 +00001224 Value *callOptimizer(Function *Callee, CallInst *CI,
1225 IRBuilder<> &B) override {
Craig Topperf40110f2014-04-25 05:29:35 +00001226 Value *Ret = nullptr;
Meador Inge193e0352012-11-13 04:16:17 +00001227 if (UnsafeFPShrink && Callee->getName() == "pow" &&
1228 TLI->has(LibFunc::powf)) {
1229 UnaryDoubleFPOpt UnsafeUnaryDoubleFP(true);
1230 Ret = UnsafeUnaryDoubleFP.callOptimizer(Callee, CI, B);
1231 }
1232
1233 FunctionType *FT = Callee->getFunctionType();
1234 // Just make sure this has 2 arguments of the same FP type, which match the
1235 // result type.
1236 if (FT->getNumParams() != 2 || FT->getReturnType() != FT->getParamType(0) ||
1237 FT->getParamType(0) != FT->getParamType(1) ||
1238 !FT->getParamType(0)->isFloatingPointTy())
1239 return Ret;
1240
1241 Value *Op1 = CI->getArgOperand(0), *Op2 = CI->getArgOperand(1);
1242 if (ConstantFP *Op1C = dyn_cast<ConstantFP>(Op1)) {
Michael Kuperstein4bb3f8f2013-08-19 06:55:47 +00001243 // pow(1.0, x) -> 1.0
1244 if (Op1C->isExactlyValue(1.0))
Meador Inge193e0352012-11-13 04:16:17 +00001245 return Op1C;
Michael Kuperstein4bb3f8f2013-08-19 06:55:47 +00001246 // pow(2.0, x) -> exp2(x)
Benjamin Kramer2702caa2013-08-31 18:19:35 +00001247 if (Op1C->isExactlyValue(2.0) &&
1248 hasUnaryFloatFn(TLI, Op1->getType(), LibFunc::exp2, LibFunc::exp2f,
1249 LibFunc::exp2l))
Meador Inge193e0352012-11-13 04:16:17 +00001250 return EmitUnaryFloatFnCall(Op2, "exp2", B, Callee->getAttributes());
Yi Jiangf92a5742013-12-12 01:55:04 +00001251 // pow(10.0, x) -> exp10(x)
1252 if (Op1C->isExactlyValue(10.0) &&
1253 hasUnaryFloatFn(TLI, Op1->getType(), LibFunc::exp10, LibFunc::exp10f,
1254 LibFunc::exp10l))
1255 return EmitUnaryFloatFnCall(Op2, TLI->getName(LibFunc::exp10), B,
1256 Callee->getAttributes());
Meador Inge193e0352012-11-13 04:16:17 +00001257 }
1258
1259 ConstantFP *Op2C = dyn_cast<ConstantFP>(Op2);
Craig Topperf40110f2014-04-25 05:29:35 +00001260 if (!Op2C) return Ret;
Meador Inge193e0352012-11-13 04:16:17 +00001261
1262 if (Op2C->getValueAPF().isZero()) // pow(x, 0.0) -> 1.0
1263 return ConstantFP::get(CI->getType(), 1.0);
1264
Michael Kuperstein4bb3f8f2013-08-19 06:55:47 +00001265 if (Op2C->isExactlyValue(0.5) &&
Benjamin Kramer2702caa2013-08-31 18:19:35 +00001266 hasUnaryFloatFn(TLI, Op2->getType(), LibFunc::sqrt, LibFunc::sqrtf,
1267 LibFunc::sqrtl) &&
1268 hasUnaryFloatFn(TLI, Op2->getType(), LibFunc::fabs, LibFunc::fabsf,
1269 LibFunc::fabsl)) {
Meador Inge193e0352012-11-13 04:16:17 +00001270 // Expand pow(x, 0.5) to (x == -infinity ? +infinity : fabs(sqrt(x))).
1271 // This is faster than calling pow, and still handles negative zero
1272 // and negative infinity correctly.
1273 // TODO: In fast-math mode, this could be just sqrt(x).
1274 // TODO: In finite-only mode, this could be just fabs(sqrt(x)).
1275 Value *Inf = ConstantFP::getInfinity(CI->getType());
1276 Value *NegInf = ConstantFP::getInfinity(CI->getType(), true);
1277 Value *Sqrt = EmitUnaryFloatFnCall(Op1, "sqrt", B,
1278 Callee->getAttributes());
1279 Value *FAbs = EmitUnaryFloatFnCall(Sqrt, "fabs", B,
1280 Callee->getAttributes());
1281 Value *FCmp = B.CreateFCmpOEQ(Op1, NegInf);
1282 Value *Sel = B.CreateSelect(FCmp, Inf, FAbs);
1283 return Sel;
1284 }
1285
1286 if (Op2C->isExactlyValue(1.0)) // pow(x, 1.0) -> x
1287 return Op1;
1288 if (Op2C->isExactlyValue(2.0)) // pow(x, 2.0) -> x*x
1289 return B.CreateFMul(Op1, Op1, "pow2");
1290 if (Op2C->isExactlyValue(-1.0)) // pow(x, -1.0) -> 1.0/x
1291 return B.CreateFDiv(ConstantFP::get(CI->getType(), 1.0),
1292 Op1, "powrecip");
Craig Topperf40110f2014-04-25 05:29:35 +00001293 return nullptr;
Meador Inge193e0352012-11-13 04:16:17 +00001294 }
1295};
1296
1297struct Exp2Opt : public UnsafeFPLibCallOptimization {
1298 Exp2Opt(bool UnsafeFPShrink) : UnsafeFPLibCallOptimization(UnsafeFPShrink) {}
Craig Topper3e4c6972014-03-05 09:10:37 +00001299 Value *callOptimizer(Function *Callee, CallInst *CI,
1300 IRBuilder<> &B) override {
Craig Topperf40110f2014-04-25 05:29:35 +00001301 Value *Ret = nullptr;
Meador Inge193e0352012-11-13 04:16:17 +00001302 if (UnsafeFPShrink && Callee->getName() == "exp2" &&
Benjamin Kramer2702caa2013-08-31 18:19:35 +00001303 TLI->has(LibFunc::exp2f)) {
Meador Inge193e0352012-11-13 04:16:17 +00001304 UnaryDoubleFPOpt UnsafeUnaryDoubleFP(true);
1305 Ret = UnsafeUnaryDoubleFP.callOptimizer(Callee, CI, B);
1306 }
1307
1308 FunctionType *FT = Callee->getFunctionType();
1309 // Just make sure this has 1 argument of FP type, which matches the
1310 // result type.
1311 if (FT->getNumParams() != 1 || FT->getReturnType() != FT->getParamType(0) ||
1312 !FT->getParamType(0)->isFloatingPointTy())
1313 return Ret;
1314
1315 Value *Op = CI->getArgOperand(0);
1316 // Turn exp2(sitofp(x)) -> ldexp(1.0, sext(x)) if sizeof(x) <= 32
1317 // Turn exp2(uitofp(x)) -> ldexp(1.0, zext(x)) if sizeof(x) < 32
Benjamin Kramer34f460e2014-02-04 20:27:23 +00001318 LibFunc::Func LdExp = LibFunc::ldexpl;
1319 if (Op->getType()->isFloatTy())
1320 LdExp = LibFunc::ldexpf;
1321 else if (Op->getType()->isDoubleTy())
1322 LdExp = LibFunc::ldexp;
Meador Inge193e0352012-11-13 04:16:17 +00001323
Benjamin Kramer34f460e2014-02-04 20:27:23 +00001324 if (TLI->has(LdExp)) {
Craig Topperf40110f2014-04-25 05:29:35 +00001325 Value *LdExpArg = nullptr;
Benjamin Kramer34f460e2014-02-04 20:27:23 +00001326 if (SIToFPInst *OpC = dyn_cast<SIToFPInst>(Op)) {
1327 if (OpC->getOperand(0)->getType()->getPrimitiveSizeInBits() <= 32)
1328 LdExpArg = B.CreateSExt(OpC->getOperand(0), B.getInt32Ty());
1329 } else if (UIToFPInst *OpC = dyn_cast<UIToFPInst>(Op)) {
1330 if (OpC->getOperand(0)->getType()->getPrimitiveSizeInBits() < 32)
1331 LdExpArg = B.CreateZExt(OpC->getOperand(0), B.getInt32Ty());
1332 }
Meador Inge193e0352012-11-13 04:16:17 +00001333
Benjamin Kramer34f460e2014-02-04 20:27:23 +00001334 if (LdExpArg) {
1335 Constant *One = ConstantFP::get(*Context, APFloat(1.0f));
1336 if (!Op->getType()->isFloatTy())
1337 One = ConstantExpr::getFPExtend(One, Op->getType());
Meador Inge193e0352012-11-13 04:16:17 +00001338
Benjamin Kramer34f460e2014-02-04 20:27:23 +00001339 Module *M = Caller->getParent();
1340 Value *Callee =
1341 M->getOrInsertFunction(TLI->getName(LdExp), Op->getType(),
1342 Op->getType(), B.getInt32Ty(), NULL);
1343 CallInst *CI = B.CreateCall2(Callee, One, LdExpArg);
1344 if (const Function *F = dyn_cast<Function>(Callee->stripPointerCasts()))
1345 CI->setCallingConv(F->getCallingConv());
Meador Inge193e0352012-11-13 04:16:17 +00001346
Benjamin Kramer34f460e2014-02-04 20:27:23 +00001347 return CI;
1348 }
Meador Inge193e0352012-11-13 04:16:17 +00001349 }
1350 return Ret;
1351 }
1352};
1353
Bob Wilsond8d92d92013-11-03 06:48:38 +00001354struct SinCosPiOpt : public LibCallOptimization {
1355 SinCosPiOpt() {}
1356
Craig Topper3e4c6972014-03-05 09:10:37 +00001357 Value *callOptimizer(Function *Callee, CallInst *CI,
1358 IRBuilder<> &B) override {
Bob Wilsond8d92d92013-11-03 06:48:38 +00001359 // Make sure the prototype is as expected, otherwise the rest of the
1360 // function is probably invalid and likely to abort.
1361 if (!isTrigLibCall(CI))
Craig Topperf40110f2014-04-25 05:29:35 +00001362 return nullptr;
Bob Wilsond8d92d92013-11-03 06:48:38 +00001363
1364 Value *Arg = CI->getArgOperand(0);
1365 SmallVector<CallInst *, 1> SinCalls;
1366 SmallVector<CallInst *, 1> CosCalls;
1367 SmallVector<CallInst *, 1> SinCosCalls;
1368
1369 bool IsFloat = Arg->getType()->isFloatTy();
1370
1371 // Look for all compatible sinpi, cospi and sincospi calls with the same
1372 // argument. If there are enough (in some sense) we can make the
1373 // substitution.
Chandler Carruthcdf47882014-03-09 03:16:01 +00001374 for (User *U : Arg->users())
1375 classifyArgUse(U, CI->getParent(), IsFloat, SinCalls, CosCalls,
Bob Wilsond8d92d92013-11-03 06:48:38 +00001376 SinCosCalls);
1377
1378 // It's only worthwhile if both sinpi and cospi are actually used.
1379 if (SinCosCalls.empty() && (SinCalls.empty() || CosCalls.empty()))
Craig Topperf40110f2014-04-25 05:29:35 +00001380 return nullptr;
Bob Wilsond8d92d92013-11-03 06:48:38 +00001381
1382 Value *Sin, *Cos, *SinCos;
1383 insertSinCosCall(B, CI->getCalledFunction(), Arg, IsFloat, Sin, Cos,
1384 SinCos);
1385
1386 replaceTrigInsts(SinCalls, Sin);
1387 replaceTrigInsts(CosCalls, Cos);
1388 replaceTrigInsts(SinCosCalls, SinCos);
1389
Craig Topperf40110f2014-04-25 05:29:35 +00001390 return nullptr;
Bob Wilsond8d92d92013-11-03 06:48:38 +00001391 }
1392
1393 bool isTrigLibCall(CallInst *CI) {
1394 Function *Callee = CI->getCalledFunction();
1395 FunctionType *FT = Callee->getFunctionType();
1396
1397 // We can only hope to do anything useful if we can ignore things like errno
1398 // and floating-point exceptions.
1399 bool AttributesSafe = CI->hasFnAttr(Attribute::NoUnwind) &&
1400 CI->hasFnAttr(Attribute::ReadNone);
1401
1402 // Other than that we need float(float) or double(double)
1403 return AttributesSafe && FT->getNumParams() == 1 &&
1404 FT->getReturnType() == FT->getParamType(0) &&
1405 (FT->getParamType(0)->isFloatTy() ||
1406 FT->getParamType(0)->isDoubleTy());
1407 }
1408
1409 void classifyArgUse(Value *Val, BasicBlock *BB, bool IsFloat,
1410 SmallVectorImpl<CallInst *> &SinCalls,
1411 SmallVectorImpl<CallInst *> &CosCalls,
1412 SmallVectorImpl<CallInst *> &SinCosCalls) {
1413 CallInst *CI = dyn_cast<CallInst>(Val);
1414
1415 if (!CI)
1416 return;
1417
1418 Function *Callee = CI->getCalledFunction();
1419 StringRef FuncName = Callee->getName();
1420 LibFunc::Func Func;
1421 if (!TLI->getLibFunc(FuncName, Func) || !TLI->has(Func) ||
1422 !isTrigLibCall(CI))
1423 return;
1424
1425 if (IsFloat) {
1426 if (Func == LibFunc::sinpif)
1427 SinCalls.push_back(CI);
1428 else if (Func == LibFunc::cospif)
1429 CosCalls.push_back(CI);
Tim Northover103e6482014-02-04 16:28:20 +00001430 else if (Func == LibFunc::sincospif_stret)
Bob Wilsond8d92d92013-11-03 06:48:38 +00001431 SinCosCalls.push_back(CI);
1432 } else {
1433 if (Func == LibFunc::sinpi)
1434 SinCalls.push_back(CI);
1435 else if (Func == LibFunc::cospi)
1436 CosCalls.push_back(CI);
1437 else if (Func == LibFunc::sincospi_stret)
1438 SinCosCalls.push_back(CI);
1439 }
1440 }
1441
1442 void replaceTrigInsts(SmallVectorImpl<CallInst*> &Calls, Value *Res) {
1443 for (SmallVectorImpl<CallInst*>::iterator I = Calls.begin(),
1444 E = Calls.end();
1445 I != E; ++I) {
1446 LCS->replaceAllUsesWith(*I, Res);
1447 }
1448 }
1449
1450 void insertSinCosCall(IRBuilder<> &B, Function *OrigCallee, Value *Arg,
1451 bool UseFloat, Value *&Sin, Value *&Cos,
1452 Value *&SinCos) {
1453 Type *ArgTy = Arg->getType();
1454 Type *ResTy;
1455 StringRef Name;
1456
1457 Triple T(OrigCallee->getParent()->getTargetTriple());
1458 if (UseFloat) {
Tim Northover103e6482014-02-04 16:28:20 +00001459 Name = "__sincospif_stret";
Bob Wilsond8d92d92013-11-03 06:48:38 +00001460
1461 assert(T.getArch() != Triple::x86 && "x86 messy and unsupported for now");
1462 // x86_64 can't use {float, float} since that would be returned in both
1463 // xmm0 and xmm1, which isn't what a real struct would do.
1464 ResTy = T.getArch() == Triple::x86_64
1465 ? static_cast<Type *>(VectorType::get(ArgTy, 2))
1466 : static_cast<Type *>(StructType::get(ArgTy, ArgTy, NULL));
1467 } else {
1468 Name = "__sincospi_stret";
1469 ResTy = StructType::get(ArgTy, ArgTy, NULL);
1470 }
1471
1472 Module *M = OrigCallee->getParent();
1473 Value *Callee = M->getOrInsertFunction(Name, OrigCallee->getAttributes(),
1474 ResTy, ArgTy, NULL);
1475
1476 if (Instruction *ArgInst = dyn_cast<Instruction>(Arg)) {
1477 // If the argument is an instruction, it must dominate all uses so put our
1478 // sincos call there.
1479 BasicBlock::iterator Loc = ArgInst;
1480 B.SetInsertPoint(ArgInst->getParent(), ++Loc);
1481 } else {
1482 // Otherwise (e.g. for a constant) the beginning of the function is as
1483 // good a place as any.
1484 BasicBlock &EntryBB = B.GetInsertBlock()->getParent()->getEntryBlock();
1485 B.SetInsertPoint(&EntryBB, EntryBB.begin());
1486 }
1487
1488 SinCos = B.CreateCall(Callee, Arg, "sincospi");
1489
1490 if (SinCos->getType()->isStructTy()) {
1491 Sin = B.CreateExtractValue(SinCos, 0, "sinpi");
1492 Cos = B.CreateExtractValue(SinCos, 1, "cospi");
1493 } else {
1494 Sin = B.CreateExtractElement(SinCos, ConstantInt::get(B.getInt32Ty(), 0),
1495 "sinpi");
1496 Cos = B.CreateExtractElement(SinCos, ConstantInt::get(B.getInt32Ty(), 1),
1497 "cospi");
1498 }
1499 }
1500
1501};
1502
Meador Inge7415f842012-11-25 20:45:27 +00001503//===----------------------------------------------------------------------===//
1504// Integer Library Call Optimizations
1505//===----------------------------------------------------------------------===//
1506
1507struct FFSOpt : public LibCallOptimization {
Craig Topper3e4c6972014-03-05 09:10:37 +00001508 Value *callOptimizer(Function *Callee, CallInst *CI,
1509 IRBuilder<> &B) override {
Meador Inge7415f842012-11-25 20:45:27 +00001510 FunctionType *FT = Callee->getFunctionType();
1511 // Just make sure this has 2 arguments of the same FP type, which match the
1512 // result type.
1513 if (FT->getNumParams() != 1 ||
1514 !FT->getReturnType()->isIntegerTy(32) ||
1515 !FT->getParamType(0)->isIntegerTy())
Craig Topperf40110f2014-04-25 05:29:35 +00001516 return nullptr;
Meador Inge7415f842012-11-25 20:45:27 +00001517
1518 Value *Op = CI->getArgOperand(0);
1519
1520 // Constant fold.
1521 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op)) {
1522 if (CI->isZero()) // ffs(0) -> 0.
1523 return B.getInt32(0);
1524 // ffs(c) -> cttz(c)+1
1525 return B.getInt32(CI->getValue().countTrailingZeros() + 1);
1526 }
1527
1528 // ffs(x) -> x != 0 ? (i32)llvm.cttz(x)+1 : 0
1529 Type *ArgType = Op->getType();
1530 Value *F = Intrinsic::getDeclaration(Callee->getParent(),
1531 Intrinsic::cttz, ArgType);
1532 Value *V = B.CreateCall2(F, Op, B.getFalse(), "cttz");
1533 V = B.CreateAdd(V, ConstantInt::get(V->getType(), 1));
1534 V = B.CreateIntCast(V, B.getInt32Ty(), false);
1535
1536 Value *Cond = B.CreateICmpNE(Op, Constant::getNullValue(ArgType));
1537 return B.CreateSelect(Cond, V, B.getInt32(0));
1538 }
1539};
1540
Meador Ingea0b6d872012-11-26 00:24:07 +00001541struct AbsOpt : public LibCallOptimization {
Craig Topper3e4c6972014-03-05 09:10:37 +00001542 bool ignoreCallingConv() override { return true; }
1543 Value *callOptimizer(Function *Callee, CallInst *CI,
1544 IRBuilder<> &B) override {
Meador Ingea0b6d872012-11-26 00:24:07 +00001545 FunctionType *FT = Callee->getFunctionType();
1546 // We require integer(integer) where the types agree.
1547 if (FT->getNumParams() != 1 || !FT->getReturnType()->isIntegerTy() ||
1548 FT->getParamType(0) != FT->getReturnType())
Craig Topperf40110f2014-04-25 05:29:35 +00001549 return nullptr;
Meador Ingea0b6d872012-11-26 00:24:07 +00001550
1551 // abs(x) -> x >s -1 ? x : -x
1552 Value *Op = CI->getArgOperand(0);
1553 Value *Pos = B.CreateICmpSGT(Op, Constant::getAllOnesValue(Op->getType()),
1554 "ispos");
1555 Value *Neg = B.CreateNeg(Op, "neg");
1556 return B.CreateSelect(Pos, Op, Neg);
1557 }
1558};
1559
Meador Inge9a59ab62012-11-26 02:31:59 +00001560struct IsDigitOpt : public LibCallOptimization {
Craig Topper3e4c6972014-03-05 09:10:37 +00001561 Value *callOptimizer(Function *Callee, CallInst *CI,
1562 IRBuilder<> &B) override {
Meador Inge9a59ab62012-11-26 02:31:59 +00001563 FunctionType *FT = Callee->getFunctionType();
1564 // We require integer(i32)
1565 if (FT->getNumParams() != 1 || !FT->getReturnType()->isIntegerTy() ||
1566 !FT->getParamType(0)->isIntegerTy(32))
Craig Topperf40110f2014-04-25 05:29:35 +00001567 return nullptr;
Meador Inge9a59ab62012-11-26 02:31:59 +00001568
1569 // isdigit(c) -> (c-'0') <u 10
1570 Value *Op = CI->getArgOperand(0);
1571 Op = B.CreateSub(Op, B.getInt32('0'), "isdigittmp");
1572 Op = B.CreateICmpULT(Op, B.getInt32(10), "isdigit");
1573 return B.CreateZExt(Op, CI->getType());
1574 }
1575};
1576
Meador Ingea62a39e2012-11-26 03:10:07 +00001577struct IsAsciiOpt : public LibCallOptimization {
Craig Topper3e4c6972014-03-05 09:10:37 +00001578 Value *callOptimizer(Function *Callee, CallInst *CI,
1579 IRBuilder<> &B) override {
Meador Ingea62a39e2012-11-26 03:10:07 +00001580 FunctionType *FT = Callee->getFunctionType();
1581 // We require integer(i32)
1582 if (FT->getNumParams() != 1 || !FT->getReturnType()->isIntegerTy() ||
1583 !FT->getParamType(0)->isIntegerTy(32))
Craig Topperf40110f2014-04-25 05:29:35 +00001584 return nullptr;
Meador Ingea62a39e2012-11-26 03:10:07 +00001585
1586 // isascii(c) -> c <u 128
1587 Value *Op = CI->getArgOperand(0);
1588 Op = B.CreateICmpULT(Op, B.getInt32(128), "isascii");
1589 return B.CreateZExt(Op, CI->getType());
1590 }
1591};
1592
Meador Inge604937d2012-11-26 03:38:52 +00001593struct ToAsciiOpt : public LibCallOptimization {
Craig Topper3e4c6972014-03-05 09:10:37 +00001594 Value *callOptimizer(Function *Callee, CallInst *CI,
1595 IRBuilder<> &B) override {
Meador Inge604937d2012-11-26 03:38:52 +00001596 FunctionType *FT = Callee->getFunctionType();
1597 // We require i32(i32)
1598 if (FT->getNumParams() != 1 || FT->getReturnType() != FT->getParamType(0) ||
1599 !FT->getParamType(0)->isIntegerTy(32))
Craig Topperf40110f2014-04-25 05:29:35 +00001600 return nullptr;
Meador Inge604937d2012-11-26 03:38:52 +00001601
Meador Ingeefe23932012-11-26 20:37:23 +00001602 // toascii(c) -> c & 0x7f
Meador Inge604937d2012-11-26 03:38:52 +00001603 return B.CreateAnd(CI->getArgOperand(0),
1604 ConstantInt::get(CI->getType(),0x7F));
1605 }
1606};
1607
Meador Inge08ca1152012-11-26 20:37:20 +00001608//===----------------------------------------------------------------------===//
1609// Formatting and IO Library Call Optimizations
1610//===----------------------------------------------------------------------===//
1611
Hal Finkel66cd3f12013-11-17 02:06:35 +00001612struct ErrorReportingOpt : public LibCallOptimization {
1613 ErrorReportingOpt(int S = -1) : StreamArg(S) {}
1614
Craig Topper3e4c6972014-03-05 09:10:37 +00001615 Value *callOptimizer(Function *Callee, CallInst *CI,
1616 IRBuilder<> &) override {
Hal Finkel66cd3f12013-11-17 02:06:35 +00001617 // Error reporting calls should be cold, mark them as such.
1618 // This applies even to non-builtin calls: it is only a hint and applies to
1619 // functions that the frontend might not understand as builtins.
1620
1621 // This heuristic was suggested in:
1622 // Improving Static Branch Prediction in a Compiler
1623 // Brian L. Deitrich, Ben-Chung Cheng, Wen-mei W. Hwu
1624 // Proceedings of PACT'98, Oct. 1998, IEEE
1625
1626 if (!CI->hasFnAttr(Attribute::Cold) && isReportingError(Callee, CI)) {
1627 CI->addAttribute(AttributeSet::FunctionIndex, Attribute::Cold);
1628 }
1629
Craig Topperf40110f2014-04-25 05:29:35 +00001630 return nullptr;
Hal Finkel66cd3f12013-11-17 02:06:35 +00001631 }
1632
1633protected:
1634 bool isReportingError(Function *Callee, CallInst *CI) {
1635 if (!ColdErrorCalls)
1636 return false;
1637
1638 if (!Callee || !Callee->isDeclaration())
1639 return false;
1640
1641 if (StreamArg < 0)
1642 return true;
1643
1644 // These functions might be considered cold, but only if their stream
1645 // argument is stderr.
1646
1647 if (StreamArg >= (int) CI->getNumArgOperands())
1648 return false;
1649 LoadInst *LI = dyn_cast<LoadInst>(CI->getArgOperand(StreamArg));
1650 if (!LI)
1651 return false;
1652 GlobalVariable *GV = dyn_cast<GlobalVariable>(LI->getPointerOperand());
1653 if (!GV || !GV->isDeclaration())
1654 return false;
1655 return GV->getName() == "stderr";
1656 }
1657
1658 int StreamArg;
1659};
1660
Meador Inge08ca1152012-11-26 20:37:20 +00001661struct PrintFOpt : public LibCallOptimization {
1662 Value *optimizeFixedFormatString(Function *Callee, CallInst *CI,
1663 IRBuilder<> &B) {
1664 // Check for a fixed format string.
1665 StringRef FormatStr;
1666 if (!getConstantStringInfo(CI->getArgOperand(0), FormatStr))
Craig Topperf40110f2014-04-25 05:29:35 +00001667 return nullptr;
Meador Inge08ca1152012-11-26 20:37:20 +00001668
1669 // Empty format string -> noop.
1670 if (FormatStr.empty()) // Tolerate printf's declared void.
1671 return CI->use_empty() ? (Value*)CI :
1672 ConstantInt::get(CI->getType(), 0);
1673
1674 // Do not do any of the following transformations if the printf return value
1675 // is used, in general the printf return value is not compatible with either
1676 // putchar() or puts().
1677 if (!CI->use_empty())
Craig Topperf40110f2014-04-25 05:29:35 +00001678 return nullptr;
Meador Inge08ca1152012-11-26 20:37:20 +00001679
1680 // printf("x") -> putchar('x'), even for '%'.
1681 if (FormatStr.size() == 1) {
Rafael Espindola37dc9e12014-02-21 00:06:31 +00001682 Value *Res = EmitPutChar(B.getInt32(FormatStr[0]), B, DL, TLI);
Meador Inge08ca1152012-11-26 20:37:20 +00001683 if (CI->use_empty() || !Res) return Res;
1684 return B.CreateIntCast(Res, CI->getType(), true);
1685 }
1686
1687 // printf("foo\n") --> puts("foo")
1688 if (FormatStr[FormatStr.size()-1] == '\n' &&
Matt Arsenaultf631f8c2013-09-10 00:41:53 +00001689 FormatStr.find('%') == StringRef::npos) { // No format characters.
Meador Inge08ca1152012-11-26 20:37:20 +00001690 // Create a string literal with no \n on it. We expect the constant merge
1691 // pass to be run after this pass, to merge duplicate strings.
1692 FormatStr = FormatStr.drop_back();
1693 Value *GV = B.CreateGlobalString(FormatStr, "str");
Rafael Espindola37dc9e12014-02-21 00:06:31 +00001694 Value *NewCI = EmitPutS(GV, B, DL, TLI);
Meador Inge08ca1152012-11-26 20:37:20 +00001695 return (CI->use_empty() || !NewCI) ?
1696 NewCI :
1697 ConstantInt::get(CI->getType(), FormatStr.size()+1);
1698 }
1699
1700 // Optimize specific format strings.
1701 // printf("%c", chr) --> putchar(chr)
1702 if (FormatStr == "%c" && CI->getNumArgOperands() > 1 &&
1703 CI->getArgOperand(1)->getType()->isIntegerTy()) {
Rafael Espindola37dc9e12014-02-21 00:06:31 +00001704 Value *Res = EmitPutChar(CI->getArgOperand(1), B, DL, TLI);
Meador Inge08ca1152012-11-26 20:37:20 +00001705
1706 if (CI->use_empty() || !Res) return Res;
1707 return B.CreateIntCast(Res, CI->getType(), true);
1708 }
1709
1710 // printf("%s\n", str) --> puts(str)
1711 if (FormatStr == "%s\n" && CI->getNumArgOperands() > 1 &&
1712 CI->getArgOperand(1)->getType()->isPointerTy()) {
Rafael Espindola37dc9e12014-02-21 00:06:31 +00001713 return EmitPutS(CI->getArgOperand(1), B, DL, TLI);
Meador Inge08ca1152012-11-26 20:37:20 +00001714 }
Craig Topperf40110f2014-04-25 05:29:35 +00001715 return nullptr;
Meador Inge08ca1152012-11-26 20:37:20 +00001716 }
1717
Craig Topper3e4c6972014-03-05 09:10:37 +00001718 Value *callOptimizer(Function *Callee, CallInst *CI,
1719 IRBuilder<> &B) override {
Meador Inge08ca1152012-11-26 20:37:20 +00001720 // Require one fixed pointer argument and an integer/void result.
1721 FunctionType *FT = Callee->getFunctionType();
1722 if (FT->getNumParams() < 1 || !FT->getParamType(0)->isPointerTy() ||
1723 !(FT->getReturnType()->isIntegerTy() ||
1724 FT->getReturnType()->isVoidTy()))
Craig Topperf40110f2014-04-25 05:29:35 +00001725 return nullptr;
Meador Inge08ca1152012-11-26 20:37:20 +00001726
1727 if (Value *V = optimizeFixedFormatString(Callee, CI, B)) {
1728 return V;
1729 }
1730
1731 // printf(format, ...) -> iprintf(format, ...) if no floating point
1732 // arguments.
1733 if (TLI->has(LibFunc::iprintf) && !callHasFloatingPointArgument(CI)) {
1734 Module *M = B.GetInsertBlock()->getParent()->getParent();
1735 Constant *IPrintFFn =
1736 M->getOrInsertFunction("iprintf", FT, Callee->getAttributes());
1737 CallInst *New = cast<CallInst>(CI->clone());
1738 New->setCalledFunction(IPrintFFn);
1739 B.Insert(New);
1740 return New;
1741 }
Craig Topperf40110f2014-04-25 05:29:35 +00001742 return nullptr;
Meador Inge08ca1152012-11-26 20:37:20 +00001743 }
1744};
1745
Meador Inge25c9b3b2012-11-27 05:57:54 +00001746struct SPrintFOpt : public LibCallOptimization {
1747 Value *OptimizeFixedFormatString(Function *Callee, CallInst *CI,
1748 IRBuilder<> &B) {
1749 // Check for a fixed format string.
1750 StringRef FormatStr;
1751 if (!getConstantStringInfo(CI->getArgOperand(1), FormatStr))
Craig Topperf40110f2014-04-25 05:29:35 +00001752 return nullptr;
Meador Inge25c9b3b2012-11-27 05:57:54 +00001753
1754 // If we just have a format string (nothing else crazy) transform it.
1755 if (CI->getNumArgOperands() == 2) {
1756 // Make sure there's no % in the constant array. We could try to handle
1757 // %% -> % in the future if we cared.
1758 for (unsigned i = 0, e = FormatStr.size(); i != e; ++i)
1759 if (FormatStr[i] == '%')
Craig Topperf40110f2014-04-25 05:29:35 +00001760 return nullptr; // we found a format specifier, bail out.
Meador Inge25c9b3b2012-11-27 05:57:54 +00001761
1762 // These optimizations require DataLayout.
Craig Topperf40110f2014-04-25 05:29:35 +00001763 if (!DL) return nullptr;
Meador Inge25c9b3b2012-11-27 05:57:54 +00001764
1765 // sprintf(str, fmt) -> llvm.memcpy(str, fmt, strlen(fmt)+1, 1)
1766 B.CreateMemCpy(CI->getArgOperand(0), CI->getArgOperand(1),
Rafael Espindola37dc9e12014-02-21 00:06:31 +00001767 ConstantInt::get(DL->getIntPtrType(*Context), // Copy the
Meador Inge25c9b3b2012-11-27 05:57:54 +00001768 FormatStr.size() + 1), 1); // nul byte.
1769 return ConstantInt::get(CI->getType(), FormatStr.size());
1770 }
1771
1772 // The remaining optimizations require the format string to be "%s" or "%c"
1773 // and have an extra operand.
1774 if (FormatStr.size() != 2 || FormatStr[0] != '%' ||
1775 CI->getNumArgOperands() < 3)
Craig Topperf40110f2014-04-25 05:29:35 +00001776 return nullptr;
Meador Inge25c9b3b2012-11-27 05:57:54 +00001777
1778 // Decode the second character of the format string.
1779 if (FormatStr[1] == 'c') {
1780 // sprintf(dst, "%c", chr) --> *(i8*)dst = chr; *((i8*)dst+1) = 0
Craig Topperf40110f2014-04-25 05:29:35 +00001781 if (!CI->getArgOperand(2)->getType()->isIntegerTy()) return nullptr;
Meador Inge25c9b3b2012-11-27 05:57:54 +00001782 Value *V = B.CreateTrunc(CI->getArgOperand(2), B.getInt8Ty(), "char");
1783 Value *Ptr = CastToCStr(CI->getArgOperand(0), B);
1784 B.CreateStore(V, Ptr);
1785 Ptr = B.CreateGEP(Ptr, B.getInt32(1), "nul");
1786 B.CreateStore(B.getInt8(0), Ptr);
1787
1788 return ConstantInt::get(CI->getType(), 1);
1789 }
1790
1791 if (FormatStr[1] == 's') {
1792 // These optimizations require DataLayout.
Craig Topperf40110f2014-04-25 05:29:35 +00001793 if (!DL) return nullptr;
Meador Inge25c9b3b2012-11-27 05:57:54 +00001794
1795 // sprintf(dest, "%s", str) -> llvm.memcpy(dest, str, strlen(str)+1, 1)
Craig Topperf40110f2014-04-25 05:29:35 +00001796 if (!CI->getArgOperand(2)->getType()->isPointerTy()) return nullptr;
Meador Inge25c9b3b2012-11-27 05:57:54 +00001797
Rafael Espindola37dc9e12014-02-21 00:06:31 +00001798 Value *Len = EmitStrLen(CI->getArgOperand(2), B, DL, TLI);
Meador Inge25c9b3b2012-11-27 05:57:54 +00001799 if (!Len)
Craig Topperf40110f2014-04-25 05:29:35 +00001800 return nullptr;
Meador Inge25c9b3b2012-11-27 05:57:54 +00001801 Value *IncLen = B.CreateAdd(Len,
1802 ConstantInt::get(Len->getType(), 1),
1803 "leninc");
1804 B.CreateMemCpy(CI->getArgOperand(0), CI->getArgOperand(2), IncLen, 1);
1805
1806 // The sprintf result is the unincremented number of bytes in the string.
1807 return B.CreateIntCast(Len, CI->getType(), false);
1808 }
Craig Topperf40110f2014-04-25 05:29:35 +00001809 return nullptr;
Meador Inge25c9b3b2012-11-27 05:57:54 +00001810 }
1811
Craig Topper3e4c6972014-03-05 09:10:37 +00001812 Value *callOptimizer(Function *Callee, CallInst *CI,
1813 IRBuilder<> &B) override {
Meador Inge25c9b3b2012-11-27 05:57:54 +00001814 // Require two fixed pointer arguments and an integer result.
1815 FunctionType *FT = Callee->getFunctionType();
1816 if (FT->getNumParams() != 2 || !FT->getParamType(0)->isPointerTy() ||
1817 !FT->getParamType(1)->isPointerTy() ||
1818 !FT->getReturnType()->isIntegerTy())
Craig Topperf40110f2014-04-25 05:29:35 +00001819 return nullptr;
Meador Inge25c9b3b2012-11-27 05:57:54 +00001820
1821 if (Value *V = OptimizeFixedFormatString(Callee, CI, B)) {
1822 return V;
1823 }
1824
1825 // sprintf(str, format, ...) -> siprintf(str, format, ...) if no floating
1826 // point arguments.
1827 if (TLI->has(LibFunc::siprintf) && !callHasFloatingPointArgument(CI)) {
1828 Module *M = B.GetInsertBlock()->getParent()->getParent();
1829 Constant *SIPrintFFn =
1830 M->getOrInsertFunction("siprintf", FT, Callee->getAttributes());
1831 CallInst *New = cast<CallInst>(CI->clone());
1832 New->setCalledFunction(SIPrintFFn);
1833 B.Insert(New);
1834 return New;
1835 }
Craig Topperf40110f2014-04-25 05:29:35 +00001836 return nullptr;
Meador Inge25c9b3b2012-11-27 05:57:54 +00001837 }
1838};
1839
Meador Inge1009cec2012-11-29 15:45:33 +00001840struct FPrintFOpt : public LibCallOptimization {
1841 Value *optimizeFixedFormatString(Function *Callee, CallInst *CI,
1842 IRBuilder<> &B) {
Hal Finkel66cd3f12013-11-17 02:06:35 +00001843 ErrorReportingOpt ER(/* StreamArg = */ 0);
1844 (void) ER.callOptimizer(Callee, CI, B);
1845
Meador Inge1009cec2012-11-29 15:45:33 +00001846 // All the optimizations depend on the format string.
1847 StringRef FormatStr;
1848 if (!getConstantStringInfo(CI->getArgOperand(1), FormatStr))
Craig Topperf40110f2014-04-25 05:29:35 +00001849 return nullptr;
Meador Inge1009cec2012-11-29 15:45:33 +00001850
Peter Collingbourne37ae72b2013-04-17 02:01:10 +00001851 // Do not do any of the following transformations if the fprintf return
1852 // value is used, in general the fprintf return value is not compatible
1853 // with fwrite(), fputc() or fputs().
1854 if (!CI->use_empty())
Craig Topperf40110f2014-04-25 05:29:35 +00001855 return nullptr;
Peter Collingbourne37ae72b2013-04-17 02:01:10 +00001856
Meador Inge1009cec2012-11-29 15:45:33 +00001857 // fprintf(F, "foo") --> fwrite("foo", 3, 1, F)
1858 if (CI->getNumArgOperands() == 2) {
1859 for (unsigned i = 0, e = FormatStr.size(); i != e; ++i)
1860 if (FormatStr[i] == '%') // Could handle %% -> % if we cared.
Craig Topperf40110f2014-04-25 05:29:35 +00001861 return nullptr; // We found a format specifier.
Meador Inge1009cec2012-11-29 15:45:33 +00001862
1863 // These optimizations require DataLayout.
Craig Topperf40110f2014-04-25 05:29:35 +00001864 if (!DL) return nullptr;
Meador Inge1009cec2012-11-29 15:45:33 +00001865
Peter Collingbourne37ae72b2013-04-17 02:01:10 +00001866 return EmitFWrite(CI->getArgOperand(1),
Rafael Espindola37dc9e12014-02-21 00:06:31 +00001867 ConstantInt::get(DL->getIntPtrType(*Context),
Peter Collingbourne37ae72b2013-04-17 02:01:10 +00001868 FormatStr.size()),
Rafael Espindola37dc9e12014-02-21 00:06:31 +00001869 CI->getArgOperand(0), B, DL, TLI);
Meador Inge1009cec2012-11-29 15:45:33 +00001870 }
1871
1872 // The remaining optimizations require the format string to be "%s" or "%c"
1873 // and have an extra operand.
1874 if (FormatStr.size() != 2 || FormatStr[0] != '%' ||
1875 CI->getNumArgOperands() < 3)
Craig Topperf40110f2014-04-25 05:29:35 +00001876 return nullptr;
Meador Inge1009cec2012-11-29 15:45:33 +00001877
1878 // Decode the second character of the format string.
1879 if (FormatStr[1] == 'c') {
1880 // fprintf(F, "%c", chr) --> fputc(chr, F)
Craig Topperf40110f2014-04-25 05:29:35 +00001881 if (!CI->getArgOperand(2)->getType()->isIntegerTy()) return nullptr;
Rafael Espindola37dc9e12014-02-21 00:06:31 +00001882 return EmitFPutC(CI->getArgOperand(2), CI->getArgOperand(0), B, DL, TLI);
Meador Inge1009cec2012-11-29 15:45:33 +00001883 }
1884
1885 if (FormatStr[1] == 's') {
1886 // fprintf(F, "%s", str) --> fputs(str, F)
Peter Collingbourne37ae72b2013-04-17 02:01:10 +00001887 if (!CI->getArgOperand(2)->getType()->isPointerTy())
Craig Topperf40110f2014-04-25 05:29:35 +00001888 return nullptr;
Rafael Espindola37dc9e12014-02-21 00:06:31 +00001889 return EmitFPutS(CI->getArgOperand(2), CI->getArgOperand(0), B, DL, TLI);
Meador Inge1009cec2012-11-29 15:45:33 +00001890 }
Craig Topperf40110f2014-04-25 05:29:35 +00001891 return nullptr;
Meador Inge1009cec2012-11-29 15:45:33 +00001892 }
1893
Craig Topper3e4c6972014-03-05 09:10:37 +00001894 Value *callOptimizer(Function *Callee, CallInst *CI,
1895 IRBuilder<> &B) override {
Meador Inge1009cec2012-11-29 15:45:33 +00001896 // Require two fixed paramters as pointers and integer result.
1897 FunctionType *FT = Callee->getFunctionType();
1898 if (FT->getNumParams() != 2 || !FT->getParamType(0)->isPointerTy() ||
1899 !FT->getParamType(1)->isPointerTy() ||
1900 !FT->getReturnType()->isIntegerTy())
Craig Topperf40110f2014-04-25 05:29:35 +00001901 return nullptr;
Meador Inge1009cec2012-11-29 15:45:33 +00001902
1903 if (Value *V = optimizeFixedFormatString(Callee, CI, B)) {
1904 return V;
1905 }
1906
1907 // fprintf(stream, format, ...) -> fiprintf(stream, format, ...) if no
1908 // floating point arguments.
1909 if (TLI->has(LibFunc::fiprintf) && !callHasFloatingPointArgument(CI)) {
1910 Module *M = B.GetInsertBlock()->getParent()->getParent();
1911 Constant *FIPrintFFn =
1912 M->getOrInsertFunction("fiprintf", FT, Callee->getAttributes());
1913 CallInst *New = cast<CallInst>(CI->clone());
1914 New->setCalledFunction(FIPrintFFn);
1915 B.Insert(New);
1916 return New;
1917 }
Craig Topperf40110f2014-04-25 05:29:35 +00001918 return nullptr;
Meador Inge1009cec2012-11-29 15:45:33 +00001919 }
1920};
1921
Meador Ingebc84d1a2012-11-29 15:45:39 +00001922struct FWriteOpt : public LibCallOptimization {
Craig Topper3e4c6972014-03-05 09:10:37 +00001923 Value *callOptimizer(Function *Callee, CallInst *CI,
1924 IRBuilder<> &B) override {
Hal Finkel66cd3f12013-11-17 02:06:35 +00001925 ErrorReportingOpt ER(/* StreamArg = */ 3);
1926 (void) ER.callOptimizer(Callee, CI, B);
1927
Meador Ingebc84d1a2012-11-29 15:45:39 +00001928 // Require a pointer, an integer, an integer, a pointer, returning integer.
1929 FunctionType *FT = Callee->getFunctionType();
1930 if (FT->getNumParams() != 4 || !FT->getParamType(0)->isPointerTy() ||
1931 !FT->getParamType(1)->isIntegerTy() ||
1932 !FT->getParamType(2)->isIntegerTy() ||
1933 !FT->getParamType(3)->isPointerTy() ||
1934 !FT->getReturnType()->isIntegerTy())
Craig Topperf40110f2014-04-25 05:29:35 +00001935 return nullptr;
Meador Ingebc84d1a2012-11-29 15:45:39 +00001936
1937 // Get the element size and count.
1938 ConstantInt *SizeC = dyn_cast<ConstantInt>(CI->getArgOperand(1));
1939 ConstantInt *CountC = dyn_cast<ConstantInt>(CI->getArgOperand(2));
Craig Topperf40110f2014-04-25 05:29:35 +00001940 if (!SizeC || !CountC) return nullptr;
Meador Ingebc84d1a2012-11-29 15:45:39 +00001941 uint64_t Bytes = SizeC->getZExtValue()*CountC->getZExtValue();
1942
1943 // If this is writing zero records, remove the call (it's a noop).
1944 if (Bytes == 0)
1945 return ConstantInt::get(CI->getType(), 0);
1946
1947 // If this is writing one byte, turn it into fputc.
1948 // This optimisation is only valid, if the return value is unused.
1949 if (Bytes == 1 && CI->use_empty()) { // fwrite(S,1,1,F) -> fputc(S[0],F)
1950 Value *Char = B.CreateLoad(CastToCStr(CI->getArgOperand(0), B), "char");
Rafael Espindola37dc9e12014-02-21 00:06:31 +00001951 Value *NewCI = EmitFPutC(Char, CI->getArgOperand(3), B, DL, TLI);
Craig Topperf40110f2014-04-25 05:29:35 +00001952 return NewCI ? ConstantInt::get(CI->getType(), 1) : nullptr;
Meador Ingebc84d1a2012-11-29 15:45:39 +00001953 }
1954
Craig Topperf40110f2014-04-25 05:29:35 +00001955 return nullptr;
Meador Ingebc84d1a2012-11-29 15:45:39 +00001956 }
1957};
1958
Meador Ingef8e72502012-11-29 15:45:43 +00001959struct FPutsOpt : public LibCallOptimization {
Craig Topper3e4c6972014-03-05 09:10:37 +00001960 Value *callOptimizer(Function *Callee, CallInst *CI,
1961 IRBuilder<> &B) override {
Hal Finkel66cd3f12013-11-17 02:06:35 +00001962 ErrorReportingOpt ER(/* StreamArg = */ 1);
1963 (void) ER.callOptimizer(Callee, CI, B);
1964
Meador Ingef8e72502012-11-29 15:45:43 +00001965 // These optimizations require DataLayout.
Craig Topperf40110f2014-04-25 05:29:35 +00001966 if (!DL) return nullptr;
Meador Ingef8e72502012-11-29 15:45:43 +00001967
1968 // Require two pointers. Also, we can't optimize if return value is used.
1969 FunctionType *FT = Callee->getFunctionType();
1970 if (FT->getNumParams() != 2 || !FT->getParamType(0)->isPointerTy() ||
1971 !FT->getParamType(1)->isPointerTy() ||
1972 !CI->use_empty())
Craig Topperf40110f2014-04-25 05:29:35 +00001973 return nullptr;
Meador Ingef8e72502012-11-29 15:45:43 +00001974
1975 // fputs(s,F) --> fwrite(s,1,strlen(s),F)
1976 uint64_t Len = GetStringLength(CI->getArgOperand(0));
Craig Topperf40110f2014-04-25 05:29:35 +00001977 if (!Len) return nullptr;
Meador Ingef8e72502012-11-29 15:45:43 +00001978 // Known to have no uses (see above).
1979 return EmitFWrite(CI->getArgOperand(0),
Rafael Espindola37dc9e12014-02-21 00:06:31 +00001980 ConstantInt::get(DL->getIntPtrType(*Context), Len-1),
1981 CI->getArgOperand(1), B, DL, TLI);
Meador Ingef8e72502012-11-29 15:45:43 +00001982 }
1983};
1984
Meador Inge75798bb2012-11-29 19:15:17 +00001985struct PutsOpt : public LibCallOptimization {
Craig Topper3e4c6972014-03-05 09:10:37 +00001986 Value *callOptimizer(Function *Callee, CallInst *CI,
1987 IRBuilder<> &B) override {
Meador Inge75798bb2012-11-29 19:15:17 +00001988 // Require one fixed pointer argument and an integer/void result.
1989 FunctionType *FT = Callee->getFunctionType();
1990 if (FT->getNumParams() < 1 || !FT->getParamType(0)->isPointerTy() ||
1991 !(FT->getReturnType()->isIntegerTy() ||
1992 FT->getReturnType()->isVoidTy()))
Craig Topperf40110f2014-04-25 05:29:35 +00001993 return nullptr;
Meador Inge75798bb2012-11-29 19:15:17 +00001994
1995 // Check for a constant string.
1996 StringRef Str;
1997 if (!getConstantStringInfo(CI->getArgOperand(0), Str))
Craig Topperf40110f2014-04-25 05:29:35 +00001998 return nullptr;
Meador Inge75798bb2012-11-29 19:15:17 +00001999
2000 if (Str.empty() && CI->use_empty()) {
2001 // puts("") -> putchar('\n')
Rafael Espindola37dc9e12014-02-21 00:06:31 +00002002 Value *Res = EmitPutChar(B.getInt32('\n'), B, DL, TLI);
Meador Inge75798bb2012-11-29 19:15:17 +00002003 if (CI->use_empty() || !Res) return Res;
2004 return B.CreateIntCast(Res, CI->getType(), true);
2005 }
2006
Craig Topperf40110f2014-04-25 05:29:35 +00002007 return nullptr;
Meador Inge75798bb2012-11-29 19:15:17 +00002008 }
2009};
2010
Meador Ingedf796f82012-10-13 16:45:24 +00002011} // End anonymous namespace.
2012
2013namespace llvm {
2014
2015class LibCallSimplifierImpl {
Rafael Espindola37dc9e12014-02-21 00:06:31 +00002016 const DataLayout *DL;
Meador Ingedf796f82012-10-13 16:45:24 +00002017 const TargetLibraryInfo *TLI;
Meador Inge76fc1a42012-11-11 03:51:43 +00002018 const LibCallSimplifier *LCS;
Meador Inge193e0352012-11-13 04:16:17 +00002019 bool UnsafeFPShrink;
Meador Inge4d2827c2012-11-11 05:11:20 +00002020
Meador Inge193e0352012-11-13 04:16:17 +00002021 // Math library call optimizations.
Meador Inge20255ef2013-03-12 00:08:29 +00002022 CosOpt Cos;
2023 PowOpt Pow;
2024 Exp2Opt Exp2;
Meador Ingedf796f82012-10-13 16:45:24 +00002025public:
Rafael Espindola37dc9e12014-02-21 00:06:31 +00002026 LibCallSimplifierImpl(const DataLayout *DL, const TargetLibraryInfo *TLI,
Meador Inge193e0352012-11-13 04:16:17 +00002027 const LibCallSimplifier *LCS,
2028 bool UnsafeFPShrink = false)
Meador Inge20255ef2013-03-12 00:08:29 +00002029 : Cos(UnsafeFPShrink), Pow(UnsafeFPShrink), Exp2(UnsafeFPShrink) {
Rafael Espindola37dc9e12014-02-21 00:06:31 +00002030 this->DL = DL;
Meador Ingedf796f82012-10-13 16:45:24 +00002031 this->TLI = TLI;
Meador Inge76fc1a42012-11-11 03:51:43 +00002032 this->LCS = LCS;
Meador Inge193e0352012-11-13 04:16:17 +00002033 this->UnsafeFPShrink = UnsafeFPShrink;
Meador Ingedf796f82012-10-13 16:45:24 +00002034 }
2035
2036 Value *optimizeCall(CallInst *CI);
Meador Inge20255ef2013-03-12 00:08:29 +00002037 LibCallOptimization *lookupOptimization(CallInst *CI);
2038 bool hasFloatVersion(StringRef FuncName);
Meador Ingedf796f82012-10-13 16:45:24 +00002039};
2040
Meador Inge20255ef2013-03-12 00:08:29 +00002041bool LibCallSimplifierImpl::hasFloatVersion(StringRef FuncName) {
2042 LibFunc::Func Func;
2043 SmallString<20> FloatFuncName = FuncName;
2044 FloatFuncName += 'f';
2045 if (TLI->getLibFunc(FloatFuncName, Func))
2046 return TLI->has(Func);
2047 return false;
2048}
Meador Inge7fb2f732012-10-13 16:45:32 +00002049
Meador Inge20255ef2013-03-12 00:08:29 +00002050// Fortified library call optimizations.
2051static MemCpyChkOpt MemCpyChk;
2052static MemMoveChkOpt MemMoveChk;
2053static MemSetChkOpt MemSetChk;
2054static StrCpyChkOpt StrCpyChk;
2055static StpCpyChkOpt StpCpyChk;
2056static StrNCpyChkOpt StrNCpyChk;
Meador Inge4d2827c2012-11-11 05:11:20 +00002057
Meador Inge20255ef2013-03-12 00:08:29 +00002058// String library call optimizations.
2059static StrCatOpt StrCat;
2060static StrNCatOpt StrNCat;
2061static StrChrOpt StrChr;
2062static StrRChrOpt StrRChr;
2063static StrCmpOpt StrCmp;
2064static StrNCmpOpt StrNCmp;
2065static StrCpyOpt StrCpy;
2066static StpCpyOpt StpCpy;
2067static StrNCpyOpt StrNCpy;
2068static StrLenOpt StrLen;
2069static StrPBrkOpt StrPBrk;
2070static StrToOpt StrTo;
2071static StrSpnOpt StrSpn;
2072static StrCSpnOpt StrCSpn;
2073static StrStrOpt StrStr;
Meador Inge193e0352012-11-13 04:16:17 +00002074
Meador Inge20255ef2013-03-12 00:08:29 +00002075// Memory library call optimizations.
2076static MemCmpOpt MemCmp;
2077static MemCpyOpt MemCpy;
2078static MemMoveOpt MemMove;
2079static MemSetOpt MemSet;
Meador Inge193e0352012-11-13 04:16:17 +00002080
Meador Inge20255ef2013-03-12 00:08:29 +00002081// Math library call optimizations.
2082static UnaryDoubleFPOpt UnaryDoubleFP(false);
Yi Jiang6ab044e2013-12-16 22:42:40 +00002083static BinaryDoubleFPOpt BinaryDoubleFP(false);
Meador Inge20255ef2013-03-12 00:08:29 +00002084static UnaryDoubleFPOpt UnsafeUnaryDoubleFP(true);
Bob Wilsond8d92d92013-11-03 06:48:38 +00002085static SinCosPiOpt SinCosPi;
Meador Inge7415f842012-11-25 20:45:27 +00002086
2087 // Integer library call optimizations.
Meador Inge20255ef2013-03-12 00:08:29 +00002088static FFSOpt FFS;
2089static AbsOpt Abs;
2090static IsDigitOpt IsDigit;
2091static IsAsciiOpt IsAscii;
2092static ToAsciiOpt ToAscii;
Meador Inge08ca1152012-11-26 20:37:20 +00002093
Meador Inge20255ef2013-03-12 00:08:29 +00002094// Formatting and IO library call optimizations.
Hal Finkel66cd3f12013-11-17 02:06:35 +00002095static ErrorReportingOpt ErrorReporting;
2096static ErrorReportingOpt ErrorReporting0(0);
2097static ErrorReportingOpt ErrorReporting1(1);
Meador Inge20255ef2013-03-12 00:08:29 +00002098static PrintFOpt PrintF;
2099static SPrintFOpt SPrintF;
2100static FPrintFOpt FPrintF;
2101static FWriteOpt FWrite;
2102static FPutsOpt FPuts;
2103static PutsOpt Puts;
2104
2105LibCallOptimization *LibCallSimplifierImpl::lookupOptimization(CallInst *CI) {
2106 LibFunc::Func Func;
2107 Function *Callee = CI->getCalledFunction();
2108 StringRef FuncName = Callee->getName();
2109
2110 // Next check for intrinsics.
2111 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(CI)) {
2112 switch (II->getIntrinsicID()) {
2113 case Intrinsic::pow:
2114 return &Pow;
2115 case Intrinsic::exp2:
2116 return &Exp2;
2117 default:
Craig Topperf40110f2014-04-25 05:29:35 +00002118 return nullptr;
Meador Inge20255ef2013-03-12 00:08:29 +00002119 }
2120 }
2121
2122 // Then check for known library functions.
2123 if (TLI->getLibFunc(FuncName, Func) && TLI->has(Func)) {
2124 switch (Func) {
2125 case LibFunc::strcat:
2126 return &StrCat;
2127 case LibFunc::strncat:
2128 return &StrNCat;
2129 case LibFunc::strchr:
2130 return &StrChr;
2131 case LibFunc::strrchr:
2132 return &StrRChr;
2133 case LibFunc::strcmp:
2134 return &StrCmp;
2135 case LibFunc::strncmp:
2136 return &StrNCmp;
2137 case LibFunc::strcpy:
2138 return &StrCpy;
2139 case LibFunc::stpcpy:
2140 return &StpCpy;
2141 case LibFunc::strncpy:
2142 return &StrNCpy;
2143 case LibFunc::strlen:
2144 return &StrLen;
2145 case LibFunc::strpbrk:
2146 return &StrPBrk;
2147 case LibFunc::strtol:
2148 case LibFunc::strtod:
2149 case LibFunc::strtof:
2150 case LibFunc::strtoul:
2151 case LibFunc::strtoll:
2152 case LibFunc::strtold:
2153 case LibFunc::strtoull:
2154 return &StrTo;
2155 case LibFunc::strspn:
2156 return &StrSpn;
2157 case LibFunc::strcspn:
2158 return &StrCSpn;
2159 case LibFunc::strstr:
2160 return &StrStr;
2161 case LibFunc::memcmp:
2162 return &MemCmp;
2163 case LibFunc::memcpy:
2164 return &MemCpy;
2165 case LibFunc::memmove:
2166 return &MemMove;
2167 case LibFunc::memset:
2168 return &MemSet;
2169 case LibFunc::cosf:
2170 case LibFunc::cos:
2171 case LibFunc::cosl:
2172 return &Cos;
Bob Wilsond8d92d92013-11-03 06:48:38 +00002173 case LibFunc::sinpif:
2174 case LibFunc::sinpi:
2175 case LibFunc::cospif:
2176 case LibFunc::cospi:
2177 return &SinCosPi;
Meador Inge20255ef2013-03-12 00:08:29 +00002178 case LibFunc::powf:
2179 case LibFunc::pow:
2180 case LibFunc::powl:
2181 return &Pow;
2182 case LibFunc::exp2l:
2183 case LibFunc::exp2:
2184 case LibFunc::exp2f:
2185 return &Exp2;
2186 case LibFunc::ffs:
2187 case LibFunc::ffsl:
2188 case LibFunc::ffsll:
2189 return &FFS;
2190 case LibFunc::abs:
2191 case LibFunc::labs:
2192 case LibFunc::llabs:
2193 return &Abs;
2194 case LibFunc::isdigit:
2195 return &IsDigit;
2196 case LibFunc::isascii:
2197 return &IsAscii;
2198 case LibFunc::toascii:
2199 return &ToAscii;
2200 case LibFunc::printf:
2201 return &PrintF;
2202 case LibFunc::sprintf:
2203 return &SPrintF;
2204 case LibFunc::fprintf:
2205 return &FPrintF;
2206 case LibFunc::fwrite:
2207 return &FWrite;
2208 case LibFunc::fputs:
2209 return &FPuts;
2210 case LibFunc::puts:
2211 return &Puts;
Hal Finkel66cd3f12013-11-17 02:06:35 +00002212 case LibFunc::perror:
2213 return &ErrorReporting;
2214 case LibFunc::vfprintf:
2215 case LibFunc::fiprintf:
2216 return &ErrorReporting0;
2217 case LibFunc::fputc:
2218 return &ErrorReporting1;
Meador Inge20255ef2013-03-12 00:08:29 +00002219 case LibFunc::ceil:
2220 case LibFunc::fabs:
2221 case LibFunc::floor:
2222 case LibFunc::rint:
2223 case LibFunc::round:
2224 case LibFunc::nearbyint:
2225 case LibFunc::trunc:
2226 if (hasFloatVersion(FuncName))
2227 return &UnaryDoubleFP;
Craig Topperf40110f2014-04-25 05:29:35 +00002228 return nullptr;
Meador Inge20255ef2013-03-12 00:08:29 +00002229 case LibFunc::acos:
2230 case LibFunc::acosh:
2231 case LibFunc::asin:
2232 case LibFunc::asinh:
2233 case LibFunc::atan:
2234 case LibFunc::atanh:
2235 case LibFunc::cbrt:
2236 case LibFunc::cosh:
2237 case LibFunc::exp:
2238 case LibFunc::exp10:
2239 case LibFunc::expm1:
2240 case LibFunc::log:
2241 case LibFunc::log10:
2242 case LibFunc::log1p:
2243 case LibFunc::log2:
2244 case LibFunc::logb:
2245 case LibFunc::sin:
2246 case LibFunc::sinh:
2247 case LibFunc::sqrt:
2248 case LibFunc::tan:
2249 case LibFunc::tanh:
2250 if (UnsafeFPShrink && hasFloatVersion(FuncName))
2251 return &UnsafeUnaryDoubleFP;
Craig Topperf40110f2014-04-25 05:29:35 +00002252 return nullptr;
Yi Jiang6ab044e2013-12-16 22:42:40 +00002253 case LibFunc::fmin:
2254 case LibFunc::fmax:
2255 if (hasFloatVersion(FuncName))
2256 return &BinaryDoubleFP;
Craig Topperf40110f2014-04-25 05:29:35 +00002257 return nullptr;
Meador Inge20255ef2013-03-12 00:08:29 +00002258 case LibFunc::memcpy_chk:
2259 return &MemCpyChk;
2260 default:
Craig Topperf40110f2014-04-25 05:29:35 +00002261 return nullptr;
Meador Inge20255ef2013-03-12 00:08:29 +00002262 }
2263 }
2264
2265 // Finally check for fortified library calls.
2266 if (FuncName.endswith("_chk")) {
2267 if (FuncName == "__memmove_chk")
2268 return &MemMoveChk;
2269 else if (FuncName == "__memset_chk")
2270 return &MemSetChk;
2271 else if (FuncName == "__strcpy_chk")
2272 return &StrCpyChk;
2273 else if (FuncName == "__stpcpy_chk")
2274 return &StpCpyChk;
2275 else if (FuncName == "__strncpy_chk")
2276 return &StrNCpyChk;
2277 else if (FuncName == "__stpncpy_chk")
2278 return &StrNCpyChk;
2279 }
2280
Craig Topperf40110f2014-04-25 05:29:35 +00002281 return nullptr;
Meador Inge20255ef2013-03-12 00:08:29 +00002282
Meador Ingedf796f82012-10-13 16:45:24 +00002283}
2284
2285Value *LibCallSimplifierImpl::optimizeCall(CallInst *CI) {
Meador Inge20255ef2013-03-12 00:08:29 +00002286 LibCallOptimization *LCO = lookupOptimization(CI);
Meador Ingedf796f82012-10-13 16:45:24 +00002287 if (LCO) {
2288 IRBuilder<> Builder(CI);
Rafael Espindola37dc9e12014-02-21 00:06:31 +00002289 return LCO->optimizeCall(CI, DL, TLI, LCS, Builder);
Meador Ingedf796f82012-10-13 16:45:24 +00002290 }
Craig Topperf40110f2014-04-25 05:29:35 +00002291 return nullptr;
Meador Ingedf796f82012-10-13 16:45:24 +00002292}
2293
Rafael Espindola37dc9e12014-02-21 00:06:31 +00002294LibCallSimplifier::LibCallSimplifier(const DataLayout *DL,
Meador Inge193e0352012-11-13 04:16:17 +00002295 const TargetLibraryInfo *TLI,
2296 bool UnsafeFPShrink) {
Rafael Espindola37dc9e12014-02-21 00:06:31 +00002297 Impl = new LibCallSimplifierImpl(DL, TLI, this, UnsafeFPShrink);
Meador Ingedf796f82012-10-13 16:45:24 +00002298}
2299
2300LibCallSimplifier::~LibCallSimplifier() {
2301 delete Impl;
2302}
2303
2304Value *LibCallSimplifier::optimizeCall(CallInst *CI) {
Craig Topperf40110f2014-04-25 05:29:35 +00002305 if (CI->isNoBuiltin()) return nullptr;
Meador Ingedf796f82012-10-13 16:45:24 +00002306 return Impl->optimizeCall(CI);
2307}
2308
Meador Inge76fc1a42012-11-11 03:51:43 +00002309void LibCallSimplifier::replaceAllUsesWith(Instruction *I, Value *With) const {
2310 I->replaceAllUsesWith(With);
2311 I->eraseFromParent();
2312}
2313
Meador Ingedf796f82012-10-13 16:45:24 +00002314}
Meador Ingedfb08a22013-06-20 19:48:07 +00002315
2316// TODO:
2317// Additional cases that we need to add to this file:
2318//
2319// cbrt:
2320// * cbrt(expN(X)) -> expN(x/3)
2321// * cbrt(sqrt(x)) -> pow(x,1/6)
2322// * cbrt(sqrt(x)) -> pow(x,1/9)
2323//
2324// exp, expf, expl:
2325// * exp(log(x)) -> x
2326//
2327// log, logf, logl:
2328// * log(exp(x)) -> x
2329// * log(x**y) -> y*log(x)
2330// * log(exp(y)) -> y*log(e)
2331// * log(exp2(y)) -> y*log(2)
2332// * log(exp10(y)) -> y*log(10)
2333// * log(sqrt(x)) -> 0.5*log(x)
2334// * log(pow(x,y)) -> y*log(x)
2335//
2336// lround, lroundf, lroundl:
2337// * lround(cnst) -> cnst'
2338//
2339// pow, powf, powl:
2340// * pow(exp(x),y) -> exp(x*y)
2341// * pow(sqrt(x),y) -> pow(x,y*0.5)
2342// * pow(pow(x,y),z)-> pow(x,y*z)
2343//
2344// round, roundf, roundl:
2345// * round(cnst) -> cnst'
2346//
2347// signbit:
2348// * signbit(cnst) -> cnst'
2349// * signbit(nncst) -> 0 (if pstv is a non-negative constant)
2350//
2351// sqrt, sqrtf, sqrtl:
2352// * sqrt(expN(x)) -> expN(x*0.5)
2353// * sqrt(Nroot(x)) -> pow(x,1/(2*N))
2354// * sqrt(pow(x,y)) -> pow(|x|,y*0.5)
2355//
Meador Ingedfb08a22013-06-20 19:48:07 +00002356// tan, tanf, tanl:
2357// * tan(atan(x)) -> x
2358//
2359// trunc, truncf, truncl:
2360// * trunc(cnst) -> cnst'
2361//
2362//