blob: 126160dbbc37f7e7c472aa263d44871e77508205 [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)
Meador Ingedf796f82012-10-13 16:45:24 +000078 return NULL;
79
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) {
91 for (Value::use_iterator UI = V->use_begin(), E = V->use_end();
92 UI != E; ++UI) {
93 if (ICmpInst *IC = dyn_cast<ICmpInst>(*UI))
94 if (IC->isEquality())
95 if (Constant *C = dyn_cast<Constant>(IC->getOperand(1)))
96 if (C->isNullValue())
97 continue;
98 // Unknown instruction.
99 return false;
100 }
101 return true;
102}
103
Meador Inge56edbc92012-11-11 03:51:48 +0000104/// isOnlyUsedInEqualityComparison - Return true if it is only used in equality
105/// comparisons with With.
106static bool isOnlyUsedInEqualityComparison(Value *V, Value *With) {
107 for (Value::use_iterator UI = V->use_begin(), E = V->use_end();
108 UI != E; ++UI) {
109 if (ICmpInst *IC = dyn_cast<ICmpInst>(*UI))
110 if (IC->isEquality() && IC->getOperand(1) == With)
111 continue;
112 // Unknown instruction.
113 return false;
114 }
115 return true;
116}
117
Meador Inge08ca1152012-11-26 20:37:20 +0000118static bool callHasFloatingPointArgument(const CallInst *CI) {
119 for (CallInst::const_op_iterator it = CI->op_begin(), e = CI->op_end();
120 it != e; ++it) {
121 if ((*it)->getType()->isFloatingPointTy())
122 return true;
123 }
124 return false;
125}
126
Benjamin Kramer2702caa2013-08-31 18:19:35 +0000127/// \brief Check whether the overloaded unary floating point function
128/// corresponing to \a Ty is available.
129static bool hasUnaryFloatFn(const TargetLibraryInfo *TLI, Type *Ty,
130 LibFunc::Func DoubleFn, LibFunc::Func FloatFn,
131 LibFunc::Func LongDoubleFn) {
132 switch (Ty->getTypeID()) {
133 case Type::FloatTyID:
134 return TLI->has(FloatFn);
135 case Type::DoubleTyID:
136 return TLI->has(DoubleFn);
137 default:
138 return TLI->has(LongDoubleFn);
139 }
140}
141
Meador Inged589ac62012-10-31 03:33:06 +0000142//===----------------------------------------------------------------------===//
Meador Ingedf796f82012-10-13 16:45:24 +0000143// Fortified Library Call Optimizations
144//===----------------------------------------------------------------------===//
145
146struct FortifiedLibCallOptimization : public LibCallOptimization {
147protected:
148 virtual bool isFoldable(unsigned SizeCIOp, unsigned SizeArgOp,
149 bool isString) const = 0;
150};
151
152struct InstFortifiedLibCallOptimization : public FortifiedLibCallOptimization {
153 CallInst *CI;
154
155 bool isFoldable(unsigned SizeCIOp, unsigned SizeArgOp, bool isString) const {
156 if (CI->getArgOperand(SizeCIOp) == CI->getArgOperand(SizeArgOp))
157 return true;
158 if (ConstantInt *SizeCI =
159 dyn_cast<ConstantInt>(CI->getArgOperand(SizeCIOp))) {
160 if (SizeCI->isAllOnesValue())
161 return true;
162 if (isString) {
163 uint64_t Len = GetStringLength(CI->getArgOperand(SizeArgOp));
164 // If the length is 0 we don't know how long it is and so we can't
165 // remove the check.
166 if (Len == 0) return false;
167 return SizeCI->getZExtValue() >= Len;
168 }
169 if (ConstantInt *Arg = dyn_cast<ConstantInt>(
170 CI->getArgOperand(SizeArgOp)))
171 return SizeCI->getZExtValue() >= Arg->getZExtValue();
172 }
173 return false;
174 }
175};
176
177struct MemCpyChkOpt : public InstFortifiedLibCallOptimization {
178 virtual Value *callOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
179 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))
Meador Ingedf796f82012-10-13 16:45:24 +0000189 return 0;
190
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 }
196 return 0;
197 }
198};
199
200struct MemMoveChkOpt : public InstFortifiedLibCallOptimization {
201 virtual Value *callOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
202 this->CI = CI;
203 FunctionType *FT = Callee->getFunctionType();
Chandler Carruth7ec50852012-11-01 08:07:29 +0000204 LLVMContext &Context = CI->getParent()->getContext();
Meador Ingedf796f82012-10-13 16:45:24 +0000205
206 // Check if this has the right signature.
207 if (FT->getNumParams() != 4 || FT->getReturnType() != FT->getParamType(0) ||
208 !FT->getParamType(0)->isPointerTy() ||
209 !FT->getParamType(1)->isPointerTy() ||
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000210 FT->getParamType(2) != DL->getIntPtrType(Context) ||
211 FT->getParamType(3) != DL->getIntPtrType(Context))
Meador Ingedf796f82012-10-13 16:45:24 +0000212 return 0;
213
214 if (isFoldable(3, 2, false)) {
215 B.CreateMemMove(CI->getArgOperand(0), CI->getArgOperand(1),
216 CI->getArgOperand(2), 1);
217 return CI->getArgOperand(0);
218 }
219 return 0;
220 }
221};
222
223struct MemSetChkOpt : public InstFortifiedLibCallOptimization {
224 virtual Value *callOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
225 this->CI = CI;
226 FunctionType *FT = Callee->getFunctionType();
Chandler Carruth7ec50852012-11-01 08:07:29 +0000227 LLVMContext &Context = CI->getParent()->getContext();
Meador Ingedf796f82012-10-13 16:45:24 +0000228
229 // Check if this has the right signature.
230 if (FT->getNumParams() != 4 || FT->getReturnType() != FT->getParamType(0) ||
231 !FT->getParamType(0)->isPointerTy() ||
232 !FT->getParamType(1)->isIntegerTy() ||
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000233 FT->getParamType(2) != DL->getIntPtrType(Context) ||
234 FT->getParamType(3) != DL->getIntPtrType(Context))
Meador Ingedf796f82012-10-13 16:45:24 +0000235 return 0;
236
237 if (isFoldable(3, 2, false)) {
238 Value *Val = B.CreateIntCast(CI->getArgOperand(1), B.getInt8Ty(),
239 false);
240 B.CreateMemSet(CI->getArgOperand(0), Val, CI->getArgOperand(2), 1);
241 return CI->getArgOperand(0);
242 }
243 return 0;
244 }
245};
246
247struct StrCpyChkOpt : public InstFortifiedLibCallOptimization {
248 virtual Value *callOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
249 this->CI = CI;
250 StringRef Name = Callee->getName();
251 FunctionType *FT = Callee->getFunctionType();
252 LLVMContext &Context = CI->getParent()->getContext();
253
254 // Check if this has the right signature.
255 if (FT->getNumParams() != 3 ||
256 FT->getReturnType() != FT->getParamType(0) ||
257 FT->getParamType(0) != FT->getParamType(1) ||
258 FT->getParamType(0) != Type::getInt8PtrTy(Context) ||
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000259 FT->getParamType(2) != DL->getIntPtrType(Context))
Meador Ingedf796f82012-10-13 16:45:24 +0000260 return 0;
261
Meador Inge000dbcc2012-10-18 18:12:40 +0000262 Value *Dst = CI->getArgOperand(0), *Src = CI->getArgOperand(1);
263 if (Dst == Src) // __strcpy_chk(x,x) -> x
264 return Src;
265
Meador Ingedf796f82012-10-13 16:45:24 +0000266 // If a) we don't have any length information, or b) we know this will
Meador Ingecdb2ca52012-10-31 00:20:51 +0000267 // fit then just lower to a plain strcpy. Otherwise we'll keep our
268 // strcpy_chk call which may fail at runtime if the size is too long.
Meador Ingedf796f82012-10-13 16:45:24 +0000269 // TODO: It might be nice to get a maximum length out of the possible
270 // string lengths for varying.
271 if (isFoldable(2, 1, true)) {
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000272 Value *Ret = EmitStrCpy(Dst, Src, B, DL, TLI, Name.substr(2, 6));
Meador Inge000dbcc2012-10-18 18:12:40 +0000273 return Ret;
274 } else {
275 // Maybe we can stil fold __strcpy_chk to __memcpy_chk.
276 uint64_t Len = GetStringLength(Src);
277 if (Len == 0) return 0;
278
279 // This optimization require DataLayout.
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000280 if (!DL) return 0;
Meador Inge000dbcc2012-10-18 18:12:40 +0000281
282 Value *Ret =
283 EmitMemCpyChk(Dst, Src,
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000284 ConstantInt::get(DL->getIntPtrType(Context), Len),
285 CI->getArgOperand(2), B, DL, TLI);
Meador Ingedf796f82012-10-13 16:45:24 +0000286 return Ret;
287 }
288 return 0;
289 }
290};
291
Meador Ingecdb2ca52012-10-31 00:20:51 +0000292struct StpCpyChkOpt : public InstFortifiedLibCallOptimization {
293 virtual Value *callOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
294 this->CI = CI;
295 StringRef Name = Callee->getName();
296 FunctionType *FT = Callee->getFunctionType();
297 LLVMContext &Context = CI->getParent()->getContext();
298
299 // Check if this has the right signature.
300 if (FT->getNumParams() != 3 ||
301 FT->getReturnType() != FT->getParamType(0) ||
302 FT->getParamType(0) != FT->getParamType(1) ||
303 FT->getParamType(0) != Type::getInt8PtrTy(Context) ||
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000304 FT->getParamType(2) != DL->getIntPtrType(FT->getParamType(0)))
Meador Ingecdb2ca52012-10-31 00:20:51 +0000305 return 0;
306
307 Value *Dst = CI->getArgOperand(0), *Src = CI->getArgOperand(1);
308 if (Dst == Src) { // stpcpy(x,x) -> x+strlen(x)
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000309 Value *StrLen = EmitStrLen(Src, B, DL, TLI);
Meador Ingecdb2ca52012-10-31 00:20:51 +0000310 return StrLen ? B.CreateInBoundsGEP(Dst, StrLen) : 0;
311 }
312
313 // If a) we don't have any length information, or b) we know this will
314 // fit then just lower to a plain stpcpy. Otherwise we'll keep our
315 // stpcpy_chk call which may fail at runtime if the size is too long.
316 // TODO: It might be nice to get a maximum length out of the possible
317 // string lengths for varying.
318 if (isFoldable(2, 1, true)) {
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000319 Value *Ret = EmitStrCpy(Dst, Src, B, DL, TLI, Name.substr(2, 6));
Meador Ingecdb2ca52012-10-31 00:20:51 +0000320 return Ret;
321 } else {
322 // Maybe we can stil fold __stpcpy_chk to __memcpy_chk.
323 uint64_t Len = GetStringLength(Src);
324 if (Len == 0) return 0;
325
326 // This optimization require DataLayout.
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000327 if (!DL) return 0;
Meador Ingecdb2ca52012-10-31 00:20:51 +0000328
329 Type *PT = FT->getParamType(0);
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000330 Value *LenV = ConstantInt::get(DL->getIntPtrType(PT), Len);
Meador Ingecdb2ca52012-10-31 00:20:51 +0000331 Value *DstEnd = B.CreateGEP(Dst,
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000332 ConstantInt::get(DL->getIntPtrType(PT),
Meador Ingecdb2ca52012-10-31 00:20:51 +0000333 Len - 1));
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000334 if (!EmitMemCpyChk(Dst, Src, LenV, CI->getArgOperand(2), B, DL, TLI))
Meador Ingecdb2ca52012-10-31 00:20:51 +0000335 return 0;
336 return DstEnd;
337 }
338 return 0;
339 }
340};
341
Meador Ingedf796f82012-10-13 16:45:24 +0000342struct StrNCpyChkOpt : public InstFortifiedLibCallOptimization {
343 virtual Value *callOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
344 this->CI = CI;
345 StringRef Name = Callee->getName();
346 FunctionType *FT = Callee->getFunctionType();
347 LLVMContext &Context = CI->getParent()->getContext();
348
349 // Check if this has the right signature.
350 if (FT->getNumParams() != 4 || FT->getReturnType() != FT->getParamType(0) ||
351 FT->getParamType(0) != FT->getParamType(1) ||
352 FT->getParamType(0) != Type::getInt8PtrTy(Context) ||
353 !FT->getParamType(2)->isIntegerTy() ||
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000354 FT->getParamType(3) != DL->getIntPtrType(Context))
Meador Ingedf796f82012-10-13 16:45:24 +0000355 return 0;
356
357 if (isFoldable(3, 2, false)) {
358 Value *Ret = EmitStrNCpy(CI->getArgOperand(0), CI->getArgOperand(1),
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000359 CI->getArgOperand(2), B, DL, TLI,
Meador Ingedf796f82012-10-13 16:45:24 +0000360 Name.substr(2, 7));
361 return Ret;
362 }
363 return 0;
364 }
365};
366
Meador Inge7fb2f732012-10-13 16:45:32 +0000367//===----------------------------------------------------------------------===//
368// String and Memory Library Call Optimizations
369//===----------------------------------------------------------------------===//
370
371struct StrCatOpt : public LibCallOptimization {
372 virtual Value *callOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
373 // Verify the "strcat" function prototype.
374 FunctionType *FT = Callee->getFunctionType();
375 if (FT->getNumParams() != 2 ||
376 FT->getReturnType() != B.getInt8PtrTy() ||
377 FT->getParamType(0) != FT->getReturnType() ||
378 FT->getParamType(1) != FT->getReturnType())
379 return 0;
380
381 // Extract some information from the instruction
382 Value *Dst = CI->getArgOperand(0);
383 Value *Src = CI->getArgOperand(1);
384
385 // See if we can get the length of the input string.
386 uint64_t Len = GetStringLength(Src);
387 if (Len == 0) return 0;
388 --Len; // Unbias length.
389
390 // Handle the simple, do-nothing case: strcat(x, "") -> x
391 if (Len == 0)
392 return Dst;
393
394 // These optimizations require DataLayout.
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000395 if (!DL) return 0;
Meador Inge7fb2f732012-10-13 16:45:32 +0000396
397 return emitStrLenMemCpy(Src, Dst, Len, B);
398 }
399
400 Value *emitStrLenMemCpy(Value *Src, Value *Dst, uint64_t Len,
401 IRBuilder<> &B) {
402 // We need to find the end of the destination string. That's where the
403 // memory is to be moved to. We just generate a call to strlen.
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000404 Value *DstLen = EmitStrLen(Dst, B, DL, TLI);
Meador Inge7fb2f732012-10-13 16:45:32 +0000405 if (!DstLen)
406 return 0;
407
408 // Now that we have the destination's length, we must index into the
409 // destination's pointer to get the actual memcpy destination (end of
410 // the string .. we're concatenating).
411 Value *CpyDst = B.CreateGEP(Dst, DstLen, "endptr");
412
413 // We have enough information to now generate the memcpy call to do the
414 // concatenation for us. Make a memcpy to copy the nul byte with align = 1.
415 B.CreateMemCpy(CpyDst, Src,
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000416 ConstantInt::get(DL->getIntPtrType(*Context), Len + 1), 1);
Meador Inge7fb2f732012-10-13 16:45:32 +0000417 return Dst;
418 }
419};
420
421struct StrNCatOpt : public StrCatOpt {
422 virtual Value *callOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
423 // Verify the "strncat" function prototype.
424 FunctionType *FT = Callee->getFunctionType();
425 if (FT->getNumParams() != 3 ||
426 FT->getReturnType() != B.getInt8PtrTy() ||
427 FT->getParamType(0) != FT->getReturnType() ||
428 FT->getParamType(1) != FT->getReturnType() ||
429 !FT->getParamType(2)->isIntegerTy())
430 return 0;
431
432 // Extract some information from the instruction
433 Value *Dst = CI->getArgOperand(0);
434 Value *Src = CI->getArgOperand(1);
435 uint64_t Len;
436
437 // We don't do anything if length is not constant
438 if (ConstantInt *LengthArg = dyn_cast<ConstantInt>(CI->getArgOperand(2)))
439 Len = LengthArg->getZExtValue();
440 else
441 return 0;
442
443 // See if we can get the length of the input string.
444 uint64_t SrcLen = GetStringLength(Src);
445 if (SrcLen == 0) return 0;
446 --SrcLen; // Unbias length.
447
448 // Handle the simple, do-nothing cases:
449 // strncat(x, "", c) -> x
450 // strncat(x, c, 0) -> x
451 if (SrcLen == 0 || Len == 0) return Dst;
452
453 // These optimizations require DataLayout.
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000454 if (!DL) return 0;
Meador Inge7fb2f732012-10-13 16:45:32 +0000455
456 // We don't optimize this case
457 if (Len < SrcLen) return 0;
458
459 // strncat(x, s, c) -> strcat(x, s)
460 // s is constant so the strcat can be optimized further
461 return emitStrLenMemCpy(Src, Dst, SrcLen, B);
462 }
463};
464
Meador Inge17418502012-10-13 16:45:37 +0000465struct StrChrOpt : public LibCallOptimization {
466 virtual Value *callOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
467 // Verify the "strchr" function prototype.
468 FunctionType *FT = Callee->getFunctionType();
469 if (FT->getNumParams() != 2 ||
470 FT->getReturnType() != B.getInt8PtrTy() ||
471 FT->getParamType(0) != FT->getReturnType() ||
472 !FT->getParamType(1)->isIntegerTy(32))
473 return 0;
474
475 Value *SrcStr = CI->getArgOperand(0);
476
477 // If the second operand is non-constant, see if we can compute the length
478 // of the input string and turn this into memchr.
479 ConstantInt *CharC = dyn_cast<ConstantInt>(CI->getArgOperand(1));
480 if (CharC == 0) {
481 // These optimizations require DataLayout.
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000482 if (!DL) return 0;
Meador Inge17418502012-10-13 16:45:37 +0000483
484 uint64_t Len = GetStringLength(SrcStr);
485 if (Len == 0 || !FT->getParamType(1)->isIntegerTy(32))// memchr needs i32.
486 return 0;
487
488 return EmitMemChr(SrcStr, CI->getArgOperand(1), // include nul.
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000489 ConstantInt::get(DL->getIntPtrType(*Context), Len),
490 B, DL, TLI);
Meador Inge17418502012-10-13 16:45:37 +0000491 }
492
493 // Otherwise, the character is a constant, see if the first argument is
494 // a string literal. If so, we can constant fold.
495 StringRef Str;
Kai Nackea56bb782014-02-04 05:55:16 +0000496 if (!getConstantStringInfo(SrcStr, Str)) {
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000497 if (DL && CharC->isZero()) // strchr(p, 0) -> p + strlen(p)
498 return B.CreateGEP(SrcStr, EmitStrLen(SrcStr, B, DL, TLI), "strchr");
Meador Inge17418502012-10-13 16:45:37 +0000499 return 0;
Kai Nackea56bb782014-02-04 05:55:16 +0000500 }
Meador Inge17418502012-10-13 16:45:37 +0000501
502 // Compute the offset, make sure to handle the case when we're searching for
503 // zero (a weird way to spell strlen).
Yunzhong Gao05efa232013-08-21 22:11:15 +0000504 size_t I = (0xFF & CharC->getSExtValue()) == 0 ?
Meador Inge17418502012-10-13 16:45:37 +0000505 Str.size() : Str.find(CharC->getSExtValue());
506 if (I == StringRef::npos) // Didn't find the char. strchr returns null.
507 return Constant::getNullValue(CI->getType());
508
509 // strchr(s+n,c) -> gep(s+n+i,c)
510 return B.CreateGEP(SrcStr, B.getInt64(I), "strchr");
511 }
512};
513
514struct StrRChrOpt : public LibCallOptimization {
515 virtual Value *callOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
516 // Verify the "strrchr" function prototype.
517 FunctionType *FT = Callee->getFunctionType();
518 if (FT->getNumParams() != 2 ||
519 FT->getReturnType() != B.getInt8PtrTy() ||
520 FT->getParamType(0) != FT->getReturnType() ||
521 !FT->getParamType(1)->isIntegerTy(32))
522 return 0;
523
524 Value *SrcStr = CI->getArgOperand(0);
525 ConstantInt *CharC = dyn_cast<ConstantInt>(CI->getArgOperand(1));
526
527 // Cannot fold anything if we're not looking for a constant.
528 if (!CharC)
529 return 0;
530
531 StringRef Str;
532 if (!getConstantStringInfo(SrcStr, Str)) {
533 // strrchr(s, 0) -> strchr(s, 0)
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000534 if (DL && CharC->isZero())
535 return EmitStrChr(SrcStr, '\0', B, DL, TLI);
Meador Inge17418502012-10-13 16:45:37 +0000536 return 0;
537 }
538
539 // Compute the offset.
Yunzhong Gao05efa232013-08-21 22:11:15 +0000540 size_t I = (0xFF & CharC->getSExtValue()) == 0 ?
Meador Inge17418502012-10-13 16:45:37 +0000541 Str.size() : Str.rfind(CharC->getSExtValue());
542 if (I == StringRef::npos) // Didn't find the char. Return null.
543 return Constant::getNullValue(CI->getType());
544
545 // strrchr(s+n,c) -> gep(s+n+i,c)
546 return B.CreateGEP(SrcStr, B.getInt64(I), "strrchr");
547 }
548};
549
Meador Inge40b6fac2012-10-15 03:47:37 +0000550struct StrCmpOpt : public LibCallOptimization {
551 virtual Value *callOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
552 // Verify the "strcmp" function prototype.
553 FunctionType *FT = Callee->getFunctionType();
554 if (FT->getNumParams() != 2 ||
555 !FT->getReturnType()->isIntegerTy(32) ||
556 FT->getParamType(0) != FT->getParamType(1) ||
557 FT->getParamType(0) != B.getInt8PtrTy())
558 return 0;
559
560 Value *Str1P = CI->getArgOperand(0), *Str2P = CI->getArgOperand(1);
561 if (Str1P == Str2P) // strcmp(x,x) -> 0
562 return ConstantInt::get(CI->getType(), 0);
563
564 StringRef Str1, Str2;
565 bool HasStr1 = getConstantStringInfo(Str1P, Str1);
566 bool HasStr2 = getConstantStringInfo(Str2P, Str2);
567
568 // strcmp(x, y) -> cnst (if both x and y are constant strings)
569 if (HasStr1 && HasStr2)
570 return ConstantInt::get(CI->getType(), Str1.compare(Str2));
571
572 if (HasStr1 && Str1.empty()) // strcmp("", x) -> -*x
573 return B.CreateNeg(B.CreateZExt(B.CreateLoad(Str2P, "strcmpload"),
574 CI->getType()));
575
576 if (HasStr2 && Str2.empty()) // strcmp(x,"") -> *x
577 return B.CreateZExt(B.CreateLoad(Str1P, "strcmpload"), CI->getType());
578
579 // strcmp(P, "x") -> memcmp(P, "x", 2)
580 uint64_t Len1 = GetStringLength(Str1P);
581 uint64_t Len2 = GetStringLength(Str2P);
582 if (Len1 && Len2) {
583 // These optimizations require DataLayout.
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000584 if (!DL) return 0;
Meador Inge40b6fac2012-10-15 03:47:37 +0000585
586 return EmitMemCmp(Str1P, Str2P,
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000587 ConstantInt::get(DL->getIntPtrType(*Context),
588 std::min(Len1, Len2)), B, DL, TLI);
Meador Inge40b6fac2012-10-15 03:47:37 +0000589 }
590
591 return 0;
592 }
593};
594
595struct StrNCmpOpt : public LibCallOptimization {
596 virtual Value *callOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
597 // Verify the "strncmp" function prototype.
598 FunctionType *FT = Callee->getFunctionType();
599 if (FT->getNumParams() != 3 ||
600 !FT->getReturnType()->isIntegerTy(32) ||
601 FT->getParamType(0) != FT->getParamType(1) ||
602 FT->getParamType(0) != B.getInt8PtrTy() ||
603 !FT->getParamType(2)->isIntegerTy())
604 return 0;
605
606 Value *Str1P = CI->getArgOperand(0), *Str2P = CI->getArgOperand(1);
607 if (Str1P == Str2P) // strncmp(x,x,n) -> 0
608 return ConstantInt::get(CI->getType(), 0);
609
610 // Get the length argument if it is constant.
611 uint64_t Length;
612 if (ConstantInt *LengthArg = dyn_cast<ConstantInt>(CI->getArgOperand(2)))
613 Length = LengthArg->getZExtValue();
614 else
615 return 0;
616
617 if (Length == 0) // strncmp(x,y,0) -> 0
618 return ConstantInt::get(CI->getType(), 0);
619
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000620 if (DL && Length == 1) // strncmp(x,y,1) -> memcmp(x,y,1)
621 return EmitMemCmp(Str1P, Str2P, CI->getArgOperand(2), B, DL, TLI);
Meador Inge40b6fac2012-10-15 03:47:37 +0000622
623 StringRef Str1, Str2;
624 bool HasStr1 = getConstantStringInfo(Str1P, Str1);
625 bool HasStr2 = getConstantStringInfo(Str2P, Str2);
626
627 // strncmp(x, y) -> cnst (if both x and y are constant strings)
628 if (HasStr1 && HasStr2) {
629 StringRef SubStr1 = Str1.substr(0, Length);
630 StringRef SubStr2 = Str2.substr(0, Length);
631 return ConstantInt::get(CI->getType(), SubStr1.compare(SubStr2));
632 }
633
634 if (HasStr1 && Str1.empty()) // strncmp("", x, n) -> -*x
635 return B.CreateNeg(B.CreateZExt(B.CreateLoad(Str2P, "strcmpload"),
636 CI->getType()));
637
638 if (HasStr2 && Str2.empty()) // strncmp(x, "", n) -> *x
639 return B.CreateZExt(B.CreateLoad(Str1P, "strcmpload"), CI->getType());
640
641 return 0;
642 }
643};
644
Meador Inge000dbcc2012-10-18 18:12:40 +0000645struct StrCpyOpt : public LibCallOptimization {
646 virtual Value *callOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
647 // Verify the "strcpy" function prototype.
648 FunctionType *FT = Callee->getFunctionType();
649 if (FT->getNumParams() != 2 ||
650 FT->getReturnType() != FT->getParamType(0) ||
651 FT->getParamType(0) != FT->getParamType(1) ||
652 FT->getParamType(0) != B.getInt8PtrTy())
653 return 0;
654
655 Value *Dst = CI->getArgOperand(0), *Src = CI->getArgOperand(1);
656 if (Dst == Src) // strcpy(x,x) -> x
657 return Src;
658
659 // These optimizations require DataLayout.
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000660 if (!DL) return 0;
Meador Inge000dbcc2012-10-18 18:12:40 +0000661
662 // See if we can get the length of the input string.
663 uint64_t Len = GetStringLength(Src);
664 if (Len == 0) return 0;
665
666 // We have enough information to now generate the memcpy call to do the
667 // copy for us. Make a memcpy to copy the nul byte with align = 1.
668 B.CreateMemCpy(Dst, Src,
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000669 ConstantInt::get(DL->getIntPtrType(*Context), Len), 1);
Meador Inge000dbcc2012-10-18 18:12:40 +0000670 return Dst;
671 }
672};
673
Meador Inge9a6a1902012-10-31 00:20:56 +0000674struct StpCpyOpt: public LibCallOptimization {
675 virtual Value *callOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
676 // Verify the "stpcpy" function prototype.
677 FunctionType *FT = Callee->getFunctionType();
678 if (FT->getNumParams() != 2 ||
679 FT->getReturnType() != FT->getParamType(0) ||
680 FT->getParamType(0) != FT->getParamType(1) ||
681 FT->getParamType(0) != B.getInt8PtrTy())
682 return 0;
683
684 // These optimizations require DataLayout.
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000685 if (!DL) return 0;
Meador Inge9a6a1902012-10-31 00:20:56 +0000686
687 Value *Dst = CI->getArgOperand(0), *Src = CI->getArgOperand(1);
688 if (Dst == Src) { // stpcpy(x,x) -> x+strlen(x)
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000689 Value *StrLen = EmitStrLen(Src, B, DL, TLI);
Meador Inge9a6a1902012-10-31 00:20:56 +0000690 return StrLen ? B.CreateInBoundsGEP(Dst, StrLen) : 0;
691 }
692
693 // See if we can get the length of the input string.
694 uint64_t Len = GetStringLength(Src);
695 if (Len == 0) return 0;
696
697 Type *PT = FT->getParamType(0);
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000698 Value *LenV = ConstantInt::get(DL->getIntPtrType(PT), Len);
Meador Inge9a6a1902012-10-31 00:20:56 +0000699 Value *DstEnd = B.CreateGEP(Dst,
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000700 ConstantInt::get(DL->getIntPtrType(PT),
Meador Inge9a6a1902012-10-31 00:20:56 +0000701 Len - 1));
702
703 // We have enough information to now generate the memcpy call to do the
704 // copy for us. Make a memcpy to copy the nul byte with align = 1.
705 B.CreateMemCpy(Dst, Src, LenV, 1);
706 return DstEnd;
707 }
708};
709
Meador Inge067294b2012-10-31 03:33:00 +0000710struct StrNCpyOpt : public LibCallOptimization {
711 virtual Value *callOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
712 FunctionType *FT = Callee->getFunctionType();
713 if (FT->getNumParams() != 3 || FT->getReturnType() != FT->getParamType(0) ||
714 FT->getParamType(0) != FT->getParamType(1) ||
715 FT->getParamType(0) != B.getInt8PtrTy() ||
716 !FT->getParamType(2)->isIntegerTy())
717 return 0;
718
719 Value *Dst = CI->getArgOperand(0);
720 Value *Src = CI->getArgOperand(1);
721 Value *LenOp = CI->getArgOperand(2);
722
723 // See if we can get the length of the input string.
724 uint64_t SrcLen = GetStringLength(Src);
725 if (SrcLen == 0) return 0;
726 --SrcLen;
727
728 if (SrcLen == 0) {
729 // strncpy(x, "", y) -> memset(x, '\0', y, 1)
730 B.CreateMemSet(Dst, B.getInt8('\0'), LenOp, 1);
731 return Dst;
732 }
733
734 uint64_t Len;
735 if (ConstantInt *LengthArg = dyn_cast<ConstantInt>(LenOp))
736 Len = LengthArg->getZExtValue();
737 else
738 return 0;
739
740 if (Len == 0) return Dst; // strncpy(x, y, 0) -> x
741
742 // These optimizations require DataLayout.
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000743 if (!DL) return 0;
Meador Inge067294b2012-10-31 03:33:00 +0000744
745 // Let strncpy handle the zero padding
746 if (Len > SrcLen+1) return 0;
747
748 Type *PT = FT->getParamType(0);
749 // strncpy(x, s, c) -> memcpy(x, s, c, 1) [s and c are constant]
750 B.CreateMemCpy(Dst, Src,
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000751 ConstantInt::get(DL->getIntPtrType(PT), Len), 1);
Meador Inge067294b2012-10-31 03:33:00 +0000752
753 return Dst;
754 }
755};
756
Meador Inged589ac62012-10-31 03:33:06 +0000757struct StrLenOpt : public LibCallOptimization {
Chad Rosier22d275f2013-02-08 18:00:14 +0000758 virtual bool ignoreCallingConv() { return true; }
Meador Inged589ac62012-10-31 03:33:06 +0000759 virtual Value *callOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
760 FunctionType *FT = Callee->getFunctionType();
761 if (FT->getNumParams() != 1 ||
762 FT->getParamType(0) != B.getInt8PtrTy() ||
763 !FT->getReturnType()->isIntegerTy())
764 return 0;
765
766 Value *Src = CI->getArgOperand(0);
767
768 // Constant folding: strlen("xyz") -> 3
769 if (uint64_t Len = GetStringLength(Src))
770 return ConstantInt::get(CI->getType(), Len-1);
771
772 // strlen(x) != 0 --> *x != 0
773 // strlen(x) == 0 --> *x == 0
774 if (isOnlyUsedInZeroEqualityComparison(CI))
775 return B.CreateZExt(B.CreateLoad(Src, "strlenfirst"), CI->getType());
776 return 0;
777 }
778};
779
Meador Inge6f8e0112012-10-31 04:29:58 +0000780struct StrPBrkOpt : public LibCallOptimization {
781 virtual Value *callOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
782 FunctionType *FT = Callee->getFunctionType();
783 if (FT->getNumParams() != 2 ||
784 FT->getParamType(0) != B.getInt8PtrTy() ||
785 FT->getParamType(1) != FT->getParamType(0) ||
786 FT->getReturnType() != FT->getParamType(0))
787 return 0;
788
789 StringRef S1, S2;
790 bool HasS1 = getConstantStringInfo(CI->getArgOperand(0), S1);
791 bool HasS2 = getConstantStringInfo(CI->getArgOperand(1), S2);
792
793 // strpbrk(s, "") -> NULL
794 // strpbrk("", s) -> NULL
795 if ((HasS1 && S1.empty()) || (HasS2 && S2.empty()))
796 return Constant::getNullValue(CI->getType());
797
798 // Constant folding.
799 if (HasS1 && HasS2) {
800 size_t I = S1.find_first_of(S2);
Matt Arsenaultf631f8c2013-09-10 00:41:53 +0000801 if (I == StringRef::npos) // No match.
Meador Inge6f8e0112012-10-31 04:29:58 +0000802 return Constant::getNullValue(CI->getType());
803
804 return B.CreateGEP(CI->getArgOperand(0), B.getInt64(I), "strpbrk");
805 }
806
807 // strpbrk(s, "a") -> strchr(s, 'a')
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000808 if (DL && HasS2 && S2.size() == 1)
809 return EmitStrChr(CI->getArgOperand(0), S2[0], B, DL, TLI);
Meador Inge6f8e0112012-10-31 04:29:58 +0000810
811 return 0;
812 }
813};
814
Meador Inge05a625a2012-10-31 14:58:26 +0000815struct StrToOpt : public LibCallOptimization {
816 virtual Value *callOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
817 FunctionType *FT = Callee->getFunctionType();
818 if ((FT->getNumParams() != 2 && FT->getNumParams() != 3) ||
819 !FT->getParamType(0)->isPointerTy() ||
820 !FT->getParamType(1)->isPointerTy())
821 return 0;
822
823 Value *EndPtr = CI->getArgOperand(1);
824 if (isa<ConstantPointerNull>(EndPtr)) {
825 // With a null EndPtr, this function won't capture the main argument.
826 // It would be readonly too, except that it still may write to errno.
Peter Collingbourne1b97a9c2013-03-02 01:20:18 +0000827 CI->addAttribute(1, Attribute::NoCapture);
Meador Inge05a625a2012-10-31 14:58:26 +0000828 }
829
830 return 0;
831 }
832};
833
Meador Inge489b5d62012-11-08 01:33:50 +0000834struct StrSpnOpt : public LibCallOptimization {
835 virtual Value *callOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
836 FunctionType *FT = Callee->getFunctionType();
837 if (FT->getNumParams() != 2 ||
838 FT->getParamType(0) != B.getInt8PtrTy() ||
839 FT->getParamType(1) != FT->getParamType(0) ||
840 !FT->getReturnType()->isIntegerTy())
841 return 0;
842
843 StringRef S1, S2;
844 bool HasS1 = getConstantStringInfo(CI->getArgOperand(0), S1);
845 bool HasS2 = getConstantStringInfo(CI->getArgOperand(1), S2);
846
847 // strspn(s, "") -> 0
848 // strspn("", s) -> 0
849 if ((HasS1 && S1.empty()) || (HasS2 && S2.empty()))
850 return Constant::getNullValue(CI->getType());
851
852 // Constant folding.
853 if (HasS1 && HasS2) {
854 size_t Pos = S1.find_first_not_of(S2);
855 if (Pos == StringRef::npos) Pos = S1.size();
856 return ConstantInt::get(CI->getType(), Pos);
857 }
858
859 return 0;
860 }
861};
862
Meador Ingebcd88ef72012-11-10 15:16:48 +0000863struct StrCSpnOpt : public LibCallOptimization {
864 virtual Value *callOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
865 FunctionType *FT = Callee->getFunctionType();
866 if (FT->getNumParams() != 2 ||
867 FT->getParamType(0) != B.getInt8PtrTy() ||
868 FT->getParamType(1) != FT->getParamType(0) ||
869 !FT->getReturnType()->isIntegerTy())
870 return 0;
871
872 StringRef S1, S2;
873 bool HasS1 = getConstantStringInfo(CI->getArgOperand(0), S1);
874 bool HasS2 = getConstantStringInfo(CI->getArgOperand(1), S2);
875
876 // strcspn("", s) -> 0
877 if (HasS1 && S1.empty())
878 return Constant::getNullValue(CI->getType());
879
880 // Constant folding.
881 if (HasS1 && HasS2) {
882 size_t Pos = S1.find_first_of(S2);
883 if (Pos == StringRef::npos) Pos = S1.size();
884 return ConstantInt::get(CI->getType(), Pos);
885 }
886
887 // strcspn(s, "") -> strlen(s)
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000888 if (DL && HasS2 && S2.empty())
889 return EmitStrLen(CI->getArgOperand(0), B, DL, TLI);
Meador Ingebcd88ef72012-11-10 15:16:48 +0000890
891 return 0;
892 }
893};
894
Meador Inge56edbc92012-11-11 03:51:48 +0000895struct StrStrOpt : public LibCallOptimization {
896 virtual Value *callOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
897 FunctionType *FT = Callee->getFunctionType();
898 if (FT->getNumParams() != 2 ||
899 !FT->getParamType(0)->isPointerTy() ||
900 !FT->getParamType(1)->isPointerTy() ||
901 !FT->getReturnType()->isPointerTy())
902 return 0;
903
904 // fold strstr(x, x) -> x.
905 if (CI->getArgOperand(0) == CI->getArgOperand(1))
906 return B.CreateBitCast(CI->getArgOperand(0), CI->getType());
907
908 // fold strstr(a, b) == a -> strncmp(a, b, strlen(b)) == 0
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000909 if (DL && isOnlyUsedInEqualityComparison(CI, CI->getArgOperand(0))) {
910 Value *StrLen = EmitStrLen(CI->getArgOperand(1), B, DL, TLI);
Meador Inge56edbc92012-11-11 03:51:48 +0000911 if (!StrLen)
912 return 0;
913 Value *StrNCmp = EmitStrNCmp(CI->getArgOperand(0), CI->getArgOperand(1),
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000914 StrLen, B, DL, TLI);
Meador Inge56edbc92012-11-11 03:51:48 +0000915 if (!StrNCmp)
916 return 0;
917 for (Value::use_iterator UI = CI->use_begin(), UE = CI->use_end();
918 UI != UE; ) {
919 ICmpInst *Old = cast<ICmpInst>(*UI++);
920 Value *Cmp = B.CreateICmp(Old->getPredicate(), StrNCmp,
921 ConstantInt::getNullValue(StrNCmp->getType()),
922 "cmp");
923 LCS->replaceAllUsesWith(Old, Cmp);
924 }
925 return CI;
926 }
927
928 // See if either input string is a constant string.
929 StringRef SearchStr, ToFindStr;
930 bool HasStr1 = getConstantStringInfo(CI->getArgOperand(0), SearchStr);
931 bool HasStr2 = getConstantStringInfo(CI->getArgOperand(1), ToFindStr);
932
933 // fold strstr(x, "") -> x.
934 if (HasStr2 && ToFindStr.empty())
935 return B.CreateBitCast(CI->getArgOperand(0), CI->getType());
936
937 // If both strings are known, constant fold it.
938 if (HasStr1 && HasStr2) {
Matt Arsenaultf631f8c2013-09-10 00:41:53 +0000939 size_t Offset = SearchStr.find(ToFindStr);
Meador Inge56edbc92012-11-11 03:51:48 +0000940
941 if (Offset == StringRef::npos) // strstr("foo", "bar") -> null
942 return Constant::getNullValue(CI->getType());
943
944 // strstr("abcd", "bc") -> gep((char*)"abcd", 1)
945 Value *Result = CastToCStr(CI->getArgOperand(0), B);
946 Result = B.CreateConstInBoundsGEP1_64(Result, Offset, "strstr");
947 return B.CreateBitCast(Result, CI->getType());
948 }
949
950 // fold strstr(x, "y") -> strchr(x, 'y').
951 if (HasStr2 && ToFindStr.size() == 1) {
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000952 Value *StrChr= EmitStrChr(CI->getArgOperand(0), ToFindStr[0], B, DL, TLI);
Meador Inge56edbc92012-11-11 03:51:48 +0000953 return StrChr ? B.CreateBitCast(StrChr, CI->getType()) : 0;
954 }
955 return 0;
956 }
957};
958
Meador Inge4d2827c2012-11-11 05:11:20 +0000959struct MemCmpOpt : public LibCallOptimization {
960 virtual Value *callOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
961 FunctionType *FT = Callee->getFunctionType();
962 if (FT->getNumParams() != 3 || !FT->getParamType(0)->isPointerTy() ||
963 !FT->getParamType(1)->isPointerTy() ||
964 !FT->getReturnType()->isIntegerTy(32))
965 return 0;
966
967 Value *LHS = CI->getArgOperand(0), *RHS = CI->getArgOperand(1);
968
969 if (LHS == RHS) // memcmp(s,s,x) -> 0
970 return Constant::getNullValue(CI->getType());
971
972 // Make sure we have a constant length.
973 ConstantInt *LenC = dyn_cast<ConstantInt>(CI->getArgOperand(2));
974 if (!LenC) return 0;
975 uint64_t Len = LenC->getZExtValue();
976
977 if (Len == 0) // memcmp(s1,s2,0) -> 0
978 return Constant::getNullValue(CI->getType());
979
980 // memcmp(S1,S2,1) -> *(unsigned char*)LHS - *(unsigned char*)RHS
981 if (Len == 1) {
982 Value *LHSV = B.CreateZExt(B.CreateLoad(CastToCStr(LHS, B), "lhsc"),
983 CI->getType(), "lhsv");
984 Value *RHSV = B.CreateZExt(B.CreateLoad(CastToCStr(RHS, B), "rhsc"),
985 CI->getType(), "rhsv");
986 return B.CreateSub(LHSV, RHSV, "chardiff");
987 }
988
989 // Constant folding: memcmp(x, y, l) -> cnst (all arguments are constant)
990 StringRef LHSStr, RHSStr;
991 if (getConstantStringInfo(LHS, LHSStr) &&
992 getConstantStringInfo(RHS, RHSStr)) {
993 // Make sure we're not reading out-of-bounds memory.
994 if (Len > LHSStr.size() || Len > RHSStr.size())
995 return 0;
Meador Ingeb3e91f62012-11-12 14:00:45 +0000996 // Fold the memcmp and normalize the result. This way we get consistent
997 // results across multiple platforms.
998 uint64_t Ret = 0;
999 int Cmp = memcmp(LHSStr.data(), RHSStr.data(), Len);
1000 if (Cmp < 0)
1001 Ret = -1;
1002 else if (Cmp > 0)
1003 Ret = 1;
Meador Inge4d2827c2012-11-11 05:11:20 +00001004 return ConstantInt::get(CI->getType(), Ret);
1005 }
1006
1007 return 0;
1008 }
1009};
1010
Meador Ingedd9234a2012-11-11 05:54:34 +00001011struct MemCpyOpt : public LibCallOptimization {
1012 virtual Value *callOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
1013 // These optimizations require DataLayout.
Rafael Espindola37dc9e12014-02-21 00:06:31 +00001014 if (!DL) return 0;
Meador Ingedd9234a2012-11-11 05:54:34 +00001015
1016 FunctionType *FT = Callee->getFunctionType();
1017 if (FT->getNumParams() != 3 || FT->getReturnType() != FT->getParamType(0) ||
1018 !FT->getParamType(0)->isPointerTy() ||
1019 !FT->getParamType(1)->isPointerTy() ||
Rafael Espindola37dc9e12014-02-21 00:06:31 +00001020 FT->getParamType(2) != DL->getIntPtrType(*Context))
Meador Ingedd9234a2012-11-11 05:54:34 +00001021 return 0;
1022
1023 // memcpy(x, y, n) -> llvm.memcpy(x, y, n, 1)
1024 B.CreateMemCpy(CI->getArgOperand(0), CI->getArgOperand(1),
1025 CI->getArgOperand(2), 1);
1026 return CI->getArgOperand(0);
1027 }
1028};
1029
Meador Inge9cf328b2012-11-11 06:22:40 +00001030struct MemMoveOpt : public LibCallOptimization {
1031 virtual Value *callOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
1032 // These optimizations require DataLayout.
Rafael Espindola37dc9e12014-02-21 00:06:31 +00001033 if (!DL) return 0;
Meador Inge9cf328b2012-11-11 06:22:40 +00001034
1035 FunctionType *FT = Callee->getFunctionType();
1036 if (FT->getNumParams() != 3 || FT->getReturnType() != FT->getParamType(0) ||
1037 !FT->getParamType(0)->isPointerTy() ||
1038 !FT->getParamType(1)->isPointerTy() ||
Rafael Espindola37dc9e12014-02-21 00:06:31 +00001039 FT->getParamType(2) != DL->getIntPtrType(*Context))
Meador Inge9cf328b2012-11-11 06:22:40 +00001040 return 0;
1041
1042 // memmove(x, y, n) -> llvm.memmove(x, y, n, 1)
1043 B.CreateMemMove(CI->getArgOperand(0), CI->getArgOperand(1),
1044 CI->getArgOperand(2), 1);
1045 return CI->getArgOperand(0);
1046 }
1047};
1048
Meador Inged4825782012-11-11 06:49:03 +00001049struct MemSetOpt : public LibCallOptimization {
1050 virtual Value *callOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
1051 // These optimizations require DataLayout.
Rafael Espindola37dc9e12014-02-21 00:06:31 +00001052 if (!DL) return 0;
Meador Inged4825782012-11-11 06:49:03 +00001053
1054 FunctionType *FT = Callee->getFunctionType();
1055 if (FT->getNumParams() != 3 || FT->getReturnType() != FT->getParamType(0) ||
1056 !FT->getParamType(0)->isPointerTy() ||
1057 !FT->getParamType(1)->isIntegerTy() ||
Rafael Espindola37dc9e12014-02-21 00:06:31 +00001058 FT->getParamType(2) != DL->getIntPtrType(FT->getParamType(0)))
Meador Inged4825782012-11-11 06:49:03 +00001059 return 0;
1060
1061 // memset(p, v, n) -> llvm.memset(p, v, n, 1)
1062 Value *Val = B.CreateIntCast(CI->getArgOperand(1), B.getInt8Ty(), false);
1063 B.CreateMemSet(CI->getArgOperand(0), Val, CI->getArgOperand(2), 1);
1064 return CI->getArgOperand(0);
1065 }
1066};
1067
Meador Inge193e0352012-11-13 04:16:17 +00001068//===----------------------------------------------------------------------===//
1069// Math Library Optimizations
1070//===----------------------------------------------------------------------===//
1071
1072//===----------------------------------------------------------------------===//
1073// Double -> Float Shrinking Optimizations for Unary Functions like 'floor'
1074
1075struct UnaryDoubleFPOpt : public LibCallOptimization {
1076 bool CheckRetType;
1077 UnaryDoubleFPOpt(bool CheckReturnType): CheckRetType(CheckReturnType) {}
1078 virtual Value *callOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
1079 FunctionType *FT = Callee->getFunctionType();
1080 if (FT->getNumParams() != 1 || !FT->getReturnType()->isDoubleTy() ||
1081 !FT->getParamType(0)->isDoubleTy())
1082 return 0;
1083
1084 if (CheckRetType) {
1085 // Check if all the uses for function like 'sin' are converted to float.
1086 for (Value::use_iterator UseI = CI->use_begin(); UseI != CI->use_end();
1087 ++UseI) {
1088 FPTruncInst *Cast = dyn_cast<FPTruncInst>(*UseI);
1089 if (Cast == 0 || !Cast->getType()->isFloatTy())
1090 return 0;
1091 }
1092 }
1093
1094 // If this is something like 'floor((double)floatval)', convert to floorf.
1095 FPExtInst *Cast = dyn_cast<FPExtInst>(CI->getArgOperand(0));
1096 if (Cast == 0 || !Cast->getOperand(0)->getType()->isFloatTy())
1097 return 0;
1098
1099 // floor((double)floatval) -> (double)floorf(floatval)
1100 Value *V = Cast->getOperand(0);
1101 V = EmitUnaryFloatFnCall(V, Callee->getName(), B, Callee->getAttributes());
1102 return B.CreateFPExt(V, B.getDoubleTy());
1103 }
1104};
1105
Yi Jiang6ab044e2013-12-16 22:42:40 +00001106// Double -> Float Shrinking Optimizations for Binary Functions like 'fmin/fmax'
1107struct BinaryDoubleFPOpt : public LibCallOptimization {
1108 bool CheckRetType;
1109 BinaryDoubleFPOpt(bool CheckReturnType): CheckRetType(CheckReturnType) {}
1110 virtual Value *callOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
1111 FunctionType *FT = Callee->getFunctionType();
1112 // Just make sure this has 2 arguments of the same FP type, which match the
1113 // result type.
1114 if (FT->getNumParams() != 2 || FT->getReturnType() != FT->getParamType(0) ||
1115 FT->getParamType(0) != FT->getParamType(1) ||
1116 !FT->getParamType(0)->isFloatingPointTy())
1117 return 0;
1118
1119 if (CheckRetType) {
1120 // Check if all the uses for function like 'fmin/fmax' are converted to
1121 // float.
1122 for (Value::use_iterator UseI = CI->use_begin(); UseI != CI->use_end();
1123 ++UseI) {
1124 FPTruncInst *Cast = dyn_cast<FPTruncInst>(*UseI);
1125 if (Cast == 0 || !Cast->getType()->isFloatTy())
1126 return 0;
1127 }
1128 }
1129
1130 // If this is something like 'fmin((double)floatval1, (double)floatval2)',
1131 // we convert it to fminf.
1132 FPExtInst *Cast1 = dyn_cast<FPExtInst>(CI->getArgOperand(0));
1133 FPExtInst *Cast2 = dyn_cast<FPExtInst>(CI->getArgOperand(1));
1134 if (Cast1 == 0 || !Cast1->getOperand(0)->getType()->isFloatTy() ||
1135 Cast2 == 0 || !Cast2->getOperand(0)->getType()->isFloatTy())
1136 return 0;
1137
1138 // fmin((double)floatval1, (double)floatval2)
1139 // -> (double)fmin(floatval1, floatval2)
1140 Value *V = NULL;
1141 Value *V1 = Cast1->getOperand(0);
1142 Value *V2 = Cast2->getOperand(0);
1143 V = EmitBinaryFloatFnCall(V1, V2, Callee->getName(), B,
1144 Callee->getAttributes());
1145 return B.CreateFPExt(V, B.getDoubleTy());
1146 }
1147};
1148
Meador Inge193e0352012-11-13 04:16:17 +00001149struct UnsafeFPLibCallOptimization : public LibCallOptimization {
1150 bool UnsafeFPShrink;
1151 UnsafeFPLibCallOptimization(bool UnsafeFPShrink) {
1152 this->UnsafeFPShrink = UnsafeFPShrink;
1153 }
1154};
1155
1156struct CosOpt : public UnsafeFPLibCallOptimization {
1157 CosOpt(bool UnsafeFPShrink) : UnsafeFPLibCallOptimization(UnsafeFPShrink) {}
1158 virtual Value *callOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
1159 Value *Ret = NULL;
1160 if (UnsafeFPShrink && Callee->getName() == "cos" &&
1161 TLI->has(LibFunc::cosf)) {
1162 UnaryDoubleFPOpt UnsafeUnaryDoubleFP(true);
1163 Ret = UnsafeUnaryDoubleFP.callOptimizer(Callee, CI, B);
1164 }
1165
1166 FunctionType *FT = Callee->getFunctionType();
1167 // Just make sure this has 1 argument of FP type, which matches the
1168 // result type.
1169 if (FT->getNumParams() != 1 || FT->getReturnType() != FT->getParamType(0) ||
1170 !FT->getParamType(0)->isFloatingPointTy())
1171 return Ret;
1172
1173 // cos(-x) -> cos(x)
1174 Value *Op1 = CI->getArgOperand(0);
1175 if (BinaryOperator::isFNeg(Op1)) {
1176 BinaryOperator *BinExpr = cast<BinaryOperator>(Op1);
1177 return B.CreateCall(Callee, BinExpr->getOperand(1), "cos");
1178 }
1179 return Ret;
1180 }
1181};
1182
1183struct PowOpt : public UnsafeFPLibCallOptimization {
1184 PowOpt(bool UnsafeFPShrink) : UnsafeFPLibCallOptimization(UnsafeFPShrink) {}
1185 virtual Value *callOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
1186 Value *Ret = NULL;
1187 if (UnsafeFPShrink && Callee->getName() == "pow" &&
1188 TLI->has(LibFunc::powf)) {
1189 UnaryDoubleFPOpt UnsafeUnaryDoubleFP(true);
1190 Ret = UnsafeUnaryDoubleFP.callOptimizer(Callee, CI, B);
1191 }
1192
1193 FunctionType *FT = Callee->getFunctionType();
1194 // Just make sure this has 2 arguments of the same FP type, which match the
1195 // result type.
1196 if (FT->getNumParams() != 2 || FT->getReturnType() != FT->getParamType(0) ||
1197 FT->getParamType(0) != FT->getParamType(1) ||
1198 !FT->getParamType(0)->isFloatingPointTy())
1199 return Ret;
1200
1201 Value *Op1 = CI->getArgOperand(0), *Op2 = CI->getArgOperand(1);
1202 if (ConstantFP *Op1C = dyn_cast<ConstantFP>(Op1)) {
Michael Kuperstein4bb3f8f2013-08-19 06:55:47 +00001203 // pow(1.0, x) -> 1.0
1204 if (Op1C->isExactlyValue(1.0))
Meador Inge193e0352012-11-13 04:16:17 +00001205 return Op1C;
Michael Kuperstein4bb3f8f2013-08-19 06:55:47 +00001206 // pow(2.0, x) -> exp2(x)
Benjamin Kramer2702caa2013-08-31 18:19:35 +00001207 if (Op1C->isExactlyValue(2.0) &&
1208 hasUnaryFloatFn(TLI, Op1->getType(), LibFunc::exp2, LibFunc::exp2f,
1209 LibFunc::exp2l))
Meador Inge193e0352012-11-13 04:16:17 +00001210 return EmitUnaryFloatFnCall(Op2, "exp2", B, Callee->getAttributes());
Yi Jiangf92a5742013-12-12 01:55:04 +00001211 // pow(10.0, x) -> exp10(x)
1212 if (Op1C->isExactlyValue(10.0) &&
1213 hasUnaryFloatFn(TLI, Op1->getType(), LibFunc::exp10, LibFunc::exp10f,
1214 LibFunc::exp10l))
1215 return EmitUnaryFloatFnCall(Op2, TLI->getName(LibFunc::exp10), B,
1216 Callee->getAttributes());
Meador Inge193e0352012-11-13 04:16:17 +00001217 }
1218
1219 ConstantFP *Op2C = dyn_cast<ConstantFP>(Op2);
1220 if (Op2C == 0) return Ret;
1221
1222 if (Op2C->getValueAPF().isZero()) // pow(x, 0.0) -> 1.0
1223 return ConstantFP::get(CI->getType(), 1.0);
1224
Michael Kuperstein4bb3f8f2013-08-19 06:55:47 +00001225 if (Op2C->isExactlyValue(0.5) &&
Benjamin Kramer2702caa2013-08-31 18:19:35 +00001226 hasUnaryFloatFn(TLI, Op2->getType(), LibFunc::sqrt, LibFunc::sqrtf,
1227 LibFunc::sqrtl) &&
1228 hasUnaryFloatFn(TLI, Op2->getType(), LibFunc::fabs, LibFunc::fabsf,
1229 LibFunc::fabsl)) {
Meador Inge193e0352012-11-13 04:16:17 +00001230 // Expand pow(x, 0.5) to (x == -infinity ? +infinity : fabs(sqrt(x))).
1231 // This is faster than calling pow, and still handles negative zero
1232 // and negative infinity correctly.
1233 // TODO: In fast-math mode, this could be just sqrt(x).
1234 // TODO: In finite-only mode, this could be just fabs(sqrt(x)).
1235 Value *Inf = ConstantFP::getInfinity(CI->getType());
1236 Value *NegInf = ConstantFP::getInfinity(CI->getType(), true);
1237 Value *Sqrt = EmitUnaryFloatFnCall(Op1, "sqrt", B,
1238 Callee->getAttributes());
1239 Value *FAbs = EmitUnaryFloatFnCall(Sqrt, "fabs", B,
1240 Callee->getAttributes());
1241 Value *FCmp = B.CreateFCmpOEQ(Op1, NegInf);
1242 Value *Sel = B.CreateSelect(FCmp, Inf, FAbs);
1243 return Sel;
1244 }
1245
1246 if (Op2C->isExactlyValue(1.0)) // pow(x, 1.0) -> x
1247 return Op1;
1248 if (Op2C->isExactlyValue(2.0)) // pow(x, 2.0) -> x*x
1249 return B.CreateFMul(Op1, Op1, "pow2");
1250 if (Op2C->isExactlyValue(-1.0)) // pow(x, -1.0) -> 1.0/x
1251 return B.CreateFDiv(ConstantFP::get(CI->getType(), 1.0),
1252 Op1, "powrecip");
1253 return 0;
1254 }
1255};
1256
1257struct Exp2Opt : public UnsafeFPLibCallOptimization {
1258 Exp2Opt(bool UnsafeFPShrink) : UnsafeFPLibCallOptimization(UnsafeFPShrink) {}
1259 virtual Value *callOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
1260 Value *Ret = NULL;
1261 if (UnsafeFPShrink && Callee->getName() == "exp2" &&
Benjamin Kramer2702caa2013-08-31 18:19:35 +00001262 TLI->has(LibFunc::exp2f)) {
Meador Inge193e0352012-11-13 04:16:17 +00001263 UnaryDoubleFPOpt UnsafeUnaryDoubleFP(true);
1264 Ret = UnsafeUnaryDoubleFP.callOptimizer(Callee, CI, B);
1265 }
1266
1267 FunctionType *FT = Callee->getFunctionType();
1268 // Just make sure this has 1 argument of FP type, which matches the
1269 // result type.
1270 if (FT->getNumParams() != 1 || FT->getReturnType() != FT->getParamType(0) ||
1271 !FT->getParamType(0)->isFloatingPointTy())
1272 return Ret;
1273
1274 Value *Op = CI->getArgOperand(0);
1275 // Turn exp2(sitofp(x)) -> ldexp(1.0, sext(x)) if sizeof(x) <= 32
1276 // Turn exp2(uitofp(x)) -> ldexp(1.0, zext(x)) if sizeof(x) < 32
Benjamin Kramer34f460e2014-02-04 20:27:23 +00001277 LibFunc::Func LdExp = LibFunc::ldexpl;
1278 if (Op->getType()->isFloatTy())
1279 LdExp = LibFunc::ldexpf;
1280 else if (Op->getType()->isDoubleTy())
1281 LdExp = LibFunc::ldexp;
Meador Inge193e0352012-11-13 04:16:17 +00001282
Benjamin Kramer34f460e2014-02-04 20:27:23 +00001283 if (TLI->has(LdExp)) {
1284 Value *LdExpArg = 0;
1285 if (SIToFPInst *OpC = dyn_cast<SIToFPInst>(Op)) {
1286 if (OpC->getOperand(0)->getType()->getPrimitiveSizeInBits() <= 32)
1287 LdExpArg = B.CreateSExt(OpC->getOperand(0), B.getInt32Ty());
1288 } else if (UIToFPInst *OpC = dyn_cast<UIToFPInst>(Op)) {
1289 if (OpC->getOperand(0)->getType()->getPrimitiveSizeInBits() < 32)
1290 LdExpArg = B.CreateZExt(OpC->getOperand(0), B.getInt32Ty());
1291 }
Meador Inge193e0352012-11-13 04:16:17 +00001292
Benjamin Kramer34f460e2014-02-04 20:27:23 +00001293 if (LdExpArg) {
1294 Constant *One = ConstantFP::get(*Context, APFloat(1.0f));
1295 if (!Op->getType()->isFloatTy())
1296 One = ConstantExpr::getFPExtend(One, Op->getType());
Meador Inge193e0352012-11-13 04:16:17 +00001297
Benjamin Kramer34f460e2014-02-04 20:27:23 +00001298 Module *M = Caller->getParent();
1299 Value *Callee =
1300 M->getOrInsertFunction(TLI->getName(LdExp), Op->getType(),
1301 Op->getType(), B.getInt32Ty(), NULL);
1302 CallInst *CI = B.CreateCall2(Callee, One, LdExpArg);
1303 if (const Function *F = dyn_cast<Function>(Callee->stripPointerCasts()))
1304 CI->setCallingConv(F->getCallingConv());
Meador Inge193e0352012-11-13 04:16:17 +00001305
Benjamin Kramer34f460e2014-02-04 20:27:23 +00001306 return CI;
1307 }
Meador Inge193e0352012-11-13 04:16:17 +00001308 }
1309 return Ret;
1310 }
1311};
1312
Bob Wilsond8d92d92013-11-03 06:48:38 +00001313struct SinCosPiOpt : public LibCallOptimization {
1314 SinCosPiOpt() {}
1315
1316 virtual Value *callOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
1317 // Make sure the prototype is as expected, otherwise the rest of the
1318 // function is probably invalid and likely to abort.
1319 if (!isTrigLibCall(CI))
1320 return 0;
1321
1322 Value *Arg = CI->getArgOperand(0);
1323 SmallVector<CallInst *, 1> SinCalls;
1324 SmallVector<CallInst *, 1> CosCalls;
1325 SmallVector<CallInst *, 1> SinCosCalls;
1326
1327 bool IsFloat = Arg->getType()->isFloatTy();
1328
1329 // Look for all compatible sinpi, cospi and sincospi calls with the same
1330 // argument. If there are enough (in some sense) we can make the
1331 // substitution.
1332 for (Value::use_iterator UI = Arg->use_begin(), UE = Arg->use_end();
1333 UI != UE; ++UI)
1334 classifyArgUse(*UI, CI->getParent(), IsFloat, SinCalls, CosCalls,
1335 SinCosCalls);
1336
1337 // It's only worthwhile if both sinpi and cospi are actually used.
1338 if (SinCosCalls.empty() && (SinCalls.empty() || CosCalls.empty()))
1339 return 0;
1340
1341 Value *Sin, *Cos, *SinCos;
1342 insertSinCosCall(B, CI->getCalledFunction(), Arg, IsFloat, Sin, Cos,
1343 SinCos);
1344
1345 replaceTrigInsts(SinCalls, Sin);
1346 replaceTrigInsts(CosCalls, Cos);
1347 replaceTrigInsts(SinCosCalls, SinCos);
1348
1349 return 0;
1350 }
1351
1352 bool isTrigLibCall(CallInst *CI) {
1353 Function *Callee = CI->getCalledFunction();
1354 FunctionType *FT = Callee->getFunctionType();
1355
1356 // We can only hope to do anything useful if we can ignore things like errno
1357 // and floating-point exceptions.
1358 bool AttributesSafe = CI->hasFnAttr(Attribute::NoUnwind) &&
1359 CI->hasFnAttr(Attribute::ReadNone);
1360
1361 // Other than that we need float(float) or double(double)
1362 return AttributesSafe && FT->getNumParams() == 1 &&
1363 FT->getReturnType() == FT->getParamType(0) &&
1364 (FT->getParamType(0)->isFloatTy() ||
1365 FT->getParamType(0)->isDoubleTy());
1366 }
1367
1368 void classifyArgUse(Value *Val, BasicBlock *BB, bool IsFloat,
1369 SmallVectorImpl<CallInst *> &SinCalls,
1370 SmallVectorImpl<CallInst *> &CosCalls,
1371 SmallVectorImpl<CallInst *> &SinCosCalls) {
1372 CallInst *CI = dyn_cast<CallInst>(Val);
1373
1374 if (!CI)
1375 return;
1376
1377 Function *Callee = CI->getCalledFunction();
1378 StringRef FuncName = Callee->getName();
1379 LibFunc::Func Func;
1380 if (!TLI->getLibFunc(FuncName, Func) || !TLI->has(Func) ||
1381 !isTrigLibCall(CI))
1382 return;
1383
1384 if (IsFloat) {
1385 if (Func == LibFunc::sinpif)
1386 SinCalls.push_back(CI);
1387 else if (Func == LibFunc::cospif)
1388 CosCalls.push_back(CI);
Tim Northover103e6482014-02-04 16:28:20 +00001389 else if (Func == LibFunc::sincospif_stret)
Bob Wilsond8d92d92013-11-03 06:48:38 +00001390 SinCosCalls.push_back(CI);
1391 } else {
1392 if (Func == LibFunc::sinpi)
1393 SinCalls.push_back(CI);
1394 else if (Func == LibFunc::cospi)
1395 CosCalls.push_back(CI);
1396 else if (Func == LibFunc::sincospi_stret)
1397 SinCosCalls.push_back(CI);
1398 }
1399 }
1400
1401 void replaceTrigInsts(SmallVectorImpl<CallInst*> &Calls, Value *Res) {
1402 for (SmallVectorImpl<CallInst*>::iterator I = Calls.begin(),
1403 E = Calls.end();
1404 I != E; ++I) {
1405 LCS->replaceAllUsesWith(*I, Res);
1406 }
1407 }
1408
1409 void insertSinCosCall(IRBuilder<> &B, Function *OrigCallee, Value *Arg,
1410 bool UseFloat, Value *&Sin, Value *&Cos,
1411 Value *&SinCos) {
1412 Type *ArgTy = Arg->getType();
1413 Type *ResTy;
1414 StringRef Name;
1415
1416 Triple T(OrigCallee->getParent()->getTargetTriple());
1417 if (UseFloat) {
Tim Northover103e6482014-02-04 16:28:20 +00001418 Name = "__sincospif_stret";
Bob Wilsond8d92d92013-11-03 06:48:38 +00001419
1420 assert(T.getArch() != Triple::x86 && "x86 messy and unsupported for now");
1421 // x86_64 can't use {float, float} since that would be returned in both
1422 // xmm0 and xmm1, which isn't what a real struct would do.
1423 ResTy = T.getArch() == Triple::x86_64
1424 ? static_cast<Type *>(VectorType::get(ArgTy, 2))
1425 : static_cast<Type *>(StructType::get(ArgTy, ArgTy, NULL));
1426 } else {
1427 Name = "__sincospi_stret";
1428 ResTy = StructType::get(ArgTy, ArgTy, NULL);
1429 }
1430
1431 Module *M = OrigCallee->getParent();
1432 Value *Callee = M->getOrInsertFunction(Name, OrigCallee->getAttributes(),
1433 ResTy, ArgTy, NULL);
1434
1435 if (Instruction *ArgInst = dyn_cast<Instruction>(Arg)) {
1436 // If the argument is an instruction, it must dominate all uses so put our
1437 // sincos call there.
1438 BasicBlock::iterator Loc = ArgInst;
1439 B.SetInsertPoint(ArgInst->getParent(), ++Loc);
1440 } else {
1441 // Otherwise (e.g. for a constant) the beginning of the function is as
1442 // good a place as any.
1443 BasicBlock &EntryBB = B.GetInsertBlock()->getParent()->getEntryBlock();
1444 B.SetInsertPoint(&EntryBB, EntryBB.begin());
1445 }
1446
1447 SinCos = B.CreateCall(Callee, Arg, "sincospi");
1448
1449 if (SinCos->getType()->isStructTy()) {
1450 Sin = B.CreateExtractValue(SinCos, 0, "sinpi");
1451 Cos = B.CreateExtractValue(SinCos, 1, "cospi");
1452 } else {
1453 Sin = B.CreateExtractElement(SinCos, ConstantInt::get(B.getInt32Ty(), 0),
1454 "sinpi");
1455 Cos = B.CreateExtractElement(SinCos, ConstantInt::get(B.getInt32Ty(), 1),
1456 "cospi");
1457 }
1458 }
1459
1460};
1461
Meador Inge7415f842012-11-25 20:45:27 +00001462//===----------------------------------------------------------------------===//
1463// Integer Library Call Optimizations
1464//===----------------------------------------------------------------------===//
1465
1466struct FFSOpt : public LibCallOptimization {
1467 virtual Value *callOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
1468 FunctionType *FT = Callee->getFunctionType();
1469 // Just make sure this has 2 arguments of the same FP type, which match the
1470 // result type.
1471 if (FT->getNumParams() != 1 ||
1472 !FT->getReturnType()->isIntegerTy(32) ||
1473 !FT->getParamType(0)->isIntegerTy())
1474 return 0;
1475
1476 Value *Op = CI->getArgOperand(0);
1477
1478 // Constant fold.
1479 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op)) {
1480 if (CI->isZero()) // ffs(0) -> 0.
1481 return B.getInt32(0);
1482 // ffs(c) -> cttz(c)+1
1483 return B.getInt32(CI->getValue().countTrailingZeros() + 1);
1484 }
1485
1486 // ffs(x) -> x != 0 ? (i32)llvm.cttz(x)+1 : 0
1487 Type *ArgType = Op->getType();
1488 Value *F = Intrinsic::getDeclaration(Callee->getParent(),
1489 Intrinsic::cttz, ArgType);
1490 Value *V = B.CreateCall2(F, Op, B.getFalse(), "cttz");
1491 V = B.CreateAdd(V, ConstantInt::get(V->getType(), 1));
1492 V = B.CreateIntCast(V, B.getInt32Ty(), false);
1493
1494 Value *Cond = B.CreateICmpNE(Op, Constant::getNullValue(ArgType));
1495 return B.CreateSelect(Cond, V, B.getInt32(0));
1496 }
1497};
1498
Meador Ingea0b6d872012-11-26 00:24:07 +00001499struct AbsOpt : public LibCallOptimization {
Chad Rosier22d275f2013-02-08 18:00:14 +00001500 virtual bool ignoreCallingConv() { return true; }
Meador Ingea0b6d872012-11-26 00:24:07 +00001501 virtual Value *callOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
1502 FunctionType *FT = Callee->getFunctionType();
1503 // We require integer(integer) where the types agree.
1504 if (FT->getNumParams() != 1 || !FT->getReturnType()->isIntegerTy() ||
1505 FT->getParamType(0) != FT->getReturnType())
1506 return 0;
1507
1508 // abs(x) -> x >s -1 ? x : -x
1509 Value *Op = CI->getArgOperand(0);
1510 Value *Pos = B.CreateICmpSGT(Op, Constant::getAllOnesValue(Op->getType()),
1511 "ispos");
1512 Value *Neg = B.CreateNeg(Op, "neg");
1513 return B.CreateSelect(Pos, Op, Neg);
1514 }
1515};
1516
Meador Inge9a59ab62012-11-26 02:31:59 +00001517struct IsDigitOpt : public LibCallOptimization {
1518 virtual Value *callOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
1519 FunctionType *FT = Callee->getFunctionType();
1520 // We require integer(i32)
1521 if (FT->getNumParams() != 1 || !FT->getReturnType()->isIntegerTy() ||
1522 !FT->getParamType(0)->isIntegerTy(32))
1523 return 0;
1524
1525 // isdigit(c) -> (c-'0') <u 10
1526 Value *Op = CI->getArgOperand(0);
1527 Op = B.CreateSub(Op, B.getInt32('0'), "isdigittmp");
1528 Op = B.CreateICmpULT(Op, B.getInt32(10), "isdigit");
1529 return B.CreateZExt(Op, CI->getType());
1530 }
1531};
1532
Meador Ingea62a39e2012-11-26 03:10:07 +00001533struct IsAsciiOpt : public LibCallOptimization {
1534 virtual Value *callOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
1535 FunctionType *FT = Callee->getFunctionType();
1536 // We require integer(i32)
1537 if (FT->getNumParams() != 1 || !FT->getReturnType()->isIntegerTy() ||
1538 !FT->getParamType(0)->isIntegerTy(32))
1539 return 0;
1540
1541 // isascii(c) -> c <u 128
1542 Value *Op = CI->getArgOperand(0);
1543 Op = B.CreateICmpULT(Op, B.getInt32(128), "isascii");
1544 return B.CreateZExt(Op, CI->getType());
1545 }
1546};
1547
Meador Inge604937d2012-11-26 03:38:52 +00001548struct ToAsciiOpt : public LibCallOptimization {
1549 virtual Value *callOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
1550 FunctionType *FT = Callee->getFunctionType();
1551 // We require i32(i32)
1552 if (FT->getNumParams() != 1 || FT->getReturnType() != FT->getParamType(0) ||
1553 !FT->getParamType(0)->isIntegerTy(32))
1554 return 0;
1555
Meador Ingeefe23932012-11-26 20:37:23 +00001556 // toascii(c) -> c & 0x7f
Meador Inge604937d2012-11-26 03:38:52 +00001557 return B.CreateAnd(CI->getArgOperand(0),
1558 ConstantInt::get(CI->getType(),0x7F));
1559 }
1560};
1561
Meador Inge08ca1152012-11-26 20:37:20 +00001562//===----------------------------------------------------------------------===//
1563// Formatting and IO Library Call Optimizations
1564//===----------------------------------------------------------------------===//
1565
Hal Finkel66cd3f12013-11-17 02:06:35 +00001566struct ErrorReportingOpt : public LibCallOptimization {
1567 ErrorReportingOpt(int S = -1) : StreamArg(S) {}
1568
1569 virtual Value *callOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &) {
1570 // Error reporting calls should be cold, mark them as such.
1571 // This applies even to non-builtin calls: it is only a hint and applies to
1572 // functions that the frontend might not understand as builtins.
1573
1574 // This heuristic was suggested in:
1575 // Improving Static Branch Prediction in a Compiler
1576 // Brian L. Deitrich, Ben-Chung Cheng, Wen-mei W. Hwu
1577 // Proceedings of PACT'98, Oct. 1998, IEEE
1578
1579 if (!CI->hasFnAttr(Attribute::Cold) && isReportingError(Callee, CI)) {
1580 CI->addAttribute(AttributeSet::FunctionIndex, Attribute::Cold);
1581 }
1582
1583 return 0;
1584 }
1585
1586protected:
1587 bool isReportingError(Function *Callee, CallInst *CI) {
1588 if (!ColdErrorCalls)
1589 return false;
1590
1591 if (!Callee || !Callee->isDeclaration())
1592 return false;
1593
1594 if (StreamArg < 0)
1595 return true;
1596
1597 // These functions might be considered cold, but only if their stream
1598 // argument is stderr.
1599
1600 if (StreamArg >= (int) CI->getNumArgOperands())
1601 return false;
1602 LoadInst *LI = dyn_cast<LoadInst>(CI->getArgOperand(StreamArg));
1603 if (!LI)
1604 return false;
1605 GlobalVariable *GV = dyn_cast<GlobalVariable>(LI->getPointerOperand());
1606 if (!GV || !GV->isDeclaration())
1607 return false;
1608 return GV->getName() == "stderr";
1609 }
1610
1611 int StreamArg;
1612};
1613
Meador Inge08ca1152012-11-26 20:37:20 +00001614struct PrintFOpt : public LibCallOptimization {
1615 Value *optimizeFixedFormatString(Function *Callee, CallInst *CI,
1616 IRBuilder<> &B) {
1617 // Check for a fixed format string.
1618 StringRef FormatStr;
1619 if (!getConstantStringInfo(CI->getArgOperand(0), FormatStr))
1620 return 0;
1621
1622 // Empty format string -> noop.
1623 if (FormatStr.empty()) // Tolerate printf's declared void.
1624 return CI->use_empty() ? (Value*)CI :
1625 ConstantInt::get(CI->getType(), 0);
1626
1627 // Do not do any of the following transformations if the printf return value
1628 // is used, in general the printf return value is not compatible with either
1629 // putchar() or puts().
1630 if (!CI->use_empty())
1631 return 0;
1632
1633 // printf("x") -> putchar('x'), even for '%'.
1634 if (FormatStr.size() == 1) {
Rafael Espindola37dc9e12014-02-21 00:06:31 +00001635 Value *Res = EmitPutChar(B.getInt32(FormatStr[0]), B, DL, TLI);
Meador Inge08ca1152012-11-26 20:37:20 +00001636 if (CI->use_empty() || !Res) return Res;
1637 return B.CreateIntCast(Res, CI->getType(), true);
1638 }
1639
1640 // printf("foo\n") --> puts("foo")
1641 if (FormatStr[FormatStr.size()-1] == '\n' &&
Matt Arsenaultf631f8c2013-09-10 00:41:53 +00001642 FormatStr.find('%') == StringRef::npos) { // No format characters.
Meador Inge08ca1152012-11-26 20:37:20 +00001643 // Create a string literal with no \n on it. We expect the constant merge
1644 // pass to be run after this pass, to merge duplicate strings.
1645 FormatStr = FormatStr.drop_back();
1646 Value *GV = B.CreateGlobalString(FormatStr, "str");
Rafael Espindola37dc9e12014-02-21 00:06:31 +00001647 Value *NewCI = EmitPutS(GV, B, DL, TLI);
Meador Inge08ca1152012-11-26 20:37:20 +00001648 return (CI->use_empty() || !NewCI) ?
1649 NewCI :
1650 ConstantInt::get(CI->getType(), FormatStr.size()+1);
1651 }
1652
1653 // Optimize specific format strings.
1654 // printf("%c", chr) --> putchar(chr)
1655 if (FormatStr == "%c" && CI->getNumArgOperands() > 1 &&
1656 CI->getArgOperand(1)->getType()->isIntegerTy()) {
Rafael Espindola37dc9e12014-02-21 00:06:31 +00001657 Value *Res = EmitPutChar(CI->getArgOperand(1), B, DL, TLI);
Meador Inge08ca1152012-11-26 20:37:20 +00001658
1659 if (CI->use_empty() || !Res) return Res;
1660 return B.CreateIntCast(Res, CI->getType(), true);
1661 }
1662
1663 // printf("%s\n", str) --> puts(str)
1664 if (FormatStr == "%s\n" && CI->getNumArgOperands() > 1 &&
1665 CI->getArgOperand(1)->getType()->isPointerTy()) {
Rafael Espindola37dc9e12014-02-21 00:06:31 +00001666 return EmitPutS(CI->getArgOperand(1), B, DL, TLI);
Meador Inge08ca1152012-11-26 20:37:20 +00001667 }
1668 return 0;
1669 }
1670
1671 virtual Value *callOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
1672 // Require one fixed pointer argument and an integer/void result.
1673 FunctionType *FT = Callee->getFunctionType();
1674 if (FT->getNumParams() < 1 || !FT->getParamType(0)->isPointerTy() ||
1675 !(FT->getReturnType()->isIntegerTy() ||
1676 FT->getReturnType()->isVoidTy()))
1677 return 0;
1678
1679 if (Value *V = optimizeFixedFormatString(Callee, CI, B)) {
1680 return V;
1681 }
1682
1683 // printf(format, ...) -> iprintf(format, ...) if no floating point
1684 // arguments.
1685 if (TLI->has(LibFunc::iprintf) && !callHasFloatingPointArgument(CI)) {
1686 Module *M = B.GetInsertBlock()->getParent()->getParent();
1687 Constant *IPrintFFn =
1688 M->getOrInsertFunction("iprintf", FT, Callee->getAttributes());
1689 CallInst *New = cast<CallInst>(CI->clone());
1690 New->setCalledFunction(IPrintFFn);
1691 B.Insert(New);
1692 return New;
1693 }
1694 return 0;
1695 }
1696};
1697
Meador Inge25c9b3b2012-11-27 05:57:54 +00001698struct SPrintFOpt : public LibCallOptimization {
1699 Value *OptimizeFixedFormatString(Function *Callee, CallInst *CI,
1700 IRBuilder<> &B) {
1701 // Check for a fixed format string.
1702 StringRef FormatStr;
1703 if (!getConstantStringInfo(CI->getArgOperand(1), FormatStr))
1704 return 0;
1705
1706 // If we just have a format string (nothing else crazy) transform it.
1707 if (CI->getNumArgOperands() == 2) {
1708 // Make sure there's no % in the constant array. We could try to handle
1709 // %% -> % in the future if we cared.
1710 for (unsigned i = 0, e = FormatStr.size(); i != e; ++i)
1711 if (FormatStr[i] == '%')
1712 return 0; // we found a format specifier, bail out.
1713
1714 // These optimizations require DataLayout.
Rafael Espindola37dc9e12014-02-21 00:06:31 +00001715 if (!DL) return 0;
Meador Inge25c9b3b2012-11-27 05:57:54 +00001716
1717 // sprintf(str, fmt) -> llvm.memcpy(str, fmt, strlen(fmt)+1, 1)
1718 B.CreateMemCpy(CI->getArgOperand(0), CI->getArgOperand(1),
Rafael Espindola37dc9e12014-02-21 00:06:31 +00001719 ConstantInt::get(DL->getIntPtrType(*Context), // Copy the
Meador Inge25c9b3b2012-11-27 05:57:54 +00001720 FormatStr.size() + 1), 1); // nul byte.
1721 return ConstantInt::get(CI->getType(), FormatStr.size());
1722 }
1723
1724 // The remaining optimizations require the format string to be "%s" or "%c"
1725 // and have an extra operand.
1726 if (FormatStr.size() != 2 || FormatStr[0] != '%' ||
1727 CI->getNumArgOperands() < 3)
1728 return 0;
1729
1730 // Decode the second character of the format string.
1731 if (FormatStr[1] == 'c') {
1732 // sprintf(dst, "%c", chr) --> *(i8*)dst = chr; *((i8*)dst+1) = 0
1733 if (!CI->getArgOperand(2)->getType()->isIntegerTy()) return 0;
1734 Value *V = B.CreateTrunc(CI->getArgOperand(2), B.getInt8Ty(), "char");
1735 Value *Ptr = CastToCStr(CI->getArgOperand(0), B);
1736 B.CreateStore(V, Ptr);
1737 Ptr = B.CreateGEP(Ptr, B.getInt32(1), "nul");
1738 B.CreateStore(B.getInt8(0), Ptr);
1739
1740 return ConstantInt::get(CI->getType(), 1);
1741 }
1742
1743 if (FormatStr[1] == 's') {
1744 // These optimizations require DataLayout.
Rafael Espindola37dc9e12014-02-21 00:06:31 +00001745 if (!DL) return 0;
Meador Inge25c9b3b2012-11-27 05:57:54 +00001746
1747 // sprintf(dest, "%s", str) -> llvm.memcpy(dest, str, strlen(str)+1, 1)
1748 if (!CI->getArgOperand(2)->getType()->isPointerTy()) return 0;
1749
Rafael Espindola37dc9e12014-02-21 00:06:31 +00001750 Value *Len = EmitStrLen(CI->getArgOperand(2), B, DL, TLI);
Meador Inge25c9b3b2012-11-27 05:57:54 +00001751 if (!Len)
1752 return 0;
1753 Value *IncLen = B.CreateAdd(Len,
1754 ConstantInt::get(Len->getType(), 1),
1755 "leninc");
1756 B.CreateMemCpy(CI->getArgOperand(0), CI->getArgOperand(2), IncLen, 1);
1757
1758 // The sprintf result is the unincremented number of bytes in the string.
1759 return B.CreateIntCast(Len, CI->getType(), false);
1760 }
1761 return 0;
1762 }
1763
1764 virtual Value *callOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
1765 // Require two fixed pointer arguments and an integer result.
1766 FunctionType *FT = Callee->getFunctionType();
1767 if (FT->getNumParams() != 2 || !FT->getParamType(0)->isPointerTy() ||
1768 !FT->getParamType(1)->isPointerTy() ||
1769 !FT->getReturnType()->isIntegerTy())
1770 return 0;
1771
1772 if (Value *V = OptimizeFixedFormatString(Callee, CI, B)) {
1773 return V;
1774 }
1775
1776 // sprintf(str, format, ...) -> siprintf(str, format, ...) if no floating
1777 // point arguments.
1778 if (TLI->has(LibFunc::siprintf) && !callHasFloatingPointArgument(CI)) {
1779 Module *M = B.GetInsertBlock()->getParent()->getParent();
1780 Constant *SIPrintFFn =
1781 M->getOrInsertFunction("siprintf", FT, Callee->getAttributes());
1782 CallInst *New = cast<CallInst>(CI->clone());
1783 New->setCalledFunction(SIPrintFFn);
1784 B.Insert(New);
1785 return New;
1786 }
1787 return 0;
1788 }
1789};
1790
Meador Inge1009cec2012-11-29 15:45:33 +00001791struct FPrintFOpt : public LibCallOptimization {
1792 Value *optimizeFixedFormatString(Function *Callee, CallInst *CI,
1793 IRBuilder<> &B) {
Hal Finkel66cd3f12013-11-17 02:06:35 +00001794 ErrorReportingOpt ER(/* StreamArg = */ 0);
1795 (void) ER.callOptimizer(Callee, CI, B);
1796
Meador Inge1009cec2012-11-29 15:45:33 +00001797 // All the optimizations depend on the format string.
1798 StringRef FormatStr;
1799 if (!getConstantStringInfo(CI->getArgOperand(1), FormatStr))
1800 return 0;
1801
Peter Collingbourne37ae72b2013-04-17 02:01:10 +00001802 // Do not do any of the following transformations if the fprintf return
1803 // value is used, in general the fprintf return value is not compatible
1804 // with fwrite(), fputc() or fputs().
1805 if (!CI->use_empty())
1806 return 0;
1807
Meador Inge1009cec2012-11-29 15:45:33 +00001808 // fprintf(F, "foo") --> fwrite("foo", 3, 1, F)
1809 if (CI->getNumArgOperands() == 2) {
1810 for (unsigned i = 0, e = FormatStr.size(); i != e; ++i)
1811 if (FormatStr[i] == '%') // Could handle %% -> % if we cared.
1812 return 0; // We found a format specifier.
1813
1814 // These optimizations require DataLayout.
Rafael Espindola37dc9e12014-02-21 00:06:31 +00001815 if (!DL) return 0;
Meador Inge1009cec2012-11-29 15:45:33 +00001816
Peter Collingbourne37ae72b2013-04-17 02:01:10 +00001817 return EmitFWrite(CI->getArgOperand(1),
Rafael Espindola37dc9e12014-02-21 00:06:31 +00001818 ConstantInt::get(DL->getIntPtrType(*Context),
Peter Collingbourne37ae72b2013-04-17 02:01:10 +00001819 FormatStr.size()),
Rafael Espindola37dc9e12014-02-21 00:06:31 +00001820 CI->getArgOperand(0), B, DL, TLI);
Meador Inge1009cec2012-11-29 15:45:33 +00001821 }
1822
1823 // The remaining optimizations require the format string to be "%s" or "%c"
1824 // and have an extra operand.
1825 if (FormatStr.size() != 2 || FormatStr[0] != '%' ||
1826 CI->getNumArgOperands() < 3)
1827 return 0;
1828
1829 // Decode the second character of the format string.
1830 if (FormatStr[1] == 'c') {
1831 // fprintf(F, "%c", chr) --> fputc(chr, F)
1832 if (!CI->getArgOperand(2)->getType()->isIntegerTy()) return 0;
Rafael Espindola37dc9e12014-02-21 00:06:31 +00001833 return EmitFPutC(CI->getArgOperand(2), CI->getArgOperand(0), B, DL, TLI);
Meador Inge1009cec2012-11-29 15:45:33 +00001834 }
1835
1836 if (FormatStr[1] == 's') {
1837 // fprintf(F, "%s", str) --> fputs(str, F)
Peter Collingbourne37ae72b2013-04-17 02:01:10 +00001838 if (!CI->getArgOperand(2)->getType()->isPointerTy())
Meador Inge1009cec2012-11-29 15:45:33 +00001839 return 0;
Rafael Espindola37dc9e12014-02-21 00:06:31 +00001840 return EmitFPutS(CI->getArgOperand(2), CI->getArgOperand(0), B, DL, TLI);
Meador Inge1009cec2012-11-29 15:45:33 +00001841 }
1842 return 0;
1843 }
1844
1845 virtual Value *callOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
1846 // Require two fixed paramters as pointers and integer result.
1847 FunctionType *FT = Callee->getFunctionType();
1848 if (FT->getNumParams() != 2 || !FT->getParamType(0)->isPointerTy() ||
1849 !FT->getParamType(1)->isPointerTy() ||
1850 !FT->getReturnType()->isIntegerTy())
1851 return 0;
1852
1853 if (Value *V = optimizeFixedFormatString(Callee, CI, B)) {
1854 return V;
1855 }
1856
1857 // fprintf(stream, format, ...) -> fiprintf(stream, format, ...) if no
1858 // floating point arguments.
1859 if (TLI->has(LibFunc::fiprintf) && !callHasFloatingPointArgument(CI)) {
1860 Module *M = B.GetInsertBlock()->getParent()->getParent();
1861 Constant *FIPrintFFn =
1862 M->getOrInsertFunction("fiprintf", FT, Callee->getAttributes());
1863 CallInst *New = cast<CallInst>(CI->clone());
1864 New->setCalledFunction(FIPrintFFn);
1865 B.Insert(New);
1866 return New;
1867 }
1868 return 0;
1869 }
1870};
1871
Meador Ingebc84d1a2012-11-29 15:45:39 +00001872struct FWriteOpt : public LibCallOptimization {
1873 virtual Value *callOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
Hal Finkel66cd3f12013-11-17 02:06:35 +00001874 ErrorReportingOpt ER(/* StreamArg = */ 3);
1875 (void) ER.callOptimizer(Callee, CI, B);
1876
Meador Ingebc84d1a2012-11-29 15:45:39 +00001877 // Require a pointer, an integer, an integer, a pointer, returning integer.
1878 FunctionType *FT = Callee->getFunctionType();
1879 if (FT->getNumParams() != 4 || !FT->getParamType(0)->isPointerTy() ||
1880 !FT->getParamType(1)->isIntegerTy() ||
1881 !FT->getParamType(2)->isIntegerTy() ||
1882 !FT->getParamType(3)->isPointerTy() ||
1883 !FT->getReturnType()->isIntegerTy())
1884 return 0;
1885
1886 // Get the element size and count.
1887 ConstantInt *SizeC = dyn_cast<ConstantInt>(CI->getArgOperand(1));
1888 ConstantInt *CountC = dyn_cast<ConstantInt>(CI->getArgOperand(2));
1889 if (!SizeC || !CountC) return 0;
1890 uint64_t Bytes = SizeC->getZExtValue()*CountC->getZExtValue();
1891
1892 // If this is writing zero records, remove the call (it's a noop).
1893 if (Bytes == 0)
1894 return ConstantInt::get(CI->getType(), 0);
1895
1896 // If this is writing one byte, turn it into fputc.
1897 // This optimisation is only valid, if the return value is unused.
1898 if (Bytes == 1 && CI->use_empty()) { // fwrite(S,1,1,F) -> fputc(S[0],F)
1899 Value *Char = B.CreateLoad(CastToCStr(CI->getArgOperand(0), B), "char");
Rafael Espindola37dc9e12014-02-21 00:06:31 +00001900 Value *NewCI = EmitFPutC(Char, CI->getArgOperand(3), B, DL, TLI);
Meador Ingebc84d1a2012-11-29 15:45:39 +00001901 return NewCI ? ConstantInt::get(CI->getType(), 1) : 0;
1902 }
1903
1904 return 0;
1905 }
1906};
1907
Meador Ingef8e72502012-11-29 15:45:43 +00001908struct FPutsOpt : public LibCallOptimization {
1909 virtual Value *callOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
Hal Finkel66cd3f12013-11-17 02:06:35 +00001910 ErrorReportingOpt ER(/* StreamArg = */ 1);
1911 (void) ER.callOptimizer(Callee, CI, B);
1912
Meador Ingef8e72502012-11-29 15:45:43 +00001913 // These optimizations require DataLayout.
Rafael Espindola37dc9e12014-02-21 00:06:31 +00001914 if (!DL) return 0;
Meador Ingef8e72502012-11-29 15:45:43 +00001915
1916 // Require two pointers. Also, we can't optimize if return value is used.
1917 FunctionType *FT = Callee->getFunctionType();
1918 if (FT->getNumParams() != 2 || !FT->getParamType(0)->isPointerTy() ||
1919 !FT->getParamType(1)->isPointerTy() ||
1920 !CI->use_empty())
1921 return 0;
1922
1923 // fputs(s,F) --> fwrite(s,1,strlen(s),F)
1924 uint64_t Len = GetStringLength(CI->getArgOperand(0));
1925 if (!Len) return 0;
1926 // Known to have no uses (see above).
1927 return EmitFWrite(CI->getArgOperand(0),
Rafael Espindola37dc9e12014-02-21 00:06:31 +00001928 ConstantInt::get(DL->getIntPtrType(*Context), Len-1),
1929 CI->getArgOperand(1), B, DL, TLI);
Meador Ingef8e72502012-11-29 15:45:43 +00001930 }
1931};
1932
Meador Inge75798bb2012-11-29 19:15:17 +00001933struct PutsOpt : public LibCallOptimization {
1934 virtual Value *callOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
1935 // Require one fixed pointer argument and an integer/void result.
1936 FunctionType *FT = Callee->getFunctionType();
1937 if (FT->getNumParams() < 1 || !FT->getParamType(0)->isPointerTy() ||
1938 !(FT->getReturnType()->isIntegerTy() ||
1939 FT->getReturnType()->isVoidTy()))
1940 return 0;
1941
1942 // Check for a constant string.
1943 StringRef Str;
1944 if (!getConstantStringInfo(CI->getArgOperand(0), Str))
1945 return 0;
1946
1947 if (Str.empty() && CI->use_empty()) {
1948 // puts("") -> putchar('\n')
Rafael Espindola37dc9e12014-02-21 00:06:31 +00001949 Value *Res = EmitPutChar(B.getInt32('\n'), B, DL, TLI);
Meador Inge75798bb2012-11-29 19:15:17 +00001950 if (CI->use_empty() || !Res) return Res;
1951 return B.CreateIntCast(Res, CI->getType(), true);
1952 }
1953
1954 return 0;
1955 }
1956};
1957
Meador Ingedf796f82012-10-13 16:45:24 +00001958} // End anonymous namespace.
1959
1960namespace llvm {
1961
1962class LibCallSimplifierImpl {
Rafael Espindola37dc9e12014-02-21 00:06:31 +00001963 const DataLayout *DL;
Meador Ingedf796f82012-10-13 16:45:24 +00001964 const TargetLibraryInfo *TLI;
Meador Inge76fc1a42012-11-11 03:51:43 +00001965 const LibCallSimplifier *LCS;
Meador Inge193e0352012-11-13 04:16:17 +00001966 bool UnsafeFPShrink;
Meador Inge4d2827c2012-11-11 05:11:20 +00001967
Meador Inge193e0352012-11-13 04:16:17 +00001968 // Math library call optimizations.
Meador Inge20255ef2013-03-12 00:08:29 +00001969 CosOpt Cos;
1970 PowOpt Pow;
1971 Exp2Opt Exp2;
Meador Ingedf796f82012-10-13 16:45:24 +00001972public:
Rafael Espindola37dc9e12014-02-21 00:06:31 +00001973 LibCallSimplifierImpl(const DataLayout *DL, const TargetLibraryInfo *TLI,
Meador Inge193e0352012-11-13 04:16:17 +00001974 const LibCallSimplifier *LCS,
1975 bool UnsafeFPShrink = false)
Meador Inge20255ef2013-03-12 00:08:29 +00001976 : Cos(UnsafeFPShrink), Pow(UnsafeFPShrink), Exp2(UnsafeFPShrink) {
Rafael Espindola37dc9e12014-02-21 00:06:31 +00001977 this->DL = DL;
Meador Ingedf796f82012-10-13 16:45:24 +00001978 this->TLI = TLI;
Meador Inge76fc1a42012-11-11 03:51:43 +00001979 this->LCS = LCS;
Meador Inge193e0352012-11-13 04:16:17 +00001980 this->UnsafeFPShrink = UnsafeFPShrink;
Meador Ingedf796f82012-10-13 16:45:24 +00001981 }
1982
1983 Value *optimizeCall(CallInst *CI);
Meador Inge20255ef2013-03-12 00:08:29 +00001984 LibCallOptimization *lookupOptimization(CallInst *CI);
1985 bool hasFloatVersion(StringRef FuncName);
Meador Ingedf796f82012-10-13 16:45:24 +00001986};
1987
Meador Inge20255ef2013-03-12 00:08:29 +00001988bool LibCallSimplifierImpl::hasFloatVersion(StringRef FuncName) {
1989 LibFunc::Func Func;
1990 SmallString<20> FloatFuncName = FuncName;
1991 FloatFuncName += 'f';
1992 if (TLI->getLibFunc(FloatFuncName, Func))
1993 return TLI->has(Func);
1994 return false;
1995}
Meador Inge7fb2f732012-10-13 16:45:32 +00001996
Meador Inge20255ef2013-03-12 00:08:29 +00001997// Fortified library call optimizations.
1998static MemCpyChkOpt MemCpyChk;
1999static MemMoveChkOpt MemMoveChk;
2000static MemSetChkOpt MemSetChk;
2001static StrCpyChkOpt StrCpyChk;
2002static StpCpyChkOpt StpCpyChk;
2003static StrNCpyChkOpt StrNCpyChk;
Meador Inge4d2827c2012-11-11 05:11:20 +00002004
Meador Inge20255ef2013-03-12 00:08:29 +00002005// String library call optimizations.
2006static StrCatOpt StrCat;
2007static StrNCatOpt StrNCat;
2008static StrChrOpt StrChr;
2009static StrRChrOpt StrRChr;
2010static StrCmpOpt StrCmp;
2011static StrNCmpOpt StrNCmp;
2012static StrCpyOpt StrCpy;
2013static StpCpyOpt StpCpy;
2014static StrNCpyOpt StrNCpy;
2015static StrLenOpt StrLen;
2016static StrPBrkOpt StrPBrk;
2017static StrToOpt StrTo;
2018static StrSpnOpt StrSpn;
2019static StrCSpnOpt StrCSpn;
2020static StrStrOpt StrStr;
Meador Inge193e0352012-11-13 04:16:17 +00002021
Meador Inge20255ef2013-03-12 00:08:29 +00002022// Memory library call optimizations.
2023static MemCmpOpt MemCmp;
2024static MemCpyOpt MemCpy;
2025static MemMoveOpt MemMove;
2026static MemSetOpt MemSet;
Meador Inge193e0352012-11-13 04:16:17 +00002027
Meador Inge20255ef2013-03-12 00:08:29 +00002028// Math library call optimizations.
2029static UnaryDoubleFPOpt UnaryDoubleFP(false);
Yi Jiang6ab044e2013-12-16 22:42:40 +00002030static BinaryDoubleFPOpt BinaryDoubleFP(false);
Meador Inge20255ef2013-03-12 00:08:29 +00002031static UnaryDoubleFPOpt UnsafeUnaryDoubleFP(true);
Bob Wilsond8d92d92013-11-03 06:48:38 +00002032static SinCosPiOpt SinCosPi;
Meador Inge7415f842012-11-25 20:45:27 +00002033
2034 // Integer library call optimizations.
Meador Inge20255ef2013-03-12 00:08:29 +00002035static FFSOpt FFS;
2036static AbsOpt Abs;
2037static IsDigitOpt IsDigit;
2038static IsAsciiOpt IsAscii;
2039static ToAsciiOpt ToAscii;
Meador Inge08ca1152012-11-26 20:37:20 +00002040
Meador Inge20255ef2013-03-12 00:08:29 +00002041// Formatting and IO library call optimizations.
Hal Finkel66cd3f12013-11-17 02:06:35 +00002042static ErrorReportingOpt ErrorReporting;
2043static ErrorReportingOpt ErrorReporting0(0);
2044static ErrorReportingOpt ErrorReporting1(1);
Meador Inge20255ef2013-03-12 00:08:29 +00002045static PrintFOpt PrintF;
2046static SPrintFOpt SPrintF;
2047static FPrintFOpt FPrintF;
2048static FWriteOpt FWrite;
2049static FPutsOpt FPuts;
2050static PutsOpt Puts;
2051
2052LibCallOptimization *LibCallSimplifierImpl::lookupOptimization(CallInst *CI) {
2053 LibFunc::Func Func;
2054 Function *Callee = CI->getCalledFunction();
2055 StringRef FuncName = Callee->getName();
2056
2057 // Next check for intrinsics.
2058 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(CI)) {
2059 switch (II->getIntrinsicID()) {
2060 case Intrinsic::pow:
2061 return &Pow;
2062 case Intrinsic::exp2:
2063 return &Exp2;
2064 default:
2065 return 0;
2066 }
2067 }
2068
2069 // Then check for known library functions.
2070 if (TLI->getLibFunc(FuncName, Func) && TLI->has(Func)) {
2071 switch (Func) {
2072 case LibFunc::strcat:
2073 return &StrCat;
2074 case LibFunc::strncat:
2075 return &StrNCat;
2076 case LibFunc::strchr:
2077 return &StrChr;
2078 case LibFunc::strrchr:
2079 return &StrRChr;
2080 case LibFunc::strcmp:
2081 return &StrCmp;
2082 case LibFunc::strncmp:
2083 return &StrNCmp;
2084 case LibFunc::strcpy:
2085 return &StrCpy;
2086 case LibFunc::stpcpy:
2087 return &StpCpy;
2088 case LibFunc::strncpy:
2089 return &StrNCpy;
2090 case LibFunc::strlen:
2091 return &StrLen;
2092 case LibFunc::strpbrk:
2093 return &StrPBrk;
2094 case LibFunc::strtol:
2095 case LibFunc::strtod:
2096 case LibFunc::strtof:
2097 case LibFunc::strtoul:
2098 case LibFunc::strtoll:
2099 case LibFunc::strtold:
2100 case LibFunc::strtoull:
2101 return &StrTo;
2102 case LibFunc::strspn:
2103 return &StrSpn;
2104 case LibFunc::strcspn:
2105 return &StrCSpn;
2106 case LibFunc::strstr:
2107 return &StrStr;
2108 case LibFunc::memcmp:
2109 return &MemCmp;
2110 case LibFunc::memcpy:
2111 return &MemCpy;
2112 case LibFunc::memmove:
2113 return &MemMove;
2114 case LibFunc::memset:
2115 return &MemSet;
2116 case LibFunc::cosf:
2117 case LibFunc::cos:
2118 case LibFunc::cosl:
2119 return &Cos;
Bob Wilsond8d92d92013-11-03 06:48:38 +00002120 case LibFunc::sinpif:
2121 case LibFunc::sinpi:
2122 case LibFunc::cospif:
2123 case LibFunc::cospi:
2124 return &SinCosPi;
Meador Inge20255ef2013-03-12 00:08:29 +00002125 case LibFunc::powf:
2126 case LibFunc::pow:
2127 case LibFunc::powl:
2128 return &Pow;
2129 case LibFunc::exp2l:
2130 case LibFunc::exp2:
2131 case LibFunc::exp2f:
2132 return &Exp2;
2133 case LibFunc::ffs:
2134 case LibFunc::ffsl:
2135 case LibFunc::ffsll:
2136 return &FFS;
2137 case LibFunc::abs:
2138 case LibFunc::labs:
2139 case LibFunc::llabs:
2140 return &Abs;
2141 case LibFunc::isdigit:
2142 return &IsDigit;
2143 case LibFunc::isascii:
2144 return &IsAscii;
2145 case LibFunc::toascii:
2146 return &ToAscii;
2147 case LibFunc::printf:
2148 return &PrintF;
2149 case LibFunc::sprintf:
2150 return &SPrintF;
2151 case LibFunc::fprintf:
2152 return &FPrintF;
2153 case LibFunc::fwrite:
2154 return &FWrite;
2155 case LibFunc::fputs:
2156 return &FPuts;
2157 case LibFunc::puts:
2158 return &Puts;
Hal Finkel66cd3f12013-11-17 02:06:35 +00002159 case LibFunc::perror:
2160 return &ErrorReporting;
2161 case LibFunc::vfprintf:
2162 case LibFunc::fiprintf:
2163 return &ErrorReporting0;
2164 case LibFunc::fputc:
2165 return &ErrorReporting1;
Meador Inge20255ef2013-03-12 00:08:29 +00002166 case LibFunc::ceil:
2167 case LibFunc::fabs:
2168 case LibFunc::floor:
2169 case LibFunc::rint:
2170 case LibFunc::round:
2171 case LibFunc::nearbyint:
2172 case LibFunc::trunc:
2173 if (hasFloatVersion(FuncName))
2174 return &UnaryDoubleFP;
2175 return 0;
2176 case LibFunc::acos:
2177 case LibFunc::acosh:
2178 case LibFunc::asin:
2179 case LibFunc::asinh:
2180 case LibFunc::atan:
2181 case LibFunc::atanh:
2182 case LibFunc::cbrt:
2183 case LibFunc::cosh:
2184 case LibFunc::exp:
2185 case LibFunc::exp10:
2186 case LibFunc::expm1:
2187 case LibFunc::log:
2188 case LibFunc::log10:
2189 case LibFunc::log1p:
2190 case LibFunc::log2:
2191 case LibFunc::logb:
2192 case LibFunc::sin:
2193 case LibFunc::sinh:
2194 case LibFunc::sqrt:
2195 case LibFunc::tan:
2196 case LibFunc::tanh:
2197 if (UnsafeFPShrink && hasFloatVersion(FuncName))
2198 return &UnsafeUnaryDoubleFP;
2199 return 0;
Yi Jiang6ab044e2013-12-16 22:42:40 +00002200 case LibFunc::fmin:
2201 case LibFunc::fmax:
2202 if (hasFloatVersion(FuncName))
2203 return &BinaryDoubleFP;
2204 return 0;
Meador Inge20255ef2013-03-12 00:08:29 +00002205 case LibFunc::memcpy_chk:
2206 return &MemCpyChk;
2207 default:
2208 return 0;
2209 }
2210 }
2211
2212 // Finally check for fortified library calls.
2213 if (FuncName.endswith("_chk")) {
2214 if (FuncName == "__memmove_chk")
2215 return &MemMoveChk;
2216 else if (FuncName == "__memset_chk")
2217 return &MemSetChk;
2218 else if (FuncName == "__strcpy_chk")
2219 return &StrCpyChk;
2220 else if (FuncName == "__stpcpy_chk")
2221 return &StpCpyChk;
2222 else if (FuncName == "__strncpy_chk")
2223 return &StrNCpyChk;
2224 else if (FuncName == "__stpncpy_chk")
2225 return &StrNCpyChk;
2226 }
2227
2228 return 0;
2229
Meador Ingedf796f82012-10-13 16:45:24 +00002230}
2231
2232Value *LibCallSimplifierImpl::optimizeCall(CallInst *CI) {
Meador Inge20255ef2013-03-12 00:08:29 +00002233 LibCallOptimization *LCO = lookupOptimization(CI);
Meador Ingedf796f82012-10-13 16:45:24 +00002234 if (LCO) {
2235 IRBuilder<> Builder(CI);
Rafael Espindola37dc9e12014-02-21 00:06:31 +00002236 return LCO->optimizeCall(CI, DL, TLI, LCS, Builder);
Meador Ingedf796f82012-10-13 16:45:24 +00002237 }
2238 return 0;
2239}
2240
Rafael Espindola37dc9e12014-02-21 00:06:31 +00002241LibCallSimplifier::LibCallSimplifier(const DataLayout *DL,
Meador Inge193e0352012-11-13 04:16:17 +00002242 const TargetLibraryInfo *TLI,
2243 bool UnsafeFPShrink) {
Rafael Espindola37dc9e12014-02-21 00:06:31 +00002244 Impl = new LibCallSimplifierImpl(DL, TLI, this, UnsafeFPShrink);
Meador Ingedf796f82012-10-13 16:45:24 +00002245}
2246
2247LibCallSimplifier::~LibCallSimplifier() {
2248 delete Impl;
2249}
2250
2251Value *LibCallSimplifier::optimizeCall(CallInst *CI) {
Michael Gottesman41748d72013-06-27 00:25:01 +00002252 if (CI->isNoBuiltin()) return 0;
Meador Ingedf796f82012-10-13 16:45:24 +00002253 return Impl->optimizeCall(CI);
2254}
2255
Meador Inge76fc1a42012-11-11 03:51:43 +00002256void LibCallSimplifier::replaceAllUsesWith(Instruction *I, Value *With) const {
2257 I->replaceAllUsesWith(With);
2258 I->eraseFromParent();
2259}
2260
Meador Ingedf796f82012-10-13 16:45:24 +00002261}
Meador Ingedfb08a22013-06-20 19:48:07 +00002262
2263// TODO:
2264// Additional cases that we need to add to this file:
2265//
2266// cbrt:
2267// * cbrt(expN(X)) -> expN(x/3)
2268// * cbrt(sqrt(x)) -> pow(x,1/6)
2269// * cbrt(sqrt(x)) -> pow(x,1/9)
2270//
2271// exp, expf, expl:
2272// * exp(log(x)) -> x
2273//
2274// log, logf, logl:
2275// * log(exp(x)) -> x
2276// * log(x**y) -> y*log(x)
2277// * log(exp(y)) -> y*log(e)
2278// * log(exp2(y)) -> y*log(2)
2279// * log(exp10(y)) -> y*log(10)
2280// * log(sqrt(x)) -> 0.5*log(x)
2281// * log(pow(x,y)) -> y*log(x)
2282//
2283// lround, lroundf, lroundl:
2284// * lround(cnst) -> cnst'
2285//
2286// pow, powf, powl:
2287// * pow(exp(x),y) -> exp(x*y)
2288// * pow(sqrt(x),y) -> pow(x,y*0.5)
2289// * pow(pow(x,y),z)-> pow(x,y*z)
2290//
2291// round, roundf, roundl:
2292// * round(cnst) -> cnst'
2293//
2294// signbit:
2295// * signbit(cnst) -> cnst'
2296// * signbit(nncst) -> 0 (if pstv is a non-negative constant)
2297//
2298// sqrt, sqrtf, sqrtl:
2299// * sqrt(expN(x)) -> expN(x*0.5)
2300// * sqrt(Nroot(x)) -> pow(x,1/(2*N))
2301// * sqrt(pow(x,y)) -> pow(|x|,y*0.5)
2302//
Meador Ingedfb08a22013-06-20 19:48:07 +00002303// tan, tanf, tanl:
2304// * tan(atan(x)) -> x
2305//
2306// trunc, truncf, truncl:
2307// * trunc(cnst) -> cnst'
2308//
2309//