blob: de9fb7c524fdd7f99c41df6bbc3b5023fce260d0 [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
Sanjay Pateld707db92015-12-31 16:10:49 +000060/// Return true if it only matters that the value is equal or not-equal to zero.
Meador Inged589ac62012-10-31 03:33:06 +000061static bool isOnlyUsedInZeroEqualityComparison(Value *V) {
Chandler Carruthcdf47882014-03-09 03:16:01 +000062 for (User *U : V->users()) {
63 if (ICmpInst *IC = dyn_cast<ICmpInst>(U))
Meador Inged589ac62012-10-31 03:33:06 +000064 if (IC->isEquality())
65 if (Constant *C = dyn_cast<Constant>(IC->getOperand(1)))
66 if (C->isNullValue())
67 continue;
68 // Unknown instruction.
69 return false;
70 }
71 return true;
72}
73
Sanjay Pateld707db92015-12-31 16:10:49 +000074/// Return true if it is only used in equality comparisons with With.
Meador Inge56edbc92012-11-11 03:51:48 +000075static bool isOnlyUsedInEqualityComparison(Value *V, Value *With) {
Chandler Carruthcdf47882014-03-09 03:16:01 +000076 for (User *U : V->users()) {
77 if (ICmpInst *IC = dyn_cast<ICmpInst>(U))
Meador Inge56edbc92012-11-11 03:51:48 +000078 if (IC->isEquality() && IC->getOperand(1) == With)
79 continue;
80 // Unknown instruction.
81 return false;
82 }
83 return true;
84}
85
Meador Inge08ca1152012-11-26 20:37:20 +000086static bool callHasFloatingPointArgument(const CallInst *CI) {
Davide Italianoda3beeb2015-11-28 22:27:48 +000087 return std::any_of(CI->op_begin(), CI->op_end(), [](const Use &OI) {
88 return OI->getType()->isFloatingPointTy();
89 });
Meador Inge08ca1152012-11-26 20:37:20 +000090}
91
Benjamin Kramer2702caa2013-08-31 18:19:35 +000092/// \brief Check whether the overloaded unary floating point function
Sanjay Patele24c60e2015-08-12 20:36:18 +000093/// corresponding to \a Ty is available.
Benjamin Kramer2702caa2013-08-31 18:19:35 +000094static bool hasUnaryFloatFn(const TargetLibraryInfo *TLI, Type *Ty,
95 LibFunc::Func DoubleFn, LibFunc::Func FloatFn,
96 LibFunc::Func LongDoubleFn) {
97 switch (Ty->getTypeID()) {
98 case Type::FloatTyID:
99 return TLI->has(FloatFn);
100 case Type::DoubleTyID:
101 return TLI->has(DoubleFn);
102 default:
103 return TLI->has(LongDoubleFn);
104 }
105}
106
Davide Italianoa904e522015-10-29 02:58:44 +0000107/// \brief Check whether we can use unsafe floating point math for
108/// the function passed as input.
109static bool canUseUnsafeFPMath(Function *F) {
110
111 // FIXME: For finer-grain optimization, we need intrinsics to have the same
112 // fast-math flag decorations that are applied to FP instructions. For now,
113 // we have to rely on the function-level unsafe-fp-math attribute to do this
Davide Italianoed5cc952015-11-16 16:54:28 +0000114 // optimization because there's no other way to express that the call can be
115 // relaxed.
Davide Italianoa904e522015-10-29 02:58:44 +0000116 if (F->hasFnAttribute("unsafe-fp-math")) {
117 Attribute Attr = F->getFnAttribute("unsafe-fp-math");
118 if (Attr.getValueAsString() == "true")
119 return true;
120 }
121 return false;
122}
123
Ahmed Bougachab7d8afb2015-01-12 17:18:19 +0000124/// \brief Returns whether \p F matches the signature expected for the
125/// string/memory copying library function \p Func.
126/// Acceptable functions are st[rp][n]?cpy, memove, memcpy, and memset.
127/// Their fortified (_chk) counterparts are also accepted.
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000128static bool checkStringCopyLibFuncSignature(Function *F, LibFunc::Func Func) {
129 const DataLayout &DL = F->getParent()->getDataLayout();
Ahmed Bougachab7d8afb2015-01-12 17:18:19 +0000130 FunctionType *FT = F->getFunctionType();
131 LLVMContext &Context = F->getContext();
132 Type *PCharTy = Type::getInt8PtrTy(Context);
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000133 Type *SizeTTy = DL.getIntPtrType(Context);
Ahmed Bougachab7d8afb2015-01-12 17:18:19 +0000134 unsigned NumParams = FT->getNumParams();
135
136 // All string libfuncs return the same type as the first parameter.
137 if (FT->getReturnType() != FT->getParamType(0))
138 return false;
139
140 switch (Func) {
141 default:
142 llvm_unreachable("Can't check signature for non-string-copy libfunc.");
143 case LibFunc::stpncpy_chk:
144 case LibFunc::strncpy_chk:
145 --NumParams; // fallthrough
146 case LibFunc::stpncpy:
147 case LibFunc::strncpy: {
148 if (NumParams != 3 || FT->getParamType(0) != FT->getParamType(1) ||
149 FT->getParamType(0) != PCharTy || !FT->getParamType(2)->isIntegerTy())
150 return false;
151 break;
152 }
153 case LibFunc::strcpy_chk:
154 case LibFunc::stpcpy_chk:
155 --NumParams; // fallthrough
156 case LibFunc::stpcpy:
157 case LibFunc::strcpy: {
158 if (NumParams != 2 || FT->getParamType(0) != FT->getParamType(1) ||
159 FT->getParamType(0) != PCharTy)
160 return false;
161 break;
162 }
163 case LibFunc::memmove_chk:
164 case LibFunc::memcpy_chk:
165 --NumParams; // fallthrough
166 case LibFunc::memmove:
167 case LibFunc::memcpy: {
168 if (NumParams != 3 || !FT->getParamType(0)->isPointerTy() ||
169 !FT->getParamType(1)->isPointerTy() || FT->getParamType(2) != SizeTTy)
170 return false;
171 break;
172 }
173 case LibFunc::memset_chk:
174 --NumParams; // fallthrough
175 case LibFunc::memset: {
176 if (NumParams != 3 || !FT->getParamType(0)->isPointerTy() ||
177 !FT->getParamType(1)->isIntegerTy() || FT->getParamType(2) != SizeTTy)
178 return false;
179 break;
180 }
181 }
182 // If this is a fortified libcall, the last parameter is a size_t.
183 if (NumParams == FT->getNumParams() - 1)
184 return FT->getParamType(FT->getNumParams() - 1) == SizeTTy;
185 return true;
186}
187
Meador Inged589ac62012-10-31 03:33:06 +0000188//===----------------------------------------------------------------------===//
Meador Inge7fb2f732012-10-13 16:45:32 +0000189// String and Memory Library Call Optimizations
190//===----------------------------------------------------------------------===//
191
Chris Bienemanad070d02014-09-17 20:55:46 +0000192Value *LibCallSimplifier::optimizeStrCat(CallInst *CI, IRBuilder<> &B) {
193 Function *Callee = CI->getCalledFunction();
194 // Verify the "strcat" function prototype.
195 FunctionType *FT = Callee->getFunctionType();
196 if (FT->getNumParams() != 2||
197 FT->getReturnType() != B.getInt8PtrTy() ||
198 FT->getParamType(0) != FT->getReturnType() ||
199 FT->getParamType(1) != FT->getReturnType())
200 return nullptr;
201
202 // Extract some information from the instruction
203 Value *Dst = CI->getArgOperand(0);
204 Value *Src = CI->getArgOperand(1);
205
206 // See if we can get the length of the input string.
207 uint64_t Len = GetStringLength(Src);
208 if (Len == 0)
209 return nullptr;
210 --Len; // Unbias length.
211
212 // Handle the simple, do-nothing case: strcat(x, "") -> x
213 if (Len == 0)
214 return Dst;
215
Chris Bienemanad070d02014-09-17 20:55:46 +0000216 return emitStrLenMemCpy(Src, Dst, Len, B);
217}
218
219Value *LibCallSimplifier::emitStrLenMemCpy(Value *Src, Value *Dst, uint64_t Len,
220 IRBuilder<> &B) {
221 // We need to find the end of the destination string. That's where the
222 // memory is to be moved to. We just generate a call to strlen.
223 Value *DstLen = EmitStrLen(Dst, B, DL, TLI);
224 if (!DstLen)
225 return nullptr;
226
227 // Now that we have the destination's length, we must index into the
228 // destination's pointer to get the actual memcpy destination (end of
229 // the string .. we're concatenating).
David Blaikie3909da72015-03-30 20:42:56 +0000230 Value *CpyDst = B.CreateGEP(B.getInt8Ty(), Dst, DstLen, "endptr");
Chris Bienemanad070d02014-09-17 20:55:46 +0000231
232 // We have enough information to now generate the memcpy call to do the
233 // concatenation for us. Make a memcpy to copy the nul byte with align = 1.
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000234 B.CreateMemCpy(CpyDst, Src,
235 ConstantInt::get(DL.getIntPtrType(Src->getContext()), Len + 1),
Pete Cooper67cf9a72015-11-19 05:56:52 +0000236 1);
Chris Bienemanad070d02014-09-17 20:55:46 +0000237 return Dst;
238}
239
240Value *LibCallSimplifier::optimizeStrNCat(CallInst *CI, IRBuilder<> &B) {
241 Function *Callee = CI->getCalledFunction();
242 // Verify the "strncat" function prototype.
243 FunctionType *FT = Callee->getFunctionType();
244 if (FT->getNumParams() != 3 || FT->getReturnType() != B.getInt8PtrTy() ||
245 FT->getParamType(0) != FT->getReturnType() ||
246 FT->getParamType(1) != FT->getReturnType() ||
247 !FT->getParamType(2)->isIntegerTy())
248 return nullptr;
249
Sanjay Pateld707db92015-12-31 16:10:49 +0000250 // Extract some information from the instruction.
Chris Bienemanad070d02014-09-17 20:55:46 +0000251 Value *Dst = CI->getArgOperand(0);
252 Value *Src = CI->getArgOperand(1);
253 uint64_t Len;
254
Sanjay Pateld707db92015-12-31 16:10:49 +0000255 // We don't do anything if length is not constant.
Chris Bienemanad070d02014-09-17 20:55:46 +0000256 if (ConstantInt *LengthArg = dyn_cast<ConstantInt>(CI->getArgOperand(2)))
257 Len = LengthArg->getZExtValue();
258 else
259 return nullptr;
260
261 // See if we can get the length of the input string.
262 uint64_t SrcLen = GetStringLength(Src);
263 if (SrcLen == 0)
264 return nullptr;
265 --SrcLen; // Unbias length.
266
267 // Handle the simple, do-nothing cases:
268 // strncat(x, "", c) -> x
269 // strncat(x, c, 0) -> x
270 if (SrcLen == 0 || Len == 0)
271 return Dst;
272
Sanjay Pateld707db92015-12-31 16:10:49 +0000273 // We don't optimize this case.
Chris Bienemanad070d02014-09-17 20:55:46 +0000274 if (Len < SrcLen)
275 return nullptr;
276
277 // strncat(x, s, c) -> strcat(x, s)
Sanjay Pateld707db92015-12-31 16:10:49 +0000278 // s is constant so the strcat can be optimized further.
Chris Bienemanad070d02014-09-17 20:55:46 +0000279 return emitStrLenMemCpy(Src, Dst, SrcLen, B);
280}
281
282Value *LibCallSimplifier::optimizeStrChr(CallInst *CI, IRBuilder<> &B) {
283 Function *Callee = CI->getCalledFunction();
284 // Verify the "strchr" function prototype.
285 FunctionType *FT = Callee->getFunctionType();
286 if (FT->getNumParams() != 2 || FT->getReturnType() != B.getInt8PtrTy() ||
287 FT->getParamType(0) != FT->getReturnType() ||
288 !FT->getParamType(1)->isIntegerTy(32))
289 return nullptr;
290
291 Value *SrcStr = CI->getArgOperand(0);
292
293 // If the second operand is non-constant, see if we can compute the length
294 // of the input string and turn this into memchr.
295 ConstantInt *CharC = dyn_cast<ConstantInt>(CI->getArgOperand(1));
296 if (!CharC) {
Chris Bienemanad070d02014-09-17 20:55:46 +0000297 uint64_t Len = GetStringLength(SrcStr);
298 if (Len == 0 || !FT->getParamType(1)->isIntegerTy(32)) // memchr needs i32.
299 return nullptr;
Meador Inge7fb2f732012-10-13 16:45:32 +0000300
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000301 return EmitMemChr(SrcStr, CI->getArgOperand(1), // include nul.
302 ConstantInt::get(DL.getIntPtrType(CI->getContext()), Len),
303 B, DL, TLI);
Meador Inge7fb2f732012-10-13 16:45:32 +0000304 }
305
Chris Bienemanad070d02014-09-17 20:55:46 +0000306 // Otherwise, the character is a constant, see if the first argument is
307 // a string literal. If so, we can constant fold.
308 StringRef Str;
309 if (!getConstantStringInfo(SrcStr, Str)) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000310 if (CharC->isZero()) // strchr(p, 0) -> p + strlen(p)
Sanjay Pateld707db92015-12-31 16:10:49 +0000311 return B.CreateGEP(B.getInt8Ty(), SrcStr, EmitStrLen(SrcStr, B, DL, TLI),
312 "strchr");
Chris Bienemanad070d02014-09-17 20:55:46 +0000313 return nullptr;
314 }
315
316 // Compute the offset, make sure to handle the case when we're searching for
317 // zero (a weird way to spell strlen).
318 size_t I = (0xFF & CharC->getSExtValue()) == 0
319 ? Str.size()
320 : Str.find(CharC->getSExtValue());
321 if (I == StringRef::npos) // Didn't find the char. strchr returns null.
322 return Constant::getNullValue(CI->getType());
323
324 // strchr(s+n,c) -> gep(s+n+i,c)
David Blaikie3909da72015-03-30 20:42:56 +0000325 return B.CreateGEP(B.getInt8Ty(), SrcStr, B.getInt64(I), "strchr");
Chris Bienemanad070d02014-09-17 20:55:46 +0000326}
327
328Value *LibCallSimplifier::optimizeStrRChr(CallInst *CI, IRBuilder<> &B) {
329 Function *Callee = CI->getCalledFunction();
330 // Verify the "strrchr" function prototype.
331 FunctionType *FT = Callee->getFunctionType();
332 if (FT->getNumParams() != 2 || FT->getReturnType() != B.getInt8PtrTy() ||
333 FT->getParamType(0) != FT->getReturnType() ||
334 !FT->getParamType(1)->isIntegerTy(32))
335 return nullptr;
336
337 Value *SrcStr = CI->getArgOperand(0);
338 ConstantInt *CharC = dyn_cast<ConstantInt>(CI->getArgOperand(1));
339
340 // Cannot fold anything if we're not looking for a constant.
341 if (!CharC)
342 return nullptr;
343
344 StringRef Str;
345 if (!getConstantStringInfo(SrcStr, Str)) {
346 // strrchr(s, 0) -> strchr(s, 0)
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000347 if (CharC->isZero())
348 return EmitStrChr(SrcStr, '\0', B, TLI);
Chris Bienemanad070d02014-09-17 20:55:46 +0000349 return nullptr;
350 }
351
352 // Compute the offset.
353 size_t I = (0xFF & CharC->getSExtValue()) == 0
354 ? Str.size()
355 : Str.rfind(CharC->getSExtValue());
356 if (I == StringRef::npos) // Didn't find the char. Return null.
357 return Constant::getNullValue(CI->getType());
358
359 // strrchr(s+n,c) -> gep(s+n+i,c)
David Blaikie3909da72015-03-30 20:42:56 +0000360 return B.CreateGEP(B.getInt8Ty(), SrcStr, B.getInt64(I), "strrchr");
Chris Bienemanad070d02014-09-17 20:55:46 +0000361}
362
363Value *LibCallSimplifier::optimizeStrCmp(CallInst *CI, IRBuilder<> &B) {
364 Function *Callee = CI->getCalledFunction();
365 // Verify the "strcmp" function prototype.
366 FunctionType *FT = Callee->getFunctionType();
367 if (FT->getNumParams() != 2 || !FT->getReturnType()->isIntegerTy(32) ||
368 FT->getParamType(0) != FT->getParamType(1) ||
369 FT->getParamType(0) != B.getInt8PtrTy())
370 return nullptr;
371
372 Value *Str1P = CI->getArgOperand(0), *Str2P = CI->getArgOperand(1);
373 if (Str1P == Str2P) // strcmp(x,x) -> 0
374 return ConstantInt::get(CI->getType(), 0);
375
376 StringRef Str1, Str2;
377 bool HasStr1 = getConstantStringInfo(Str1P, Str1);
378 bool HasStr2 = getConstantStringInfo(Str2P, Str2);
379
380 // strcmp(x, y) -> cnst (if both x and y are constant strings)
381 if (HasStr1 && HasStr2)
382 return ConstantInt::get(CI->getType(), Str1.compare(Str2));
383
384 if (HasStr1 && Str1.empty()) // strcmp("", x) -> -*x
385 return B.CreateNeg(
386 B.CreateZExt(B.CreateLoad(Str2P, "strcmpload"), CI->getType()));
387
388 if (HasStr2 && Str2.empty()) // strcmp(x,"") -> *x
389 return B.CreateZExt(B.CreateLoad(Str1P, "strcmpload"), CI->getType());
390
391 // strcmp(P, "x") -> memcmp(P, "x", 2)
392 uint64_t Len1 = GetStringLength(Str1P);
393 uint64_t Len2 = GetStringLength(Str2P);
394 if (Len1 && Len2) {
Chris Bienemanad070d02014-09-17 20:55:46 +0000395 return EmitMemCmp(Str1P, Str2P,
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000396 ConstantInt::get(DL.getIntPtrType(CI->getContext()),
Chris Bienemanad070d02014-09-17 20:55:46 +0000397 std::min(Len1, Len2)),
398 B, DL, TLI);
399 }
Meador Inge7fb2f732012-10-13 16:45:32 +0000400
Chris Bienemanad070d02014-09-17 20:55:46 +0000401 return nullptr;
402}
403
404Value *LibCallSimplifier::optimizeStrNCmp(CallInst *CI, IRBuilder<> &B) {
405 Function *Callee = CI->getCalledFunction();
406 // Verify the "strncmp" function prototype.
407 FunctionType *FT = Callee->getFunctionType();
408 if (FT->getNumParams() != 3 || !FT->getReturnType()->isIntegerTy(32) ||
409 FT->getParamType(0) != FT->getParamType(1) ||
410 FT->getParamType(0) != B.getInt8PtrTy() ||
411 !FT->getParamType(2)->isIntegerTy())
412 return nullptr;
413
414 Value *Str1P = CI->getArgOperand(0), *Str2P = CI->getArgOperand(1);
415 if (Str1P == Str2P) // strncmp(x,x,n) -> 0
416 return ConstantInt::get(CI->getType(), 0);
417
418 // Get the length argument if it is constant.
419 uint64_t Length;
420 if (ConstantInt *LengthArg = dyn_cast<ConstantInt>(CI->getArgOperand(2)))
421 Length = LengthArg->getZExtValue();
422 else
423 return nullptr;
424
425 if (Length == 0) // strncmp(x,y,0) -> 0
426 return ConstantInt::get(CI->getType(), 0);
427
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000428 if (Length == 1) // strncmp(x,y,1) -> memcmp(x,y,1)
Chris Bienemanad070d02014-09-17 20:55:46 +0000429 return EmitMemCmp(Str1P, Str2P, CI->getArgOperand(2), B, DL, TLI);
430
431 StringRef Str1, Str2;
432 bool HasStr1 = getConstantStringInfo(Str1P, Str1);
433 bool HasStr2 = getConstantStringInfo(Str2P, Str2);
434
435 // strncmp(x, y) -> cnst (if both x and y are constant strings)
436 if (HasStr1 && HasStr2) {
437 StringRef SubStr1 = Str1.substr(0, Length);
438 StringRef SubStr2 = Str2.substr(0, Length);
439 return ConstantInt::get(CI->getType(), SubStr1.compare(SubStr2));
440 }
441
442 if (HasStr1 && Str1.empty()) // strncmp("", x, n) -> -*x
443 return B.CreateNeg(
444 B.CreateZExt(B.CreateLoad(Str2P, "strcmpload"), CI->getType()));
445
446 if (HasStr2 && Str2.empty()) // strncmp(x, "", n) -> *x
447 return B.CreateZExt(B.CreateLoad(Str1P, "strcmpload"), CI->getType());
448
449 return nullptr;
450}
451
452Value *LibCallSimplifier::optimizeStrCpy(CallInst *CI, IRBuilder<> &B) {
453 Function *Callee = CI->getCalledFunction();
Ahmed Bougachab7d8afb2015-01-12 17:18:19 +0000454
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000455 if (!checkStringCopyLibFuncSignature(Callee, LibFunc::strcpy))
Chris Bienemanad070d02014-09-17 20:55:46 +0000456 return nullptr;
457
458 Value *Dst = CI->getArgOperand(0), *Src = CI->getArgOperand(1);
459 if (Dst == Src) // strcpy(x,x) -> x
460 return Src;
461
Chris Bienemanad070d02014-09-17 20:55:46 +0000462 // See if we can get the length of the input string.
463 uint64_t Len = GetStringLength(Src);
464 if (Len == 0)
465 return nullptr;
466
467 // We have enough information to now generate the memcpy call to do the
468 // copy for us. Make a memcpy to copy the nul byte with align = 1.
469 B.CreateMemCpy(Dst, Src,
Pete Cooper67cf9a72015-11-19 05:56:52 +0000470 ConstantInt::get(DL.getIntPtrType(CI->getContext()), Len), 1);
Chris Bienemanad070d02014-09-17 20:55:46 +0000471 return Dst;
472}
473
474Value *LibCallSimplifier::optimizeStpCpy(CallInst *CI, IRBuilder<> &B) {
475 Function *Callee = CI->getCalledFunction();
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000476 if (!checkStringCopyLibFuncSignature(Callee, LibFunc::stpcpy))
Chris Bienemanad070d02014-09-17 20:55:46 +0000477 return nullptr;
478
479 Value *Dst = CI->getArgOperand(0), *Src = CI->getArgOperand(1);
480 if (Dst == Src) { // stpcpy(x,x) -> x+strlen(x)
481 Value *StrLen = EmitStrLen(Src, B, DL, TLI);
David Blaikieaa41cd52015-04-03 21:33:42 +0000482 return StrLen ? B.CreateInBoundsGEP(B.getInt8Ty(), Dst, StrLen) : nullptr;
Chris Bienemanad070d02014-09-17 20:55:46 +0000483 }
484
485 // See if we can get the length of the input string.
486 uint64_t Len = GetStringLength(Src);
487 if (Len == 0)
488 return nullptr;
489
Davide Italianob7487e62015-11-02 23:07:14 +0000490 Type *PT = Callee->getFunctionType()->getParamType(0);
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000491 Value *LenV = ConstantInt::get(DL.getIntPtrType(PT), Len);
Sanjay Pateld707db92015-12-31 16:10:49 +0000492 Value *DstEnd = B.CreateGEP(B.getInt8Ty(), Dst,
493 ConstantInt::get(DL.getIntPtrType(PT), Len - 1));
Chris Bienemanad070d02014-09-17 20:55:46 +0000494
495 // We have enough information to now generate the memcpy call to do the
496 // copy for us. Make a memcpy to copy the nul byte with align = 1.
Pete Cooper67cf9a72015-11-19 05:56:52 +0000497 B.CreateMemCpy(Dst, Src, LenV, 1);
Chris Bienemanad070d02014-09-17 20:55:46 +0000498 return DstEnd;
499}
500
501Value *LibCallSimplifier::optimizeStrNCpy(CallInst *CI, IRBuilder<> &B) {
502 Function *Callee = CI->getCalledFunction();
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000503 if (!checkStringCopyLibFuncSignature(Callee, LibFunc::strncpy))
Chris Bienemanad070d02014-09-17 20:55:46 +0000504 return nullptr;
505
506 Value *Dst = CI->getArgOperand(0);
507 Value *Src = CI->getArgOperand(1);
508 Value *LenOp = CI->getArgOperand(2);
509
510 // See if we can get the length of the input string.
511 uint64_t SrcLen = GetStringLength(Src);
512 if (SrcLen == 0)
513 return nullptr;
514 --SrcLen;
515
516 if (SrcLen == 0) {
517 // strncpy(x, "", y) -> memset(x, '\0', y, 1)
518 B.CreateMemSet(Dst, B.getInt8('\0'), LenOp, 1);
Meador Inge7fb2f732012-10-13 16:45:32 +0000519 return Dst;
520 }
Meador Inge7fb2f732012-10-13 16:45:32 +0000521
Chris Bienemanad070d02014-09-17 20:55:46 +0000522 uint64_t Len;
523 if (ConstantInt *LengthArg = dyn_cast<ConstantInt>(LenOp))
524 Len = LengthArg->getZExtValue();
525 else
526 return nullptr;
Meador Inge7fb2f732012-10-13 16:45:32 +0000527
Chris Bienemanad070d02014-09-17 20:55:46 +0000528 if (Len == 0)
529 return Dst; // strncpy(x, y, 0) -> x
Meador Inge7fb2f732012-10-13 16:45:32 +0000530
Chris Bienemanad070d02014-09-17 20:55:46 +0000531 // Let strncpy handle the zero padding
532 if (Len > SrcLen + 1)
533 return nullptr;
Meador Inge7fb2f732012-10-13 16:45:32 +0000534
Davide Italianob7487e62015-11-02 23:07:14 +0000535 Type *PT = Callee->getFunctionType()->getParamType(0);
Chris Bienemanad070d02014-09-17 20:55:46 +0000536 // strncpy(x, s, c) -> memcpy(x, s, c, 1) [s and c are constant]
Pete Cooper67cf9a72015-11-19 05:56:52 +0000537 B.CreateMemCpy(Dst, Src, ConstantInt::get(DL.getIntPtrType(PT), Len), 1);
Meador Inge7fb2f732012-10-13 16:45:32 +0000538
Chris Bienemanad070d02014-09-17 20:55:46 +0000539 return Dst;
540}
Meador Inge7fb2f732012-10-13 16:45:32 +0000541
Chris Bienemanad070d02014-09-17 20:55:46 +0000542Value *LibCallSimplifier::optimizeStrLen(CallInst *CI, IRBuilder<> &B) {
543 Function *Callee = CI->getCalledFunction();
544 FunctionType *FT = Callee->getFunctionType();
545 if (FT->getNumParams() != 1 || FT->getParamType(0) != B.getInt8PtrTy() ||
546 !FT->getReturnType()->isIntegerTy())
547 return nullptr;
Meador Inge7fb2f732012-10-13 16:45:32 +0000548
Chris Bienemanad070d02014-09-17 20:55:46 +0000549 Value *Src = CI->getArgOperand(0);
550
551 // Constant folding: strlen("xyz") -> 3
552 if (uint64_t Len = GetStringLength(Src))
553 return ConstantInt::get(CI->getType(), Len - 1);
554
555 // strlen(x?"foo":"bars") --> x ? 3 : 4
556 if (SelectInst *SI = dyn_cast<SelectInst>(Src)) {
557 uint64_t LenTrue = GetStringLength(SI->getTrueValue());
558 uint64_t LenFalse = GetStringLength(SI->getFalseValue());
559 if (LenTrue && LenFalse) {
560 Function *Caller = CI->getParent()->getParent();
561 emitOptimizationRemark(CI->getContext(), "simplify-libcalls", *Caller,
562 SI->getDebugLoc(),
563 "folded strlen(select) to select of constants");
564 return B.CreateSelect(SI->getCondition(),
565 ConstantInt::get(CI->getType(), LenTrue - 1),
566 ConstantInt::get(CI->getType(), LenFalse - 1));
567 }
Meador Inge7fb2f732012-10-13 16:45:32 +0000568 }
Meador Inge7fb2f732012-10-13 16:45:32 +0000569
Chris Bienemanad070d02014-09-17 20:55:46 +0000570 // strlen(x) != 0 --> *x != 0
571 // strlen(x) == 0 --> *x == 0
572 if (isOnlyUsedInZeroEqualityComparison(CI))
573 return B.CreateZExt(B.CreateLoad(Src, "strlenfirst"), CI->getType());
Meador Inge17418502012-10-13 16:45:37 +0000574
Chris Bienemanad070d02014-09-17 20:55:46 +0000575 return nullptr;
576}
Meador Inge17418502012-10-13 16:45:37 +0000577
Chris Bienemanad070d02014-09-17 20:55:46 +0000578Value *LibCallSimplifier::optimizeStrPBrk(CallInst *CI, IRBuilder<> &B) {
579 Function *Callee = CI->getCalledFunction();
580 FunctionType *FT = Callee->getFunctionType();
581 if (FT->getNumParams() != 2 || FT->getParamType(0) != B.getInt8PtrTy() ||
582 FT->getParamType(1) != FT->getParamType(0) ||
583 FT->getReturnType() != FT->getParamType(0))
584 return nullptr;
Meador Inge17418502012-10-13 16:45:37 +0000585
Chris Bienemanad070d02014-09-17 20:55:46 +0000586 StringRef S1, S2;
587 bool HasS1 = getConstantStringInfo(CI->getArgOperand(0), S1);
588 bool HasS2 = getConstantStringInfo(CI->getArgOperand(1), S2);
Meador Inge17418502012-10-13 16:45:37 +0000589
Reid Kleckner971c3ea2014-11-13 22:55:19 +0000590 // strpbrk(s, "") -> nullptr
591 // strpbrk("", s) -> nullptr
Chris Bienemanad070d02014-09-17 20:55:46 +0000592 if ((HasS1 && S1.empty()) || (HasS2 && S2.empty()))
593 return Constant::getNullValue(CI->getType());
Meador Inge17418502012-10-13 16:45:37 +0000594
Chris Bienemanad070d02014-09-17 20:55:46 +0000595 // Constant folding.
596 if (HasS1 && HasS2) {
597 size_t I = S1.find_first_of(S2);
598 if (I == StringRef::npos) // No match.
Meador Inge17418502012-10-13 16:45:37 +0000599 return Constant::getNullValue(CI->getType());
600
Sanjay Pateld707db92015-12-31 16:10:49 +0000601 return B.CreateGEP(B.getInt8Ty(), CI->getArgOperand(0), B.getInt64(I),
602 "strpbrk");
Meador Inge17418502012-10-13 16:45:37 +0000603 }
Meador Inge17418502012-10-13 16:45:37 +0000604
Chris Bienemanad070d02014-09-17 20:55:46 +0000605 // strpbrk(s, "a") -> strchr(s, 'a')
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000606 if (HasS2 && S2.size() == 1)
607 return EmitStrChr(CI->getArgOperand(0), S2[0], B, TLI);
Chris Bienemanad070d02014-09-17 20:55:46 +0000608
609 return nullptr;
610}
611
612Value *LibCallSimplifier::optimizeStrTo(CallInst *CI, IRBuilder<> &B) {
613 Function *Callee = CI->getCalledFunction();
614 FunctionType *FT = Callee->getFunctionType();
615 if ((FT->getNumParams() != 2 && FT->getNumParams() != 3) ||
616 !FT->getParamType(0)->isPointerTy() ||
617 !FT->getParamType(1)->isPointerTy())
618 return nullptr;
619
620 Value *EndPtr = CI->getArgOperand(1);
621 if (isa<ConstantPointerNull>(EndPtr)) {
622 // With a null EndPtr, this function won't capture the main argument.
623 // It would be readonly too, except that it still may write to errno.
624 CI->addAttribute(1, Attribute::NoCapture);
625 }
626
627 return nullptr;
628}
629
630Value *LibCallSimplifier::optimizeStrSpn(CallInst *CI, IRBuilder<> &B) {
631 Function *Callee = CI->getCalledFunction();
632 FunctionType *FT = Callee->getFunctionType();
633 if (FT->getNumParams() != 2 || FT->getParamType(0) != B.getInt8PtrTy() ||
634 FT->getParamType(1) != FT->getParamType(0) ||
635 !FT->getReturnType()->isIntegerTy())
636 return nullptr;
637
638 StringRef S1, S2;
639 bool HasS1 = getConstantStringInfo(CI->getArgOperand(0), S1);
640 bool HasS2 = getConstantStringInfo(CI->getArgOperand(1), S2);
641
642 // strspn(s, "") -> 0
643 // strspn("", s) -> 0
644 if ((HasS1 && S1.empty()) || (HasS2 && S2.empty()))
645 return Constant::getNullValue(CI->getType());
646
647 // Constant folding.
648 if (HasS1 && HasS2) {
649 size_t Pos = S1.find_first_not_of(S2);
650 if (Pos == StringRef::npos)
651 Pos = S1.size();
652 return ConstantInt::get(CI->getType(), Pos);
653 }
654
655 return nullptr;
656}
657
658Value *LibCallSimplifier::optimizeStrCSpn(CallInst *CI, IRBuilder<> &B) {
659 Function *Callee = CI->getCalledFunction();
660 FunctionType *FT = Callee->getFunctionType();
661 if (FT->getNumParams() != 2 || FT->getParamType(0) != B.getInt8PtrTy() ||
662 FT->getParamType(1) != FT->getParamType(0) ||
663 !FT->getReturnType()->isIntegerTy())
664 return nullptr;
665
666 StringRef S1, S2;
667 bool HasS1 = getConstantStringInfo(CI->getArgOperand(0), S1);
668 bool HasS2 = getConstantStringInfo(CI->getArgOperand(1), S2);
669
670 // strcspn("", s) -> 0
671 if (HasS1 && S1.empty())
672 return Constant::getNullValue(CI->getType());
673
674 // Constant folding.
675 if (HasS1 && HasS2) {
676 size_t Pos = S1.find_first_of(S2);
677 if (Pos == StringRef::npos)
678 Pos = S1.size();
679 return ConstantInt::get(CI->getType(), Pos);
680 }
681
682 // strcspn(s, "") -> strlen(s)
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000683 if (HasS2 && S2.empty())
Chris Bienemanad070d02014-09-17 20:55:46 +0000684 return EmitStrLen(CI->getArgOperand(0), B, DL, TLI);
685
686 return nullptr;
687}
688
689Value *LibCallSimplifier::optimizeStrStr(CallInst *CI, IRBuilder<> &B) {
690 Function *Callee = CI->getCalledFunction();
691 FunctionType *FT = Callee->getFunctionType();
692 if (FT->getNumParams() != 2 || !FT->getParamType(0)->isPointerTy() ||
693 !FT->getParamType(1)->isPointerTy() ||
694 !FT->getReturnType()->isPointerTy())
695 return nullptr;
696
697 // fold strstr(x, x) -> x.
698 if (CI->getArgOperand(0) == CI->getArgOperand(1))
699 return B.CreateBitCast(CI->getArgOperand(0), CI->getType());
700
701 // fold strstr(a, b) == a -> strncmp(a, b, strlen(b)) == 0
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000702 if (isOnlyUsedInEqualityComparison(CI, CI->getArgOperand(0))) {
Chris Bienemanad070d02014-09-17 20:55:46 +0000703 Value *StrLen = EmitStrLen(CI->getArgOperand(1), B, DL, TLI);
704 if (!StrLen)
Craig Topperf40110f2014-04-25 05:29:35 +0000705 return nullptr;
Chris Bienemanad070d02014-09-17 20:55:46 +0000706 Value *StrNCmp = EmitStrNCmp(CI->getArgOperand(0), CI->getArgOperand(1),
707 StrLen, B, DL, TLI);
708 if (!StrNCmp)
Craig Topperf40110f2014-04-25 05:29:35 +0000709 return nullptr;
Chris Bienemanad070d02014-09-17 20:55:46 +0000710 for (auto UI = CI->user_begin(), UE = CI->user_end(); UI != UE;) {
711 ICmpInst *Old = cast<ICmpInst>(*UI++);
712 Value *Cmp =
713 B.CreateICmp(Old->getPredicate(), StrNCmp,
714 ConstantInt::getNullValue(StrNCmp->getType()), "cmp");
715 replaceAllUsesWith(Old, Cmp);
Meador Inge17418502012-10-13 16:45:37 +0000716 }
Chris Bienemanad070d02014-09-17 20:55:46 +0000717 return CI;
718 }
Meador Inge17418502012-10-13 16:45:37 +0000719
Chris Bienemanad070d02014-09-17 20:55:46 +0000720 // See if either input string is a constant string.
721 StringRef SearchStr, ToFindStr;
722 bool HasStr1 = getConstantStringInfo(CI->getArgOperand(0), SearchStr);
723 bool HasStr2 = getConstantStringInfo(CI->getArgOperand(1), ToFindStr);
724
725 // fold strstr(x, "") -> x.
726 if (HasStr2 && ToFindStr.empty())
727 return B.CreateBitCast(CI->getArgOperand(0), CI->getType());
728
729 // If both strings are known, constant fold it.
730 if (HasStr1 && HasStr2) {
731 size_t Offset = SearchStr.find(ToFindStr);
732
733 if (Offset == StringRef::npos) // strstr("foo", "bar") -> null
Meador Inge17418502012-10-13 16:45:37 +0000734 return Constant::getNullValue(CI->getType());
735
Chris Bienemanad070d02014-09-17 20:55:46 +0000736 // strstr("abcd", "bc") -> gep((char*)"abcd", 1)
737 Value *Result = CastToCStr(CI->getArgOperand(0), B);
738 Result = B.CreateConstInBoundsGEP1_64(Result, Offset, "strstr");
739 return B.CreateBitCast(Result, CI->getType());
Meador Inge17418502012-10-13 16:45:37 +0000740 }
Meador Inge17418502012-10-13 16:45:37 +0000741
Chris Bienemanad070d02014-09-17 20:55:46 +0000742 // fold strstr(x, "y") -> strchr(x, 'y').
743 if (HasStr2 && ToFindStr.size() == 1) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000744 Value *StrChr = EmitStrChr(CI->getArgOperand(0), ToFindStr[0], B, TLI);
Chris Bienemanad070d02014-09-17 20:55:46 +0000745 return StrChr ? B.CreateBitCast(StrChr, CI->getType()) : nullptr;
746 }
747 return nullptr;
748}
Meador Inge40b6fac2012-10-15 03:47:37 +0000749
Benjamin Kramer691363e2015-03-21 15:36:21 +0000750Value *LibCallSimplifier::optimizeMemChr(CallInst *CI, IRBuilder<> &B) {
751 Function *Callee = CI->getCalledFunction();
752 FunctionType *FT = Callee->getFunctionType();
753 if (FT->getNumParams() != 3 || !FT->getParamType(0)->isPointerTy() ||
754 !FT->getParamType(1)->isIntegerTy(32) ||
755 !FT->getParamType(2)->isIntegerTy() ||
756 !FT->getReturnType()->isPointerTy())
757 return nullptr;
758
759 Value *SrcStr = CI->getArgOperand(0);
760 ConstantInt *CharC = dyn_cast<ConstantInt>(CI->getArgOperand(1));
761 ConstantInt *LenC = dyn_cast<ConstantInt>(CI->getArgOperand(2));
762
763 // memchr(x, y, 0) -> null
764 if (LenC && LenC->isNullValue())
765 return Constant::getNullValue(CI->getType());
766
Benjamin Kramer7857d722015-03-21 21:09:33 +0000767 // From now on we need at least constant length and string.
Benjamin Kramer691363e2015-03-21 15:36:21 +0000768 StringRef Str;
Benjamin Kramer7857d722015-03-21 21:09:33 +0000769 if (!LenC || !getConstantStringInfo(SrcStr, Str, 0, /*TrimAtNul=*/false))
Benjamin Kramer691363e2015-03-21 15:36:21 +0000770 return nullptr;
771
772 // Truncate the string to LenC. If Str is smaller than LenC we will still only
773 // scan the string, as reading past the end of it is undefined and we can just
774 // return null if we don't find the char.
775 Str = Str.substr(0, LenC->getZExtValue());
776
Benjamin Kramer7857d722015-03-21 21:09:33 +0000777 // If the char is variable but the input str and length are not we can turn
778 // this memchr call into a simple bit field test. Of course this only works
779 // when the return value is only checked against null.
780 //
781 // It would be really nice to reuse switch lowering here but we can't change
782 // the CFG at this point.
783 //
784 // memchr("\r\n", C, 2) != nullptr -> (C & ((1 << '\r') | (1 << '\n'))) != 0
785 // after bounds check.
786 if (!CharC && !Str.empty() && isOnlyUsedInZeroEqualityComparison(CI)) {
Benjamin Kramerd6aa0ec2015-03-21 22:04:26 +0000787 unsigned char Max =
788 *std::max_element(reinterpret_cast<const unsigned char *>(Str.begin()),
789 reinterpret_cast<const unsigned char *>(Str.end()));
Benjamin Kramer7857d722015-03-21 21:09:33 +0000790
791 // Make sure the bit field we're about to create fits in a register on the
792 // target.
793 // FIXME: On a 64 bit architecture this prevents us from using the
794 // interesting range of alpha ascii chars. We could do better by emitting
795 // two bitfields or shifting the range by 64 if no lower chars are used.
796 if (!DL.fitsInLegalInteger(Max + 1))
797 return nullptr;
798
799 // For the bit field use a power-of-2 type with at least 8 bits to avoid
800 // creating unnecessary illegal types.
801 unsigned char Width = NextPowerOf2(std::max((unsigned char)7, Max));
802
803 // Now build the bit field.
804 APInt Bitfield(Width, 0);
805 for (char C : Str)
806 Bitfield.setBit((unsigned char)C);
807 Value *BitfieldC = B.getInt(Bitfield);
808
809 // First check that the bit field access is within bounds.
810 Value *C = B.CreateZExtOrTrunc(CI->getArgOperand(1), BitfieldC->getType());
811 Value *Bounds = B.CreateICmp(ICmpInst::ICMP_ULT, C, B.getIntN(Width, Width),
812 "memchr.bounds");
813
814 // Create code that checks if the given bit is set in the field.
815 Value *Shl = B.CreateShl(B.getIntN(Width, 1ULL), C);
816 Value *Bits = B.CreateIsNotNull(B.CreateAnd(Shl, BitfieldC), "memchr.bits");
817
818 // Finally merge both checks and cast to pointer type. The inttoptr
819 // implicitly zexts the i1 to intptr type.
820 return B.CreateIntToPtr(B.CreateAnd(Bounds, Bits, "memchr"), CI->getType());
821 }
822
823 // Check if all arguments are constants. If so, we can constant fold.
824 if (!CharC)
825 return nullptr;
826
Benjamin Kramer691363e2015-03-21 15:36:21 +0000827 // Compute the offset.
828 size_t I = Str.find(CharC->getSExtValue() & 0xFF);
829 if (I == StringRef::npos) // Didn't find the char. memchr returns null.
830 return Constant::getNullValue(CI->getType());
831
832 // memchr(s+n,c,l) -> gep(s+n+i,c)
David Blaikie3909da72015-03-30 20:42:56 +0000833 return B.CreateGEP(B.getInt8Ty(), SrcStr, B.getInt64(I), "memchr");
Benjamin Kramer691363e2015-03-21 15:36:21 +0000834}
835
Chris Bienemanad070d02014-09-17 20:55:46 +0000836Value *LibCallSimplifier::optimizeMemCmp(CallInst *CI, IRBuilder<> &B) {
837 Function *Callee = CI->getCalledFunction();
838 FunctionType *FT = Callee->getFunctionType();
839 if (FT->getNumParams() != 3 || !FT->getParamType(0)->isPointerTy() ||
840 !FT->getParamType(1)->isPointerTy() ||
841 !FT->getReturnType()->isIntegerTy(32))
Craig Topperf40110f2014-04-25 05:29:35 +0000842 return nullptr;
Meador Inge40b6fac2012-10-15 03:47:37 +0000843
Chris Bienemanad070d02014-09-17 20:55:46 +0000844 Value *LHS = CI->getArgOperand(0), *RHS = CI->getArgOperand(1);
Meador Inge40b6fac2012-10-15 03:47:37 +0000845
Chris Bienemanad070d02014-09-17 20:55:46 +0000846 if (LHS == RHS) // memcmp(s,s,x) -> 0
847 return Constant::getNullValue(CI->getType());
Meador Inge40b6fac2012-10-15 03:47:37 +0000848
Chris Bienemanad070d02014-09-17 20:55:46 +0000849 // Make sure we have a constant length.
850 ConstantInt *LenC = dyn_cast<ConstantInt>(CI->getArgOperand(2));
851 if (!LenC)
Craig Topperf40110f2014-04-25 05:29:35 +0000852 return nullptr;
Chris Bienemanad070d02014-09-17 20:55:46 +0000853 uint64_t Len = LenC->getZExtValue();
854
855 if (Len == 0) // memcmp(s1,s2,0) -> 0
856 return Constant::getNullValue(CI->getType());
857
858 // memcmp(S1,S2,1) -> *(unsigned char*)LHS - *(unsigned char*)RHS
859 if (Len == 1) {
860 Value *LHSV = B.CreateZExt(B.CreateLoad(CastToCStr(LHS, B), "lhsc"),
861 CI->getType(), "lhsv");
862 Value *RHSV = B.CreateZExt(B.CreateLoad(CastToCStr(RHS, B), "rhsc"),
863 CI->getType(), "rhsv");
864 return B.CreateSub(LHSV, RHSV, "chardiff");
Meador Inge40b6fac2012-10-15 03:47:37 +0000865 }
Meador Inge40b6fac2012-10-15 03:47:37 +0000866
Chad Rosierdc655322015-08-28 18:30:18 +0000867 // memcmp(S1,S2,N/8)==0 -> (*(intN_t*)S1 != *(intN_t*)S2)==0
868 if (DL.isLegalInteger(Len * 8) && isOnlyUsedInZeroEqualityComparison(CI)) {
869
870 IntegerType *IntType = IntegerType::get(CI->getContext(), Len * 8);
871 unsigned PrefAlignment = DL.getPrefTypeAlignment(IntType);
872
873 if (getKnownAlignment(LHS, DL, CI) >= PrefAlignment &&
874 getKnownAlignment(RHS, DL, CI) >= PrefAlignment) {
875
876 Type *LHSPtrTy =
877 IntType->getPointerTo(LHS->getType()->getPointerAddressSpace());
878 Type *RHSPtrTy =
879 IntType->getPointerTo(RHS->getType()->getPointerAddressSpace());
880
Sanjay Pateld707db92015-12-31 16:10:49 +0000881 Value *LHSV =
882 B.CreateLoad(B.CreateBitCast(LHS, LHSPtrTy, "lhsc"), "lhsv");
883 Value *RHSV =
884 B.CreateLoad(B.CreateBitCast(RHS, RHSPtrTy, "rhsc"), "rhsv");
Chad Rosierdc655322015-08-28 18:30:18 +0000885
886 return B.CreateZExt(B.CreateICmpNE(LHSV, RHSV), CI->getType(), "memcmp");
887 }
888 }
889
Chris Bienemanad070d02014-09-17 20:55:46 +0000890 // Constant folding: memcmp(x, y, l) -> cnst (all arguments are constant)
891 StringRef LHSStr, RHSStr;
892 if (getConstantStringInfo(LHS, LHSStr) &&
893 getConstantStringInfo(RHS, RHSStr)) {
894 // Make sure we're not reading out-of-bounds memory.
895 if (Len > LHSStr.size() || Len > RHSStr.size())
Craig Topperf40110f2014-04-25 05:29:35 +0000896 return nullptr;
Chris Bienemanad070d02014-09-17 20:55:46 +0000897 // Fold the memcmp and normalize the result. This way we get consistent
898 // results across multiple platforms.
899 uint64_t Ret = 0;
900 int Cmp = memcmp(LHSStr.data(), RHSStr.data(), Len);
901 if (Cmp < 0)
902 Ret = -1;
903 else if (Cmp > 0)
904 Ret = 1;
905 return ConstantInt::get(CI->getType(), Ret);
Meador Inge000dbcc2012-10-18 18:12:40 +0000906 }
Meador Inge000dbcc2012-10-18 18:12:40 +0000907
Chris Bienemanad070d02014-09-17 20:55:46 +0000908 return nullptr;
909}
Meador Inge9a6a1902012-10-31 00:20:56 +0000910
Chris Bienemanad070d02014-09-17 20:55:46 +0000911Value *LibCallSimplifier::optimizeMemCpy(CallInst *CI, IRBuilder<> &B) {
912 Function *Callee = CI->getCalledFunction();
Meador Inged589ac62012-10-31 03:33:06 +0000913
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000914 if (!checkStringCopyLibFuncSignature(Callee, LibFunc::memcpy))
Craig Topperf40110f2014-04-25 05:29:35 +0000915 return nullptr;
Meador Inge6f8e0112012-10-31 04:29:58 +0000916
Chris Bienemanad070d02014-09-17 20:55:46 +0000917 // memcpy(x, y, n) -> llvm.memcpy(x, y, n, 1)
918 B.CreateMemCpy(CI->getArgOperand(0), CI->getArgOperand(1),
Pete Cooper67cf9a72015-11-19 05:56:52 +0000919 CI->getArgOperand(2), 1);
Chris Bienemanad070d02014-09-17 20:55:46 +0000920 return CI->getArgOperand(0);
921}
Meador Inge05a625a2012-10-31 14:58:26 +0000922
Chris Bienemanad070d02014-09-17 20:55:46 +0000923Value *LibCallSimplifier::optimizeMemMove(CallInst *CI, IRBuilder<> &B) {
924 Function *Callee = CI->getCalledFunction();
Meador Inge05a625a2012-10-31 14:58:26 +0000925
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000926 if (!checkStringCopyLibFuncSignature(Callee, LibFunc::memmove))
Craig Topperf40110f2014-04-25 05:29:35 +0000927 return nullptr;
Meador Inge489b5d62012-11-08 01:33:50 +0000928
Chris Bienemanad070d02014-09-17 20:55:46 +0000929 // memmove(x, y, n) -> llvm.memmove(x, y, n, 1)
930 B.CreateMemMove(CI->getArgOperand(0), CI->getArgOperand(1),
Pete Cooper67cf9a72015-11-19 05:56:52 +0000931 CI->getArgOperand(2), 1);
Chris Bienemanad070d02014-09-17 20:55:46 +0000932 return CI->getArgOperand(0);
933}
Meador Ingebcd88ef72012-11-10 15:16:48 +0000934
Chris Bienemanad070d02014-09-17 20:55:46 +0000935Value *LibCallSimplifier::optimizeMemSet(CallInst *CI, IRBuilder<> &B) {
936 Function *Callee = CI->getCalledFunction();
Meador Ingebcd88ef72012-11-10 15:16:48 +0000937
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000938 if (!checkStringCopyLibFuncSignature(Callee, LibFunc::memset))
Craig Topperf40110f2014-04-25 05:29:35 +0000939 return nullptr;
Meador Inge56edbc92012-11-11 03:51:48 +0000940
Chris Bienemanad070d02014-09-17 20:55:46 +0000941 // memset(p, v, n) -> llvm.memset(p, v, n, 1)
942 Value *Val = B.CreateIntCast(CI->getArgOperand(1), B.getInt8Ty(), false);
943 B.CreateMemSet(CI->getArgOperand(0), Val, CI->getArgOperand(2), 1);
944 return CI->getArgOperand(0);
945}
Meador Inged4825782012-11-11 06:49:03 +0000946
Meador Inge193e0352012-11-13 04:16:17 +0000947//===----------------------------------------------------------------------===//
948// Math Library Optimizations
949//===----------------------------------------------------------------------===//
950
Matthias Braund34e4d22014-12-03 21:46:33 +0000951/// Return a variant of Val with float type.
952/// Currently this works in two cases: If Val is an FPExtension of a float
953/// value to something bigger, simply return the operand.
954/// If Val is a ConstantFP but can be converted to a float ConstantFP without
955/// loss of precision do so.
956static Value *valueHasFloatPrecision(Value *Val) {
957 if (FPExtInst *Cast = dyn_cast<FPExtInst>(Val)) {
958 Value *Op = Cast->getOperand(0);
959 if (Op->getType()->isFloatTy())
960 return Op;
961 }
962 if (ConstantFP *Const = dyn_cast<ConstantFP>(Val)) {
963 APFloat F = Const->getValueAPF();
Matthias Braun395a82f2014-12-03 22:10:39 +0000964 bool losesInfo;
Matthias Braund34e4d22014-12-03 21:46:33 +0000965 (void)F.convert(APFloat::IEEEsingle, APFloat::rmNearestTiesToEven,
Matthias Braun395a82f2014-12-03 22:10:39 +0000966 &losesInfo);
967 if (!losesInfo)
Matthias Braund34e4d22014-12-03 21:46:33 +0000968 return ConstantFP::get(Const->getContext(), F);
969 }
970 return nullptr;
971}
972
Meador Inge193e0352012-11-13 04:16:17 +0000973//===----------------------------------------------------------------------===//
974// Double -> Float Shrinking Optimizations for Unary Functions like 'floor'
975
Chris Bienemanad070d02014-09-17 20:55:46 +0000976Value *LibCallSimplifier::optimizeUnaryDoubleFP(CallInst *CI, IRBuilder<> &B,
977 bool CheckRetType) {
978 Function *Callee = CI->getCalledFunction();
979 FunctionType *FT = Callee->getFunctionType();
980 if (FT->getNumParams() != 1 || !FT->getReturnType()->isDoubleTy() ||
981 !FT->getParamType(0)->isDoubleTy())
982 return nullptr;
Meador Inge193e0352012-11-13 04:16:17 +0000983
Chris Bienemanad070d02014-09-17 20:55:46 +0000984 if (CheckRetType) {
985 // Check if all the uses for function like 'sin' are converted to float.
986 for (User *U : CI->users()) {
987 FPTruncInst *Cast = dyn_cast<FPTruncInst>(U);
988 if (!Cast || !Cast->getType()->isFloatTy())
989 return nullptr;
Meador Inge193e0352012-11-13 04:16:17 +0000990 }
Meador Inge193e0352012-11-13 04:16:17 +0000991 }
Chris Bienemanad070d02014-09-17 20:55:46 +0000992
993 // If this is something like 'floor((double)floatval)', convert to floorf.
Matthias Braund34e4d22014-12-03 21:46:33 +0000994 Value *V = valueHasFloatPrecision(CI->getArgOperand(0));
995 if (V == nullptr)
Chris Bienemanad070d02014-09-17 20:55:46 +0000996 return nullptr;
Sanjay Patelaa231142015-12-31 21:52:31 +0000997
998 // Propagate fast-math flags from the existing call to the new call.
999 IRBuilder<>::FastMathFlagGuard Guard(B);
Sanjay Patela2528152016-01-12 18:03:37 +00001000 B.setFastMathFlags(CI->getFastMathFlags());
Chris Bienemanad070d02014-09-17 20:55:46 +00001001
1002 // floor((double)floatval) -> (double)floorf(floatval)
Sanjay Patel848309d2014-10-23 21:52:45 +00001003 if (Callee->isIntrinsic()) {
Sanjay Patelaf674fb2015-12-14 17:24:23 +00001004 Module *M = CI->getModule();
Pete Cooper9e1d3352015-05-20 17:16:39 +00001005 Intrinsic::ID IID = Callee->getIntrinsicID();
Sanjay Patel848309d2014-10-23 21:52:45 +00001006 Function *F = Intrinsic::getDeclaration(M, IID, B.getFloatTy());
1007 V = B.CreateCall(F, V);
1008 } else {
1009 // The call is a library call rather than an intrinsic.
1010 V = EmitUnaryFloatFnCall(V, Callee->getName(), B, Callee->getAttributes());
1011 }
1012
Chris Bienemanad070d02014-09-17 20:55:46 +00001013 return B.CreateFPExt(V, B.getDoubleTy());
1014}
Meador Inge193e0352012-11-13 04:16:17 +00001015
Yi Jiang6ab044e2013-12-16 22:42:40 +00001016// Double -> Float Shrinking Optimizations for Binary Functions like 'fmin/fmax'
Chris Bienemanad070d02014-09-17 20:55:46 +00001017Value *LibCallSimplifier::optimizeBinaryDoubleFP(CallInst *CI, IRBuilder<> &B) {
1018 Function *Callee = CI->getCalledFunction();
1019 FunctionType *FT = Callee->getFunctionType();
1020 // Just make sure this has 2 arguments of the same FP type, which match the
1021 // result type.
1022 if (FT->getNumParams() != 2 || FT->getReturnType() != FT->getParamType(0) ||
1023 FT->getParamType(0) != FT->getParamType(1) ||
1024 !FT->getParamType(0)->isFloatingPointTy())
Craig Topperf40110f2014-04-25 05:29:35 +00001025 return nullptr;
Meador Inge193e0352012-11-13 04:16:17 +00001026
Chris Bienemanad070d02014-09-17 20:55:46 +00001027 // If this is something like 'fmin((double)floatval1, (double)floatval2)',
Matthias Braund34e4d22014-12-03 21:46:33 +00001028 // or fmin(1.0, (double)floatval), then we convert it to fminf.
1029 Value *V1 = valueHasFloatPrecision(CI->getArgOperand(0));
1030 if (V1 == nullptr)
1031 return nullptr;
1032 Value *V2 = valueHasFloatPrecision(CI->getArgOperand(1));
1033 if (V2 == nullptr)
Craig Topperf40110f2014-04-25 05:29:35 +00001034 return nullptr;
Chris Bienemanad070d02014-09-17 20:55:46 +00001035
Sanjay Patelbee05ca2015-12-31 23:40:59 +00001036 // Propagate fast-math flags from the existing call to the new call.
1037 IRBuilder<>::FastMathFlagGuard Guard(B);
Sanjay Patela2528152016-01-12 18:03:37 +00001038 B.setFastMathFlags(CI->getFastMathFlags());
Sanjay Patelbee05ca2015-12-31 23:40:59 +00001039
Chris Bienemanad070d02014-09-17 20:55:46 +00001040 // fmin((double)floatval1, (double)floatval2)
Matthias Braund34e4d22014-12-03 21:46:33 +00001041 // -> (double)fminf(floatval1, floatval2)
Sanjay Patel848309d2014-10-23 21:52:45 +00001042 // TODO: Handle intrinsics in the same way as in optimizeUnaryDoubleFP().
Matthias Braund34e4d22014-12-03 21:46:33 +00001043 Value *V = EmitBinaryFloatFnCall(V1, V2, Callee->getName(), B,
1044 Callee->getAttributes());
Chris Bienemanad070d02014-09-17 20:55:46 +00001045 return B.CreateFPExt(V, B.getDoubleTy());
1046}
1047
1048Value *LibCallSimplifier::optimizeCos(CallInst *CI, IRBuilder<> &B) {
1049 Function *Callee = CI->getCalledFunction();
1050 Value *Ret = nullptr;
Davide Italianoa3458772015-11-05 19:18:23 +00001051 StringRef Name = Callee->getName();
1052 if (UnsafeFPShrink && Name == "cos" && hasFloatVersion(Name))
Chris Bienemanad070d02014-09-17 20:55:46 +00001053 Ret = optimizeUnaryDoubleFP(CI, B, true);
Bob Wilsond8d92d92013-11-03 06:48:38 +00001054
Chris Bienemanad070d02014-09-17 20:55:46 +00001055 FunctionType *FT = Callee->getFunctionType();
1056 // Just make sure this has 1 argument of FP type, which matches the
1057 // result type.
1058 if (FT->getNumParams() != 1 || FT->getReturnType() != FT->getParamType(0) ||
1059 !FT->getParamType(0)->isFloatingPointTy())
1060 return Ret;
Bob Wilsond8d92d92013-11-03 06:48:38 +00001061
Chris Bienemanad070d02014-09-17 20:55:46 +00001062 // cos(-x) -> cos(x)
1063 Value *Op1 = CI->getArgOperand(0);
1064 if (BinaryOperator::isFNeg(Op1)) {
1065 BinaryOperator *BinExpr = cast<BinaryOperator>(Op1);
1066 return B.CreateCall(Callee, BinExpr->getOperand(1), "cos");
1067 }
1068 return Ret;
1069}
Bob Wilsond8d92d92013-11-03 06:48:38 +00001070
Weiming Zhao82130722015-12-04 22:00:47 +00001071static Value *getPow(Value *InnerChain[33], unsigned Exp, IRBuilder<> &B) {
1072 // Multiplications calculated using Addition Chains.
1073 // Refer: http://wwwhomes.uni-bielefeld.de/achim/addition_chain.html
1074
1075 assert(Exp != 0 && "Incorrect exponent 0 not handled");
1076
1077 if (InnerChain[Exp])
1078 return InnerChain[Exp];
1079
1080 static const unsigned AddChain[33][2] = {
1081 {0, 0}, // Unused.
1082 {0, 0}, // Unused (base case = pow1).
1083 {1, 1}, // Unused (pre-computed).
1084 {1, 2}, {2, 2}, {2, 3}, {3, 3}, {2, 5}, {4, 4},
1085 {1, 8}, {5, 5}, {1, 10}, {6, 6}, {4, 9}, {7, 7},
1086 {3, 12}, {8, 8}, {8, 9}, {2, 16}, {1, 18}, {10, 10},
1087 {6, 15}, {11, 11}, {3, 20}, {12, 12}, {8, 17}, {13, 13},
1088 {3, 24}, {14, 14}, {4, 25}, {15, 15}, {3, 28}, {16, 16},
1089 };
1090
1091 InnerChain[Exp] = B.CreateFMul(getPow(InnerChain, AddChain[Exp][0], B),
1092 getPow(InnerChain, AddChain[Exp][1], B));
1093 return InnerChain[Exp];
1094}
1095
Chris Bienemanad070d02014-09-17 20:55:46 +00001096Value *LibCallSimplifier::optimizePow(CallInst *CI, IRBuilder<> &B) {
1097 Function *Callee = CI->getCalledFunction();
Chris Bienemanad070d02014-09-17 20:55:46 +00001098 Value *Ret = nullptr;
Davide Italianoa3458772015-11-05 19:18:23 +00001099 StringRef Name = Callee->getName();
1100 if (UnsafeFPShrink && Name == "pow" && hasFloatVersion(Name))
Chris Bienemanad070d02014-09-17 20:55:46 +00001101 Ret = optimizeUnaryDoubleFP(CI, B, true);
Bob Wilsond8d92d92013-11-03 06:48:38 +00001102
Chris Bienemanad070d02014-09-17 20:55:46 +00001103 FunctionType *FT = Callee->getFunctionType();
1104 // Just make sure this has 2 arguments of the same FP type, which match the
1105 // result type.
1106 if (FT->getNumParams() != 2 || FT->getReturnType() != FT->getParamType(0) ||
1107 FT->getParamType(0) != FT->getParamType(1) ||
1108 !FT->getParamType(0)->isFloatingPointTy())
1109 return Ret;
Bob Wilsond8d92d92013-11-03 06:48:38 +00001110
Chris Bienemanad070d02014-09-17 20:55:46 +00001111 Value *Op1 = CI->getArgOperand(0), *Op2 = CI->getArgOperand(1);
1112 if (ConstantFP *Op1C = dyn_cast<ConstantFP>(Op1)) {
1113 // pow(1.0, x) -> 1.0
1114 if (Op1C->isExactlyValue(1.0))
1115 return Op1C;
1116 // pow(2.0, x) -> exp2(x)
1117 if (Op1C->isExactlyValue(2.0) &&
1118 hasUnaryFloatFn(TLI, Op1->getType(), LibFunc::exp2, LibFunc::exp2f,
1119 LibFunc::exp2l))
Davide Italianod9f87b42015-11-06 21:05:07 +00001120 return EmitUnaryFloatFnCall(Op2, TLI->getName(LibFunc::exp2), B,
1121 Callee->getAttributes());
Chris Bienemanad070d02014-09-17 20:55:46 +00001122 // pow(10.0, x) -> exp10(x)
1123 if (Op1C->isExactlyValue(10.0) &&
1124 hasUnaryFloatFn(TLI, Op1->getType(), LibFunc::exp10, LibFunc::exp10f,
1125 LibFunc::exp10l))
1126 return EmitUnaryFloatFnCall(Op2, TLI->getName(LibFunc::exp10), B,
1127 Callee->getAttributes());
Bob Wilsond8d92d92013-11-03 06:48:38 +00001128 }
1129
Sanjay Patel6002e782016-01-12 17:30:37 +00001130 // pow(exp(x), y) -> exp(x * y)
Davide Italianoc8a79132015-11-03 20:32:23 +00001131 // pow(exp2(x), y) -> exp2(x * y)
Sanjay Patel6002e782016-01-12 17:30:37 +00001132 // We enable these only with fast-math. Besides rounding differences, the
1133 // transformation changes overflow and underflow behavior quite dramatically.
Davide Italianoc8a79132015-11-03 20:32:23 +00001134 // Example: x = 1000, y = 0.001.
1135 // pow(exp(x), y) = pow(inf, 0.001) = inf, whereas exp(x*y) = exp(1).
Sanjay Patel6002e782016-01-12 17:30:37 +00001136 auto *OpC = dyn_cast<CallInst>(Op1);
1137 if (OpC && OpC->hasUnsafeAlgebra() && CI->hasUnsafeAlgebra()) {
1138 LibFunc::Func Func;
1139 Function *OpCCallee = OpC->getCalledFunction();
1140 if (OpCCallee && TLI->getLibFunc(OpCCallee->getName(), Func) &&
1141 TLI->has(Func) && (Func == LibFunc::exp || Func == LibFunc::exp2)) {
Davide Italianoc8a79132015-11-03 20:32:23 +00001142 IRBuilder<>::FastMathFlagGuard Guard(B);
Sanjay Patela2528152016-01-12 18:03:37 +00001143 B.setFastMathFlags(CI->getFastMathFlags());
Sanjay Patel6002e782016-01-12 17:30:37 +00001144 Value *FMul = B.CreateFMul(OpC->getArgOperand(0), Op2, "mul");
1145 return EmitUnaryFloatFnCall(FMul, OpCCallee->getName(), B,
1146 OpCCallee->getAttributes());
Davide Italianoc8a79132015-11-03 20:32:23 +00001147 }
1148 }
1149
Chris Bienemanad070d02014-09-17 20:55:46 +00001150 ConstantFP *Op2C = dyn_cast<ConstantFP>(Op2);
1151 if (!Op2C)
1152 return Ret;
1153
1154 if (Op2C->getValueAPF().isZero()) // pow(x, 0.0) -> 1.0
1155 return ConstantFP::get(CI->getType(), 1.0);
1156
1157 if (Op2C->isExactlyValue(0.5) &&
1158 hasUnaryFloatFn(TLI, Op2->getType(), LibFunc::sqrt, LibFunc::sqrtf,
1159 LibFunc::sqrtl) &&
1160 hasUnaryFloatFn(TLI, Op2->getType(), LibFunc::fabs, LibFunc::fabsf,
1161 LibFunc::fabsl)) {
Davide Italianoc5cedd12015-11-18 23:21:32 +00001162
1163 // In -ffast-math, pow(x, 0.5) -> sqrt(x).
Sanjay Patel53ba88d2016-01-12 19:06:35 +00001164 if (CI->hasUnsafeAlgebra()) {
1165 IRBuilder<>::FastMathFlagGuard Guard(B);
1166 B.setFastMathFlags(CI->getFastMathFlags());
Davide Italianoc5cedd12015-11-18 23:21:32 +00001167 return EmitUnaryFloatFnCall(Op1, TLI->getName(LibFunc::sqrt), B,
1168 Callee->getAttributes());
Sanjay Patel53ba88d2016-01-12 19:06:35 +00001169 }
Davide Italianoc5cedd12015-11-18 23:21:32 +00001170
Chris Bienemanad070d02014-09-17 20:55:46 +00001171 // Expand pow(x, 0.5) to (x == -infinity ? +infinity : fabs(sqrt(x))).
1172 // This is faster than calling pow, and still handles negative zero
1173 // and negative infinity correctly.
Chris Bienemanad070d02014-09-17 20:55:46 +00001174 // TODO: In finite-only mode, this could be just fabs(sqrt(x)).
1175 Value *Inf = ConstantFP::getInfinity(CI->getType());
1176 Value *NegInf = ConstantFP::getInfinity(CI->getType(), true);
1177 Value *Sqrt = EmitUnaryFloatFnCall(Op1, "sqrt", B, Callee->getAttributes());
1178 Value *FAbs =
1179 EmitUnaryFloatFnCall(Sqrt, "fabs", B, Callee->getAttributes());
1180 Value *FCmp = B.CreateFCmpOEQ(Op1, NegInf);
1181 Value *Sel = B.CreateSelect(FCmp, Inf, FAbs);
1182 return Sel;
Bob Wilsond8d92d92013-11-03 06:48:38 +00001183 }
1184
Chris Bienemanad070d02014-09-17 20:55:46 +00001185 if (Op2C->isExactlyValue(1.0)) // pow(x, 1.0) -> x
1186 return Op1;
1187 if (Op2C->isExactlyValue(2.0)) // pow(x, 2.0) -> x*x
1188 return B.CreateFMul(Op1, Op1, "pow2");
1189 if (Op2C->isExactlyValue(-1.0)) // pow(x, -1.0) -> 1.0/x
1190 return B.CreateFDiv(ConstantFP::get(CI->getType(), 1.0), Op1, "powrecip");
Weiming Zhao82130722015-12-04 22:00:47 +00001191
1192 // In -ffast-math, generate repeated fmul instead of generating pow(x, n).
Sanjay Patel81a63cd2016-01-19 18:15:12 +00001193 if (CI->hasUnsafeAlgebra()) {
Weiming Zhao82130722015-12-04 22:00:47 +00001194 APFloat V = abs(Op2C->getValueAPF());
1195 // We limit to a max of 7 fmul(s). Thus max exponent is 32.
1196 // This transformation applies to integer exponents only.
1197 if (V.compare(APFloat(V.getSemantics(), 32.0)) == APFloat::cmpGreaterThan ||
1198 !V.isInteger())
1199 return nullptr;
1200
1201 // We will memoize intermediate products of the Addition Chain.
1202 Value *InnerChain[33] = {nullptr};
1203 InnerChain[1] = Op1;
1204 InnerChain[2] = B.CreateFMul(Op1, Op1);
1205
1206 // We cannot readily convert a non-double type (like float) to a double.
1207 // So we first convert V to something which could be converted to double.
1208 bool ignored;
1209 V.convert(APFloat::IEEEdouble, APFloat::rmTowardZero, &ignored);
Sanjay Patel81a63cd2016-01-19 18:15:12 +00001210
1211 // TODO: Should the new instructions propagate the 'fast' flag of the pow()?
Weiming Zhao82130722015-12-04 22:00:47 +00001212 Value *FMul = getPow(InnerChain, V.convertToDouble(), B);
1213 // For negative exponents simply compute the reciprocal.
1214 if (Op2C->isNegative())
1215 FMul = B.CreateFDiv(ConstantFP::get(CI->getType(), 1.0), FMul);
1216 return FMul;
1217 }
1218
Chris Bienemanad070d02014-09-17 20:55:46 +00001219 return nullptr;
1220}
Bob Wilsond8d92d92013-11-03 06:48:38 +00001221
Chris Bienemanad070d02014-09-17 20:55:46 +00001222Value *LibCallSimplifier::optimizeExp2(CallInst *CI, IRBuilder<> &B) {
1223 Function *Callee = CI->getCalledFunction();
1224 Function *Caller = CI->getParent()->getParent();
Chris Bienemanad070d02014-09-17 20:55:46 +00001225 Value *Ret = nullptr;
Davide Italianoa3458772015-11-05 19:18:23 +00001226 StringRef Name = Callee->getName();
1227 if (UnsafeFPShrink && Name == "exp2" && hasFloatVersion(Name))
Chris Bienemanad070d02014-09-17 20:55:46 +00001228 Ret = optimizeUnaryDoubleFP(CI, B, true);
Bob Wilsond8d92d92013-11-03 06:48:38 +00001229
Chris Bienemanad070d02014-09-17 20:55:46 +00001230 FunctionType *FT = Callee->getFunctionType();
1231 // Just make sure this has 1 argument of FP type, which matches the
1232 // result type.
1233 if (FT->getNumParams() != 1 || FT->getReturnType() != FT->getParamType(0) ||
1234 !FT->getParamType(0)->isFloatingPointTy())
1235 return Ret;
1236
1237 Value *Op = CI->getArgOperand(0);
1238 // Turn exp2(sitofp(x)) -> ldexp(1.0, sext(x)) if sizeof(x) <= 32
1239 // Turn exp2(uitofp(x)) -> ldexp(1.0, zext(x)) if sizeof(x) < 32
1240 LibFunc::Func LdExp = LibFunc::ldexpl;
1241 if (Op->getType()->isFloatTy())
1242 LdExp = LibFunc::ldexpf;
1243 else if (Op->getType()->isDoubleTy())
1244 LdExp = LibFunc::ldexp;
1245
1246 if (TLI->has(LdExp)) {
1247 Value *LdExpArg = nullptr;
1248 if (SIToFPInst *OpC = dyn_cast<SIToFPInst>(Op)) {
1249 if (OpC->getOperand(0)->getType()->getPrimitiveSizeInBits() <= 32)
1250 LdExpArg = B.CreateSExt(OpC->getOperand(0), B.getInt32Ty());
1251 } else if (UIToFPInst *OpC = dyn_cast<UIToFPInst>(Op)) {
1252 if (OpC->getOperand(0)->getType()->getPrimitiveSizeInBits() < 32)
1253 LdExpArg = B.CreateZExt(OpC->getOperand(0), B.getInt32Ty());
1254 }
1255
1256 if (LdExpArg) {
1257 Constant *One = ConstantFP::get(CI->getContext(), APFloat(1.0f));
1258 if (!Op->getType()->isFloatTy())
1259 One = ConstantExpr::getFPExtend(One, Op->getType());
1260
1261 Module *M = Caller->getParent();
1262 Value *Callee =
1263 M->getOrInsertFunction(TLI->getName(LdExp), Op->getType(),
Reid Kleckner971c3ea2014-11-13 22:55:19 +00001264 Op->getType(), B.getInt32Ty(), nullptr);
David Blaikieff6409d2015-05-18 22:13:54 +00001265 CallInst *CI = B.CreateCall(Callee, {One, LdExpArg});
Chris Bienemanad070d02014-09-17 20:55:46 +00001266 if (const Function *F = dyn_cast<Function>(Callee->stripPointerCasts()))
1267 CI->setCallingConv(F->getCallingConv());
1268
1269 return CI;
1270 }
1271 }
1272 return Ret;
1273}
1274
Sanjay Patel0ca42bb2014-10-14 20:43:11 +00001275Value *LibCallSimplifier::optimizeFabs(CallInst *CI, IRBuilder<> &B) {
1276 Function *Callee = CI->getCalledFunction();
Sanjay Patel0ca42bb2014-10-14 20:43:11 +00001277 Value *Ret = nullptr;
Davide Italianoa3458772015-11-05 19:18:23 +00001278 StringRef Name = Callee->getName();
1279 if (Name == "fabs" && hasFloatVersion(Name))
Sanjay Patel0ca42bb2014-10-14 20:43:11 +00001280 Ret = optimizeUnaryDoubleFP(CI, B, false);
Sanjay Patel0ca42bb2014-10-14 20:43:11 +00001281
1282 FunctionType *FT = Callee->getFunctionType();
1283 // Make sure this has 1 argument of FP type which matches the result type.
1284 if (FT->getNumParams() != 1 || FT->getReturnType() != FT->getParamType(0) ||
1285 !FT->getParamType(0)->isFloatingPointTy())
1286 return Ret;
1287
1288 Value *Op = CI->getArgOperand(0);
1289 if (Instruction *I = dyn_cast<Instruction>(Op)) {
1290 // Fold fabs(x * x) -> x * x; any squared FP value must already be positive.
1291 if (I->getOpcode() == Instruction::FMul)
1292 if (I->getOperand(0) == I->getOperand(1))
1293 return Op;
1294 }
1295 return Ret;
1296}
1297
Sanjay Patel57fd1dc2015-08-16 20:18:19 +00001298Value *LibCallSimplifier::optimizeFMinFMax(CallInst *CI, IRBuilder<> &B) {
1299 // If we can shrink the call to a float function rather than a double
1300 // function, do that first.
1301 Function *Callee = CI->getCalledFunction();
Davide Italianoa3458772015-11-05 19:18:23 +00001302 StringRef Name = Callee->getName();
Sanjay Patelc7ddb7f2016-01-06 00:32:15 +00001303 if ((Name == "fmin" || Name == "fmax") && hasFloatVersion(Name))
1304 if (Value *Ret = optimizeBinaryDoubleFP(CI, B))
Sanjay Patel57fd1dc2015-08-16 20:18:19 +00001305 return Ret;
Sanjay Patel57fd1dc2015-08-16 20:18:19 +00001306
1307 // Make sure this has 2 arguments of FP type which match the result type.
1308 FunctionType *FT = Callee->getFunctionType();
1309 if (FT->getNumParams() != 2 || FT->getReturnType() != FT->getParamType(0) ||
1310 FT->getParamType(0) != FT->getParamType(1) ||
1311 !FT->getParamType(0)->isFloatingPointTy())
1312 return nullptr;
1313
Benjamin Kramerbb70d752015-08-16 21:16:37 +00001314 IRBuilder<>::FastMathFlagGuard Guard(B);
Sanjay Patel57fd1dc2015-08-16 20:18:19 +00001315 FastMathFlags FMF;
Sanjay Patel29095ea2016-01-05 20:46:19 +00001316 if (CI->hasUnsafeAlgebra()) {
Sanjay Patel57fd1dc2015-08-16 20:18:19 +00001317 // Unsafe algebra sets all fast-math-flags to true.
1318 FMF.setUnsafeAlgebra();
1319 } else {
1320 // At a minimum, no-nans-fp-math must be true.
Sanjay Patel29095ea2016-01-05 20:46:19 +00001321 if (!CI->hasNoNaNs())
Sanjay Patel57fd1dc2015-08-16 20:18:19 +00001322 return nullptr;
1323 // No-signed-zeros is implied by the definitions of fmax/fmin themselves:
1324 // "Ideally, fmax would be sensitive to the sign of zero, for example
NAKAMURA Takumi0d725392015-09-07 00:26:54 +00001325 // fmax(-0. 0, +0. 0) would return +0; however, implementation in software
Sanjay Patel57fd1dc2015-08-16 20:18:19 +00001326 // might be impractical."
1327 FMF.setNoSignedZeros();
1328 FMF.setNoNaNs();
1329 }
Sanjay Patela2528152016-01-12 18:03:37 +00001330 B.setFastMathFlags(FMF);
Sanjay Patel57fd1dc2015-08-16 20:18:19 +00001331
1332 // We have a relaxed floating-point environment. We can ignore NaN-handling
1333 // and transform to a compare and select. We do not have to consider errno or
1334 // exceptions, because fmin/fmax do not have those.
1335 Value *Op0 = CI->getArgOperand(0);
1336 Value *Op1 = CI->getArgOperand(1);
1337 Value *Cmp = Callee->getName().startswith("fmin") ?
1338 B.CreateFCmpOLT(Op0, Op1) : B.CreateFCmpOGT(Op0, Op1);
1339 return B.CreateSelect(Cmp, Op0, Op1);
1340}
1341
Davide Italianob8b71332015-11-29 20:58:04 +00001342Value *LibCallSimplifier::optimizeLog(CallInst *CI, IRBuilder<> &B) {
1343 Function *Callee = CI->getCalledFunction();
1344 Value *Ret = nullptr;
1345 StringRef Name = Callee->getName();
1346 if (UnsafeFPShrink && hasFloatVersion(Name))
1347 Ret = optimizeUnaryDoubleFP(CI, B, true);
1348 FunctionType *FT = Callee->getFunctionType();
1349
1350 // Just make sure this has 1 argument of FP type, which matches the
1351 // result type.
1352 if (FT->getNumParams() != 1 || FT->getReturnType() != FT->getParamType(0) ||
1353 !FT->getParamType(0)->isFloatingPointTy())
1354 return Ret;
1355
Sanjay Patele896ede2016-01-11 23:31:48 +00001356 if (!CI->hasUnsafeAlgebra())
Davide Italianob8b71332015-11-29 20:58:04 +00001357 return Ret;
1358 Value *Op1 = CI->getArgOperand(0);
1359 auto *OpC = dyn_cast<CallInst>(Op1);
Sanjay Patele896ede2016-01-11 23:31:48 +00001360
1361 // The earlier call must also be unsafe in order to do these transforms.
1362 if (!OpC || !OpC->hasUnsafeAlgebra())
Davide Italianob8b71332015-11-29 20:58:04 +00001363 return Ret;
1364
1365 // log(pow(x,y)) -> y*log(x)
1366 // This is only applicable to log, log2, log10.
1367 if (Name != "log" && Name != "log2" && Name != "log10")
1368 return Ret;
1369
1370 IRBuilder<>::FastMathFlagGuard Guard(B);
1371 FastMathFlags FMF;
1372 FMF.setUnsafeAlgebra();
Sanjay Patela2528152016-01-12 18:03:37 +00001373 B.setFastMathFlags(FMF);
Davide Italianob8b71332015-11-29 20:58:04 +00001374
1375 LibFunc::Func Func;
1376 Function *F = OpC->getCalledFunction();
Davide Italiano0b14f292015-11-29 21:58:56 +00001377 if (F && ((TLI->getLibFunc(F->getName(), Func) && TLI->has(Func) &&
1378 Func == LibFunc::pow) || F->getIntrinsicID() == Intrinsic::pow))
Davide Italianob8b71332015-11-29 20:58:04 +00001379 return B.CreateFMul(OpC->getArgOperand(1),
1380 EmitUnaryFloatFnCall(OpC->getOperand(0), Callee->getName(), B,
1381 Callee->getAttributes()), "mul");
Davide Italiano1aeed6a2015-11-30 19:36:35 +00001382
1383 // log(exp2(y)) -> y*log(2)
1384 if (F && Name == "log" && TLI->getLibFunc(F->getName(), Func) &&
1385 TLI->has(Func) && Func == LibFunc::exp2)
1386 return B.CreateFMul(
1387 OpC->getArgOperand(0),
1388 EmitUnaryFloatFnCall(ConstantFP::get(CI->getType(), 2.0),
1389 Callee->getName(), B, Callee->getAttributes()),
1390 "logmul");
Davide Italianob8b71332015-11-29 20:58:04 +00001391 return Ret;
1392}
1393
Sanjay Patelc699a612014-10-16 18:48:17 +00001394Value *LibCallSimplifier::optimizeSqrt(CallInst *CI, IRBuilder<> &B) {
1395 Function *Callee = CI->getCalledFunction();
1396
1397 Value *Ret = nullptr;
Sanjay Patel848309d2014-10-23 21:52:45 +00001398 if (TLI->has(LibFunc::sqrtf) && (Callee->getName() == "sqrt" ||
1399 Callee->getIntrinsicID() == Intrinsic::sqrt))
Sanjay Patelc699a612014-10-16 18:48:17 +00001400 Ret = optimizeUnaryDoubleFP(CI, B, true);
Sanjay Patel683f2972016-01-11 22:34:19 +00001401
1402 if (!CI->hasUnsafeAlgebra())
Davide Italianoa904e522015-10-29 02:58:44 +00001403 return Ret;
Sanjay Patelc699a612014-10-16 18:48:17 +00001404
Sanjay Patelc2d64612016-01-06 20:52:21 +00001405 Instruction *I = dyn_cast<Instruction>(CI->getArgOperand(0));
1406 if (!I || I->getOpcode() != Instruction::FMul || !I->hasUnsafeAlgebra())
1407 return Ret;
1408
1409 // We're looking for a repeated factor in a multiplication tree,
1410 // so we can do this fold: sqrt(x * x) -> fabs(x);
Sanjay Patel683f2972016-01-11 22:34:19 +00001411 // or this fold: sqrt((x * x) * y) -> fabs(x) * sqrt(y).
Sanjay Patelc2d64612016-01-06 20:52:21 +00001412 Value *Op0 = I->getOperand(0);
1413 Value *Op1 = I->getOperand(1);
1414 Value *RepeatOp = nullptr;
1415 Value *OtherOp = nullptr;
1416 if (Op0 == Op1) {
1417 // Simple match: the operands of the multiply are identical.
1418 RepeatOp = Op0;
1419 } else {
1420 // Look for a more complicated pattern: one of the operands is itself
1421 // a multiply, so search for a common factor in that multiply.
1422 // Note: We don't bother looking any deeper than this first level or for
1423 // variations of this pattern because instcombine's visitFMUL and/or the
1424 // reassociation pass should give us this form.
1425 Value *OtherMul0, *OtherMul1;
1426 if (match(Op0, m_FMul(m_Value(OtherMul0), m_Value(OtherMul1)))) {
1427 // Pattern: sqrt((x * y) * z)
Sanjay Patel6c1ddbb2016-01-11 22:50:36 +00001428 if (OtherMul0 == OtherMul1 &&
1429 cast<Instruction>(Op0)->hasUnsafeAlgebra()) {
Sanjay Patelc2d64612016-01-06 20:52:21 +00001430 // Matched: sqrt((x * x) * z)
1431 RepeatOp = OtherMul0;
1432 OtherOp = Op1;
Sanjay Patelc699a612014-10-16 18:48:17 +00001433 }
1434 }
1435 }
Sanjay Patelc2d64612016-01-06 20:52:21 +00001436 if (!RepeatOp)
1437 return Ret;
1438
1439 // Fast math flags for any created instructions should match the sqrt
1440 // and multiply.
Sanjay Patelc2d64612016-01-06 20:52:21 +00001441 IRBuilder<>::FastMathFlagGuard Guard(B);
Sanjay Patela2528152016-01-12 18:03:37 +00001442 B.setFastMathFlags(I->getFastMathFlags());
Sanjay Patel9f67dad2016-01-11 22:35:39 +00001443
Sanjay Patelc2d64612016-01-06 20:52:21 +00001444 // If we found a repeated factor, hoist it out of the square root and
1445 // replace it with the fabs of that factor.
1446 Module *M = Callee->getParent();
1447 Type *ArgType = I->getType();
1448 Value *Fabs = Intrinsic::getDeclaration(M, Intrinsic::fabs, ArgType);
1449 Value *FabsCall = B.CreateCall(Fabs, RepeatOp, "fabs");
1450 if (OtherOp) {
1451 // If we found a non-repeated factor, we still need to get its square
1452 // root. We then multiply that by the value that was simplified out
1453 // of the square root calculation.
1454 Value *Sqrt = Intrinsic::getDeclaration(M, Intrinsic::sqrt, ArgType);
1455 Value *SqrtCall = B.CreateCall(Sqrt, OtherOp, "sqrt");
1456 return B.CreateFMul(FabsCall, SqrtCall);
1457 }
1458 return FabsCall;
Sanjay Patelc699a612014-10-16 18:48:17 +00001459}
1460
Sanjay Patelcddcd722016-01-06 19:23:35 +00001461// TODO: Generalize to handle any trig function and its inverse.
Davide Italiano51507d22015-11-04 23:36:56 +00001462Value *LibCallSimplifier::optimizeTan(CallInst *CI, IRBuilder<> &B) {
1463 Function *Callee = CI->getCalledFunction();
1464 Value *Ret = nullptr;
Davide Italianoa3458772015-11-05 19:18:23 +00001465 StringRef Name = Callee->getName();
1466 if (UnsafeFPShrink && Name == "tan" && hasFloatVersion(Name))
Davide Italiano51507d22015-11-04 23:36:56 +00001467 Ret = optimizeUnaryDoubleFP(CI, B, true);
1468 FunctionType *FT = Callee->getFunctionType();
1469
1470 // Just make sure this has 1 argument of FP type, which matches the
1471 // result type.
1472 if (FT->getNumParams() != 1 || FT->getReturnType() != FT->getParamType(0) ||
1473 !FT->getParamType(0)->isFloatingPointTy())
1474 return Ret;
1475
Davide Italiano51507d22015-11-04 23:36:56 +00001476 Value *Op1 = CI->getArgOperand(0);
1477 auto *OpC = dyn_cast<CallInst>(Op1);
1478 if (!OpC)
1479 return Ret;
1480
Sanjay Patelcddcd722016-01-06 19:23:35 +00001481 // Both calls must allow unsafe optimizations in order to remove them.
1482 if (!CI->hasUnsafeAlgebra() || !OpC->hasUnsafeAlgebra())
1483 return Ret;
1484
Davide Italiano51507d22015-11-04 23:36:56 +00001485 // tan(atan(x)) -> x
1486 // tanf(atanf(x)) -> x
1487 // tanl(atanl(x)) -> x
1488 LibFunc::Func Func;
1489 Function *F = OpC->getCalledFunction();
Benjamin Kramerfb419e72015-11-26 09:51:17 +00001490 if (F && TLI->getLibFunc(F->getName(), Func) && TLI->has(Func) &&
Davide Italiano51507d22015-11-04 23:36:56 +00001491 ((Func == LibFunc::atan && Callee->getName() == "tan") ||
1492 (Func == LibFunc::atanf && Callee->getName() == "tanf") ||
1493 (Func == LibFunc::atanl && Callee->getName() == "tanl")))
1494 Ret = OpC->getArgOperand(0);
1495 return Ret;
1496}
1497
Chris Bienemanad070d02014-09-17 20:55:46 +00001498static bool isTrigLibCall(CallInst *CI);
1499static void insertSinCosCall(IRBuilder<> &B, Function *OrigCallee, Value *Arg,
1500 bool UseFloat, Value *&Sin, Value *&Cos,
1501 Value *&SinCos);
1502
1503Value *LibCallSimplifier::optimizeSinCosPi(CallInst *CI, IRBuilder<> &B) {
1504
1505 // Make sure the prototype is as expected, otherwise the rest of the
1506 // function is probably invalid and likely to abort.
1507 if (!isTrigLibCall(CI))
1508 return nullptr;
1509
1510 Value *Arg = CI->getArgOperand(0);
1511 SmallVector<CallInst *, 1> SinCalls;
1512 SmallVector<CallInst *, 1> CosCalls;
1513 SmallVector<CallInst *, 1> SinCosCalls;
1514
1515 bool IsFloat = Arg->getType()->isFloatTy();
1516
1517 // Look for all compatible sinpi, cospi and sincospi calls with the same
1518 // argument. If there are enough (in some sense) we can make the
1519 // substitution.
1520 for (User *U : Arg->users())
1521 classifyArgUse(U, CI->getParent(), IsFloat, SinCalls, CosCalls,
1522 SinCosCalls);
1523
1524 // It's only worthwhile if both sinpi and cospi are actually used.
1525 if (SinCosCalls.empty() && (SinCalls.empty() || CosCalls.empty()))
1526 return nullptr;
1527
1528 Value *Sin, *Cos, *SinCos;
1529 insertSinCosCall(B, CI->getCalledFunction(), Arg, IsFloat, Sin, Cos, SinCos);
1530
1531 replaceTrigInsts(SinCalls, Sin);
1532 replaceTrigInsts(CosCalls, Cos);
1533 replaceTrigInsts(SinCosCalls, SinCos);
1534
1535 return nullptr;
1536}
1537
1538static bool isTrigLibCall(CallInst *CI) {
1539 Function *Callee = CI->getCalledFunction();
1540 FunctionType *FT = Callee->getFunctionType();
1541
1542 // We can only hope to do anything useful if we can ignore things like errno
1543 // and floating-point exceptions.
1544 bool AttributesSafe =
1545 CI->hasFnAttr(Attribute::NoUnwind) && CI->hasFnAttr(Attribute::ReadNone);
1546
1547 // Other than that we need float(float) or double(double)
1548 return AttributesSafe && FT->getNumParams() == 1 &&
1549 FT->getReturnType() == FT->getParamType(0) &&
1550 (FT->getParamType(0)->isFloatTy() ||
1551 FT->getParamType(0)->isDoubleTy());
1552}
1553
1554void
1555LibCallSimplifier::classifyArgUse(Value *Val, BasicBlock *BB, bool IsFloat,
1556 SmallVectorImpl<CallInst *> &SinCalls,
1557 SmallVectorImpl<CallInst *> &CosCalls,
1558 SmallVectorImpl<CallInst *> &SinCosCalls) {
1559 CallInst *CI = dyn_cast<CallInst>(Val);
1560
1561 if (!CI)
1562 return;
1563
1564 Function *Callee = CI->getCalledFunction();
Chris Bienemanad070d02014-09-17 20:55:46 +00001565 LibFunc::Func Func;
Benjamin Kramer89766e52015-11-28 21:43:12 +00001566 if (!Callee || !TLI->getLibFunc(Callee->getName(), Func) || !TLI->has(Func) ||
1567 !isTrigLibCall(CI))
Chris Bienemanad070d02014-09-17 20:55:46 +00001568 return;
1569
1570 if (IsFloat) {
1571 if (Func == LibFunc::sinpif)
1572 SinCalls.push_back(CI);
1573 else if (Func == LibFunc::cospif)
1574 CosCalls.push_back(CI);
1575 else if (Func == LibFunc::sincospif_stret)
1576 SinCosCalls.push_back(CI);
1577 } else {
1578 if (Func == LibFunc::sinpi)
1579 SinCalls.push_back(CI);
1580 else if (Func == LibFunc::cospi)
1581 CosCalls.push_back(CI);
1582 else if (Func == LibFunc::sincospi_stret)
1583 SinCosCalls.push_back(CI);
1584 }
1585}
1586
1587void LibCallSimplifier::replaceTrigInsts(SmallVectorImpl<CallInst *> &Calls,
1588 Value *Res) {
Davide Italianoc6926882015-10-27 04:17:51 +00001589 for (CallInst *C : Calls)
1590 replaceAllUsesWith(C, Res);
Chris Bienemanad070d02014-09-17 20:55:46 +00001591}
1592
1593void insertSinCosCall(IRBuilder<> &B, Function *OrigCallee, Value *Arg,
1594 bool UseFloat, Value *&Sin, Value *&Cos, Value *&SinCos) {
1595 Type *ArgTy = Arg->getType();
1596 Type *ResTy;
1597 StringRef Name;
1598
1599 Triple T(OrigCallee->getParent()->getTargetTriple());
1600 if (UseFloat) {
1601 Name = "__sincospif_stret";
1602
1603 assert(T.getArch() != Triple::x86 && "x86 messy and unsupported for now");
1604 // x86_64 can't use {float, float} since that would be returned in both
1605 // xmm0 and xmm1, which isn't what a real struct would do.
1606 ResTy = T.getArch() == Triple::x86_64
1607 ? static_cast<Type *>(VectorType::get(ArgTy, 2))
Reid Kleckner971c3ea2014-11-13 22:55:19 +00001608 : static_cast<Type *>(StructType::get(ArgTy, ArgTy, nullptr));
Chris Bienemanad070d02014-09-17 20:55:46 +00001609 } else {
1610 Name = "__sincospi_stret";
Reid Kleckner971c3ea2014-11-13 22:55:19 +00001611 ResTy = StructType::get(ArgTy, ArgTy, nullptr);
Chris Bienemanad070d02014-09-17 20:55:46 +00001612 }
1613
1614 Module *M = OrigCallee->getParent();
1615 Value *Callee = M->getOrInsertFunction(Name, OrigCallee->getAttributes(),
Reid Kleckner971c3ea2014-11-13 22:55:19 +00001616 ResTy, ArgTy, nullptr);
Chris Bienemanad070d02014-09-17 20:55:46 +00001617
1618 if (Instruction *ArgInst = dyn_cast<Instruction>(Arg)) {
1619 // If the argument is an instruction, it must dominate all uses so put our
1620 // sincos call there.
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +00001621 B.SetInsertPoint(ArgInst->getParent(), ++ArgInst->getIterator());
Chris Bienemanad070d02014-09-17 20:55:46 +00001622 } else {
1623 // Otherwise (e.g. for a constant) the beginning of the function is as
1624 // good a place as any.
1625 BasicBlock &EntryBB = B.GetInsertBlock()->getParent()->getEntryBlock();
1626 B.SetInsertPoint(&EntryBB, EntryBB.begin());
1627 }
1628
1629 SinCos = B.CreateCall(Callee, Arg, "sincospi");
1630
1631 if (SinCos->getType()->isStructTy()) {
1632 Sin = B.CreateExtractValue(SinCos, 0, "sinpi");
1633 Cos = B.CreateExtractValue(SinCos, 1, "cospi");
1634 } else {
1635 Sin = B.CreateExtractElement(SinCos, ConstantInt::get(B.getInt32Ty(), 0),
1636 "sinpi");
1637 Cos = B.CreateExtractElement(SinCos, ConstantInt::get(B.getInt32Ty(), 1),
1638 "cospi");
1639 }
1640}
Bob Wilsond8d92d92013-11-03 06:48:38 +00001641
Meador Inge7415f842012-11-25 20:45:27 +00001642//===----------------------------------------------------------------------===//
1643// Integer Library Call Optimizations
1644//===----------------------------------------------------------------------===//
1645
Davide Italiano396f3ee2015-10-31 23:17:45 +00001646static bool checkIntUnaryReturnAndParam(Function *Callee) {
1647 FunctionType *FT = Callee->getFunctionType();
Davide Italiano5cdf9152015-11-01 00:09:16 +00001648 return FT->getNumParams() == 1 && FT->getReturnType()->isIntegerTy(32) &&
1649 FT->getParamType(0)->isIntegerTy();
Davide Italiano396f3ee2015-10-31 23:17:45 +00001650}
1651
Chris Bienemanad070d02014-09-17 20:55:46 +00001652Value *LibCallSimplifier::optimizeFFS(CallInst *CI, IRBuilder<> &B) {
1653 Function *Callee = CI->getCalledFunction();
Davide Italiano396f3ee2015-10-31 23:17:45 +00001654 if (!checkIntUnaryReturnAndParam(Callee))
Chris Bienemanad070d02014-09-17 20:55:46 +00001655 return nullptr;
Chris Bienemanad070d02014-09-17 20:55:46 +00001656 Value *Op = CI->getArgOperand(0);
Meador Inge7415f842012-11-25 20:45:27 +00001657
Chris Bienemanad070d02014-09-17 20:55:46 +00001658 // Constant fold.
1659 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op)) {
1660 if (CI->isZero()) // ffs(0) -> 0.
1661 return B.getInt32(0);
1662 // ffs(c) -> cttz(c)+1
1663 return B.getInt32(CI->getValue().countTrailingZeros() + 1);
Meador Inge7415f842012-11-25 20:45:27 +00001664 }
Meador Inge7415f842012-11-25 20:45:27 +00001665
Chris Bienemanad070d02014-09-17 20:55:46 +00001666 // ffs(x) -> x != 0 ? (i32)llvm.cttz(x)+1 : 0
1667 Type *ArgType = Op->getType();
1668 Value *F =
1669 Intrinsic::getDeclaration(Callee->getParent(), Intrinsic::cttz, ArgType);
Davide Italianoa1953862015-08-13 20:34:26 +00001670 Value *V = B.CreateCall(F, {Op, B.getTrue()}, "cttz");
Chris Bienemanad070d02014-09-17 20:55:46 +00001671 V = B.CreateAdd(V, ConstantInt::get(V->getType(), 1));
1672 V = B.CreateIntCast(V, B.getInt32Ty(), false);
Meador Ingea0b6d872012-11-26 00:24:07 +00001673
Chris Bienemanad070d02014-09-17 20:55:46 +00001674 Value *Cond = B.CreateICmpNE(Op, Constant::getNullValue(ArgType));
1675 return B.CreateSelect(Cond, V, B.getInt32(0));
1676}
Meador Ingea0b6d872012-11-26 00:24:07 +00001677
Chris Bienemanad070d02014-09-17 20:55:46 +00001678Value *LibCallSimplifier::optimizeAbs(CallInst *CI, IRBuilder<> &B) {
1679 Function *Callee = CI->getCalledFunction();
1680 FunctionType *FT = Callee->getFunctionType();
1681 // We require integer(integer) where the types agree.
1682 if (FT->getNumParams() != 1 || !FT->getReturnType()->isIntegerTy() ||
1683 FT->getParamType(0) != FT->getReturnType())
1684 return nullptr;
Meador Inge9a59ab62012-11-26 02:31:59 +00001685
Chris Bienemanad070d02014-09-17 20:55:46 +00001686 // abs(x) -> x >s -1 ? x : -x
1687 Value *Op = CI->getArgOperand(0);
1688 Value *Pos =
1689 B.CreateICmpSGT(Op, Constant::getAllOnesValue(Op->getType()), "ispos");
1690 Value *Neg = B.CreateNeg(Op, "neg");
1691 return B.CreateSelect(Pos, Op, Neg);
1692}
Meador Inge9a59ab62012-11-26 02:31:59 +00001693
Chris Bienemanad070d02014-09-17 20:55:46 +00001694Value *LibCallSimplifier::optimizeIsDigit(CallInst *CI, IRBuilder<> &B) {
Davide Italiano396f3ee2015-10-31 23:17:45 +00001695 if (!checkIntUnaryReturnAndParam(CI->getCalledFunction()))
Chris Bienemanad070d02014-09-17 20:55:46 +00001696 return nullptr;
Meador Ingea62a39e2012-11-26 03:10:07 +00001697
Chris Bienemanad070d02014-09-17 20:55:46 +00001698 // isdigit(c) -> (c-'0') <u 10
1699 Value *Op = CI->getArgOperand(0);
1700 Op = B.CreateSub(Op, B.getInt32('0'), "isdigittmp");
1701 Op = B.CreateICmpULT(Op, B.getInt32(10), "isdigit");
1702 return B.CreateZExt(Op, CI->getType());
1703}
Meador Ingea62a39e2012-11-26 03:10:07 +00001704
Chris Bienemanad070d02014-09-17 20:55:46 +00001705Value *LibCallSimplifier::optimizeIsAscii(CallInst *CI, IRBuilder<> &B) {
Davide Italiano396f3ee2015-10-31 23:17:45 +00001706 if (!checkIntUnaryReturnAndParam(CI->getCalledFunction()))
Chris Bienemanad070d02014-09-17 20:55:46 +00001707 return nullptr;
Meador Inge604937d2012-11-26 03:38:52 +00001708
Chris Bienemanad070d02014-09-17 20:55:46 +00001709 // isascii(c) -> c <u 128
1710 Value *Op = CI->getArgOperand(0);
1711 Op = B.CreateICmpULT(Op, B.getInt32(128), "isascii");
1712 return B.CreateZExt(Op, CI->getType());
1713}
1714
1715Value *LibCallSimplifier::optimizeToAscii(CallInst *CI, IRBuilder<> &B) {
Davide Italiano396f3ee2015-10-31 23:17:45 +00001716 if (!checkIntUnaryReturnAndParam(CI->getCalledFunction()))
Chris Bienemanad070d02014-09-17 20:55:46 +00001717 return nullptr;
1718
1719 // toascii(c) -> c & 0x7f
1720 return B.CreateAnd(CI->getArgOperand(0),
1721 ConstantInt::get(CI->getType(), 0x7F));
1722}
Meador Inge604937d2012-11-26 03:38:52 +00001723
Meador Inge08ca1152012-11-26 20:37:20 +00001724//===----------------------------------------------------------------------===//
1725// Formatting and IO Library Call Optimizations
1726//===----------------------------------------------------------------------===//
1727
Chris Bienemanad070d02014-09-17 20:55:46 +00001728static bool isReportingError(Function *Callee, CallInst *CI, int StreamArg);
Hal Finkel66cd3f12013-11-17 02:06:35 +00001729
Chris Bienemanad070d02014-09-17 20:55:46 +00001730Value *LibCallSimplifier::optimizeErrorReporting(CallInst *CI, IRBuilder<> &B,
1731 int StreamArg) {
1732 // Error reporting calls should be cold, mark them as such.
1733 // This applies even to non-builtin calls: it is only a hint and applies to
1734 // functions that the frontend might not understand as builtins.
Hal Finkel66cd3f12013-11-17 02:06:35 +00001735
Chris Bienemanad070d02014-09-17 20:55:46 +00001736 // This heuristic was suggested in:
1737 // Improving Static Branch Prediction in a Compiler
1738 // Brian L. Deitrich, Ben-Chung Cheng, Wen-mei W. Hwu
1739 // Proceedings of PACT'98, Oct. 1998, IEEE
1740 Function *Callee = CI->getCalledFunction();
Hal Finkel66cd3f12013-11-17 02:06:35 +00001741
Chris Bienemanad070d02014-09-17 20:55:46 +00001742 if (!CI->hasFnAttr(Attribute::Cold) &&
1743 isReportingError(Callee, CI, StreamArg)) {
1744 CI->addAttribute(AttributeSet::FunctionIndex, Attribute::Cold);
1745 }
Hal Finkel66cd3f12013-11-17 02:06:35 +00001746
Chris Bienemanad070d02014-09-17 20:55:46 +00001747 return nullptr;
1748}
1749
1750static bool isReportingError(Function *Callee, CallInst *CI, int StreamArg) {
Davide Italianoe84d4da2015-11-02 22:33:26 +00001751 if (!ColdErrorCalls || !Callee || !Callee->isDeclaration())
Chris Bienemanad070d02014-09-17 20:55:46 +00001752 return false;
1753
1754 if (StreamArg < 0)
1755 return true;
1756
1757 // These functions might be considered cold, but only if their stream
1758 // argument is stderr.
1759
1760 if (StreamArg >= (int)CI->getNumArgOperands())
1761 return false;
1762 LoadInst *LI = dyn_cast<LoadInst>(CI->getArgOperand(StreamArg));
1763 if (!LI)
1764 return false;
1765 GlobalVariable *GV = dyn_cast<GlobalVariable>(LI->getPointerOperand());
1766 if (!GV || !GV->isDeclaration())
1767 return false;
1768 return GV->getName() == "stderr";
1769}
1770
1771Value *LibCallSimplifier::optimizePrintFString(CallInst *CI, IRBuilder<> &B) {
1772 // Check for a fixed format string.
1773 StringRef FormatStr;
1774 if (!getConstantStringInfo(CI->getArgOperand(0), FormatStr))
Craig Topperf40110f2014-04-25 05:29:35 +00001775 return nullptr;
Hal Finkel66cd3f12013-11-17 02:06:35 +00001776
Chris Bienemanad070d02014-09-17 20:55:46 +00001777 // Empty format string -> noop.
1778 if (FormatStr.empty()) // Tolerate printf's declared void.
1779 return CI->use_empty() ? (Value *)CI : ConstantInt::get(CI->getType(), 0);
Hal Finkel66cd3f12013-11-17 02:06:35 +00001780
Chris Bienemanad070d02014-09-17 20:55:46 +00001781 // Do not do any of the following transformations if the printf return value
1782 // is used, in general the printf return value is not compatible with either
1783 // putchar() or puts().
1784 if (!CI->use_empty())
Craig Topperf40110f2014-04-25 05:29:35 +00001785 return nullptr;
Chris Bienemanad070d02014-09-17 20:55:46 +00001786
1787 // printf("x") -> putchar('x'), even for '%'.
1788 if (FormatStr.size() == 1) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001789 Value *Res = EmitPutChar(B.getInt32(FormatStr[0]), B, TLI);
Chris Bienemanad070d02014-09-17 20:55:46 +00001790 if (CI->use_empty() || !Res)
1791 return Res;
1792 return B.CreateIntCast(Res, CI->getType(), true);
Meador Inge08ca1152012-11-26 20:37:20 +00001793 }
1794
Chris Bienemanad070d02014-09-17 20:55:46 +00001795 // printf("foo\n") --> puts("foo")
1796 if (FormatStr[FormatStr.size() - 1] == '\n' &&
1797 FormatStr.find('%') == StringRef::npos) { // No format characters.
1798 // Create a string literal with no \n on it. We expect the constant merge
1799 // pass to be run after this pass, to merge duplicate strings.
1800 FormatStr = FormatStr.drop_back();
1801 Value *GV = B.CreateGlobalString(FormatStr, "str");
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001802 Value *NewCI = EmitPutS(GV, B, TLI);
Chris Bienemanad070d02014-09-17 20:55:46 +00001803 return (CI->use_empty() || !NewCI)
1804 ? NewCI
1805 : ConstantInt::get(CI->getType(), FormatStr.size() + 1);
1806 }
Meador Inge08ca1152012-11-26 20:37:20 +00001807
Chris Bienemanad070d02014-09-17 20:55:46 +00001808 // Optimize specific format strings.
1809 // printf("%c", chr) --> putchar(chr)
1810 if (FormatStr == "%c" && CI->getNumArgOperands() > 1 &&
1811 CI->getArgOperand(1)->getType()->isIntegerTy()) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001812 Value *Res = EmitPutChar(CI->getArgOperand(1), B, TLI);
Meador Inge08ca1152012-11-26 20:37:20 +00001813
Chris Bienemanad070d02014-09-17 20:55:46 +00001814 if (CI->use_empty() || !Res)
1815 return Res;
1816 return B.CreateIntCast(Res, CI->getType(), true);
1817 }
1818
1819 // printf("%s\n", str) --> puts(str)
1820 if (FormatStr == "%s\n" && CI->getNumArgOperands() > 1 &&
1821 CI->getArgOperand(1)->getType()->isPointerTy()) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001822 return EmitPutS(CI->getArgOperand(1), B, TLI);
Chris Bienemanad070d02014-09-17 20:55:46 +00001823 }
1824 return nullptr;
1825}
1826
1827Value *LibCallSimplifier::optimizePrintF(CallInst *CI, IRBuilder<> &B) {
1828
1829 Function *Callee = CI->getCalledFunction();
1830 // Require one fixed pointer argument and an integer/void result.
1831 FunctionType *FT = Callee->getFunctionType();
1832 if (FT->getNumParams() < 1 || !FT->getParamType(0)->isPointerTy() ||
1833 !(FT->getReturnType()->isIntegerTy() || FT->getReturnType()->isVoidTy()))
1834 return nullptr;
1835
1836 if (Value *V = optimizePrintFString(CI, B)) {
1837 return V;
1838 }
1839
1840 // printf(format, ...) -> iprintf(format, ...) if no floating point
1841 // arguments.
1842 if (TLI->has(LibFunc::iprintf) && !callHasFloatingPointArgument(CI)) {
1843 Module *M = B.GetInsertBlock()->getParent()->getParent();
1844 Constant *IPrintFFn =
Meador Inge08ca1152012-11-26 20:37:20 +00001845 M->getOrInsertFunction("iprintf", FT, Callee->getAttributes());
Chris Bienemanad070d02014-09-17 20:55:46 +00001846 CallInst *New = cast<CallInst>(CI->clone());
1847 New->setCalledFunction(IPrintFFn);
1848 B.Insert(New);
1849 return New;
Meador Inge08ca1152012-11-26 20:37:20 +00001850 }
Chris Bienemanad070d02014-09-17 20:55:46 +00001851 return nullptr;
1852}
Meador Inge08ca1152012-11-26 20:37:20 +00001853
Chris Bienemanad070d02014-09-17 20:55:46 +00001854Value *LibCallSimplifier::optimizeSPrintFString(CallInst *CI, IRBuilder<> &B) {
1855 // Check for a fixed format string.
1856 StringRef FormatStr;
1857 if (!getConstantStringInfo(CI->getArgOperand(1), FormatStr))
Craig Topperf40110f2014-04-25 05:29:35 +00001858 return nullptr;
Meador Inge25c9b3b2012-11-27 05:57:54 +00001859
Chris Bienemanad070d02014-09-17 20:55:46 +00001860 // If we just have a format string (nothing else crazy) transform it.
1861 if (CI->getNumArgOperands() == 2) {
1862 // Make sure there's no % in the constant array. We could try to handle
1863 // %% -> % in the future if we cared.
1864 for (unsigned i = 0, e = FormatStr.size(); i != e; ++i)
1865 if (FormatStr[i] == '%')
1866 return nullptr; // we found a format specifier, bail out.
Hal Finkel66cd3f12013-11-17 02:06:35 +00001867
Chris Bienemanad070d02014-09-17 20:55:46 +00001868 // sprintf(str, fmt) -> llvm.memcpy(str, fmt, strlen(fmt)+1, 1)
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001869 B.CreateMemCpy(CI->getArgOperand(0), CI->getArgOperand(1),
1870 ConstantInt::get(DL.getIntPtrType(CI->getContext()),
1871 FormatStr.size() + 1),
Pete Cooper67cf9a72015-11-19 05:56:52 +00001872 1); // Copy the null byte.
Chris Bienemanad070d02014-09-17 20:55:46 +00001873 return ConstantInt::get(CI->getType(), FormatStr.size());
Meador Ingef8e72502012-11-29 15:45:43 +00001874 }
Meador Ingef8e72502012-11-29 15:45:43 +00001875
Chris Bienemanad070d02014-09-17 20:55:46 +00001876 // The remaining optimizations require the format string to be "%s" or "%c"
1877 // and have an extra operand.
1878 if (FormatStr.size() != 2 || FormatStr[0] != '%' ||
1879 CI->getNumArgOperands() < 3)
Craig Topperf40110f2014-04-25 05:29:35 +00001880 return nullptr;
Meador Inge75798bb2012-11-29 19:15:17 +00001881
Chris Bienemanad070d02014-09-17 20:55:46 +00001882 // Decode the second character of the format string.
1883 if (FormatStr[1] == 'c') {
1884 // sprintf(dst, "%c", chr) --> *(i8*)dst = chr; *((i8*)dst+1) = 0
1885 if (!CI->getArgOperand(2)->getType()->isIntegerTy())
1886 return nullptr;
1887 Value *V = B.CreateTrunc(CI->getArgOperand(2), B.getInt8Ty(), "char");
1888 Value *Ptr = CastToCStr(CI->getArgOperand(0), B);
1889 B.CreateStore(V, Ptr);
David Blaikie3909da72015-03-30 20:42:56 +00001890 Ptr = B.CreateGEP(B.getInt8Ty(), Ptr, B.getInt32(1), "nul");
Chris Bienemanad070d02014-09-17 20:55:46 +00001891 B.CreateStore(B.getInt8(0), Ptr);
Meador Ingedf796f82012-10-13 16:45:24 +00001892
Chris Bienemanad070d02014-09-17 20:55:46 +00001893 return ConstantInt::get(CI->getType(), 1);
Meador Ingedf796f82012-10-13 16:45:24 +00001894 }
1895
Chris Bienemanad070d02014-09-17 20:55:46 +00001896 if (FormatStr[1] == 's') {
Chris Bienemanad070d02014-09-17 20:55:46 +00001897 // sprintf(dest, "%s", str) -> llvm.memcpy(dest, str, strlen(str)+1, 1)
1898 if (!CI->getArgOperand(2)->getType()->isPointerTy())
1899 return nullptr;
1900
1901 Value *Len = EmitStrLen(CI->getArgOperand(2), B, DL, TLI);
1902 if (!Len)
1903 return nullptr;
1904 Value *IncLen =
1905 B.CreateAdd(Len, ConstantInt::get(Len->getType(), 1), "leninc");
Pete Cooper67cf9a72015-11-19 05:56:52 +00001906 B.CreateMemCpy(CI->getArgOperand(0), CI->getArgOperand(2), IncLen, 1);
Chris Bienemanad070d02014-09-17 20:55:46 +00001907
1908 // The sprintf result is the unincremented number of bytes in the string.
1909 return B.CreateIntCast(Len, CI->getType(), false);
1910 }
1911 return nullptr;
1912}
1913
1914Value *LibCallSimplifier::optimizeSPrintF(CallInst *CI, IRBuilder<> &B) {
1915 Function *Callee = CI->getCalledFunction();
1916 // Require two fixed pointer arguments and an integer result.
1917 FunctionType *FT = Callee->getFunctionType();
1918 if (FT->getNumParams() != 2 || !FT->getParamType(0)->isPointerTy() ||
1919 !FT->getParamType(1)->isPointerTy() ||
1920 !FT->getReturnType()->isIntegerTy())
1921 return nullptr;
1922
1923 if (Value *V = optimizeSPrintFString(CI, B)) {
1924 return V;
1925 }
1926
1927 // sprintf(str, format, ...) -> siprintf(str, format, ...) if no floating
1928 // point arguments.
1929 if (TLI->has(LibFunc::siprintf) && !callHasFloatingPointArgument(CI)) {
1930 Module *M = B.GetInsertBlock()->getParent()->getParent();
1931 Constant *SIPrintFFn =
1932 M->getOrInsertFunction("siprintf", FT, Callee->getAttributes());
1933 CallInst *New = cast<CallInst>(CI->clone());
1934 New->setCalledFunction(SIPrintFFn);
1935 B.Insert(New);
1936 return New;
1937 }
1938 return nullptr;
1939}
1940
1941Value *LibCallSimplifier::optimizeFPrintFString(CallInst *CI, IRBuilder<> &B) {
1942 optimizeErrorReporting(CI, B, 0);
1943
1944 // All the optimizations depend on the format string.
1945 StringRef FormatStr;
1946 if (!getConstantStringInfo(CI->getArgOperand(1), FormatStr))
1947 return nullptr;
1948
1949 // Do not do any of the following transformations if the fprintf return
1950 // value is used, in general the fprintf return value is not compatible
1951 // with fwrite(), fputc() or fputs().
1952 if (!CI->use_empty())
1953 return nullptr;
1954
1955 // fprintf(F, "foo") --> fwrite("foo", 3, 1, F)
1956 if (CI->getNumArgOperands() == 2) {
1957 for (unsigned i = 0, e = FormatStr.size(); i != e; ++i)
1958 if (FormatStr[i] == '%') // Could handle %% -> % if we cared.
1959 return nullptr; // We found a format specifier.
1960
Chris Bienemanad070d02014-09-17 20:55:46 +00001961 return EmitFWrite(
1962 CI->getArgOperand(1),
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001963 ConstantInt::get(DL.getIntPtrType(CI->getContext()), FormatStr.size()),
Chris Bienemanad070d02014-09-17 20:55:46 +00001964 CI->getArgOperand(0), B, DL, TLI);
1965 }
1966
1967 // The remaining optimizations require the format string to be "%s" or "%c"
1968 // and have an extra operand.
1969 if (FormatStr.size() != 2 || FormatStr[0] != '%' ||
1970 CI->getNumArgOperands() < 3)
1971 return nullptr;
1972
1973 // Decode the second character of the format string.
1974 if (FormatStr[1] == 'c') {
1975 // fprintf(F, "%c", chr) --> fputc(chr, F)
1976 if (!CI->getArgOperand(2)->getType()->isIntegerTy())
1977 return nullptr;
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001978 return EmitFPutC(CI->getArgOperand(2), CI->getArgOperand(0), B, TLI);
Chris Bienemanad070d02014-09-17 20:55:46 +00001979 }
1980
1981 if (FormatStr[1] == 's') {
1982 // fprintf(F, "%s", str) --> fputs(str, F)
1983 if (!CI->getArgOperand(2)->getType()->isPointerTy())
1984 return nullptr;
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001985 return EmitFPutS(CI->getArgOperand(2), CI->getArgOperand(0), B, TLI);
Chris Bienemanad070d02014-09-17 20:55:46 +00001986 }
1987 return nullptr;
1988}
1989
1990Value *LibCallSimplifier::optimizeFPrintF(CallInst *CI, IRBuilder<> &B) {
1991 Function *Callee = CI->getCalledFunction();
1992 // Require two fixed paramters as pointers and integer result.
1993 FunctionType *FT = Callee->getFunctionType();
1994 if (FT->getNumParams() != 2 || !FT->getParamType(0)->isPointerTy() ||
1995 !FT->getParamType(1)->isPointerTy() ||
1996 !FT->getReturnType()->isIntegerTy())
1997 return nullptr;
1998
1999 if (Value *V = optimizeFPrintFString(CI, B)) {
2000 return V;
2001 }
2002
2003 // fprintf(stream, format, ...) -> fiprintf(stream, format, ...) if no
2004 // floating point arguments.
2005 if (TLI->has(LibFunc::fiprintf) && !callHasFloatingPointArgument(CI)) {
2006 Module *M = B.GetInsertBlock()->getParent()->getParent();
2007 Constant *FIPrintFFn =
2008 M->getOrInsertFunction("fiprintf", FT, Callee->getAttributes());
2009 CallInst *New = cast<CallInst>(CI->clone());
2010 New->setCalledFunction(FIPrintFFn);
2011 B.Insert(New);
2012 return New;
2013 }
2014 return nullptr;
2015}
2016
2017Value *LibCallSimplifier::optimizeFWrite(CallInst *CI, IRBuilder<> &B) {
2018 optimizeErrorReporting(CI, B, 3);
2019
2020 Function *Callee = CI->getCalledFunction();
2021 // Require a pointer, an integer, an integer, a pointer, returning integer.
2022 FunctionType *FT = Callee->getFunctionType();
2023 if (FT->getNumParams() != 4 || !FT->getParamType(0)->isPointerTy() ||
2024 !FT->getParamType(1)->isIntegerTy() ||
2025 !FT->getParamType(2)->isIntegerTy() ||
2026 !FT->getParamType(3)->isPointerTy() ||
2027 !FT->getReturnType()->isIntegerTy())
2028 return nullptr;
2029
2030 // Get the element size and count.
2031 ConstantInt *SizeC = dyn_cast<ConstantInt>(CI->getArgOperand(1));
2032 ConstantInt *CountC = dyn_cast<ConstantInt>(CI->getArgOperand(2));
2033 if (!SizeC || !CountC)
2034 return nullptr;
2035 uint64_t Bytes = SizeC->getZExtValue() * CountC->getZExtValue();
2036
2037 // If this is writing zero records, remove the call (it's a noop).
2038 if (Bytes == 0)
2039 return ConstantInt::get(CI->getType(), 0);
2040
2041 // If this is writing one byte, turn it into fputc.
2042 // This optimisation is only valid, if the return value is unused.
2043 if (Bytes == 1 && CI->use_empty()) { // fwrite(S,1,1,F) -> fputc(S[0],F)
2044 Value *Char = B.CreateLoad(CastToCStr(CI->getArgOperand(0), B), "char");
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002045 Value *NewCI = EmitFPutC(Char, CI->getArgOperand(3), B, TLI);
Chris Bienemanad070d02014-09-17 20:55:46 +00002046 return NewCI ? ConstantInt::get(CI->getType(), 1) : nullptr;
2047 }
2048
2049 return nullptr;
2050}
2051
2052Value *LibCallSimplifier::optimizeFPuts(CallInst *CI, IRBuilder<> &B) {
2053 optimizeErrorReporting(CI, B, 1);
2054
2055 Function *Callee = CI->getCalledFunction();
2056
Chris Bienemanad070d02014-09-17 20:55:46 +00002057 // Require two pointers. Also, we can't optimize if return value is used.
2058 FunctionType *FT = Callee->getFunctionType();
2059 if (FT->getNumParams() != 2 || !FT->getParamType(0)->isPointerTy() ||
2060 !FT->getParamType(1)->isPointerTy() || !CI->use_empty())
2061 return nullptr;
2062
2063 // fputs(s,F) --> fwrite(s,1,strlen(s),F)
2064 uint64_t Len = GetStringLength(CI->getArgOperand(0));
2065 if (!Len)
2066 return nullptr;
2067
2068 // Known to have no uses (see above).
2069 return EmitFWrite(
2070 CI->getArgOperand(0),
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002071 ConstantInt::get(DL.getIntPtrType(CI->getContext()), Len - 1),
Chris Bienemanad070d02014-09-17 20:55:46 +00002072 CI->getArgOperand(1), B, DL, TLI);
2073}
2074
2075Value *LibCallSimplifier::optimizePuts(CallInst *CI, IRBuilder<> &B) {
2076 Function *Callee = CI->getCalledFunction();
2077 // Require one fixed pointer argument and an integer/void result.
2078 FunctionType *FT = Callee->getFunctionType();
2079 if (FT->getNumParams() < 1 || !FT->getParamType(0)->isPointerTy() ||
2080 !(FT->getReturnType()->isIntegerTy() || FT->getReturnType()->isVoidTy()))
2081 return nullptr;
2082
2083 // Check for a constant string.
2084 StringRef Str;
2085 if (!getConstantStringInfo(CI->getArgOperand(0), Str))
2086 return nullptr;
2087
2088 if (Str.empty() && CI->use_empty()) {
2089 // puts("") -> putchar('\n')
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002090 Value *Res = EmitPutChar(B.getInt32('\n'), B, TLI);
Chris Bienemanad070d02014-09-17 20:55:46 +00002091 if (CI->use_empty() || !Res)
2092 return Res;
2093 return B.CreateIntCast(Res, CI->getType(), true);
2094 }
2095
2096 return nullptr;
2097}
2098
2099bool LibCallSimplifier::hasFloatVersion(StringRef FuncName) {
Meador Inge20255ef2013-03-12 00:08:29 +00002100 LibFunc::Func Func;
2101 SmallString<20> FloatFuncName = FuncName;
2102 FloatFuncName += 'f';
2103 if (TLI->getLibFunc(FloatFuncName, Func))
2104 return TLI->has(Func);
2105 return false;
2106}
Meador Inge7fb2f732012-10-13 16:45:32 +00002107
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00002108Value *LibCallSimplifier::optimizeStringMemoryLibCall(CallInst *CI,
2109 IRBuilder<> &Builder) {
2110 LibFunc::Func Func;
2111 Function *Callee = CI->getCalledFunction();
2112 StringRef FuncName = Callee->getName();
2113
2114 // Check for string/memory library functions.
2115 if (TLI->getLibFunc(FuncName, Func) && TLI->has(Func)) {
2116 // Make sure we never change the calling convention.
2117 assert((ignoreCallingConv(Func) ||
2118 CI->getCallingConv() == llvm::CallingConv::C) &&
2119 "Optimizing string/memory libcall would change the calling convention");
2120 switch (Func) {
2121 case LibFunc::strcat:
2122 return optimizeStrCat(CI, Builder);
2123 case LibFunc::strncat:
2124 return optimizeStrNCat(CI, Builder);
2125 case LibFunc::strchr:
2126 return optimizeStrChr(CI, Builder);
2127 case LibFunc::strrchr:
2128 return optimizeStrRChr(CI, Builder);
2129 case LibFunc::strcmp:
2130 return optimizeStrCmp(CI, Builder);
2131 case LibFunc::strncmp:
2132 return optimizeStrNCmp(CI, Builder);
2133 case LibFunc::strcpy:
2134 return optimizeStrCpy(CI, Builder);
2135 case LibFunc::stpcpy:
2136 return optimizeStpCpy(CI, Builder);
2137 case LibFunc::strncpy:
2138 return optimizeStrNCpy(CI, Builder);
2139 case LibFunc::strlen:
2140 return optimizeStrLen(CI, Builder);
2141 case LibFunc::strpbrk:
2142 return optimizeStrPBrk(CI, Builder);
2143 case LibFunc::strtol:
2144 case LibFunc::strtod:
2145 case LibFunc::strtof:
2146 case LibFunc::strtoul:
2147 case LibFunc::strtoll:
2148 case LibFunc::strtold:
2149 case LibFunc::strtoull:
2150 return optimizeStrTo(CI, Builder);
2151 case LibFunc::strspn:
2152 return optimizeStrSpn(CI, Builder);
2153 case LibFunc::strcspn:
2154 return optimizeStrCSpn(CI, Builder);
2155 case LibFunc::strstr:
2156 return optimizeStrStr(CI, Builder);
Benjamin Kramer691363e2015-03-21 15:36:21 +00002157 case LibFunc::memchr:
2158 return optimizeMemChr(CI, Builder);
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00002159 case LibFunc::memcmp:
2160 return optimizeMemCmp(CI, Builder);
2161 case LibFunc::memcpy:
2162 return optimizeMemCpy(CI, Builder);
2163 case LibFunc::memmove:
2164 return optimizeMemMove(CI, Builder);
2165 case LibFunc::memset:
2166 return optimizeMemSet(CI, Builder);
2167 default:
2168 break;
2169 }
2170 }
2171 return nullptr;
2172}
2173
Chris Bienemanad070d02014-09-17 20:55:46 +00002174Value *LibCallSimplifier::optimizeCall(CallInst *CI) {
2175 if (CI->isNoBuiltin())
2176 return nullptr;
Meador Inge4d2827c2012-11-11 05:11:20 +00002177
Meador Inge20255ef2013-03-12 00:08:29 +00002178 LibFunc::Func Func;
2179 Function *Callee = CI->getCalledFunction();
2180 StringRef FuncName = Callee->getName();
David Majnemerb70e23c2016-01-06 05:01:34 +00002181
2182 SmallVector<OperandBundleDef, 2> OpBundles;
2183 CI->getOperandBundlesAsDefs(OpBundles);
2184 IRBuilder<> Builder(CI, /*FPMathTag=*/nullptr, OpBundles);
Chris Bienemanad070d02014-09-17 20:55:46 +00002185 bool isCallingConvC = CI->getCallingConv() == llvm::CallingConv::C;
Meador Inge20255ef2013-03-12 00:08:29 +00002186
Sanjay Patela92fa442014-10-22 15:29:23 +00002187 // Command-line parameter overrides function attribute.
2188 if (EnableUnsafeFPShrink.getNumOccurrences() > 0)
2189 UnsafeFPShrink = EnableUnsafeFPShrink;
Davide Italianoa904e522015-10-29 02:58:44 +00002190 else if (canUseUnsafeFPMath(Callee))
2191 UnsafeFPShrink = true;
Sanjay Patela92fa442014-10-22 15:29:23 +00002192
Sanjay Patel848309d2014-10-23 21:52:45 +00002193 // First, check for intrinsics.
Meador Inge20255ef2013-03-12 00:08:29 +00002194 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(CI)) {
Chris Bienemanad070d02014-09-17 20:55:46 +00002195 if (!isCallingConvC)
2196 return nullptr;
Meador Inge20255ef2013-03-12 00:08:29 +00002197 switch (II->getIntrinsicID()) {
2198 case Intrinsic::pow:
Chris Bienemanad070d02014-09-17 20:55:46 +00002199 return optimizePow(CI, Builder);
Meador Inge20255ef2013-03-12 00:08:29 +00002200 case Intrinsic::exp2:
Chris Bienemanad070d02014-09-17 20:55:46 +00002201 return optimizeExp2(CI, Builder);
Sanjay Patel0ca42bb2014-10-14 20:43:11 +00002202 case Intrinsic::fabs:
2203 return optimizeFabs(CI, Builder);
Davide Italianob8b71332015-11-29 20:58:04 +00002204 case Intrinsic::log:
2205 return optimizeLog(CI, Builder);
Sanjay Patelc699a612014-10-16 18:48:17 +00002206 case Intrinsic::sqrt:
2207 return optimizeSqrt(CI, Builder);
Meador Inge20255ef2013-03-12 00:08:29 +00002208 default:
Chris Bienemanad070d02014-09-17 20:55:46 +00002209 return nullptr;
Meador Inge20255ef2013-03-12 00:08:29 +00002210 }
2211 }
2212
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002213 // Also try to simplify calls to fortified library functions.
2214 if (Value *SimplifiedFortifiedCI = FortifiedSimplifier.optimizeCall(CI)) {
2215 // Try to further simplify the result.
Ahmed Bougacha71d7b182015-01-14 00:55:05 +00002216 CallInst *SimplifiedCI = dyn_cast<CallInst>(SimplifiedFortifiedCI);
Bruno Cardoso Lopesb491a2d2015-10-01 22:43:53 +00002217 if (SimplifiedCI && SimplifiedCI->getCalledFunction()) {
2218 // Use an IR Builder from SimplifiedCI if available instead of CI
2219 // to guarantee we reach all uses we might replace later on.
2220 IRBuilder<> TmpBuilder(SimplifiedCI);
2221 if (Value *V = optimizeStringMemoryLibCall(SimplifiedCI, TmpBuilder)) {
Ahmed Bougacha1ac93562015-01-27 21:52:16 +00002222 // If we were able to further simplify, remove the now redundant call.
2223 SimplifiedCI->replaceAllUsesWith(V);
2224 SimplifiedCI->eraseFromParent();
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002225 return V;
Ahmed Bougacha1ac93562015-01-27 21:52:16 +00002226 }
Bruno Cardoso Lopesb491a2d2015-10-01 22:43:53 +00002227 }
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002228 return SimplifiedFortifiedCI;
2229 }
2230
Meador Inge20255ef2013-03-12 00:08:29 +00002231 // Then check for known library functions.
2232 if (TLI->getLibFunc(FuncName, Func) && TLI->has(Func)) {
Chris Bienemanad070d02014-09-17 20:55:46 +00002233 // We never change the calling convention.
2234 if (!ignoreCallingConv(Func) && !isCallingConvC)
2235 return nullptr;
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00002236 if (Value *V = optimizeStringMemoryLibCall(CI, Builder))
2237 return V;
Meador Inge20255ef2013-03-12 00:08:29 +00002238 switch (Func) {
Chris Bienemanad070d02014-09-17 20:55:46 +00002239 case LibFunc::cosf:
2240 case LibFunc::cos:
2241 case LibFunc::cosl:
2242 return optimizeCos(CI, Builder);
2243 case LibFunc::sinpif:
2244 case LibFunc::sinpi:
2245 case LibFunc::cospif:
2246 case LibFunc::cospi:
2247 return optimizeSinCosPi(CI, Builder);
2248 case LibFunc::powf:
2249 case LibFunc::pow:
2250 case LibFunc::powl:
2251 return optimizePow(CI, Builder);
2252 case LibFunc::exp2l:
2253 case LibFunc::exp2:
2254 case LibFunc::exp2f:
2255 return optimizeExp2(CI, Builder);
Sanjay Patel0ca42bb2014-10-14 20:43:11 +00002256 case LibFunc::fabsf:
2257 case LibFunc::fabs:
2258 case LibFunc::fabsl:
2259 return optimizeFabs(CI, Builder);
Sanjay Patelc699a612014-10-16 18:48:17 +00002260 case LibFunc::sqrtf:
2261 case LibFunc::sqrt:
2262 case LibFunc::sqrtl:
2263 return optimizeSqrt(CI, Builder);
Chris Bienemanad070d02014-09-17 20:55:46 +00002264 case LibFunc::ffs:
2265 case LibFunc::ffsl:
2266 case LibFunc::ffsll:
2267 return optimizeFFS(CI, Builder);
2268 case LibFunc::abs:
2269 case LibFunc::labs:
2270 case LibFunc::llabs:
2271 return optimizeAbs(CI, Builder);
2272 case LibFunc::isdigit:
2273 return optimizeIsDigit(CI, Builder);
2274 case LibFunc::isascii:
2275 return optimizeIsAscii(CI, Builder);
2276 case LibFunc::toascii:
2277 return optimizeToAscii(CI, Builder);
2278 case LibFunc::printf:
2279 return optimizePrintF(CI, Builder);
2280 case LibFunc::sprintf:
2281 return optimizeSPrintF(CI, Builder);
2282 case LibFunc::fprintf:
2283 return optimizeFPrintF(CI, Builder);
2284 case LibFunc::fwrite:
2285 return optimizeFWrite(CI, Builder);
2286 case LibFunc::fputs:
2287 return optimizeFPuts(CI, Builder);
Davide Italianob8b71332015-11-29 20:58:04 +00002288 case LibFunc::log:
2289 case LibFunc::log10:
2290 case LibFunc::log1p:
2291 case LibFunc::log2:
2292 case LibFunc::logb:
2293 return optimizeLog(CI, Builder);
Chris Bienemanad070d02014-09-17 20:55:46 +00002294 case LibFunc::puts:
2295 return optimizePuts(CI, Builder);
Davide Italiano51507d22015-11-04 23:36:56 +00002296 case LibFunc::tan:
2297 case LibFunc::tanf:
2298 case LibFunc::tanl:
2299 return optimizeTan(CI, Builder);
Chris Bienemanad070d02014-09-17 20:55:46 +00002300 case LibFunc::perror:
2301 return optimizeErrorReporting(CI, Builder);
2302 case LibFunc::vfprintf:
2303 case LibFunc::fiprintf:
2304 return optimizeErrorReporting(CI, Builder, 0);
2305 case LibFunc::fputc:
2306 return optimizeErrorReporting(CI, Builder, 1);
2307 case LibFunc::ceil:
Chris Bienemanad070d02014-09-17 20:55:46 +00002308 case LibFunc::floor:
2309 case LibFunc::rint:
2310 case LibFunc::round:
2311 case LibFunc::nearbyint:
2312 case LibFunc::trunc:
2313 if (hasFloatVersion(FuncName))
2314 return optimizeUnaryDoubleFP(CI, Builder, false);
2315 return nullptr;
2316 case LibFunc::acos:
2317 case LibFunc::acosh:
2318 case LibFunc::asin:
2319 case LibFunc::asinh:
2320 case LibFunc::atan:
2321 case LibFunc::atanh:
2322 case LibFunc::cbrt:
2323 case LibFunc::cosh:
2324 case LibFunc::exp:
2325 case LibFunc::exp10:
2326 case LibFunc::expm1:
Chris Bienemanad070d02014-09-17 20:55:46 +00002327 case LibFunc::sin:
2328 case LibFunc::sinh:
Chris Bienemanad070d02014-09-17 20:55:46 +00002329 case LibFunc::tanh:
2330 if (UnsafeFPShrink && hasFloatVersion(FuncName))
2331 return optimizeUnaryDoubleFP(CI, Builder, true);
2332 return nullptr;
Matthias Braun892c9232014-12-03 21:46:29 +00002333 case LibFunc::copysign:
Chris Bienemanad070d02014-09-17 20:55:46 +00002334 if (hasFloatVersion(FuncName))
2335 return optimizeBinaryDoubleFP(CI, Builder);
2336 return nullptr;
Sanjay Patel57fd1dc2015-08-16 20:18:19 +00002337 case LibFunc::fminf:
2338 case LibFunc::fmin:
2339 case LibFunc::fminl:
2340 case LibFunc::fmaxf:
2341 case LibFunc::fmax:
2342 case LibFunc::fmaxl:
2343 return optimizeFMinFMax(CI, Builder);
Chris Bienemanad070d02014-09-17 20:55:46 +00002344 default:
2345 return nullptr;
2346 }
Meador Inge20255ef2013-03-12 00:08:29 +00002347 }
Craig Topperf40110f2014-04-25 05:29:35 +00002348 return nullptr;
Meador Ingedf796f82012-10-13 16:45:24 +00002349}
2350
Chandler Carruth92803822015-01-21 02:11:59 +00002351LibCallSimplifier::LibCallSimplifier(
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002352 const DataLayout &DL, const TargetLibraryInfo *TLI,
Chandler Carruth92803822015-01-21 02:11:59 +00002353 function_ref<void(Instruction *, Value *)> Replacer)
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002354 : FortifiedSimplifier(TLI), DL(DL), TLI(TLI), UnsafeFPShrink(false),
Chandler Carruth92803822015-01-21 02:11:59 +00002355 Replacer(Replacer) {}
2356
2357void LibCallSimplifier::replaceAllUsesWith(Instruction *I, Value *With) {
2358 // Indirect through the replacer used in this instance.
2359 Replacer(I, With);
Meador Ingedf796f82012-10-13 16:45:24 +00002360}
2361
Meador Ingedfb08a22013-06-20 19:48:07 +00002362// TODO:
2363// Additional cases that we need to add to this file:
2364//
2365// cbrt:
2366// * cbrt(expN(X)) -> expN(x/3)
2367// * cbrt(sqrt(x)) -> pow(x,1/6)
David Majnemer3354fe42015-08-26 18:30:16 +00002368// * cbrt(cbrt(x)) -> pow(x,1/9)
Meador Ingedfb08a22013-06-20 19:48:07 +00002369//
2370// exp, expf, expl:
2371// * exp(log(x)) -> x
2372//
2373// log, logf, logl:
2374// * log(exp(x)) -> x
Meador Ingedfb08a22013-06-20 19:48:07 +00002375// * log(exp(y)) -> y*log(e)
Meador Ingedfb08a22013-06-20 19:48:07 +00002376// * log(exp10(y)) -> y*log(10)
2377// * log(sqrt(x)) -> 0.5*log(x)
Meador Ingedfb08a22013-06-20 19:48:07 +00002378//
2379// lround, lroundf, lroundl:
2380// * lround(cnst) -> cnst'
2381//
2382// pow, powf, powl:
Meador Ingedfb08a22013-06-20 19:48:07 +00002383// * pow(sqrt(x),y) -> pow(x,y*0.5)
2384// * pow(pow(x,y),z)-> pow(x,y*z)
2385//
2386// round, roundf, roundl:
2387// * round(cnst) -> cnst'
2388//
2389// signbit:
2390// * signbit(cnst) -> cnst'
2391// * signbit(nncst) -> 0 (if pstv is a non-negative constant)
2392//
2393// sqrt, sqrtf, sqrtl:
2394// * sqrt(expN(x)) -> expN(x*0.5)
2395// * sqrt(Nroot(x)) -> pow(x,1/(2*N))
2396// * sqrt(pow(x,y)) -> pow(|x|,y*0.5)
2397//
Meador Ingedfb08a22013-06-20 19:48:07 +00002398// trunc, truncf, truncl:
2399// * trunc(cnst) -> cnst'
2400//
2401//
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002402
2403//===----------------------------------------------------------------------===//
2404// Fortified Library Call Optimizations
2405//===----------------------------------------------------------------------===//
2406
2407bool FortifiedLibCallSimplifier::isFortifiedCallFoldable(CallInst *CI,
2408 unsigned ObjSizeOp,
2409 unsigned SizeOp,
2410 bool isString) {
2411 if (CI->getArgOperand(ObjSizeOp) == CI->getArgOperand(SizeOp))
2412 return true;
2413 if (ConstantInt *ObjSizeCI =
2414 dyn_cast<ConstantInt>(CI->getArgOperand(ObjSizeOp))) {
2415 if (ObjSizeCI->isAllOnesValue())
2416 return true;
2417 // If the object size wasn't -1 (unknown), bail out if we were asked to.
2418 if (OnlyLowerUnknownSize)
2419 return false;
2420 if (isString) {
2421 uint64_t Len = GetStringLength(CI->getArgOperand(SizeOp));
2422 // If the length is 0 we don't know how long it is and so we can't
2423 // remove the check.
2424 if (Len == 0)
2425 return false;
2426 return ObjSizeCI->getZExtValue() >= Len;
2427 }
2428 if (ConstantInt *SizeCI = dyn_cast<ConstantInt>(CI->getArgOperand(SizeOp)))
2429 return ObjSizeCI->getZExtValue() >= SizeCI->getZExtValue();
2430 }
2431 return false;
2432}
2433
Sanjay Pateld707db92015-12-31 16:10:49 +00002434Value *FortifiedLibCallSimplifier::optimizeMemCpyChk(CallInst *CI,
2435 IRBuilder<> &B) {
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002436 Function *Callee = CI->getCalledFunction();
2437
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002438 if (!checkStringCopyLibFuncSignature(Callee, LibFunc::memcpy_chk))
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002439 return nullptr;
2440
2441 if (isFortifiedCallFoldable(CI, 3, 2, false)) {
2442 B.CreateMemCpy(CI->getArgOperand(0), CI->getArgOperand(1),
Pete Cooper67cf9a72015-11-19 05:56:52 +00002443 CI->getArgOperand(2), 1);
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002444 return CI->getArgOperand(0);
2445 }
2446 return nullptr;
2447}
2448
Sanjay Pateld707db92015-12-31 16:10:49 +00002449Value *FortifiedLibCallSimplifier::optimizeMemMoveChk(CallInst *CI,
2450 IRBuilder<> &B) {
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002451 Function *Callee = CI->getCalledFunction();
2452
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002453 if (!checkStringCopyLibFuncSignature(Callee, LibFunc::memmove_chk))
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002454 return nullptr;
2455
2456 if (isFortifiedCallFoldable(CI, 3, 2, false)) {
2457 B.CreateMemMove(CI->getArgOperand(0), CI->getArgOperand(1),
Pete Cooper67cf9a72015-11-19 05:56:52 +00002458 CI->getArgOperand(2), 1);
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002459 return CI->getArgOperand(0);
2460 }
2461 return nullptr;
2462}
2463
Sanjay Pateld707db92015-12-31 16:10:49 +00002464Value *FortifiedLibCallSimplifier::optimizeMemSetChk(CallInst *CI,
2465 IRBuilder<> &B) {
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002466 Function *Callee = CI->getCalledFunction();
2467
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002468 if (!checkStringCopyLibFuncSignature(Callee, LibFunc::memset_chk))
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002469 return nullptr;
2470
2471 if (isFortifiedCallFoldable(CI, 3, 2, false)) {
2472 Value *Val = B.CreateIntCast(CI->getArgOperand(1), B.getInt8Ty(), false);
2473 B.CreateMemSet(CI->getArgOperand(0), Val, CI->getArgOperand(2), 1);
2474 return CI->getArgOperand(0);
2475 }
2476 return nullptr;
2477}
2478
Ahmed Bougacha1ac93562015-01-27 21:52:16 +00002479Value *FortifiedLibCallSimplifier::optimizeStrpCpyChk(CallInst *CI,
2480 IRBuilder<> &B,
2481 LibFunc::Func Func) {
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002482 Function *Callee = CI->getCalledFunction();
2483 StringRef Name = Callee->getName();
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002484 const DataLayout &DL = CI->getModule()->getDataLayout();
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002485
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002486 if (!checkStringCopyLibFuncSignature(Callee, Func))
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002487 return nullptr;
2488
2489 Value *Dst = CI->getArgOperand(0), *Src = CI->getArgOperand(1),
2490 *ObjSize = CI->getArgOperand(2);
2491
2492 // __stpcpy_chk(x,x,...) -> x+strlen(x)
Ahmed Bougacha1ac93562015-01-27 21:52:16 +00002493 if (Func == LibFunc::stpcpy_chk && !OnlyLowerUnknownSize && Dst == Src) {
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002494 Value *StrLen = EmitStrLen(Src, B, DL, TLI);
David Blaikieaa41cd52015-04-03 21:33:42 +00002495 return StrLen ? B.CreateInBoundsGEP(B.getInt8Ty(), Dst, StrLen) : nullptr;
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002496 }
2497
2498 // If a) we don't have any length information, or b) we know this will
2499 // fit then just lower to a plain st[rp]cpy. Otherwise we'll keep our
2500 // st[rp]cpy_chk call which may fail at runtime if the size is too long.
2501 // TODO: It might be nice to get a maximum length out of the possible
2502 // string lengths for varying.
David Blaikie65fab6d2015-04-03 21:32:06 +00002503 if (isFortifiedCallFoldable(CI, 2, 1, true))
2504 return EmitStrCpy(Dst, Src, B, TLI, Name.substr(2, 6));
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002505
David Blaikie65fab6d2015-04-03 21:32:06 +00002506 if (OnlyLowerUnknownSize)
2507 return nullptr;
2508
2509 // Maybe we can stil fold __st[rp]cpy_chk to __memcpy_chk.
2510 uint64_t Len = GetStringLength(Src);
2511 if (Len == 0)
2512 return nullptr;
2513
2514 Type *SizeTTy = DL.getIntPtrType(CI->getContext());
2515 Value *LenV = ConstantInt::get(SizeTTy, Len);
2516 Value *Ret = EmitMemCpyChk(Dst, Src, LenV, ObjSize, B, DL, TLI);
2517 // If the function was an __stpcpy_chk, and we were able to fold it into
2518 // a __memcpy_chk, we still need to return the correct end pointer.
2519 if (Ret && Func == LibFunc::stpcpy_chk)
2520 return B.CreateGEP(B.getInt8Ty(), Dst, ConstantInt::get(SizeTTy, Len - 1));
2521 return Ret;
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002522}
2523
Ahmed Bougacha1ac93562015-01-27 21:52:16 +00002524Value *FortifiedLibCallSimplifier::optimizeStrpNCpyChk(CallInst *CI,
2525 IRBuilder<> &B,
2526 LibFunc::Func Func) {
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002527 Function *Callee = CI->getCalledFunction();
2528 StringRef Name = Callee->getName();
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002529
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002530 if (!checkStringCopyLibFuncSignature(Callee, Func))
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002531 return nullptr;
2532 if (isFortifiedCallFoldable(CI, 3, 2, false)) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002533 Value *Ret = EmitStrNCpy(CI->getArgOperand(0), CI->getArgOperand(1),
2534 CI->getArgOperand(2), B, TLI, Name.substr(2, 7));
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002535 return Ret;
2536 }
2537 return nullptr;
2538}
2539
2540Value *FortifiedLibCallSimplifier::optimizeCall(CallInst *CI) {
Ahmed Bougacha408d0102015-04-01 00:45:09 +00002541 // FIXME: We shouldn't be changing "nobuiltin" or TLI unavailable calls here.
2542 // Some clang users checked for _chk libcall availability using:
2543 // __has_builtin(__builtin___memcpy_chk)
2544 // When compiling with -fno-builtin, this is always true.
2545 // When passing -ffreestanding/-mkernel, which both imply -fno-builtin, we
2546 // end up with fortified libcalls, which isn't acceptable in a freestanding
2547 // environment which only provides their non-fortified counterparts.
2548 //
2549 // Until we change clang and/or teach external users to check for availability
2550 // differently, disregard the "nobuiltin" attribute and TLI::has.
2551 //
2552 // PR23093.
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002553
2554 LibFunc::Func Func;
2555 Function *Callee = CI->getCalledFunction();
2556 StringRef FuncName = Callee->getName();
David Majnemerb70e23c2016-01-06 05:01:34 +00002557
2558 SmallVector<OperandBundleDef, 2> OpBundles;
2559 CI->getOperandBundlesAsDefs(OpBundles);
2560 IRBuilder<> Builder(CI, /*FPMathTag=*/nullptr, OpBundles);
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002561 bool isCallingConvC = CI->getCallingConv() == llvm::CallingConv::C;
2562
2563 // First, check that this is a known library functions.
Ahmed Bougacha408d0102015-04-01 00:45:09 +00002564 if (!TLI->getLibFunc(FuncName, Func))
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002565 return nullptr;
2566
2567 // We never change the calling convention.
2568 if (!ignoreCallingConv(Func) && !isCallingConvC)
2569 return nullptr;
2570
2571 switch (Func) {
2572 case LibFunc::memcpy_chk:
2573 return optimizeMemCpyChk(CI, Builder);
2574 case LibFunc::memmove_chk:
2575 return optimizeMemMoveChk(CI, Builder);
2576 case LibFunc::memset_chk:
2577 return optimizeMemSetChk(CI, Builder);
2578 case LibFunc::stpcpy_chk:
2579 case LibFunc::strcpy_chk:
Ahmed Bougacha1ac93562015-01-27 21:52:16 +00002580 return optimizeStrpCpyChk(CI, Builder, Func);
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002581 case LibFunc::stpncpy_chk:
2582 case LibFunc::strncpy_chk:
Ahmed Bougacha1ac93562015-01-27 21:52:16 +00002583 return optimizeStrpNCpyChk(CI, Builder, Func);
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002584 default:
2585 break;
2586 }
2587 return nullptr;
2588}
2589
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002590FortifiedLibCallSimplifier::FortifiedLibCallSimplifier(
2591 const TargetLibraryInfo *TLI, bool OnlyLowerUnknownSize)
2592 : TLI(TLI), OnlyLowerUnknownSize(OnlyLowerUnknownSize) {}