blob: cc6c47e8f978d8672821ede9fda7ffe6f291cc49 [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"
Hal Finkel66cd3f12013-11-17 02:06:35 +000032#include "llvm/Support/CommandLine.h"
Craig Topperb45eabc2017-04-26 16:39:58 +000033#include "llvm/Support/KnownBits.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>
Sanjay Patela92fa442014-10-22 15:29:23 +000041 EnableUnsafeFPShrink("enable-double-float-shrink", cl::Hidden,
42 cl::init(false),
43 cl::desc("Enable unsafe double to float "
44 "shrinking for math lib calls"));
45
46
Meador Ingedf796f82012-10-13 16:45:24 +000047//===----------------------------------------------------------------------===//
Meador Inged589ac62012-10-31 03:33:06 +000048// Helper Functions
49//===----------------------------------------------------------------------===//
50
David L. Jonesd21529f2017-01-23 23:16:46 +000051static bool ignoreCallingConv(LibFunc Func) {
52 return Func == LibFunc_abs || Func == LibFunc_labs ||
53 Func == LibFunc_llabs || Func == LibFunc_strlen;
Chris Bienemanad070d02014-09-17 20:55:46 +000054}
55
Sam Parker214f7bf2016-09-13 12:10:14 +000056static bool isCallingConvCCompatible(CallInst *CI) {
57 switch(CI->getCallingConv()) {
58 default:
59 return false;
60 case llvm::CallingConv::C:
61 return true;
62 case llvm::CallingConv::ARM_APCS:
63 case llvm::CallingConv::ARM_AAPCS:
64 case llvm::CallingConv::ARM_AAPCS_VFP: {
65
66 // The iOS ABI diverges from the standard in some cases, so for now don't
67 // try to simplify those calls.
68 if (Triple(CI->getModule()->getTargetTriple()).isiOS())
69 return false;
70
71 auto *FuncTy = CI->getFunctionType();
72
73 if (!FuncTy->getReturnType()->isPointerTy() &&
74 !FuncTy->getReturnType()->isIntegerTy() &&
75 !FuncTy->getReturnType()->isVoidTy())
76 return false;
77
78 for (auto Param : FuncTy->params()) {
79 if (!Param->isPointerTy() && !Param->isIntegerTy())
80 return false;
81 }
82 return true;
83 }
84 }
85 return false;
86}
87
Sanjay Pateld707db92015-12-31 16:10:49 +000088/// Return true if it is only used in equality comparisons with With.
Meador Inge56edbc92012-11-11 03:51:48 +000089static bool isOnlyUsedInEqualityComparison(Value *V, Value *With) {
Chandler Carruthcdf47882014-03-09 03:16:01 +000090 for (User *U : V->users()) {
91 if (ICmpInst *IC = dyn_cast<ICmpInst>(U))
Meador Inge56edbc92012-11-11 03:51:48 +000092 if (IC->isEquality() && IC->getOperand(1) == With)
93 continue;
94 // Unknown instruction.
95 return false;
96 }
97 return true;
98}
99
Meador Inge08ca1152012-11-26 20:37:20 +0000100static bool callHasFloatingPointArgument(const CallInst *CI) {
David Majnemer0a16c222016-08-11 21:15:00 +0000101 return any_of(CI->operands(), [](const Use &OI) {
Davide Italianoda3beeb2015-11-28 22:27:48 +0000102 return OI->getType()->isFloatingPointTy();
103 });
Meador Inge08ca1152012-11-26 20:37:20 +0000104}
105
Benjamin Kramer2702caa2013-08-31 18:19:35 +0000106/// \brief Check whether the overloaded unary floating point function
Sanjay Patele24c60e2015-08-12 20:36:18 +0000107/// corresponding to \a Ty is available.
Benjamin Kramer2702caa2013-08-31 18:19:35 +0000108static bool hasUnaryFloatFn(const TargetLibraryInfo *TLI, Type *Ty,
David L. Jonesd21529f2017-01-23 23:16:46 +0000109 LibFunc DoubleFn, LibFunc FloatFn,
110 LibFunc LongDoubleFn) {
Benjamin Kramer2702caa2013-08-31 18:19:35 +0000111 switch (Ty->getTypeID()) {
112 case Type::FloatTyID:
113 return TLI->has(FloatFn);
114 case Type::DoubleTyID:
115 return TLI->has(DoubleFn);
116 default:
117 return TLI->has(LongDoubleFn);
118 }
119}
120
Meador Inged589ac62012-10-31 03:33:06 +0000121//===----------------------------------------------------------------------===//
Meador Inge7fb2f732012-10-13 16:45:32 +0000122// String and Memory Library Call Optimizations
123//===----------------------------------------------------------------------===//
124
Chris Bienemanad070d02014-09-17 20:55:46 +0000125Value *LibCallSimplifier::optimizeStrCat(CallInst *CI, IRBuilder<> &B) {
Chris Bienemanad070d02014-09-17 20:55:46 +0000126 // Extract some information from the instruction
127 Value *Dst = CI->getArgOperand(0);
128 Value *Src = CI->getArgOperand(1);
129
130 // See if we can get the length of the input string.
131 uint64_t Len = GetStringLength(Src);
132 if (Len == 0)
133 return nullptr;
134 --Len; // Unbias length.
135
136 // Handle the simple, do-nothing case: strcat(x, "") -> x
137 if (Len == 0)
138 return Dst;
139
Chris Bienemanad070d02014-09-17 20:55:46 +0000140 return emitStrLenMemCpy(Src, Dst, Len, B);
141}
142
143Value *LibCallSimplifier::emitStrLenMemCpy(Value *Src, Value *Dst, uint64_t Len,
144 IRBuilder<> &B) {
145 // We need to find the end of the destination string. That's where the
146 // memory is to be moved to. We just generate a call to strlen.
Sanjay Pateld3112a52016-01-19 19:46:10 +0000147 Value *DstLen = emitStrLen(Dst, B, DL, TLI);
Chris Bienemanad070d02014-09-17 20:55:46 +0000148 if (!DstLen)
149 return nullptr;
150
151 // Now that we have the destination's length, we must index into the
152 // destination's pointer to get the actual memcpy destination (end of
153 // the string .. we're concatenating).
David Blaikie3909da72015-03-30 20:42:56 +0000154 Value *CpyDst = B.CreateGEP(B.getInt8Ty(), Dst, DstLen, "endptr");
Chris Bienemanad070d02014-09-17 20:55:46 +0000155
156 // We have enough information to now generate the memcpy call to do the
157 // concatenation for us. Make a memcpy to copy the nul byte with align = 1.
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000158 B.CreateMemCpy(CpyDst, Src,
159 ConstantInt::get(DL.getIntPtrType(Src->getContext()), Len + 1),
Pete Cooper67cf9a72015-11-19 05:56:52 +0000160 1);
Chris Bienemanad070d02014-09-17 20:55:46 +0000161 return Dst;
162}
163
164Value *LibCallSimplifier::optimizeStrNCat(CallInst *CI, IRBuilder<> &B) {
Sanjay Pateld707db92015-12-31 16:10:49 +0000165 // Extract some information from the instruction.
Chris Bienemanad070d02014-09-17 20:55:46 +0000166 Value *Dst = CI->getArgOperand(0);
167 Value *Src = CI->getArgOperand(1);
168 uint64_t Len;
169
Sanjay Pateld707db92015-12-31 16:10:49 +0000170 // We don't do anything if length is not constant.
Chris Bienemanad070d02014-09-17 20:55:46 +0000171 if (ConstantInt *LengthArg = dyn_cast<ConstantInt>(CI->getArgOperand(2)))
172 Len = LengthArg->getZExtValue();
173 else
174 return nullptr;
175
176 // See if we can get the length of the input string.
177 uint64_t SrcLen = GetStringLength(Src);
178 if (SrcLen == 0)
179 return nullptr;
180 --SrcLen; // Unbias length.
181
182 // Handle the simple, do-nothing cases:
183 // strncat(x, "", c) -> x
184 // strncat(x, c, 0) -> x
185 if (SrcLen == 0 || Len == 0)
186 return Dst;
187
Sanjay Pateld707db92015-12-31 16:10:49 +0000188 // We don't optimize this case.
Chris Bienemanad070d02014-09-17 20:55:46 +0000189 if (Len < SrcLen)
190 return nullptr;
191
192 // strncat(x, s, c) -> strcat(x, s)
Sanjay Pateld707db92015-12-31 16:10:49 +0000193 // s is constant so the strcat can be optimized further.
Chris Bienemanad070d02014-09-17 20:55:46 +0000194 return emitStrLenMemCpy(Src, Dst, SrcLen, B);
195}
196
197Value *LibCallSimplifier::optimizeStrChr(CallInst *CI, IRBuilder<> &B) {
198 Function *Callee = CI->getCalledFunction();
Chris Bienemanad070d02014-09-17 20:55:46 +0000199 FunctionType *FT = Callee->getFunctionType();
Chris Bienemanad070d02014-09-17 20:55:46 +0000200 Value *SrcStr = CI->getArgOperand(0);
201
202 // If the second operand is non-constant, see if we can compute the length
203 // of the input string and turn this into memchr.
204 ConstantInt *CharC = dyn_cast<ConstantInt>(CI->getArgOperand(1));
205 if (!CharC) {
Chris Bienemanad070d02014-09-17 20:55:46 +0000206 uint64_t Len = GetStringLength(SrcStr);
207 if (Len == 0 || !FT->getParamType(1)->isIntegerTy(32)) // memchr needs i32.
208 return nullptr;
Meador Inge7fb2f732012-10-13 16:45:32 +0000209
Sanjay Pateld3112a52016-01-19 19:46:10 +0000210 return emitMemChr(SrcStr, CI->getArgOperand(1), // include nul.
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000211 ConstantInt::get(DL.getIntPtrType(CI->getContext()), Len),
212 B, DL, TLI);
Meador Inge7fb2f732012-10-13 16:45:32 +0000213 }
214
Chris Bienemanad070d02014-09-17 20:55:46 +0000215 // Otherwise, the character is a constant, see if the first argument is
216 // a string literal. If so, we can constant fold.
217 StringRef Str;
218 if (!getConstantStringInfo(SrcStr, Str)) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000219 if (CharC->isZero()) // strchr(p, 0) -> p + strlen(p)
Sanjay Pateld3112a52016-01-19 19:46:10 +0000220 return B.CreateGEP(B.getInt8Ty(), SrcStr, emitStrLen(SrcStr, B, DL, TLI),
Sanjay Pateld707db92015-12-31 16:10:49 +0000221 "strchr");
Chris Bienemanad070d02014-09-17 20:55:46 +0000222 return nullptr;
223 }
224
225 // Compute the offset, make sure to handle the case when we're searching for
226 // zero (a weird way to spell strlen).
227 size_t I = (0xFF & CharC->getSExtValue()) == 0
228 ? Str.size()
229 : Str.find(CharC->getSExtValue());
230 if (I == StringRef::npos) // Didn't find the char. strchr returns null.
231 return Constant::getNullValue(CI->getType());
232
233 // strchr(s+n,c) -> gep(s+n+i,c)
David Blaikie3909da72015-03-30 20:42:56 +0000234 return B.CreateGEP(B.getInt8Ty(), SrcStr, B.getInt64(I), "strchr");
Chris Bienemanad070d02014-09-17 20:55:46 +0000235}
236
237Value *LibCallSimplifier::optimizeStrRChr(CallInst *CI, IRBuilder<> &B) {
Chris Bienemanad070d02014-09-17 20:55:46 +0000238 Value *SrcStr = CI->getArgOperand(0);
239 ConstantInt *CharC = dyn_cast<ConstantInt>(CI->getArgOperand(1));
240
241 // Cannot fold anything if we're not looking for a constant.
242 if (!CharC)
243 return nullptr;
244
245 StringRef Str;
246 if (!getConstantStringInfo(SrcStr, Str)) {
247 // strrchr(s, 0) -> strchr(s, 0)
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000248 if (CharC->isZero())
Sanjay Pateld3112a52016-01-19 19:46:10 +0000249 return emitStrChr(SrcStr, '\0', B, TLI);
Chris Bienemanad070d02014-09-17 20:55:46 +0000250 return nullptr;
251 }
252
253 // Compute the offset.
254 size_t I = (0xFF & CharC->getSExtValue()) == 0
255 ? Str.size()
256 : Str.rfind(CharC->getSExtValue());
257 if (I == StringRef::npos) // Didn't find the char. Return null.
258 return Constant::getNullValue(CI->getType());
259
260 // strrchr(s+n,c) -> gep(s+n+i,c)
David Blaikie3909da72015-03-30 20:42:56 +0000261 return B.CreateGEP(B.getInt8Ty(), SrcStr, B.getInt64(I), "strrchr");
Chris Bienemanad070d02014-09-17 20:55:46 +0000262}
263
264Value *LibCallSimplifier::optimizeStrCmp(CallInst *CI, IRBuilder<> &B) {
Chris Bienemanad070d02014-09-17 20:55:46 +0000265 Value *Str1P = CI->getArgOperand(0), *Str2P = CI->getArgOperand(1);
266 if (Str1P == Str2P) // strcmp(x,x) -> 0
267 return ConstantInt::get(CI->getType(), 0);
268
269 StringRef Str1, Str2;
270 bool HasStr1 = getConstantStringInfo(Str1P, Str1);
271 bool HasStr2 = getConstantStringInfo(Str2P, Str2);
272
273 // strcmp(x, y) -> cnst (if both x and y are constant strings)
274 if (HasStr1 && HasStr2)
275 return ConstantInt::get(CI->getType(), Str1.compare(Str2));
276
277 if (HasStr1 && Str1.empty()) // strcmp("", x) -> -*x
278 return B.CreateNeg(
279 B.CreateZExt(B.CreateLoad(Str2P, "strcmpload"), CI->getType()));
280
281 if (HasStr2 && Str2.empty()) // strcmp(x,"") -> *x
282 return B.CreateZExt(B.CreateLoad(Str1P, "strcmpload"), CI->getType());
283
284 // strcmp(P, "x") -> memcmp(P, "x", 2)
285 uint64_t Len1 = GetStringLength(Str1P);
286 uint64_t Len2 = GetStringLength(Str2P);
287 if (Len1 && Len2) {
Sanjay Pateld3112a52016-01-19 19:46:10 +0000288 return emitMemCmp(Str1P, Str2P,
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000289 ConstantInt::get(DL.getIntPtrType(CI->getContext()),
Chris Bienemanad070d02014-09-17 20:55:46 +0000290 std::min(Len1, Len2)),
291 B, DL, TLI);
292 }
Meador Inge7fb2f732012-10-13 16:45:32 +0000293
Chris Bienemanad070d02014-09-17 20:55:46 +0000294 return nullptr;
295}
296
297Value *LibCallSimplifier::optimizeStrNCmp(CallInst *CI, IRBuilder<> &B) {
Chris Bienemanad070d02014-09-17 20:55:46 +0000298 Value *Str1P = CI->getArgOperand(0), *Str2P = CI->getArgOperand(1);
299 if (Str1P == Str2P) // strncmp(x,x,n) -> 0
300 return ConstantInt::get(CI->getType(), 0);
301
302 // Get the length argument if it is constant.
303 uint64_t Length;
304 if (ConstantInt *LengthArg = dyn_cast<ConstantInt>(CI->getArgOperand(2)))
305 Length = LengthArg->getZExtValue();
306 else
307 return nullptr;
308
309 if (Length == 0) // strncmp(x,y,0) -> 0
310 return ConstantInt::get(CI->getType(), 0);
311
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000312 if (Length == 1) // strncmp(x,y,1) -> memcmp(x,y,1)
Sanjay Pateld3112a52016-01-19 19:46:10 +0000313 return emitMemCmp(Str1P, Str2P, CI->getArgOperand(2), B, DL, TLI);
Chris Bienemanad070d02014-09-17 20:55:46 +0000314
315 StringRef Str1, Str2;
316 bool HasStr1 = getConstantStringInfo(Str1P, Str1);
317 bool HasStr2 = getConstantStringInfo(Str2P, Str2);
318
319 // strncmp(x, y) -> cnst (if both x and y are constant strings)
320 if (HasStr1 && HasStr2) {
321 StringRef SubStr1 = Str1.substr(0, Length);
322 StringRef SubStr2 = Str2.substr(0, Length);
323 return ConstantInt::get(CI->getType(), SubStr1.compare(SubStr2));
324 }
325
326 if (HasStr1 && Str1.empty()) // strncmp("", x, n) -> -*x
327 return B.CreateNeg(
328 B.CreateZExt(B.CreateLoad(Str2P, "strcmpload"), CI->getType()));
329
330 if (HasStr2 && Str2.empty()) // strncmp(x, "", n) -> *x
331 return B.CreateZExt(B.CreateLoad(Str1P, "strcmpload"), CI->getType());
332
333 return nullptr;
334}
335
336Value *LibCallSimplifier::optimizeStrCpy(CallInst *CI, IRBuilder<> &B) {
Chris Bienemanad070d02014-09-17 20:55:46 +0000337 Value *Dst = CI->getArgOperand(0), *Src = CI->getArgOperand(1);
338 if (Dst == Src) // strcpy(x,x) -> x
339 return Src;
340
Chris Bienemanad070d02014-09-17 20:55:46 +0000341 // See if we can get the length of the input string.
342 uint64_t Len = GetStringLength(Src);
343 if (Len == 0)
344 return nullptr;
345
346 // We have enough information to now generate the memcpy call to do the
347 // copy for us. Make a memcpy to copy the nul byte with align = 1.
348 B.CreateMemCpy(Dst, Src,
Pete Cooper67cf9a72015-11-19 05:56:52 +0000349 ConstantInt::get(DL.getIntPtrType(CI->getContext()), Len), 1);
Chris Bienemanad070d02014-09-17 20:55:46 +0000350 return Dst;
351}
352
353Value *LibCallSimplifier::optimizeStpCpy(CallInst *CI, IRBuilder<> &B) {
354 Function *Callee = CI->getCalledFunction();
Chris Bienemanad070d02014-09-17 20:55:46 +0000355 Value *Dst = CI->getArgOperand(0), *Src = CI->getArgOperand(1);
356 if (Dst == Src) { // stpcpy(x,x) -> x+strlen(x)
Sanjay Pateld3112a52016-01-19 19:46:10 +0000357 Value *StrLen = emitStrLen(Src, B, DL, TLI);
David Blaikieaa41cd52015-04-03 21:33:42 +0000358 return StrLen ? B.CreateInBoundsGEP(B.getInt8Ty(), Dst, StrLen) : nullptr;
Chris Bienemanad070d02014-09-17 20:55:46 +0000359 }
360
361 // See if we can get the length of the input string.
362 uint64_t Len = GetStringLength(Src);
363 if (Len == 0)
364 return nullptr;
365
Davide Italianob7487e62015-11-02 23:07:14 +0000366 Type *PT = Callee->getFunctionType()->getParamType(0);
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000367 Value *LenV = ConstantInt::get(DL.getIntPtrType(PT), Len);
Sanjay Pateld707db92015-12-31 16:10:49 +0000368 Value *DstEnd = B.CreateGEP(B.getInt8Ty(), Dst,
369 ConstantInt::get(DL.getIntPtrType(PT), Len - 1));
Chris Bienemanad070d02014-09-17 20:55:46 +0000370
371 // We have enough information to now generate the memcpy call to do the
372 // copy for us. Make a memcpy to copy the nul byte with align = 1.
Pete Cooper67cf9a72015-11-19 05:56:52 +0000373 B.CreateMemCpy(Dst, Src, LenV, 1);
Chris Bienemanad070d02014-09-17 20:55:46 +0000374 return DstEnd;
375}
376
377Value *LibCallSimplifier::optimizeStrNCpy(CallInst *CI, IRBuilder<> &B) {
378 Function *Callee = CI->getCalledFunction();
Chris Bienemanad070d02014-09-17 20:55:46 +0000379 Value *Dst = CI->getArgOperand(0);
380 Value *Src = CI->getArgOperand(1);
381 Value *LenOp = CI->getArgOperand(2);
382
383 // See if we can get the length of the input string.
384 uint64_t SrcLen = GetStringLength(Src);
385 if (SrcLen == 0)
386 return nullptr;
387 --SrcLen;
388
389 if (SrcLen == 0) {
390 // strncpy(x, "", y) -> memset(x, '\0', y, 1)
391 B.CreateMemSet(Dst, B.getInt8('\0'), LenOp, 1);
Meador Inge7fb2f732012-10-13 16:45:32 +0000392 return Dst;
393 }
Meador Inge7fb2f732012-10-13 16:45:32 +0000394
Chris Bienemanad070d02014-09-17 20:55:46 +0000395 uint64_t Len;
396 if (ConstantInt *LengthArg = dyn_cast<ConstantInt>(LenOp))
397 Len = LengthArg->getZExtValue();
398 else
399 return nullptr;
Meador Inge7fb2f732012-10-13 16:45:32 +0000400
Chris Bienemanad070d02014-09-17 20:55:46 +0000401 if (Len == 0)
402 return Dst; // strncpy(x, y, 0) -> x
Meador Inge7fb2f732012-10-13 16:45:32 +0000403
Chris Bienemanad070d02014-09-17 20:55:46 +0000404 // Let strncpy handle the zero padding
405 if (Len > SrcLen + 1)
406 return nullptr;
Meador Inge7fb2f732012-10-13 16:45:32 +0000407
Davide Italianob7487e62015-11-02 23:07:14 +0000408 Type *PT = Callee->getFunctionType()->getParamType(0);
Chris Bienemanad070d02014-09-17 20:55:46 +0000409 // strncpy(x, s, c) -> memcpy(x, s, c, 1) [s and c are constant]
Pete Cooper67cf9a72015-11-19 05:56:52 +0000410 B.CreateMemCpy(Dst, Src, ConstantInt::get(DL.getIntPtrType(PT), Len), 1);
Meador Inge7fb2f732012-10-13 16:45:32 +0000411
Chris Bienemanad070d02014-09-17 20:55:46 +0000412 return Dst;
413}
Meador Inge7fb2f732012-10-13 16:45:32 +0000414
Matthias Braun50ec0b52017-05-19 22:37:09 +0000415Value *LibCallSimplifier::optimizeStringLength(CallInst *CI, IRBuilder<> &B,
416 unsigned CharSize) {
Chris Bienemanad070d02014-09-17 20:55:46 +0000417 Value *Src = CI->getArgOperand(0);
418
419 // Constant folding: strlen("xyz") -> 3
Matthias Braun50ec0b52017-05-19 22:37:09 +0000420 if (uint64_t Len = GetStringLength(Src, CharSize))
Chris Bienemanad070d02014-09-17 20:55:46 +0000421 return ConstantInt::get(CI->getType(), Len - 1);
422
David L Kreitzer752c1442016-04-13 14:31:06 +0000423 // If s is a constant pointer pointing to a string literal, we can fold
Matthias Braun50ec0b52017-05-19 22:37:09 +0000424 // strlen(s + x) to strlen(s) - x, when x is known to be in the range
David L Kreitzer752c1442016-04-13 14:31:06 +0000425 // [0, strlen(s)] or the string has a single null terminator '\0' at the end.
Matthias Braun50ec0b52017-05-19 22:37:09 +0000426 // We only try to simplify strlen when the pointer s points to an array
David L Kreitzer752c1442016-04-13 14:31:06 +0000427 // of i8. Otherwise, we would need to scale the offset x before doing the
Matthias Braun50ec0b52017-05-19 22:37:09 +0000428 // subtraction. This will make the optimization more complex, and it's not
429 // very useful because calling strlen for a pointer of other types is
David L Kreitzer752c1442016-04-13 14:31:06 +0000430 // very uncommon.
431 if (GEPOperator *GEP = dyn_cast<GEPOperator>(Src)) {
Matthias Braun50ec0b52017-05-19 22:37:09 +0000432 if (!isGEPBasedOnPointerToString(GEP, CharSize))
David L Kreitzer752c1442016-04-13 14:31:06 +0000433 return nullptr;
434
Matthias Braun50ec0b52017-05-19 22:37:09 +0000435 ConstantDataArraySlice Slice;
436 if (getConstantDataArrayInfo(GEP->getOperand(0), Slice, CharSize)) {
437 uint64_t NullTermIdx;
438 if (Slice.Array == nullptr) {
439 NullTermIdx = 0;
440 } else {
441 NullTermIdx = ~((uint64_t)0);
442 for (uint64_t I = 0, E = Slice.Length; I < E; ++I) {
443 if (Slice.Array->getElementAsInteger(I + Slice.Offset) == 0) {
444 NullTermIdx = I;
445 break;
446 }
447 }
448 // If the string does not have '\0', leave it to strlen to compute
449 // its length.
450 if (NullTermIdx == ~((uint64_t)0))
451 return nullptr;
452 }
453
David L Kreitzer752c1442016-04-13 14:31:06 +0000454 Value *Offset = GEP->getOperand(2);
Craig Topper8205a1a2017-05-24 16:53:07 +0000455 KnownBits Known = computeKnownBits(Offset, DL, 0, nullptr, CI, nullptr);
Craig Topperb45eabc2017-04-26 16:39:58 +0000456 Known.Zero.flipAllBits();
Matthias Braun50ec0b52017-05-19 22:37:09 +0000457 uint64_t ArrSize =
David L Kreitzer752c1442016-04-13 14:31:06 +0000458 cast<ArrayType>(GEP->getSourceElementType())->getNumElements();
459
Matthias Braun50ec0b52017-05-19 22:37:09 +0000460 // KnownZero's bits are flipped, so zeros in KnownZero now represent
461 // bits known to be zeros in Offset, and ones in KnowZero represent
David L Kreitzer752c1442016-04-13 14:31:06 +0000462 // bits unknown in Offset. Therefore, Offset is known to be in range
Matthias Braun50ec0b52017-05-19 22:37:09 +0000463 // [0, NullTermIdx] when the flipped KnownZero is non-negative and
David L Kreitzer752c1442016-04-13 14:31:06 +0000464 // unsigned-less-than NullTermIdx.
465 //
Matthias Braun50ec0b52017-05-19 22:37:09 +0000466 // If Offset is not provably in the range [0, NullTermIdx], we can still
467 // optimize if we can prove that the program has undefined behavior when
468 // Offset is outside that range. That is the case when GEP->getOperand(0)
David L Kreitzer752c1442016-04-13 14:31:06 +0000469 // is a pointer to an object whose memory extent is NullTermIdx+1.
Matthias Braun50ec0b52017-05-19 22:37:09 +0000470 if ((Known.Zero.isNonNegative() && Known.Zero.ule(NullTermIdx)) ||
David L Kreitzer752c1442016-04-13 14:31:06 +0000471 (GEP->isInBounds() && isa<GlobalVariable>(GEP->getOperand(0)) &&
Matthias Braun50ec0b52017-05-19 22:37:09 +0000472 NullTermIdx == ArrSize - 1)) {
473 Offset = B.CreateSExtOrTrunc(Offset, CI->getType());
474 return B.CreateSub(ConstantInt::get(CI->getType(), NullTermIdx),
David L Kreitzer752c1442016-04-13 14:31:06 +0000475 Offset);
Matthias Braun50ec0b52017-05-19 22:37:09 +0000476 }
David L Kreitzer752c1442016-04-13 14:31:06 +0000477 }
478
479 return nullptr;
480 }
481
Chris Bienemanad070d02014-09-17 20:55:46 +0000482 // strlen(x?"foo":"bars") --> x ? 3 : 4
483 if (SelectInst *SI = dyn_cast<SelectInst>(Src)) {
Matthias Braun50ec0b52017-05-19 22:37:09 +0000484 uint64_t LenTrue = GetStringLength(SI->getTrueValue(), CharSize);
485 uint64_t LenFalse = GetStringLength(SI->getFalseValue(), CharSize);
Chris Bienemanad070d02014-09-17 20:55:46 +0000486 if (LenTrue && LenFalse) {
487 Function *Caller = CI->getParent()->getParent();
488 emitOptimizationRemark(CI->getContext(), "simplify-libcalls", *Caller,
489 SI->getDebugLoc(),
490 "folded strlen(select) to select of constants");
491 return B.CreateSelect(SI->getCondition(),
492 ConstantInt::get(CI->getType(), LenTrue - 1),
493 ConstantInt::get(CI->getType(), LenFalse - 1));
494 }
Meador Inge7fb2f732012-10-13 16:45:32 +0000495 }
Meador Inge7fb2f732012-10-13 16:45:32 +0000496
Chris Bienemanad070d02014-09-17 20:55:46 +0000497 // strlen(x) != 0 --> *x != 0
498 // strlen(x) == 0 --> *x == 0
499 if (isOnlyUsedInZeroEqualityComparison(CI))
500 return B.CreateZExt(B.CreateLoad(Src, "strlenfirst"), CI->getType());
Meador Inge17418502012-10-13 16:45:37 +0000501
Chris Bienemanad070d02014-09-17 20:55:46 +0000502 return nullptr;
503}
Meador Inge17418502012-10-13 16:45:37 +0000504
Matthias Braun50ec0b52017-05-19 22:37:09 +0000505Value *LibCallSimplifier::optimizeStrLen(CallInst *CI, IRBuilder<> &B) {
506 return optimizeStringLength(CI, B, 8);
507}
508
509Value *LibCallSimplifier::optimizeWcslen(CallInst *CI, IRBuilder<> &B) {
510 Module &M = *CI->getParent()->getParent()->getParent();
511 unsigned WCharSize = TLI->getWCharSize(M) * 8;
512
513 return optimizeStringLength(CI, B, WCharSize);
514}
515
Chris Bienemanad070d02014-09-17 20:55:46 +0000516Value *LibCallSimplifier::optimizeStrPBrk(CallInst *CI, IRBuilder<> &B) {
Chris Bienemanad070d02014-09-17 20:55:46 +0000517 StringRef S1, S2;
518 bool HasS1 = getConstantStringInfo(CI->getArgOperand(0), S1);
519 bool HasS2 = getConstantStringInfo(CI->getArgOperand(1), S2);
Meador Inge17418502012-10-13 16:45:37 +0000520
Reid Kleckner971c3ea2014-11-13 22:55:19 +0000521 // strpbrk(s, "") -> nullptr
522 // strpbrk("", s) -> nullptr
Chris Bienemanad070d02014-09-17 20:55:46 +0000523 if ((HasS1 && S1.empty()) || (HasS2 && S2.empty()))
524 return Constant::getNullValue(CI->getType());
Meador Inge17418502012-10-13 16:45:37 +0000525
Chris Bienemanad070d02014-09-17 20:55:46 +0000526 // Constant folding.
527 if (HasS1 && HasS2) {
528 size_t I = S1.find_first_of(S2);
529 if (I == StringRef::npos) // No match.
Meador Inge17418502012-10-13 16:45:37 +0000530 return Constant::getNullValue(CI->getType());
531
Sanjay Pateld707db92015-12-31 16:10:49 +0000532 return B.CreateGEP(B.getInt8Ty(), CI->getArgOperand(0), B.getInt64(I),
533 "strpbrk");
Meador Inge17418502012-10-13 16:45:37 +0000534 }
Meador Inge17418502012-10-13 16:45:37 +0000535
Chris Bienemanad070d02014-09-17 20:55:46 +0000536 // strpbrk(s, "a") -> strchr(s, 'a')
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000537 if (HasS2 && S2.size() == 1)
Sanjay Pateld3112a52016-01-19 19:46:10 +0000538 return emitStrChr(CI->getArgOperand(0), S2[0], B, TLI);
Chris Bienemanad070d02014-09-17 20:55:46 +0000539
540 return nullptr;
541}
542
543Value *LibCallSimplifier::optimizeStrTo(CallInst *CI, IRBuilder<> &B) {
Chris Bienemanad070d02014-09-17 20:55:46 +0000544 Value *EndPtr = CI->getArgOperand(1);
545 if (isa<ConstantPointerNull>(EndPtr)) {
546 // With a null EndPtr, this function won't capture the main argument.
547 // It would be readonly too, except that it still may write to errno.
Reid Klecknera0b45f42017-05-03 18:17:31 +0000548 CI->addParamAttr(0, Attribute::NoCapture);
Chris Bienemanad070d02014-09-17 20:55:46 +0000549 }
550
551 return nullptr;
552}
553
554Value *LibCallSimplifier::optimizeStrSpn(CallInst *CI, IRBuilder<> &B) {
Chris Bienemanad070d02014-09-17 20:55:46 +0000555 StringRef S1, S2;
556 bool HasS1 = getConstantStringInfo(CI->getArgOperand(0), S1);
557 bool HasS2 = getConstantStringInfo(CI->getArgOperand(1), S2);
558
559 // strspn(s, "") -> 0
560 // strspn("", s) -> 0
561 if ((HasS1 && S1.empty()) || (HasS2 && S2.empty()))
562 return Constant::getNullValue(CI->getType());
563
564 // Constant folding.
565 if (HasS1 && HasS2) {
566 size_t Pos = S1.find_first_not_of(S2);
567 if (Pos == StringRef::npos)
568 Pos = S1.size();
569 return ConstantInt::get(CI->getType(), Pos);
570 }
571
572 return nullptr;
573}
574
575Value *LibCallSimplifier::optimizeStrCSpn(CallInst *CI, IRBuilder<> &B) {
Chris Bienemanad070d02014-09-17 20:55:46 +0000576 StringRef S1, S2;
577 bool HasS1 = getConstantStringInfo(CI->getArgOperand(0), S1);
578 bool HasS2 = getConstantStringInfo(CI->getArgOperand(1), S2);
579
580 // strcspn("", s) -> 0
581 if (HasS1 && S1.empty())
582 return Constant::getNullValue(CI->getType());
583
584 // Constant folding.
585 if (HasS1 && HasS2) {
586 size_t Pos = S1.find_first_of(S2);
587 if (Pos == StringRef::npos)
588 Pos = S1.size();
589 return ConstantInt::get(CI->getType(), Pos);
590 }
591
592 // strcspn(s, "") -> strlen(s)
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000593 if (HasS2 && S2.empty())
Sanjay Pateld3112a52016-01-19 19:46:10 +0000594 return emitStrLen(CI->getArgOperand(0), B, DL, TLI);
Chris Bienemanad070d02014-09-17 20:55:46 +0000595
596 return nullptr;
597}
598
599Value *LibCallSimplifier::optimizeStrStr(CallInst *CI, IRBuilder<> &B) {
Chris Bienemanad070d02014-09-17 20:55:46 +0000600 // fold strstr(x, x) -> x.
601 if (CI->getArgOperand(0) == CI->getArgOperand(1))
602 return B.CreateBitCast(CI->getArgOperand(0), CI->getType());
603
604 // fold strstr(a, b) == a -> strncmp(a, b, strlen(b)) == 0
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000605 if (isOnlyUsedInEqualityComparison(CI, CI->getArgOperand(0))) {
Sanjay Pateld3112a52016-01-19 19:46:10 +0000606 Value *StrLen = emitStrLen(CI->getArgOperand(1), B, DL, TLI);
Chris Bienemanad070d02014-09-17 20:55:46 +0000607 if (!StrLen)
Craig Topperf40110f2014-04-25 05:29:35 +0000608 return nullptr;
Sanjay Pateld3112a52016-01-19 19:46:10 +0000609 Value *StrNCmp = emitStrNCmp(CI->getArgOperand(0), CI->getArgOperand(1),
Chris Bienemanad070d02014-09-17 20:55:46 +0000610 StrLen, B, DL, TLI);
611 if (!StrNCmp)
Craig Topperf40110f2014-04-25 05:29:35 +0000612 return nullptr;
Chris Bienemanad070d02014-09-17 20:55:46 +0000613 for (auto UI = CI->user_begin(), UE = CI->user_end(); UI != UE;) {
614 ICmpInst *Old = cast<ICmpInst>(*UI++);
615 Value *Cmp =
616 B.CreateICmp(Old->getPredicate(), StrNCmp,
617 ConstantInt::getNullValue(StrNCmp->getType()), "cmp");
618 replaceAllUsesWith(Old, Cmp);
Meador Inge17418502012-10-13 16:45:37 +0000619 }
Chris Bienemanad070d02014-09-17 20:55:46 +0000620 return CI;
621 }
Meador Inge17418502012-10-13 16:45:37 +0000622
Chris Bienemanad070d02014-09-17 20:55:46 +0000623 // See if either input string is a constant string.
624 StringRef SearchStr, ToFindStr;
625 bool HasStr1 = getConstantStringInfo(CI->getArgOperand(0), SearchStr);
626 bool HasStr2 = getConstantStringInfo(CI->getArgOperand(1), ToFindStr);
627
628 // fold strstr(x, "") -> x.
629 if (HasStr2 && ToFindStr.empty())
630 return B.CreateBitCast(CI->getArgOperand(0), CI->getType());
631
632 // If both strings are known, constant fold it.
633 if (HasStr1 && HasStr2) {
634 size_t Offset = SearchStr.find(ToFindStr);
635
636 if (Offset == StringRef::npos) // strstr("foo", "bar") -> null
Meador Inge17418502012-10-13 16:45:37 +0000637 return Constant::getNullValue(CI->getType());
638
Chris Bienemanad070d02014-09-17 20:55:46 +0000639 // strstr("abcd", "bc") -> gep((char*)"abcd", 1)
Sanjay Pateld3112a52016-01-19 19:46:10 +0000640 Value *Result = castToCStr(CI->getArgOperand(0), B);
Chris Bienemanad070d02014-09-17 20:55:46 +0000641 Result = B.CreateConstInBoundsGEP1_64(Result, Offset, "strstr");
642 return B.CreateBitCast(Result, CI->getType());
Meador Inge17418502012-10-13 16:45:37 +0000643 }
Meador Inge17418502012-10-13 16:45:37 +0000644
Chris Bienemanad070d02014-09-17 20:55:46 +0000645 // fold strstr(x, "y") -> strchr(x, 'y').
646 if (HasStr2 && ToFindStr.size() == 1) {
Sanjay Pateld3112a52016-01-19 19:46:10 +0000647 Value *StrChr = emitStrChr(CI->getArgOperand(0), ToFindStr[0], B, TLI);
Chris Bienemanad070d02014-09-17 20:55:46 +0000648 return StrChr ? B.CreateBitCast(StrChr, CI->getType()) : nullptr;
649 }
650 return nullptr;
651}
Meador Inge40b6fac2012-10-15 03:47:37 +0000652
Benjamin Kramer691363e2015-03-21 15:36:21 +0000653Value *LibCallSimplifier::optimizeMemChr(CallInst *CI, IRBuilder<> &B) {
Benjamin Kramer691363e2015-03-21 15:36:21 +0000654 Value *SrcStr = CI->getArgOperand(0);
655 ConstantInt *CharC = dyn_cast<ConstantInt>(CI->getArgOperand(1));
656 ConstantInt *LenC = dyn_cast<ConstantInt>(CI->getArgOperand(2));
657
658 // memchr(x, y, 0) -> null
659 if (LenC && LenC->isNullValue())
660 return Constant::getNullValue(CI->getType());
661
Benjamin Kramer7857d722015-03-21 21:09:33 +0000662 // From now on we need at least constant length and string.
Benjamin Kramer691363e2015-03-21 15:36:21 +0000663 StringRef Str;
Benjamin Kramer7857d722015-03-21 21:09:33 +0000664 if (!LenC || !getConstantStringInfo(SrcStr, Str, 0, /*TrimAtNul=*/false))
Benjamin Kramer691363e2015-03-21 15:36:21 +0000665 return nullptr;
666
667 // Truncate the string to LenC. If Str is smaller than LenC we will still only
668 // scan the string, as reading past the end of it is undefined and we can just
669 // return null if we don't find the char.
670 Str = Str.substr(0, LenC->getZExtValue());
671
Benjamin Kramer7857d722015-03-21 21:09:33 +0000672 // If the char is variable but the input str and length are not we can turn
673 // this memchr call into a simple bit field test. Of course this only works
674 // when the return value is only checked against null.
675 //
676 // It would be really nice to reuse switch lowering here but we can't change
677 // the CFG at this point.
678 //
679 // memchr("\r\n", C, 2) != nullptr -> (C & ((1 << '\r') | (1 << '\n'))) != 0
680 // after bounds check.
681 if (!CharC && !Str.empty() && isOnlyUsedInZeroEqualityComparison(CI)) {
Benjamin Kramerd6aa0ec2015-03-21 22:04:26 +0000682 unsigned char Max =
683 *std::max_element(reinterpret_cast<const unsigned char *>(Str.begin()),
684 reinterpret_cast<const unsigned char *>(Str.end()));
Benjamin Kramer7857d722015-03-21 21:09:33 +0000685
686 // Make sure the bit field we're about to create fits in a register on the
687 // target.
688 // FIXME: On a 64 bit architecture this prevents us from using the
689 // interesting range of alpha ascii chars. We could do better by emitting
690 // two bitfields or shifting the range by 64 if no lower chars are used.
691 if (!DL.fitsInLegalInteger(Max + 1))
692 return nullptr;
693
694 // For the bit field use a power-of-2 type with at least 8 bits to avoid
695 // creating unnecessary illegal types.
696 unsigned char Width = NextPowerOf2(std::max((unsigned char)7, Max));
697
698 // Now build the bit field.
699 APInt Bitfield(Width, 0);
700 for (char C : Str)
701 Bitfield.setBit((unsigned char)C);
702 Value *BitfieldC = B.getInt(Bitfield);
703
704 // First check that the bit field access is within bounds.
705 Value *C = B.CreateZExtOrTrunc(CI->getArgOperand(1), BitfieldC->getType());
706 Value *Bounds = B.CreateICmp(ICmpInst::ICMP_ULT, C, B.getIntN(Width, Width),
707 "memchr.bounds");
708
709 // Create code that checks if the given bit is set in the field.
710 Value *Shl = B.CreateShl(B.getIntN(Width, 1ULL), C);
711 Value *Bits = B.CreateIsNotNull(B.CreateAnd(Shl, BitfieldC), "memchr.bits");
712
713 // Finally merge both checks and cast to pointer type. The inttoptr
714 // implicitly zexts the i1 to intptr type.
715 return B.CreateIntToPtr(B.CreateAnd(Bounds, Bits, "memchr"), CI->getType());
716 }
717
718 // Check if all arguments are constants. If so, we can constant fold.
719 if (!CharC)
720 return nullptr;
721
Benjamin Kramer691363e2015-03-21 15:36:21 +0000722 // Compute the offset.
723 size_t I = Str.find(CharC->getSExtValue() & 0xFF);
724 if (I == StringRef::npos) // Didn't find the char. memchr returns null.
725 return Constant::getNullValue(CI->getType());
726
727 // memchr(s+n,c,l) -> gep(s+n+i,c)
David Blaikie3909da72015-03-30 20:42:56 +0000728 return B.CreateGEP(B.getInt8Ty(), SrcStr, B.getInt64(I), "memchr");
Benjamin Kramer691363e2015-03-21 15:36:21 +0000729}
730
Chris Bienemanad070d02014-09-17 20:55:46 +0000731Value *LibCallSimplifier::optimizeMemCmp(CallInst *CI, IRBuilder<> &B) {
Chris Bienemanad070d02014-09-17 20:55:46 +0000732 Value *LHS = CI->getArgOperand(0), *RHS = CI->getArgOperand(1);
Meador Inge40b6fac2012-10-15 03:47:37 +0000733
Chris Bienemanad070d02014-09-17 20:55:46 +0000734 if (LHS == RHS) // memcmp(s,s,x) -> 0
735 return Constant::getNullValue(CI->getType());
Meador Inge40b6fac2012-10-15 03:47:37 +0000736
Chris Bienemanad070d02014-09-17 20:55:46 +0000737 // Make sure we have a constant length.
738 ConstantInt *LenC = dyn_cast<ConstantInt>(CI->getArgOperand(2));
739 if (!LenC)
Craig Topperf40110f2014-04-25 05:29:35 +0000740 return nullptr;
Chris Bienemanad070d02014-09-17 20:55:46 +0000741 uint64_t Len = LenC->getZExtValue();
742
743 if (Len == 0) // memcmp(s1,s2,0) -> 0
744 return Constant::getNullValue(CI->getType());
745
746 // memcmp(S1,S2,1) -> *(unsigned char*)LHS - *(unsigned char*)RHS
747 if (Len == 1) {
Sanjay Pateld3112a52016-01-19 19:46:10 +0000748 Value *LHSV = B.CreateZExt(B.CreateLoad(castToCStr(LHS, B), "lhsc"),
Chris Bienemanad070d02014-09-17 20:55:46 +0000749 CI->getType(), "lhsv");
Sanjay Pateld3112a52016-01-19 19:46:10 +0000750 Value *RHSV = B.CreateZExt(B.CreateLoad(castToCStr(RHS, B), "rhsc"),
Chris Bienemanad070d02014-09-17 20:55:46 +0000751 CI->getType(), "rhsv");
752 return B.CreateSub(LHSV, RHSV, "chardiff");
Meador Inge40b6fac2012-10-15 03:47:37 +0000753 }
Meador Inge40b6fac2012-10-15 03:47:37 +0000754
Chad Rosierdc655322015-08-28 18:30:18 +0000755 // memcmp(S1,S2,N/8)==0 -> (*(intN_t*)S1 != *(intN_t*)S2)==0
756 if (DL.isLegalInteger(Len * 8) && isOnlyUsedInZeroEqualityComparison(CI)) {
757
758 IntegerType *IntType = IntegerType::get(CI->getContext(), Len * 8);
759 unsigned PrefAlignment = DL.getPrefTypeAlignment(IntType);
760
761 if (getKnownAlignment(LHS, DL, CI) >= PrefAlignment &&
762 getKnownAlignment(RHS, DL, CI) >= PrefAlignment) {
763
764 Type *LHSPtrTy =
765 IntType->getPointerTo(LHS->getType()->getPointerAddressSpace());
766 Type *RHSPtrTy =
767 IntType->getPointerTo(RHS->getType()->getPointerAddressSpace());
768
Sanjay Pateld707db92015-12-31 16:10:49 +0000769 Value *LHSV =
770 B.CreateLoad(B.CreateBitCast(LHS, LHSPtrTy, "lhsc"), "lhsv");
771 Value *RHSV =
772 B.CreateLoad(B.CreateBitCast(RHS, RHSPtrTy, "rhsc"), "rhsv");
Chad Rosierdc655322015-08-28 18:30:18 +0000773
774 return B.CreateZExt(B.CreateICmpNE(LHSV, RHSV), CI->getType(), "memcmp");
775 }
776 }
777
Chris Bienemanad070d02014-09-17 20:55:46 +0000778 // Constant folding: memcmp(x, y, l) -> cnst (all arguments are constant)
779 StringRef LHSStr, RHSStr;
780 if (getConstantStringInfo(LHS, LHSStr) &&
781 getConstantStringInfo(RHS, RHSStr)) {
782 // Make sure we're not reading out-of-bounds memory.
783 if (Len > LHSStr.size() || Len > RHSStr.size())
Craig Topperf40110f2014-04-25 05:29:35 +0000784 return nullptr;
Chris Bienemanad070d02014-09-17 20:55:46 +0000785 // Fold the memcmp and normalize the result. This way we get consistent
786 // results across multiple platforms.
787 uint64_t Ret = 0;
788 int Cmp = memcmp(LHSStr.data(), RHSStr.data(), Len);
789 if (Cmp < 0)
790 Ret = -1;
791 else if (Cmp > 0)
792 Ret = 1;
793 return ConstantInt::get(CI->getType(), Ret);
Meador Inge000dbcc2012-10-18 18:12:40 +0000794 }
Meador Inge000dbcc2012-10-18 18:12:40 +0000795
Chris Bienemanad070d02014-09-17 20:55:46 +0000796 return nullptr;
797}
Meador Inge9a6a1902012-10-31 00:20:56 +0000798
Chris Bienemanad070d02014-09-17 20:55:46 +0000799Value *LibCallSimplifier::optimizeMemCpy(CallInst *CI, IRBuilder<> &B) {
Chris Bienemanad070d02014-09-17 20:55:46 +0000800 // memcpy(x, y, n) -> llvm.memcpy(x, y, n, 1)
801 B.CreateMemCpy(CI->getArgOperand(0), CI->getArgOperand(1),
Pete Cooper67cf9a72015-11-19 05:56:52 +0000802 CI->getArgOperand(2), 1);
Chris Bienemanad070d02014-09-17 20:55:46 +0000803 return CI->getArgOperand(0);
804}
Meador Inge05a625a2012-10-31 14:58:26 +0000805
Chris Bienemanad070d02014-09-17 20:55:46 +0000806Value *LibCallSimplifier::optimizeMemMove(CallInst *CI, IRBuilder<> &B) {
Chris Bienemanad070d02014-09-17 20:55:46 +0000807 // memmove(x, y, n) -> llvm.memmove(x, y, n, 1)
808 B.CreateMemMove(CI->getArgOperand(0), CI->getArgOperand(1),
Pete Cooper67cf9a72015-11-19 05:56:52 +0000809 CI->getArgOperand(2), 1);
Chris Bienemanad070d02014-09-17 20:55:46 +0000810 return CI->getArgOperand(0);
811}
Meador Ingebcd88ef72012-11-10 15:16:48 +0000812
Sanjay Patel980b2802016-01-26 16:17:24 +0000813// TODO: Does this belong in BuildLibCalls or should all of those similar
814// functions be moved here?
Reid Klecknerb5180542017-03-21 16:57:19 +0000815static Value *emitCalloc(Value *Num, Value *Size, const AttributeList &Attrs,
Sanjay Patel980b2802016-01-26 16:17:24 +0000816 IRBuilder<> &B, const TargetLibraryInfo &TLI) {
David L. Jonesd21529f2017-01-23 23:16:46 +0000817 LibFunc Func;
Sanjay Patel980b2802016-01-26 16:17:24 +0000818 if (!TLI.getLibFunc("calloc", Func) || !TLI.has(Func))
819 return nullptr;
820
821 Module *M = B.GetInsertBlock()->getModule();
822 const DataLayout &DL = M->getDataLayout();
823 IntegerType *PtrType = DL.getIntPtrType((B.GetInsertBlock()->getContext()));
824 Value *Calloc = M->getOrInsertFunction("calloc", Attrs, B.getInt8PtrTy(),
Serge Guelton59a2d7b2017-04-11 15:01:18 +0000825 PtrType, PtrType);
Sanjay Patel980b2802016-01-26 16:17:24 +0000826 CallInst *CI = B.CreateCall(Calloc, { Num, Size }, "calloc");
827
828 if (const auto *F = dyn_cast<Function>(Calloc->stripPointerCasts()))
829 CI->setCallingConv(F->getCallingConv());
830
831 return CI;
832}
833
834/// Fold memset[_chk](malloc(n), 0, n) --> calloc(1, n).
835static Value *foldMallocMemset(CallInst *Memset, IRBuilder<> &B,
836 const TargetLibraryInfo &TLI) {
837 // This has to be a memset of zeros (bzero).
838 auto *FillValue = dyn_cast<ConstantInt>(Memset->getArgOperand(1));
839 if (!FillValue || FillValue->getZExtValue() != 0)
840 return nullptr;
841
842 // TODO: We should handle the case where the malloc has more than one use.
843 // This is necessary to optimize common patterns such as when the result of
844 // the malloc is checked against null or when a memset intrinsic is used in
845 // place of a memset library call.
846 auto *Malloc = dyn_cast<CallInst>(Memset->getArgOperand(0));
847 if (!Malloc || !Malloc->hasOneUse())
848 return nullptr;
849
850 // Is the inner call really malloc()?
851 Function *InnerCallee = Malloc->getCalledFunction();
Matthias Braunc36a78c2017-04-25 19:44:25 +0000852 if (!InnerCallee)
853 return nullptr;
854
David L. Jonesd21529f2017-01-23 23:16:46 +0000855 LibFunc Func;
Ahmed Bougachad765a822016-04-27 19:04:35 +0000856 if (!TLI.getLibFunc(*InnerCallee, Func) || !TLI.has(Func) ||
David L. Jonesd21529f2017-01-23 23:16:46 +0000857 Func != LibFunc_malloc)
Sanjay Patel980b2802016-01-26 16:17:24 +0000858 return nullptr;
859
Sanjay Patel980b2802016-01-26 16:17:24 +0000860 // The memset must cover the same number of bytes that are malloc'd.
861 if (Memset->getArgOperand(2) != Malloc->getArgOperand(0))
862 return nullptr;
863
864 // Replace the malloc with a calloc. We need the data layout to know what the
865 // actual size of a 'size_t' parameter is.
866 B.SetInsertPoint(Malloc->getParent(), ++Malloc->getIterator());
867 const DataLayout &DL = Malloc->getModule()->getDataLayout();
868 IntegerType *SizeType = DL.getIntPtrType(B.GetInsertBlock()->getContext());
869 Value *Calloc = emitCalloc(ConstantInt::get(SizeType, 1),
870 Malloc->getArgOperand(0), Malloc->getAttributes(),
871 B, TLI);
872 if (!Calloc)
873 return nullptr;
874
875 Malloc->replaceAllUsesWith(Calloc);
876 Malloc->eraseFromParent();
877
878 return Calloc;
879}
880
Chris Bienemanad070d02014-09-17 20:55:46 +0000881Value *LibCallSimplifier::optimizeMemSet(CallInst *CI, IRBuilder<> &B) {
Sanjay Patel980b2802016-01-26 16:17:24 +0000882 if (auto *Calloc = foldMallocMemset(CI, B, *TLI))
883 return Calloc;
884
Chris Bienemanad070d02014-09-17 20:55:46 +0000885 // memset(p, v, n) -> llvm.memset(p, v, n, 1)
886 Value *Val = B.CreateIntCast(CI->getArgOperand(1), B.getInt8Ty(), false);
887 B.CreateMemSet(CI->getArgOperand(0), Val, CI->getArgOperand(2), 1);
888 return CI->getArgOperand(0);
889}
Meador Inged4825782012-11-11 06:49:03 +0000890
Meador Inge193e0352012-11-13 04:16:17 +0000891//===----------------------------------------------------------------------===//
892// Math Library Optimizations
893//===----------------------------------------------------------------------===//
894
Matthias Braund34e4d22014-12-03 21:46:33 +0000895/// Return a variant of Val with float type.
896/// Currently this works in two cases: If Val is an FPExtension of a float
897/// value to something bigger, simply return the operand.
898/// If Val is a ConstantFP but can be converted to a float ConstantFP without
899/// loss of precision do so.
900static Value *valueHasFloatPrecision(Value *Val) {
901 if (FPExtInst *Cast = dyn_cast<FPExtInst>(Val)) {
902 Value *Op = Cast->getOperand(0);
903 if (Op->getType()->isFloatTy())
904 return Op;
905 }
906 if (ConstantFP *Const = dyn_cast<ConstantFP>(Val)) {
907 APFloat F = Const->getValueAPF();
Matthias Braun395a82f2014-12-03 22:10:39 +0000908 bool losesInfo;
Stephan Bergmann17c7f702016-12-14 11:57:17 +0000909 (void)F.convert(APFloat::IEEEsingle(), APFloat::rmNearestTiesToEven,
Matthias Braun395a82f2014-12-03 22:10:39 +0000910 &losesInfo);
911 if (!losesInfo)
Matthias Braund34e4d22014-12-03 21:46:33 +0000912 return ConstantFP::get(Const->getContext(), F);
913 }
914 return nullptr;
915}
916
Sanjay Patel4e971da2016-01-21 18:01:57 +0000917/// Shrink double -> float for unary functions like 'floor'.
918static Value *optimizeUnaryDoubleFP(CallInst *CI, IRBuilder<> &B,
919 bool CheckRetType) {
Chris Bienemanad070d02014-09-17 20:55:46 +0000920 Function *Callee = CI->getCalledFunction();
Ahmed Bougachad765a822016-04-27 19:04:35 +0000921 // We know this libcall has a valid prototype, but we don't know which.
922 if (!CI->getType()->isDoubleTy())
Chris Bienemanad070d02014-09-17 20:55:46 +0000923 return nullptr;
Meador Inge193e0352012-11-13 04:16:17 +0000924
Chris Bienemanad070d02014-09-17 20:55:46 +0000925 if (CheckRetType) {
926 // Check if all the uses for function like 'sin' are converted to float.
927 for (User *U : CI->users()) {
928 FPTruncInst *Cast = dyn_cast<FPTruncInst>(U);
929 if (!Cast || !Cast->getType()->isFloatTy())
930 return nullptr;
Meador Inge193e0352012-11-13 04:16:17 +0000931 }
Meador Inge193e0352012-11-13 04:16:17 +0000932 }
Chris Bienemanad070d02014-09-17 20:55:46 +0000933
934 // If this is something like 'floor((double)floatval)', convert to floorf.
Matthias Braund34e4d22014-12-03 21:46:33 +0000935 Value *V = valueHasFloatPrecision(CI->getArgOperand(0));
936 if (V == nullptr)
Chris Bienemanad070d02014-09-17 20:55:46 +0000937 return nullptr;
Sanjay Patelaa231142015-12-31 21:52:31 +0000938
Andrew Ng1606fc02017-04-25 12:36:14 +0000939 // If call isn't an intrinsic, check that it isn't within a function with the
940 // same name as the float version of this call.
941 //
942 // e.g. inline float expf(float val) { return (float) exp((double) val); }
943 //
944 // A similar such definition exists in the MinGW-w64 math.h header file which
945 // when compiled with -O2 -ffast-math causes the generation of infinite loops
946 // where expf is called.
947 if (!Callee->isIntrinsic()) {
948 const Function *F = CI->getFunction();
949 StringRef FName = F->getName();
950 StringRef CalleeName = Callee->getName();
951 if ((FName.size() == (CalleeName.size() + 1)) &&
952 (FName.back() == 'f') &&
953 FName.startswith(CalleeName))
954 return nullptr;
955 }
956
Sanjay Patelaa231142015-12-31 21:52:31 +0000957 // Propagate fast-math flags from the existing call to the new call.
958 IRBuilder<>::FastMathFlagGuard Guard(B);
Sanjay Patela2528152016-01-12 18:03:37 +0000959 B.setFastMathFlags(CI->getFastMathFlags());
Chris Bienemanad070d02014-09-17 20:55:46 +0000960
961 // floor((double)floatval) -> (double)floorf(floatval)
Sanjay Patel848309d2014-10-23 21:52:45 +0000962 if (Callee->isIntrinsic()) {
Sanjay Patelaf674fb2015-12-14 17:24:23 +0000963 Module *M = CI->getModule();
Pete Cooper9e1d3352015-05-20 17:16:39 +0000964 Intrinsic::ID IID = Callee->getIntrinsicID();
Sanjay Patel848309d2014-10-23 21:52:45 +0000965 Function *F = Intrinsic::getDeclaration(M, IID, B.getFloatTy());
966 V = B.CreateCall(F, V);
967 } else {
968 // The call is a library call rather than an intrinsic.
Sanjay Pateld3112a52016-01-19 19:46:10 +0000969 V = emitUnaryFloatFnCall(V, Callee->getName(), B, Callee->getAttributes());
Sanjay Patel848309d2014-10-23 21:52:45 +0000970 }
971
Chris Bienemanad070d02014-09-17 20:55:46 +0000972 return B.CreateFPExt(V, B.getDoubleTy());
973}
Meador Inge193e0352012-11-13 04:16:17 +0000974
Matt Arsenault954a6242017-01-23 23:55:08 +0000975// Replace a libcall \p CI with a call to intrinsic \p IID
976static Value *replaceUnaryCall(CallInst *CI, IRBuilder<> &B, Intrinsic::ID IID) {
977 // Propagate fast-math flags from the existing call to the new call.
978 IRBuilder<>::FastMathFlagGuard Guard(B);
979 B.setFastMathFlags(CI->getFastMathFlags());
980
981 Module *M = CI->getModule();
982 Value *V = CI->getArgOperand(0);
983 Function *F = Intrinsic::getDeclaration(M, IID, CI->getType());
984 CallInst *NewCall = B.CreateCall(F, V);
985 NewCall->takeName(CI);
986 return NewCall;
987}
988
Sanjay Patel4e971da2016-01-21 18:01:57 +0000989/// Shrink double -> float for binary functions like 'fmin/fmax'.
990static Value *optimizeBinaryDoubleFP(CallInst *CI, IRBuilder<> &B) {
Chris Bienemanad070d02014-09-17 20:55:46 +0000991 Function *Callee = CI->getCalledFunction();
Ahmed Bougachad765a822016-04-27 19:04:35 +0000992 // We know this libcall has a valid prototype, but we don't know which.
993 if (!CI->getType()->isDoubleTy())
Craig Topperf40110f2014-04-25 05:29:35 +0000994 return nullptr;
Meador Inge193e0352012-11-13 04:16:17 +0000995
Chris Bienemanad070d02014-09-17 20:55:46 +0000996 // If this is something like 'fmin((double)floatval1, (double)floatval2)',
Matthias Braund34e4d22014-12-03 21:46:33 +0000997 // or fmin(1.0, (double)floatval), then we convert it to fminf.
998 Value *V1 = valueHasFloatPrecision(CI->getArgOperand(0));
999 if (V1 == nullptr)
1000 return nullptr;
1001 Value *V2 = valueHasFloatPrecision(CI->getArgOperand(1));
1002 if (V2 == nullptr)
Craig Topperf40110f2014-04-25 05:29:35 +00001003 return nullptr;
Chris Bienemanad070d02014-09-17 20:55:46 +00001004
Sanjay Patelbee05ca2015-12-31 23:40:59 +00001005 // Propagate fast-math flags from the existing call to the new call.
1006 IRBuilder<>::FastMathFlagGuard Guard(B);
Sanjay Patela2528152016-01-12 18:03:37 +00001007 B.setFastMathFlags(CI->getFastMathFlags());
Sanjay Patelbee05ca2015-12-31 23:40:59 +00001008
Chris Bienemanad070d02014-09-17 20:55:46 +00001009 // fmin((double)floatval1, (double)floatval2)
Matthias Braund34e4d22014-12-03 21:46:33 +00001010 // -> (double)fminf(floatval1, floatval2)
Sanjay Patel848309d2014-10-23 21:52:45 +00001011 // TODO: Handle intrinsics in the same way as in optimizeUnaryDoubleFP().
Sanjay Pateld3112a52016-01-19 19:46:10 +00001012 Value *V = emitBinaryFloatFnCall(V1, V2, Callee->getName(), B,
Matthias Braund34e4d22014-12-03 21:46:33 +00001013 Callee->getAttributes());
Chris Bienemanad070d02014-09-17 20:55:46 +00001014 return B.CreateFPExt(V, B.getDoubleTy());
1015}
1016
1017Value *LibCallSimplifier::optimizeCos(CallInst *CI, IRBuilder<> &B) {
1018 Function *Callee = CI->getCalledFunction();
1019 Value *Ret = nullptr;
Davide Italianoa3458772015-11-05 19:18:23 +00001020 StringRef Name = Callee->getName();
1021 if (UnsafeFPShrink && Name == "cos" && hasFloatVersion(Name))
Chris Bienemanad070d02014-09-17 20:55:46 +00001022 Ret = optimizeUnaryDoubleFP(CI, B, true);
Bob Wilsond8d92d92013-11-03 06:48:38 +00001023
Chris Bienemanad070d02014-09-17 20:55:46 +00001024 // cos(-x) -> cos(x)
1025 Value *Op1 = CI->getArgOperand(0);
1026 if (BinaryOperator::isFNeg(Op1)) {
1027 BinaryOperator *BinExpr = cast<BinaryOperator>(Op1);
1028 return B.CreateCall(Callee, BinExpr->getOperand(1), "cos");
1029 }
1030 return Ret;
1031}
Bob Wilsond8d92d92013-11-03 06:48:38 +00001032
Weiming Zhao82130722015-12-04 22:00:47 +00001033static Value *getPow(Value *InnerChain[33], unsigned Exp, IRBuilder<> &B) {
1034 // Multiplications calculated using Addition Chains.
1035 // Refer: http://wwwhomes.uni-bielefeld.de/achim/addition_chain.html
1036
1037 assert(Exp != 0 && "Incorrect exponent 0 not handled");
1038
1039 if (InnerChain[Exp])
1040 return InnerChain[Exp];
1041
1042 static const unsigned AddChain[33][2] = {
1043 {0, 0}, // Unused.
1044 {0, 0}, // Unused (base case = pow1).
1045 {1, 1}, // Unused (pre-computed).
1046 {1, 2}, {2, 2}, {2, 3}, {3, 3}, {2, 5}, {4, 4},
1047 {1, 8}, {5, 5}, {1, 10}, {6, 6}, {4, 9}, {7, 7},
1048 {3, 12}, {8, 8}, {8, 9}, {2, 16}, {1, 18}, {10, 10},
1049 {6, 15}, {11, 11}, {3, 20}, {12, 12}, {8, 17}, {13, 13},
1050 {3, 24}, {14, 14}, {4, 25}, {15, 15}, {3, 28}, {16, 16},
1051 };
1052
1053 InnerChain[Exp] = B.CreateFMul(getPow(InnerChain, AddChain[Exp][0], B),
1054 getPow(InnerChain, AddChain[Exp][1], B));
1055 return InnerChain[Exp];
1056}
1057
Chris Bienemanad070d02014-09-17 20:55:46 +00001058Value *LibCallSimplifier::optimizePow(CallInst *CI, IRBuilder<> &B) {
1059 Function *Callee = CI->getCalledFunction();
Chris Bienemanad070d02014-09-17 20:55:46 +00001060 Value *Ret = nullptr;
Davide Italianoa3458772015-11-05 19:18:23 +00001061 StringRef Name = Callee->getName();
1062 if (UnsafeFPShrink && Name == "pow" && hasFloatVersion(Name))
Chris Bienemanad070d02014-09-17 20:55:46 +00001063 Ret = optimizeUnaryDoubleFP(CI, B, true);
Bob Wilsond8d92d92013-11-03 06:48:38 +00001064
Chris Bienemanad070d02014-09-17 20:55:46 +00001065 Value *Op1 = CI->getArgOperand(0), *Op2 = CI->getArgOperand(1);
Davide Italiano27da1312016-08-07 20:27:03 +00001066
1067 // pow(1.0, x) -> 1.0
1068 if (match(Op1, m_SpecificFP(1.0)))
1069 return Op1;
1070 // pow(2.0, x) -> llvm.exp2(x)
1071 if (match(Op1, m_SpecificFP(2.0))) {
1072 Value *Exp2 = Intrinsic::getDeclaration(CI->getModule(), Intrinsic::exp2,
1073 CI->getType());
1074 return B.CreateCall(Exp2, Op2, "exp2");
1075 }
1076
1077 // There's no llvm.exp10 intrinsic yet, but, maybe, some day there will
1078 // be one.
Chris Bienemanad070d02014-09-17 20:55:46 +00001079 if (ConstantFP *Op1C = dyn_cast<ConstantFP>(Op1)) {
Chris Bienemanad070d02014-09-17 20:55:46 +00001080 // pow(10.0, x) -> exp10(x)
1081 if (Op1C->isExactlyValue(10.0) &&
David L. Jonesd21529f2017-01-23 23:16:46 +00001082 hasUnaryFloatFn(TLI, Op1->getType(), LibFunc_exp10, LibFunc_exp10f,
1083 LibFunc_exp10l))
1084 return emitUnaryFloatFnCall(Op2, TLI->getName(LibFunc_exp10), B,
Chris Bienemanad070d02014-09-17 20:55:46 +00001085 Callee->getAttributes());
Bob Wilsond8d92d92013-11-03 06:48:38 +00001086 }
1087
Sanjay Patel6002e782016-01-12 17:30:37 +00001088 // pow(exp(x), y) -> exp(x * y)
Davide Italianoc8a79132015-11-03 20:32:23 +00001089 // pow(exp2(x), y) -> exp2(x * y)
Sanjay Patel6002e782016-01-12 17:30:37 +00001090 // We enable these only with fast-math. Besides rounding differences, the
1091 // transformation changes overflow and underflow behavior quite dramatically.
Davide Italianoc8a79132015-11-03 20:32:23 +00001092 // Example: x = 1000, y = 0.001.
1093 // pow(exp(x), y) = pow(inf, 0.001) = inf, whereas exp(x*y) = exp(1).
Sanjay Patel6002e782016-01-12 17:30:37 +00001094 auto *OpC = dyn_cast<CallInst>(Op1);
1095 if (OpC && OpC->hasUnsafeAlgebra() && CI->hasUnsafeAlgebra()) {
David L. Jonesd21529f2017-01-23 23:16:46 +00001096 LibFunc Func;
Sanjay Patel6002e782016-01-12 17:30:37 +00001097 Function *OpCCallee = OpC->getCalledFunction();
1098 if (OpCCallee && TLI->getLibFunc(OpCCallee->getName(), Func) &&
David L. Jonesd21529f2017-01-23 23:16:46 +00001099 TLI->has(Func) && (Func == LibFunc_exp || Func == LibFunc_exp2)) {
Davide Italianoc8a79132015-11-03 20:32:23 +00001100 IRBuilder<>::FastMathFlagGuard Guard(B);
Sanjay Patela2528152016-01-12 18:03:37 +00001101 B.setFastMathFlags(CI->getFastMathFlags());
Sanjay Patel6002e782016-01-12 17:30:37 +00001102 Value *FMul = B.CreateFMul(OpC->getArgOperand(0), Op2, "mul");
Sanjay Pateld3112a52016-01-19 19:46:10 +00001103 return emitUnaryFloatFnCall(FMul, OpCCallee->getName(), B,
Sanjay Patel6002e782016-01-12 17:30:37 +00001104 OpCCallee->getAttributes());
Davide Italianoc8a79132015-11-03 20:32:23 +00001105 }
1106 }
1107
Chris Bienemanad070d02014-09-17 20:55:46 +00001108 ConstantFP *Op2C = dyn_cast<ConstantFP>(Op2);
1109 if (!Op2C)
1110 return Ret;
1111
1112 if (Op2C->getValueAPF().isZero()) // pow(x, 0.0) -> 1.0
1113 return ConstantFP::get(CI->getType(), 1.0);
1114
Davide Italiano472684e2017-01-09 21:55:23 +00001115 if (Op2C->isExactlyValue(-0.5) &&
David L. Jonesd21529f2017-01-23 23:16:46 +00001116 hasUnaryFloatFn(TLI, Op2->getType(), LibFunc_sqrt, LibFunc_sqrtf,
1117 LibFunc_sqrtl)) {
Davide Italiano472684e2017-01-09 21:55:23 +00001118 // If -ffast-math:
1119 // pow(x, -0.5) -> 1.0 / sqrt(x)
1120 if (CI->hasUnsafeAlgebra()) {
1121 IRBuilder<>::FastMathFlagGuard Guard(B);
1122 B.setFastMathFlags(CI->getFastMathFlags());
1123
Justin Lebarcb9b41d2017-01-27 00:58:03 +00001124 // TODO: If the pow call is an intrinsic, we should lower to the sqrt
1125 // intrinsic, so we match errno semantics. We also should check that the
1126 // target can in fact lower the sqrt intrinsic -- we currently have no way
1127 // to ask this question other than asking whether the target has a sqrt
1128 // libcall, which is a sufficient but not necessary condition.
David L. Jonesd21529f2017-01-23 23:16:46 +00001129 Value *Sqrt = emitUnaryFloatFnCall(Op1, TLI->getName(LibFunc_sqrt), B,
Davide Italiano472684e2017-01-09 21:55:23 +00001130 Callee->getAttributes());
1131
1132 return B.CreateFDiv(ConstantFP::get(CI->getType(), 1.0), Sqrt, "sqrtrecip");
1133 }
1134 }
1135
Chris Bienemanad070d02014-09-17 20:55:46 +00001136 if (Op2C->isExactlyValue(0.5) &&
David L. Jonesd21529f2017-01-23 23:16:46 +00001137 hasUnaryFloatFn(TLI, Op2->getType(), LibFunc_sqrt, LibFunc_sqrtf,
1138 LibFunc_sqrtl)) {
Davide Italianoc5cedd12015-11-18 23:21:32 +00001139
1140 // In -ffast-math, pow(x, 0.5) -> sqrt(x).
Sanjay Patel53ba88d2016-01-12 19:06:35 +00001141 if (CI->hasUnsafeAlgebra()) {
1142 IRBuilder<>::FastMathFlagGuard Guard(B);
1143 B.setFastMathFlags(CI->getFastMathFlags());
Davide Italiano873219c2016-08-10 06:33:32 +00001144
Justin Lebarcb9b41d2017-01-27 00:58:03 +00001145 // TODO: As above, we should lower to the sqrt intrinsic if the pow is an
1146 // intrinsic, to match errno semantics.
David L. Jonesd21529f2017-01-23 23:16:46 +00001147 return emitUnaryFloatFnCall(Op1, TLI->getName(LibFunc_sqrt), B,
Davide Italiano873219c2016-08-10 06:33:32 +00001148 Callee->getAttributes());
Sanjay Patel53ba88d2016-01-12 19:06:35 +00001149 }
Davide Italianoc5cedd12015-11-18 23:21:32 +00001150
Chris Bienemanad070d02014-09-17 20:55:46 +00001151 // Expand pow(x, 0.5) to (x == -infinity ? +infinity : fabs(sqrt(x))).
1152 // This is faster than calling pow, and still handles negative zero
1153 // and negative infinity correctly.
Chris Bienemanad070d02014-09-17 20:55:46 +00001154 // TODO: In finite-only mode, this could be just fabs(sqrt(x)).
1155 Value *Inf = ConstantFP::getInfinity(CI->getType());
1156 Value *NegInf = ConstantFP::getInfinity(CI->getType(), true);
Justin Lebarcb9b41d2017-01-27 00:58:03 +00001157
1158 // TODO: As above, we should lower to the sqrt intrinsic if the pow is an
1159 // intrinsic, to match errno semantics.
Sanjay Pateld3112a52016-01-19 19:46:10 +00001160 Value *Sqrt = emitUnaryFloatFnCall(Op1, "sqrt", B, Callee->getAttributes());
Matt Arsenaultb948b4d2017-01-17 00:30:31 +00001161
1162 Module *M = Callee->getParent();
1163 Function *FabsF = Intrinsic::getDeclaration(M, Intrinsic::fabs,
1164 CI->getType());
1165 Value *FAbs = B.CreateCall(FabsF, Sqrt);
1166
Chris Bienemanad070d02014-09-17 20:55:46 +00001167 Value *FCmp = B.CreateFCmpOEQ(Op1, NegInf);
1168 Value *Sel = B.CreateSelect(FCmp, Inf, FAbs);
1169 return Sel;
Bob Wilsond8d92d92013-11-03 06:48:38 +00001170 }
1171
Chris Bienemanad070d02014-09-17 20:55:46 +00001172 if (Op2C->isExactlyValue(1.0)) // pow(x, 1.0) -> x
1173 return Op1;
1174 if (Op2C->isExactlyValue(2.0)) // pow(x, 2.0) -> x*x
1175 return B.CreateFMul(Op1, Op1, "pow2");
1176 if (Op2C->isExactlyValue(-1.0)) // pow(x, -1.0) -> 1.0/x
1177 return B.CreateFDiv(ConstantFP::get(CI->getType(), 1.0), Op1, "powrecip");
Weiming Zhao82130722015-12-04 22:00:47 +00001178
1179 // In -ffast-math, generate repeated fmul instead of generating pow(x, n).
Sanjay Patel81a63cd2016-01-19 18:15:12 +00001180 if (CI->hasUnsafeAlgebra()) {
Weiming Zhao82130722015-12-04 22:00:47 +00001181 APFloat V = abs(Op2C->getValueAPF());
1182 // We limit to a max of 7 fmul(s). Thus max exponent is 32.
1183 // This transformation applies to integer exponents only.
1184 if (V.compare(APFloat(V.getSemantics(), 32.0)) == APFloat::cmpGreaterThan ||
1185 !V.isInteger())
1186 return nullptr;
1187
Davide Italianof8711f02017-01-10 18:02:05 +00001188 // Propagate fast math flags.
1189 IRBuilder<>::FastMathFlagGuard Guard(B);
1190 B.setFastMathFlags(CI->getFastMathFlags());
1191
Weiming Zhao82130722015-12-04 22:00:47 +00001192 // We will memoize intermediate products of the Addition Chain.
1193 Value *InnerChain[33] = {nullptr};
1194 InnerChain[1] = Op1;
1195 InnerChain[2] = B.CreateFMul(Op1, Op1);
1196
1197 // We cannot readily convert a non-double type (like float) to a double.
1198 // So we first convert V to something which could be converted to double.
1199 bool ignored;
Stephan Bergmann17c7f702016-12-14 11:57:17 +00001200 V.convert(APFloat::IEEEdouble(), APFloat::rmTowardZero, &ignored);
Sanjay Patel81a63cd2016-01-19 18:15:12 +00001201
Weiming Zhao82130722015-12-04 22:00:47 +00001202 Value *FMul = getPow(InnerChain, V.convertToDouble(), B);
1203 // For negative exponents simply compute the reciprocal.
1204 if (Op2C->isNegative())
1205 FMul = B.CreateFDiv(ConstantFP::get(CI->getType(), 1.0), FMul);
1206 return FMul;
1207 }
1208
Chris Bienemanad070d02014-09-17 20:55:46 +00001209 return nullptr;
1210}
Bob Wilsond8d92d92013-11-03 06:48:38 +00001211
Chris Bienemanad070d02014-09-17 20:55:46 +00001212Value *LibCallSimplifier::optimizeExp2(CallInst *CI, IRBuilder<> &B) {
1213 Function *Callee = CI->getCalledFunction();
Chris Bienemanad070d02014-09-17 20:55:46 +00001214 Value *Ret = nullptr;
Davide Italianoa3458772015-11-05 19:18:23 +00001215 StringRef Name = Callee->getName();
1216 if (UnsafeFPShrink && Name == "exp2" && hasFloatVersion(Name))
Chris Bienemanad070d02014-09-17 20:55:46 +00001217 Ret = optimizeUnaryDoubleFP(CI, B, true);
Bob Wilsond8d92d92013-11-03 06:48:38 +00001218
Chris Bienemanad070d02014-09-17 20:55:46 +00001219 Value *Op = CI->getArgOperand(0);
1220 // Turn exp2(sitofp(x)) -> ldexp(1.0, sext(x)) if sizeof(x) <= 32
1221 // Turn exp2(uitofp(x)) -> ldexp(1.0, zext(x)) if sizeof(x) < 32
David L. Jonesd21529f2017-01-23 23:16:46 +00001222 LibFunc LdExp = LibFunc_ldexpl;
Chris Bienemanad070d02014-09-17 20:55:46 +00001223 if (Op->getType()->isFloatTy())
David L. Jonesd21529f2017-01-23 23:16:46 +00001224 LdExp = LibFunc_ldexpf;
Chris Bienemanad070d02014-09-17 20:55:46 +00001225 else if (Op->getType()->isDoubleTy())
David L. Jonesd21529f2017-01-23 23:16:46 +00001226 LdExp = LibFunc_ldexp;
Chris Bienemanad070d02014-09-17 20:55:46 +00001227
1228 if (TLI->has(LdExp)) {
1229 Value *LdExpArg = nullptr;
1230 if (SIToFPInst *OpC = dyn_cast<SIToFPInst>(Op)) {
1231 if (OpC->getOperand(0)->getType()->getPrimitiveSizeInBits() <= 32)
1232 LdExpArg = B.CreateSExt(OpC->getOperand(0), B.getInt32Ty());
1233 } else if (UIToFPInst *OpC = dyn_cast<UIToFPInst>(Op)) {
1234 if (OpC->getOperand(0)->getType()->getPrimitiveSizeInBits() < 32)
1235 LdExpArg = B.CreateZExt(OpC->getOperand(0), B.getInt32Ty());
1236 }
1237
1238 if (LdExpArg) {
1239 Constant *One = ConstantFP::get(CI->getContext(), APFloat(1.0f));
1240 if (!Op->getType()->isFloatTy())
1241 One = ConstantExpr::getFPExtend(One, Op->getType());
1242
Sanjay Patel0e603fc2016-01-21 22:31:18 +00001243 Module *M = CI->getModule();
Mehdi Aminidb11fdf2017-04-06 20:23:57 +00001244 Value *NewCallee =
1245 M->getOrInsertFunction(TLI->getName(LdExp), Op->getType(),
Serge Guelton59a2d7b2017-04-11 15:01:18 +00001246 Op->getType(), B.getInt32Ty());
Sanjay Patel042aed902016-01-21 22:41:16 +00001247 CallInst *CI = B.CreateCall(NewCallee, {One, LdExpArg});
Chris Bienemanad070d02014-09-17 20:55:46 +00001248 if (const Function *F = dyn_cast<Function>(Callee->stripPointerCasts()))
1249 CI->setCallingConv(F->getCallingConv());
1250
1251 return CI;
1252 }
1253 }
1254 return Ret;
1255}
1256
Sanjay Patel57fd1dc2015-08-16 20:18:19 +00001257Value *LibCallSimplifier::optimizeFMinFMax(CallInst *CI, IRBuilder<> &B) {
Sanjay Patel9beec212016-01-21 22:58:01 +00001258 Function *Callee = CI->getCalledFunction();
Sanjay Patel57fd1dc2015-08-16 20:18:19 +00001259 // If we can shrink the call to a float function rather than a double
1260 // function, do that first.
Davide Italianoa3458772015-11-05 19:18:23 +00001261 StringRef Name = Callee->getName();
Sanjay Patelc7ddb7f2016-01-06 00:32:15 +00001262 if ((Name == "fmin" || Name == "fmax") && hasFloatVersion(Name))
1263 if (Value *Ret = optimizeBinaryDoubleFP(CI, B))
Sanjay Patel57fd1dc2015-08-16 20:18:19 +00001264 return Ret;
Sanjay Patel57fd1dc2015-08-16 20:18:19 +00001265
Benjamin Kramerbb70d752015-08-16 21:16:37 +00001266 IRBuilder<>::FastMathFlagGuard Guard(B);
Sanjay Patel57fd1dc2015-08-16 20:18:19 +00001267 FastMathFlags FMF;
Sanjay Patel29095ea2016-01-05 20:46:19 +00001268 if (CI->hasUnsafeAlgebra()) {
Sanjay Patel57fd1dc2015-08-16 20:18:19 +00001269 // Unsafe algebra sets all fast-math-flags to true.
1270 FMF.setUnsafeAlgebra();
1271 } else {
1272 // At a minimum, no-nans-fp-math must be true.
Sanjay Patel29095ea2016-01-05 20:46:19 +00001273 if (!CI->hasNoNaNs())
Sanjay Patel57fd1dc2015-08-16 20:18:19 +00001274 return nullptr;
1275 // No-signed-zeros is implied by the definitions of fmax/fmin themselves:
1276 // "Ideally, fmax would be sensitive to the sign of zero, for example
NAKAMURA Takumi0d725392015-09-07 00:26:54 +00001277 // fmax(-0. 0, +0. 0) would return +0; however, implementation in software
Sanjay Patel57fd1dc2015-08-16 20:18:19 +00001278 // might be impractical."
1279 FMF.setNoSignedZeros();
1280 FMF.setNoNaNs();
1281 }
Sanjay Patela2528152016-01-12 18:03:37 +00001282 B.setFastMathFlags(FMF);
Sanjay Patel57fd1dc2015-08-16 20:18:19 +00001283
1284 // We have a relaxed floating-point environment. We can ignore NaN-handling
1285 // and transform to a compare and select. We do not have to consider errno or
1286 // exceptions, because fmin/fmax do not have those.
1287 Value *Op0 = CI->getArgOperand(0);
1288 Value *Op1 = CI->getArgOperand(1);
1289 Value *Cmp = Callee->getName().startswith("fmin") ?
1290 B.CreateFCmpOLT(Op0, Op1) : B.CreateFCmpOGT(Op0, Op1);
1291 return B.CreateSelect(Cmp, Op0, Op1);
1292}
1293
Davide Italianob8b71332015-11-29 20:58:04 +00001294Value *LibCallSimplifier::optimizeLog(CallInst *CI, IRBuilder<> &B) {
1295 Function *Callee = CI->getCalledFunction();
1296 Value *Ret = nullptr;
1297 StringRef Name = Callee->getName();
1298 if (UnsafeFPShrink && hasFloatVersion(Name))
1299 Ret = optimizeUnaryDoubleFP(CI, B, true);
Davide Italianob8b71332015-11-29 20:58:04 +00001300
Sanjay Patele896ede2016-01-11 23:31:48 +00001301 if (!CI->hasUnsafeAlgebra())
Davide Italianob8b71332015-11-29 20:58:04 +00001302 return Ret;
1303 Value *Op1 = CI->getArgOperand(0);
1304 auto *OpC = dyn_cast<CallInst>(Op1);
Sanjay Patele896ede2016-01-11 23:31:48 +00001305
1306 // The earlier call must also be unsafe in order to do these transforms.
1307 if (!OpC || !OpC->hasUnsafeAlgebra())
Davide Italianob8b71332015-11-29 20:58:04 +00001308 return Ret;
1309
1310 // log(pow(x,y)) -> y*log(x)
1311 // This is only applicable to log, log2, log10.
1312 if (Name != "log" && Name != "log2" && Name != "log10")
1313 return Ret;
1314
1315 IRBuilder<>::FastMathFlagGuard Guard(B);
1316 FastMathFlags FMF;
1317 FMF.setUnsafeAlgebra();
Sanjay Patela2528152016-01-12 18:03:37 +00001318 B.setFastMathFlags(FMF);
Davide Italianob8b71332015-11-29 20:58:04 +00001319
David L. Jonesd21529f2017-01-23 23:16:46 +00001320 LibFunc Func;
Davide Italianob8b71332015-11-29 20:58:04 +00001321 Function *F = OpC->getCalledFunction();
Davide Italiano0b14f292015-11-29 21:58:56 +00001322 if (F && ((TLI->getLibFunc(F->getName(), Func) && TLI->has(Func) &&
David L. Jonesd21529f2017-01-23 23:16:46 +00001323 Func == LibFunc_pow) || F->getIntrinsicID() == Intrinsic::pow))
Davide Italianob8b71332015-11-29 20:58:04 +00001324 return B.CreateFMul(OpC->getArgOperand(1),
Sanjay Pateld3112a52016-01-19 19:46:10 +00001325 emitUnaryFloatFnCall(OpC->getOperand(0), Callee->getName(), B,
Davide Italianob8b71332015-11-29 20:58:04 +00001326 Callee->getAttributes()), "mul");
Davide Italiano1aeed6a2015-11-30 19:36:35 +00001327
1328 // log(exp2(y)) -> y*log(2)
1329 if (F && Name == "log" && TLI->getLibFunc(F->getName(), Func) &&
David L. Jonesd21529f2017-01-23 23:16:46 +00001330 TLI->has(Func) && Func == LibFunc_exp2)
Davide Italiano1aeed6a2015-11-30 19:36:35 +00001331 return B.CreateFMul(
1332 OpC->getArgOperand(0),
Sanjay Pateld3112a52016-01-19 19:46:10 +00001333 emitUnaryFloatFnCall(ConstantFP::get(CI->getType(), 2.0),
Davide Italiano1aeed6a2015-11-30 19:36:35 +00001334 Callee->getName(), B, Callee->getAttributes()),
1335 "logmul");
Davide Italianob8b71332015-11-29 20:58:04 +00001336 return Ret;
1337}
1338
Sanjay Patelc699a612014-10-16 18:48:17 +00001339Value *LibCallSimplifier::optimizeSqrt(CallInst *CI, IRBuilder<> &B) {
1340 Function *Callee = CI->getCalledFunction();
Sanjay Patelc699a612014-10-16 18:48:17 +00001341 Value *Ret = nullptr;
Justin Lebarcb9b41d2017-01-27 00:58:03 +00001342 // TODO: Once we have a way (other than checking for the existince of the
1343 // libcall) to tell whether our target can lower @llvm.sqrt, relax the
1344 // condition below.
David L. Jonesd21529f2017-01-23 23:16:46 +00001345 if (TLI->has(LibFunc_sqrtf) && (Callee->getName() == "sqrt" ||
Justin Lebarcb9b41d2017-01-27 00:58:03 +00001346 Callee->getIntrinsicID() == Intrinsic::sqrt))
Sanjay Patelc699a612014-10-16 18:48:17 +00001347 Ret = optimizeUnaryDoubleFP(CI, B, true);
Sanjay Patel683f2972016-01-11 22:34:19 +00001348
1349 if (!CI->hasUnsafeAlgebra())
Davide Italianoa904e522015-10-29 02:58:44 +00001350 return Ret;
Sanjay Patelc699a612014-10-16 18:48:17 +00001351
Sanjay Patelc2d64612016-01-06 20:52:21 +00001352 Instruction *I = dyn_cast<Instruction>(CI->getArgOperand(0));
1353 if (!I || I->getOpcode() != Instruction::FMul || !I->hasUnsafeAlgebra())
1354 return Ret;
1355
1356 // We're looking for a repeated factor in a multiplication tree,
1357 // so we can do this fold: sqrt(x * x) -> fabs(x);
Sanjay Patel683f2972016-01-11 22:34:19 +00001358 // or this fold: sqrt((x * x) * y) -> fabs(x) * sqrt(y).
Sanjay Patelc2d64612016-01-06 20:52:21 +00001359 Value *Op0 = I->getOperand(0);
1360 Value *Op1 = I->getOperand(1);
1361 Value *RepeatOp = nullptr;
1362 Value *OtherOp = nullptr;
1363 if (Op0 == Op1) {
1364 // Simple match: the operands of the multiply are identical.
1365 RepeatOp = Op0;
1366 } else {
1367 // Look for a more complicated pattern: one of the operands is itself
1368 // a multiply, so search for a common factor in that multiply.
1369 // Note: We don't bother looking any deeper than this first level or for
1370 // variations of this pattern because instcombine's visitFMUL and/or the
1371 // reassociation pass should give us this form.
1372 Value *OtherMul0, *OtherMul1;
1373 if (match(Op0, m_FMul(m_Value(OtherMul0), m_Value(OtherMul1)))) {
1374 // Pattern: sqrt((x * y) * z)
Sanjay Patel6c1ddbb2016-01-11 22:50:36 +00001375 if (OtherMul0 == OtherMul1 &&
1376 cast<Instruction>(Op0)->hasUnsafeAlgebra()) {
Sanjay Patelc2d64612016-01-06 20:52:21 +00001377 // Matched: sqrt((x * x) * z)
1378 RepeatOp = OtherMul0;
1379 OtherOp = Op1;
Sanjay Patelc699a612014-10-16 18:48:17 +00001380 }
1381 }
1382 }
Sanjay Patelc2d64612016-01-06 20:52:21 +00001383 if (!RepeatOp)
1384 return Ret;
1385
1386 // Fast math flags for any created instructions should match the sqrt
1387 // and multiply.
Sanjay Patelc2d64612016-01-06 20:52:21 +00001388 IRBuilder<>::FastMathFlagGuard Guard(B);
Sanjay Patela2528152016-01-12 18:03:37 +00001389 B.setFastMathFlags(I->getFastMathFlags());
Sanjay Patel9f67dad2016-01-11 22:35:39 +00001390
Sanjay Patelc2d64612016-01-06 20:52:21 +00001391 // If we found a repeated factor, hoist it out of the square root and
1392 // replace it with the fabs of that factor.
1393 Module *M = Callee->getParent();
1394 Type *ArgType = I->getType();
1395 Value *Fabs = Intrinsic::getDeclaration(M, Intrinsic::fabs, ArgType);
1396 Value *FabsCall = B.CreateCall(Fabs, RepeatOp, "fabs");
1397 if (OtherOp) {
1398 // If we found a non-repeated factor, we still need to get its square
1399 // root. We then multiply that by the value that was simplified out
1400 // of the square root calculation.
1401 Value *Sqrt = Intrinsic::getDeclaration(M, Intrinsic::sqrt, ArgType);
1402 Value *SqrtCall = B.CreateCall(Sqrt, OtherOp, "sqrt");
1403 return B.CreateFMul(FabsCall, SqrtCall);
1404 }
1405 return FabsCall;
Sanjay Patelc699a612014-10-16 18:48:17 +00001406}
1407
Sanjay Patelcddcd722016-01-06 19:23:35 +00001408// TODO: Generalize to handle any trig function and its inverse.
Davide Italiano51507d22015-11-04 23:36:56 +00001409Value *LibCallSimplifier::optimizeTan(CallInst *CI, IRBuilder<> &B) {
1410 Function *Callee = CI->getCalledFunction();
1411 Value *Ret = nullptr;
Davide Italianoa3458772015-11-05 19:18:23 +00001412 StringRef Name = Callee->getName();
1413 if (UnsafeFPShrink && Name == "tan" && hasFloatVersion(Name))
Davide Italiano51507d22015-11-04 23:36:56 +00001414 Ret = optimizeUnaryDoubleFP(CI, B, true);
Davide Italiano51507d22015-11-04 23:36:56 +00001415
Davide Italiano51507d22015-11-04 23:36:56 +00001416 Value *Op1 = CI->getArgOperand(0);
1417 auto *OpC = dyn_cast<CallInst>(Op1);
1418 if (!OpC)
1419 return Ret;
1420
Sanjay Patelcddcd722016-01-06 19:23:35 +00001421 // Both calls must allow unsafe optimizations in order to remove them.
1422 if (!CI->hasUnsafeAlgebra() || !OpC->hasUnsafeAlgebra())
1423 return Ret;
1424
Davide Italiano51507d22015-11-04 23:36:56 +00001425 // tan(atan(x)) -> x
1426 // tanf(atanf(x)) -> x
1427 // tanl(atanl(x)) -> x
David L. Jonesd21529f2017-01-23 23:16:46 +00001428 LibFunc Func;
Davide Italiano51507d22015-11-04 23:36:56 +00001429 Function *F = OpC->getCalledFunction();
Benjamin Kramerfb419e72015-11-26 09:51:17 +00001430 if (F && TLI->getLibFunc(F->getName(), Func) && TLI->has(Func) &&
David L. Jonesd21529f2017-01-23 23:16:46 +00001431 ((Func == LibFunc_atan && Callee->getName() == "tan") ||
1432 (Func == LibFunc_atanf && Callee->getName() == "tanf") ||
1433 (Func == LibFunc_atanl && Callee->getName() == "tanl")))
Davide Italiano51507d22015-11-04 23:36:56 +00001434 Ret = OpC->getArgOperand(0);
1435 return Ret;
1436}
1437
Sanjay Patel57747212016-01-21 23:38:43 +00001438static bool isTrigLibCall(CallInst *CI) {
Sanjay Patel57747212016-01-21 23:38:43 +00001439 // We can only hope to do anything useful if we can ignore things like errno
1440 // and floating-point exceptions.
Ahmed Bougachad765a822016-04-27 19:04:35 +00001441 // We already checked the prototype.
1442 return CI->hasFnAttr(Attribute::NoUnwind) &&
1443 CI->hasFnAttr(Attribute::ReadNone);
Sanjay Patel57747212016-01-21 23:38:43 +00001444}
1445
Chris Bienemanad070d02014-09-17 20:55:46 +00001446static void insertSinCosCall(IRBuilder<> &B, Function *OrigCallee, Value *Arg,
1447 bool UseFloat, Value *&Sin, Value *&Cos,
Sanjay Patel57747212016-01-21 23:38:43 +00001448 Value *&SinCos) {
1449 Type *ArgTy = Arg->getType();
1450 Type *ResTy;
1451 StringRef Name;
1452
1453 Triple T(OrigCallee->getParent()->getTargetTriple());
1454 if (UseFloat) {
1455 Name = "__sincospif_stret";
1456
1457 assert(T.getArch() != Triple::x86 && "x86 messy and unsupported for now");
1458 // x86_64 can't use {float, float} since that would be returned in both
1459 // xmm0 and xmm1, which isn't what a real struct would do.
1460 ResTy = T.getArch() == Triple::x86_64
Serge Gueltone38003f2017-05-09 19:31:13 +00001461 ? static_cast<Type *>(VectorType::get(ArgTy, 2))
1462 : static_cast<Type *>(StructType::get(ArgTy, ArgTy));
Sanjay Patel57747212016-01-21 23:38:43 +00001463 } else {
1464 Name = "__sincospi_stret";
Serge Gueltone38003f2017-05-09 19:31:13 +00001465 ResTy = StructType::get(ArgTy, ArgTy);
Sanjay Patel57747212016-01-21 23:38:43 +00001466 }
1467
1468 Module *M = OrigCallee->getParent();
Mehdi Aminidb11fdf2017-04-06 20:23:57 +00001469 Value *Callee = M->getOrInsertFunction(Name, OrigCallee->getAttributes(),
Serge Guelton59a2d7b2017-04-11 15:01:18 +00001470 ResTy, ArgTy);
Sanjay Patel57747212016-01-21 23:38:43 +00001471
1472 if (Instruction *ArgInst = dyn_cast<Instruction>(Arg)) {
1473 // If the argument is an instruction, it must dominate all uses so put our
1474 // sincos call there.
1475 B.SetInsertPoint(ArgInst->getParent(), ++ArgInst->getIterator());
1476 } else {
1477 // Otherwise (e.g. for a constant) the beginning of the function is as
1478 // good a place as any.
1479 BasicBlock &EntryBB = B.GetInsertBlock()->getParent()->getEntryBlock();
1480 B.SetInsertPoint(&EntryBB, EntryBB.begin());
1481 }
1482
1483 SinCos = B.CreateCall(Callee, Arg, "sincospi");
1484
1485 if (SinCos->getType()->isStructTy()) {
1486 Sin = B.CreateExtractValue(SinCos, 0, "sinpi");
1487 Cos = B.CreateExtractValue(SinCos, 1, "cospi");
1488 } else {
1489 Sin = B.CreateExtractElement(SinCos, ConstantInt::get(B.getInt32Ty(), 0),
1490 "sinpi");
1491 Cos = B.CreateExtractElement(SinCos, ConstantInt::get(B.getInt32Ty(), 1),
1492 "cospi");
1493 }
1494}
Chris Bienemanad070d02014-09-17 20:55:46 +00001495
1496Value *LibCallSimplifier::optimizeSinCosPi(CallInst *CI, IRBuilder<> &B) {
Chris Bienemanad070d02014-09-17 20:55:46 +00001497 // Make sure the prototype is as expected, otherwise the rest of the
1498 // function is probably invalid and likely to abort.
1499 if (!isTrigLibCall(CI))
1500 return nullptr;
1501
1502 Value *Arg = CI->getArgOperand(0);
1503 SmallVector<CallInst *, 1> SinCalls;
1504 SmallVector<CallInst *, 1> CosCalls;
1505 SmallVector<CallInst *, 1> SinCosCalls;
1506
1507 bool IsFloat = Arg->getType()->isFloatTy();
1508
1509 // Look for all compatible sinpi, cospi and sincospi calls with the same
1510 // argument. If there are enough (in some sense) we can make the
1511 // substitution.
David Majnemerabae6b52016-03-19 04:53:02 +00001512 Function *F = CI->getFunction();
Chris Bienemanad070d02014-09-17 20:55:46 +00001513 for (User *U : Arg->users())
David Majnemerabae6b52016-03-19 04:53:02 +00001514 classifyArgUse(U, F, IsFloat, SinCalls, CosCalls, SinCosCalls);
Chris Bienemanad070d02014-09-17 20:55:46 +00001515
1516 // It's only worthwhile if both sinpi and cospi are actually used.
1517 if (SinCosCalls.empty() && (SinCalls.empty() || CosCalls.empty()))
1518 return nullptr;
1519
1520 Value *Sin, *Cos, *SinCos;
1521 insertSinCosCall(B, CI->getCalledFunction(), Arg, IsFloat, Sin, Cos, SinCos);
1522
Davide Italianof024a562016-12-16 02:28:38 +00001523 auto replaceTrigInsts = [this](SmallVectorImpl<CallInst *> &Calls,
1524 Value *Res) {
1525 for (CallInst *C : Calls)
1526 replaceAllUsesWith(C, Res);
1527 };
1528
Chris Bienemanad070d02014-09-17 20:55:46 +00001529 replaceTrigInsts(SinCalls, Sin);
1530 replaceTrigInsts(CosCalls, Cos);
1531 replaceTrigInsts(SinCosCalls, SinCos);
1532
1533 return nullptr;
1534}
1535
David Majnemerabae6b52016-03-19 04:53:02 +00001536void LibCallSimplifier::classifyArgUse(
1537 Value *Val, Function *F, bool IsFloat,
1538 SmallVectorImpl<CallInst *> &SinCalls,
1539 SmallVectorImpl<CallInst *> &CosCalls,
1540 SmallVectorImpl<CallInst *> &SinCosCalls) {
Chris Bienemanad070d02014-09-17 20:55:46 +00001541 CallInst *CI = dyn_cast<CallInst>(Val);
1542
1543 if (!CI)
1544 return;
1545
David Majnemerabae6b52016-03-19 04:53:02 +00001546 // Don't consider calls in other functions.
1547 if (CI->getFunction() != F)
1548 return;
1549
Chris Bienemanad070d02014-09-17 20:55:46 +00001550 Function *Callee = CI->getCalledFunction();
David L. Jonesd21529f2017-01-23 23:16:46 +00001551 LibFunc Func;
Ahmed Bougachad765a822016-04-27 19:04:35 +00001552 if (!Callee || !TLI->getLibFunc(*Callee, Func) || !TLI->has(Func) ||
Benjamin Kramer89766e52015-11-28 21:43:12 +00001553 !isTrigLibCall(CI))
Chris Bienemanad070d02014-09-17 20:55:46 +00001554 return;
1555
1556 if (IsFloat) {
David L. Jonesd21529f2017-01-23 23:16:46 +00001557 if (Func == LibFunc_sinpif)
Chris Bienemanad070d02014-09-17 20:55:46 +00001558 SinCalls.push_back(CI);
David L. Jonesd21529f2017-01-23 23:16:46 +00001559 else if (Func == LibFunc_cospif)
Chris Bienemanad070d02014-09-17 20:55:46 +00001560 CosCalls.push_back(CI);
David L. Jonesd21529f2017-01-23 23:16:46 +00001561 else if (Func == LibFunc_sincospif_stret)
Chris Bienemanad070d02014-09-17 20:55:46 +00001562 SinCosCalls.push_back(CI);
1563 } else {
David L. Jonesd21529f2017-01-23 23:16:46 +00001564 if (Func == LibFunc_sinpi)
Chris Bienemanad070d02014-09-17 20:55:46 +00001565 SinCalls.push_back(CI);
David L. Jonesd21529f2017-01-23 23:16:46 +00001566 else if (Func == LibFunc_cospi)
Chris Bienemanad070d02014-09-17 20:55:46 +00001567 CosCalls.push_back(CI);
David L. Jonesd21529f2017-01-23 23:16:46 +00001568 else if (Func == LibFunc_sincospi_stret)
Chris Bienemanad070d02014-09-17 20:55:46 +00001569 SinCosCalls.push_back(CI);
1570 }
1571}
1572
Meador Inge7415f842012-11-25 20:45:27 +00001573//===----------------------------------------------------------------------===//
1574// Integer Library Call Optimizations
1575//===----------------------------------------------------------------------===//
1576
Chris Bienemanad070d02014-09-17 20:55:46 +00001577Value *LibCallSimplifier::optimizeFFS(CallInst *CI, IRBuilder<> &B) {
Chris Bienemanad070d02014-09-17 20:55:46 +00001578 // ffs(x) -> x != 0 ? (i32)llvm.cttz(x)+1 : 0
Davide Italiano890e8502016-12-15 23:11:00 +00001579 Value *Op = CI->getArgOperand(0);
Chris Bienemanad070d02014-09-17 20:55:46 +00001580 Type *ArgType = Op->getType();
Davide Italiano890e8502016-12-15 23:11:00 +00001581 Value *F = Intrinsic::getDeclaration(CI->getCalledFunction()->getParent(),
1582 Intrinsic::cttz, ArgType);
Davide Italianoa1953862015-08-13 20:34:26 +00001583 Value *V = B.CreateCall(F, {Op, B.getTrue()}, "cttz");
Chris Bienemanad070d02014-09-17 20:55:46 +00001584 V = B.CreateAdd(V, ConstantInt::get(V->getType(), 1));
1585 V = B.CreateIntCast(V, B.getInt32Ty(), false);
Meador Ingea0b6d872012-11-26 00:24:07 +00001586
Chris Bienemanad070d02014-09-17 20:55:46 +00001587 Value *Cond = B.CreateICmpNE(Op, Constant::getNullValue(ArgType));
1588 return B.CreateSelect(Cond, V, B.getInt32(0));
1589}
Meador Ingea0b6d872012-11-26 00:24:07 +00001590
Davide Italiano85ad36b2016-12-15 23:45:11 +00001591Value *LibCallSimplifier::optimizeFls(CallInst *CI, IRBuilder<> &B) {
1592 // fls(x) -> (i32)(sizeInBits(x) - llvm.ctlz(x, false))
1593 Value *Op = CI->getArgOperand(0);
1594 Type *ArgType = Op->getType();
1595 Value *F = Intrinsic::getDeclaration(CI->getCalledFunction()->getParent(),
1596 Intrinsic::ctlz, ArgType);
1597 Value *V = B.CreateCall(F, {Op, B.getFalse()}, "ctlz");
1598 V = B.CreateSub(ConstantInt::get(V->getType(), ArgType->getIntegerBitWidth()),
1599 V);
1600 return B.CreateIntCast(V, CI->getType(), false);
1601}
1602
Chris Bienemanad070d02014-09-17 20:55:46 +00001603Value *LibCallSimplifier::optimizeAbs(CallInst *CI, IRBuilder<> &B) {
Chris Bienemanad070d02014-09-17 20:55:46 +00001604 // abs(x) -> x >s -1 ? x : -x
1605 Value *Op = CI->getArgOperand(0);
1606 Value *Pos =
1607 B.CreateICmpSGT(Op, Constant::getAllOnesValue(Op->getType()), "ispos");
1608 Value *Neg = B.CreateNeg(Op, "neg");
1609 return B.CreateSelect(Pos, Op, Neg);
1610}
Meador Inge9a59ab62012-11-26 02:31:59 +00001611
Chris Bienemanad070d02014-09-17 20:55:46 +00001612Value *LibCallSimplifier::optimizeIsDigit(CallInst *CI, IRBuilder<> &B) {
Chris Bienemanad070d02014-09-17 20:55:46 +00001613 // isdigit(c) -> (c-'0') <u 10
1614 Value *Op = CI->getArgOperand(0);
1615 Op = B.CreateSub(Op, B.getInt32('0'), "isdigittmp");
1616 Op = B.CreateICmpULT(Op, B.getInt32(10), "isdigit");
1617 return B.CreateZExt(Op, CI->getType());
1618}
Meador Ingea62a39e2012-11-26 03:10:07 +00001619
Chris Bienemanad070d02014-09-17 20:55:46 +00001620Value *LibCallSimplifier::optimizeIsAscii(CallInst *CI, IRBuilder<> &B) {
Chris Bienemanad070d02014-09-17 20:55:46 +00001621 // isascii(c) -> c <u 128
1622 Value *Op = CI->getArgOperand(0);
1623 Op = B.CreateICmpULT(Op, B.getInt32(128), "isascii");
1624 return B.CreateZExt(Op, CI->getType());
1625}
1626
1627Value *LibCallSimplifier::optimizeToAscii(CallInst *CI, IRBuilder<> &B) {
Chris Bienemanad070d02014-09-17 20:55:46 +00001628 // toascii(c) -> c & 0x7f
1629 return B.CreateAnd(CI->getArgOperand(0),
1630 ConstantInt::get(CI->getType(), 0x7F));
1631}
Meador Inge604937d2012-11-26 03:38:52 +00001632
Meador Inge08ca1152012-11-26 20:37:20 +00001633//===----------------------------------------------------------------------===//
1634// Formatting and IO Library Call Optimizations
1635//===----------------------------------------------------------------------===//
1636
Chris Bienemanad070d02014-09-17 20:55:46 +00001637static bool isReportingError(Function *Callee, CallInst *CI, int StreamArg);
Hal Finkel66cd3f12013-11-17 02:06:35 +00001638
Chris Bienemanad070d02014-09-17 20:55:46 +00001639Value *LibCallSimplifier::optimizeErrorReporting(CallInst *CI, IRBuilder<> &B,
1640 int StreamArg) {
Ahmed Bougachad765a822016-04-27 19:04:35 +00001641 Function *Callee = CI->getCalledFunction();
Chris Bienemanad070d02014-09-17 20:55:46 +00001642 // Error reporting calls should be cold, mark them as such.
1643 // This applies even to non-builtin calls: it is only a hint and applies to
1644 // functions that the frontend might not understand as builtins.
Hal Finkel66cd3f12013-11-17 02:06:35 +00001645
Chris Bienemanad070d02014-09-17 20:55:46 +00001646 // This heuristic was suggested in:
1647 // Improving Static Branch Prediction in a Compiler
1648 // Brian L. Deitrich, Ben-Chung Cheng, Wen-mei W. Hwu
1649 // Proceedings of PACT'98, Oct. 1998, IEEE
Chris Bienemanad070d02014-09-17 20:55:46 +00001650 if (!CI->hasFnAttr(Attribute::Cold) &&
1651 isReportingError(Callee, CI, StreamArg)) {
Reid Klecknerb5180542017-03-21 16:57:19 +00001652 CI->addAttribute(AttributeList::FunctionIndex, Attribute::Cold);
Chris Bienemanad070d02014-09-17 20:55:46 +00001653 }
Hal Finkel66cd3f12013-11-17 02:06:35 +00001654
Chris Bienemanad070d02014-09-17 20:55:46 +00001655 return nullptr;
1656}
1657
1658static bool isReportingError(Function *Callee, CallInst *CI, int StreamArg) {
Davide Italiano5b65f122017-04-25 03:48:47 +00001659 if (!Callee || !Callee->isDeclaration())
Chris Bienemanad070d02014-09-17 20:55:46 +00001660 return false;
1661
1662 if (StreamArg < 0)
1663 return true;
1664
1665 // These functions might be considered cold, but only if their stream
1666 // argument is stderr.
1667
1668 if (StreamArg >= (int)CI->getNumArgOperands())
1669 return false;
1670 LoadInst *LI = dyn_cast<LoadInst>(CI->getArgOperand(StreamArg));
1671 if (!LI)
1672 return false;
1673 GlobalVariable *GV = dyn_cast<GlobalVariable>(LI->getPointerOperand());
1674 if (!GV || !GV->isDeclaration())
1675 return false;
1676 return GV->getName() == "stderr";
1677}
1678
1679Value *LibCallSimplifier::optimizePrintFString(CallInst *CI, IRBuilder<> &B) {
1680 // Check for a fixed format string.
1681 StringRef FormatStr;
1682 if (!getConstantStringInfo(CI->getArgOperand(0), FormatStr))
Craig Topperf40110f2014-04-25 05:29:35 +00001683 return nullptr;
Hal Finkel66cd3f12013-11-17 02:06:35 +00001684
Chris Bienemanad070d02014-09-17 20:55:46 +00001685 // Empty format string -> noop.
1686 if (FormatStr.empty()) // Tolerate printf's declared void.
1687 return CI->use_empty() ? (Value *)CI : ConstantInt::get(CI->getType(), 0);
Hal Finkel66cd3f12013-11-17 02:06:35 +00001688
Chris Bienemanad070d02014-09-17 20:55:46 +00001689 // Do not do any of the following transformations if the printf return value
1690 // is used, in general the printf return value is not compatible with either
1691 // putchar() or puts().
1692 if (!CI->use_empty())
Craig Topperf40110f2014-04-25 05:29:35 +00001693 return nullptr;
Chris Bienemanad070d02014-09-17 20:55:46 +00001694
Joerg Sonnenberger8ffe7ab2016-05-09 14:36:16 +00001695 // printf("x") -> putchar('x'), even for "%" and "%%".
1696 if (FormatStr.size() == 1 || FormatStr == "%%")
Davide Italianod4f5a052016-04-03 01:46:52 +00001697 return emitPutChar(B.getInt32(FormatStr[0]), B, TLI);
Meador Inge08ca1152012-11-26 20:37:20 +00001698
Davide Italiano6db1dcb2016-03-28 15:54:01 +00001699 // printf("%s", "a") --> putchar('a')
1700 if (FormatStr == "%s" && CI->getNumArgOperands() > 1) {
1701 StringRef ChrStr;
1702 if (!getConstantStringInfo(CI->getOperand(1), ChrStr))
1703 return nullptr;
1704 if (ChrStr.size() != 1)
1705 return nullptr;
Davide Italianod4f5a052016-04-03 01:46:52 +00001706 return emitPutChar(B.getInt32(ChrStr[0]), B, TLI);
Davide Italiano6db1dcb2016-03-28 15:54:01 +00001707 }
1708
Chris Bienemanad070d02014-09-17 20:55:46 +00001709 // printf("foo\n") --> puts("foo")
1710 if (FormatStr[FormatStr.size() - 1] == '\n' &&
1711 FormatStr.find('%') == StringRef::npos) { // No format characters.
1712 // Create a string literal with no \n on it. We expect the constant merge
1713 // pass to be run after this pass, to merge duplicate strings.
1714 FormatStr = FormatStr.drop_back();
1715 Value *GV = B.CreateGlobalString(FormatStr, "str");
Davide Italianod4f5a052016-04-03 01:46:52 +00001716 return emitPutS(GV, B, TLI);
Chris Bienemanad070d02014-09-17 20:55:46 +00001717 }
Meador Inge08ca1152012-11-26 20:37:20 +00001718
Chris Bienemanad070d02014-09-17 20:55:46 +00001719 // Optimize specific format strings.
1720 // printf("%c", chr) --> putchar(chr)
1721 if (FormatStr == "%c" && CI->getNumArgOperands() > 1 &&
Davide Italianod4f5a052016-04-03 01:46:52 +00001722 CI->getArgOperand(1)->getType()->isIntegerTy())
1723 return emitPutChar(CI->getArgOperand(1), B, TLI);
Chris Bienemanad070d02014-09-17 20:55:46 +00001724
1725 // printf("%s\n", str) --> puts(str)
1726 if (FormatStr == "%s\n" && CI->getNumArgOperands() > 1 &&
Davide Italianod4f5a052016-04-03 01:46:52 +00001727 CI->getArgOperand(1)->getType()->isPointerTy())
Sanjay Pateld3112a52016-01-19 19:46:10 +00001728 return emitPutS(CI->getArgOperand(1), B, TLI);
Chris Bienemanad070d02014-09-17 20:55:46 +00001729 return nullptr;
1730}
1731
1732Value *LibCallSimplifier::optimizePrintF(CallInst *CI, IRBuilder<> &B) {
1733
1734 Function *Callee = CI->getCalledFunction();
Chris Bienemanad070d02014-09-17 20:55:46 +00001735 FunctionType *FT = Callee->getFunctionType();
Chris Bienemanad070d02014-09-17 20:55:46 +00001736 if (Value *V = optimizePrintFString(CI, B)) {
1737 return V;
1738 }
1739
1740 // printf(format, ...) -> iprintf(format, ...) if no floating point
1741 // arguments.
David L. Jonesd21529f2017-01-23 23:16:46 +00001742 if (TLI->has(LibFunc_iprintf) && !callHasFloatingPointArgument(CI)) {
Chris Bienemanad070d02014-09-17 20:55:46 +00001743 Module *M = B.GetInsertBlock()->getParent()->getParent();
1744 Constant *IPrintFFn =
Meador Inge08ca1152012-11-26 20:37:20 +00001745 M->getOrInsertFunction("iprintf", FT, Callee->getAttributes());
Chris Bienemanad070d02014-09-17 20:55:46 +00001746 CallInst *New = cast<CallInst>(CI->clone());
1747 New->setCalledFunction(IPrintFFn);
1748 B.Insert(New);
1749 return New;
Meador Inge08ca1152012-11-26 20:37:20 +00001750 }
Chris Bienemanad070d02014-09-17 20:55:46 +00001751 return nullptr;
1752}
Meador Inge08ca1152012-11-26 20:37:20 +00001753
Chris Bienemanad070d02014-09-17 20:55:46 +00001754Value *LibCallSimplifier::optimizeSPrintFString(CallInst *CI, IRBuilder<> &B) {
1755 // Check for a fixed format string.
1756 StringRef FormatStr;
1757 if (!getConstantStringInfo(CI->getArgOperand(1), FormatStr))
Craig Topperf40110f2014-04-25 05:29:35 +00001758 return nullptr;
Meador Inge25c9b3b2012-11-27 05:57:54 +00001759
Chris Bienemanad070d02014-09-17 20:55:46 +00001760 // If we just have a format string (nothing else crazy) transform it.
1761 if (CI->getNumArgOperands() == 2) {
1762 // Make sure there's no % in the constant array. We could try to handle
1763 // %% -> % in the future if we cared.
1764 for (unsigned i = 0, e = FormatStr.size(); i != e; ++i)
1765 if (FormatStr[i] == '%')
1766 return nullptr; // we found a format specifier, bail out.
Hal Finkel66cd3f12013-11-17 02:06:35 +00001767
Chris Bienemanad070d02014-09-17 20:55:46 +00001768 // sprintf(str, fmt) -> llvm.memcpy(str, fmt, strlen(fmt)+1, 1)
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001769 B.CreateMemCpy(CI->getArgOperand(0), CI->getArgOperand(1),
1770 ConstantInt::get(DL.getIntPtrType(CI->getContext()),
1771 FormatStr.size() + 1),
Pete Cooper67cf9a72015-11-19 05:56:52 +00001772 1); // Copy the null byte.
Chris Bienemanad070d02014-09-17 20:55:46 +00001773 return ConstantInt::get(CI->getType(), FormatStr.size());
Meador Ingef8e72502012-11-29 15:45:43 +00001774 }
Meador Ingef8e72502012-11-29 15:45:43 +00001775
Chris Bienemanad070d02014-09-17 20:55:46 +00001776 // The remaining optimizations require the format string to be "%s" or "%c"
1777 // and have an extra operand.
1778 if (FormatStr.size() != 2 || FormatStr[0] != '%' ||
1779 CI->getNumArgOperands() < 3)
Craig Topperf40110f2014-04-25 05:29:35 +00001780 return nullptr;
Meador Inge75798bb2012-11-29 19:15:17 +00001781
Chris Bienemanad070d02014-09-17 20:55:46 +00001782 // Decode the second character of the format string.
1783 if (FormatStr[1] == 'c') {
1784 // sprintf(dst, "%c", chr) --> *(i8*)dst = chr; *((i8*)dst+1) = 0
1785 if (!CI->getArgOperand(2)->getType()->isIntegerTy())
1786 return nullptr;
1787 Value *V = B.CreateTrunc(CI->getArgOperand(2), B.getInt8Ty(), "char");
Sanjay Pateld3112a52016-01-19 19:46:10 +00001788 Value *Ptr = castToCStr(CI->getArgOperand(0), B);
Chris Bienemanad070d02014-09-17 20:55:46 +00001789 B.CreateStore(V, Ptr);
David Blaikie3909da72015-03-30 20:42:56 +00001790 Ptr = B.CreateGEP(B.getInt8Ty(), Ptr, B.getInt32(1), "nul");
Chris Bienemanad070d02014-09-17 20:55:46 +00001791 B.CreateStore(B.getInt8(0), Ptr);
Meador Ingedf796f82012-10-13 16:45:24 +00001792
Chris Bienemanad070d02014-09-17 20:55:46 +00001793 return ConstantInt::get(CI->getType(), 1);
Meador Ingedf796f82012-10-13 16:45:24 +00001794 }
1795
Chris Bienemanad070d02014-09-17 20:55:46 +00001796 if (FormatStr[1] == 's') {
Chris Bienemanad070d02014-09-17 20:55:46 +00001797 // sprintf(dest, "%s", str) -> llvm.memcpy(dest, str, strlen(str)+1, 1)
1798 if (!CI->getArgOperand(2)->getType()->isPointerTy())
1799 return nullptr;
1800
Sanjay Pateld3112a52016-01-19 19:46:10 +00001801 Value *Len = emitStrLen(CI->getArgOperand(2), B, DL, TLI);
Chris Bienemanad070d02014-09-17 20:55:46 +00001802 if (!Len)
1803 return nullptr;
David Majnemerabb9f552016-04-26 21:04:47 +00001804 Value *IncLen =
1805 B.CreateAdd(Len, ConstantInt::get(Len->getType(), 1), "leninc");
1806 B.CreateMemCpy(CI->getArgOperand(0), CI->getArgOperand(2), IncLen, 1);
Chris Bienemanad070d02014-09-17 20:55:46 +00001807
1808 // The sprintf result is the unincremented number of bytes in the string.
1809 return B.CreateIntCast(Len, CI->getType(), false);
1810 }
1811 return nullptr;
1812}
1813
1814Value *LibCallSimplifier::optimizeSPrintF(CallInst *CI, IRBuilder<> &B) {
1815 Function *Callee = CI->getCalledFunction();
Chris Bienemanad070d02014-09-17 20:55:46 +00001816 FunctionType *FT = Callee->getFunctionType();
Chris Bienemanad070d02014-09-17 20:55:46 +00001817 if (Value *V = optimizeSPrintFString(CI, B)) {
1818 return V;
1819 }
1820
1821 // sprintf(str, format, ...) -> siprintf(str, format, ...) if no floating
1822 // point arguments.
David L. Jonesd21529f2017-01-23 23:16:46 +00001823 if (TLI->has(LibFunc_siprintf) && !callHasFloatingPointArgument(CI)) {
Chris Bienemanad070d02014-09-17 20:55:46 +00001824 Module *M = B.GetInsertBlock()->getParent()->getParent();
1825 Constant *SIPrintFFn =
1826 M->getOrInsertFunction("siprintf", FT, Callee->getAttributes());
1827 CallInst *New = cast<CallInst>(CI->clone());
1828 New->setCalledFunction(SIPrintFFn);
1829 B.Insert(New);
1830 return New;
1831 }
1832 return nullptr;
1833}
1834
1835Value *LibCallSimplifier::optimizeFPrintFString(CallInst *CI, IRBuilder<> &B) {
1836 optimizeErrorReporting(CI, B, 0);
1837
1838 // All the optimizations depend on the format string.
1839 StringRef FormatStr;
1840 if (!getConstantStringInfo(CI->getArgOperand(1), FormatStr))
1841 return nullptr;
1842
1843 // Do not do any of the following transformations if the fprintf return
1844 // value is used, in general the fprintf return value is not compatible
1845 // with fwrite(), fputc() or fputs().
1846 if (!CI->use_empty())
1847 return nullptr;
1848
1849 // fprintf(F, "foo") --> fwrite("foo", 3, 1, F)
1850 if (CI->getNumArgOperands() == 2) {
1851 for (unsigned i = 0, e = FormatStr.size(); i != e; ++i)
1852 if (FormatStr[i] == '%') // Could handle %% -> % if we cared.
1853 return nullptr; // We found a format specifier.
1854
Sanjay Pateld3112a52016-01-19 19:46:10 +00001855 return emitFWrite(
Chris Bienemanad070d02014-09-17 20:55:46 +00001856 CI->getArgOperand(1),
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001857 ConstantInt::get(DL.getIntPtrType(CI->getContext()), FormatStr.size()),
Chris Bienemanad070d02014-09-17 20:55:46 +00001858 CI->getArgOperand(0), B, DL, TLI);
1859 }
1860
1861 // The remaining optimizations require the format string to be "%s" or "%c"
1862 // and have an extra operand.
1863 if (FormatStr.size() != 2 || FormatStr[0] != '%' ||
1864 CI->getNumArgOperands() < 3)
1865 return nullptr;
1866
1867 // Decode the second character of the format string.
1868 if (FormatStr[1] == 'c') {
1869 // fprintf(F, "%c", chr) --> fputc(chr, F)
1870 if (!CI->getArgOperand(2)->getType()->isIntegerTy())
1871 return nullptr;
Sanjay Pateld3112a52016-01-19 19:46:10 +00001872 return emitFPutC(CI->getArgOperand(2), CI->getArgOperand(0), B, TLI);
Chris Bienemanad070d02014-09-17 20:55:46 +00001873 }
1874
1875 if (FormatStr[1] == 's') {
1876 // fprintf(F, "%s", str) --> fputs(str, F)
1877 if (!CI->getArgOperand(2)->getType()->isPointerTy())
1878 return nullptr;
Sanjay Pateld3112a52016-01-19 19:46:10 +00001879 return emitFPutS(CI->getArgOperand(2), CI->getArgOperand(0), B, TLI);
Chris Bienemanad070d02014-09-17 20:55:46 +00001880 }
1881 return nullptr;
1882}
1883
1884Value *LibCallSimplifier::optimizeFPrintF(CallInst *CI, IRBuilder<> &B) {
1885 Function *Callee = CI->getCalledFunction();
Chris Bienemanad070d02014-09-17 20:55:46 +00001886 FunctionType *FT = Callee->getFunctionType();
Chris Bienemanad070d02014-09-17 20:55:46 +00001887 if (Value *V = optimizeFPrintFString(CI, B)) {
1888 return V;
1889 }
1890
1891 // fprintf(stream, format, ...) -> fiprintf(stream, format, ...) if no
1892 // floating point arguments.
David L. Jonesd21529f2017-01-23 23:16:46 +00001893 if (TLI->has(LibFunc_fiprintf) && !callHasFloatingPointArgument(CI)) {
Chris Bienemanad070d02014-09-17 20:55:46 +00001894 Module *M = B.GetInsertBlock()->getParent()->getParent();
1895 Constant *FIPrintFFn =
1896 M->getOrInsertFunction("fiprintf", FT, Callee->getAttributes());
1897 CallInst *New = cast<CallInst>(CI->clone());
1898 New->setCalledFunction(FIPrintFFn);
1899 B.Insert(New);
1900 return New;
1901 }
1902 return nullptr;
1903}
1904
1905Value *LibCallSimplifier::optimizeFWrite(CallInst *CI, IRBuilder<> &B) {
1906 optimizeErrorReporting(CI, B, 3);
1907
Chris Bienemanad070d02014-09-17 20:55:46 +00001908 // Get the element size and count.
1909 ConstantInt *SizeC = dyn_cast<ConstantInt>(CI->getArgOperand(1));
1910 ConstantInt *CountC = dyn_cast<ConstantInt>(CI->getArgOperand(2));
1911 if (!SizeC || !CountC)
1912 return nullptr;
1913 uint64_t Bytes = SizeC->getZExtValue() * CountC->getZExtValue();
1914
1915 // If this is writing zero records, remove the call (it's a noop).
1916 if (Bytes == 0)
1917 return ConstantInt::get(CI->getType(), 0);
1918
1919 // If this is writing one byte, turn it into fputc.
1920 // This optimisation is only valid, if the return value is unused.
1921 if (Bytes == 1 && CI->use_empty()) { // fwrite(S,1,1,F) -> fputc(S[0],F)
Sanjay Pateld3112a52016-01-19 19:46:10 +00001922 Value *Char = B.CreateLoad(castToCStr(CI->getArgOperand(0), B), "char");
1923 Value *NewCI = emitFPutC(Char, CI->getArgOperand(3), B, TLI);
Chris Bienemanad070d02014-09-17 20:55:46 +00001924 return NewCI ? ConstantInt::get(CI->getType(), 1) : nullptr;
1925 }
1926
1927 return nullptr;
1928}
1929
1930Value *LibCallSimplifier::optimizeFPuts(CallInst *CI, IRBuilder<> &B) {
1931 optimizeErrorReporting(CI, B, 1);
1932
Sjoerd Meijer7435a912016-07-07 14:31:19 +00001933 // Don't rewrite fputs to fwrite when optimising for size because fwrite
1934 // requires more arguments and thus extra MOVs are required.
1935 if (CI->getParent()->getParent()->optForSize())
1936 return nullptr;
1937
Ahmed Bougachad765a822016-04-27 19:04:35 +00001938 // We can't optimize if return value is used.
1939 if (!CI->use_empty())
Chris Bienemanad070d02014-09-17 20:55:46 +00001940 return nullptr;
1941
1942 // fputs(s,F) --> fwrite(s,1,strlen(s),F)
1943 uint64_t Len = GetStringLength(CI->getArgOperand(0));
1944 if (!Len)
1945 return nullptr;
1946
1947 // Known to have no uses (see above).
Sanjay Pateld3112a52016-01-19 19:46:10 +00001948 return emitFWrite(
Chris Bienemanad070d02014-09-17 20:55:46 +00001949 CI->getArgOperand(0),
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001950 ConstantInt::get(DL.getIntPtrType(CI->getContext()), Len - 1),
Chris Bienemanad070d02014-09-17 20:55:46 +00001951 CI->getArgOperand(1), B, DL, TLI);
1952}
1953
1954Value *LibCallSimplifier::optimizePuts(CallInst *CI, IRBuilder<> &B) {
Chris Bienemanad070d02014-09-17 20:55:46 +00001955 // Check for a constant string.
1956 StringRef Str;
1957 if (!getConstantStringInfo(CI->getArgOperand(0), Str))
1958 return nullptr;
1959
1960 if (Str.empty() && CI->use_empty()) {
1961 // puts("") -> putchar('\n')
Sanjay Pateld3112a52016-01-19 19:46:10 +00001962 Value *Res = emitPutChar(B.getInt32('\n'), B, TLI);
Chris Bienemanad070d02014-09-17 20:55:46 +00001963 if (CI->use_empty() || !Res)
1964 return Res;
1965 return B.CreateIntCast(Res, CI->getType(), true);
1966 }
1967
1968 return nullptr;
1969}
1970
1971bool LibCallSimplifier::hasFloatVersion(StringRef FuncName) {
David L. Jonesd21529f2017-01-23 23:16:46 +00001972 LibFunc Func;
Meador Inge20255ef2013-03-12 00:08:29 +00001973 SmallString<20> FloatFuncName = FuncName;
1974 FloatFuncName += 'f';
1975 if (TLI->getLibFunc(FloatFuncName, Func))
1976 return TLI->has(Func);
1977 return false;
1978}
Meador Inge7fb2f732012-10-13 16:45:32 +00001979
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00001980Value *LibCallSimplifier::optimizeStringMemoryLibCall(CallInst *CI,
1981 IRBuilder<> &Builder) {
David L. Jonesd21529f2017-01-23 23:16:46 +00001982 LibFunc Func;
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00001983 Function *Callee = CI->getCalledFunction();
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00001984 // Check for string/memory library functions.
Ahmed Bougachad765a822016-04-27 19:04:35 +00001985 if (TLI->getLibFunc(*Callee, Func) && TLI->has(Func)) {
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00001986 // Make sure we never change the calling convention.
1987 assert((ignoreCallingConv(Func) ||
Sam Parker214f7bf2016-09-13 12:10:14 +00001988 isCallingConvCCompatible(CI)) &&
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00001989 "Optimizing string/memory libcall would change the calling convention");
1990 switch (Func) {
David L. Jonesd21529f2017-01-23 23:16:46 +00001991 case LibFunc_strcat:
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00001992 return optimizeStrCat(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00001993 case LibFunc_strncat:
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00001994 return optimizeStrNCat(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00001995 case LibFunc_strchr:
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00001996 return optimizeStrChr(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00001997 case LibFunc_strrchr:
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00001998 return optimizeStrRChr(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00001999 case LibFunc_strcmp:
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00002000 return optimizeStrCmp(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002001 case LibFunc_strncmp:
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00002002 return optimizeStrNCmp(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002003 case LibFunc_strcpy:
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00002004 return optimizeStrCpy(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002005 case LibFunc_stpcpy:
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00002006 return optimizeStpCpy(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002007 case LibFunc_strncpy:
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00002008 return optimizeStrNCpy(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002009 case LibFunc_strlen:
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00002010 return optimizeStrLen(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002011 case LibFunc_strpbrk:
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00002012 return optimizeStrPBrk(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002013 case LibFunc_strtol:
2014 case LibFunc_strtod:
2015 case LibFunc_strtof:
2016 case LibFunc_strtoul:
2017 case LibFunc_strtoll:
2018 case LibFunc_strtold:
2019 case LibFunc_strtoull:
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00002020 return optimizeStrTo(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002021 case LibFunc_strspn:
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00002022 return optimizeStrSpn(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002023 case LibFunc_strcspn:
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00002024 return optimizeStrCSpn(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002025 case LibFunc_strstr:
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00002026 return optimizeStrStr(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002027 case LibFunc_memchr:
Benjamin Kramer691363e2015-03-21 15:36:21 +00002028 return optimizeMemChr(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002029 case LibFunc_memcmp:
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00002030 return optimizeMemCmp(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002031 case LibFunc_memcpy:
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00002032 return optimizeMemCpy(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002033 case LibFunc_memmove:
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00002034 return optimizeMemMove(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002035 case LibFunc_memset:
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00002036 return optimizeMemSet(CI, Builder);
Matthias Braun50ec0b52017-05-19 22:37:09 +00002037 case LibFunc_wcslen:
2038 return optimizeWcslen(CI, Builder);
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00002039 default:
2040 break;
2041 }
2042 }
2043 return nullptr;
2044}
2045
Chris Bienemanad070d02014-09-17 20:55:46 +00002046Value *LibCallSimplifier::optimizeCall(CallInst *CI) {
2047 if (CI->isNoBuiltin())
2048 return nullptr;
Meador Inge4d2827c2012-11-11 05:11:20 +00002049
David L. Jonesd21529f2017-01-23 23:16:46 +00002050 LibFunc Func;
Meador Inge20255ef2013-03-12 00:08:29 +00002051 Function *Callee = CI->getCalledFunction();
2052 StringRef FuncName = Callee->getName();
David Majnemerb70e23c2016-01-06 05:01:34 +00002053
2054 SmallVector<OperandBundleDef, 2> OpBundles;
2055 CI->getOperandBundlesAsDefs(OpBundles);
2056 IRBuilder<> Builder(CI, /*FPMathTag=*/nullptr, OpBundles);
Sam Parker214f7bf2016-09-13 12:10:14 +00002057 bool isCallingConvC = isCallingConvCCompatible(CI);
Meador Inge20255ef2013-03-12 00:08:29 +00002058
Sanjay Pateld1f4f032016-01-19 18:38:52 +00002059 // Command-line parameter overrides instruction attribute.
Sanjay Patela92fa442014-10-22 15:29:23 +00002060 if (EnableUnsafeFPShrink.getNumOccurrences() > 0)
2061 UnsafeFPShrink = EnableUnsafeFPShrink;
Sanjay Pateld1f4f032016-01-19 18:38:52 +00002062 else if (isa<FPMathOperator>(CI) && CI->hasUnsafeAlgebra())
Davide Italianoa904e522015-10-29 02:58:44 +00002063 UnsafeFPShrink = true;
Sanjay Patela92fa442014-10-22 15:29:23 +00002064
Sanjay Patel848309d2014-10-23 21:52:45 +00002065 // First, check for intrinsics.
Meador Inge20255ef2013-03-12 00:08:29 +00002066 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(CI)) {
Chris Bienemanad070d02014-09-17 20:55:46 +00002067 if (!isCallingConvC)
2068 return nullptr;
Meador Inge20255ef2013-03-12 00:08:29 +00002069 switch (II->getIntrinsicID()) {
2070 case Intrinsic::pow:
Chris Bienemanad070d02014-09-17 20:55:46 +00002071 return optimizePow(CI, Builder);
Meador Inge20255ef2013-03-12 00:08:29 +00002072 case Intrinsic::exp2:
Chris Bienemanad070d02014-09-17 20:55:46 +00002073 return optimizeExp2(CI, Builder);
Davide Italianob8b71332015-11-29 20:58:04 +00002074 case Intrinsic::log:
2075 return optimizeLog(CI, Builder);
Sanjay Patelc699a612014-10-16 18:48:17 +00002076 case Intrinsic::sqrt:
2077 return optimizeSqrt(CI, Builder);
Sanjay Patel980b2802016-01-26 16:17:24 +00002078 // TODO: Use foldMallocMemset() with memset intrinsic.
Meador Inge20255ef2013-03-12 00:08:29 +00002079 default:
Chris Bienemanad070d02014-09-17 20:55:46 +00002080 return nullptr;
Meador Inge20255ef2013-03-12 00:08:29 +00002081 }
2082 }
2083
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002084 // Also try to simplify calls to fortified library functions.
2085 if (Value *SimplifiedFortifiedCI = FortifiedSimplifier.optimizeCall(CI)) {
2086 // Try to further simplify the result.
Ahmed Bougacha71d7b182015-01-14 00:55:05 +00002087 CallInst *SimplifiedCI = dyn_cast<CallInst>(SimplifiedFortifiedCI);
Bruno Cardoso Lopesb491a2d2015-10-01 22:43:53 +00002088 if (SimplifiedCI && SimplifiedCI->getCalledFunction()) {
2089 // Use an IR Builder from SimplifiedCI if available instead of CI
2090 // to guarantee we reach all uses we might replace later on.
2091 IRBuilder<> TmpBuilder(SimplifiedCI);
2092 if (Value *V = optimizeStringMemoryLibCall(SimplifiedCI, TmpBuilder)) {
Ahmed Bougacha1ac93562015-01-27 21:52:16 +00002093 // If we were able to further simplify, remove the now redundant call.
2094 SimplifiedCI->replaceAllUsesWith(V);
2095 SimplifiedCI->eraseFromParent();
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002096 return V;
Ahmed Bougacha1ac93562015-01-27 21:52:16 +00002097 }
Bruno Cardoso Lopesb491a2d2015-10-01 22:43:53 +00002098 }
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002099 return SimplifiedFortifiedCI;
2100 }
2101
Meador Inge20255ef2013-03-12 00:08:29 +00002102 // Then check for known library functions.
Ahmed Bougachad765a822016-04-27 19:04:35 +00002103 if (TLI->getLibFunc(*Callee, Func) && TLI->has(Func)) {
Chris Bienemanad070d02014-09-17 20:55:46 +00002104 // We never change the calling convention.
2105 if (!ignoreCallingConv(Func) && !isCallingConvC)
2106 return nullptr;
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00002107 if (Value *V = optimizeStringMemoryLibCall(CI, Builder))
2108 return V;
Meador Inge20255ef2013-03-12 00:08:29 +00002109 switch (Func) {
David L. Jonesd21529f2017-01-23 23:16:46 +00002110 case LibFunc_cosf:
2111 case LibFunc_cos:
2112 case LibFunc_cosl:
Chris Bienemanad070d02014-09-17 20:55:46 +00002113 return optimizeCos(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002114 case LibFunc_sinpif:
2115 case LibFunc_sinpi:
2116 case LibFunc_cospif:
2117 case LibFunc_cospi:
Chris Bienemanad070d02014-09-17 20:55:46 +00002118 return optimizeSinCosPi(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002119 case LibFunc_powf:
2120 case LibFunc_pow:
2121 case LibFunc_powl:
Chris Bienemanad070d02014-09-17 20:55:46 +00002122 return optimizePow(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002123 case LibFunc_exp2l:
2124 case LibFunc_exp2:
2125 case LibFunc_exp2f:
Chris Bienemanad070d02014-09-17 20:55:46 +00002126 return optimizeExp2(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002127 case LibFunc_fabsf:
2128 case LibFunc_fabs:
2129 case LibFunc_fabsl:
Matt Arsenault954a6242017-01-23 23:55:08 +00002130 return replaceUnaryCall(CI, Builder, Intrinsic::fabs);
David L. Jonesd21529f2017-01-23 23:16:46 +00002131 case LibFunc_sqrtf:
2132 case LibFunc_sqrt:
2133 case LibFunc_sqrtl:
Sanjay Patelc699a612014-10-16 18:48:17 +00002134 return optimizeSqrt(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002135 case LibFunc_ffs:
2136 case LibFunc_ffsl:
2137 case LibFunc_ffsll:
Chris Bienemanad070d02014-09-17 20:55:46 +00002138 return optimizeFFS(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002139 case LibFunc_fls:
2140 case LibFunc_flsl:
2141 case LibFunc_flsll:
Davide Italiano85ad36b2016-12-15 23:45:11 +00002142 return optimizeFls(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002143 case LibFunc_abs:
2144 case LibFunc_labs:
2145 case LibFunc_llabs:
Chris Bienemanad070d02014-09-17 20:55:46 +00002146 return optimizeAbs(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002147 case LibFunc_isdigit:
Chris Bienemanad070d02014-09-17 20:55:46 +00002148 return optimizeIsDigit(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002149 case LibFunc_isascii:
Chris Bienemanad070d02014-09-17 20:55:46 +00002150 return optimizeIsAscii(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002151 case LibFunc_toascii:
Chris Bienemanad070d02014-09-17 20:55:46 +00002152 return optimizeToAscii(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002153 case LibFunc_printf:
Chris Bienemanad070d02014-09-17 20:55:46 +00002154 return optimizePrintF(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002155 case LibFunc_sprintf:
Chris Bienemanad070d02014-09-17 20:55:46 +00002156 return optimizeSPrintF(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002157 case LibFunc_fprintf:
Chris Bienemanad070d02014-09-17 20:55:46 +00002158 return optimizeFPrintF(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002159 case LibFunc_fwrite:
Chris Bienemanad070d02014-09-17 20:55:46 +00002160 return optimizeFWrite(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002161 case LibFunc_fputs:
Chris Bienemanad070d02014-09-17 20:55:46 +00002162 return optimizeFPuts(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002163 case LibFunc_log:
2164 case LibFunc_log10:
2165 case LibFunc_log1p:
2166 case LibFunc_log2:
2167 case LibFunc_logb:
Davide Italianob8b71332015-11-29 20:58:04 +00002168 return optimizeLog(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002169 case LibFunc_puts:
Chris Bienemanad070d02014-09-17 20:55:46 +00002170 return optimizePuts(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002171 case LibFunc_tan:
2172 case LibFunc_tanf:
2173 case LibFunc_tanl:
Davide Italiano51507d22015-11-04 23:36:56 +00002174 return optimizeTan(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002175 case LibFunc_perror:
Chris Bienemanad070d02014-09-17 20:55:46 +00002176 return optimizeErrorReporting(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002177 case LibFunc_vfprintf:
2178 case LibFunc_fiprintf:
Chris Bienemanad070d02014-09-17 20:55:46 +00002179 return optimizeErrorReporting(CI, Builder, 0);
David L. Jonesd21529f2017-01-23 23:16:46 +00002180 case LibFunc_fputc:
Chris Bienemanad070d02014-09-17 20:55:46 +00002181 return optimizeErrorReporting(CI, Builder, 1);
David L. Jonesd21529f2017-01-23 23:16:46 +00002182 case LibFunc_ceil:
Matt Arsenault954a6242017-01-23 23:55:08 +00002183 return replaceUnaryCall(CI, Builder, Intrinsic::ceil);
David L. Jonesd21529f2017-01-23 23:16:46 +00002184 case LibFunc_floor:
Matt Arsenault954a6242017-01-23 23:55:08 +00002185 return replaceUnaryCall(CI, Builder, Intrinsic::floor);
David L. Jonesd21529f2017-01-23 23:16:46 +00002186 case LibFunc_round:
Matt Arsenault954a6242017-01-23 23:55:08 +00002187 return replaceUnaryCall(CI, Builder, Intrinsic::round);
David L. Jonesd21529f2017-01-23 23:16:46 +00002188 case LibFunc_nearbyint:
Matt Arsenault954a6242017-01-23 23:55:08 +00002189 return replaceUnaryCall(CI, Builder, Intrinsic::nearbyint);
Joerg Sonnenberger28bed102017-03-31 19:58:07 +00002190 case LibFunc_rint:
2191 return replaceUnaryCall(CI, Builder, Intrinsic::rint);
David L. Jonesd21529f2017-01-23 23:16:46 +00002192 case LibFunc_trunc:
Matt Arsenault954a6242017-01-23 23:55:08 +00002193 return replaceUnaryCall(CI, Builder, Intrinsic::trunc);
David L. Jonesd21529f2017-01-23 23:16:46 +00002194 case LibFunc_acos:
2195 case LibFunc_acosh:
2196 case LibFunc_asin:
2197 case LibFunc_asinh:
2198 case LibFunc_atan:
2199 case LibFunc_atanh:
2200 case LibFunc_cbrt:
2201 case LibFunc_cosh:
2202 case LibFunc_exp:
2203 case LibFunc_exp10:
2204 case LibFunc_expm1:
2205 case LibFunc_sin:
2206 case LibFunc_sinh:
2207 case LibFunc_tanh:
Chris Bienemanad070d02014-09-17 20:55:46 +00002208 if (UnsafeFPShrink && hasFloatVersion(FuncName))
2209 return optimizeUnaryDoubleFP(CI, Builder, true);
2210 return nullptr;
David L. Jonesd21529f2017-01-23 23:16:46 +00002211 case LibFunc_copysign:
Chris Bienemanad070d02014-09-17 20:55:46 +00002212 if (hasFloatVersion(FuncName))
2213 return optimizeBinaryDoubleFP(CI, Builder);
2214 return nullptr;
David L. Jonesd21529f2017-01-23 23:16:46 +00002215 case LibFunc_fminf:
2216 case LibFunc_fmin:
2217 case LibFunc_fminl:
2218 case LibFunc_fmaxf:
2219 case LibFunc_fmax:
2220 case LibFunc_fmaxl:
Sanjay Patel57fd1dc2015-08-16 20:18:19 +00002221 return optimizeFMinFMax(CI, Builder);
Chris Bienemanad070d02014-09-17 20:55:46 +00002222 default:
2223 return nullptr;
2224 }
Meador Inge20255ef2013-03-12 00:08:29 +00002225 }
Craig Topperf40110f2014-04-25 05:29:35 +00002226 return nullptr;
Meador Ingedf796f82012-10-13 16:45:24 +00002227}
2228
Chandler Carruth92803822015-01-21 02:11:59 +00002229LibCallSimplifier::LibCallSimplifier(
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002230 const DataLayout &DL, const TargetLibraryInfo *TLI,
Chandler Carruth92803822015-01-21 02:11:59 +00002231 function_ref<void(Instruction *, Value *)> Replacer)
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002232 : FortifiedSimplifier(TLI), DL(DL), TLI(TLI), UnsafeFPShrink(false),
Chandler Carruth92803822015-01-21 02:11:59 +00002233 Replacer(Replacer) {}
2234
2235void LibCallSimplifier::replaceAllUsesWith(Instruction *I, Value *With) {
2236 // Indirect through the replacer used in this instance.
2237 Replacer(I, With);
Meador Ingedf796f82012-10-13 16:45:24 +00002238}
2239
Meador Ingedfb08a22013-06-20 19:48:07 +00002240// TODO:
2241// Additional cases that we need to add to this file:
2242//
2243// cbrt:
2244// * cbrt(expN(X)) -> expN(x/3)
2245// * cbrt(sqrt(x)) -> pow(x,1/6)
David Majnemer3354fe42015-08-26 18:30:16 +00002246// * cbrt(cbrt(x)) -> pow(x,1/9)
Meador Ingedfb08a22013-06-20 19:48:07 +00002247//
2248// exp, expf, expl:
2249// * exp(log(x)) -> x
2250//
2251// log, logf, logl:
2252// * log(exp(x)) -> x
Meador Ingedfb08a22013-06-20 19:48:07 +00002253// * log(exp(y)) -> y*log(e)
Meador Ingedfb08a22013-06-20 19:48:07 +00002254// * log(exp10(y)) -> y*log(10)
2255// * log(sqrt(x)) -> 0.5*log(x)
Meador Ingedfb08a22013-06-20 19:48:07 +00002256//
Meador Ingedfb08a22013-06-20 19:48:07 +00002257// pow, powf, powl:
Meador Ingedfb08a22013-06-20 19:48:07 +00002258// * pow(sqrt(x),y) -> pow(x,y*0.5)
2259// * pow(pow(x,y),z)-> pow(x,y*z)
2260//
Meador Ingedfb08a22013-06-20 19:48:07 +00002261// signbit:
2262// * signbit(cnst) -> cnst'
2263// * signbit(nncst) -> 0 (if pstv is a non-negative constant)
2264//
2265// sqrt, sqrtf, sqrtl:
2266// * sqrt(expN(x)) -> expN(x*0.5)
2267// * sqrt(Nroot(x)) -> pow(x,1/(2*N))
2268// * sqrt(pow(x,y)) -> pow(|x|,y*0.5)
2269//
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002270
2271//===----------------------------------------------------------------------===//
2272// Fortified Library Call Optimizations
2273//===----------------------------------------------------------------------===//
2274
2275bool FortifiedLibCallSimplifier::isFortifiedCallFoldable(CallInst *CI,
2276 unsigned ObjSizeOp,
2277 unsigned SizeOp,
2278 bool isString) {
2279 if (CI->getArgOperand(ObjSizeOp) == CI->getArgOperand(SizeOp))
2280 return true;
2281 if (ConstantInt *ObjSizeCI =
2282 dyn_cast<ConstantInt>(CI->getArgOperand(ObjSizeOp))) {
2283 if (ObjSizeCI->isAllOnesValue())
2284 return true;
2285 // If the object size wasn't -1 (unknown), bail out if we were asked to.
2286 if (OnlyLowerUnknownSize)
2287 return false;
2288 if (isString) {
2289 uint64_t Len = GetStringLength(CI->getArgOperand(SizeOp));
2290 // If the length is 0 we don't know how long it is and so we can't
2291 // remove the check.
2292 if (Len == 0)
2293 return false;
2294 return ObjSizeCI->getZExtValue() >= Len;
2295 }
2296 if (ConstantInt *SizeCI = dyn_cast<ConstantInt>(CI->getArgOperand(SizeOp)))
2297 return ObjSizeCI->getZExtValue() >= SizeCI->getZExtValue();
2298 }
2299 return false;
2300}
2301
Sanjay Pateld707db92015-12-31 16:10:49 +00002302Value *FortifiedLibCallSimplifier::optimizeMemCpyChk(CallInst *CI,
2303 IRBuilder<> &B) {
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002304 if (isFortifiedCallFoldable(CI, 3, 2, false)) {
2305 B.CreateMemCpy(CI->getArgOperand(0), CI->getArgOperand(1),
Pete Cooper67cf9a72015-11-19 05:56:52 +00002306 CI->getArgOperand(2), 1);
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002307 return CI->getArgOperand(0);
2308 }
2309 return nullptr;
2310}
2311
Sanjay Pateld707db92015-12-31 16:10:49 +00002312Value *FortifiedLibCallSimplifier::optimizeMemMoveChk(CallInst *CI,
2313 IRBuilder<> &B) {
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002314 if (isFortifiedCallFoldable(CI, 3, 2, false)) {
2315 B.CreateMemMove(CI->getArgOperand(0), CI->getArgOperand(1),
Pete Cooper67cf9a72015-11-19 05:56:52 +00002316 CI->getArgOperand(2), 1);
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002317 return CI->getArgOperand(0);
2318 }
2319 return nullptr;
2320}
2321
Sanjay Pateld707db92015-12-31 16:10:49 +00002322Value *FortifiedLibCallSimplifier::optimizeMemSetChk(CallInst *CI,
2323 IRBuilder<> &B) {
Sanjay Patel980b2802016-01-26 16:17:24 +00002324 // TODO: Try foldMallocMemset() here.
2325
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002326 if (isFortifiedCallFoldable(CI, 3, 2, false)) {
2327 Value *Val = B.CreateIntCast(CI->getArgOperand(1), B.getInt8Ty(), false);
2328 B.CreateMemSet(CI->getArgOperand(0), Val, CI->getArgOperand(2), 1);
2329 return CI->getArgOperand(0);
2330 }
2331 return nullptr;
2332}
2333
Ahmed Bougacha1ac93562015-01-27 21:52:16 +00002334Value *FortifiedLibCallSimplifier::optimizeStrpCpyChk(CallInst *CI,
2335 IRBuilder<> &B,
David L. Jonesd21529f2017-01-23 23:16:46 +00002336 LibFunc Func) {
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002337 Function *Callee = CI->getCalledFunction();
2338 StringRef Name = Callee->getName();
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002339 const DataLayout &DL = CI->getModule()->getDataLayout();
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002340 Value *Dst = CI->getArgOperand(0), *Src = CI->getArgOperand(1),
2341 *ObjSize = CI->getArgOperand(2);
2342
2343 // __stpcpy_chk(x,x,...) -> x+strlen(x)
David L. Jonesd21529f2017-01-23 23:16:46 +00002344 if (Func == LibFunc_stpcpy_chk && !OnlyLowerUnknownSize && Dst == Src) {
Sanjay Pateld3112a52016-01-19 19:46:10 +00002345 Value *StrLen = emitStrLen(Src, B, DL, TLI);
David Blaikieaa41cd52015-04-03 21:33:42 +00002346 return StrLen ? B.CreateInBoundsGEP(B.getInt8Ty(), Dst, StrLen) : nullptr;
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002347 }
2348
2349 // If a) we don't have any length information, or b) we know this will
2350 // fit then just lower to a plain st[rp]cpy. Otherwise we'll keep our
2351 // st[rp]cpy_chk call which may fail at runtime if the size is too long.
2352 // TODO: It might be nice to get a maximum length out of the possible
2353 // string lengths for varying.
David Blaikie65fab6d2015-04-03 21:32:06 +00002354 if (isFortifiedCallFoldable(CI, 2, 1, true))
Sanjay Pateld3112a52016-01-19 19:46:10 +00002355 return emitStrCpy(Dst, Src, B, TLI, Name.substr(2, 6));
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002356
David Blaikie65fab6d2015-04-03 21:32:06 +00002357 if (OnlyLowerUnknownSize)
2358 return nullptr;
2359
2360 // Maybe we can stil fold __st[rp]cpy_chk to __memcpy_chk.
2361 uint64_t Len = GetStringLength(Src);
2362 if (Len == 0)
2363 return nullptr;
2364
2365 Type *SizeTTy = DL.getIntPtrType(CI->getContext());
2366 Value *LenV = ConstantInt::get(SizeTTy, Len);
Sanjay Pateld3112a52016-01-19 19:46:10 +00002367 Value *Ret = emitMemCpyChk(Dst, Src, LenV, ObjSize, B, DL, TLI);
David Blaikie65fab6d2015-04-03 21:32:06 +00002368 // If the function was an __stpcpy_chk, and we were able to fold it into
2369 // a __memcpy_chk, we still need to return the correct end pointer.
David L. Jonesd21529f2017-01-23 23:16:46 +00002370 if (Ret && Func == LibFunc_stpcpy_chk)
David Blaikie65fab6d2015-04-03 21:32:06 +00002371 return B.CreateGEP(B.getInt8Ty(), Dst, ConstantInt::get(SizeTTy, Len - 1));
2372 return Ret;
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002373}
2374
Ahmed Bougacha1ac93562015-01-27 21:52:16 +00002375Value *FortifiedLibCallSimplifier::optimizeStrpNCpyChk(CallInst *CI,
2376 IRBuilder<> &B,
David L. Jonesd21529f2017-01-23 23:16:46 +00002377 LibFunc Func) {
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002378 Function *Callee = CI->getCalledFunction();
2379 StringRef Name = Callee->getName();
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002380 if (isFortifiedCallFoldable(CI, 3, 2, false)) {
Sanjay Pateld3112a52016-01-19 19:46:10 +00002381 Value *Ret = emitStrNCpy(CI->getArgOperand(0), CI->getArgOperand(1),
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002382 CI->getArgOperand(2), B, TLI, Name.substr(2, 7));
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002383 return Ret;
2384 }
2385 return nullptr;
2386}
2387
2388Value *FortifiedLibCallSimplifier::optimizeCall(CallInst *CI) {
Ahmed Bougacha408d0102015-04-01 00:45:09 +00002389 // FIXME: We shouldn't be changing "nobuiltin" or TLI unavailable calls here.
2390 // Some clang users checked for _chk libcall availability using:
2391 // __has_builtin(__builtin___memcpy_chk)
2392 // When compiling with -fno-builtin, this is always true.
2393 // When passing -ffreestanding/-mkernel, which both imply -fno-builtin, we
2394 // end up with fortified libcalls, which isn't acceptable in a freestanding
2395 // environment which only provides their non-fortified counterparts.
2396 //
2397 // Until we change clang and/or teach external users to check for availability
2398 // differently, disregard the "nobuiltin" attribute and TLI::has.
2399 //
2400 // PR23093.
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002401
David L. Jonesd21529f2017-01-23 23:16:46 +00002402 LibFunc Func;
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002403 Function *Callee = CI->getCalledFunction();
David Majnemerb70e23c2016-01-06 05:01:34 +00002404
2405 SmallVector<OperandBundleDef, 2> OpBundles;
2406 CI->getOperandBundlesAsDefs(OpBundles);
2407 IRBuilder<> Builder(CI, /*FPMathTag=*/nullptr, OpBundles);
Sam Parker214f7bf2016-09-13 12:10:14 +00002408 bool isCallingConvC = isCallingConvCCompatible(CI);
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002409
Ahmed Bougachad765a822016-04-27 19:04:35 +00002410 // First, check that this is a known library functions and that the prototype
2411 // is correct.
2412 if (!TLI->getLibFunc(*Callee, Func))
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002413 return nullptr;
2414
2415 // We never change the calling convention.
2416 if (!ignoreCallingConv(Func) && !isCallingConvC)
2417 return nullptr;
2418
2419 switch (Func) {
David L. Jonesd21529f2017-01-23 23:16:46 +00002420 case LibFunc_memcpy_chk:
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002421 return optimizeMemCpyChk(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002422 case LibFunc_memmove_chk:
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002423 return optimizeMemMoveChk(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002424 case LibFunc_memset_chk:
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002425 return optimizeMemSetChk(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002426 case LibFunc_stpcpy_chk:
2427 case LibFunc_strcpy_chk:
Ahmed Bougacha1ac93562015-01-27 21:52:16 +00002428 return optimizeStrpCpyChk(CI, Builder, Func);
David L. Jonesd21529f2017-01-23 23:16:46 +00002429 case LibFunc_stpncpy_chk:
2430 case LibFunc_strncpy_chk:
Ahmed Bougacha1ac93562015-01-27 21:52:16 +00002431 return optimizeStrpNCpyChk(CI, Builder, Func);
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002432 default:
2433 break;
2434 }
2435 return nullptr;
2436}
2437
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002438FortifiedLibCallSimplifier::FortifiedLibCallSimplifier(
2439 const TargetLibraryInfo *TLI, bool OnlyLowerUnknownSize)
2440 : TLI(TLI), OnlyLowerUnknownSize(OnlyLowerUnknownSize) {}