blob: 8389e39f7af030fb5dbda2cdd2ea6b3988697708 [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"
Weiming Zhao45d4cb92015-11-24 18:57:06 +000021#include "llvm/Analysis/TargetLibraryInfo.h"
Meador Ingedf796f82012-10-13 16:45:24 +000022#include "llvm/Analysis/ValueTracking.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000023#include "llvm/IR/DataLayout.h"
Diego Novillo7f8af8b2014-05-22 14:19:46 +000024#include "llvm/IR/DiagnosticInfo.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000025#include "llvm/IR/Function.h"
26#include "llvm/IR/IRBuilder.h"
Meador Inge20255ef2013-03-12 00:08:29 +000027#include "llvm/IR/IntrinsicInst.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000028#include "llvm/IR/Intrinsics.h"
29#include "llvm/IR/LLVMContext.h"
30#include "llvm/IR/Module.h"
Sanjay Patelc699a612014-10-16 18:48:17 +000031#include "llvm/IR/PatternMatch.h"
Nadav Rotem464e8072013-02-27 05:53:43 +000032#include "llvm/Support/Allocator.h"
Hal Finkel66cd3f12013-11-17 02:06:35 +000033#include "llvm/Support/CommandLine.h"
Meador Ingedf796f82012-10-13 16:45:24 +000034#include "llvm/Transforms/Utils/BuildLibCalls.h"
Chad Rosierdc655322015-08-28 18:30:18 +000035#include "llvm/Transforms/Utils/Local.h"
Meador Ingedf796f82012-10-13 16:45:24 +000036
37using namespace llvm;
Sanjay Patelc699a612014-10-16 18:48:17 +000038using namespace PatternMatch;
Meador Ingedf796f82012-10-13 16:45:24 +000039
Hal Finkel66cd3f12013-11-17 02:06:35 +000040static cl::opt<bool>
Chris Bienemanad070d02014-09-17 20:55:46 +000041 ColdErrorCalls("error-reporting-is-cold", cl::init(true), cl::Hidden,
42 cl::desc("Treat error-reporting calls as cold"));
Meador Ingedf796f82012-10-13 16:45:24 +000043
Sanjay Patela92fa442014-10-22 15:29:23 +000044static cl::opt<bool>
45 EnableUnsafeFPShrink("enable-double-float-shrink", cl::Hidden,
46 cl::init(false),
47 cl::desc("Enable unsafe double to float "
48 "shrinking for math lib calls"));
49
50
Meador Ingedf796f82012-10-13 16:45:24 +000051//===----------------------------------------------------------------------===//
Meador Inged589ac62012-10-31 03:33:06 +000052// Helper Functions
53//===----------------------------------------------------------------------===//
54
Chris Bienemanad070d02014-09-17 20:55:46 +000055static bool ignoreCallingConv(LibFunc::Func Func) {
Davide Italianob883b012015-11-12 23:39:00 +000056 return Func == LibFunc::abs || Func == LibFunc::labs ||
57 Func == LibFunc::llabs || Func == LibFunc::strlen;
Chris Bienemanad070d02014-09-17 20:55:46 +000058}
59
Meador Inged589ac62012-10-31 03:33:06 +000060/// isOnlyUsedInZeroEqualityComparison - Return true if it only matters that the
61/// value is equal or not-equal to zero.
62static bool isOnlyUsedInZeroEqualityComparison(Value *V) {
Chandler Carruthcdf47882014-03-09 03:16:01 +000063 for (User *U : V->users()) {
64 if (ICmpInst *IC = dyn_cast<ICmpInst>(U))
Meador Inged589ac62012-10-31 03:33:06 +000065 if (IC->isEquality())
66 if (Constant *C = dyn_cast<Constant>(IC->getOperand(1)))
67 if (C->isNullValue())
68 continue;
69 // Unknown instruction.
70 return false;
71 }
72 return true;
73}
74
Meador Inge56edbc92012-11-11 03:51:48 +000075/// isOnlyUsedInEqualityComparison - Return true if it is only used in equality
76/// comparisons with With.
77static bool isOnlyUsedInEqualityComparison(Value *V, Value *With) {
Chandler Carruthcdf47882014-03-09 03:16:01 +000078 for (User *U : V->users()) {
79 if (ICmpInst *IC = dyn_cast<ICmpInst>(U))
Meador Inge56edbc92012-11-11 03:51:48 +000080 if (IC->isEquality() && IC->getOperand(1) == With)
81 continue;
82 // Unknown instruction.
83 return false;
84 }
85 return true;
86}
87
Meador Inge08ca1152012-11-26 20:37:20 +000088static bool callHasFloatingPointArgument(const CallInst *CI) {
Davide Italianoac0953a2015-11-27 08:05:40 +000089 for (const Use &OI : CI->operands())
90 if (OI->getType()->isFloatingPointTy())
Meador Inge08ca1152012-11-26 20:37:20 +000091 return true;
Meador Inge08ca1152012-11-26 20:37:20 +000092 return false;
93}
94
Benjamin Kramer2702caa2013-08-31 18:19:35 +000095/// \brief Check whether the overloaded unary floating point function
Sanjay Patele24c60e2015-08-12 20:36:18 +000096/// corresponding to \a Ty is available.
Benjamin Kramer2702caa2013-08-31 18:19:35 +000097static bool hasUnaryFloatFn(const TargetLibraryInfo *TLI, Type *Ty,
98 LibFunc::Func DoubleFn, LibFunc::Func FloatFn,
99 LibFunc::Func LongDoubleFn) {
100 switch (Ty->getTypeID()) {
101 case Type::FloatTyID:
102 return TLI->has(FloatFn);
103 case Type::DoubleTyID:
104 return TLI->has(DoubleFn);
105 default:
106 return TLI->has(LongDoubleFn);
107 }
108}
109
Davide Italianoa904e522015-10-29 02:58:44 +0000110/// \brief Check whether we can use unsafe floating point math for
111/// the function passed as input.
112static bool canUseUnsafeFPMath(Function *F) {
113
114 // FIXME: For finer-grain optimization, we need intrinsics to have the same
115 // fast-math flag decorations that are applied to FP instructions. For now,
116 // we have to rely on the function-level unsafe-fp-math attribute to do this
Davide Italianoed5cc952015-11-16 16:54:28 +0000117 // optimization because there's no other way to express that the call can be
118 // relaxed.
Davide Italianoa904e522015-10-29 02:58:44 +0000119 if (F->hasFnAttribute("unsafe-fp-math")) {
120 Attribute Attr = F->getFnAttribute("unsafe-fp-math");
121 if (Attr.getValueAsString() == "true")
122 return true;
123 }
124 return false;
125}
126
Ahmed Bougachab7d8afb2015-01-12 17:18:19 +0000127/// \brief Returns whether \p F matches the signature expected for the
128/// string/memory copying library function \p Func.
129/// Acceptable functions are st[rp][n]?cpy, memove, memcpy, and memset.
130/// Their fortified (_chk) counterparts are also accepted.
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000131static bool checkStringCopyLibFuncSignature(Function *F, LibFunc::Func Func) {
132 const DataLayout &DL = F->getParent()->getDataLayout();
Ahmed Bougachab7d8afb2015-01-12 17:18:19 +0000133 FunctionType *FT = F->getFunctionType();
134 LLVMContext &Context = F->getContext();
135 Type *PCharTy = Type::getInt8PtrTy(Context);
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000136 Type *SizeTTy = DL.getIntPtrType(Context);
Ahmed Bougachab7d8afb2015-01-12 17:18:19 +0000137 unsigned NumParams = FT->getNumParams();
138
139 // All string libfuncs return the same type as the first parameter.
140 if (FT->getReturnType() != FT->getParamType(0))
141 return false;
142
143 switch (Func) {
144 default:
145 llvm_unreachable("Can't check signature for non-string-copy libfunc.");
146 case LibFunc::stpncpy_chk:
147 case LibFunc::strncpy_chk:
148 --NumParams; // fallthrough
149 case LibFunc::stpncpy:
150 case LibFunc::strncpy: {
151 if (NumParams != 3 || FT->getParamType(0) != FT->getParamType(1) ||
152 FT->getParamType(0) != PCharTy || !FT->getParamType(2)->isIntegerTy())
153 return false;
154 break;
155 }
156 case LibFunc::strcpy_chk:
157 case LibFunc::stpcpy_chk:
158 --NumParams; // fallthrough
159 case LibFunc::stpcpy:
160 case LibFunc::strcpy: {
161 if (NumParams != 2 || FT->getParamType(0) != FT->getParamType(1) ||
162 FT->getParamType(0) != PCharTy)
163 return false;
164 break;
165 }
166 case LibFunc::memmove_chk:
167 case LibFunc::memcpy_chk:
168 --NumParams; // fallthrough
169 case LibFunc::memmove:
170 case LibFunc::memcpy: {
171 if (NumParams != 3 || !FT->getParamType(0)->isPointerTy() ||
172 !FT->getParamType(1)->isPointerTy() || FT->getParamType(2) != SizeTTy)
173 return false;
174 break;
175 }
176 case LibFunc::memset_chk:
177 --NumParams; // fallthrough
178 case LibFunc::memset: {
179 if (NumParams != 3 || !FT->getParamType(0)->isPointerTy() ||
180 !FT->getParamType(1)->isIntegerTy() || FT->getParamType(2) != SizeTTy)
181 return false;
182 break;
183 }
184 }
185 // If this is a fortified libcall, the last parameter is a size_t.
186 if (NumParams == FT->getNumParams() - 1)
187 return FT->getParamType(FT->getNumParams() - 1) == SizeTTy;
188 return true;
189}
190
Meador Inged589ac62012-10-31 03:33:06 +0000191//===----------------------------------------------------------------------===//
Meador Inge7fb2f732012-10-13 16:45:32 +0000192// String and Memory Library Call Optimizations
193//===----------------------------------------------------------------------===//
194
Chris Bienemanad070d02014-09-17 20:55:46 +0000195Value *LibCallSimplifier::optimizeStrCat(CallInst *CI, IRBuilder<> &B) {
196 Function *Callee = CI->getCalledFunction();
197 // Verify the "strcat" function prototype.
198 FunctionType *FT = Callee->getFunctionType();
199 if (FT->getNumParams() != 2||
200 FT->getReturnType() != B.getInt8PtrTy() ||
201 FT->getParamType(0) != FT->getReturnType() ||
202 FT->getParamType(1) != FT->getReturnType())
203 return nullptr;
204
205 // Extract some information from the instruction
206 Value *Dst = CI->getArgOperand(0);
207 Value *Src = CI->getArgOperand(1);
208
209 // See if we can get the length of the input string.
210 uint64_t Len = GetStringLength(Src);
211 if (Len == 0)
212 return nullptr;
213 --Len; // Unbias length.
214
215 // Handle the simple, do-nothing case: strcat(x, "") -> x
216 if (Len == 0)
217 return Dst;
218
Chris Bienemanad070d02014-09-17 20:55:46 +0000219 return emitStrLenMemCpy(Src, Dst, Len, B);
220}
221
222Value *LibCallSimplifier::emitStrLenMemCpy(Value *Src, Value *Dst, uint64_t Len,
223 IRBuilder<> &B) {
224 // We need to find the end of the destination string. That's where the
225 // memory is to be moved to. We just generate a call to strlen.
226 Value *DstLen = EmitStrLen(Dst, B, DL, TLI);
227 if (!DstLen)
228 return nullptr;
229
230 // Now that we have the destination's length, we must index into the
231 // destination's pointer to get the actual memcpy destination (end of
232 // the string .. we're concatenating).
David Blaikie3909da72015-03-30 20:42:56 +0000233 Value *CpyDst = B.CreateGEP(B.getInt8Ty(), Dst, DstLen, "endptr");
Chris Bienemanad070d02014-09-17 20:55:46 +0000234
235 // We have enough information to now generate the memcpy call to do the
236 // concatenation for us. Make a memcpy to copy the nul byte with align = 1.
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000237 B.CreateMemCpy(CpyDst, Src,
238 ConstantInt::get(DL.getIntPtrType(Src->getContext()), Len + 1),
Pete Cooper67cf9a72015-11-19 05:56:52 +0000239 1);
Chris Bienemanad070d02014-09-17 20:55:46 +0000240 return Dst;
241}
242
243Value *LibCallSimplifier::optimizeStrNCat(CallInst *CI, IRBuilder<> &B) {
244 Function *Callee = CI->getCalledFunction();
245 // Verify the "strncat" function prototype.
246 FunctionType *FT = Callee->getFunctionType();
247 if (FT->getNumParams() != 3 || FT->getReturnType() != B.getInt8PtrTy() ||
248 FT->getParamType(0) != FT->getReturnType() ||
249 FT->getParamType(1) != FT->getReturnType() ||
250 !FT->getParamType(2)->isIntegerTy())
251 return nullptr;
252
253 // Extract some information from the instruction
254 Value *Dst = CI->getArgOperand(0);
255 Value *Src = CI->getArgOperand(1);
256 uint64_t Len;
257
258 // We don't do anything if length is not constant
259 if (ConstantInt *LengthArg = dyn_cast<ConstantInt>(CI->getArgOperand(2)))
260 Len = LengthArg->getZExtValue();
261 else
262 return nullptr;
263
264 // See if we can get the length of the input string.
265 uint64_t SrcLen = GetStringLength(Src);
266 if (SrcLen == 0)
267 return nullptr;
268 --SrcLen; // Unbias length.
269
270 // Handle the simple, do-nothing cases:
271 // strncat(x, "", c) -> x
272 // strncat(x, c, 0) -> x
273 if (SrcLen == 0 || Len == 0)
274 return Dst;
275
Chris Bienemanad070d02014-09-17 20:55:46 +0000276 // We don't optimize this case
277 if (Len < SrcLen)
278 return nullptr;
279
280 // strncat(x, s, c) -> strcat(x, s)
281 // s is constant so the strcat can be optimized further
282 return emitStrLenMemCpy(Src, Dst, SrcLen, B);
283}
284
285Value *LibCallSimplifier::optimizeStrChr(CallInst *CI, IRBuilder<> &B) {
286 Function *Callee = CI->getCalledFunction();
287 // Verify the "strchr" function prototype.
288 FunctionType *FT = Callee->getFunctionType();
289 if (FT->getNumParams() != 2 || FT->getReturnType() != B.getInt8PtrTy() ||
290 FT->getParamType(0) != FT->getReturnType() ||
291 !FT->getParamType(1)->isIntegerTy(32))
292 return nullptr;
293
294 Value *SrcStr = CI->getArgOperand(0);
295
296 // If the second operand is non-constant, see if we can compute the length
297 // of the input string and turn this into memchr.
298 ConstantInt *CharC = dyn_cast<ConstantInt>(CI->getArgOperand(1));
299 if (!CharC) {
Chris Bienemanad070d02014-09-17 20:55:46 +0000300 uint64_t Len = GetStringLength(SrcStr);
301 if (Len == 0 || !FT->getParamType(1)->isIntegerTy(32)) // memchr needs i32.
302 return nullptr;
Meador Inge7fb2f732012-10-13 16:45:32 +0000303
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000304 return EmitMemChr(SrcStr, CI->getArgOperand(1), // include nul.
305 ConstantInt::get(DL.getIntPtrType(CI->getContext()), Len),
306 B, DL, TLI);
Meador Inge7fb2f732012-10-13 16:45:32 +0000307 }
308
Chris Bienemanad070d02014-09-17 20:55:46 +0000309 // Otherwise, the character is a constant, see if the first argument is
310 // a string literal. If so, we can constant fold.
311 StringRef Str;
312 if (!getConstantStringInfo(SrcStr, Str)) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000313 if (CharC->isZero()) // strchr(p, 0) -> p + strlen(p)
David Blaikie3909da72015-03-30 20:42:56 +0000314 return B.CreateGEP(B.getInt8Ty(), SrcStr, EmitStrLen(SrcStr, B, DL, TLI), "strchr");
Chris Bienemanad070d02014-09-17 20:55:46 +0000315 return nullptr;
316 }
317
318 // Compute the offset, make sure to handle the case when we're searching for
319 // zero (a weird way to spell strlen).
320 size_t I = (0xFF & CharC->getSExtValue()) == 0
321 ? Str.size()
322 : Str.find(CharC->getSExtValue());
323 if (I == StringRef::npos) // Didn't find the char. strchr returns null.
324 return Constant::getNullValue(CI->getType());
325
326 // strchr(s+n,c) -> gep(s+n+i,c)
David Blaikie3909da72015-03-30 20:42:56 +0000327 return B.CreateGEP(B.getInt8Ty(), SrcStr, B.getInt64(I), "strchr");
Chris Bienemanad070d02014-09-17 20:55:46 +0000328}
329
330Value *LibCallSimplifier::optimizeStrRChr(CallInst *CI, IRBuilder<> &B) {
331 Function *Callee = CI->getCalledFunction();
332 // Verify the "strrchr" function prototype.
333 FunctionType *FT = Callee->getFunctionType();
334 if (FT->getNumParams() != 2 || FT->getReturnType() != B.getInt8PtrTy() ||
335 FT->getParamType(0) != FT->getReturnType() ||
336 !FT->getParamType(1)->isIntegerTy(32))
337 return nullptr;
338
339 Value *SrcStr = CI->getArgOperand(0);
340 ConstantInt *CharC = dyn_cast<ConstantInt>(CI->getArgOperand(1));
341
342 // Cannot fold anything if we're not looking for a constant.
343 if (!CharC)
344 return nullptr;
345
346 StringRef Str;
347 if (!getConstantStringInfo(SrcStr, Str)) {
348 // strrchr(s, 0) -> strchr(s, 0)
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000349 if (CharC->isZero())
350 return EmitStrChr(SrcStr, '\0', B, TLI);
Chris Bienemanad070d02014-09-17 20:55:46 +0000351 return nullptr;
352 }
353
354 // Compute the offset.
355 size_t I = (0xFF & CharC->getSExtValue()) == 0
356 ? Str.size()
357 : Str.rfind(CharC->getSExtValue());
358 if (I == StringRef::npos) // Didn't find the char. Return null.
359 return Constant::getNullValue(CI->getType());
360
361 // strrchr(s+n,c) -> gep(s+n+i,c)
David Blaikie3909da72015-03-30 20:42:56 +0000362 return B.CreateGEP(B.getInt8Ty(), SrcStr, B.getInt64(I), "strrchr");
Chris Bienemanad070d02014-09-17 20:55:46 +0000363}
364
365Value *LibCallSimplifier::optimizeStrCmp(CallInst *CI, IRBuilder<> &B) {
366 Function *Callee = CI->getCalledFunction();
367 // Verify the "strcmp" function prototype.
368 FunctionType *FT = Callee->getFunctionType();
369 if (FT->getNumParams() != 2 || !FT->getReturnType()->isIntegerTy(32) ||
370 FT->getParamType(0) != FT->getParamType(1) ||
371 FT->getParamType(0) != B.getInt8PtrTy())
372 return nullptr;
373
374 Value *Str1P = CI->getArgOperand(0), *Str2P = CI->getArgOperand(1);
375 if (Str1P == Str2P) // strcmp(x,x) -> 0
376 return ConstantInt::get(CI->getType(), 0);
377
378 StringRef Str1, Str2;
379 bool HasStr1 = getConstantStringInfo(Str1P, Str1);
380 bool HasStr2 = getConstantStringInfo(Str2P, Str2);
381
382 // strcmp(x, y) -> cnst (if both x and y are constant strings)
383 if (HasStr1 && HasStr2)
384 return ConstantInt::get(CI->getType(), Str1.compare(Str2));
385
386 if (HasStr1 && Str1.empty()) // strcmp("", x) -> -*x
387 return B.CreateNeg(
388 B.CreateZExt(B.CreateLoad(Str2P, "strcmpload"), CI->getType()));
389
390 if (HasStr2 && Str2.empty()) // strcmp(x,"") -> *x
391 return B.CreateZExt(B.CreateLoad(Str1P, "strcmpload"), CI->getType());
392
393 // strcmp(P, "x") -> memcmp(P, "x", 2)
394 uint64_t Len1 = GetStringLength(Str1P);
395 uint64_t Len2 = GetStringLength(Str2P);
396 if (Len1 && Len2) {
Chris Bienemanad070d02014-09-17 20:55:46 +0000397 return EmitMemCmp(Str1P, Str2P,
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000398 ConstantInt::get(DL.getIntPtrType(CI->getContext()),
Chris Bienemanad070d02014-09-17 20:55:46 +0000399 std::min(Len1, Len2)),
400 B, DL, TLI);
401 }
Meador Inge7fb2f732012-10-13 16:45:32 +0000402
Chris Bienemanad070d02014-09-17 20:55:46 +0000403 return nullptr;
404}
405
406Value *LibCallSimplifier::optimizeStrNCmp(CallInst *CI, IRBuilder<> &B) {
407 Function *Callee = CI->getCalledFunction();
408 // Verify the "strncmp" function prototype.
409 FunctionType *FT = Callee->getFunctionType();
410 if (FT->getNumParams() != 3 || !FT->getReturnType()->isIntegerTy(32) ||
411 FT->getParamType(0) != FT->getParamType(1) ||
412 FT->getParamType(0) != B.getInt8PtrTy() ||
413 !FT->getParamType(2)->isIntegerTy())
414 return nullptr;
415
416 Value *Str1P = CI->getArgOperand(0), *Str2P = CI->getArgOperand(1);
417 if (Str1P == Str2P) // strncmp(x,x,n) -> 0
418 return ConstantInt::get(CI->getType(), 0);
419
420 // Get the length argument if it is constant.
421 uint64_t Length;
422 if (ConstantInt *LengthArg = dyn_cast<ConstantInt>(CI->getArgOperand(2)))
423 Length = LengthArg->getZExtValue();
424 else
425 return nullptr;
426
427 if (Length == 0) // strncmp(x,y,0) -> 0
428 return ConstantInt::get(CI->getType(), 0);
429
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000430 if (Length == 1) // strncmp(x,y,1) -> memcmp(x,y,1)
Chris Bienemanad070d02014-09-17 20:55:46 +0000431 return EmitMemCmp(Str1P, Str2P, CI->getArgOperand(2), B, DL, TLI);
432
433 StringRef Str1, Str2;
434 bool HasStr1 = getConstantStringInfo(Str1P, Str1);
435 bool HasStr2 = getConstantStringInfo(Str2P, Str2);
436
437 // strncmp(x, y) -> cnst (if both x and y are constant strings)
438 if (HasStr1 && HasStr2) {
439 StringRef SubStr1 = Str1.substr(0, Length);
440 StringRef SubStr2 = Str2.substr(0, Length);
441 return ConstantInt::get(CI->getType(), SubStr1.compare(SubStr2));
442 }
443
444 if (HasStr1 && Str1.empty()) // strncmp("", x, n) -> -*x
445 return B.CreateNeg(
446 B.CreateZExt(B.CreateLoad(Str2P, "strcmpload"), CI->getType()));
447
448 if (HasStr2 && Str2.empty()) // strncmp(x, "", n) -> *x
449 return B.CreateZExt(B.CreateLoad(Str1P, "strcmpload"), CI->getType());
450
451 return nullptr;
452}
453
454Value *LibCallSimplifier::optimizeStrCpy(CallInst *CI, IRBuilder<> &B) {
455 Function *Callee = CI->getCalledFunction();
Ahmed Bougachab7d8afb2015-01-12 17:18:19 +0000456
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000457 if (!checkStringCopyLibFuncSignature(Callee, LibFunc::strcpy))
Chris Bienemanad070d02014-09-17 20:55:46 +0000458 return nullptr;
459
460 Value *Dst = CI->getArgOperand(0), *Src = CI->getArgOperand(1);
461 if (Dst == Src) // strcpy(x,x) -> x
462 return Src;
463
Chris Bienemanad070d02014-09-17 20:55:46 +0000464 // See if we can get the length of the input string.
465 uint64_t Len = GetStringLength(Src);
466 if (Len == 0)
467 return nullptr;
468
469 // We have enough information to now generate the memcpy call to do the
470 // copy for us. Make a memcpy to copy the nul byte with align = 1.
471 B.CreateMemCpy(Dst, Src,
Pete Cooper67cf9a72015-11-19 05:56:52 +0000472 ConstantInt::get(DL.getIntPtrType(CI->getContext()), Len), 1);
Chris Bienemanad070d02014-09-17 20:55:46 +0000473 return Dst;
474}
475
476Value *LibCallSimplifier::optimizeStpCpy(CallInst *CI, IRBuilder<> &B) {
477 Function *Callee = CI->getCalledFunction();
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000478 if (!checkStringCopyLibFuncSignature(Callee, LibFunc::stpcpy))
Chris Bienemanad070d02014-09-17 20:55:46 +0000479 return nullptr;
480
481 Value *Dst = CI->getArgOperand(0), *Src = CI->getArgOperand(1);
482 if (Dst == Src) { // stpcpy(x,x) -> x+strlen(x)
483 Value *StrLen = EmitStrLen(Src, B, DL, TLI);
David Blaikieaa41cd52015-04-03 21:33:42 +0000484 return StrLen ? B.CreateInBoundsGEP(B.getInt8Ty(), Dst, StrLen) : nullptr;
Chris Bienemanad070d02014-09-17 20:55:46 +0000485 }
486
487 // See if we can get the length of the input string.
488 uint64_t Len = GetStringLength(Src);
489 if (Len == 0)
490 return nullptr;
491
Davide Italianob7487e62015-11-02 23:07:14 +0000492 Type *PT = Callee->getFunctionType()->getParamType(0);
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000493 Value *LenV = ConstantInt::get(DL.getIntPtrType(PT), Len);
Chris Bienemanad070d02014-09-17 20:55:46 +0000494 Value *DstEnd =
David Blaikie3909da72015-03-30 20:42:56 +0000495 B.CreateGEP(B.getInt8Ty(), Dst, ConstantInt::get(DL.getIntPtrType(PT), Len - 1));
Chris Bienemanad070d02014-09-17 20:55:46 +0000496
497 // We have enough information to now generate the memcpy call to do the
498 // copy for us. Make a memcpy to copy the nul byte with align = 1.
Pete Cooper67cf9a72015-11-19 05:56:52 +0000499 B.CreateMemCpy(Dst, Src, LenV, 1);
Chris Bienemanad070d02014-09-17 20:55:46 +0000500 return DstEnd;
501}
502
503Value *LibCallSimplifier::optimizeStrNCpy(CallInst *CI, IRBuilder<> &B) {
504 Function *Callee = CI->getCalledFunction();
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000505 if (!checkStringCopyLibFuncSignature(Callee, LibFunc::strncpy))
Chris Bienemanad070d02014-09-17 20:55:46 +0000506 return nullptr;
507
508 Value *Dst = CI->getArgOperand(0);
509 Value *Src = CI->getArgOperand(1);
510 Value *LenOp = CI->getArgOperand(2);
511
512 // See if we can get the length of the input string.
513 uint64_t SrcLen = GetStringLength(Src);
514 if (SrcLen == 0)
515 return nullptr;
516 --SrcLen;
517
518 if (SrcLen == 0) {
519 // strncpy(x, "", y) -> memset(x, '\0', y, 1)
520 B.CreateMemSet(Dst, B.getInt8('\0'), LenOp, 1);
Meador Inge7fb2f732012-10-13 16:45:32 +0000521 return Dst;
522 }
Meador Inge7fb2f732012-10-13 16:45:32 +0000523
Chris Bienemanad070d02014-09-17 20:55:46 +0000524 uint64_t Len;
525 if (ConstantInt *LengthArg = dyn_cast<ConstantInt>(LenOp))
526 Len = LengthArg->getZExtValue();
527 else
528 return nullptr;
Meador Inge7fb2f732012-10-13 16:45:32 +0000529
Chris Bienemanad070d02014-09-17 20:55:46 +0000530 if (Len == 0)
531 return Dst; // strncpy(x, y, 0) -> x
Meador Inge7fb2f732012-10-13 16:45:32 +0000532
Chris Bienemanad070d02014-09-17 20:55:46 +0000533 // Let strncpy handle the zero padding
534 if (Len > SrcLen + 1)
535 return nullptr;
Meador Inge7fb2f732012-10-13 16:45:32 +0000536
Davide Italianob7487e62015-11-02 23:07:14 +0000537 Type *PT = Callee->getFunctionType()->getParamType(0);
Chris Bienemanad070d02014-09-17 20:55:46 +0000538 // strncpy(x, s, c) -> memcpy(x, s, c, 1) [s and c are constant]
Pete Cooper67cf9a72015-11-19 05:56:52 +0000539 B.CreateMemCpy(Dst, Src, ConstantInt::get(DL.getIntPtrType(PT), Len), 1);
Meador Inge7fb2f732012-10-13 16:45:32 +0000540
Chris Bienemanad070d02014-09-17 20:55:46 +0000541 return Dst;
542}
Meador Inge7fb2f732012-10-13 16:45:32 +0000543
Chris Bienemanad070d02014-09-17 20:55:46 +0000544Value *LibCallSimplifier::optimizeStrLen(CallInst *CI, IRBuilder<> &B) {
545 Function *Callee = CI->getCalledFunction();
546 FunctionType *FT = Callee->getFunctionType();
547 if (FT->getNumParams() != 1 || FT->getParamType(0) != B.getInt8PtrTy() ||
548 !FT->getReturnType()->isIntegerTy())
549 return nullptr;
Meador Inge7fb2f732012-10-13 16:45:32 +0000550
Chris Bienemanad070d02014-09-17 20:55:46 +0000551 Value *Src = CI->getArgOperand(0);
552
553 // Constant folding: strlen("xyz") -> 3
554 if (uint64_t Len = GetStringLength(Src))
555 return ConstantInt::get(CI->getType(), Len - 1);
556
557 // strlen(x?"foo":"bars") --> x ? 3 : 4
558 if (SelectInst *SI = dyn_cast<SelectInst>(Src)) {
559 uint64_t LenTrue = GetStringLength(SI->getTrueValue());
560 uint64_t LenFalse = GetStringLength(SI->getFalseValue());
561 if (LenTrue && LenFalse) {
562 Function *Caller = CI->getParent()->getParent();
563 emitOptimizationRemark(CI->getContext(), "simplify-libcalls", *Caller,
564 SI->getDebugLoc(),
565 "folded strlen(select) to select of constants");
566 return B.CreateSelect(SI->getCondition(),
567 ConstantInt::get(CI->getType(), LenTrue - 1),
568 ConstantInt::get(CI->getType(), LenFalse - 1));
569 }
Meador Inge7fb2f732012-10-13 16:45:32 +0000570 }
Meador Inge7fb2f732012-10-13 16:45:32 +0000571
Chris Bienemanad070d02014-09-17 20:55:46 +0000572 // strlen(x) != 0 --> *x != 0
573 // strlen(x) == 0 --> *x == 0
574 if (isOnlyUsedInZeroEqualityComparison(CI))
575 return B.CreateZExt(B.CreateLoad(Src, "strlenfirst"), CI->getType());
Meador Inge17418502012-10-13 16:45:37 +0000576
Chris Bienemanad070d02014-09-17 20:55:46 +0000577 return nullptr;
578}
Meador Inge17418502012-10-13 16:45:37 +0000579
Chris Bienemanad070d02014-09-17 20:55:46 +0000580Value *LibCallSimplifier::optimizeStrPBrk(CallInst *CI, IRBuilder<> &B) {
581 Function *Callee = CI->getCalledFunction();
582 FunctionType *FT = Callee->getFunctionType();
583 if (FT->getNumParams() != 2 || FT->getParamType(0) != B.getInt8PtrTy() ||
584 FT->getParamType(1) != FT->getParamType(0) ||
585 FT->getReturnType() != FT->getParamType(0))
586 return nullptr;
Meador Inge17418502012-10-13 16:45:37 +0000587
Chris Bienemanad070d02014-09-17 20:55:46 +0000588 StringRef S1, S2;
589 bool HasS1 = getConstantStringInfo(CI->getArgOperand(0), S1);
590 bool HasS2 = getConstantStringInfo(CI->getArgOperand(1), S2);
Meador Inge17418502012-10-13 16:45:37 +0000591
Reid Kleckner971c3ea2014-11-13 22:55:19 +0000592 // strpbrk(s, "") -> nullptr
593 // strpbrk("", s) -> nullptr
Chris Bienemanad070d02014-09-17 20:55:46 +0000594 if ((HasS1 && S1.empty()) || (HasS2 && S2.empty()))
595 return Constant::getNullValue(CI->getType());
Meador Inge17418502012-10-13 16:45:37 +0000596
Chris Bienemanad070d02014-09-17 20:55:46 +0000597 // Constant folding.
598 if (HasS1 && HasS2) {
599 size_t I = S1.find_first_of(S2);
600 if (I == StringRef::npos) // No match.
Meador Inge17418502012-10-13 16:45:37 +0000601 return Constant::getNullValue(CI->getType());
602
David Blaikie3909da72015-03-30 20:42:56 +0000603 return B.CreateGEP(B.getInt8Ty(), CI->getArgOperand(0), B.getInt64(I), "strpbrk");
Meador Inge17418502012-10-13 16:45:37 +0000604 }
Meador Inge17418502012-10-13 16:45:37 +0000605
Chris Bienemanad070d02014-09-17 20:55:46 +0000606 // strpbrk(s, "a") -> strchr(s, 'a')
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000607 if (HasS2 && S2.size() == 1)
608 return EmitStrChr(CI->getArgOperand(0), S2[0], B, TLI);
Chris Bienemanad070d02014-09-17 20:55:46 +0000609
610 return nullptr;
611}
612
613Value *LibCallSimplifier::optimizeStrTo(CallInst *CI, IRBuilder<> &B) {
614 Function *Callee = CI->getCalledFunction();
615 FunctionType *FT = Callee->getFunctionType();
616 if ((FT->getNumParams() != 2 && FT->getNumParams() != 3) ||
617 !FT->getParamType(0)->isPointerTy() ||
618 !FT->getParamType(1)->isPointerTy())
619 return nullptr;
620
621 Value *EndPtr = CI->getArgOperand(1);
622 if (isa<ConstantPointerNull>(EndPtr)) {
623 // With a null EndPtr, this function won't capture the main argument.
624 // It would be readonly too, except that it still may write to errno.
625 CI->addAttribute(1, Attribute::NoCapture);
626 }
627
628 return nullptr;
629}
630
631Value *LibCallSimplifier::optimizeStrSpn(CallInst *CI, IRBuilder<> &B) {
632 Function *Callee = CI->getCalledFunction();
633 FunctionType *FT = Callee->getFunctionType();
634 if (FT->getNumParams() != 2 || FT->getParamType(0) != B.getInt8PtrTy() ||
635 FT->getParamType(1) != FT->getParamType(0) ||
636 !FT->getReturnType()->isIntegerTy())
637 return nullptr;
638
639 StringRef S1, S2;
640 bool HasS1 = getConstantStringInfo(CI->getArgOperand(0), S1);
641 bool HasS2 = getConstantStringInfo(CI->getArgOperand(1), S2);
642
643 // strspn(s, "") -> 0
644 // strspn("", s) -> 0
645 if ((HasS1 && S1.empty()) || (HasS2 && S2.empty()))
646 return Constant::getNullValue(CI->getType());
647
648 // Constant folding.
649 if (HasS1 && HasS2) {
650 size_t Pos = S1.find_first_not_of(S2);
651 if (Pos == StringRef::npos)
652 Pos = S1.size();
653 return ConstantInt::get(CI->getType(), Pos);
654 }
655
656 return nullptr;
657}
658
659Value *LibCallSimplifier::optimizeStrCSpn(CallInst *CI, IRBuilder<> &B) {
660 Function *Callee = CI->getCalledFunction();
661 FunctionType *FT = Callee->getFunctionType();
662 if (FT->getNumParams() != 2 || FT->getParamType(0) != B.getInt8PtrTy() ||
663 FT->getParamType(1) != FT->getParamType(0) ||
664 !FT->getReturnType()->isIntegerTy())
665 return nullptr;
666
667 StringRef S1, S2;
668 bool HasS1 = getConstantStringInfo(CI->getArgOperand(0), S1);
669 bool HasS2 = getConstantStringInfo(CI->getArgOperand(1), S2);
670
671 // strcspn("", s) -> 0
672 if (HasS1 && S1.empty())
673 return Constant::getNullValue(CI->getType());
674
675 // Constant folding.
676 if (HasS1 && HasS2) {
677 size_t Pos = S1.find_first_of(S2);
678 if (Pos == StringRef::npos)
679 Pos = S1.size();
680 return ConstantInt::get(CI->getType(), Pos);
681 }
682
683 // strcspn(s, "") -> strlen(s)
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000684 if (HasS2 && S2.empty())
Chris Bienemanad070d02014-09-17 20:55:46 +0000685 return EmitStrLen(CI->getArgOperand(0), B, DL, TLI);
686
687 return nullptr;
688}
689
690Value *LibCallSimplifier::optimizeStrStr(CallInst *CI, IRBuilder<> &B) {
691 Function *Callee = CI->getCalledFunction();
692 FunctionType *FT = Callee->getFunctionType();
693 if (FT->getNumParams() != 2 || !FT->getParamType(0)->isPointerTy() ||
694 !FT->getParamType(1)->isPointerTy() ||
695 !FT->getReturnType()->isPointerTy())
696 return nullptr;
697
698 // fold strstr(x, x) -> x.
699 if (CI->getArgOperand(0) == CI->getArgOperand(1))
700 return B.CreateBitCast(CI->getArgOperand(0), CI->getType());
701
702 // fold strstr(a, b) == a -> strncmp(a, b, strlen(b)) == 0
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000703 if (isOnlyUsedInEqualityComparison(CI, CI->getArgOperand(0))) {
Chris Bienemanad070d02014-09-17 20:55:46 +0000704 Value *StrLen = EmitStrLen(CI->getArgOperand(1), B, DL, TLI);
705 if (!StrLen)
Craig Topperf40110f2014-04-25 05:29:35 +0000706 return nullptr;
Chris Bienemanad070d02014-09-17 20:55:46 +0000707 Value *StrNCmp = EmitStrNCmp(CI->getArgOperand(0), CI->getArgOperand(1),
708 StrLen, B, DL, TLI);
709 if (!StrNCmp)
Craig Topperf40110f2014-04-25 05:29:35 +0000710 return nullptr;
Chris Bienemanad070d02014-09-17 20:55:46 +0000711 for (auto UI = CI->user_begin(), UE = CI->user_end(); UI != UE;) {
712 ICmpInst *Old = cast<ICmpInst>(*UI++);
713 Value *Cmp =
714 B.CreateICmp(Old->getPredicate(), StrNCmp,
715 ConstantInt::getNullValue(StrNCmp->getType()), "cmp");
716 replaceAllUsesWith(Old, Cmp);
Meador Inge17418502012-10-13 16:45:37 +0000717 }
Chris Bienemanad070d02014-09-17 20:55:46 +0000718 return CI;
719 }
Meador Inge17418502012-10-13 16:45:37 +0000720
Chris Bienemanad070d02014-09-17 20:55:46 +0000721 // See if either input string is a constant string.
722 StringRef SearchStr, ToFindStr;
723 bool HasStr1 = getConstantStringInfo(CI->getArgOperand(0), SearchStr);
724 bool HasStr2 = getConstantStringInfo(CI->getArgOperand(1), ToFindStr);
725
726 // fold strstr(x, "") -> x.
727 if (HasStr2 && ToFindStr.empty())
728 return B.CreateBitCast(CI->getArgOperand(0), CI->getType());
729
730 // If both strings are known, constant fold it.
731 if (HasStr1 && HasStr2) {
732 size_t Offset = SearchStr.find(ToFindStr);
733
734 if (Offset == StringRef::npos) // strstr("foo", "bar") -> null
Meador Inge17418502012-10-13 16:45:37 +0000735 return Constant::getNullValue(CI->getType());
736
Chris Bienemanad070d02014-09-17 20:55:46 +0000737 // strstr("abcd", "bc") -> gep((char*)"abcd", 1)
738 Value *Result = CastToCStr(CI->getArgOperand(0), B);
739 Result = B.CreateConstInBoundsGEP1_64(Result, Offset, "strstr");
740 return B.CreateBitCast(Result, CI->getType());
Meador Inge17418502012-10-13 16:45:37 +0000741 }
Meador Inge17418502012-10-13 16:45:37 +0000742
Chris Bienemanad070d02014-09-17 20:55:46 +0000743 // fold strstr(x, "y") -> strchr(x, 'y').
744 if (HasStr2 && ToFindStr.size() == 1) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000745 Value *StrChr = EmitStrChr(CI->getArgOperand(0), ToFindStr[0], B, TLI);
Chris Bienemanad070d02014-09-17 20:55:46 +0000746 return StrChr ? B.CreateBitCast(StrChr, CI->getType()) : nullptr;
747 }
748 return nullptr;
749}
Meador Inge40b6fac2012-10-15 03:47:37 +0000750
Benjamin Kramer691363e2015-03-21 15:36:21 +0000751Value *LibCallSimplifier::optimizeMemChr(CallInst *CI, IRBuilder<> &B) {
752 Function *Callee = CI->getCalledFunction();
753 FunctionType *FT = Callee->getFunctionType();
754 if (FT->getNumParams() != 3 || !FT->getParamType(0)->isPointerTy() ||
755 !FT->getParamType(1)->isIntegerTy(32) ||
756 !FT->getParamType(2)->isIntegerTy() ||
757 !FT->getReturnType()->isPointerTy())
758 return nullptr;
759
760 Value *SrcStr = CI->getArgOperand(0);
761 ConstantInt *CharC = dyn_cast<ConstantInt>(CI->getArgOperand(1));
762 ConstantInt *LenC = dyn_cast<ConstantInt>(CI->getArgOperand(2));
763
764 // memchr(x, y, 0) -> null
765 if (LenC && LenC->isNullValue())
766 return Constant::getNullValue(CI->getType());
767
Benjamin Kramer7857d722015-03-21 21:09:33 +0000768 // From now on we need at least constant length and string.
Benjamin Kramer691363e2015-03-21 15:36:21 +0000769 StringRef Str;
Benjamin Kramer7857d722015-03-21 21:09:33 +0000770 if (!LenC || !getConstantStringInfo(SrcStr, Str, 0, /*TrimAtNul=*/false))
Benjamin Kramer691363e2015-03-21 15:36:21 +0000771 return nullptr;
772
773 // Truncate the string to LenC. If Str is smaller than LenC we will still only
774 // scan the string, as reading past the end of it is undefined and we can just
775 // return null if we don't find the char.
776 Str = Str.substr(0, LenC->getZExtValue());
777
Benjamin Kramer7857d722015-03-21 21:09:33 +0000778 // If the char is variable but the input str and length are not we can turn
779 // this memchr call into a simple bit field test. Of course this only works
780 // when the return value is only checked against null.
781 //
782 // It would be really nice to reuse switch lowering here but we can't change
783 // the CFG at this point.
784 //
785 // memchr("\r\n", C, 2) != nullptr -> (C & ((1 << '\r') | (1 << '\n'))) != 0
786 // after bounds check.
787 if (!CharC && !Str.empty() && isOnlyUsedInZeroEqualityComparison(CI)) {
Benjamin Kramerd6aa0ec2015-03-21 22:04:26 +0000788 unsigned char Max =
789 *std::max_element(reinterpret_cast<const unsigned char *>(Str.begin()),
790 reinterpret_cast<const unsigned char *>(Str.end()));
Benjamin Kramer7857d722015-03-21 21:09:33 +0000791
792 // Make sure the bit field we're about to create fits in a register on the
793 // target.
794 // FIXME: On a 64 bit architecture this prevents us from using the
795 // interesting range of alpha ascii chars. We could do better by emitting
796 // two bitfields or shifting the range by 64 if no lower chars are used.
797 if (!DL.fitsInLegalInteger(Max + 1))
798 return nullptr;
799
800 // For the bit field use a power-of-2 type with at least 8 bits to avoid
801 // creating unnecessary illegal types.
802 unsigned char Width = NextPowerOf2(std::max((unsigned char)7, Max));
803
804 // Now build the bit field.
805 APInt Bitfield(Width, 0);
806 for (char C : Str)
807 Bitfield.setBit((unsigned char)C);
808 Value *BitfieldC = B.getInt(Bitfield);
809
810 // First check that the bit field access is within bounds.
811 Value *C = B.CreateZExtOrTrunc(CI->getArgOperand(1), BitfieldC->getType());
812 Value *Bounds = B.CreateICmp(ICmpInst::ICMP_ULT, C, B.getIntN(Width, Width),
813 "memchr.bounds");
814
815 // Create code that checks if the given bit is set in the field.
816 Value *Shl = B.CreateShl(B.getIntN(Width, 1ULL), C);
817 Value *Bits = B.CreateIsNotNull(B.CreateAnd(Shl, BitfieldC), "memchr.bits");
818
819 // Finally merge both checks and cast to pointer type. The inttoptr
820 // implicitly zexts the i1 to intptr type.
821 return B.CreateIntToPtr(B.CreateAnd(Bounds, Bits, "memchr"), CI->getType());
822 }
823
824 // Check if all arguments are constants. If so, we can constant fold.
825 if (!CharC)
826 return nullptr;
827
Benjamin Kramer691363e2015-03-21 15:36:21 +0000828 // Compute the offset.
829 size_t I = Str.find(CharC->getSExtValue() & 0xFF);
830 if (I == StringRef::npos) // Didn't find the char. memchr returns null.
831 return Constant::getNullValue(CI->getType());
832
833 // memchr(s+n,c,l) -> gep(s+n+i,c)
David Blaikie3909da72015-03-30 20:42:56 +0000834 return B.CreateGEP(B.getInt8Ty(), SrcStr, B.getInt64(I), "memchr");
Benjamin Kramer691363e2015-03-21 15:36:21 +0000835}
836
Chris Bienemanad070d02014-09-17 20:55:46 +0000837Value *LibCallSimplifier::optimizeMemCmp(CallInst *CI, IRBuilder<> &B) {
838 Function *Callee = CI->getCalledFunction();
839 FunctionType *FT = Callee->getFunctionType();
840 if (FT->getNumParams() != 3 || !FT->getParamType(0)->isPointerTy() ||
841 !FT->getParamType(1)->isPointerTy() ||
842 !FT->getReturnType()->isIntegerTy(32))
Craig Topperf40110f2014-04-25 05:29:35 +0000843 return nullptr;
Meador Inge40b6fac2012-10-15 03:47:37 +0000844
Chris Bienemanad070d02014-09-17 20:55:46 +0000845 Value *LHS = CI->getArgOperand(0), *RHS = CI->getArgOperand(1);
Meador Inge40b6fac2012-10-15 03:47:37 +0000846
Chris Bienemanad070d02014-09-17 20:55:46 +0000847 if (LHS == RHS) // memcmp(s,s,x) -> 0
848 return Constant::getNullValue(CI->getType());
Meador Inge40b6fac2012-10-15 03:47:37 +0000849
Chris Bienemanad070d02014-09-17 20:55:46 +0000850 // Make sure we have a constant length.
851 ConstantInt *LenC = dyn_cast<ConstantInt>(CI->getArgOperand(2));
852 if (!LenC)
Craig Topperf40110f2014-04-25 05:29:35 +0000853 return nullptr;
Chris Bienemanad070d02014-09-17 20:55:46 +0000854 uint64_t Len = LenC->getZExtValue();
855
856 if (Len == 0) // memcmp(s1,s2,0) -> 0
857 return Constant::getNullValue(CI->getType());
858
859 // memcmp(S1,S2,1) -> *(unsigned char*)LHS - *(unsigned char*)RHS
860 if (Len == 1) {
861 Value *LHSV = B.CreateZExt(B.CreateLoad(CastToCStr(LHS, B), "lhsc"),
862 CI->getType(), "lhsv");
863 Value *RHSV = B.CreateZExt(B.CreateLoad(CastToCStr(RHS, B), "rhsc"),
864 CI->getType(), "rhsv");
865 return B.CreateSub(LHSV, RHSV, "chardiff");
Meador Inge40b6fac2012-10-15 03:47:37 +0000866 }
Meador Inge40b6fac2012-10-15 03:47:37 +0000867
Chad Rosierdc655322015-08-28 18:30:18 +0000868 // memcmp(S1,S2,N/8)==0 -> (*(intN_t*)S1 != *(intN_t*)S2)==0
869 if (DL.isLegalInteger(Len * 8) && isOnlyUsedInZeroEqualityComparison(CI)) {
870
871 IntegerType *IntType = IntegerType::get(CI->getContext(), Len * 8);
872 unsigned PrefAlignment = DL.getPrefTypeAlignment(IntType);
873
874 if (getKnownAlignment(LHS, DL, CI) >= PrefAlignment &&
875 getKnownAlignment(RHS, DL, CI) >= PrefAlignment) {
876
877 Type *LHSPtrTy =
878 IntType->getPointerTo(LHS->getType()->getPointerAddressSpace());
879 Type *RHSPtrTy =
880 IntType->getPointerTo(RHS->getType()->getPointerAddressSpace());
881
882 Value *LHSV = B.CreateLoad(B.CreateBitCast(LHS, LHSPtrTy, "lhsc"), "lhsv");
883 Value *RHSV = B.CreateLoad(B.CreateBitCast(RHS, RHSPtrTy, "rhsc"), "rhsv");
884
885 return B.CreateZExt(B.CreateICmpNE(LHSV, RHSV), CI->getType(), "memcmp");
886 }
887 }
888
Chris Bienemanad070d02014-09-17 20:55:46 +0000889 // Constant folding: memcmp(x, y, l) -> cnst (all arguments are constant)
890 StringRef LHSStr, RHSStr;
891 if (getConstantStringInfo(LHS, LHSStr) &&
892 getConstantStringInfo(RHS, RHSStr)) {
893 // Make sure we're not reading out-of-bounds memory.
894 if (Len > LHSStr.size() || Len > RHSStr.size())
Craig Topperf40110f2014-04-25 05:29:35 +0000895 return nullptr;
Chris Bienemanad070d02014-09-17 20:55:46 +0000896 // Fold the memcmp and normalize the result. This way we get consistent
897 // results across multiple platforms.
898 uint64_t Ret = 0;
899 int Cmp = memcmp(LHSStr.data(), RHSStr.data(), Len);
900 if (Cmp < 0)
901 Ret = -1;
902 else if (Cmp > 0)
903 Ret = 1;
904 return ConstantInt::get(CI->getType(), Ret);
Meador Inge000dbcc2012-10-18 18:12:40 +0000905 }
Meador Inge000dbcc2012-10-18 18:12:40 +0000906
Chris Bienemanad070d02014-09-17 20:55:46 +0000907 return nullptr;
908}
Meador Inge9a6a1902012-10-31 00:20:56 +0000909
Chris Bienemanad070d02014-09-17 20:55:46 +0000910Value *LibCallSimplifier::optimizeMemCpy(CallInst *CI, IRBuilder<> &B) {
911 Function *Callee = CI->getCalledFunction();
Meador Inged589ac62012-10-31 03:33:06 +0000912
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000913 if (!checkStringCopyLibFuncSignature(Callee, LibFunc::memcpy))
Craig Topperf40110f2014-04-25 05:29:35 +0000914 return nullptr;
Meador Inge6f8e0112012-10-31 04:29:58 +0000915
Chris Bienemanad070d02014-09-17 20:55:46 +0000916 // memcpy(x, y, n) -> llvm.memcpy(x, y, n, 1)
917 B.CreateMemCpy(CI->getArgOperand(0), CI->getArgOperand(1),
Pete Cooper67cf9a72015-11-19 05:56:52 +0000918 CI->getArgOperand(2), 1);
Chris Bienemanad070d02014-09-17 20:55:46 +0000919 return CI->getArgOperand(0);
920}
Meador Inge05a625a2012-10-31 14:58:26 +0000921
Chris Bienemanad070d02014-09-17 20:55:46 +0000922Value *LibCallSimplifier::optimizeMemMove(CallInst *CI, IRBuilder<> &B) {
923 Function *Callee = CI->getCalledFunction();
Meador Inge05a625a2012-10-31 14:58:26 +0000924
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000925 if (!checkStringCopyLibFuncSignature(Callee, LibFunc::memmove))
Craig Topperf40110f2014-04-25 05:29:35 +0000926 return nullptr;
Meador Inge489b5d62012-11-08 01:33:50 +0000927
Chris Bienemanad070d02014-09-17 20:55:46 +0000928 // memmove(x, y, n) -> llvm.memmove(x, y, n, 1)
929 B.CreateMemMove(CI->getArgOperand(0), CI->getArgOperand(1),
Pete Cooper67cf9a72015-11-19 05:56:52 +0000930 CI->getArgOperand(2), 1);
Chris Bienemanad070d02014-09-17 20:55:46 +0000931 return CI->getArgOperand(0);
932}
Meador Ingebcd88ef72012-11-10 15:16:48 +0000933
Chris Bienemanad070d02014-09-17 20:55:46 +0000934Value *LibCallSimplifier::optimizeMemSet(CallInst *CI, IRBuilder<> &B) {
935 Function *Callee = CI->getCalledFunction();
Meador Ingebcd88ef72012-11-10 15:16:48 +0000936
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000937 if (!checkStringCopyLibFuncSignature(Callee, LibFunc::memset))
Craig Topperf40110f2014-04-25 05:29:35 +0000938 return nullptr;
Meador Inge56edbc92012-11-11 03:51:48 +0000939
Chris Bienemanad070d02014-09-17 20:55:46 +0000940 // memset(p, v, n) -> llvm.memset(p, v, n, 1)
941 Value *Val = B.CreateIntCast(CI->getArgOperand(1), B.getInt8Ty(), false);
942 B.CreateMemSet(CI->getArgOperand(0), Val, CI->getArgOperand(2), 1);
943 return CI->getArgOperand(0);
944}
Meador Inged4825782012-11-11 06:49:03 +0000945
Meador Inge193e0352012-11-13 04:16:17 +0000946//===----------------------------------------------------------------------===//
947// Math Library Optimizations
948//===----------------------------------------------------------------------===//
949
Matthias Braund34e4d22014-12-03 21:46:33 +0000950/// Return a variant of Val with float type.
951/// Currently this works in two cases: If Val is an FPExtension of a float
952/// value to something bigger, simply return the operand.
953/// If Val is a ConstantFP but can be converted to a float ConstantFP without
954/// loss of precision do so.
955static Value *valueHasFloatPrecision(Value *Val) {
956 if (FPExtInst *Cast = dyn_cast<FPExtInst>(Val)) {
957 Value *Op = Cast->getOperand(0);
958 if (Op->getType()->isFloatTy())
959 return Op;
960 }
961 if (ConstantFP *Const = dyn_cast<ConstantFP>(Val)) {
962 APFloat F = Const->getValueAPF();
Matthias Braun395a82f2014-12-03 22:10:39 +0000963 bool losesInfo;
Matthias Braund34e4d22014-12-03 21:46:33 +0000964 (void)F.convert(APFloat::IEEEsingle, APFloat::rmNearestTiesToEven,
Matthias Braun395a82f2014-12-03 22:10:39 +0000965 &losesInfo);
966 if (!losesInfo)
Matthias Braund34e4d22014-12-03 21:46:33 +0000967 return ConstantFP::get(Const->getContext(), F);
968 }
969 return nullptr;
970}
971
Meador Inge193e0352012-11-13 04:16:17 +0000972//===----------------------------------------------------------------------===//
973// Double -> Float Shrinking Optimizations for Unary Functions like 'floor'
974
Chris Bienemanad070d02014-09-17 20:55:46 +0000975Value *LibCallSimplifier::optimizeUnaryDoubleFP(CallInst *CI, IRBuilder<> &B,
976 bool CheckRetType) {
977 Function *Callee = CI->getCalledFunction();
978 FunctionType *FT = Callee->getFunctionType();
979 if (FT->getNumParams() != 1 || !FT->getReturnType()->isDoubleTy() ||
980 !FT->getParamType(0)->isDoubleTy())
981 return nullptr;
Meador Inge193e0352012-11-13 04:16:17 +0000982
Chris Bienemanad070d02014-09-17 20:55:46 +0000983 if (CheckRetType) {
984 // Check if all the uses for function like 'sin' are converted to float.
985 for (User *U : CI->users()) {
986 FPTruncInst *Cast = dyn_cast<FPTruncInst>(U);
987 if (!Cast || !Cast->getType()->isFloatTy())
988 return nullptr;
Meador Inge193e0352012-11-13 04:16:17 +0000989 }
Meador Inge193e0352012-11-13 04:16:17 +0000990 }
Chris Bienemanad070d02014-09-17 20:55:46 +0000991
992 // If this is something like 'floor((double)floatval)', convert to floorf.
Matthias Braund34e4d22014-12-03 21:46:33 +0000993 Value *V = valueHasFloatPrecision(CI->getArgOperand(0));
994 if (V == nullptr)
Chris Bienemanad070d02014-09-17 20:55:46 +0000995 return nullptr;
996
997 // floor((double)floatval) -> (double)floorf(floatval)
Sanjay Patel848309d2014-10-23 21:52:45 +0000998 if (Callee->isIntrinsic()) {
999 Module *M = CI->getParent()->getParent()->getParent();
Pete Cooper9e1d3352015-05-20 17:16:39 +00001000 Intrinsic::ID IID = Callee->getIntrinsicID();
Sanjay Patel848309d2014-10-23 21:52:45 +00001001 Function *F = Intrinsic::getDeclaration(M, IID, B.getFloatTy());
1002 V = B.CreateCall(F, V);
1003 } else {
1004 // The call is a library call rather than an intrinsic.
1005 V = EmitUnaryFloatFnCall(V, Callee->getName(), B, Callee->getAttributes());
1006 }
1007
Chris Bienemanad070d02014-09-17 20:55:46 +00001008 return B.CreateFPExt(V, B.getDoubleTy());
1009}
Meador Inge193e0352012-11-13 04:16:17 +00001010
Yi Jiang6ab044e2013-12-16 22:42:40 +00001011// Double -> Float Shrinking Optimizations for Binary Functions like 'fmin/fmax'
Chris Bienemanad070d02014-09-17 20:55:46 +00001012Value *LibCallSimplifier::optimizeBinaryDoubleFP(CallInst *CI, IRBuilder<> &B) {
1013 Function *Callee = CI->getCalledFunction();
1014 FunctionType *FT = Callee->getFunctionType();
1015 // Just make sure this has 2 arguments of the same FP type, which match the
1016 // result type.
1017 if (FT->getNumParams() != 2 || FT->getReturnType() != FT->getParamType(0) ||
1018 FT->getParamType(0) != FT->getParamType(1) ||
1019 !FT->getParamType(0)->isFloatingPointTy())
Craig Topperf40110f2014-04-25 05:29:35 +00001020 return nullptr;
Meador Inge193e0352012-11-13 04:16:17 +00001021
Chris Bienemanad070d02014-09-17 20:55:46 +00001022 // If this is something like 'fmin((double)floatval1, (double)floatval2)',
Matthias Braund34e4d22014-12-03 21:46:33 +00001023 // or fmin(1.0, (double)floatval), then we convert it to fminf.
1024 Value *V1 = valueHasFloatPrecision(CI->getArgOperand(0));
1025 if (V1 == nullptr)
1026 return nullptr;
1027 Value *V2 = valueHasFloatPrecision(CI->getArgOperand(1));
1028 if (V2 == nullptr)
Craig Topperf40110f2014-04-25 05:29:35 +00001029 return nullptr;
Chris Bienemanad070d02014-09-17 20:55:46 +00001030
1031 // fmin((double)floatval1, (double)floatval2)
Matthias Braund34e4d22014-12-03 21:46:33 +00001032 // -> (double)fminf(floatval1, floatval2)
Sanjay Patel848309d2014-10-23 21:52:45 +00001033 // TODO: Handle intrinsics in the same way as in optimizeUnaryDoubleFP().
Matthias Braund34e4d22014-12-03 21:46:33 +00001034 Value *V = EmitBinaryFloatFnCall(V1, V2, Callee->getName(), B,
1035 Callee->getAttributes());
Chris Bienemanad070d02014-09-17 20:55:46 +00001036 return B.CreateFPExt(V, B.getDoubleTy());
1037}
1038
1039Value *LibCallSimplifier::optimizeCos(CallInst *CI, IRBuilder<> &B) {
1040 Function *Callee = CI->getCalledFunction();
1041 Value *Ret = nullptr;
Davide Italianoa3458772015-11-05 19:18:23 +00001042 StringRef Name = Callee->getName();
1043 if (UnsafeFPShrink && Name == "cos" && hasFloatVersion(Name))
Chris Bienemanad070d02014-09-17 20:55:46 +00001044 Ret = optimizeUnaryDoubleFP(CI, B, true);
Bob Wilsond8d92d92013-11-03 06:48:38 +00001045
Chris Bienemanad070d02014-09-17 20:55:46 +00001046 FunctionType *FT = Callee->getFunctionType();
1047 // Just make sure this has 1 argument of FP type, which matches the
1048 // result type.
1049 if (FT->getNumParams() != 1 || FT->getReturnType() != FT->getParamType(0) ||
1050 !FT->getParamType(0)->isFloatingPointTy())
1051 return Ret;
Bob Wilsond8d92d92013-11-03 06:48:38 +00001052
Chris Bienemanad070d02014-09-17 20:55:46 +00001053 // cos(-x) -> cos(x)
1054 Value *Op1 = CI->getArgOperand(0);
1055 if (BinaryOperator::isFNeg(Op1)) {
1056 BinaryOperator *BinExpr = cast<BinaryOperator>(Op1);
1057 return B.CreateCall(Callee, BinExpr->getOperand(1), "cos");
1058 }
1059 return Ret;
1060}
Bob Wilsond8d92d92013-11-03 06:48:38 +00001061
Chris Bienemanad070d02014-09-17 20:55:46 +00001062Value *LibCallSimplifier::optimizePow(CallInst *CI, IRBuilder<> &B) {
1063 Function *Callee = CI->getCalledFunction();
Chris Bienemanad070d02014-09-17 20:55:46 +00001064 Value *Ret = nullptr;
Davide Italianoa3458772015-11-05 19:18:23 +00001065 StringRef Name = Callee->getName();
1066 if (UnsafeFPShrink && Name == "pow" && hasFloatVersion(Name))
Chris Bienemanad070d02014-09-17 20:55:46 +00001067 Ret = optimizeUnaryDoubleFP(CI, B, true);
Bob Wilsond8d92d92013-11-03 06:48:38 +00001068
Chris Bienemanad070d02014-09-17 20:55:46 +00001069 FunctionType *FT = Callee->getFunctionType();
1070 // Just make sure this has 2 arguments of the same FP type, which match the
1071 // result type.
1072 if (FT->getNumParams() != 2 || FT->getReturnType() != FT->getParamType(0) ||
1073 FT->getParamType(0) != FT->getParamType(1) ||
1074 !FT->getParamType(0)->isFloatingPointTy())
1075 return Ret;
Bob Wilsond8d92d92013-11-03 06:48:38 +00001076
Chris Bienemanad070d02014-09-17 20:55:46 +00001077 Value *Op1 = CI->getArgOperand(0), *Op2 = CI->getArgOperand(1);
1078 if (ConstantFP *Op1C = dyn_cast<ConstantFP>(Op1)) {
1079 // pow(1.0, x) -> 1.0
1080 if (Op1C->isExactlyValue(1.0))
1081 return Op1C;
1082 // pow(2.0, x) -> exp2(x)
1083 if (Op1C->isExactlyValue(2.0) &&
1084 hasUnaryFloatFn(TLI, Op1->getType(), LibFunc::exp2, LibFunc::exp2f,
1085 LibFunc::exp2l))
Davide Italianod9f87b42015-11-06 21:05:07 +00001086 return EmitUnaryFloatFnCall(Op2, TLI->getName(LibFunc::exp2), B,
1087 Callee->getAttributes());
Chris Bienemanad070d02014-09-17 20:55:46 +00001088 // pow(10.0, x) -> exp10(x)
1089 if (Op1C->isExactlyValue(10.0) &&
1090 hasUnaryFloatFn(TLI, Op1->getType(), LibFunc::exp10, LibFunc::exp10f,
1091 LibFunc::exp10l))
1092 return EmitUnaryFloatFnCall(Op2, TLI->getName(LibFunc::exp10), B,
1093 Callee->getAttributes());
Bob Wilsond8d92d92013-11-03 06:48:38 +00001094 }
1095
Davide Italianoc5cedd12015-11-18 23:21:32 +00001096 bool unsafeFPMath = canUseUnsafeFPMath(CI->getParent()->getParent());
1097
Davide Italianoc8a79132015-11-03 20:32:23 +00001098 // pow(exp(x), y) -> exp(x*y)
1099 // pow(exp2(x), y) -> exp2(x * y)
1100 // We enable these only under fast-math. Besides rounding
1101 // differences the transformation changes overflow and
1102 // underflow behavior quite dramatically.
1103 // Example: x = 1000, y = 0.001.
1104 // pow(exp(x), y) = pow(inf, 0.001) = inf, whereas exp(x*y) = exp(1).
Davide Italianoc5cedd12015-11-18 23:21:32 +00001105 if (unsafeFPMath) {
Davide Italianoc8a79132015-11-03 20:32:23 +00001106 if (auto *OpC = dyn_cast<CallInst>(Op1)) {
1107 IRBuilder<>::FastMathFlagGuard Guard(B);
1108 FastMathFlags FMF;
1109 FMF.setUnsafeAlgebra();
1110 B.SetFastMathFlags(FMF);
1111
1112 LibFunc::Func Func;
Benjamin Kramerfb419e72015-11-26 09:51:17 +00001113 Function *OpCCallee = OpC->getCalledFunction();
1114 if (OpCCallee && TLI->getLibFunc(OpCCallee->getName(), Func) &&
1115 TLI->has(Func) && (Func == LibFunc::exp || Func == LibFunc::exp2))
Davide Italianoc8a79132015-11-03 20:32:23 +00001116 return EmitUnaryFloatFnCall(
Benjamin Kramerfb419e72015-11-26 09:51:17 +00001117 B.CreateFMul(OpC->getArgOperand(0), Op2, "mul"),
1118 OpCCallee->getName(), B, OpCCallee->getAttributes());
Davide Italianoc8a79132015-11-03 20:32:23 +00001119 }
1120 }
1121
Chris Bienemanad070d02014-09-17 20:55:46 +00001122 ConstantFP *Op2C = dyn_cast<ConstantFP>(Op2);
1123 if (!Op2C)
1124 return Ret;
1125
1126 if (Op2C->getValueAPF().isZero()) // pow(x, 0.0) -> 1.0
1127 return ConstantFP::get(CI->getType(), 1.0);
1128
1129 if (Op2C->isExactlyValue(0.5) &&
1130 hasUnaryFloatFn(TLI, Op2->getType(), LibFunc::sqrt, LibFunc::sqrtf,
1131 LibFunc::sqrtl) &&
1132 hasUnaryFloatFn(TLI, Op2->getType(), LibFunc::fabs, LibFunc::fabsf,
1133 LibFunc::fabsl)) {
Davide Italianoc5cedd12015-11-18 23:21:32 +00001134
1135 // In -ffast-math, pow(x, 0.5) -> sqrt(x).
1136 if (unsafeFPMath)
1137 return EmitUnaryFloatFnCall(Op1, TLI->getName(LibFunc::sqrt), B,
1138 Callee->getAttributes());
1139
Chris Bienemanad070d02014-09-17 20:55:46 +00001140 // Expand pow(x, 0.5) to (x == -infinity ? +infinity : fabs(sqrt(x))).
1141 // This is faster than calling pow, and still handles negative zero
1142 // and negative infinity correctly.
Chris Bienemanad070d02014-09-17 20:55:46 +00001143 // TODO: In finite-only mode, this could be just fabs(sqrt(x)).
1144 Value *Inf = ConstantFP::getInfinity(CI->getType());
1145 Value *NegInf = ConstantFP::getInfinity(CI->getType(), true);
1146 Value *Sqrt = EmitUnaryFloatFnCall(Op1, "sqrt", B, Callee->getAttributes());
1147 Value *FAbs =
1148 EmitUnaryFloatFnCall(Sqrt, "fabs", B, Callee->getAttributes());
1149 Value *FCmp = B.CreateFCmpOEQ(Op1, NegInf);
1150 Value *Sel = B.CreateSelect(FCmp, Inf, FAbs);
1151 return Sel;
Bob Wilsond8d92d92013-11-03 06:48:38 +00001152 }
1153
Chris Bienemanad070d02014-09-17 20:55:46 +00001154 if (Op2C->isExactlyValue(1.0)) // pow(x, 1.0) -> x
1155 return Op1;
1156 if (Op2C->isExactlyValue(2.0)) // pow(x, 2.0) -> x*x
1157 return B.CreateFMul(Op1, Op1, "pow2");
1158 if (Op2C->isExactlyValue(-1.0)) // pow(x, -1.0) -> 1.0/x
1159 return B.CreateFDiv(ConstantFP::get(CI->getType(), 1.0), Op1, "powrecip");
1160 return nullptr;
1161}
Bob Wilsond8d92d92013-11-03 06:48:38 +00001162
Chris Bienemanad070d02014-09-17 20:55:46 +00001163Value *LibCallSimplifier::optimizeExp2(CallInst *CI, IRBuilder<> &B) {
1164 Function *Callee = CI->getCalledFunction();
1165 Function *Caller = CI->getParent()->getParent();
Chris Bienemanad070d02014-09-17 20:55:46 +00001166 Value *Ret = nullptr;
Davide Italianoa3458772015-11-05 19:18:23 +00001167 StringRef Name = Callee->getName();
1168 if (UnsafeFPShrink && Name == "exp2" && hasFloatVersion(Name))
Chris Bienemanad070d02014-09-17 20:55:46 +00001169 Ret = optimizeUnaryDoubleFP(CI, B, true);
Bob Wilsond8d92d92013-11-03 06:48:38 +00001170
Chris Bienemanad070d02014-09-17 20:55:46 +00001171 FunctionType *FT = Callee->getFunctionType();
1172 // Just make sure this has 1 argument of FP type, which matches the
1173 // result type.
1174 if (FT->getNumParams() != 1 || FT->getReturnType() != FT->getParamType(0) ||
1175 !FT->getParamType(0)->isFloatingPointTy())
1176 return Ret;
1177
1178 Value *Op = CI->getArgOperand(0);
1179 // Turn exp2(sitofp(x)) -> ldexp(1.0, sext(x)) if sizeof(x) <= 32
1180 // Turn exp2(uitofp(x)) -> ldexp(1.0, zext(x)) if sizeof(x) < 32
1181 LibFunc::Func LdExp = LibFunc::ldexpl;
1182 if (Op->getType()->isFloatTy())
1183 LdExp = LibFunc::ldexpf;
1184 else if (Op->getType()->isDoubleTy())
1185 LdExp = LibFunc::ldexp;
1186
1187 if (TLI->has(LdExp)) {
1188 Value *LdExpArg = nullptr;
1189 if (SIToFPInst *OpC = dyn_cast<SIToFPInst>(Op)) {
1190 if (OpC->getOperand(0)->getType()->getPrimitiveSizeInBits() <= 32)
1191 LdExpArg = B.CreateSExt(OpC->getOperand(0), B.getInt32Ty());
1192 } else if (UIToFPInst *OpC = dyn_cast<UIToFPInst>(Op)) {
1193 if (OpC->getOperand(0)->getType()->getPrimitiveSizeInBits() < 32)
1194 LdExpArg = B.CreateZExt(OpC->getOperand(0), B.getInt32Ty());
1195 }
1196
1197 if (LdExpArg) {
1198 Constant *One = ConstantFP::get(CI->getContext(), APFloat(1.0f));
1199 if (!Op->getType()->isFloatTy())
1200 One = ConstantExpr::getFPExtend(One, Op->getType());
1201
1202 Module *M = Caller->getParent();
1203 Value *Callee =
1204 M->getOrInsertFunction(TLI->getName(LdExp), Op->getType(),
Reid Kleckner971c3ea2014-11-13 22:55:19 +00001205 Op->getType(), B.getInt32Ty(), nullptr);
David Blaikieff6409d2015-05-18 22:13:54 +00001206 CallInst *CI = B.CreateCall(Callee, {One, LdExpArg});
Chris Bienemanad070d02014-09-17 20:55:46 +00001207 if (const Function *F = dyn_cast<Function>(Callee->stripPointerCasts()))
1208 CI->setCallingConv(F->getCallingConv());
1209
1210 return CI;
1211 }
1212 }
1213 return Ret;
1214}
1215
Sanjay Patel0ca42bb2014-10-14 20:43:11 +00001216Value *LibCallSimplifier::optimizeFabs(CallInst *CI, IRBuilder<> &B) {
1217 Function *Callee = CI->getCalledFunction();
Sanjay Patel0ca42bb2014-10-14 20:43:11 +00001218 Value *Ret = nullptr;
Davide Italianoa3458772015-11-05 19:18:23 +00001219 StringRef Name = Callee->getName();
1220 if (Name == "fabs" && hasFloatVersion(Name))
Sanjay Patel0ca42bb2014-10-14 20:43:11 +00001221 Ret = optimizeUnaryDoubleFP(CI, B, false);
Sanjay Patel0ca42bb2014-10-14 20:43:11 +00001222
1223 FunctionType *FT = Callee->getFunctionType();
1224 // Make sure this has 1 argument of FP type which matches the result type.
1225 if (FT->getNumParams() != 1 || FT->getReturnType() != FT->getParamType(0) ||
1226 !FT->getParamType(0)->isFloatingPointTy())
1227 return Ret;
1228
1229 Value *Op = CI->getArgOperand(0);
1230 if (Instruction *I = dyn_cast<Instruction>(Op)) {
1231 // Fold fabs(x * x) -> x * x; any squared FP value must already be positive.
1232 if (I->getOpcode() == Instruction::FMul)
1233 if (I->getOperand(0) == I->getOperand(1))
1234 return Op;
1235 }
1236 return Ret;
1237}
1238
Sanjay Patel57fd1dc2015-08-16 20:18:19 +00001239Value *LibCallSimplifier::optimizeFMinFMax(CallInst *CI, IRBuilder<> &B) {
1240 // If we can shrink the call to a float function rather than a double
1241 // function, do that first.
1242 Function *Callee = CI->getCalledFunction();
Davide Italianoa3458772015-11-05 19:18:23 +00001243 StringRef Name = Callee->getName();
1244 if ((Name == "fmin" && hasFloatVersion(Name)) ||
1245 (Name == "fmax" && hasFloatVersion(Name))) {
Sanjay Patel57fd1dc2015-08-16 20:18:19 +00001246 Value *Ret = optimizeBinaryDoubleFP(CI, B);
1247 if (Ret)
1248 return Ret;
1249 }
1250
1251 // Make sure this has 2 arguments of FP type which match the result type.
1252 FunctionType *FT = Callee->getFunctionType();
1253 if (FT->getNumParams() != 2 || FT->getReturnType() != FT->getParamType(0) ||
1254 FT->getParamType(0) != FT->getParamType(1) ||
1255 !FT->getParamType(0)->isFloatingPointTy())
1256 return nullptr;
1257
Benjamin Kramerbb70d752015-08-16 21:16:37 +00001258 IRBuilder<>::FastMathFlagGuard Guard(B);
Sanjay Patel57fd1dc2015-08-16 20:18:19 +00001259 FastMathFlags FMF;
1260 Function *F = CI->getParent()->getParent();
Davide Italianoa904e522015-10-29 02:58:44 +00001261 if (canUseUnsafeFPMath(F)) {
Sanjay Patel57fd1dc2015-08-16 20:18:19 +00001262 // Unsafe algebra sets all fast-math-flags to true.
1263 FMF.setUnsafeAlgebra();
1264 } else {
1265 // At a minimum, no-nans-fp-math must be true.
Davide Italianoa904e522015-10-29 02:58:44 +00001266 Attribute Attr = F->getFnAttribute("no-nans-fp-math");
Sanjay Patel57fd1dc2015-08-16 20:18:19 +00001267 if (Attr.getValueAsString() != "true")
1268 return nullptr;
1269 // No-signed-zeros is implied by the definitions of fmax/fmin themselves:
1270 // "Ideally, fmax would be sensitive to the sign of zero, for example
NAKAMURA Takumi0d725392015-09-07 00:26:54 +00001271 // fmax(-0. 0, +0. 0) would return +0; however, implementation in software
Sanjay Patel57fd1dc2015-08-16 20:18:19 +00001272 // might be impractical."
1273 FMF.setNoSignedZeros();
1274 FMF.setNoNaNs();
1275 }
1276 B.SetFastMathFlags(FMF);
1277
1278 // We have a relaxed floating-point environment. We can ignore NaN-handling
1279 // and transform to a compare and select. We do not have to consider errno or
1280 // exceptions, because fmin/fmax do not have those.
1281 Value *Op0 = CI->getArgOperand(0);
1282 Value *Op1 = CI->getArgOperand(1);
1283 Value *Cmp = Callee->getName().startswith("fmin") ?
1284 B.CreateFCmpOLT(Op0, Op1) : B.CreateFCmpOGT(Op0, Op1);
1285 return B.CreateSelect(Cmp, Op0, Op1);
1286}
1287
Sanjay Patelc699a612014-10-16 18:48:17 +00001288Value *LibCallSimplifier::optimizeSqrt(CallInst *CI, IRBuilder<> &B) {
1289 Function *Callee = CI->getCalledFunction();
1290
1291 Value *Ret = nullptr;
Sanjay Patel848309d2014-10-23 21:52:45 +00001292 if (TLI->has(LibFunc::sqrtf) && (Callee->getName() == "sqrt" ||
1293 Callee->getIntrinsicID() == Intrinsic::sqrt))
Sanjay Patelc699a612014-10-16 18:48:17 +00001294 Ret = optimizeUnaryDoubleFP(CI, B, true);
Davide Italianoa904e522015-10-29 02:58:44 +00001295 if (!canUseUnsafeFPMath(CI->getParent()->getParent()))
1296 return Ret;
Sanjay Patelc699a612014-10-16 18:48:17 +00001297
Sanjay Patelc699a612014-10-16 18:48:17 +00001298 Value *Op = CI->getArgOperand(0);
1299 if (Instruction *I = dyn_cast<Instruction>(Op)) {
1300 if (I->getOpcode() == Instruction::FMul && I->hasUnsafeAlgebra()) {
1301 // We're looking for a repeated factor in a multiplication tree,
1302 // so we can do this fold: sqrt(x * x) -> fabs(x);
1303 // or this fold: sqrt(x * x * y) -> fabs(x) * sqrt(y).
1304 Value *Op0 = I->getOperand(0);
1305 Value *Op1 = I->getOperand(1);
1306 Value *RepeatOp = nullptr;
1307 Value *OtherOp = nullptr;
1308 if (Op0 == Op1) {
1309 // Simple match: the operands of the multiply are identical.
1310 RepeatOp = Op0;
1311 } else {
1312 // Look for a more complicated pattern: one of the operands is itself
1313 // a multiply, so search for a common factor in that multiply.
1314 // Note: We don't bother looking any deeper than this first level or for
1315 // variations of this pattern because instcombine's visitFMUL and/or the
1316 // reassociation pass should give us this form.
1317 Value *OtherMul0, *OtherMul1;
1318 if (match(Op0, m_FMul(m_Value(OtherMul0), m_Value(OtherMul1)))) {
1319 // Pattern: sqrt((x * y) * z)
1320 if (OtherMul0 == OtherMul1) {
1321 // Matched: sqrt((x * x) * z)
1322 RepeatOp = OtherMul0;
1323 OtherOp = Op1;
1324 }
1325 }
1326 }
1327 if (RepeatOp) {
1328 // Fast math flags for any created instructions should match the sqrt
1329 // and multiply.
1330 // FIXME: We're not checking the sqrt because it doesn't have
1331 // fast-math-flags (see earlier comment).
Benjamin Kramerbb70d752015-08-16 21:16:37 +00001332 IRBuilder<>::FastMathFlagGuard Guard(B);
Sanjay Patelc699a612014-10-16 18:48:17 +00001333 B.SetFastMathFlags(I->getFastMathFlags());
1334 // If we found a repeated factor, hoist it out of the square root and
1335 // replace it with the fabs of that factor.
1336 Module *M = Callee->getParent();
1337 Type *ArgType = Op->getType();
1338 Value *Fabs = Intrinsic::getDeclaration(M, Intrinsic::fabs, ArgType);
1339 Value *FabsCall = B.CreateCall(Fabs, RepeatOp, "fabs");
1340 if (OtherOp) {
1341 // If we found a non-repeated factor, we still need to get its square
1342 // root. We then multiply that by the value that was simplified out
1343 // of the square root calculation.
1344 Value *Sqrt = Intrinsic::getDeclaration(M, Intrinsic::sqrt, ArgType);
1345 Value *SqrtCall = B.CreateCall(Sqrt, OtherOp, "sqrt");
1346 return B.CreateFMul(FabsCall, SqrtCall);
1347 }
1348 return FabsCall;
1349 }
1350 }
1351 }
1352 return Ret;
1353}
1354
Davide Italiano51507d22015-11-04 23:36:56 +00001355Value *LibCallSimplifier::optimizeTan(CallInst *CI, IRBuilder<> &B) {
1356 Function *Callee = CI->getCalledFunction();
1357 Value *Ret = nullptr;
Davide Italianoa3458772015-11-05 19:18:23 +00001358 StringRef Name = Callee->getName();
1359 if (UnsafeFPShrink && Name == "tan" && hasFloatVersion(Name))
Davide Italiano51507d22015-11-04 23:36:56 +00001360 Ret = optimizeUnaryDoubleFP(CI, B, true);
1361 FunctionType *FT = Callee->getFunctionType();
1362
1363 // Just make sure this has 1 argument of FP type, which matches the
1364 // result type.
1365 if (FT->getNumParams() != 1 || FT->getReturnType() != FT->getParamType(0) ||
1366 !FT->getParamType(0)->isFloatingPointTy())
1367 return Ret;
1368
1369 if (!canUseUnsafeFPMath(CI->getParent()->getParent()))
1370 return Ret;
1371 Value *Op1 = CI->getArgOperand(0);
1372 auto *OpC = dyn_cast<CallInst>(Op1);
1373 if (!OpC)
1374 return Ret;
1375
1376 // tan(atan(x)) -> x
1377 // tanf(atanf(x)) -> x
1378 // tanl(atanl(x)) -> x
1379 LibFunc::Func Func;
1380 Function *F = OpC->getCalledFunction();
Benjamin Kramerfb419e72015-11-26 09:51:17 +00001381 if (F && TLI->getLibFunc(F->getName(), Func) && TLI->has(Func) &&
Davide Italiano51507d22015-11-04 23:36:56 +00001382 ((Func == LibFunc::atan && Callee->getName() == "tan") ||
1383 (Func == LibFunc::atanf && Callee->getName() == "tanf") ||
1384 (Func == LibFunc::atanl && Callee->getName() == "tanl")))
1385 Ret = OpC->getArgOperand(0);
1386 return Ret;
1387}
1388
Chris Bienemanad070d02014-09-17 20:55:46 +00001389static bool isTrigLibCall(CallInst *CI);
1390static void insertSinCosCall(IRBuilder<> &B, Function *OrigCallee, Value *Arg,
1391 bool UseFloat, Value *&Sin, Value *&Cos,
1392 Value *&SinCos);
1393
1394Value *LibCallSimplifier::optimizeSinCosPi(CallInst *CI, IRBuilder<> &B) {
1395
1396 // Make sure the prototype is as expected, otherwise the rest of the
1397 // function is probably invalid and likely to abort.
1398 if (!isTrigLibCall(CI))
1399 return nullptr;
1400
1401 Value *Arg = CI->getArgOperand(0);
1402 SmallVector<CallInst *, 1> SinCalls;
1403 SmallVector<CallInst *, 1> CosCalls;
1404 SmallVector<CallInst *, 1> SinCosCalls;
1405
1406 bool IsFloat = Arg->getType()->isFloatTy();
1407
1408 // Look for all compatible sinpi, cospi and sincospi calls with the same
1409 // argument. If there are enough (in some sense) we can make the
1410 // substitution.
1411 for (User *U : Arg->users())
1412 classifyArgUse(U, CI->getParent(), IsFloat, SinCalls, CosCalls,
1413 SinCosCalls);
1414
1415 // It's only worthwhile if both sinpi and cospi are actually used.
1416 if (SinCosCalls.empty() && (SinCalls.empty() || CosCalls.empty()))
1417 return nullptr;
1418
1419 Value *Sin, *Cos, *SinCos;
1420 insertSinCosCall(B, CI->getCalledFunction(), Arg, IsFloat, Sin, Cos, SinCos);
1421
1422 replaceTrigInsts(SinCalls, Sin);
1423 replaceTrigInsts(CosCalls, Cos);
1424 replaceTrigInsts(SinCosCalls, SinCos);
1425
1426 return nullptr;
1427}
1428
1429static bool isTrigLibCall(CallInst *CI) {
1430 Function *Callee = CI->getCalledFunction();
1431 FunctionType *FT = Callee->getFunctionType();
1432
1433 // We can only hope to do anything useful if we can ignore things like errno
1434 // and floating-point exceptions.
1435 bool AttributesSafe =
1436 CI->hasFnAttr(Attribute::NoUnwind) && CI->hasFnAttr(Attribute::ReadNone);
1437
1438 // Other than that we need float(float) or double(double)
1439 return AttributesSafe && FT->getNumParams() == 1 &&
1440 FT->getReturnType() == FT->getParamType(0) &&
1441 (FT->getParamType(0)->isFloatTy() ||
1442 FT->getParamType(0)->isDoubleTy());
1443}
1444
1445void
1446LibCallSimplifier::classifyArgUse(Value *Val, BasicBlock *BB, bool IsFloat,
1447 SmallVectorImpl<CallInst *> &SinCalls,
1448 SmallVectorImpl<CallInst *> &CosCalls,
1449 SmallVectorImpl<CallInst *> &SinCosCalls) {
1450 CallInst *CI = dyn_cast<CallInst>(Val);
1451
1452 if (!CI)
1453 return;
1454
1455 Function *Callee = CI->getCalledFunction();
Chris Bienemanad070d02014-09-17 20:55:46 +00001456 LibFunc::Func Func;
Benjamin Kramer89766e52015-11-28 21:43:12 +00001457 if (!Callee || !TLI->getLibFunc(Callee->getName(), Func) || !TLI->has(Func) ||
1458 !isTrigLibCall(CI))
Chris Bienemanad070d02014-09-17 20:55:46 +00001459 return;
1460
1461 if (IsFloat) {
1462 if (Func == LibFunc::sinpif)
1463 SinCalls.push_back(CI);
1464 else if (Func == LibFunc::cospif)
1465 CosCalls.push_back(CI);
1466 else if (Func == LibFunc::sincospif_stret)
1467 SinCosCalls.push_back(CI);
1468 } else {
1469 if (Func == LibFunc::sinpi)
1470 SinCalls.push_back(CI);
1471 else if (Func == LibFunc::cospi)
1472 CosCalls.push_back(CI);
1473 else if (Func == LibFunc::sincospi_stret)
1474 SinCosCalls.push_back(CI);
1475 }
1476}
1477
1478void LibCallSimplifier::replaceTrigInsts(SmallVectorImpl<CallInst *> &Calls,
1479 Value *Res) {
Davide Italianoc6926882015-10-27 04:17:51 +00001480 for (CallInst *C : Calls)
1481 replaceAllUsesWith(C, Res);
Chris Bienemanad070d02014-09-17 20:55:46 +00001482}
1483
1484void insertSinCosCall(IRBuilder<> &B, Function *OrigCallee, Value *Arg,
1485 bool UseFloat, Value *&Sin, Value *&Cos, Value *&SinCos) {
1486 Type *ArgTy = Arg->getType();
1487 Type *ResTy;
1488 StringRef Name;
1489
1490 Triple T(OrigCallee->getParent()->getTargetTriple());
1491 if (UseFloat) {
1492 Name = "__sincospif_stret";
1493
1494 assert(T.getArch() != Triple::x86 && "x86 messy and unsupported for now");
1495 // x86_64 can't use {float, float} since that would be returned in both
1496 // xmm0 and xmm1, which isn't what a real struct would do.
1497 ResTy = T.getArch() == Triple::x86_64
1498 ? static_cast<Type *>(VectorType::get(ArgTy, 2))
Reid Kleckner971c3ea2014-11-13 22:55:19 +00001499 : static_cast<Type *>(StructType::get(ArgTy, ArgTy, nullptr));
Chris Bienemanad070d02014-09-17 20:55:46 +00001500 } else {
1501 Name = "__sincospi_stret";
Reid Kleckner971c3ea2014-11-13 22:55:19 +00001502 ResTy = StructType::get(ArgTy, ArgTy, nullptr);
Chris Bienemanad070d02014-09-17 20:55:46 +00001503 }
1504
1505 Module *M = OrigCallee->getParent();
1506 Value *Callee = M->getOrInsertFunction(Name, OrigCallee->getAttributes(),
Reid Kleckner971c3ea2014-11-13 22:55:19 +00001507 ResTy, ArgTy, nullptr);
Chris Bienemanad070d02014-09-17 20:55:46 +00001508
1509 if (Instruction *ArgInst = dyn_cast<Instruction>(Arg)) {
1510 // If the argument is an instruction, it must dominate all uses so put our
1511 // sincos call there.
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +00001512 B.SetInsertPoint(ArgInst->getParent(), ++ArgInst->getIterator());
Chris Bienemanad070d02014-09-17 20:55:46 +00001513 } else {
1514 // Otherwise (e.g. for a constant) the beginning of the function is as
1515 // good a place as any.
1516 BasicBlock &EntryBB = B.GetInsertBlock()->getParent()->getEntryBlock();
1517 B.SetInsertPoint(&EntryBB, EntryBB.begin());
1518 }
1519
1520 SinCos = B.CreateCall(Callee, Arg, "sincospi");
1521
1522 if (SinCos->getType()->isStructTy()) {
1523 Sin = B.CreateExtractValue(SinCos, 0, "sinpi");
1524 Cos = B.CreateExtractValue(SinCos, 1, "cospi");
1525 } else {
1526 Sin = B.CreateExtractElement(SinCos, ConstantInt::get(B.getInt32Ty(), 0),
1527 "sinpi");
1528 Cos = B.CreateExtractElement(SinCos, ConstantInt::get(B.getInt32Ty(), 1),
1529 "cospi");
1530 }
1531}
Bob Wilsond8d92d92013-11-03 06:48:38 +00001532
Meador Inge7415f842012-11-25 20:45:27 +00001533//===----------------------------------------------------------------------===//
1534// Integer Library Call Optimizations
1535//===----------------------------------------------------------------------===//
1536
Davide Italiano396f3ee2015-10-31 23:17:45 +00001537static bool checkIntUnaryReturnAndParam(Function *Callee) {
1538 FunctionType *FT = Callee->getFunctionType();
Davide Italiano5cdf9152015-11-01 00:09:16 +00001539 return FT->getNumParams() == 1 && FT->getReturnType()->isIntegerTy(32) &&
1540 FT->getParamType(0)->isIntegerTy();
Davide Italiano396f3ee2015-10-31 23:17:45 +00001541}
1542
Chris Bienemanad070d02014-09-17 20:55:46 +00001543Value *LibCallSimplifier::optimizeFFS(CallInst *CI, IRBuilder<> &B) {
1544 Function *Callee = CI->getCalledFunction();
Davide Italiano396f3ee2015-10-31 23:17:45 +00001545 if (!checkIntUnaryReturnAndParam(Callee))
Chris Bienemanad070d02014-09-17 20:55:46 +00001546 return nullptr;
Chris Bienemanad070d02014-09-17 20:55:46 +00001547 Value *Op = CI->getArgOperand(0);
Meador Inge7415f842012-11-25 20:45:27 +00001548
Chris Bienemanad070d02014-09-17 20:55:46 +00001549 // Constant fold.
1550 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op)) {
1551 if (CI->isZero()) // ffs(0) -> 0.
1552 return B.getInt32(0);
1553 // ffs(c) -> cttz(c)+1
1554 return B.getInt32(CI->getValue().countTrailingZeros() + 1);
Meador Inge7415f842012-11-25 20:45:27 +00001555 }
Meador Inge7415f842012-11-25 20:45:27 +00001556
Chris Bienemanad070d02014-09-17 20:55:46 +00001557 // ffs(x) -> x != 0 ? (i32)llvm.cttz(x)+1 : 0
1558 Type *ArgType = Op->getType();
1559 Value *F =
1560 Intrinsic::getDeclaration(Callee->getParent(), Intrinsic::cttz, ArgType);
Davide Italianoa1953862015-08-13 20:34:26 +00001561 Value *V = B.CreateCall(F, {Op, B.getTrue()}, "cttz");
Chris Bienemanad070d02014-09-17 20:55:46 +00001562 V = B.CreateAdd(V, ConstantInt::get(V->getType(), 1));
1563 V = B.CreateIntCast(V, B.getInt32Ty(), false);
Meador Ingea0b6d872012-11-26 00:24:07 +00001564
Chris Bienemanad070d02014-09-17 20:55:46 +00001565 Value *Cond = B.CreateICmpNE(Op, Constant::getNullValue(ArgType));
1566 return B.CreateSelect(Cond, V, B.getInt32(0));
1567}
Meador Ingea0b6d872012-11-26 00:24:07 +00001568
Chris Bienemanad070d02014-09-17 20:55:46 +00001569Value *LibCallSimplifier::optimizeAbs(CallInst *CI, IRBuilder<> &B) {
1570 Function *Callee = CI->getCalledFunction();
1571 FunctionType *FT = Callee->getFunctionType();
1572 // We require integer(integer) where the types agree.
1573 if (FT->getNumParams() != 1 || !FT->getReturnType()->isIntegerTy() ||
1574 FT->getParamType(0) != FT->getReturnType())
1575 return nullptr;
Meador Inge9a59ab62012-11-26 02:31:59 +00001576
Chris Bienemanad070d02014-09-17 20:55:46 +00001577 // abs(x) -> x >s -1 ? x : -x
1578 Value *Op = CI->getArgOperand(0);
1579 Value *Pos =
1580 B.CreateICmpSGT(Op, Constant::getAllOnesValue(Op->getType()), "ispos");
1581 Value *Neg = B.CreateNeg(Op, "neg");
1582 return B.CreateSelect(Pos, Op, Neg);
1583}
Meador Inge9a59ab62012-11-26 02:31:59 +00001584
Chris Bienemanad070d02014-09-17 20:55:46 +00001585Value *LibCallSimplifier::optimizeIsDigit(CallInst *CI, IRBuilder<> &B) {
Davide Italiano396f3ee2015-10-31 23:17:45 +00001586 if (!checkIntUnaryReturnAndParam(CI->getCalledFunction()))
Chris Bienemanad070d02014-09-17 20:55:46 +00001587 return nullptr;
Meador Ingea62a39e2012-11-26 03:10:07 +00001588
Chris Bienemanad070d02014-09-17 20:55:46 +00001589 // isdigit(c) -> (c-'0') <u 10
1590 Value *Op = CI->getArgOperand(0);
1591 Op = B.CreateSub(Op, B.getInt32('0'), "isdigittmp");
1592 Op = B.CreateICmpULT(Op, B.getInt32(10), "isdigit");
1593 return B.CreateZExt(Op, CI->getType());
1594}
Meador Ingea62a39e2012-11-26 03:10:07 +00001595
Chris Bienemanad070d02014-09-17 20:55:46 +00001596Value *LibCallSimplifier::optimizeIsAscii(CallInst *CI, IRBuilder<> &B) {
Davide Italiano396f3ee2015-10-31 23:17:45 +00001597 if (!checkIntUnaryReturnAndParam(CI->getCalledFunction()))
Chris Bienemanad070d02014-09-17 20:55:46 +00001598 return nullptr;
Meador Inge604937d2012-11-26 03:38:52 +00001599
Chris Bienemanad070d02014-09-17 20:55:46 +00001600 // isascii(c) -> c <u 128
1601 Value *Op = CI->getArgOperand(0);
1602 Op = B.CreateICmpULT(Op, B.getInt32(128), "isascii");
1603 return B.CreateZExt(Op, CI->getType());
1604}
1605
1606Value *LibCallSimplifier::optimizeToAscii(CallInst *CI, IRBuilder<> &B) {
Davide Italiano396f3ee2015-10-31 23:17:45 +00001607 if (!checkIntUnaryReturnAndParam(CI->getCalledFunction()))
Chris Bienemanad070d02014-09-17 20:55:46 +00001608 return nullptr;
1609
1610 // toascii(c) -> c & 0x7f
1611 return B.CreateAnd(CI->getArgOperand(0),
1612 ConstantInt::get(CI->getType(), 0x7F));
1613}
Meador Inge604937d2012-11-26 03:38:52 +00001614
Meador Inge08ca1152012-11-26 20:37:20 +00001615//===----------------------------------------------------------------------===//
1616// Formatting and IO Library Call Optimizations
1617//===----------------------------------------------------------------------===//
1618
Chris Bienemanad070d02014-09-17 20:55:46 +00001619static bool isReportingError(Function *Callee, CallInst *CI, int StreamArg);
Hal Finkel66cd3f12013-11-17 02:06:35 +00001620
Chris Bienemanad070d02014-09-17 20:55:46 +00001621Value *LibCallSimplifier::optimizeErrorReporting(CallInst *CI, IRBuilder<> &B,
1622 int StreamArg) {
1623 // Error reporting calls should be cold, mark them as such.
1624 // This applies even to non-builtin calls: it is only a hint and applies to
1625 // functions that the frontend might not understand as builtins.
Hal Finkel66cd3f12013-11-17 02:06:35 +00001626
Chris Bienemanad070d02014-09-17 20:55:46 +00001627 // This heuristic was suggested in:
1628 // Improving Static Branch Prediction in a Compiler
1629 // Brian L. Deitrich, Ben-Chung Cheng, Wen-mei W. Hwu
1630 // Proceedings of PACT'98, Oct. 1998, IEEE
1631 Function *Callee = CI->getCalledFunction();
Hal Finkel66cd3f12013-11-17 02:06:35 +00001632
Chris Bienemanad070d02014-09-17 20:55:46 +00001633 if (!CI->hasFnAttr(Attribute::Cold) &&
1634 isReportingError(Callee, CI, StreamArg)) {
1635 CI->addAttribute(AttributeSet::FunctionIndex, Attribute::Cold);
1636 }
Hal Finkel66cd3f12013-11-17 02:06:35 +00001637
Chris Bienemanad070d02014-09-17 20:55:46 +00001638 return nullptr;
1639}
1640
1641static bool isReportingError(Function *Callee, CallInst *CI, int StreamArg) {
Davide Italianoe84d4da2015-11-02 22:33:26 +00001642 if (!ColdErrorCalls || !Callee || !Callee->isDeclaration())
Chris Bienemanad070d02014-09-17 20:55:46 +00001643 return false;
1644
1645 if (StreamArg < 0)
1646 return true;
1647
1648 // These functions might be considered cold, but only if their stream
1649 // argument is stderr.
1650
1651 if (StreamArg >= (int)CI->getNumArgOperands())
1652 return false;
1653 LoadInst *LI = dyn_cast<LoadInst>(CI->getArgOperand(StreamArg));
1654 if (!LI)
1655 return false;
1656 GlobalVariable *GV = dyn_cast<GlobalVariable>(LI->getPointerOperand());
1657 if (!GV || !GV->isDeclaration())
1658 return false;
1659 return GV->getName() == "stderr";
1660}
1661
1662Value *LibCallSimplifier::optimizePrintFString(CallInst *CI, IRBuilder<> &B) {
1663 // Check for a fixed format string.
1664 StringRef FormatStr;
1665 if (!getConstantStringInfo(CI->getArgOperand(0), FormatStr))
Craig Topperf40110f2014-04-25 05:29:35 +00001666 return nullptr;
Hal Finkel66cd3f12013-11-17 02:06:35 +00001667
Chris Bienemanad070d02014-09-17 20:55:46 +00001668 // Empty format string -> noop.
1669 if (FormatStr.empty()) // Tolerate printf's declared void.
1670 return CI->use_empty() ? (Value *)CI : ConstantInt::get(CI->getType(), 0);
Hal Finkel66cd3f12013-11-17 02:06:35 +00001671
Chris Bienemanad070d02014-09-17 20:55:46 +00001672 // Do not do any of the following transformations if the printf return value
1673 // is used, in general the printf return value is not compatible with either
1674 // putchar() or puts().
1675 if (!CI->use_empty())
Craig Topperf40110f2014-04-25 05:29:35 +00001676 return nullptr;
Chris Bienemanad070d02014-09-17 20:55:46 +00001677
1678 // printf("x") -> putchar('x'), even for '%'.
1679 if (FormatStr.size() == 1) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001680 Value *Res = EmitPutChar(B.getInt32(FormatStr[0]), B, TLI);
Chris Bienemanad070d02014-09-17 20:55:46 +00001681 if (CI->use_empty() || !Res)
1682 return Res;
1683 return B.CreateIntCast(Res, CI->getType(), true);
Meador Inge08ca1152012-11-26 20:37:20 +00001684 }
1685
Chris Bienemanad070d02014-09-17 20:55:46 +00001686 // printf("foo\n") --> puts("foo")
1687 if (FormatStr[FormatStr.size() - 1] == '\n' &&
1688 FormatStr.find('%') == StringRef::npos) { // No format characters.
1689 // Create a string literal with no \n on it. We expect the constant merge
1690 // pass to be run after this pass, to merge duplicate strings.
1691 FormatStr = FormatStr.drop_back();
1692 Value *GV = B.CreateGlobalString(FormatStr, "str");
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001693 Value *NewCI = EmitPutS(GV, B, TLI);
Chris Bienemanad070d02014-09-17 20:55:46 +00001694 return (CI->use_empty() || !NewCI)
1695 ? NewCI
1696 : ConstantInt::get(CI->getType(), FormatStr.size() + 1);
1697 }
Meador Inge08ca1152012-11-26 20:37:20 +00001698
Chris Bienemanad070d02014-09-17 20:55:46 +00001699 // Optimize specific format strings.
1700 // printf("%c", chr) --> putchar(chr)
1701 if (FormatStr == "%c" && CI->getNumArgOperands() > 1 &&
1702 CI->getArgOperand(1)->getType()->isIntegerTy()) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001703 Value *Res = EmitPutChar(CI->getArgOperand(1), B, TLI);
Meador Inge08ca1152012-11-26 20:37:20 +00001704
Chris Bienemanad070d02014-09-17 20:55:46 +00001705 if (CI->use_empty() || !Res)
1706 return Res;
1707 return B.CreateIntCast(Res, CI->getType(), true);
1708 }
1709
1710 // printf("%s\n", str) --> puts(str)
1711 if (FormatStr == "%s\n" && CI->getNumArgOperands() > 1 &&
1712 CI->getArgOperand(1)->getType()->isPointerTy()) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001713 return EmitPutS(CI->getArgOperand(1), B, TLI);
Chris Bienemanad070d02014-09-17 20:55:46 +00001714 }
1715 return nullptr;
1716}
1717
1718Value *LibCallSimplifier::optimizePrintF(CallInst *CI, IRBuilder<> &B) {
1719
1720 Function *Callee = CI->getCalledFunction();
1721 // Require one fixed pointer argument and an integer/void result.
1722 FunctionType *FT = Callee->getFunctionType();
1723 if (FT->getNumParams() < 1 || !FT->getParamType(0)->isPointerTy() ||
1724 !(FT->getReturnType()->isIntegerTy() || FT->getReturnType()->isVoidTy()))
1725 return nullptr;
1726
1727 if (Value *V = optimizePrintFString(CI, B)) {
1728 return V;
1729 }
1730
1731 // printf(format, ...) -> iprintf(format, ...) if no floating point
1732 // arguments.
1733 if (TLI->has(LibFunc::iprintf) && !callHasFloatingPointArgument(CI)) {
1734 Module *M = B.GetInsertBlock()->getParent()->getParent();
1735 Constant *IPrintFFn =
Meador Inge08ca1152012-11-26 20:37:20 +00001736 M->getOrInsertFunction("iprintf", FT, Callee->getAttributes());
Chris Bienemanad070d02014-09-17 20:55:46 +00001737 CallInst *New = cast<CallInst>(CI->clone());
1738 New->setCalledFunction(IPrintFFn);
1739 B.Insert(New);
1740 return New;
Meador Inge08ca1152012-11-26 20:37:20 +00001741 }
Chris Bienemanad070d02014-09-17 20:55:46 +00001742 return nullptr;
1743}
Meador Inge08ca1152012-11-26 20:37:20 +00001744
Chris Bienemanad070d02014-09-17 20:55:46 +00001745Value *LibCallSimplifier::optimizeSPrintFString(CallInst *CI, IRBuilder<> &B) {
1746 // Check for a fixed format string.
1747 StringRef FormatStr;
1748 if (!getConstantStringInfo(CI->getArgOperand(1), FormatStr))
Craig Topperf40110f2014-04-25 05:29:35 +00001749 return nullptr;
Meador Inge25c9b3b2012-11-27 05:57:54 +00001750
Chris Bienemanad070d02014-09-17 20:55:46 +00001751 // If we just have a format string (nothing else crazy) transform it.
1752 if (CI->getNumArgOperands() == 2) {
1753 // Make sure there's no % in the constant array. We could try to handle
1754 // %% -> % in the future if we cared.
1755 for (unsigned i = 0, e = FormatStr.size(); i != e; ++i)
1756 if (FormatStr[i] == '%')
1757 return nullptr; // we found a format specifier, bail out.
Hal Finkel66cd3f12013-11-17 02:06:35 +00001758
Chris Bienemanad070d02014-09-17 20:55:46 +00001759 // sprintf(str, fmt) -> llvm.memcpy(str, fmt, strlen(fmt)+1, 1)
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001760 B.CreateMemCpy(CI->getArgOperand(0), CI->getArgOperand(1),
1761 ConstantInt::get(DL.getIntPtrType(CI->getContext()),
1762 FormatStr.size() + 1),
Pete Cooper67cf9a72015-11-19 05:56:52 +00001763 1); // Copy the null byte.
Chris Bienemanad070d02014-09-17 20:55:46 +00001764 return ConstantInt::get(CI->getType(), FormatStr.size());
Meador Ingef8e72502012-11-29 15:45:43 +00001765 }
Meador Ingef8e72502012-11-29 15:45:43 +00001766
Chris Bienemanad070d02014-09-17 20:55:46 +00001767 // The remaining optimizations require the format string to be "%s" or "%c"
1768 // and have an extra operand.
1769 if (FormatStr.size() != 2 || FormatStr[0] != '%' ||
1770 CI->getNumArgOperands() < 3)
Craig Topperf40110f2014-04-25 05:29:35 +00001771 return nullptr;
Meador Inge75798bb2012-11-29 19:15:17 +00001772
Chris Bienemanad070d02014-09-17 20:55:46 +00001773 // Decode the second character of the format string.
1774 if (FormatStr[1] == 'c') {
1775 // sprintf(dst, "%c", chr) --> *(i8*)dst = chr; *((i8*)dst+1) = 0
1776 if (!CI->getArgOperand(2)->getType()->isIntegerTy())
1777 return nullptr;
1778 Value *V = B.CreateTrunc(CI->getArgOperand(2), B.getInt8Ty(), "char");
1779 Value *Ptr = CastToCStr(CI->getArgOperand(0), B);
1780 B.CreateStore(V, Ptr);
David Blaikie3909da72015-03-30 20:42:56 +00001781 Ptr = B.CreateGEP(B.getInt8Ty(), Ptr, B.getInt32(1), "nul");
Chris Bienemanad070d02014-09-17 20:55:46 +00001782 B.CreateStore(B.getInt8(0), Ptr);
Meador Ingedf796f82012-10-13 16:45:24 +00001783
Chris Bienemanad070d02014-09-17 20:55:46 +00001784 return ConstantInt::get(CI->getType(), 1);
Meador Ingedf796f82012-10-13 16:45:24 +00001785 }
1786
Chris Bienemanad070d02014-09-17 20:55:46 +00001787 if (FormatStr[1] == 's') {
Chris Bienemanad070d02014-09-17 20:55:46 +00001788 // sprintf(dest, "%s", str) -> llvm.memcpy(dest, str, strlen(str)+1, 1)
1789 if (!CI->getArgOperand(2)->getType()->isPointerTy())
1790 return nullptr;
1791
1792 Value *Len = EmitStrLen(CI->getArgOperand(2), B, DL, TLI);
1793 if (!Len)
1794 return nullptr;
1795 Value *IncLen =
1796 B.CreateAdd(Len, ConstantInt::get(Len->getType(), 1), "leninc");
Pete Cooper67cf9a72015-11-19 05:56:52 +00001797 B.CreateMemCpy(CI->getArgOperand(0), CI->getArgOperand(2), IncLen, 1);
Chris Bienemanad070d02014-09-17 20:55:46 +00001798
1799 // The sprintf result is the unincremented number of bytes in the string.
1800 return B.CreateIntCast(Len, CI->getType(), false);
1801 }
1802 return nullptr;
1803}
1804
1805Value *LibCallSimplifier::optimizeSPrintF(CallInst *CI, IRBuilder<> &B) {
1806 Function *Callee = CI->getCalledFunction();
1807 // Require two fixed pointer arguments and an integer result.
1808 FunctionType *FT = Callee->getFunctionType();
1809 if (FT->getNumParams() != 2 || !FT->getParamType(0)->isPointerTy() ||
1810 !FT->getParamType(1)->isPointerTy() ||
1811 !FT->getReturnType()->isIntegerTy())
1812 return nullptr;
1813
1814 if (Value *V = optimizeSPrintFString(CI, B)) {
1815 return V;
1816 }
1817
1818 // sprintf(str, format, ...) -> siprintf(str, format, ...) if no floating
1819 // point arguments.
1820 if (TLI->has(LibFunc::siprintf) && !callHasFloatingPointArgument(CI)) {
1821 Module *M = B.GetInsertBlock()->getParent()->getParent();
1822 Constant *SIPrintFFn =
1823 M->getOrInsertFunction("siprintf", FT, Callee->getAttributes());
1824 CallInst *New = cast<CallInst>(CI->clone());
1825 New->setCalledFunction(SIPrintFFn);
1826 B.Insert(New);
1827 return New;
1828 }
1829 return nullptr;
1830}
1831
1832Value *LibCallSimplifier::optimizeFPrintFString(CallInst *CI, IRBuilder<> &B) {
1833 optimizeErrorReporting(CI, B, 0);
1834
1835 // All the optimizations depend on the format string.
1836 StringRef FormatStr;
1837 if (!getConstantStringInfo(CI->getArgOperand(1), FormatStr))
1838 return nullptr;
1839
1840 // Do not do any of the following transformations if the fprintf return
1841 // value is used, in general the fprintf return value is not compatible
1842 // with fwrite(), fputc() or fputs().
1843 if (!CI->use_empty())
1844 return nullptr;
1845
1846 // fprintf(F, "foo") --> fwrite("foo", 3, 1, F)
1847 if (CI->getNumArgOperands() == 2) {
1848 for (unsigned i = 0, e = FormatStr.size(); i != e; ++i)
1849 if (FormatStr[i] == '%') // Could handle %% -> % if we cared.
1850 return nullptr; // We found a format specifier.
1851
Chris Bienemanad070d02014-09-17 20:55:46 +00001852 return EmitFWrite(
1853 CI->getArgOperand(1),
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001854 ConstantInt::get(DL.getIntPtrType(CI->getContext()), FormatStr.size()),
Chris Bienemanad070d02014-09-17 20:55:46 +00001855 CI->getArgOperand(0), B, DL, TLI);
1856 }
1857
1858 // The remaining optimizations require the format string to be "%s" or "%c"
1859 // and have an extra operand.
1860 if (FormatStr.size() != 2 || FormatStr[0] != '%' ||
1861 CI->getNumArgOperands() < 3)
1862 return nullptr;
1863
1864 // Decode the second character of the format string.
1865 if (FormatStr[1] == 'c') {
1866 // fprintf(F, "%c", chr) --> fputc(chr, F)
1867 if (!CI->getArgOperand(2)->getType()->isIntegerTy())
1868 return nullptr;
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001869 return EmitFPutC(CI->getArgOperand(2), CI->getArgOperand(0), B, TLI);
Chris Bienemanad070d02014-09-17 20:55:46 +00001870 }
1871
1872 if (FormatStr[1] == 's') {
1873 // fprintf(F, "%s", str) --> fputs(str, F)
1874 if (!CI->getArgOperand(2)->getType()->isPointerTy())
1875 return nullptr;
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001876 return EmitFPutS(CI->getArgOperand(2), CI->getArgOperand(0), B, TLI);
Chris Bienemanad070d02014-09-17 20:55:46 +00001877 }
1878 return nullptr;
1879}
1880
1881Value *LibCallSimplifier::optimizeFPrintF(CallInst *CI, IRBuilder<> &B) {
1882 Function *Callee = CI->getCalledFunction();
1883 // Require two fixed paramters as pointers and integer result.
1884 FunctionType *FT = Callee->getFunctionType();
1885 if (FT->getNumParams() != 2 || !FT->getParamType(0)->isPointerTy() ||
1886 !FT->getParamType(1)->isPointerTy() ||
1887 !FT->getReturnType()->isIntegerTy())
1888 return nullptr;
1889
1890 if (Value *V = optimizeFPrintFString(CI, B)) {
1891 return V;
1892 }
1893
1894 // fprintf(stream, format, ...) -> fiprintf(stream, format, ...) if no
1895 // floating point arguments.
1896 if (TLI->has(LibFunc::fiprintf) && !callHasFloatingPointArgument(CI)) {
1897 Module *M = B.GetInsertBlock()->getParent()->getParent();
1898 Constant *FIPrintFFn =
1899 M->getOrInsertFunction("fiprintf", FT, Callee->getAttributes());
1900 CallInst *New = cast<CallInst>(CI->clone());
1901 New->setCalledFunction(FIPrintFFn);
1902 B.Insert(New);
1903 return New;
1904 }
1905 return nullptr;
1906}
1907
1908Value *LibCallSimplifier::optimizeFWrite(CallInst *CI, IRBuilder<> &B) {
1909 optimizeErrorReporting(CI, B, 3);
1910
1911 Function *Callee = CI->getCalledFunction();
1912 // Require a pointer, an integer, an integer, a pointer, returning integer.
1913 FunctionType *FT = Callee->getFunctionType();
1914 if (FT->getNumParams() != 4 || !FT->getParamType(0)->isPointerTy() ||
1915 !FT->getParamType(1)->isIntegerTy() ||
1916 !FT->getParamType(2)->isIntegerTy() ||
1917 !FT->getParamType(3)->isPointerTy() ||
1918 !FT->getReturnType()->isIntegerTy())
1919 return nullptr;
1920
1921 // Get the element size and count.
1922 ConstantInt *SizeC = dyn_cast<ConstantInt>(CI->getArgOperand(1));
1923 ConstantInt *CountC = dyn_cast<ConstantInt>(CI->getArgOperand(2));
1924 if (!SizeC || !CountC)
1925 return nullptr;
1926 uint64_t Bytes = SizeC->getZExtValue() * CountC->getZExtValue();
1927
1928 // If this is writing zero records, remove the call (it's a noop).
1929 if (Bytes == 0)
1930 return ConstantInt::get(CI->getType(), 0);
1931
1932 // If this is writing one byte, turn it into fputc.
1933 // This optimisation is only valid, if the return value is unused.
1934 if (Bytes == 1 && CI->use_empty()) { // fwrite(S,1,1,F) -> fputc(S[0],F)
1935 Value *Char = B.CreateLoad(CastToCStr(CI->getArgOperand(0), B), "char");
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001936 Value *NewCI = EmitFPutC(Char, CI->getArgOperand(3), B, TLI);
Chris Bienemanad070d02014-09-17 20:55:46 +00001937 return NewCI ? ConstantInt::get(CI->getType(), 1) : nullptr;
1938 }
1939
1940 return nullptr;
1941}
1942
1943Value *LibCallSimplifier::optimizeFPuts(CallInst *CI, IRBuilder<> &B) {
1944 optimizeErrorReporting(CI, B, 1);
1945
1946 Function *Callee = CI->getCalledFunction();
1947
Chris Bienemanad070d02014-09-17 20:55:46 +00001948 // Require two pointers. Also, we can't optimize if return value is used.
1949 FunctionType *FT = Callee->getFunctionType();
1950 if (FT->getNumParams() != 2 || !FT->getParamType(0)->isPointerTy() ||
1951 !FT->getParamType(1)->isPointerTy() || !CI->use_empty())
1952 return nullptr;
1953
1954 // fputs(s,F) --> fwrite(s,1,strlen(s),F)
1955 uint64_t Len = GetStringLength(CI->getArgOperand(0));
1956 if (!Len)
1957 return nullptr;
1958
1959 // Known to have no uses (see above).
1960 return EmitFWrite(
1961 CI->getArgOperand(0),
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001962 ConstantInt::get(DL.getIntPtrType(CI->getContext()), Len - 1),
Chris Bienemanad070d02014-09-17 20:55:46 +00001963 CI->getArgOperand(1), B, DL, TLI);
1964}
1965
1966Value *LibCallSimplifier::optimizePuts(CallInst *CI, IRBuilder<> &B) {
1967 Function *Callee = CI->getCalledFunction();
1968 // Require one fixed pointer argument and an integer/void result.
1969 FunctionType *FT = Callee->getFunctionType();
1970 if (FT->getNumParams() < 1 || !FT->getParamType(0)->isPointerTy() ||
1971 !(FT->getReturnType()->isIntegerTy() || FT->getReturnType()->isVoidTy()))
1972 return nullptr;
1973
1974 // Check for a constant string.
1975 StringRef Str;
1976 if (!getConstantStringInfo(CI->getArgOperand(0), Str))
1977 return nullptr;
1978
1979 if (Str.empty() && CI->use_empty()) {
1980 // puts("") -> putchar('\n')
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001981 Value *Res = EmitPutChar(B.getInt32('\n'), B, TLI);
Chris Bienemanad070d02014-09-17 20:55:46 +00001982 if (CI->use_empty() || !Res)
1983 return Res;
1984 return B.CreateIntCast(Res, CI->getType(), true);
1985 }
1986
1987 return nullptr;
1988}
1989
1990bool LibCallSimplifier::hasFloatVersion(StringRef FuncName) {
Meador Inge20255ef2013-03-12 00:08:29 +00001991 LibFunc::Func Func;
1992 SmallString<20> FloatFuncName = FuncName;
1993 FloatFuncName += 'f';
1994 if (TLI->getLibFunc(FloatFuncName, Func))
1995 return TLI->has(Func);
1996 return false;
1997}
Meador Inge7fb2f732012-10-13 16:45:32 +00001998
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00001999Value *LibCallSimplifier::optimizeStringMemoryLibCall(CallInst *CI,
2000 IRBuilder<> &Builder) {
2001 LibFunc::Func Func;
2002 Function *Callee = CI->getCalledFunction();
2003 StringRef FuncName = Callee->getName();
2004
2005 // Check for string/memory library functions.
2006 if (TLI->getLibFunc(FuncName, Func) && TLI->has(Func)) {
2007 // Make sure we never change the calling convention.
2008 assert((ignoreCallingConv(Func) ||
2009 CI->getCallingConv() == llvm::CallingConv::C) &&
2010 "Optimizing string/memory libcall would change the calling convention");
2011 switch (Func) {
2012 case LibFunc::strcat:
2013 return optimizeStrCat(CI, Builder);
2014 case LibFunc::strncat:
2015 return optimizeStrNCat(CI, Builder);
2016 case LibFunc::strchr:
2017 return optimizeStrChr(CI, Builder);
2018 case LibFunc::strrchr:
2019 return optimizeStrRChr(CI, Builder);
2020 case LibFunc::strcmp:
2021 return optimizeStrCmp(CI, Builder);
2022 case LibFunc::strncmp:
2023 return optimizeStrNCmp(CI, Builder);
2024 case LibFunc::strcpy:
2025 return optimizeStrCpy(CI, Builder);
2026 case LibFunc::stpcpy:
2027 return optimizeStpCpy(CI, Builder);
2028 case LibFunc::strncpy:
2029 return optimizeStrNCpy(CI, Builder);
2030 case LibFunc::strlen:
2031 return optimizeStrLen(CI, Builder);
2032 case LibFunc::strpbrk:
2033 return optimizeStrPBrk(CI, Builder);
2034 case LibFunc::strtol:
2035 case LibFunc::strtod:
2036 case LibFunc::strtof:
2037 case LibFunc::strtoul:
2038 case LibFunc::strtoll:
2039 case LibFunc::strtold:
2040 case LibFunc::strtoull:
2041 return optimizeStrTo(CI, Builder);
2042 case LibFunc::strspn:
2043 return optimizeStrSpn(CI, Builder);
2044 case LibFunc::strcspn:
2045 return optimizeStrCSpn(CI, Builder);
2046 case LibFunc::strstr:
2047 return optimizeStrStr(CI, Builder);
Benjamin Kramer691363e2015-03-21 15:36:21 +00002048 case LibFunc::memchr:
2049 return optimizeMemChr(CI, Builder);
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00002050 case LibFunc::memcmp:
2051 return optimizeMemCmp(CI, Builder);
2052 case LibFunc::memcpy:
2053 return optimizeMemCpy(CI, Builder);
2054 case LibFunc::memmove:
2055 return optimizeMemMove(CI, Builder);
2056 case LibFunc::memset:
2057 return optimizeMemSet(CI, Builder);
2058 default:
2059 break;
2060 }
2061 }
2062 return nullptr;
2063}
2064
Chris Bienemanad070d02014-09-17 20:55:46 +00002065Value *LibCallSimplifier::optimizeCall(CallInst *CI) {
2066 if (CI->isNoBuiltin())
2067 return nullptr;
Meador Inge4d2827c2012-11-11 05:11:20 +00002068
Meador Inge20255ef2013-03-12 00:08:29 +00002069 LibFunc::Func Func;
2070 Function *Callee = CI->getCalledFunction();
2071 StringRef FuncName = Callee->getName();
Chris Bienemanad070d02014-09-17 20:55:46 +00002072 IRBuilder<> Builder(CI);
2073 bool isCallingConvC = CI->getCallingConv() == llvm::CallingConv::C;
Meador Inge20255ef2013-03-12 00:08:29 +00002074
Sanjay Patela92fa442014-10-22 15:29:23 +00002075 // Command-line parameter overrides function attribute.
2076 if (EnableUnsafeFPShrink.getNumOccurrences() > 0)
2077 UnsafeFPShrink = EnableUnsafeFPShrink;
Davide Italianoa904e522015-10-29 02:58:44 +00002078 else if (canUseUnsafeFPMath(Callee))
2079 UnsafeFPShrink = true;
Sanjay Patela92fa442014-10-22 15:29:23 +00002080
Sanjay Patel848309d2014-10-23 21:52:45 +00002081 // First, check for intrinsics.
Meador Inge20255ef2013-03-12 00:08:29 +00002082 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(CI)) {
Chris Bienemanad070d02014-09-17 20:55:46 +00002083 if (!isCallingConvC)
2084 return nullptr;
Meador Inge20255ef2013-03-12 00:08:29 +00002085 switch (II->getIntrinsicID()) {
2086 case Intrinsic::pow:
Chris Bienemanad070d02014-09-17 20:55:46 +00002087 return optimizePow(CI, Builder);
Meador Inge20255ef2013-03-12 00:08:29 +00002088 case Intrinsic::exp2:
Chris Bienemanad070d02014-09-17 20:55:46 +00002089 return optimizeExp2(CI, Builder);
Sanjay Patel0ca42bb2014-10-14 20:43:11 +00002090 case Intrinsic::fabs:
2091 return optimizeFabs(CI, Builder);
Sanjay Patelc699a612014-10-16 18:48:17 +00002092 case Intrinsic::sqrt:
2093 return optimizeSqrt(CI, Builder);
Meador Inge20255ef2013-03-12 00:08:29 +00002094 default:
Chris Bienemanad070d02014-09-17 20:55:46 +00002095 return nullptr;
Meador Inge20255ef2013-03-12 00:08:29 +00002096 }
2097 }
2098
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002099 // Also try to simplify calls to fortified library functions.
2100 if (Value *SimplifiedFortifiedCI = FortifiedSimplifier.optimizeCall(CI)) {
2101 // Try to further simplify the result.
Ahmed Bougacha71d7b182015-01-14 00:55:05 +00002102 CallInst *SimplifiedCI = dyn_cast<CallInst>(SimplifiedFortifiedCI);
Bruno Cardoso Lopesb491a2d2015-10-01 22:43:53 +00002103 if (SimplifiedCI && SimplifiedCI->getCalledFunction()) {
2104 // Use an IR Builder from SimplifiedCI if available instead of CI
2105 // to guarantee we reach all uses we might replace later on.
2106 IRBuilder<> TmpBuilder(SimplifiedCI);
2107 if (Value *V = optimizeStringMemoryLibCall(SimplifiedCI, TmpBuilder)) {
Ahmed Bougacha1ac93562015-01-27 21:52:16 +00002108 // If we were able to further simplify, remove the now redundant call.
2109 SimplifiedCI->replaceAllUsesWith(V);
2110 SimplifiedCI->eraseFromParent();
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002111 return V;
Ahmed Bougacha1ac93562015-01-27 21:52:16 +00002112 }
Bruno Cardoso Lopesb491a2d2015-10-01 22:43:53 +00002113 }
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002114 return SimplifiedFortifiedCI;
2115 }
2116
Meador Inge20255ef2013-03-12 00:08:29 +00002117 // Then check for known library functions.
2118 if (TLI->getLibFunc(FuncName, Func) && TLI->has(Func)) {
Chris Bienemanad070d02014-09-17 20:55:46 +00002119 // We never change the calling convention.
2120 if (!ignoreCallingConv(Func) && !isCallingConvC)
2121 return nullptr;
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00002122 if (Value *V = optimizeStringMemoryLibCall(CI, Builder))
2123 return V;
Meador Inge20255ef2013-03-12 00:08:29 +00002124 switch (Func) {
Chris Bienemanad070d02014-09-17 20:55:46 +00002125 case LibFunc::cosf:
2126 case LibFunc::cos:
2127 case LibFunc::cosl:
2128 return optimizeCos(CI, Builder);
2129 case LibFunc::sinpif:
2130 case LibFunc::sinpi:
2131 case LibFunc::cospif:
2132 case LibFunc::cospi:
2133 return optimizeSinCosPi(CI, Builder);
2134 case LibFunc::powf:
2135 case LibFunc::pow:
2136 case LibFunc::powl:
2137 return optimizePow(CI, Builder);
2138 case LibFunc::exp2l:
2139 case LibFunc::exp2:
2140 case LibFunc::exp2f:
2141 return optimizeExp2(CI, Builder);
Sanjay Patel0ca42bb2014-10-14 20:43:11 +00002142 case LibFunc::fabsf:
2143 case LibFunc::fabs:
2144 case LibFunc::fabsl:
2145 return optimizeFabs(CI, Builder);
Sanjay Patelc699a612014-10-16 18:48:17 +00002146 case LibFunc::sqrtf:
2147 case LibFunc::sqrt:
2148 case LibFunc::sqrtl:
2149 return optimizeSqrt(CI, Builder);
Chris Bienemanad070d02014-09-17 20:55:46 +00002150 case LibFunc::ffs:
2151 case LibFunc::ffsl:
2152 case LibFunc::ffsll:
2153 return optimizeFFS(CI, Builder);
2154 case LibFunc::abs:
2155 case LibFunc::labs:
2156 case LibFunc::llabs:
2157 return optimizeAbs(CI, Builder);
2158 case LibFunc::isdigit:
2159 return optimizeIsDigit(CI, Builder);
2160 case LibFunc::isascii:
2161 return optimizeIsAscii(CI, Builder);
2162 case LibFunc::toascii:
2163 return optimizeToAscii(CI, Builder);
2164 case LibFunc::printf:
2165 return optimizePrintF(CI, Builder);
2166 case LibFunc::sprintf:
2167 return optimizeSPrintF(CI, Builder);
2168 case LibFunc::fprintf:
2169 return optimizeFPrintF(CI, Builder);
2170 case LibFunc::fwrite:
2171 return optimizeFWrite(CI, Builder);
2172 case LibFunc::fputs:
2173 return optimizeFPuts(CI, Builder);
2174 case LibFunc::puts:
2175 return optimizePuts(CI, Builder);
Davide Italiano51507d22015-11-04 23:36:56 +00002176 case LibFunc::tan:
2177 case LibFunc::tanf:
2178 case LibFunc::tanl:
2179 return optimizeTan(CI, Builder);
Chris Bienemanad070d02014-09-17 20:55:46 +00002180 case LibFunc::perror:
2181 return optimizeErrorReporting(CI, Builder);
2182 case LibFunc::vfprintf:
2183 case LibFunc::fiprintf:
2184 return optimizeErrorReporting(CI, Builder, 0);
2185 case LibFunc::fputc:
2186 return optimizeErrorReporting(CI, Builder, 1);
2187 case LibFunc::ceil:
Chris Bienemanad070d02014-09-17 20:55:46 +00002188 case LibFunc::floor:
2189 case LibFunc::rint:
2190 case LibFunc::round:
2191 case LibFunc::nearbyint:
2192 case LibFunc::trunc:
2193 if (hasFloatVersion(FuncName))
2194 return optimizeUnaryDoubleFP(CI, Builder, false);
2195 return nullptr;
2196 case LibFunc::acos:
2197 case LibFunc::acosh:
2198 case LibFunc::asin:
2199 case LibFunc::asinh:
2200 case LibFunc::atan:
2201 case LibFunc::atanh:
2202 case LibFunc::cbrt:
2203 case LibFunc::cosh:
2204 case LibFunc::exp:
2205 case LibFunc::exp10:
2206 case LibFunc::expm1:
2207 case LibFunc::log:
2208 case LibFunc::log10:
2209 case LibFunc::log1p:
2210 case LibFunc::log2:
2211 case LibFunc::logb:
2212 case LibFunc::sin:
2213 case LibFunc::sinh:
Chris Bienemanad070d02014-09-17 20:55:46 +00002214 case LibFunc::tanh:
2215 if (UnsafeFPShrink && hasFloatVersion(FuncName))
2216 return optimizeUnaryDoubleFP(CI, Builder, true);
2217 return nullptr;
Matthias Braun892c9232014-12-03 21:46:29 +00002218 case LibFunc::copysign:
Chris Bienemanad070d02014-09-17 20:55:46 +00002219 if (hasFloatVersion(FuncName))
2220 return optimizeBinaryDoubleFP(CI, Builder);
2221 return nullptr;
Sanjay Patel57fd1dc2015-08-16 20:18:19 +00002222 case LibFunc::fminf:
2223 case LibFunc::fmin:
2224 case LibFunc::fminl:
2225 case LibFunc::fmaxf:
2226 case LibFunc::fmax:
2227 case LibFunc::fmaxl:
2228 return optimizeFMinFMax(CI, Builder);
Chris Bienemanad070d02014-09-17 20:55:46 +00002229 default:
2230 return nullptr;
2231 }
Meador Inge20255ef2013-03-12 00:08:29 +00002232 }
Craig Topperf40110f2014-04-25 05:29:35 +00002233 return nullptr;
Meador Ingedf796f82012-10-13 16:45:24 +00002234}
2235
Chandler Carruth92803822015-01-21 02:11:59 +00002236LibCallSimplifier::LibCallSimplifier(
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002237 const DataLayout &DL, const TargetLibraryInfo *TLI,
Chandler Carruth92803822015-01-21 02:11:59 +00002238 function_ref<void(Instruction *, Value *)> Replacer)
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002239 : FortifiedSimplifier(TLI), DL(DL), TLI(TLI), UnsafeFPShrink(false),
Chandler Carruth92803822015-01-21 02:11:59 +00002240 Replacer(Replacer) {}
2241
2242void LibCallSimplifier::replaceAllUsesWith(Instruction *I, Value *With) {
2243 // Indirect through the replacer used in this instance.
2244 Replacer(I, With);
Meador Ingedf796f82012-10-13 16:45:24 +00002245}
2246
Meador Ingedfb08a22013-06-20 19:48:07 +00002247// TODO:
2248// Additional cases that we need to add to this file:
2249//
2250// cbrt:
2251// * cbrt(expN(X)) -> expN(x/3)
2252// * cbrt(sqrt(x)) -> pow(x,1/6)
David Majnemer3354fe42015-08-26 18:30:16 +00002253// * cbrt(cbrt(x)) -> pow(x,1/9)
Meador Ingedfb08a22013-06-20 19:48:07 +00002254//
2255// exp, expf, expl:
2256// * exp(log(x)) -> x
2257//
2258// log, logf, logl:
2259// * log(exp(x)) -> x
2260// * log(x**y) -> y*log(x)
2261// * log(exp(y)) -> y*log(e)
2262// * log(exp2(y)) -> y*log(2)
2263// * log(exp10(y)) -> y*log(10)
2264// * log(sqrt(x)) -> 0.5*log(x)
2265// * log(pow(x,y)) -> y*log(x)
2266//
2267// lround, lroundf, lroundl:
2268// * lround(cnst) -> cnst'
2269//
2270// pow, powf, powl:
Meador Ingedfb08a22013-06-20 19:48:07 +00002271// * pow(sqrt(x),y) -> pow(x,y*0.5)
2272// * pow(pow(x,y),z)-> pow(x,y*z)
2273//
2274// round, roundf, roundl:
2275// * round(cnst) -> cnst'
2276//
2277// signbit:
2278// * signbit(cnst) -> cnst'
2279// * signbit(nncst) -> 0 (if pstv is a non-negative constant)
2280//
2281// sqrt, sqrtf, sqrtl:
2282// * sqrt(expN(x)) -> expN(x*0.5)
2283// * sqrt(Nroot(x)) -> pow(x,1/(2*N))
2284// * sqrt(pow(x,y)) -> pow(|x|,y*0.5)
2285//
Meador Ingedfb08a22013-06-20 19:48:07 +00002286// trunc, truncf, truncl:
2287// * trunc(cnst) -> cnst'
2288//
2289//
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002290
2291//===----------------------------------------------------------------------===//
2292// Fortified Library Call Optimizations
2293//===----------------------------------------------------------------------===//
2294
2295bool FortifiedLibCallSimplifier::isFortifiedCallFoldable(CallInst *CI,
2296 unsigned ObjSizeOp,
2297 unsigned SizeOp,
2298 bool isString) {
2299 if (CI->getArgOperand(ObjSizeOp) == CI->getArgOperand(SizeOp))
2300 return true;
2301 if (ConstantInt *ObjSizeCI =
2302 dyn_cast<ConstantInt>(CI->getArgOperand(ObjSizeOp))) {
2303 if (ObjSizeCI->isAllOnesValue())
2304 return true;
2305 // If the object size wasn't -1 (unknown), bail out if we were asked to.
2306 if (OnlyLowerUnknownSize)
2307 return false;
2308 if (isString) {
2309 uint64_t Len = GetStringLength(CI->getArgOperand(SizeOp));
2310 // If the length is 0 we don't know how long it is and so we can't
2311 // remove the check.
2312 if (Len == 0)
2313 return false;
2314 return ObjSizeCI->getZExtValue() >= Len;
2315 }
2316 if (ConstantInt *SizeCI = dyn_cast<ConstantInt>(CI->getArgOperand(SizeOp)))
2317 return ObjSizeCI->getZExtValue() >= SizeCI->getZExtValue();
2318 }
2319 return false;
2320}
2321
2322Value *FortifiedLibCallSimplifier::optimizeMemCpyChk(CallInst *CI, IRBuilder<> &B) {
2323 Function *Callee = CI->getCalledFunction();
2324
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002325 if (!checkStringCopyLibFuncSignature(Callee, LibFunc::memcpy_chk))
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002326 return nullptr;
2327
2328 if (isFortifiedCallFoldable(CI, 3, 2, false)) {
2329 B.CreateMemCpy(CI->getArgOperand(0), CI->getArgOperand(1),
Pete Cooper67cf9a72015-11-19 05:56:52 +00002330 CI->getArgOperand(2), 1);
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002331 return CI->getArgOperand(0);
2332 }
2333 return nullptr;
2334}
2335
2336Value *FortifiedLibCallSimplifier::optimizeMemMoveChk(CallInst *CI, IRBuilder<> &B) {
2337 Function *Callee = CI->getCalledFunction();
2338
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002339 if (!checkStringCopyLibFuncSignature(Callee, LibFunc::memmove_chk))
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002340 return nullptr;
2341
2342 if (isFortifiedCallFoldable(CI, 3, 2, false)) {
2343 B.CreateMemMove(CI->getArgOperand(0), CI->getArgOperand(1),
Pete Cooper67cf9a72015-11-19 05:56:52 +00002344 CI->getArgOperand(2), 1);
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002345 return CI->getArgOperand(0);
2346 }
2347 return nullptr;
2348}
2349
2350Value *FortifiedLibCallSimplifier::optimizeMemSetChk(CallInst *CI, IRBuilder<> &B) {
2351 Function *Callee = CI->getCalledFunction();
2352
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002353 if (!checkStringCopyLibFuncSignature(Callee, LibFunc::memset_chk))
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002354 return nullptr;
2355
2356 if (isFortifiedCallFoldable(CI, 3, 2, false)) {
2357 Value *Val = B.CreateIntCast(CI->getArgOperand(1), B.getInt8Ty(), false);
2358 B.CreateMemSet(CI->getArgOperand(0), Val, CI->getArgOperand(2), 1);
2359 return CI->getArgOperand(0);
2360 }
2361 return nullptr;
2362}
2363
Ahmed Bougacha1ac93562015-01-27 21:52:16 +00002364Value *FortifiedLibCallSimplifier::optimizeStrpCpyChk(CallInst *CI,
2365 IRBuilder<> &B,
2366 LibFunc::Func Func) {
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002367 Function *Callee = CI->getCalledFunction();
2368 StringRef Name = Callee->getName();
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002369 const DataLayout &DL = CI->getModule()->getDataLayout();
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002370
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002371 if (!checkStringCopyLibFuncSignature(Callee, Func))
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002372 return nullptr;
2373
2374 Value *Dst = CI->getArgOperand(0), *Src = CI->getArgOperand(1),
2375 *ObjSize = CI->getArgOperand(2);
2376
2377 // __stpcpy_chk(x,x,...) -> x+strlen(x)
Ahmed Bougacha1ac93562015-01-27 21:52:16 +00002378 if (Func == LibFunc::stpcpy_chk && !OnlyLowerUnknownSize && Dst == Src) {
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002379 Value *StrLen = EmitStrLen(Src, B, DL, TLI);
David Blaikieaa41cd52015-04-03 21:33:42 +00002380 return StrLen ? B.CreateInBoundsGEP(B.getInt8Ty(), Dst, StrLen) : nullptr;
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002381 }
2382
2383 // If a) we don't have any length information, or b) we know this will
2384 // fit then just lower to a plain st[rp]cpy. Otherwise we'll keep our
2385 // st[rp]cpy_chk call which may fail at runtime if the size is too long.
2386 // TODO: It might be nice to get a maximum length out of the possible
2387 // string lengths for varying.
David Blaikie65fab6d2015-04-03 21:32:06 +00002388 if (isFortifiedCallFoldable(CI, 2, 1, true))
2389 return EmitStrCpy(Dst, Src, B, TLI, Name.substr(2, 6));
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002390
David Blaikie65fab6d2015-04-03 21:32:06 +00002391 if (OnlyLowerUnknownSize)
2392 return nullptr;
2393
2394 // Maybe we can stil fold __st[rp]cpy_chk to __memcpy_chk.
2395 uint64_t Len = GetStringLength(Src);
2396 if (Len == 0)
2397 return nullptr;
2398
2399 Type *SizeTTy = DL.getIntPtrType(CI->getContext());
2400 Value *LenV = ConstantInt::get(SizeTTy, Len);
2401 Value *Ret = EmitMemCpyChk(Dst, Src, LenV, ObjSize, B, DL, TLI);
2402 // If the function was an __stpcpy_chk, and we were able to fold it into
2403 // a __memcpy_chk, we still need to return the correct end pointer.
2404 if (Ret && Func == LibFunc::stpcpy_chk)
2405 return B.CreateGEP(B.getInt8Ty(), Dst, ConstantInt::get(SizeTTy, Len - 1));
2406 return Ret;
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002407}
2408
Ahmed Bougacha1ac93562015-01-27 21:52:16 +00002409Value *FortifiedLibCallSimplifier::optimizeStrpNCpyChk(CallInst *CI,
2410 IRBuilder<> &B,
2411 LibFunc::Func Func) {
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002412 Function *Callee = CI->getCalledFunction();
2413 StringRef Name = Callee->getName();
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002414
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002415 if (!checkStringCopyLibFuncSignature(Callee, Func))
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002416 return nullptr;
2417 if (isFortifiedCallFoldable(CI, 3, 2, false)) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002418 Value *Ret = EmitStrNCpy(CI->getArgOperand(0), CI->getArgOperand(1),
2419 CI->getArgOperand(2), B, TLI, Name.substr(2, 7));
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002420 return Ret;
2421 }
2422 return nullptr;
2423}
2424
2425Value *FortifiedLibCallSimplifier::optimizeCall(CallInst *CI) {
Ahmed Bougacha408d0102015-04-01 00:45:09 +00002426 // FIXME: We shouldn't be changing "nobuiltin" or TLI unavailable calls here.
2427 // Some clang users checked for _chk libcall availability using:
2428 // __has_builtin(__builtin___memcpy_chk)
2429 // When compiling with -fno-builtin, this is always true.
2430 // When passing -ffreestanding/-mkernel, which both imply -fno-builtin, we
2431 // end up with fortified libcalls, which isn't acceptable in a freestanding
2432 // environment which only provides their non-fortified counterparts.
2433 //
2434 // Until we change clang and/or teach external users to check for availability
2435 // differently, disregard the "nobuiltin" attribute and TLI::has.
2436 //
2437 // PR23093.
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002438
2439 LibFunc::Func Func;
2440 Function *Callee = CI->getCalledFunction();
2441 StringRef FuncName = Callee->getName();
2442 IRBuilder<> Builder(CI);
2443 bool isCallingConvC = CI->getCallingConv() == llvm::CallingConv::C;
2444
2445 // First, check that this is a known library functions.
Ahmed Bougacha408d0102015-04-01 00:45:09 +00002446 if (!TLI->getLibFunc(FuncName, Func))
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002447 return nullptr;
2448
2449 // We never change the calling convention.
2450 if (!ignoreCallingConv(Func) && !isCallingConvC)
2451 return nullptr;
2452
2453 switch (Func) {
2454 case LibFunc::memcpy_chk:
2455 return optimizeMemCpyChk(CI, Builder);
2456 case LibFunc::memmove_chk:
2457 return optimizeMemMoveChk(CI, Builder);
2458 case LibFunc::memset_chk:
2459 return optimizeMemSetChk(CI, Builder);
2460 case LibFunc::stpcpy_chk:
2461 case LibFunc::strcpy_chk:
Ahmed Bougacha1ac93562015-01-27 21:52:16 +00002462 return optimizeStrpCpyChk(CI, Builder, Func);
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002463 case LibFunc::stpncpy_chk:
2464 case LibFunc::strncpy_chk:
Ahmed Bougacha1ac93562015-01-27 21:52:16 +00002465 return optimizeStrpNCpyChk(CI, Builder, Func);
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002466 default:
2467 break;
2468 }
2469 return nullptr;
2470}
2471
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002472FortifiedLibCallSimplifier::FortifiedLibCallSimplifier(
2473 const TargetLibraryInfo *TLI, bool OnlyLowerUnknownSize)
2474 : TLI(TLI), OnlyLowerUnknownSize(OnlyLowerUnknownSize) {}