blob: 685922cb634c6230259b8bbf0788ae4574aa893f [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//
Craig Topper2915bc02018-03-01 20:05:09 +000010// This file implements the library calls simplifier. It does not implement
11// any pass, but can't be used by other passes to do simplifications.
Meador Ingedf796f82012-10-13 16:45:24 +000012//
13//===----------------------------------------------------------------------===//
14
15#include "llvm/Transforms/Utils/SimplifyLibCalls.h"
Meador Inge20255ef2013-03-12 00:08:29 +000016#include "llvm/ADT/SmallString.h"
Meador Ingedf796f82012-10-13 16:45:24 +000017#include "llvm/ADT/StringMap.h"
Bob Wilsond8d92d92013-11-03 06:48:38 +000018#include "llvm/ADT/Triple.h"
Sanjay Patel82ec8722017-08-21 19:13:14 +000019#include "llvm/Analysis/ConstantFolding.h"
Adam Nemet0965da22017-10-09 23:19:02 +000020#include "llvm/Analysis/OptimizationRemarkEmitter.h"
Weiming Zhao45d4cb92015-11-24 18:57:06 +000021#include "llvm/Analysis/TargetLibraryInfo.h"
David Blaikie2be39222018-03-21 22:34:23 +000022#include "llvm/Analysis/Utils/Local.h"
Meador Ingedf796f82012-10-13 16:45:24 +000023#include "llvm/Analysis/ValueTracking.h"
David Bolvanskyca22d422018-05-16 11:39:52 +000024#include "llvm/Analysis/CaptureTracking.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000025#include "llvm/IR/DataLayout.h"
26#include "llvm/IR/Function.h"
27#include "llvm/IR/IRBuilder.h"
Meador Inge20255ef2013-03-12 00:08:29 +000028#include "llvm/IR/IntrinsicInst.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000029#include "llvm/IR/Intrinsics.h"
30#include "llvm/IR/LLVMContext.h"
31#include "llvm/IR/Module.h"
Sanjay Patelc699a612014-10-16 18:48:17 +000032#include "llvm/IR/PatternMatch.h"
Hal Finkel66cd3f12013-11-17 02:06:35 +000033#include "llvm/Support/CommandLine.h"
Craig Topperb45eabc2017-04-26 16:39:58 +000034#include "llvm/Support/KnownBits.h"
Meador Ingedf796f82012-10-13 16:45:24 +000035#include "llvm/Transforms/Utils/BuildLibCalls.h"
36
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
David Bolvanskycb8ca5f32018-04-25 18:58:53 +0000106static Value *convertStrToNumber(CallInst *CI, StringRef &Str, int64_t Base) {
107 if (Base < 2 || Base > 36)
108 // handle special zero base
109 if (Base != 0)
110 return nullptr;
111
112 char *End;
113 std::string nptr = Str.str();
114 errno = 0;
115 long long int Result = strtoll(nptr.c_str(), &End, Base);
116 if (errno)
117 return nullptr;
118
119 // if we assume all possible target locales are ASCII supersets,
120 // then if strtoll successfully parses a number on the host,
121 // it will also successfully parse the same way on the target
122 if (*End != '\0')
123 return nullptr;
124
125 if (!isIntN(CI->getType()->getPrimitiveSizeInBits(), Result))
126 return nullptr;
127
128 return ConstantInt::get(CI->getType(), Result);
129}
130
David Bolvanskyca22d422018-05-16 11:39:52 +0000131static bool isLocallyOpenedFile(Value *File, CallInst *CI, IRBuilder<> &B,
132 const TargetLibraryInfo *TLI) {
133 CallInst *FOpen = dyn_cast<CallInst>(File);
134 if (!FOpen)
135 return false;
136
137 Function *InnerCallee = FOpen->getCalledFunction();
138 if (!InnerCallee)
139 return false;
140
141 LibFunc Func;
142 if (!TLI->getLibFunc(*InnerCallee, Func) || !TLI->has(Func) ||
143 Func != LibFunc_fopen)
144 return false;
145
146 inferLibFuncAttributes(*CI->getCalledFunction(), *TLI);
147 if (PointerMayBeCaptured(File, true, true))
148 return false;
149
150 return true;
151}
152
Meador Inged589ac62012-10-31 03:33:06 +0000153//===----------------------------------------------------------------------===//
Meador Inge7fb2f732012-10-13 16:45:32 +0000154// String and Memory Library Call Optimizations
155//===----------------------------------------------------------------------===//
156
Chris Bienemanad070d02014-09-17 20:55:46 +0000157Value *LibCallSimplifier::optimizeStrCat(CallInst *CI, IRBuilder<> &B) {
Chris Bienemanad070d02014-09-17 20:55:46 +0000158 // Extract some information from the instruction
159 Value *Dst = CI->getArgOperand(0);
160 Value *Src = CI->getArgOperand(1);
161
162 // See if we can get the length of the input string.
David Bolvansky1f343fa2018-05-22 20:27:36 +0000163 uint64_t Len = GetStringLength(Src);
Chris Bienemanad070d02014-09-17 20:55:46 +0000164 if (Len == 0)
165 return nullptr;
166 --Len; // Unbias length.
167
168 // Handle the simple, do-nothing case: strcat(x, "") -> x
169 if (Len == 0)
170 return Dst;
171
Chris Bienemanad070d02014-09-17 20:55:46 +0000172 return emitStrLenMemCpy(Src, Dst, Len, B);
173}
174
175Value *LibCallSimplifier::emitStrLenMemCpy(Value *Src, Value *Dst, uint64_t Len,
176 IRBuilder<> &B) {
177 // We need to find the end of the destination string. That's where the
178 // memory is to be moved to. We just generate a call to strlen.
Sanjay Pateld3112a52016-01-19 19:46:10 +0000179 Value *DstLen = emitStrLen(Dst, B, DL, TLI);
Chris Bienemanad070d02014-09-17 20:55:46 +0000180 if (!DstLen)
181 return nullptr;
182
183 // Now that we have the destination's length, we must index into the
184 // destination's pointer to get the actual memcpy destination (end of
185 // the string .. we're concatenating).
David Blaikie3909da72015-03-30 20:42:56 +0000186 Value *CpyDst = B.CreateGEP(B.getInt8Ty(), Dst, DstLen, "endptr");
Chris Bienemanad070d02014-09-17 20:55:46 +0000187
188 // We have enough information to now generate the memcpy call to do the
189 // concatenation for us. Make a memcpy to copy the nul byte with align = 1.
Daniel Neilson8acd8b02018-02-05 21:23:22 +0000190 B.CreateMemCpy(CpyDst, 1, Src, 1,
191 ConstantInt::get(DL.getIntPtrType(Src->getContext()), Len + 1));
Chris Bienemanad070d02014-09-17 20:55:46 +0000192 return Dst;
193}
194
195Value *LibCallSimplifier::optimizeStrNCat(CallInst *CI, IRBuilder<> &B) {
Sanjay Pateld707db92015-12-31 16:10:49 +0000196 // Extract some information from the instruction.
Chris Bienemanad070d02014-09-17 20:55:46 +0000197 Value *Dst = CI->getArgOperand(0);
198 Value *Src = CI->getArgOperand(1);
199 uint64_t Len;
200
Sanjay Pateld707db92015-12-31 16:10:49 +0000201 // We don't do anything if length is not constant.
Chris Bienemanad070d02014-09-17 20:55:46 +0000202 if (ConstantInt *LengthArg = dyn_cast<ConstantInt>(CI->getArgOperand(2)))
203 Len = LengthArg->getZExtValue();
204 else
205 return nullptr;
206
207 // See if we can get the length of the input string.
David Bolvansky1f343fa2018-05-22 20:27:36 +0000208 uint64_t SrcLen = GetStringLength(Src);
Chris Bienemanad070d02014-09-17 20:55:46 +0000209 if (SrcLen == 0)
210 return nullptr;
211 --SrcLen; // Unbias length.
212
213 // Handle the simple, do-nothing cases:
214 // strncat(x, "", c) -> x
215 // strncat(x, c, 0) -> x
216 if (SrcLen == 0 || Len == 0)
217 return Dst;
218
Sanjay Pateld707db92015-12-31 16:10:49 +0000219 // We don't optimize this case.
Chris Bienemanad070d02014-09-17 20:55:46 +0000220 if (Len < SrcLen)
221 return nullptr;
222
223 // strncat(x, s, c) -> strcat(x, s)
Sanjay Pateld707db92015-12-31 16:10:49 +0000224 // s is constant so the strcat can be optimized further.
Chris Bienemanad070d02014-09-17 20:55:46 +0000225 return emitStrLenMemCpy(Src, Dst, SrcLen, B);
226}
227
228Value *LibCallSimplifier::optimizeStrChr(CallInst *CI, IRBuilder<> &B) {
229 Function *Callee = CI->getCalledFunction();
Chris Bienemanad070d02014-09-17 20:55:46 +0000230 FunctionType *FT = Callee->getFunctionType();
Chris Bienemanad070d02014-09-17 20:55:46 +0000231 Value *SrcStr = CI->getArgOperand(0);
232
233 // If the second operand is non-constant, see if we can compute the length
234 // of the input string and turn this into memchr.
235 ConstantInt *CharC = dyn_cast<ConstantInt>(CI->getArgOperand(1));
236 if (!CharC) {
David Bolvansky1f343fa2018-05-22 20:27:36 +0000237 uint64_t Len = GetStringLength(SrcStr);
Chris Bienemanad070d02014-09-17 20:55:46 +0000238 if (Len == 0 || !FT->getParamType(1)->isIntegerTy(32)) // memchr needs i32.
239 return nullptr;
Meador Inge7fb2f732012-10-13 16:45:32 +0000240
Sanjay Pateld3112a52016-01-19 19:46:10 +0000241 return emitMemChr(SrcStr, CI->getArgOperand(1), // include nul.
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000242 ConstantInt::get(DL.getIntPtrType(CI->getContext()), Len),
243 B, DL, TLI);
Meador Inge7fb2f732012-10-13 16:45:32 +0000244 }
245
Chris Bienemanad070d02014-09-17 20:55:46 +0000246 // Otherwise, the character is a constant, see if the first argument is
247 // a string literal. If so, we can constant fold.
248 StringRef Str;
249 if (!getConstantStringInfo(SrcStr, Str)) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000250 if (CharC->isZero()) // strchr(p, 0) -> p + strlen(p)
Sanjay Pateld3112a52016-01-19 19:46:10 +0000251 return B.CreateGEP(B.getInt8Ty(), SrcStr, emitStrLen(SrcStr, B, DL, TLI),
Sanjay Pateld707db92015-12-31 16:10:49 +0000252 "strchr");
Chris Bienemanad070d02014-09-17 20:55:46 +0000253 return nullptr;
254 }
255
256 // Compute the offset, make sure to handle the case when we're searching for
257 // zero (a weird way to spell strlen).
258 size_t I = (0xFF & CharC->getSExtValue()) == 0
259 ? Str.size()
260 : Str.find(CharC->getSExtValue());
261 if (I == StringRef::npos) // Didn't find the char. strchr returns null.
262 return Constant::getNullValue(CI->getType());
263
264 // strchr(s+n,c) -> gep(s+n+i,c)
David Blaikie3909da72015-03-30 20:42:56 +0000265 return B.CreateGEP(B.getInt8Ty(), SrcStr, B.getInt64(I), "strchr");
Chris Bienemanad070d02014-09-17 20:55:46 +0000266}
267
268Value *LibCallSimplifier::optimizeStrRChr(CallInst *CI, IRBuilder<> &B) {
Chris Bienemanad070d02014-09-17 20:55:46 +0000269 Value *SrcStr = CI->getArgOperand(0);
270 ConstantInt *CharC = dyn_cast<ConstantInt>(CI->getArgOperand(1));
271
272 // Cannot fold anything if we're not looking for a constant.
273 if (!CharC)
274 return nullptr;
275
276 StringRef Str;
277 if (!getConstantStringInfo(SrcStr, Str)) {
278 // strrchr(s, 0) -> strchr(s, 0)
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000279 if (CharC->isZero())
Sanjay Pateld3112a52016-01-19 19:46:10 +0000280 return emitStrChr(SrcStr, '\0', B, TLI);
Chris Bienemanad070d02014-09-17 20:55:46 +0000281 return nullptr;
282 }
283
284 // Compute the offset.
285 size_t I = (0xFF & CharC->getSExtValue()) == 0
286 ? Str.size()
287 : Str.rfind(CharC->getSExtValue());
288 if (I == StringRef::npos) // Didn't find the char. Return null.
289 return Constant::getNullValue(CI->getType());
290
291 // strrchr(s+n,c) -> gep(s+n+i,c)
David Blaikie3909da72015-03-30 20:42:56 +0000292 return B.CreateGEP(B.getInt8Ty(), SrcStr, B.getInt64(I), "strrchr");
Chris Bienemanad070d02014-09-17 20:55:46 +0000293}
294
295Value *LibCallSimplifier::optimizeStrCmp(CallInst *CI, IRBuilder<> &B) {
Chris Bienemanad070d02014-09-17 20:55:46 +0000296 Value *Str1P = CI->getArgOperand(0), *Str2P = CI->getArgOperand(1);
297 if (Str1P == Str2P) // strcmp(x,x) -> 0
298 return ConstantInt::get(CI->getType(), 0);
299
300 StringRef Str1, Str2;
301 bool HasStr1 = getConstantStringInfo(Str1P, Str1);
302 bool HasStr2 = getConstantStringInfo(Str2P, Str2);
303
304 // strcmp(x, y) -> cnst (if both x and y are constant strings)
305 if (HasStr1 && HasStr2)
306 return ConstantInt::get(CI->getType(), Str1.compare(Str2));
307
308 if (HasStr1 && Str1.empty()) // strcmp("", x) -> -*x
309 return B.CreateNeg(
310 B.CreateZExt(B.CreateLoad(Str2P, "strcmpload"), CI->getType()));
311
312 if (HasStr2 && Str2.empty()) // strcmp(x,"") -> *x
313 return B.CreateZExt(B.CreateLoad(Str1P, "strcmpload"), CI->getType());
314
315 // strcmp(P, "x") -> memcmp(P, "x", 2)
David Bolvansky1f343fa2018-05-22 20:27:36 +0000316 uint64_t Len1 = GetStringLength(Str1P);
317 uint64_t Len2 = GetStringLength(Str2P);
Chris Bienemanad070d02014-09-17 20:55:46 +0000318 if (Len1 && Len2) {
Sanjay Pateld3112a52016-01-19 19:46:10 +0000319 return emitMemCmp(Str1P, Str2P,
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000320 ConstantInt::get(DL.getIntPtrType(CI->getContext()),
Chris Bienemanad070d02014-09-17 20:55:46 +0000321 std::min(Len1, Len2)),
322 B, DL, TLI);
323 }
Meador Inge7fb2f732012-10-13 16:45:32 +0000324
Chris Bienemanad070d02014-09-17 20:55:46 +0000325 return nullptr;
326}
327
328Value *LibCallSimplifier::optimizeStrNCmp(CallInst *CI, IRBuilder<> &B) {
Chris Bienemanad070d02014-09-17 20:55:46 +0000329 Value *Str1P = CI->getArgOperand(0), *Str2P = CI->getArgOperand(1);
330 if (Str1P == Str2P) // strncmp(x,x,n) -> 0
331 return ConstantInt::get(CI->getType(), 0);
332
333 // Get the length argument if it is constant.
334 uint64_t Length;
335 if (ConstantInt *LengthArg = dyn_cast<ConstantInt>(CI->getArgOperand(2)))
336 Length = LengthArg->getZExtValue();
337 else
338 return nullptr;
339
340 if (Length == 0) // strncmp(x,y,0) -> 0
341 return ConstantInt::get(CI->getType(), 0);
342
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000343 if (Length == 1) // strncmp(x,y,1) -> memcmp(x,y,1)
Sanjay Pateld3112a52016-01-19 19:46:10 +0000344 return emitMemCmp(Str1P, Str2P, CI->getArgOperand(2), B, DL, TLI);
Chris Bienemanad070d02014-09-17 20:55:46 +0000345
346 StringRef Str1, Str2;
347 bool HasStr1 = getConstantStringInfo(Str1P, Str1);
348 bool HasStr2 = getConstantStringInfo(Str2P, Str2);
349
350 // strncmp(x, y) -> cnst (if both x and y are constant strings)
351 if (HasStr1 && HasStr2) {
352 StringRef SubStr1 = Str1.substr(0, Length);
353 StringRef SubStr2 = Str2.substr(0, Length);
354 return ConstantInt::get(CI->getType(), SubStr1.compare(SubStr2));
355 }
356
357 if (HasStr1 && Str1.empty()) // strncmp("", x, n) -> -*x
358 return B.CreateNeg(
359 B.CreateZExt(B.CreateLoad(Str2P, "strcmpload"), CI->getType()));
360
361 if (HasStr2 && Str2.empty()) // strncmp(x, "", n) -> *x
362 return B.CreateZExt(B.CreateLoad(Str1P, "strcmpload"), CI->getType());
363
364 return nullptr;
365}
366
367Value *LibCallSimplifier::optimizeStrCpy(CallInst *CI, IRBuilder<> &B) {
Chris Bienemanad070d02014-09-17 20:55:46 +0000368 Value *Dst = CI->getArgOperand(0), *Src = CI->getArgOperand(1);
369 if (Dst == Src) // strcpy(x,x) -> x
370 return Src;
371
Chris Bienemanad070d02014-09-17 20:55:46 +0000372 // See if we can get the length of the input string.
David Bolvansky1f343fa2018-05-22 20:27:36 +0000373 uint64_t Len = GetStringLength(Src);
Chris Bienemanad070d02014-09-17 20:55:46 +0000374 if (Len == 0)
375 return nullptr;
376
377 // We have enough information to now generate the memcpy call to do the
378 // copy for us. Make a memcpy to copy the nul byte with align = 1.
Daniel Neilson8acd8b02018-02-05 21:23:22 +0000379 B.CreateMemCpy(Dst, 1, Src, 1,
380 ConstantInt::get(DL.getIntPtrType(CI->getContext()), Len));
Chris Bienemanad070d02014-09-17 20:55:46 +0000381 return Dst;
382}
383
384Value *LibCallSimplifier::optimizeStpCpy(CallInst *CI, IRBuilder<> &B) {
385 Function *Callee = CI->getCalledFunction();
Chris Bienemanad070d02014-09-17 20:55:46 +0000386 Value *Dst = CI->getArgOperand(0), *Src = CI->getArgOperand(1);
387 if (Dst == Src) { // stpcpy(x,x) -> x+strlen(x)
Sanjay Pateld3112a52016-01-19 19:46:10 +0000388 Value *StrLen = emitStrLen(Src, B, DL, TLI);
David Blaikieaa41cd52015-04-03 21:33:42 +0000389 return StrLen ? B.CreateInBoundsGEP(B.getInt8Ty(), Dst, StrLen) : nullptr;
Chris Bienemanad070d02014-09-17 20:55:46 +0000390 }
391
392 // See if we can get the length of the input string.
David Bolvansky1f343fa2018-05-22 20:27:36 +0000393 uint64_t Len = GetStringLength(Src);
Chris Bienemanad070d02014-09-17 20:55:46 +0000394 if (Len == 0)
395 return nullptr;
396
Davide Italianob7487e62015-11-02 23:07:14 +0000397 Type *PT = Callee->getFunctionType()->getParamType(0);
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000398 Value *LenV = ConstantInt::get(DL.getIntPtrType(PT), Len);
Sanjay Pateld707db92015-12-31 16:10:49 +0000399 Value *DstEnd = B.CreateGEP(B.getInt8Ty(), Dst,
400 ConstantInt::get(DL.getIntPtrType(PT), Len - 1));
Chris Bienemanad070d02014-09-17 20:55:46 +0000401
402 // We have enough information to now generate the memcpy call to do the
403 // copy for us. Make a memcpy to copy the nul byte with align = 1.
Daniel Neilson8acd8b02018-02-05 21:23:22 +0000404 B.CreateMemCpy(Dst, 1, Src, 1, LenV);
Chris Bienemanad070d02014-09-17 20:55:46 +0000405 return DstEnd;
406}
407
408Value *LibCallSimplifier::optimizeStrNCpy(CallInst *CI, IRBuilder<> &B) {
409 Function *Callee = CI->getCalledFunction();
Chris Bienemanad070d02014-09-17 20:55:46 +0000410 Value *Dst = CI->getArgOperand(0);
411 Value *Src = CI->getArgOperand(1);
412 Value *LenOp = CI->getArgOperand(2);
413
414 // See if we can get the length of the input string.
David Bolvansky1f343fa2018-05-22 20:27:36 +0000415 uint64_t SrcLen = GetStringLength(Src);
Chris Bienemanad070d02014-09-17 20:55:46 +0000416 if (SrcLen == 0)
417 return nullptr;
418 --SrcLen;
419
420 if (SrcLen == 0) {
Daniel Neilson8acd8b02018-02-05 21:23:22 +0000421 // strncpy(x, "", y) -> memset(align 1 x, '\0', y)
Chris Bienemanad070d02014-09-17 20:55:46 +0000422 B.CreateMemSet(Dst, B.getInt8('\0'), LenOp, 1);
Meador Inge7fb2f732012-10-13 16:45:32 +0000423 return Dst;
424 }
Meador Inge7fb2f732012-10-13 16:45:32 +0000425
Chris Bienemanad070d02014-09-17 20:55:46 +0000426 uint64_t Len;
427 if (ConstantInt *LengthArg = dyn_cast<ConstantInt>(LenOp))
428 Len = LengthArg->getZExtValue();
429 else
430 return nullptr;
Meador Inge7fb2f732012-10-13 16:45:32 +0000431
Chris Bienemanad070d02014-09-17 20:55:46 +0000432 if (Len == 0)
433 return Dst; // strncpy(x, y, 0) -> x
Meador Inge7fb2f732012-10-13 16:45:32 +0000434
Chris Bienemanad070d02014-09-17 20:55:46 +0000435 // Let strncpy handle the zero padding
436 if (Len > SrcLen + 1)
437 return nullptr;
Meador Inge7fb2f732012-10-13 16:45:32 +0000438
Davide Italianob7487e62015-11-02 23:07:14 +0000439 Type *PT = Callee->getFunctionType()->getParamType(0);
Daniel Neilson8acd8b02018-02-05 21:23:22 +0000440 // strncpy(x, s, c) -> memcpy(align 1 x, align 1 s, c) [s and c are constant]
441 B.CreateMemCpy(Dst, 1, Src, 1, ConstantInt::get(DL.getIntPtrType(PT), Len));
Meador Inge7fb2f732012-10-13 16:45:32 +0000442
Chris Bienemanad070d02014-09-17 20:55:46 +0000443 return Dst;
444}
Meador Inge7fb2f732012-10-13 16:45:32 +0000445
Matthias Braun50ec0b52017-05-19 22:37:09 +0000446Value *LibCallSimplifier::optimizeStringLength(CallInst *CI, IRBuilder<> &B,
447 unsigned CharSize) {
Chris Bienemanad070d02014-09-17 20:55:46 +0000448 Value *Src = CI->getArgOperand(0);
449
450 // Constant folding: strlen("xyz") -> 3
David Bolvansky1f343fa2018-05-22 20:27:36 +0000451 if (uint64_t Len = GetStringLength(Src, CharSize))
Chris Bienemanad070d02014-09-17 20:55:46 +0000452 return ConstantInt::get(CI->getType(), Len - 1);
453
David L Kreitzer752c1442016-04-13 14:31:06 +0000454 // If s is a constant pointer pointing to a string literal, we can fold
Matthias Braun50ec0b52017-05-19 22:37:09 +0000455 // strlen(s + x) to strlen(s) - x, when x is known to be in the range
David L Kreitzer752c1442016-04-13 14:31:06 +0000456 // [0, strlen(s)] or the string has a single null terminator '\0' at the end.
Matthias Braun50ec0b52017-05-19 22:37:09 +0000457 // We only try to simplify strlen when the pointer s points to an array
David L Kreitzer752c1442016-04-13 14:31:06 +0000458 // of i8. Otherwise, we would need to scale the offset x before doing the
Matthias Braun50ec0b52017-05-19 22:37:09 +0000459 // subtraction. This will make the optimization more complex, and it's not
460 // very useful because calling strlen for a pointer of other types is
David L Kreitzer752c1442016-04-13 14:31:06 +0000461 // very uncommon.
462 if (GEPOperator *GEP = dyn_cast<GEPOperator>(Src)) {
Matthias Braun50ec0b52017-05-19 22:37:09 +0000463 if (!isGEPBasedOnPointerToString(GEP, CharSize))
David L Kreitzer752c1442016-04-13 14:31:06 +0000464 return nullptr;
465
Matthias Braun50ec0b52017-05-19 22:37:09 +0000466 ConstantDataArraySlice Slice;
467 if (getConstantDataArrayInfo(GEP->getOperand(0), Slice, CharSize)) {
468 uint64_t NullTermIdx;
469 if (Slice.Array == nullptr) {
470 NullTermIdx = 0;
471 } else {
472 NullTermIdx = ~((uint64_t)0);
473 for (uint64_t I = 0, E = Slice.Length; I < E; ++I) {
474 if (Slice.Array->getElementAsInteger(I + Slice.Offset) == 0) {
475 NullTermIdx = I;
476 break;
477 }
478 }
479 // If the string does not have '\0', leave it to strlen to compute
480 // its length.
481 if (NullTermIdx == ~((uint64_t)0))
482 return nullptr;
483 }
484
David L Kreitzer752c1442016-04-13 14:31:06 +0000485 Value *Offset = GEP->getOperand(2);
Craig Topper8205a1a2017-05-24 16:53:07 +0000486 KnownBits Known = computeKnownBits(Offset, DL, 0, nullptr, CI, nullptr);
Craig Topperb45eabc2017-04-26 16:39:58 +0000487 Known.Zero.flipAllBits();
Matthias Braun50ec0b52017-05-19 22:37:09 +0000488 uint64_t ArrSize =
David L Kreitzer752c1442016-04-13 14:31:06 +0000489 cast<ArrayType>(GEP->getSourceElementType())->getNumElements();
490
Matthias Braun50ec0b52017-05-19 22:37:09 +0000491 // KnownZero's bits are flipped, so zeros in KnownZero now represent
492 // bits known to be zeros in Offset, and ones in KnowZero represent
David L Kreitzer752c1442016-04-13 14:31:06 +0000493 // bits unknown in Offset. Therefore, Offset is known to be in range
Matthias Braun50ec0b52017-05-19 22:37:09 +0000494 // [0, NullTermIdx] when the flipped KnownZero is non-negative and
David L Kreitzer752c1442016-04-13 14:31:06 +0000495 // unsigned-less-than NullTermIdx.
496 //
Matthias Braun50ec0b52017-05-19 22:37:09 +0000497 // If Offset is not provably in the range [0, NullTermIdx], we can still
498 // optimize if we can prove that the program has undefined behavior when
499 // Offset is outside that range. That is the case when GEP->getOperand(0)
David L Kreitzer752c1442016-04-13 14:31:06 +0000500 // is a pointer to an object whose memory extent is NullTermIdx+1.
Matthias Braun50ec0b52017-05-19 22:37:09 +0000501 if ((Known.Zero.isNonNegative() && Known.Zero.ule(NullTermIdx)) ||
David L Kreitzer752c1442016-04-13 14:31:06 +0000502 (GEP->isInBounds() && isa<GlobalVariable>(GEP->getOperand(0)) &&
Matthias Braun50ec0b52017-05-19 22:37:09 +0000503 NullTermIdx == ArrSize - 1)) {
504 Offset = B.CreateSExtOrTrunc(Offset, CI->getType());
505 return B.CreateSub(ConstantInt::get(CI->getType(), NullTermIdx),
David L Kreitzer752c1442016-04-13 14:31:06 +0000506 Offset);
Matthias Braun50ec0b52017-05-19 22:37:09 +0000507 }
David L Kreitzer752c1442016-04-13 14:31:06 +0000508 }
509
510 return nullptr;
511 }
512
Chris Bienemanad070d02014-09-17 20:55:46 +0000513 // strlen(x?"foo":"bars") --> x ? 3 : 4
514 if (SelectInst *SI = dyn_cast<SelectInst>(Src)) {
David Bolvansky1f343fa2018-05-22 20:27:36 +0000515 uint64_t LenTrue = GetStringLength(SI->getTrueValue(), CharSize);
516 uint64_t LenFalse = GetStringLength(SI->getFalseValue(), CharSize);
Chris Bienemanad070d02014-09-17 20:55:46 +0000517 if (LenTrue && LenFalse) {
Vivek Pandya95906582017-10-11 17:12:59 +0000518 ORE.emit([&]() {
519 return OptimizationRemark("instcombine", "simplify-libcalls", CI)
520 << "folded strlen(select) to select of constants";
521 });
Chris Bienemanad070d02014-09-17 20:55:46 +0000522 return B.CreateSelect(SI->getCondition(),
523 ConstantInt::get(CI->getType(), LenTrue - 1),
524 ConstantInt::get(CI->getType(), LenFalse - 1));
525 }
Meador Inge7fb2f732012-10-13 16:45:32 +0000526 }
Meador Inge7fb2f732012-10-13 16:45:32 +0000527
Chris Bienemanad070d02014-09-17 20:55:46 +0000528 // strlen(x) != 0 --> *x != 0
529 // strlen(x) == 0 --> *x == 0
530 if (isOnlyUsedInZeroEqualityComparison(CI))
531 return B.CreateZExt(B.CreateLoad(Src, "strlenfirst"), CI->getType());
Meador Inge17418502012-10-13 16:45:37 +0000532
Chris Bienemanad070d02014-09-17 20:55:46 +0000533 return nullptr;
534}
Meador Inge17418502012-10-13 16:45:37 +0000535
Matthias Braun50ec0b52017-05-19 22:37:09 +0000536Value *LibCallSimplifier::optimizeStrLen(CallInst *CI, IRBuilder<> &B) {
537 return optimizeStringLength(CI, B, 8);
538}
539
540Value *LibCallSimplifier::optimizeWcslen(CallInst *CI, IRBuilder<> &B) {
David Bolvansky5430b7372018-05-31 16:39:27 +0000541 Module &M = *CI->getModule();
Matthias Braun50ec0b52017-05-19 22:37:09 +0000542 unsigned WCharSize = TLI->getWCharSize(M) * 8;
Matthias Brauncc603ee2017-09-26 02:36:57 +0000543 // We cannot perform this optimization without wchar_size metadata.
544 if (WCharSize == 0)
545 return nullptr;
Matthias Braun50ec0b52017-05-19 22:37:09 +0000546
547 return optimizeStringLength(CI, B, WCharSize);
548}
549
Chris Bienemanad070d02014-09-17 20:55:46 +0000550Value *LibCallSimplifier::optimizeStrPBrk(CallInst *CI, IRBuilder<> &B) {
Chris Bienemanad070d02014-09-17 20:55:46 +0000551 StringRef S1, S2;
552 bool HasS1 = getConstantStringInfo(CI->getArgOperand(0), S1);
553 bool HasS2 = getConstantStringInfo(CI->getArgOperand(1), S2);
Meador Inge17418502012-10-13 16:45:37 +0000554
Reid Kleckner971c3ea2014-11-13 22:55:19 +0000555 // strpbrk(s, "") -> nullptr
556 // strpbrk("", s) -> nullptr
Chris Bienemanad070d02014-09-17 20:55:46 +0000557 if ((HasS1 && S1.empty()) || (HasS2 && S2.empty()))
558 return Constant::getNullValue(CI->getType());
Meador Inge17418502012-10-13 16:45:37 +0000559
Chris Bienemanad070d02014-09-17 20:55:46 +0000560 // Constant folding.
561 if (HasS1 && HasS2) {
562 size_t I = S1.find_first_of(S2);
563 if (I == StringRef::npos) // No match.
Meador Inge17418502012-10-13 16:45:37 +0000564 return Constant::getNullValue(CI->getType());
565
Sanjay Pateld707db92015-12-31 16:10:49 +0000566 return B.CreateGEP(B.getInt8Ty(), CI->getArgOperand(0), B.getInt64(I),
567 "strpbrk");
Meador Inge17418502012-10-13 16:45:37 +0000568 }
Meador Inge17418502012-10-13 16:45:37 +0000569
Chris Bienemanad070d02014-09-17 20:55:46 +0000570 // strpbrk(s, "a") -> strchr(s, 'a')
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000571 if (HasS2 && S2.size() == 1)
Sanjay Pateld3112a52016-01-19 19:46:10 +0000572 return emitStrChr(CI->getArgOperand(0), S2[0], B, TLI);
Chris Bienemanad070d02014-09-17 20:55:46 +0000573
574 return nullptr;
575}
576
577Value *LibCallSimplifier::optimizeStrTo(CallInst *CI, IRBuilder<> &B) {
Chris Bienemanad070d02014-09-17 20:55:46 +0000578 Value *EndPtr = CI->getArgOperand(1);
579 if (isa<ConstantPointerNull>(EndPtr)) {
580 // With a null EndPtr, this function won't capture the main argument.
581 // It would be readonly too, except that it still may write to errno.
Reid Klecknera0b45f42017-05-03 18:17:31 +0000582 CI->addParamAttr(0, Attribute::NoCapture);
Chris Bienemanad070d02014-09-17 20:55:46 +0000583 }
584
585 return nullptr;
586}
587
588Value *LibCallSimplifier::optimizeStrSpn(CallInst *CI, IRBuilder<> &B) {
Chris Bienemanad070d02014-09-17 20:55:46 +0000589 StringRef S1, S2;
590 bool HasS1 = getConstantStringInfo(CI->getArgOperand(0), S1);
591 bool HasS2 = getConstantStringInfo(CI->getArgOperand(1), S2);
592
593 // strspn(s, "") -> 0
594 // strspn("", s) -> 0
595 if ((HasS1 && S1.empty()) || (HasS2 && S2.empty()))
596 return Constant::getNullValue(CI->getType());
597
598 // Constant folding.
599 if (HasS1 && HasS2) {
600 size_t Pos = S1.find_first_not_of(S2);
601 if (Pos == StringRef::npos)
602 Pos = S1.size();
603 return ConstantInt::get(CI->getType(), Pos);
604 }
605
606 return nullptr;
607}
608
609Value *LibCallSimplifier::optimizeStrCSpn(CallInst *CI, IRBuilder<> &B) {
Chris Bienemanad070d02014-09-17 20:55:46 +0000610 StringRef S1, S2;
611 bool HasS1 = getConstantStringInfo(CI->getArgOperand(0), S1);
612 bool HasS2 = getConstantStringInfo(CI->getArgOperand(1), S2);
613
614 // strcspn("", s) -> 0
615 if (HasS1 && S1.empty())
616 return Constant::getNullValue(CI->getType());
617
618 // Constant folding.
619 if (HasS1 && HasS2) {
620 size_t Pos = S1.find_first_of(S2);
621 if (Pos == StringRef::npos)
622 Pos = S1.size();
623 return ConstantInt::get(CI->getType(), Pos);
624 }
625
626 // strcspn(s, "") -> strlen(s)
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000627 if (HasS2 && S2.empty())
Sanjay Pateld3112a52016-01-19 19:46:10 +0000628 return emitStrLen(CI->getArgOperand(0), B, DL, TLI);
Chris Bienemanad070d02014-09-17 20:55:46 +0000629
630 return nullptr;
631}
632
633Value *LibCallSimplifier::optimizeStrStr(CallInst *CI, IRBuilder<> &B) {
Chris Bienemanad070d02014-09-17 20:55:46 +0000634 // fold strstr(x, x) -> x.
635 if (CI->getArgOperand(0) == CI->getArgOperand(1))
636 return B.CreateBitCast(CI->getArgOperand(0), CI->getType());
637
638 // fold strstr(a, b) == a -> strncmp(a, b, strlen(b)) == 0
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000639 if (isOnlyUsedInEqualityComparison(CI, CI->getArgOperand(0))) {
Sanjay Pateld3112a52016-01-19 19:46:10 +0000640 Value *StrLen = emitStrLen(CI->getArgOperand(1), B, DL, TLI);
Chris Bienemanad070d02014-09-17 20:55:46 +0000641 if (!StrLen)
Craig Topperf40110f2014-04-25 05:29:35 +0000642 return nullptr;
Sanjay Pateld3112a52016-01-19 19:46:10 +0000643 Value *StrNCmp = emitStrNCmp(CI->getArgOperand(0), CI->getArgOperand(1),
Chris Bienemanad070d02014-09-17 20:55:46 +0000644 StrLen, B, DL, TLI);
645 if (!StrNCmp)
Craig Topperf40110f2014-04-25 05:29:35 +0000646 return nullptr;
Chris Bienemanad070d02014-09-17 20:55:46 +0000647 for (auto UI = CI->user_begin(), UE = CI->user_end(); UI != UE;) {
648 ICmpInst *Old = cast<ICmpInst>(*UI++);
649 Value *Cmp =
650 B.CreateICmp(Old->getPredicate(), StrNCmp,
651 ConstantInt::getNullValue(StrNCmp->getType()), "cmp");
652 replaceAllUsesWith(Old, Cmp);
Meador Inge17418502012-10-13 16:45:37 +0000653 }
Chris Bienemanad070d02014-09-17 20:55:46 +0000654 return CI;
655 }
Meador Inge17418502012-10-13 16:45:37 +0000656
Chris Bienemanad070d02014-09-17 20:55:46 +0000657 // See if either input string is a constant string.
658 StringRef SearchStr, ToFindStr;
659 bool HasStr1 = getConstantStringInfo(CI->getArgOperand(0), SearchStr);
660 bool HasStr2 = getConstantStringInfo(CI->getArgOperand(1), ToFindStr);
661
662 // fold strstr(x, "") -> x.
663 if (HasStr2 && ToFindStr.empty())
664 return B.CreateBitCast(CI->getArgOperand(0), CI->getType());
665
666 // If both strings are known, constant fold it.
667 if (HasStr1 && HasStr2) {
668 size_t Offset = SearchStr.find(ToFindStr);
669
670 if (Offset == StringRef::npos) // strstr("foo", "bar") -> null
Meador Inge17418502012-10-13 16:45:37 +0000671 return Constant::getNullValue(CI->getType());
672
Chris Bienemanad070d02014-09-17 20:55:46 +0000673 // strstr("abcd", "bc") -> gep((char*)"abcd", 1)
Sanjay Pateld3112a52016-01-19 19:46:10 +0000674 Value *Result = castToCStr(CI->getArgOperand(0), B);
Chris Bienemanad070d02014-09-17 20:55:46 +0000675 Result = B.CreateConstInBoundsGEP1_64(Result, Offset, "strstr");
676 return B.CreateBitCast(Result, CI->getType());
Meador Inge17418502012-10-13 16:45:37 +0000677 }
Meador Inge17418502012-10-13 16:45:37 +0000678
Chris Bienemanad070d02014-09-17 20:55:46 +0000679 // fold strstr(x, "y") -> strchr(x, 'y').
680 if (HasStr2 && ToFindStr.size() == 1) {
Sanjay Pateld3112a52016-01-19 19:46:10 +0000681 Value *StrChr = emitStrChr(CI->getArgOperand(0), ToFindStr[0], B, TLI);
Chris Bienemanad070d02014-09-17 20:55:46 +0000682 return StrChr ? B.CreateBitCast(StrChr, CI->getType()) : nullptr;
683 }
684 return nullptr;
685}
Meador Inge40b6fac2012-10-15 03:47:37 +0000686
Benjamin Kramer691363e2015-03-21 15:36:21 +0000687Value *LibCallSimplifier::optimizeMemChr(CallInst *CI, IRBuilder<> &B) {
Benjamin Kramer691363e2015-03-21 15:36:21 +0000688 Value *SrcStr = CI->getArgOperand(0);
689 ConstantInt *CharC = dyn_cast<ConstantInt>(CI->getArgOperand(1));
690 ConstantInt *LenC = dyn_cast<ConstantInt>(CI->getArgOperand(2));
691
692 // memchr(x, y, 0) -> null
Craig Topper79ab6432017-07-06 18:39:47 +0000693 if (LenC && LenC->isZero())
Benjamin Kramer691363e2015-03-21 15:36:21 +0000694 return Constant::getNullValue(CI->getType());
695
Benjamin Kramer7857d722015-03-21 21:09:33 +0000696 // From now on we need at least constant length and string.
Benjamin Kramer691363e2015-03-21 15:36:21 +0000697 StringRef Str;
Benjamin Kramer7857d722015-03-21 21:09:33 +0000698 if (!LenC || !getConstantStringInfo(SrcStr, Str, 0, /*TrimAtNul=*/false))
Benjamin Kramer691363e2015-03-21 15:36:21 +0000699 return nullptr;
700
701 // Truncate the string to LenC. If Str is smaller than LenC we will still only
702 // scan the string, as reading past the end of it is undefined and we can just
703 // return null if we don't find the char.
704 Str = Str.substr(0, LenC->getZExtValue());
705
Benjamin Kramer7857d722015-03-21 21:09:33 +0000706 // If the char is variable but the input str and length are not we can turn
707 // this memchr call into a simple bit field test. Of course this only works
708 // when the return value is only checked against null.
709 //
710 // It would be really nice to reuse switch lowering here but we can't change
711 // the CFG at this point.
712 //
713 // memchr("\r\n", C, 2) != nullptr -> (C & ((1 << '\r') | (1 << '\n'))) != 0
714 // after bounds check.
715 if (!CharC && !Str.empty() && isOnlyUsedInZeroEqualityComparison(CI)) {
Benjamin Kramerd6aa0ec2015-03-21 22:04:26 +0000716 unsigned char Max =
717 *std::max_element(reinterpret_cast<const unsigned char *>(Str.begin()),
718 reinterpret_cast<const unsigned char *>(Str.end()));
Benjamin Kramer7857d722015-03-21 21:09:33 +0000719
720 // Make sure the bit field we're about to create fits in a register on the
721 // target.
722 // FIXME: On a 64 bit architecture this prevents us from using the
723 // interesting range of alpha ascii chars. We could do better by emitting
724 // two bitfields or shifting the range by 64 if no lower chars are used.
725 if (!DL.fitsInLegalInteger(Max + 1))
726 return nullptr;
727
728 // For the bit field use a power-of-2 type with at least 8 bits to avoid
729 // creating unnecessary illegal types.
730 unsigned char Width = NextPowerOf2(std::max((unsigned char)7, Max));
731
732 // Now build the bit field.
733 APInt Bitfield(Width, 0);
734 for (char C : Str)
735 Bitfield.setBit((unsigned char)C);
736 Value *BitfieldC = B.getInt(Bitfield);
737
738 // First check that the bit field access is within bounds.
739 Value *C = B.CreateZExtOrTrunc(CI->getArgOperand(1), BitfieldC->getType());
740 Value *Bounds = B.CreateICmp(ICmpInst::ICMP_ULT, C, B.getIntN(Width, Width),
741 "memchr.bounds");
742
743 // Create code that checks if the given bit is set in the field.
744 Value *Shl = B.CreateShl(B.getIntN(Width, 1ULL), C);
745 Value *Bits = B.CreateIsNotNull(B.CreateAnd(Shl, BitfieldC), "memchr.bits");
746
747 // Finally merge both checks and cast to pointer type. The inttoptr
748 // implicitly zexts the i1 to intptr type.
749 return B.CreateIntToPtr(B.CreateAnd(Bounds, Bits, "memchr"), CI->getType());
750 }
751
752 // Check if all arguments are constants. If so, we can constant fold.
753 if (!CharC)
754 return nullptr;
755
Benjamin Kramer691363e2015-03-21 15:36:21 +0000756 // Compute the offset.
757 size_t I = Str.find(CharC->getSExtValue() & 0xFF);
758 if (I == StringRef::npos) // Didn't find the char. memchr returns null.
759 return Constant::getNullValue(CI->getType());
760
761 // memchr(s+n,c,l) -> gep(s+n+i,c)
David Blaikie3909da72015-03-30 20:42:56 +0000762 return B.CreateGEP(B.getInt8Ty(), SrcStr, B.getInt64(I), "memchr");
Benjamin Kramer691363e2015-03-21 15:36:21 +0000763}
764
Chris Bienemanad070d02014-09-17 20:55:46 +0000765Value *LibCallSimplifier::optimizeMemCmp(CallInst *CI, IRBuilder<> &B) {
Chris Bienemanad070d02014-09-17 20:55:46 +0000766 Value *LHS = CI->getArgOperand(0), *RHS = CI->getArgOperand(1);
Meador Inge40b6fac2012-10-15 03:47:37 +0000767
Chris Bienemanad070d02014-09-17 20:55:46 +0000768 if (LHS == RHS) // memcmp(s,s,x) -> 0
769 return Constant::getNullValue(CI->getType());
Meador Inge40b6fac2012-10-15 03:47:37 +0000770
Chris Bienemanad070d02014-09-17 20:55:46 +0000771 // Make sure we have a constant length.
772 ConstantInt *LenC = dyn_cast<ConstantInt>(CI->getArgOperand(2));
773 if (!LenC)
Craig Topperf40110f2014-04-25 05:29:35 +0000774 return nullptr;
Chris Bienemanad070d02014-09-17 20:55:46 +0000775
Sanjay Patel70db4242017-06-09 14:22:03 +0000776 uint64_t Len = LenC->getZExtValue();
Chris Bienemanad070d02014-09-17 20:55:46 +0000777 if (Len == 0) // memcmp(s1,s2,0) -> 0
778 return Constant::getNullValue(CI->getType());
779
780 // memcmp(S1,S2,1) -> *(unsigned char*)LHS - *(unsigned char*)RHS
781 if (Len == 1) {
Sanjay Pateld3112a52016-01-19 19:46:10 +0000782 Value *LHSV = B.CreateZExt(B.CreateLoad(castToCStr(LHS, B), "lhsc"),
Chris Bienemanad070d02014-09-17 20:55:46 +0000783 CI->getType(), "lhsv");
Sanjay Pateld3112a52016-01-19 19:46:10 +0000784 Value *RHSV = B.CreateZExt(B.CreateLoad(castToCStr(RHS, B), "rhsc"),
Chris Bienemanad070d02014-09-17 20:55:46 +0000785 CI->getType(), "rhsv");
786 return B.CreateSub(LHSV, RHSV, "chardiff");
Meador Inge40b6fac2012-10-15 03:47:37 +0000787 }
Meador Inge40b6fac2012-10-15 03:47:37 +0000788
Chad Rosierdc655322015-08-28 18:30:18 +0000789 // memcmp(S1,S2,N/8)==0 -> (*(intN_t*)S1 != *(intN_t*)S2)==0
Sanjay Patel82ec8722017-08-21 19:13:14 +0000790 // TODO: The case where both inputs are constants does not need to be limited
791 // to legal integers or equality comparison. See block below this.
Chad Rosierdc655322015-08-28 18:30:18 +0000792 if (DL.isLegalInteger(Len * 8) && isOnlyUsedInZeroEqualityComparison(CI)) {
Chad Rosierdc655322015-08-28 18:30:18 +0000793 IntegerType *IntType = IntegerType::get(CI->getContext(), Len * 8);
794 unsigned PrefAlignment = DL.getPrefTypeAlignment(IntType);
795
Sanjay Patel82ec8722017-08-21 19:13:14 +0000796 // First, see if we can fold either argument to a constant.
797 Value *LHSV = nullptr;
798 if (auto *LHSC = dyn_cast<Constant>(LHS)) {
799 LHSC = ConstantExpr::getBitCast(LHSC, IntType->getPointerTo());
800 LHSV = ConstantFoldLoadFromConstPtr(LHSC, IntType, DL);
801 }
802 Value *RHSV = nullptr;
803 if (auto *RHSC = dyn_cast<Constant>(RHS)) {
804 RHSC = ConstantExpr::getBitCast(RHSC, IntType->getPointerTo());
805 RHSV = ConstantFoldLoadFromConstPtr(RHSC, IntType, DL);
806 }
Chad Rosierdc655322015-08-28 18:30:18 +0000807
Sanjay Patel82ec8722017-08-21 19:13:14 +0000808 // Don't generate unaligned loads. If either source is constant data,
809 // alignment doesn't matter for that source because there is no load.
810 if ((LHSV || getKnownAlignment(LHS, DL, CI) >= PrefAlignment) &&
811 (RHSV || getKnownAlignment(RHS, DL, CI) >= PrefAlignment)) {
812 if (!LHSV) {
813 Type *LHSPtrTy =
814 IntType->getPointerTo(LHS->getType()->getPointerAddressSpace());
815 LHSV = B.CreateLoad(B.CreateBitCast(LHS, LHSPtrTy), "lhsv");
816 }
817 if (!RHSV) {
818 Type *RHSPtrTy =
819 IntType->getPointerTo(RHS->getType()->getPointerAddressSpace());
820 RHSV = B.CreateLoad(B.CreateBitCast(RHS, RHSPtrTy), "rhsv");
821 }
Sanjay Patel7756edf2017-08-21 13:55:49 +0000822 return B.CreateZExt(B.CreateICmpNE(LHSV, RHSV), CI->getType(), "memcmp");
Sanjay Patel707f7862017-08-21 15:16:25 +0000823 }
Chad Rosierdc655322015-08-28 18:30:18 +0000824 }
825
Sanjay Patel82ec8722017-08-21 19:13:14 +0000826 // Constant folding: memcmp(x, y, Len) -> constant (all arguments are const).
827 // TODO: This is limited to i8 arrays.
Chris Bienemanad070d02014-09-17 20:55:46 +0000828 StringRef LHSStr, RHSStr;
829 if (getConstantStringInfo(LHS, LHSStr) &&
830 getConstantStringInfo(RHS, RHSStr)) {
831 // Make sure we're not reading out-of-bounds memory.
832 if (Len > LHSStr.size() || Len > RHSStr.size())
Craig Topperf40110f2014-04-25 05:29:35 +0000833 return nullptr;
Chris Bienemanad070d02014-09-17 20:55:46 +0000834 // Fold the memcmp and normalize the result. This way we get consistent
835 // results across multiple platforms.
836 uint64_t Ret = 0;
837 int Cmp = memcmp(LHSStr.data(), RHSStr.data(), Len);
838 if (Cmp < 0)
839 Ret = -1;
840 else if (Cmp > 0)
841 Ret = 1;
842 return ConstantInt::get(CI->getType(), Ret);
Meador Inge000dbcc2012-10-18 18:12:40 +0000843 }
Meador Inge000dbcc2012-10-18 18:12:40 +0000844
Chris Bienemanad070d02014-09-17 20:55:46 +0000845 return nullptr;
846}
Meador Inge9a6a1902012-10-31 00:20:56 +0000847
Chris Bienemanad070d02014-09-17 20:55:46 +0000848Value *LibCallSimplifier::optimizeMemCpy(CallInst *CI, IRBuilder<> &B) {
Daniel Neilson8acd8b02018-02-05 21:23:22 +0000849 // memcpy(x, y, n) -> llvm.memcpy(align 1 x, align 1 y, n)
850 B.CreateMemCpy(CI->getArgOperand(0), 1, CI->getArgOperand(1), 1,
851 CI->getArgOperand(2));
Chris Bienemanad070d02014-09-17 20:55:46 +0000852 return CI->getArgOperand(0);
853}
Meador Inge05a625a2012-10-31 14:58:26 +0000854
Chris Bienemanad070d02014-09-17 20:55:46 +0000855Value *LibCallSimplifier::optimizeMemMove(CallInst *CI, IRBuilder<> &B) {
Daniel Neilson8acd8b02018-02-05 21:23:22 +0000856 // memmove(x, y, n) -> llvm.memmove(align 1 x, align 1 y, n)
857 B.CreateMemMove(CI->getArgOperand(0), 1, CI->getArgOperand(1), 1,
858 CI->getArgOperand(2));
Chris Bienemanad070d02014-09-17 20:55:46 +0000859 return CI->getArgOperand(0);
860}
Meador Ingebcd88ef72012-11-10 15:16:48 +0000861
Sanjay Patel980b2802016-01-26 16:17:24 +0000862/// Fold memset[_chk](malloc(n), 0, n) --> calloc(1, n).
863static Value *foldMallocMemset(CallInst *Memset, IRBuilder<> &B,
864 const TargetLibraryInfo &TLI) {
865 // This has to be a memset of zeros (bzero).
866 auto *FillValue = dyn_cast<ConstantInt>(Memset->getArgOperand(1));
867 if (!FillValue || FillValue->getZExtValue() != 0)
868 return nullptr;
869
870 // TODO: We should handle the case where the malloc has more than one use.
871 // This is necessary to optimize common patterns such as when the result of
872 // the malloc is checked against null or when a memset intrinsic is used in
873 // place of a memset library call.
874 auto *Malloc = dyn_cast<CallInst>(Memset->getArgOperand(0));
875 if (!Malloc || !Malloc->hasOneUse())
876 return nullptr;
877
878 // Is the inner call really malloc()?
879 Function *InnerCallee = Malloc->getCalledFunction();
Matthias Braunc36a78c2017-04-25 19:44:25 +0000880 if (!InnerCallee)
881 return nullptr;
882
David L. Jonesd21529f2017-01-23 23:16:46 +0000883 LibFunc Func;
Ahmed Bougachad765a822016-04-27 19:04:35 +0000884 if (!TLI.getLibFunc(*InnerCallee, Func) || !TLI.has(Func) ||
David L. Jonesd21529f2017-01-23 23:16:46 +0000885 Func != LibFunc_malloc)
Sanjay Patel980b2802016-01-26 16:17:24 +0000886 return nullptr;
887
Sanjay Patel980b2802016-01-26 16:17:24 +0000888 // The memset must cover the same number of bytes that are malloc'd.
889 if (Memset->getArgOperand(2) != Malloc->getArgOperand(0))
890 return nullptr;
891
892 // Replace the malloc with a calloc. We need the data layout to know what the
893 // actual size of a 'size_t' parameter is.
894 B.SetInsertPoint(Malloc->getParent(), ++Malloc->getIterator());
895 const DataLayout &DL = Malloc->getModule()->getDataLayout();
896 IntegerType *SizeType = DL.getIntPtrType(B.GetInsertBlock()->getContext());
897 Value *Calloc = emitCalloc(ConstantInt::get(SizeType, 1),
898 Malloc->getArgOperand(0), Malloc->getAttributes(),
899 B, TLI);
900 if (!Calloc)
901 return nullptr;
902
903 Malloc->replaceAllUsesWith(Calloc);
904 Malloc->eraseFromParent();
905
906 return Calloc;
907}
908
Chris Bienemanad070d02014-09-17 20:55:46 +0000909Value *LibCallSimplifier::optimizeMemSet(CallInst *CI, IRBuilder<> &B) {
Sanjay Patel980b2802016-01-26 16:17:24 +0000910 if (auto *Calloc = foldMallocMemset(CI, B, *TLI))
911 return Calloc;
912
Daniel Neilson8acd8b02018-02-05 21:23:22 +0000913 // memset(p, v, n) -> llvm.memset(align 1 p, v, n)
Chris Bienemanad070d02014-09-17 20:55:46 +0000914 Value *Val = B.CreateIntCast(CI->getArgOperand(1), B.getInt8Ty(), false);
915 B.CreateMemSet(CI->getArgOperand(0), Val, CI->getArgOperand(2), 1);
916 return CI->getArgOperand(0);
917}
Meador Inged4825782012-11-11 06:49:03 +0000918
Sanjay Patelb2ab3f22018-04-18 14:21:31 +0000919Value *LibCallSimplifier::optimizeRealloc(CallInst *CI, IRBuilder<> &B) {
920 if (isa<ConstantPointerNull>(CI->getArgOperand(0)))
921 return emitMalloc(CI->getArgOperand(1), B, DL, TLI);
922
923 return nullptr;
924}
925
Meador Inge193e0352012-11-13 04:16:17 +0000926//===----------------------------------------------------------------------===//
927// Math Library Optimizations
928//===----------------------------------------------------------------------===//
929
Matthias Braund34e4d22014-12-03 21:46:33 +0000930/// Return a variant of Val with float type.
931/// Currently this works in two cases: If Val is an FPExtension of a float
932/// value to something bigger, simply return the operand.
933/// If Val is a ConstantFP but can be converted to a float ConstantFP without
934/// loss of precision do so.
935static Value *valueHasFloatPrecision(Value *Val) {
936 if (FPExtInst *Cast = dyn_cast<FPExtInst>(Val)) {
937 Value *Op = Cast->getOperand(0);
938 if (Op->getType()->isFloatTy())
939 return Op;
940 }
941 if (ConstantFP *Const = dyn_cast<ConstantFP>(Val)) {
942 APFloat F = Const->getValueAPF();
Matthias Braun395a82f2014-12-03 22:10:39 +0000943 bool losesInfo;
Stephan Bergmann17c7f702016-12-14 11:57:17 +0000944 (void)F.convert(APFloat::IEEEsingle(), APFloat::rmNearestTiesToEven,
Matthias Braun395a82f2014-12-03 22:10:39 +0000945 &losesInfo);
946 if (!losesInfo)
Matthias Braund34e4d22014-12-03 21:46:33 +0000947 return ConstantFP::get(Const->getContext(), F);
948 }
949 return nullptr;
950}
951
Sanjay Patel4e971da2016-01-21 18:01:57 +0000952/// Shrink double -> float for unary functions like 'floor'.
953static Value *optimizeUnaryDoubleFP(CallInst *CI, IRBuilder<> &B,
954 bool CheckRetType) {
Chris Bienemanad070d02014-09-17 20:55:46 +0000955 Function *Callee = CI->getCalledFunction();
Ahmed Bougachad765a822016-04-27 19:04:35 +0000956 // We know this libcall has a valid prototype, but we don't know which.
957 if (!CI->getType()->isDoubleTy())
Chris Bienemanad070d02014-09-17 20:55:46 +0000958 return nullptr;
Meador Inge193e0352012-11-13 04:16:17 +0000959
Chris Bienemanad070d02014-09-17 20:55:46 +0000960 if (CheckRetType) {
961 // Check if all the uses for function like 'sin' are converted to float.
962 for (User *U : CI->users()) {
963 FPTruncInst *Cast = dyn_cast<FPTruncInst>(U);
964 if (!Cast || !Cast->getType()->isFloatTy())
965 return nullptr;
Meador Inge193e0352012-11-13 04:16:17 +0000966 }
Meador Inge193e0352012-11-13 04:16:17 +0000967 }
Chris Bienemanad070d02014-09-17 20:55:46 +0000968
969 // If this is something like 'floor((double)floatval)', convert to floorf.
Matthias Braund34e4d22014-12-03 21:46:33 +0000970 Value *V = valueHasFloatPrecision(CI->getArgOperand(0));
971 if (V == nullptr)
Chris Bienemanad070d02014-09-17 20:55:46 +0000972 return nullptr;
Sanjay Patelaa231142015-12-31 21:52:31 +0000973
Andrew Ng1606fc02017-04-25 12:36:14 +0000974 // If call isn't an intrinsic, check that it isn't within a function with the
975 // same name as the float version of this call.
976 //
977 // e.g. inline float expf(float val) { return (float) exp((double) val); }
978 //
979 // A similar such definition exists in the MinGW-w64 math.h header file which
980 // when compiled with -O2 -ffast-math causes the generation of infinite loops
981 // where expf is called.
982 if (!Callee->isIntrinsic()) {
983 const Function *F = CI->getFunction();
984 StringRef FName = F->getName();
985 StringRef CalleeName = Callee->getName();
986 if ((FName.size() == (CalleeName.size() + 1)) &&
987 (FName.back() == 'f') &&
988 FName.startswith(CalleeName))
989 return nullptr;
990 }
991
Sanjay Patelaa231142015-12-31 21:52:31 +0000992 // Propagate fast-math flags from the existing call to the new call.
993 IRBuilder<>::FastMathFlagGuard Guard(B);
Sanjay Patela2528152016-01-12 18:03:37 +0000994 B.setFastMathFlags(CI->getFastMathFlags());
Chris Bienemanad070d02014-09-17 20:55:46 +0000995
996 // floor((double)floatval) -> (double)floorf(floatval)
Sanjay Patel848309d2014-10-23 21:52:45 +0000997 if (Callee->isIntrinsic()) {
Sanjay Patelaf674fb2015-12-14 17:24:23 +0000998 Module *M = CI->getModule();
Pete Cooper9e1d3352015-05-20 17:16:39 +0000999 Intrinsic::ID IID = Callee->getIntrinsicID();
Sanjay Patel848309d2014-10-23 21:52:45 +00001000 Function *F = Intrinsic::getDeclaration(M, IID, B.getFloatTy());
1001 V = B.CreateCall(F, V);
1002 } else {
1003 // The call is a library call rather than an intrinsic.
Sanjay Pateld3112a52016-01-19 19:46:10 +00001004 V = emitUnaryFloatFnCall(V, Callee->getName(), B, Callee->getAttributes());
Sanjay Patel848309d2014-10-23 21:52:45 +00001005 }
1006
Chris Bienemanad070d02014-09-17 20:55:46 +00001007 return B.CreateFPExt(V, B.getDoubleTy());
1008}
Meador Inge193e0352012-11-13 04:16:17 +00001009
Matt Arsenault954a6242017-01-23 23:55:08 +00001010// Replace a libcall \p CI with a call to intrinsic \p IID
1011static Value *replaceUnaryCall(CallInst *CI, IRBuilder<> &B, Intrinsic::ID IID) {
1012 // Propagate fast-math flags from the existing call to the new call.
1013 IRBuilder<>::FastMathFlagGuard Guard(B);
1014 B.setFastMathFlags(CI->getFastMathFlags());
1015
1016 Module *M = CI->getModule();
1017 Value *V = CI->getArgOperand(0);
1018 Function *F = Intrinsic::getDeclaration(M, IID, CI->getType());
1019 CallInst *NewCall = B.CreateCall(F, V);
1020 NewCall->takeName(CI);
1021 return NewCall;
1022}
1023
Sanjay Patel4e971da2016-01-21 18:01:57 +00001024/// Shrink double -> float for binary functions like 'fmin/fmax'.
1025static Value *optimizeBinaryDoubleFP(CallInst *CI, IRBuilder<> &B) {
Chris Bienemanad070d02014-09-17 20:55:46 +00001026 Function *Callee = CI->getCalledFunction();
Ahmed Bougachad765a822016-04-27 19:04:35 +00001027 // We know this libcall has a valid prototype, but we don't know which.
1028 if (!CI->getType()->isDoubleTy())
Craig Topperf40110f2014-04-25 05:29:35 +00001029 return nullptr;
Meador Inge193e0352012-11-13 04:16:17 +00001030
Chris Bienemanad070d02014-09-17 20:55:46 +00001031 // If this is something like 'fmin((double)floatval1, (double)floatval2)',
Matthias Braund34e4d22014-12-03 21:46:33 +00001032 // or fmin(1.0, (double)floatval), then we convert it to fminf.
1033 Value *V1 = valueHasFloatPrecision(CI->getArgOperand(0));
1034 if (V1 == nullptr)
1035 return nullptr;
1036 Value *V2 = valueHasFloatPrecision(CI->getArgOperand(1));
1037 if (V2 == nullptr)
Craig Topperf40110f2014-04-25 05:29:35 +00001038 return nullptr;
Chris Bienemanad070d02014-09-17 20:55:46 +00001039
Sanjay Patelbee05ca2015-12-31 23:40:59 +00001040 // Propagate fast-math flags from the existing call to the new call.
1041 IRBuilder<>::FastMathFlagGuard Guard(B);
Sanjay Patela2528152016-01-12 18:03:37 +00001042 B.setFastMathFlags(CI->getFastMathFlags());
Sanjay Patelbee05ca2015-12-31 23:40:59 +00001043
Chris Bienemanad070d02014-09-17 20:55:46 +00001044 // fmin((double)floatval1, (double)floatval2)
Matthias Braund34e4d22014-12-03 21:46:33 +00001045 // -> (double)fminf(floatval1, floatval2)
Sanjay Patel848309d2014-10-23 21:52:45 +00001046 // TODO: Handle intrinsics in the same way as in optimizeUnaryDoubleFP().
Sanjay Pateld3112a52016-01-19 19:46:10 +00001047 Value *V = emitBinaryFloatFnCall(V1, V2, Callee->getName(), B,
Matthias Braund34e4d22014-12-03 21:46:33 +00001048 Callee->getAttributes());
Chris Bienemanad070d02014-09-17 20:55:46 +00001049 return B.CreateFPExt(V, B.getDoubleTy());
1050}
1051
Hal Finkel2ff24732017-12-16 01:26:25 +00001052// cabs(z) -> sqrt((creal(z)*creal(z)) + (cimag(z)*cimag(z)))
1053Value *LibCallSimplifier::optimizeCAbs(CallInst *CI, IRBuilder<> &B) {
1054 if (!CI->isFast())
1055 return nullptr;
1056
1057 // Propagate fast-math flags from the existing call to new instructions.
1058 IRBuilder<>::FastMathFlagGuard Guard(B);
1059 B.setFastMathFlags(CI->getFastMathFlags());
1060
1061 Value *Real, *Imag;
1062 if (CI->getNumArgOperands() == 1) {
1063 Value *Op = CI->getArgOperand(0);
1064 assert(Op->getType()->isArrayTy() && "Unexpected signature for cabs!");
1065 Real = B.CreateExtractValue(Op, 0, "real");
1066 Imag = B.CreateExtractValue(Op, 1, "imag");
1067 } else {
1068 assert(CI->getNumArgOperands() == 2 && "Unexpected signature for cabs!");
1069 Real = CI->getArgOperand(0);
1070 Imag = CI->getArgOperand(1);
1071 }
1072
1073 Value *RealReal = B.CreateFMul(Real, Real);
1074 Value *ImagImag = B.CreateFMul(Imag, Imag);
1075
1076 Function *FSqrt = Intrinsic::getDeclaration(CI->getModule(), Intrinsic::sqrt,
1077 CI->getType());
1078 return B.CreateCall(FSqrt, B.CreateFAdd(RealReal, ImagImag), "cabs");
1079}
1080
Chris Bienemanad070d02014-09-17 20:55:46 +00001081Value *LibCallSimplifier::optimizeCos(CallInst *CI, IRBuilder<> &B) {
1082 Function *Callee = CI->getCalledFunction();
1083 Value *Ret = nullptr;
Davide Italianoa3458772015-11-05 19:18:23 +00001084 StringRef Name = Callee->getName();
1085 if (UnsafeFPShrink && Name == "cos" && hasFloatVersion(Name))
Chris Bienemanad070d02014-09-17 20:55:46 +00001086 Ret = optimizeUnaryDoubleFP(CI, B, true);
Bob Wilsond8d92d92013-11-03 06:48:38 +00001087
Chris Bienemanad070d02014-09-17 20:55:46 +00001088 // cos(-x) -> cos(x)
1089 Value *Op1 = CI->getArgOperand(0);
1090 if (BinaryOperator::isFNeg(Op1)) {
1091 BinaryOperator *BinExpr = cast<BinaryOperator>(Op1);
1092 return B.CreateCall(Callee, BinExpr->getOperand(1), "cos");
1093 }
1094 return Ret;
1095}
Bob Wilsond8d92d92013-11-03 06:48:38 +00001096
Weiming Zhao82130722015-12-04 22:00:47 +00001097static Value *getPow(Value *InnerChain[33], unsigned Exp, IRBuilder<> &B) {
1098 // Multiplications calculated using Addition Chains.
1099 // Refer: http://wwwhomes.uni-bielefeld.de/achim/addition_chain.html
1100
1101 assert(Exp != 0 && "Incorrect exponent 0 not handled");
1102
1103 if (InnerChain[Exp])
1104 return InnerChain[Exp];
1105
1106 static const unsigned AddChain[33][2] = {
1107 {0, 0}, // Unused.
1108 {0, 0}, // Unused (base case = pow1).
1109 {1, 1}, // Unused (pre-computed).
1110 {1, 2}, {2, 2}, {2, 3}, {3, 3}, {2, 5}, {4, 4},
1111 {1, 8}, {5, 5}, {1, 10}, {6, 6}, {4, 9}, {7, 7},
1112 {3, 12}, {8, 8}, {8, 9}, {2, 16}, {1, 18}, {10, 10},
1113 {6, 15}, {11, 11}, {3, 20}, {12, 12}, {8, 17}, {13, 13},
1114 {3, 24}, {14, 14}, {4, 25}, {15, 15}, {3, 28}, {16, 16},
1115 };
1116
1117 InnerChain[Exp] = B.CreateFMul(getPow(InnerChain, AddChain[Exp][0], B),
1118 getPow(InnerChain, AddChain[Exp][1], B));
1119 return InnerChain[Exp];
1120}
1121
Sanjay Patelfbd3e662017-11-19 16:13:14 +00001122/// Use square root in place of pow(x, +/-0.5).
1123Value *LibCallSimplifier::replacePowWithSqrt(CallInst *Pow, IRBuilder<> &B) {
1124 // TODO: There is some subset of 'fast' under which these transforms should
1125 // be allowed.
1126 if (!Pow->isFast())
1127 return nullptr;
1128
Sanjay Patel9771a962017-11-19 16:42:27 +00001129 const APFloat *Arg1C;
1130 if (!match(Pow->getArgOperand(1), m_APFloat(Arg1C)))
Sanjay Patelfbd3e662017-11-19 16:13:14 +00001131 return nullptr;
Sanjay Patel9771a962017-11-19 16:42:27 +00001132 if (!Arg1C->isExactlyValue(0.5) && !Arg1C->isExactlyValue(-0.5))
Sanjay Patelfbd3e662017-11-19 16:13:14 +00001133 return nullptr;
1134
1135 // Fast-math flags from the pow() are propagated to all replacement ops.
1136 IRBuilder<>::FastMathFlagGuard Guard(B);
1137 B.setFastMathFlags(Pow->getFastMathFlags());
1138 Type *Ty = Pow->getType();
1139 Value *Sqrt;
1140 if (Pow->hasFnAttr(Attribute::ReadNone)) {
1141 // We know that errno is never set, so replace with an intrinsic:
1142 // pow(x, 0.5) --> llvm.sqrt(x)
1143 // llvm.pow(x, 0.5) --> llvm.sqrt(x)
1144 auto *F = Intrinsic::getDeclaration(Pow->getModule(), Intrinsic::sqrt, Ty);
1145 Sqrt = B.CreateCall(F, Pow->getArgOperand(0));
1146 } else if (hasUnaryFloatFn(TLI, Ty, LibFunc_sqrt, LibFunc_sqrtf,
1147 LibFunc_sqrtl)) {
1148 // Errno could be set, so we must use a sqrt libcall.
1149 // TODO: We also should check that the target can in fact lower the sqrt
1150 // libcall. We currently have no way to ask this question, so we ask
1151 // whether the target has a sqrt libcall which is not exactly the same.
1152 Sqrt = emitUnaryFloatFnCall(Pow->getArgOperand(0),
1153 TLI->getName(LibFunc_sqrt), B,
1154 Pow->getCalledFunction()->getAttributes());
1155 } else {
1156 // We can't replace with an intrinsic or a libcall.
1157 return nullptr;
1158 }
1159
1160 // If this is pow(x, -0.5), get the reciprocal.
Sanjay Patel9771a962017-11-19 16:42:27 +00001161 if (Arg1C->isExactlyValue(-0.5))
Sanjay Patelfbd3e662017-11-19 16:13:14 +00001162 Sqrt = B.CreateFDiv(ConstantFP::get(Ty, 1.0), Sqrt);
1163
1164 return Sqrt;
1165}
1166
Chris Bienemanad070d02014-09-17 20:55:46 +00001167Value *LibCallSimplifier::optimizePow(CallInst *CI, IRBuilder<> &B) {
1168 Function *Callee = CI->getCalledFunction();
Chris Bienemanad070d02014-09-17 20:55:46 +00001169 Value *Ret = nullptr;
Davide Italianoa3458772015-11-05 19:18:23 +00001170 StringRef Name = Callee->getName();
1171 if (UnsafeFPShrink && Name == "pow" && hasFloatVersion(Name))
Chris Bienemanad070d02014-09-17 20:55:46 +00001172 Ret = optimizeUnaryDoubleFP(CI, B, true);
Bob Wilsond8d92d92013-11-03 06:48:38 +00001173
Chris Bienemanad070d02014-09-17 20:55:46 +00001174 Value *Op1 = CI->getArgOperand(0), *Op2 = CI->getArgOperand(1);
Davide Italiano27da1312016-08-07 20:27:03 +00001175
1176 // pow(1.0, x) -> 1.0
1177 if (match(Op1, m_SpecificFP(1.0)))
1178 return Op1;
1179 // pow(2.0, x) -> llvm.exp2(x)
1180 if (match(Op1, m_SpecificFP(2.0))) {
1181 Value *Exp2 = Intrinsic::getDeclaration(CI->getModule(), Intrinsic::exp2,
1182 CI->getType());
1183 return B.CreateCall(Exp2, Op2, "exp2");
1184 }
1185
1186 // There's no llvm.exp10 intrinsic yet, but, maybe, some day there will
1187 // be one.
Chris Bienemanad070d02014-09-17 20:55:46 +00001188 if (ConstantFP *Op1C = dyn_cast<ConstantFP>(Op1)) {
Chris Bienemanad070d02014-09-17 20:55:46 +00001189 // pow(10.0, x) -> exp10(x)
1190 if (Op1C->isExactlyValue(10.0) &&
David L. Jonesd21529f2017-01-23 23:16:46 +00001191 hasUnaryFloatFn(TLI, Op1->getType(), LibFunc_exp10, LibFunc_exp10f,
1192 LibFunc_exp10l))
1193 return emitUnaryFloatFnCall(Op2, TLI->getName(LibFunc_exp10), B,
Chris Bienemanad070d02014-09-17 20:55:46 +00001194 Callee->getAttributes());
Bob Wilsond8d92d92013-11-03 06:48:38 +00001195 }
1196
Sanjay Patel6002e782016-01-12 17:30:37 +00001197 // pow(exp(x), y) -> exp(x * y)
Davide Italianoc8a79132015-11-03 20:32:23 +00001198 // pow(exp2(x), y) -> exp2(x * y)
Sanjay Patel6002e782016-01-12 17:30:37 +00001199 // We enable these only with fast-math. Besides rounding differences, the
1200 // transformation changes overflow and underflow behavior quite dramatically.
Davide Italianoc8a79132015-11-03 20:32:23 +00001201 // Example: x = 1000, y = 0.001.
1202 // pow(exp(x), y) = pow(inf, 0.001) = inf, whereas exp(x*y) = exp(1).
Sanjay Patel6002e782016-01-12 17:30:37 +00001203 auto *OpC = dyn_cast<CallInst>(Op1);
Sanjay Patel629c4112017-11-06 16:27:15 +00001204 if (OpC && OpC->isFast() && CI->isFast()) {
David L. Jonesd21529f2017-01-23 23:16:46 +00001205 LibFunc Func;
Sanjay Patel6002e782016-01-12 17:30:37 +00001206 Function *OpCCallee = OpC->getCalledFunction();
1207 if (OpCCallee && TLI->getLibFunc(OpCCallee->getName(), Func) &&
David L. Jonesd21529f2017-01-23 23:16:46 +00001208 TLI->has(Func) && (Func == LibFunc_exp || Func == LibFunc_exp2)) {
Davide Italianoc8a79132015-11-03 20:32:23 +00001209 IRBuilder<>::FastMathFlagGuard Guard(B);
Sanjay Patela2528152016-01-12 18:03:37 +00001210 B.setFastMathFlags(CI->getFastMathFlags());
Sanjay Patel6002e782016-01-12 17:30:37 +00001211 Value *FMul = B.CreateFMul(OpC->getArgOperand(0), Op2, "mul");
Sanjay Pateld3112a52016-01-19 19:46:10 +00001212 return emitUnaryFloatFnCall(FMul, OpCCallee->getName(), B,
Sanjay Patel6002e782016-01-12 17:30:37 +00001213 OpCCallee->getAttributes());
Davide Italianoc8a79132015-11-03 20:32:23 +00001214 }
1215 }
1216
Sanjay Patel9771a962017-11-19 16:42:27 +00001217 if (Value *Sqrt = replacePowWithSqrt(CI, B))
1218 return Sqrt;
1219
Chris Bienemanad070d02014-09-17 20:55:46 +00001220 ConstantFP *Op2C = dyn_cast<ConstantFP>(Op2);
1221 if (!Op2C)
1222 return Ret;
1223
1224 if (Op2C->getValueAPF().isZero()) // pow(x, 0.0) -> 1.0
1225 return ConstantFP::get(CI->getType(), 1.0);
1226
Sanjay Patelfbd3e662017-11-19 16:13:14 +00001227 // FIXME: Correct the transforms and pull this into replacePowWithSqrt().
Chris Bienemanad070d02014-09-17 20:55:46 +00001228 if (Op2C->isExactlyValue(0.5) &&
David L. Jonesd21529f2017-01-23 23:16:46 +00001229 hasUnaryFloatFn(TLI, Op2->getType(), LibFunc_sqrt, LibFunc_sqrtf,
1230 LibFunc_sqrtl)) {
Chris Bienemanad070d02014-09-17 20:55:46 +00001231 // Expand pow(x, 0.5) to (x == -infinity ? +infinity : fabs(sqrt(x))).
1232 // This is faster than calling pow, and still handles negative zero
1233 // and negative infinity correctly.
Chris Bienemanad070d02014-09-17 20:55:46 +00001234 // TODO: In finite-only mode, this could be just fabs(sqrt(x)).
1235 Value *Inf = ConstantFP::getInfinity(CI->getType());
1236 Value *NegInf = ConstantFP::getInfinity(CI->getType(), true);
Justin Lebarcb9b41d2017-01-27 00:58:03 +00001237
1238 // TODO: As above, we should lower to the sqrt intrinsic if the pow is an
1239 // intrinsic, to match errno semantics.
Sanjay Pateld3112a52016-01-19 19:46:10 +00001240 Value *Sqrt = emitUnaryFloatFnCall(Op1, "sqrt", B, Callee->getAttributes());
Matt Arsenaultb948b4d2017-01-17 00:30:31 +00001241
1242 Module *M = Callee->getParent();
1243 Function *FabsF = Intrinsic::getDeclaration(M, Intrinsic::fabs,
1244 CI->getType());
1245 Value *FAbs = B.CreateCall(FabsF, Sqrt);
1246
Chris Bienemanad070d02014-09-17 20:55:46 +00001247 Value *FCmp = B.CreateFCmpOEQ(Op1, NegInf);
1248 Value *Sel = B.CreateSelect(FCmp, Inf, FAbs);
1249 return Sel;
Bob Wilsond8d92d92013-11-03 06:48:38 +00001250 }
1251
Sanjay Patelb23e1482017-12-10 17:25:54 +00001252 // Propagate fast-math-flags from the call to any created instructions.
1253 IRBuilder<>::FastMathFlagGuard Guard(B);
1254 B.setFastMathFlags(CI->getFastMathFlags());
1255 // pow(x, 1.0) --> x
1256 if (Op2C->isExactlyValue(1.0))
Chris Bienemanad070d02014-09-17 20:55:46 +00001257 return Op1;
Sanjay Patelb23e1482017-12-10 17:25:54 +00001258 // pow(x, 2.0) --> x * x
1259 if (Op2C->isExactlyValue(2.0))
Chris Bienemanad070d02014-09-17 20:55:46 +00001260 return B.CreateFMul(Op1, Op1, "pow2");
Sanjay Patelb23e1482017-12-10 17:25:54 +00001261 // pow(x, -1.0) --> 1.0 / x
1262 if (Op2C->isExactlyValue(-1.0))
Chris Bienemanad070d02014-09-17 20:55:46 +00001263 return B.CreateFDiv(ConstantFP::get(CI->getType(), 1.0), Op1, "powrecip");
Weiming Zhao82130722015-12-04 22:00:47 +00001264
1265 // In -ffast-math, generate repeated fmul instead of generating pow(x, n).
Sanjay Patel629c4112017-11-06 16:27:15 +00001266 if (CI->isFast()) {
Weiming Zhao82130722015-12-04 22:00:47 +00001267 APFloat V = abs(Op2C->getValueAPF());
1268 // We limit to a max of 7 fmul(s). Thus max exponent is 32.
1269 // This transformation applies to integer exponents only.
1270 if (V.compare(APFloat(V.getSemantics(), 32.0)) == APFloat::cmpGreaterThan ||
1271 !V.isInteger())
1272 return nullptr;
1273
1274 // We will memoize intermediate products of the Addition Chain.
1275 Value *InnerChain[33] = {nullptr};
1276 InnerChain[1] = Op1;
1277 InnerChain[2] = B.CreateFMul(Op1, Op1);
1278
1279 // We cannot readily convert a non-double type (like float) to a double.
1280 // So we first convert V to something which could be converted to double.
Sanjay Patelb23e1482017-12-10 17:25:54 +00001281 bool Ignored;
1282 V.convert(APFloat::IEEEdouble(), APFloat::rmTowardZero, &Ignored);
Sanjay Patel81a63cd2016-01-19 18:15:12 +00001283
Weiming Zhao82130722015-12-04 22:00:47 +00001284 Value *FMul = getPow(InnerChain, V.convertToDouble(), B);
1285 // For negative exponents simply compute the reciprocal.
1286 if (Op2C->isNegative())
1287 FMul = B.CreateFDiv(ConstantFP::get(CI->getType(), 1.0), FMul);
1288 return FMul;
1289 }
1290
Chris Bienemanad070d02014-09-17 20:55:46 +00001291 return nullptr;
1292}
Bob Wilsond8d92d92013-11-03 06:48:38 +00001293
Chris Bienemanad070d02014-09-17 20:55:46 +00001294Value *LibCallSimplifier::optimizeExp2(CallInst *CI, IRBuilder<> &B) {
1295 Function *Callee = CI->getCalledFunction();
Chris Bienemanad070d02014-09-17 20:55:46 +00001296 Value *Ret = nullptr;
Davide Italianoa3458772015-11-05 19:18:23 +00001297 StringRef Name = Callee->getName();
1298 if (UnsafeFPShrink && Name == "exp2" && hasFloatVersion(Name))
Chris Bienemanad070d02014-09-17 20:55:46 +00001299 Ret = optimizeUnaryDoubleFP(CI, B, true);
Bob Wilsond8d92d92013-11-03 06:48:38 +00001300
Chris Bienemanad070d02014-09-17 20:55:46 +00001301 Value *Op = CI->getArgOperand(0);
1302 // Turn exp2(sitofp(x)) -> ldexp(1.0, sext(x)) if sizeof(x) <= 32
1303 // Turn exp2(uitofp(x)) -> ldexp(1.0, zext(x)) if sizeof(x) < 32
David L. Jonesd21529f2017-01-23 23:16:46 +00001304 LibFunc LdExp = LibFunc_ldexpl;
Chris Bienemanad070d02014-09-17 20:55:46 +00001305 if (Op->getType()->isFloatTy())
David L. Jonesd21529f2017-01-23 23:16:46 +00001306 LdExp = LibFunc_ldexpf;
Chris Bienemanad070d02014-09-17 20:55:46 +00001307 else if (Op->getType()->isDoubleTy())
David L. Jonesd21529f2017-01-23 23:16:46 +00001308 LdExp = LibFunc_ldexp;
Chris Bienemanad070d02014-09-17 20:55:46 +00001309
1310 if (TLI->has(LdExp)) {
1311 Value *LdExpArg = nullptr;
1312 if (SIToFPInst *OpC = dyn_cast<SIToFPInst>(Op)) {
1313 if (OpC->getOperand(0)->getType()->getPrimitiveSizeInBits() <= 32)
1314 LdExpArg = B.CreateSExt(OpC->getOperand(0), B.getInt32Ty());
1315 } else if (UIToFPInst *OpC = dyn_cast<UIToFPInst>(Op)) {
1316 if (OpC->getOperand(0)->getType()->getPrimitiveSizeInBits() < 32)
1317 LdExpArg = B.CreateZExt(OpC->getOperand(0), B.getInt32Ty());
1318 }
1319
1320 if (LdExpArg) {
1321 Constant *One = ConstantFP::get(CI->getContext(), APFloat(1.0f));
1322 if (!Op->getType()->isFloatTy())
1323 One = ConstantExpr::getFPExtend(One, Op->getType());
1324
Sanjay Patel0e603fc2016-01-21 22:31:18 +00001325 Module *M = CI->getModule();
Mehdi Aminidb11fdf2017-04-06 20:23:57 +00001326 Value *NewCallee =
1327 M->getOrInsertFunction(TLI->getName(LdExp), Op->getType(),
Serge Guelton59a2d7b2017-04-11 15:01:18 +00001328 Op->getType(), B.getInt32Ty());
Sanjay Patel042aed902016-01-21 22:41:16 +00001329 CallInst *CI = B.CreateCall(NewCallee, {One, LdExpArg});
Chris Bienemanad070d02014-09-17 20:55:46 +00001330 if (const Function *F = dyn_cast<Function>(Callee->stripPointerCasts()))
1331 CI->setCallingConv(F->getCallingConv());
1332
1333 return CI;
1334 }
1335 }
1336 return Ret;
1337}
1338
Sanjay Patel57fd1dc2015-08-16 20:18:19 +00001339Value *LibCallSimplifier::optimizeFMinFMax(CallInst *CI, IRBuilder<> &B) {
Sanjay Patel9beec212016-01-21 22:58:01 +00001340 Function *Callee = CI->getCalledFunction();
Sanjay Patel57fd1dc2015-08-16 20:18:19 +00001341 // If we can shrink the call to a float function rather than a double
1342 // function, do that first.
Davide Italianoa3458772015-11-05 19:18:23 +00001343 StringRef Name = Callee->getName();
Sanjay Patelc7ddb7f2016-01-06 00:32:15 +00001344 if ((Name == "fmin" || Name == "fmax") && hasFloatVersion(Name))
1345 if (Value *Ret = optimizeBinaryDoubleFP(CI, B))
Sanjay Patel57fd1dc2015-08-16 20:18:19 +00001346 return Ret;
Sanjay Patel57fd1dc2015-08-16 20:18:19 +00001347
Benjamin Kramerbb70d752015-08-16 21:16:37 +00001348 IRBuilder<>::FastMathFlagGuard Guard(B);
Sanjay Patel57fd1dc2015-08-16 20:18:19 +00001349 FastMathFlags FMF;
Sanjay Patel629c4112017-11-06 16:27:15 +00001350 if (CI->isFast()) {
1351 // If the call is 'fast', then anything we create here will also be 'fast'.
1352 FMF.setFast();
Sanjay Patel57fd1dc2015-08-16 20:18:19 +00001353 } else {
1354 // At a minimum, no-nans-fp-math must be true.
Sanjay Patel29095ea2016-01-05 20:46:19 +00001355 if (!CI->hasNoNaNs())
Sanjay Patel57fd1dc2015-08-16 20:18:19 +00001356 return nullptr;
1357 // No-signed-zeros is implied by the definitions of fmax/fmin themselves:
1358 // "Ideally, fmax would be sensitive to the sign of zero, for example
NAKAMURA Takumi0d725392015-09-07 00:26:54 +00001359 // fmax(-0. 0, +0. 0) would return +0; however, implementation in software
Sanjay Patel57fd1dc2015-08-16 20:18:19 +00001360 // might be impractical."
1361 FMF.setNoSignedZeros();
1362 FMF.setNoNaNs();
1363 }
Sanjay Patela2528152016-01-12 18:03:37 +00001364 B.setFastMathFlags(FMF);
Sanjay Patel57fd1dc2015-08-16 20:18:19 +00001365
1366 // We have a relaxed floating-point environment. We can ignore NaN-handling
1367 // and transform to a compare and select. We do not have to consider errno or
1368 // exceptions, because fmin/fmax do not have those.
1369 Value *Op0 = CI->getArgOperand(0);
1370 Value *Op1 = CI->getArgOperand(1);
1371 Value *Cmp = Callee->getName().startswith("fmin") ?
1372 B.CreateFCmpOLT(Op0, Op1) : B.CreateFCmpOGT(Op0, Op1);
1373 return B.CreateSelect(Cmp, Op0, Op1);
1374}
1375
Davide Italianob8b71332015-11-29 20:58:04 +00001376Value *LibCallSimplifier::optimizeLog(CallInst *CI, IRBuilder<> &B) {
1377 Function *Callee = CI->getCalledFunction();
1378 Value *Ret = nullptr;
1379 StringRef Name = Callee->getName();
1380 if (UnsafeFPShrink && hasFloatVersion(Name))
1381 Ret = optimizeUnaryDoubleFP(CI, B, true);
Davide Italianob8b71332015-11-29 20:58:04 +00001382
Sanjay Patel629c4112017-11-06 16:27:15 +00001383 if (!CI->isFast())
Davide Italianob8b71332015-11-29 20:58:04 +00001384 return Ret;
1385 Value *Op1 = CI->getArgOperand(0);
1386 auto *OpC = dyn_cast<CallInst>(Op1);
Sanjay Patele896ede2016-01-11 23:31:48 +00001387
Sanjay Patel629c4112017-11-06 16:27:15 +00001388 // The earlier call must also be 'fast' in order to do these transforms.
1389 if (!OpC || !OpC->isFast())
Davide Italianob8b71332015-11-29 20:58:04 +00001390 return Ret;
1391
1392 // log(pow(x,y)) -> y*log(x)
1393 // This is only applicable to log, log2, log10.
1394 if (Name != "log" && Name != "log2" && Name != "log10")
1395 return Ret;
1396
1397 IRBuilder<>::FastMathFlagGuard Guard(B);
1398 FastMathFlags FMF;
Sanjay Patel629c4112017-11-06 16:27:15 +00001399 FMF.setFast();
Sanjay Patela2528152016-01-12 18:03:37 +00001400 B.setFastMathFlags(FMF);
Davide Italianob8b71332015-11-29 20:58:04 +00001401
David L. Jonesd21529f2017-01-23 23:16:46 +00001402 LibFunc Func;
Davide Italianob8b71332015-11-29 20:58:04 +00001403 Function *F = OpC->getCalledFunction();
Davide Italiano0b14f292015-11-29 21:58:56 +00001404 if (F && ((TLI->getLibFunc(F->getName(), Func) && TLI->has(Func) &&
David L. Jonesd21529f2017-01-23 23:16:46 +00001405 Func == LibFunc_pow) || F->getIntrinsicID() == Intrinsic::pow))
Davide Italianob8b71332015-11-29 20:58:04 +00001406 return B.CreateFMul(OpC->getArgOperand(1),
Sanjay Pateld3112a52016-01-19 19:46:10 +00001407 emitUnaryFloatFnCall(OpC->getOperand(0), Callee->getName(), B,
Davide Italianob8b71332015-11-29 20:58:04 +00001408 Callee->getAttributes()), "mul");
Davide Italiano1aeed6a2015-11-30 19:36:35 +00001409
1410 // log(exp2(y)) -> y*log(2)
1411 if (F && Name == "log" && TLI->getLibFunc(F->getName(), Func) &&
David L. Jonesd21529f2017-01-23 23:16:46 +00001412 TLI->has(Func) && Func == LibFunc_exp2)
Davide Italiano1aeed6a2015-11-30 19:36:35 +00001413 return B.CreateFMul(
1414 OpC->getArgOperand(0),
Sanjay Pateld3112a52016-01-19 19:46:10 +00001415 emitUnaryFloatFnCall(ConstantFP::get(CI->getType(), 2.0),
Davide Italiano1aeed6a2015-11-30 19:36:35 +00001416 Callee->getName(), B, Callee->getAttributes()),
1417 "logmul");
Davide Italianob8b71332015-11-29 20:58:04 +00001418 return Ret;
1419}
1420
Sanjay Patelc699a612014-10-16 18:48:17 +00001421Value *LibCallSimplifier::optimizeSqrt(CallInst *CI, IRBuilder<> &B) {
1422 Function *Callee = CI->getCalledFunction();
Sanjay Patelc699a612014-10-16 18:48:17 +00001423 Value *Ret = nullptr;
Justin Lebarcb9b41d2017-01-27 00:58:03 +00001424 // TODO: Once we have a way (other than checking for the existince of the
1425 // libcall) to tell whether our target can lower @llvm.sqrt, relax the
1426 // condition below.
David L. Jonesd21529f2017-01-23 23:16:46 +00001427 if (TLI->has(LibFunc_sqrtf) && (Callee->getName() == "sqrt" ||
Justin Lebarcb9b41d2017-01-27 00:58:03 +00001428 Callee->getIntrinsicID() == Intrinsic::sqrt))
Sanjay Patelc699a612014-10-16 18:48:17 +00001429 Ret = optimizeUnaryDoubleFP(CI, B, true);
Sanjay Patel683f2972016-01-11 22:34:19 +00001430
Sanjay Patel629c4112017-11-06 16:27:15 +00001431 if (!CI->isFast())
Davide Italianoa904e522015-10-29 02:58:44 +00001432 return Ret;
Sanjay Patelc699a612014-10-16 18:48:17 +00001433
Sanjay Patelc2d64612016-01-06 20:52:21 +00001434 Instruction *I = dyn_cast<Instruction>(CI->getArgOperand(0));
Sanjay Patel629c4112017-11-06 16:27:15 +00001435 if (!I || I->getOpcode() != Instruction::FMul || !I->isFast())
Sanjay Patelc2d64612016-01-06 20:52:21 +00001436 return Ret;
1437
1438 // We're looking for a repeated factor in a multiplication tree,
1439 // so we can do this fold: sqrt(x * x) -> fabs(x);
Sanjay Patel683f2972016-01-11 22:34:19 +00001440 // or this fold: sqrt((x * x) * y) -> fabs(x) * sqrt(y).
Sanjay Patelc2d64612016-01-06 20:52:21 +00001441 Value *Op0 = I->getOperand(0);
1442 Value *Op1 = I->getOperand(1);
1443 Value *RepeatOp = nullptr;
1444 Value *OtherOp = nullptr;
1445 if (Op0 == Op1) {
1446 // Simple match: the operands of the multiply are identical.
1447 RepeatOp = Op0;
1448 } else {
1449 // Look for a more complicated pattern: one of the operands is itself
1450 // a multiply, so search for a common factor in that multiply.
1451 // Note: We don't bother looking any deeper than this first level or for
1452 // variations of this pattern because instcombine's visitFMUL and/or the
1453 // reassociation pass should give us this form.
1454 Value *OtherMul0, *OtherMul1;
1455 if (match(Op0, m_FMul(m_Value(OtherMul0), m_Value(OtherMul1)))) {
1456 // Pattern: sqrt((x * y) * z)
Sanjay Patel629c4112017-11-06 16:27:15 +00001457 if (OtherMul0 == OtherMul1 && cast<Instruction>(Op0)->isFast()) {
Sanjay Patelc2d64612016-01-06 20:52:21 +00001458 // Matched: sqrt((x * x) * z)
1459 RepeatOp = OtherMul0;
1460 OtherOp = Op1;
Sanjay Patelc699a612014-10-16 18:48:17 +00001461 }
1462 }
1463 }
Sanjay Patelc2d64612016-01-06 20:52:21 +00001464 if (!RepeatOp)
1465 return Ret;
1466
1467 // Fast math flags for any created instructions should match the sqrt
1468 // and multiply.
Sanjay Patelc2d64612016-01-06 20:52:21 +00001469 IRBuilder<>::FastMathFlagGuard Guard(B);
Sanjay Patela2528152016-01-12 18:03:37 +00001470 B.setFastMathFlags(I->getFastMathFlags());
Sanjay Patel9f67dad2016-01-11 22:35:39 +00001471
Sanjay Patelc2d64612016-01-06 20:52:21 +00001472 // If we found a repeated factor, hoist it out of the square root and
1473 // replace it with the fabs of that factor.
1474 Module *M = Callee->getParent();
1475 Type *ArgType = I->getType();
1476 Value *Fabs = Intrinsic::getDeclaration(M, Intrinsic::fabs, ArgType);
1477 Value *FabsCall = B.CreateCall(Fabs, RepeatOp, "fabs");
1478 if (OtherOp) {
1479 // If we found a non-repeated factor, we still need to get its square
1480 // root. We then multiply that by the value that was simplified out
1481 // of the square root calculation.
1482 Value *Sqrt = Intrinsic::getDeclaration(M, Intrinsic::sqrt, ArgType);
1483 Value *SqrtCall = B.CreateCall(Sqrt, OtherOp, "sqrt");
1484 return B.CreateFMul(FabsCall, SqrtCall);
1485 }
1486 return FabsCall;
Sanjay Patelc699a612014-10-16 18:48:17 +00001487}
1488
Sanjay Patelcddcd722016-01-06 19:23:35 +00001489// TODO: Generalize to handle any trig function and its inverse.
Davide Italiano51507d22015-11-04 23:36:56 +00001490Value *LibCallSimplifier::optimizeTan(CallInst *CI, IRBuilder<> &B) {
1491 Function *Callee = CI->getCalledFunction();
1492 Value *Ret = nullptr;
Davide Italianoa3458772015-11-05 19:18:23 +00001493 StringRef Name = Callee->getName();
1494 if (UnsafeFPShrink && Name == "tan" && hasFloatVersion(Name))
Davide Italiano51507d22015-11-04 23:36:56 +00001495 Ret = optimizeUnaryDoubleFP(CI, B, true);
Davide Italiano51507d22015-11-04 23:36:56 +00001496
Davide Italiano51507d22015-11-04 23:36:56 +00001497 Value *Op1 = CI->getArgOperand(0);
1498 auto *OpC = dyn_cast<CallInst>(Op1);
1499 if (!OpC)
1500 return Ret;
1501
Sanjay Patel629c4112017-11-06 16:27:15 +00001502 // Both calls must be 'fast' in order to remove them.
1503 if (!CI->isFast() || !OpC->isFast())
Sanjay Patelcddcd722016-01-06 19:23:35 +00001504 return Ret;
1505
Davide Italiano51507d22015-11-04 23:36:56 +00001506 // tan(atan(x)) -> x
1507 // tanf(atanf(x)) -> x
1508 // tanl(atanl(x)) -> x
David L. Jonesd21529f2017-01-23 23:16:46 +00001509 LibFunc Func;
Davide Italiano51507d22015-11-04 23:36:56 +00001510 Function *F = OpC->getCalledFunction();
Benjamin Kramerfb419e72015-11-26 09:51:17 +00001511 if (F && TLI->getLibFunc(F->getName(), Func) && TLI->has(Func) &&
David L. Jonesd21529f2017-01-23 23:16:46 +00001512 ((Func == LibFunc_atan && Callee->getName() == "tan") ||
1513 (Func == LibFunc_atanf && Callee->getName() == "tanf") ||
1514 (Func == LibFunc_atanl && Callee->getName() == "tanl")))
Davide Italiano51507d22015-11-04 23:36:56 +00001515 Ret = OpC->getArgOperand(0);
1516 return Ret;
1517}
1518
Sanjay Patel57747212016-01-21 23:38:43 +00001519static bool isTrigLibCall(CallInst *CI) {
Sanjay Patel57747212016-01-21 23:38:43 +00001520 // We can only hope to do anything useful if we can ignore things like errno
1521 // and floating-point exceptions.
Ahmed Bougachad765a822016-04-27 19:04:35 +00001522 // We already checked the prototype.
1523 return CI->hasFnAttr(Attribute::NoUnwind) &&
1524 CI->hasFnAttr(Attribute::ReadNone);
Sanjay Patel57747212016-01-21 23:38:43 +00001525}
1526
Chris Bienemanad070d02014-09-17 20:55:46 +00001527static void insertSinCosCall(IRBuilder<> &B, Function *OrigCallee, Value *Arg,
1528 bool UseFloat, Value *&Sin, Value *&Cos,
Sanjay Patel57747212016-01-21 23:38:43 +00001529 Value *&SinCos) {
1530 Type *ArgTy = Arg->getType();
1531 Type *ResTy;
1532 StringRef Name;
1533
1534 Triple T(OrigCallee->getParent()->getTargetTriple());
1535 if (UseFloat) {
1536 Name = "__sincospif_stret";
1537
1538 assert(T.getArch() != Triple::x86 && "x86 messy and unsupported for now");
1539 // x86_64 can't use {float, float} since that would be returned in both
1540 // xmm0 and xmm1, which isn't what a real struct would do.
1541 ResTy = T.getArch() == Triple::x86_64
Serge Gueltone38003f2017-05-09 19:31:13 +00001542 ? static_cast<Type *>(VectorType::get(ArgTy, 2))
1543 : static_cast<Type *>(StructType::get(ArgTy, ArgTy));
Sanjay Patel57747212016-01-21 23:38:43 +00001544 } else {
1545 Name = "__sincospi_stret";
Serge Gueltone38003f2017-05-09 19:31:13 +00001546 ResTy = StructType::get(ArgTy, ArgTy);
Sanjay Patel57747212016-01-21 23:38:43 +00001547 }
1548
1549 Module *M = OrigCallee->getParent();
Mehdi Aminidb11fdf2017-04-06 20:23:57 +00001550 Value *Callee = M->getOrInsertFunction(Name, OrigCallee->getAttributes(),
Serge Guelton59a2d7b2017-04-11 15:01:18 +00001551 ResTy, ArgTy);
Sanjay Patel57747212016-01-21 23:38:43 +00001552
1553 if (Instruction *ArgInst = dyn_cast<Instruction>(Arg)) {
1554 // If the argument is an instruction, it must dominate all uses so put our
1555 // sincos call there.
1556 B.SetInsertPoint(ArgInst->getParent(), ++ArgInst->getIterator());
1557 } else {
1558 // Otherwise (e.g. for a constant) the beginning of the function is as
1559 // good a place as any.
1560 BasicBlock &EntryBB = B.GetInsertBlock()->getParent()->getEntryBlock();
1561 B.SetInsertPoint(&EntryBB, EntryBB.begin());
1562 }
1563
1564 SinCos = B.CreateCall(Callee, Arg, "sincospi");
1565
1566 if (SinCos->getType()->isStructTy()) {
1567 Sin = B.CreateExtractValue(SinCos, 0, "sinpi");
1568 Cos = B.CreateExtractValue(SinCos, 1, "cospi");
1569 } else {
1570 Sin = B.CreateExtractElement(SinCos, ConstantInt::get(B.getInt32Ty(), 0),
1571 "sinpi");
1572 Cos = B.CreateExtractElement(SinCos, ConstantInt::get(B.getInt32Ty(), 1),
1573 "cospi");
1574 }
1575}
Chris Bienemanad070d02014-09-17 20:55:46 +00001576
1577Value *LibCallSimplifier::optimizeSinCosPi(CallInst *CI, IRBuilder<> &B) {
Chris Bienemanad070d02014-09-17 20:55:46 +00001578 // Make sure the prototype is as expected, otherwise the rest of the
1579 // function is probably invalid and likely to abort.
1580 if (!isTrigLibCall(CI))
1581 return nullptr;
1582
1583 Value *Arg = CI->getArgOperand(0);
1584 SmallVector<CallInst *, 1> SinCalls;
1585 SmallVector<CallInst *, 1> CosCalls;
1586 SmallVector<CallInst *, 1> SinCosCalls;
1587
1588 bool IsFloat = Arg->getType()->isFloatTy();
1589
1590 // Look for all compatible sinpi, cospi and sincospi calls with the same
1591 // argument. If there are enough (in some sense) we can make the
1592 // substitution.
David Majnemerabae6b52016-03-19 04:53:02 +00001593 Function *F = CI->getFunction();
Chris Bienemanad070d02014-09-17 20:55:46 +00001594 for (User *U : Arg->users())
David Majnemerabae6b52016-03-19 04:53:02 +00001595 classifyArgUse(U, F, IsFloat, SinCalls, CosCalls, SinCosCalls);
Chris Bienemanad070d02014-09-17 20:55:46 +00001596
1597 // It's only worthwhile if both sinpi and cospi are actually used.
1598 if (SinCosCalls.empty() && (SinCalls.empty() || CosCalls.empty()))
1599 return nullptr;
1600
1601 Value *Sin, *Cos, *SinCos;
1602 insertSinCosCall(B, CI->getCalledFunction(), Arg, IsFloat, Sin, Cos, SinCos);
1603
Davide Italianof024a562016-12-16 02:28:38 +00001604 auto replaceTrigInsts = [this](SmallVectorImpl<CallInst *> &Calls,
1605 Value *Res) {
1606 for (CallInst *C : Calls)
1607 replaceAllUsesWith(C, Res);
1608 };
1609
Chris Bienemanad070d02014-09-17 20:55:46 +00001610 replaceTrigInsts(SinCalls, Sin);
1611 replaceTrigInsts(CosCalls, Cos);
1612 replaceTrigInsts(SinCosCalls, SinCos);
1613
1614 return nullptr;
1615}
1616
David Majnemerabae6b52016-03-19 04:53:02 +00001617void LibCallSimplifier::classifyArgUse(
1618 Value *Val, Function *F, bool IsFloat,
1619 SmallVectorImpl<CallInst *> &SinCalls,
1620 SmallVectorImpl<CallInst *> &CosCalls,
1621 SmallVectorImpl<CallInst *> &SinCosCalls) {
Chris Bienemanad070d02014-09-17 20:55:46 +00001622 CallInst *CI = dyn_cast<CallInst>(Val);
1623
1624 if (!CI)
1625 return;
1626
David Majnemerabae6b52016-03-19 04:53:02 +00001627 // Don't consider calls in other functions.
1628 if (CI->getFunction() != F)
1629 return;
1630
Chris Bienemanad070d02014-09-17 20:55:46 +00001631 Function *Callee = CI->getCalledFunction();
David L. Jonesd21529f2017-01-23 23:16:46 +00001632 LibFunc Func;
Ahmed Bougachad765a822016-04-27 19:04:35 +00001633 if (!Callee || !TLI->getLibFunc(*Callee, Func) || !TLI->has(Func) ||
Benjamin Kramer89766e52015-11-28 21:43:12 +00001634 !isTrigLibCall(CI))
Chris Bienemanad070d02014-09-17 20:55:46 +00001635 return;
1636
1637 if (IsFloat) {
David L. Jonesd21529f2017-01-23 23:16:46 +00001638 if (Func == LibFunc_sinpif)
Chris Bienemanad070d02014-09-17 20:55:46 +00001639 SinCalls.push_back(CI);
David L. Jonesd21529f2017-01-23 23:16:46 +00001640 else if (Func == LibFunc_cospif)
Chris Bienemanad070d02014-09-17 20:55:46 +00001641 CosCalls.push_back(CI);
David L. Jonesd21529f2017-01-23 23:16:46 +00001642 else if (Func == LibFunc_sincospif_stret)
Chris Bienemanad070d02014-09-17 20:55:46 +00001643 SinCosCalls.push_back(CI);
1644 } else {
David L. Jonesd21529f2017-01-23 23:16:46 +00001645 if (Func == LibFunc_sinpi)
Chris Bienemanad070d02014-09-17 20:55:46 +00001646 SinCalls.push_back(CI);
David L. Jonesd21529f2017-01-23 23:16:46 +00001647 else if (Func == LibFunc_cospi)
Chris Bienemanad070d02014-09-17 20:55:46 +00001648 CosCalls.push_back(CI);
David L. Jonesd21529f2017-01-23 23:16:46 +00001649 else if (Func == LibFunc_sincospi_stret)
Chris Bienemanad070d02014-09-17 20:55:46 +00001650 SinCosCalls.push_back(CI);
1651 }
1652}
1653
Meador Inge7415f842012-11-25 20:45:27 +00001654//===----------------------------------------------------------------------===//
1655// Integer Library Call Optimizations
1656//===----------------------------------------------------------------------===//
1657
Chris Bienemanad070d02014-09-17 20:55:46 +00001658Value *LibCallSimplifier::optimizeFFS(CallInst *CI, IRBuilder<> &B) {
Chris Bienemanad070d02014-09-17 20:55:46 +00001659 // ffs(x) -> x != 0 ? (i32)llvm.cttz(x)+1 : 0
Davide Italiano890e8502016-12-15 23:11:00 +00001660 Value *Op = CI->getArgOperand(0);
Chris Bienemanad070d02014-09-17 20:55:46 +00001661 Type *ArgType = Op->getType();
Davide Italiano890e8502016-12-15 23:11:00 +00001662 Value *F = Intrinsic::getDeclaration(CI->getCalledFunction()->getParent(),
1663 Intrinsic::cttz, ArgType);
Davide Italianoa1953862015-08-13 20:34:26 +00001664 Value *V = B.CreateCall(F, {Op, B.getTrue()}, "cttz");
Chris Bienemanad070d02014-09-17 20:55:46 +00001665 V = B.CreateAdd(V, ConstantInt::get(V->getType(), 1));
1666 V = B.CreateIntCast(V, B.getInt32Ty(), false);
Meador Ingea0b6d872012-11-26 00:24:07 +00001667
Chris Bienemanad070d02014-09-17 20:55:46 +00001668 Value *Cond = B.CreateICmpNE(Op, Constant::getNullValue(ArgType));
1669 return B.CreateSelect(Cond, V, B.getInt32(0));
1670}
Meador Ingea0b6d872012-11-26 00:24:07 +00001671
Davide Italiano85ad36b2016-12-15 23:45:11 +00001672Value *LibCallSimplifier::optimizeFls(CallInst *CI, IRBuilder<> &B) {
1673 // fls(x) -> (i32)(sizeInBits(x) - llvm.ctlz(x, false))
1674 Value *Op = CI->getArgOperand(0);
1675 Type *ArgType = Op->getType();
1676 Value *F = Intrinsic::getDeclaration(CI->getCalledFunction()->getParent(),
1677 Intrinsic::ctlz, ArgType);
1678 Value *V = B.CreateCall(F, {Op, B.getFalse()}, "ctlz");
1679 V = B.CreateSub(ConstantInt::get(V->getType(), ArgType->getIntegerBitWidth()),
1680 V);
1681 return B.CreateIntCast(V, CI->getType(), false);
1682}
1683
Chris Bienemanad070d02014-09-17 20:55:46 +00001684Value *LibCallSimplifier::optimizeAbs(CallInst *CI, IRBuilder<> &B) {
Sanjay Patel4b969352018-05-22 23:29:40 +00001685 // abs(x) -> x <s 0 ? -x : x
1686 // The negation has 'nsw' because abs of INT_MIN is undefined.
1687 Value *X = CI->getArgOperand(0);
1688 Value *IsNeg = B.CreateICmpSLT(X, Constant::getNullValue(X->getType()));
1689 Value *NegX = B.CreateNSWNeg(X, "neg");
1690 return B.CreateSelect(IsNeg, NegX, X);
Chris Bienemanad070d02014-09-17 20:55:46 +00001691}
Meador Inge9a59ab62012-11-26 02:31:59 +00001692
Chris Bienemanad070d02014-09-17 20:55:46 +00001693Value *LibCallSimplifier::optimizeIsDigit(CallInst *CI, IRBuilder<> &B) {
Chris Bienemanad070d02014-09-17 20:55:46 +00001694 // isdigit(c) -> (c-'0') <u 10
1695 Value *Op = CI->getArgOperand(0);
1696 Op = B.CreateSub(Op, B.getInt32('0'), "isdigittmp");
1697 Op = B.CreateICmpULT(Op, B.getInt32(10), "isdigit");
1698 return B.CreateZExt(Op, CI->getType());
1699}
Meador Ingea62a39e2012-11-26 03:10:07 +00001700
Chris Bienemanad070d02014-09-17 20:55:46 +00001701Value *LibCallSimplifier::optimizeIsAscii(CallInst *CI, IRBuilder<> &B) {
Chris Bienemanad070d02014-09-17 20:55:46 +00001702 // isascii(c) -> c <u 128
1703 Value *Op = CI->getArgOperand(0);
1704 Op = B.CreateICmpULT(Op, B.getInt32(128), "isascii");
1705 return B.CreateZExt(Op, CI->getType());
1706}
1707
1708Value *LibCallSimplifier::optimizeToAscii(CallInst *CI, IRBuilder<> &B) {
Chris Bienemanad070d02014-09-17 20:55:46 +00001709 // toascii(c) -> c & 0x7f
1710 return B.CreateAnd(CI->getArgOperand(0),
1711 ConstantInt::get(CI->getType(), 0x7F));
1712}
Meador Inge604937d2012-11-26 03:38:52 +00001713
David Bolvanskycb8ca5f32018-04-25 18:58:53 +00001714Value *LibCallSimplifier::optimizeAtoi(CallInst *CI, IRBuilder<> &B) {
1715 StringRef Str;
1716 if (!getConstantStringInfo(CI->getArgOperand(0), Str))
1717 return nullptr;
1718
1719 return convertStrToNumber(CI, Str, 10);
1720}
1721
1722Value *LibCallSimplifier::optimizeStrtol(CallInst *CI, IRBuilder<> &B) {
1723 StringRef Str;
1724 if (!getConstantStringInfo(CI->getArgOperand(0), Str))
1725 return nullptr;
1726
1727 if (!isa<ConstantPointerNull>(CI->getArgOperand(1)))
1728 return nullptr;
1729
1730 if (ConstantInt *CInt = dyn_cast<ConstantInt>(CI->getArgOperand(2))) {
1731 return convertStrToNumber(CI, Str, CInt->getSExtValue());
1732 }
1733
1734 return nullptr;
1735}
1736
Meador Inge08ca1152012-11-26 20:37:20 +00001737//===----------------------------------------------------------------------===//
1738// Formatting and IO Library Call Optimizations
1739//===----------------------------------------------------------------------===//
1740
Chris Bienemanad070d02014-09-17 20:55:46 +00001741static bool isReportingError(Function *Callee, CallInst *CI, int StreamArg);
Hal Finkel66cd3f12013-11-17 02:06:35 +00001742
Chris Bienemanad070d02014-09-17 20:55:46 +00001743Value *LibCallSimplifier::optimizeErrorReporting(CallInst *CI, IRBuilder<> &B,
1744 int StreamArg) {
Ahmed Bougachad765a822016-04-27 19:04:35 +00001745 Function *Callee = CI->getCalledFunction();
Chris Bienemanad070d02014-09-17 20:55:46 +00001746 // Error reporting calls should be cold, mark them as such.
1747 // This applies even to non-builtin calls: it is only a hint and applies to
1748 // functions that the frontend might not understand as builtins.
Hal Finkel66cd3f12013-11-17 02:06:35 +00001749
Chris Bienemanad070d02014-09-17 20:55:46 +00001750 // This heuristic was suggested in:
1751 // Improving Static Branch Prediction in a Compiler
1752 // Brian L. Deitrich, Ben-Chung Cheng, Wen-mei W. Hwu
1753 // Proceedings of PACT'98, Oct. 1998, IEEE
Chris Bienemanad070d02014-09-17 20:55:46 +00001754 if (!CI->hasFnAttr(Attribute::Cold) &&
1755 isReportingError(Callee, CI, StreamArg)) {
Reid Klecknerb5180542017-03-21 16:57:19 +00001756 CI->addAttribute(AttributeList::FunctionIndex, Attribute::Cold);
Chris Bienemanad070d02014-09-17 20:55:46 +00001757 }
Hal Finkel66cd3f12013-11-17 02:06:35 +00001758
Chris Bienemanad070d02014-09-17 20:55:46 +00001759 return nullptr;
1760}
1761
1762static bool isReportingError(Function *Callee, CallInst *CI, int StreamArg) {
Davide Italiano5b65f122017-04-25 03:48:47 +00001763 if (!Callee || !Callee->isDeclaration())
Chris Bienemanad070d02014-09-17 20:55:46 +00001764 return false;
1765
1766 if (StreamArg < 0)
1767 return true;
1768
1769 // These functions might be considered cold, but only if their stream
1770 // argument is stderr.
1771
1772 if (StreamArg >= (int)CI->getNumArgOperands())
1773 return false;
1774 LoadInst *LI = dyn_cast<LoadInst>(CI->getArgOperand(StreamArg));
1775 if (!LI)
1776 return false;
1777 GlobalVariable *GV = dyn_cast<GlobalVariable>(LI->getPointerOperand());
1778 if (!GV || !GV->isDeclaration())
1779 return false;
1780 return GV->getName() == "stderr";
1781}
1782
1783Value *LibCallSimplifier::optimizePrintFString(CallInst *CI, IRBuilder<> &B) {
1784 // Check for a fixed format string.
1785 StringRef FormatStr;
1786 if (!getConstantStringInfo(CI->getArgOperand(0), FormatStr))
Craig Topperf40110f2014-04-25 05:29:35 +00001787 return nullptr;
Hal Finkel66cd3f12013-11-17 02:06:35 +00001788
Chris Bienemanad070d02014-09-17 20:55:46 +00001789 // Empty format string -> noop.
1790 if (FormatStr.empty()) // Tolerate printf's declared void.
1791 return CI->use_empty() ? (Value *)CI : ConstantInt::get(CI->getType(), 0);
Hal Finkel66cd3f12013-11-17 02:06:35 +00001792
Chris Bienemanad070d02014-09-17 20:55:46 +00001793 // Do not do any of the following transformations if the printf return value
1794 // is used, in general the printf return value is not compatible with either
1795 // putchar() or puts().
1796 if (!CI->use_empty())
Craig Topperf40110f2014-04-25 05:29:35 +00001797 return nullptr;
Chris Bienemanad070d02014-09-17 20:55:46 +00001798
Joerg Sonnenberger8ffe7ab2016-05-09 14:36:16 +00001799 // printf("x") -> putchar('x'), even for "%" and "%%".
1800 if (FormatStr.size() == 1 || FormatStr == "%%")
Davide Italianod4f5a052016-04-03 01:46:52 +00001801 return emitPutChar(B.getInt32(FormatStr[0]), B, TLI);
Meador Inge08ca1152012-11-26 20:37:20 +00001802
Davide Italiano6db1dcb2016-03-28 15:54:01 +00001803 // printf("%s", "a") --> putchar('a')
1804 if (FormatStr == "%s" && CI->getNumArgOperands() > 1) {
1805 StringRef ChrStr;
1806 if (!getConstantStringInfo(CI->getOperand(1), ChrStr))
1807 return nullptr;
1808 if (ChrStr.size() != 1)
1809 return nullptr;
Davide Italianod4f5a052016-04-03 01:46:52 +00001810 return emitPutChar(B.getInt32(ChrStr[0]), B, TLI);
Davide Italiano6db1dcb2016-03-28 15:54:01 +00001811 }
1812
Chris Bienemanad070d02014-09-17 20:55:46 +00001813 // printf("foo\n") --> puts("foo")
1814 if (FormatStr[FormatStr.size() - 1] == '\n' &&
1815 FormatStr.find('%') == StringRef::npos) { // No format characters.
1816 // Create a string literal with no \n on it. We expect the constant merge
1817 // pass to be run after this pass, to merge duplicate strings.
1818 FormatStr = FormatStr.drop_back();
1819 Value *GV = B.CreateGlobalString(FormatStr, "str");
Davide Italianod4f5a052016-04-03 01:46:52 +00001820 return emitPutS(GV, B, TLI);
Chris Bienemanad070d02014-09-17 20:55:46 +00001821 }
Meador Inge08ca1152012-11-26 20:37:20 +00001822
Chris Bienemanad070d02014-09-17 20:55:46 +00001823 // Optimize specific format strings.
1824 // printf("%c", chr) --> putchar(chr)
1825 if (FormatStr == "%c" && CI->getNumArgOperands() > 1 &&
Davide Italianod4f5a052016-04-03 01:46:52 +00001826 CI->getArgOperand(1)->getType()->isIntegerTy())
1827 return emitPutChar(CI->getArgOperand(1), B, TLI);
Chris Bienemanad070d02014-09-17 20:55:46 +00001828
1829 // printf("%s\n", str) --> puts(str)
1830 if (FormatStr == "%s\n" && CI->getNumArgOperands() > 1 &&
Davide Italianod4f5a052016-04-03 01:46:52 +00001831 CI->getArgOperand(1)->getType()->isPointerTy())
Sanjay Pateld3112a52016-01-19 19:46:10 +00001832 return emitPutS(CI->getArgOperand(1), B, TLI);
Chris Bienemanad070d02014-09-17 20:55:46 +00001833 return nullptr;
1834}
1835
1836Value *LibCallSimplifier::optimizePrintF(CallInst *CI, IRBuilder<> &B) {
1837
1838 Function *Callee = CI->getCalledFunction();
Chris Bienemanad070d02014-09-17 20:55:46 +00001839 FunctionType *FT = Callee->getFunctionType();
Chris Bienemanad070d02014-09-17 20:55:46 +00001840 if (Value *V = optimizePrintFString(CI, B)) {
1841 return V;
1842 }
1843
1844 // printf(format, ...) -> iprintf(format, ...) if no floating point
1845 // arguments.
David L. Jonesd21529f2017-01-23 23:16:46 +00001846 if (TLI->has(LibFunc_iprintf) && !callHasFloatingPointArgument(CI)) {
Chris Bienemanad070d02014-09-17 20:55:46 +00001847 Module *M = B.GetInsertBlock()->getParent()->getParent();
1848 Constant *IPrintFFn =
Meador Inge08ca1152012-11-26 20:37:20 +00001849 M->getOrInsertFunction("iprintf", FT, Callee->getAttributes());
Chris Bienemanad070d02014-09-17 20:55:46 +00001850 CallInst *New = cast<CallInst>(CI->clone());
1851 New->setCalledFunction(IPrintFFn);
1852 B.Insert(New);
1853 return New;
Meador Inge08ca1152012-11-26 20:37:20 +00001854 }
Chris Bienemanad070d02014-09-17 20:55:46 +00001855 return nullptr;
1856}
Meador Inge08ca1152012-11-26 20:37:20 +00001857
Chris Bienemanad070d02014-09-17 20:55:46 +00001858Value *LibCallSimplifier::optimizeSPrintFString(CallInst *CI, IRBuilder<> &B) {
1859 // Check for a fixed format string.
1860 StringRef FormatStr;
1861 if (!getConstantStringInfo(CI->getArgOperand(1), FormatStr))
Craig Topperf40110f2014-04-25 05:29:35 +00001862 return nullptr;
Meador Inge25c9b3b2012-11-27 05:57:54 +00001863
Chris Bienemanad070d02014-09-17 20:55:46 +00001864 // If we just have a format string (nothing else crazy) transform it.
1865 if (CI->getNumArgOperands() == 2) {
1866 // Make sure there's no % in the constant array. We could try to handle
1867 // %% -> % in the future if we cared.
David Bolvansky5430b7372018-05-31 16:39:27 +00001868 if (FormatStr.find('%') != StringRef::npos)
1869 return nullptr; // we found a format specifier, bail out.
Hal Finkel66cd3f12013-11-17 02:06:35 +00001870
Daniel Neilson8acd8b02018-02-05 21:23:22 +00001871 // sprintf(str, fmt) -> llvm.memcpy(align 1 str, align 1 fmt, strlen(fmt)+1)
1872 B.CreateMemCpy(CI->getArgOperand(0), 1, CI->getArgOperand(1), 1,
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001873 ConstantInt::get(DL.getIntPtrType(CI->getContext()),
Daniel Neilson8acd8b02018-02-05 21:23:22 +00001874 FormatStr.size() + 1)); // Copy the null byte.
Chris Bienemanad070d02014-09-17 20:55:46 +00001875 return ConstantInt::get(CI->getType(), FormatStr.size());
Meador Ingef8e72502012-11-29 15:45:43 +00001876 }
Meador Ingef8e72502012-11-29 15:45:43 +00001877
Chris Bienemanad070d02014-09-17 20:55:46 +00001878 // The remaining optimizations require the format string to be "%s" or "%c"
1879 // and have an extra operand.
1880 if (FormatStr.size() != 2 || FormatStr[0] != '%' ||
1881 CI->getNumArgOperands() < 3)
Craig Topperf40110f2014-04-25 05:29:35 +00001882 return nullptr;
Meador Inge75798bb2012-11-29 19:15:17 +00001883
Chris Bienemanad070d02014-09-17 20:55:46 +00001884 // Decode the second character of the format string.
1885 if (FormatStr[1] == 'c') {
1886 // sprintf(dst, "%c", chr) --> *(i8*)dst = chr; *((i8*)dst+1) = 0
1887 if (!CI->getArgOperand(2)->getType()->isIntegerTy())
1888 return nullptr;
1889 Value *V = B.CreateTrunc(CI->getArgOperand(2), B.getInt8Ty(), "char");
Sanjay Pateld3112a52016-01-19 19:46:10 +00001890 Value *Ptr = castToCStr(CI->getArgOperand(0), B);
Chris Bienemanad070d02014-09-17 20:55:46 +00001891 B.CreateStore(V, Ptr);
David Blaikie3909da72015-03-30 20:42:56 +00001892 Ptr = B.CreateGEP(B.getInt8Ty(), Ptr, B.getInt32(1), "nul");
Chris Bienemanad070d02014-09-17 20:55:46 +00001893 B.CreateStore(B.getInt8(0), Ptr);
Meador Ingedf796f82012-10-13 16:45:24 +00001894
Chris Bienemanad070d02014-09-17 20:55:46 +00001895 return ConstantInt::get(CI->getType(), 1);
Meador Ingedf796f82012-10-13 16:45:24 +00001896 }
1897
Chris Bienemanad070d02014-09-17 20:55:46 +00001898 if (FormatStr[1] == 's') {
Chris Bienemanad070d02014-09-17 20:55:46 +00001899 // sprintf(dest, "%s", str) -> llvm.memcpy(dest, str, strlen(str)+1, 1)
1900 if (!CI->getArgOperand(2)->getType()->isPointerTy())
1901 return nullptr;
1902
Sanjay Pateld3112a52016-01-19 19:46:10 +00001903 Value *Len = emitStrLen(CI->getArgOperand(2), B, DL, TLI);
Chris Bienemanad070d02014-09-17 20:55:46 +00001904 if (!Len)
1905 return nullptr;
David Majnemerabb9f552016-04-26 21:04:47 +00001906 Value *IncLen =
1907 B.CreateAdd(Len, ConstantInt::get(Len->getType(), 1), "leninc");
Daniel Neilson8acd8b02018-02-05 21:23:22 +00001908 B.CreateMemCpy(CI->getArgOperand(0), 1, CI->getArgOperand(2), 1, IncLen);
Chris Bienemanad070d02014-09-17 20:55:46 +00001909
1910 // The sprintf result is the unincremented number of bytes in the string.
1911 return B.CreateIntCast(Len, CI->getType(), false);
1912 }
1913 return nullptr;
1914}
1915
1916Value *LibCallSimplifier::optimizeSPrintF(CallInst *CI, IRBuilder<> &B) {
1917 Function *Callee = CI->getCalledFunction();
Chris Bienemanad070d02014-09-17 20:55:46 +00001918 FunctionType *FT = Callee->getFunctionType();
Chris Bienemanad070d02014-09-17 20:55:46 +00001919 if (Value *V = optimizeSPrintFString(CI, B)) {
1920 return V;
1921 }
1922
1923 // sprintf(str, format, ...) -> siprintf(str, format, ...) if no floating
1924 // point arguments.
David L. Jonesd21529f2017-01-23 23:16:46 +00001925 if (TLI->has(LibFunc_siprintf) && !callHasFloatingPointArgument(CI)) {
Chris Bienemanad070d02014-09-17 20:55:46 +00001926 Module *M = B.GetInsertBlock()->getParent()->getParent();
1927 Constant *SIPrintFFn =
1928 M->getOrInsertFunction("siprintf", FT, Callee->getAttributes());
1929 CallInst *New = cast<CallInst>(CI->clone());
1930 New->setCalledFunction(SIPrintFFn);
1931 B.Insert(New);
1932 return New;
1933 }
1934 return nullptr;
1935}
1936
David Bolvanskycd93c4e2018-05-11 17:50:49 +00001937Value *LibCallSimplifier::optimizeSnPrintFString(CallInst *CI, IRBuilder<> &B) {
1938 // Check for a fixed format string.
1939 StringRef FormatStr;
1940 if (!getConstantStringInfo(CI->getArgOperand(2), FormatStr))
1941 return nullptr;
1942
1943 // Check for size
1944 ConstantInt *Size = dyn_cast<ConstantInt>(CI->getArgOperand(1));
1945 if (!Size)
1946 return nullptr;
1947
1948 uint64_t N = Size->getZExtValue();
1949
1950 // If we just have a format string (nothing else crazy) transform it.
1951 if (CI->getNumArgOperands() == 3) {
1952 // Make sure there's no % in the constant array. We could try to handle
1953 // %% -> % in the future if we cared.
David Bolvansky5430b7372018-05-31 16:39:27 +00001954 if (FormatStr.find('%') != StringRef::npos)
1955 return nullptr; // we found a format specifier, bail out.
David Bolvanskycd93c4e2018-05-11 17:50:49 +00001956
1957 if (N == 0)
1958 return ConstantInt::get(CI->getType(), FormatStr.size());
1959 else if (N < FormatStr.size() + 1)
1960 return nullptr;
1961
1962 // sprintf(str, size, fmt) -> llvm.memcpy(align 1 str, align 1 fmt,
1963 // strlen(fmt)+1)
1964 B.CreateMemCpy(
1965 CI->getArgOperand(0), 1, CI->getArgOperand(2), 1,
1966 ConstantInt::get(DL.getIntPtrType(CI->getContext()),
1967 FormatStr.size() + 1)); // Copy the null byte.
1968 return ConstantInt::get(CI->getType(), FormatStr.size());
1969 }
1970
1971 // The remaining optimizations require the format string to be "%s" or "%c"
1972 // and have an extra operand.
1973 if (FormatStr.size() == 2 && FormatStr[0] == '%' &&
1974 CI->getNumArgOperands() == 4) {
1975
1976 // Decode the second character of the format string.
1977 if (FormatStr[1] == 'c') {
1978 if (N == 0)
1979 return ConstantInt::get(CI->getType(), 1);
1980 else if (N == 1)
1981 return nullptr;
1982
1983 // snprintf(dst, size, "%c", chr) --> *(i8*)dst = chr; *((i8*)dst+1) = 0
1984 if (!CI->getArgOperand(3)->getType()->isIntegerTy())
1985 return nullptr;
1986 Value *V = B.CreateTrunc(CI->getArgOperand(3), B.getInt8Ty(), "char");
1987 Value *Ptr = castToCStr(CI->getArgOperand(0), B);
1988 B.CreateStore(V, Ptr);
1989 Ptr = B.CreateGEP(B.getInt8Ty(), Ptr, B.getInt32(1), "nul");
1990 B.CreateStore(B.getInt8(0), Ptr);
1991
1992 return ConstantInt::get(CI->getType(), 1);
1993 }
1994
1995 if (FormatStr[1] == 's') {
1996 // snprintf(dest, size, "%s", str) to llvm.memcpy(dest, str, len+1, 1)
1997 StringRef Str;
1998 if (!getConstantStringInfo(CI->getArgOperand(3), Str))
1999 return nullptr;
2000
2001 if (N == 0)
2002 return ConstantInt::get(CI->getType(), Str.size());
2003 else if (N < Str.size() + 1)
2004 return nullptr;
2005
2006 B.CreateMemCpy(CI->getArgOperand(0), 1, CI->getArgOperand(3), 1,
2007 ConstantInt::get(CI->getType(), Str.size() + 1));
2008
2009 // The snprintf result is the unincremented number of bytes in the string.
2010 return ConstantInt::get(CI->getType(), Str.size());
2011 }
2012 }
2013 return nullptr;
2014}
2015
2016Value *LibCallSimplifier::optimizeSnPrintF(CallInst *CI, IRBuilder<> &B) {
2017 if (Value *V = optimizeSnPrintFString(CI, B)) {
2018 return V;
2019 }
2020
2021 return nullptr;
2022}
2023
Chris Bienemanad070d02014-09-17 20:55:46 +00002024Value *LibCallSimplifier::optimizeFPrintFString(CallInst *CI, IRBuilder<> &B) {
2025 optimizeErrorReporting(CI, B, 0);
2026
2027 // All the optimizations depend on the format string.
2028 StringRef FormatStr;
2029 if (!getConstantStringInfo(CI->getArgOperand(1), FormatStr))
2030 return nullptr;
2031
2032 // Do not do any of the following transformations if the fprintf return
2033 // value is used, in general the fprintf return value is not compatible
2034 // with fwrite(), fputc() or fputs().
2035 if (!CI->use_empty())
2036 return nullptr;
2037
2038 // fprintf(F, "foo") --> fwrite("foo", 3, 1, F)
2039 if (CI->getNumArgOperands() == 2) {
David Bolvansky5430b7372018-05-31 16:39:27 +00002040 // Could handle %% -> % if we cared.
2041 if (FormatStr.find('%') != StringRef::npos)
2042 return nullptr; // We found a format specifier.
Chris Bienemanad070d02014-09-17 20:55:46 +00002043
Sanjay Pateld3112a52016-01-19 19:46:10 +00002044 return emitFWrite(
Chris Bienemanad070d02014-09-17 20:55:46 +00002045 CI->getArgOperand(1),
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002046 ConstantInt::get(DL.getIntPtrType(CI->getContext()), FormatStr.size()),
Chris Bienemanad070d02014-09-17 20:55:46 +00002047 CI->getArgOperand(0), B, DL, TLI);
2048 }
2049
2050 // The remaining optimizations require the format string to be "%s" or "%c"
2051 // and have an extra operand.
2052 if (FormatStr.size() != 2 || FormatStr[0] != '%' ||
2053 CI->getNumArgOperands() < 3)
2054 return nullptr;
2055
2056 // Decode the second character of the format string.
2057 if (FormatStr[1] == 'c') {
2058 // fprintf(F, "%c", chr) --> fputc(chr, F)
2059 if (!CI->getArgOperand(2)->getType()->isIntegerTy())
2060 return nullptr;
Sanjay Pateld3112a52016-01-19 19:46:10 +00002061 return emitFPutC(CI->getArgOperand(2), CI->getArgOperand(0), B, TLI);
Chris Bienemanad070d02014-09-17 20:55:46 +00002062 }
2063
2064 if (FormatStr[1] == 's') {
2065 // fprintf(F, "%s", str) --> fputs(str, F)
2066 if (!CI->getArgOperand(2)->getType()->isPointerTy())
2067 return nullptr;
Sanjay Pateld3112a52016-01-19 19:46:10 +00002068 return emitFPutS(CI->getArgOperand(2), CI->getArgOperand(0), B, TLI);
Chris Bienemanad070d02014-09-17 20:55:46 +00002069 }
2070 return nullptr;
2071}
2072
2073Value *LibCallSimplifier::optimizeFPrintF(CallInst *CI, IRBuilder<> &B) {
2074 Function *Callee = CI->getCalledFunction();
Chris Bienemanad070d02014-09-17 20:55:46 +00002075 FunctionType *FT = Callee->getFunctionType();
Chris Bienemanad070d02014-09-17 20:55:46 +00002076 if (Value *V = optimizeFPrintFString(CI, B)) {
2077 return V;
2078 }
2079
2080 // fprintf(stream, format, ...) -> fiprintf(stream, format, ...) if no
2081 // floating point arguments.
David L. Jonesd21529f2017-01-23 23:16:46 +00002082 if (TLI->has(LibFunc_fiprintf) && !callHasFloatingPointArgument(CI)) {
Chris Bienemanad070d02014-09-17 20:55:46 +00002083 Module *M = B.GetInsertBlock()->getParent()->getParent();
2084 Constant *FIPrintFFn =
2085 M->getOrInsertFunction("fiprintf", FT, Callee->getAttributes());
2086 CallInst *New = cast<CallInst>(CI->clone());
2087 New->setCalledFunction(FIPrintFFn);
2088 B.Insert(New);
2089 return New;
2090 }
2091 return nullptr;
2092}
2093
2094Value *LibCallSimplifier::optimizeFWrite(CallInst *CI, IRBuilder<> &B) {
2095 optimizeErrorReporting(CI, B, 3);
2096
Chris Bienemanad070d02014-09-17 20:55:46 +00002097 // Get the element size and count.
2098 ConstantInt *SizeC = dyn_cast<ConstantInt>(CI->getArgOperand(1));
2099 ConstantInt *CountC = dyn_cast<ConstantInt>(CI->getArgOperand(2));
David Bolvanskyca22d422018-05-16 11:39:52 +00002100 if (SizeC && CountC) {
2101 uint64_t Bytes = SizeC->getZExtValue() * CountC->getZExtValue();
Chris Bienemanad070d02014-09-17 20:55:46 +00002102
David Bolvanskyca22d422018-05-16 11:39:52 +00002103 // If this is writing zero records, remove the call (it's a noop).
2104 if (Bytes == 0)
2105 return ConstantInt::get(CI->getType(), 0);
Chris Bienemanad070d02014-09-17 20:55:46 +00002106
David Bolvanskyca22d422018-05-16 11:39:52 +00002107 // If this is writing one byte, turn it into fputc.
2108 // This optimisation is only valid, if the return value is unused.
2109 if (Bytes == 1 && CI->use_empty()) { // fwrite(S,1,1,F) -> fputc(S[0],F)
2110 Value *Char = B.CreateLoad(castToCStr(CI->getArgOperand(0), B), "char");
2111 Value *NewCI = emitFPutC(Char, CI->getArgOperand(3), B, TLI);
2112 return NewCI ? ConstantInt::get(CI->getType(), 1) : nullptr;
2113 }
Chris Bienemanad070d02014-09-17 20:55:46 +00002114 }
2115
David Bolvanskyca22d422018-05-16 11:39:52 +00002116 if (isLocallyOpenedFile(CI->getArgOperand(3), CI, B, TLI))
2117 return emitFWriteUnlocked(CI->getArgOperand(0), CI->getArgOperand(1),
2118 CI->getArgOperand(2), CI->getArgOperand(3), B, DL,
2119 TLI);
2120
Chris Bienemanad070d02014-09-17 20:55:46 +00002121 return nullptr;
2122}
2123
2124Value *LibCallSimplifier::optimizeFPuts(CallInst *CI, IRBuilder<> &B) {
2125 optimizeErrorReporting(CI, B, 1);
2126
Sjoerd Meijer7435a912016-07-07 14:31:19 +00002127 // Don't rewrite fputs to fwrite when optimising for size because fwrite
2128 // requires more arguments and thus extra MOVs are required.
David Bolvansky5430b7372018-05-31 16:39:27 +00002129 if (CI->getFunction()->optForSize())
Sjoerd Meijer7435a912016-07-07 14:31:19 +00002130 return nullptr;
2131
David Bolvanskyca22d422018-05-16 11:39:52 +00002132 // Check if has any use
2133 if (!CI->use_empty()) {
2134 if (isLocallyOpenedFile(CI->getArgOperand(1), CI, B, TLI))
2135 return emitFPutSUnlocked(CI->getArgOperand(0), CI->getArgOperand(1), B,
2136 TLI);
2137 else
2138 // We can't optimize if return value is used.
2139 return nullptr;
2140 }
Chris Bienemanad070d02014-09-17 20:55:46 +00002141
2142 // fputs(s,F) --> fwrite(s,1,strlen(s),F)
David Bolvansky1f343fa2018-05-22 20:27:36 +00002143 uint64_t Len = GetStringLength(CI->getArgOperand(0));
Chris Bienemanad070d02014-09-17 20:55:46 +00002144 if (!Len)
2145 return nullptr;
2146
2147 // Known to have no uses (see above).
Sanjay Pateld3112a52016-01-19 19:46:10 +00002148 return emitFWrite(
Chris Bienemanad070d02014-09-17 20:55:46 +00002149 CI->getArgOperand(0),
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002150 ConstantInt::get(DL.getIntPtrType(CI->getContext()), Len - 1),
Chris Bienemanad070d02014-09-17 20:55:46 +00002151 CI->getArgOperand(1), B, DL, TLI);
2152}
2153
David Bolvanskyca22d422018-05-16 11:39:52 +00002154Value *LibCallSimplifier::optimizeFPutc(CallInst *CI, IRBuilder<> &B) {
2155 optimizeErrorReporting(CI, B, 1);
2156
2157 if (isLocallyOpenedFile(CI->getArgOperand(1), CI, B, TLI))
2158 return emitFPutCUnlocked(CI->getArgOperand(0), CI->getArgOperand(1), B,
2159 TLI);
2160
2161 return nullptr;
2162}
2163
2164Value *LibCallSimplifier::optimizeFGetc(CallInst *CI, IRBuilder<> &B) {
2165 if (isLocallyOpenedFile(CI->getArgOperand(0), CI, B, TLI))
2166 return emitFGetCUnlocked(CI->getArgOperand(0), B, TLI);
2167
2168 return nullptr;
2169}
2170
2171Value *LibCallSimplifier::optimizeFGets(CallInst *CI, IRBuilder<> &B) {
2172 if (isLocallyOpenedFile(CI->getArgOperand(2), CI, B, TLI))
2173 return emitFGetSUnlocked(CI->getArgOperand(0), CI->getArgOperand(1),
2174 CI->getArgOperand(2), B, TLI);
2175
2176 return nullptr;
2177}
2178
2179Value *LibCallSimplifier::optimizeFRead(CallInst *CI, IRBuilder<> &B) {
2180 if (isLocallyOpenedFile(CI->getArgOperand(3), CI, B, TLI))
2181 return emitFReadUnlocked(CI->getArgOperand(0), CI->getArgOperand(1),
2182 CI->getArgOperand(2), CI->getArgOperand(3), B, DL,
2183 TLI);
2184
2185 return nullptr;
2186}
2187
Chris Bienemanad070d02014-09-17 20:55:46 +00002188Value *LibCallSimplifier::optimizePuts(CallInst *CI, IRBuilder<> &B) {
Chris Bienemanad070d02014-09-17 20:55:46 +00002189 // Check for a constant string.
2190 StringRef Str;
2191 if (!getConstantStringInfo(CI->getArgOperand(0), Str))
2192 return nullptr;
2193
2194 if (Str.empty() && CI->use_empty()) {
2195 // puts("") -> putchar('\n')
Sanjay Pateld3112a52016-01-19 19:46:10 +00002196 Value *Res = emitPutChar(B.getInt32('\n'), B, TLI);
Chris Bienemanad070d02014-09-17 20:55:46 +00002197 if (CI->use_empty() || !Res)
2198 return Res;
2199 return B.CreateIntCast(Res, CI->getType(), true);
2200 }
2201
2202 return nullptr;
2203}
2204
2205bool LibCallSimplifier::hasFloatVersion(StringRef FuncName) {
David L. Jonesd21529f2017-01-23 23:16:46 +00002206 LibFunc Func;
Meador Inge20255ef2013-03-12 00:08:29 +00002207 SmallString<20> FloatFuncName = FuncName;
2208 FloatFuncName += 'f';
2209 if (TLI->getLibFunc(FloatFuncName, Func))
2210 return TLI->has(Func);
2211 return false;
2212}
Meador Inge7fb2f732012-10-13 16:45:32 +00002213
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00002214Value *LibCallSimplifier::optimizeStringMemoryLibCall(CallInst *CI,
2215 IRBuilder<> &Builder) {
David L. Jonesd21529f2017-01-23 23:16:46 +00002216 LibFunc Func;
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00002217 Function *Callee = CI->getCalledFunction();
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00002218 // Check for string/memory library functions.
Ahmed Bougachad765a822016-04-27 19:04:35 +00002219 if (TLI->getLibFunc(*Callee, Func) && TLI->has(Func)) {
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00002220 // Make sure we never change the calling convention.
2221 assert((ignoreCallingConv(Func) ||
Sam Parker214f7bf2016-09-13 12:10:14 +00002222 isCallingConvCCompatible(CI)) &&
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00002223 "Optimizing string/memory libcall would change the calling convention");
2224 switch (Func) {
David L. Jonesd21529f2017-01-23 23:16:46 +00002225 case LibFunc_strcat:
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00002226 return optimizeStrCat(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002227 case LibFunc_strncat:
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00002228 return optimizeStrNCat(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002229 case LibFunc_strchr:
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00002230 return optimizeStrChr(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002231 case LibFunc_strrchr:
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00002232 return optimizeStrRChr(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002233 case LibFunc_strcmp:
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00002234 return optimizeStrCmp(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002235 case LibFunc_strncmp:
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00002236 return optimizeStrNCmp(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002237 case LibFunc_strcpy:
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00002238 return optimizeStrCpy(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002239 case LibFunc_stpcpy:
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00002240 return optimizeStpCpy(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002241 case LibFunc_strncpy:
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00002242 return optimizeStrNCpy(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002243 case LibFunc_strlen:
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00002244 return optimizeStrLen(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002245 case LibFunc_strpbrk:
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00002246 return optimizeStrPBrk(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002247 case LibFunc_strtol:
2248 case LibFunc_strtod:
2249 case LibFunc_strtof:
2250 case LibFunc_strtoul:
2251 case LibFunc_strtoll:
2252 case LibFunc_strtold:
2253 case LibFunc_strtoull:
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00002254 return optimizeStrTo(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002255 case LibFunc_strspn:
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00002256 return optimizeStrSpn(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002257 case LibFunc_strcspn:
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00002258 return optimizeStrCSpn(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002259 case LibFunc_strstr:
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00002260 return optimizeStrStr(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002261 case LibFunc_memchr:
Benjamin Kramer691363e2015-03-21 15:36:21 +00002262 return optimizeMemChr(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002263 case LibFunc_memcmp:
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00002264 return optimizeMemCmp(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002265 case LibFunc_memcpy:
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00002266 return optimizeMemCpy(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002267 case LibFunc_memmove:
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00002268 return optimizeMemMove(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002269 case LibFunc_memset:
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00002270 return optimizeMemSet(CI, Builder);
Sanjay Patelb2ab3f22018-04-18 14:21:31 +00002271 case LibFunc_realloc:
2272 return optimizeRealloc(CI, Builder);
Matthias Braun50ec0b52017-05-19 22:37:09 +00002273 case LibFunc_wcslen:
2274 return optimizeWcslen(CI, Builder);
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00002275 default:
2276 break;
2277 }
2278 }
2279 return nullptr;
2280}
2281
Andrew Kaylor53a5fbb2017-08-14 21:15:13 +00002282Value *LibCallSimplifier::optimizeFloatingPointLibCall(CallInst *CI,
2283 LibFunc Func,
2284 IRBuilder<> &Builder) {
2285 // Don't optimize calls that require strict floating point semantics.
2286 if (CI->isStrictFP())
2287 return nullptr;
2288
2289 switch (Func) {
2290 case LibFunc_cosf:
2291 case LibFunc_cos:
2292 case LibFunc_cosl:
2293 return optimizeCos(CI, Builder);
2294 case LibFunc_sinpif:
2295 case LibFunc_sinpi:
2296 case LibFunc_cospif:
2297 case LibFunc_cospi:
2298 return optimizeSinCosPi(CI, Builder);
2299 case LibFunc_powf:
2300 case LibFunc_pow:
2301 case LibFunc_powl:
2302 return optimizePow(CI, Builder);
2303 case LibFunc_exp2l:
2304 case LibFunc_exp2:
2305 case LibFunc_exp2f:
2306 return optimizeExp2(CI, Builder);
2307 case LibFunc_fabsf:
2308 case LibFunc_fabs:
2309 case LibFunc_fabsl:
2310 return replaceUnaryCall(CI, Builder, Intrinsic::fabs);
2311 case LibFunc_sqrtf:
2312 case LibFunc_sqrt:
2313 case LibFunc_sqrtl:
2314 return optimizeSqrt(CI, Builder);
2315 case LibFunc_log:
2316 case LibFunc_log10:
2317 case LibFunc_log1p:
2318 case LibFunc_log2:
2319 case LibFunc_logb:
2320 return optimizeLog(CI, Builder);
2321 case LibFunc_tan:
2322 case LibFunc_tanf:
2323 case LibFunc_tanl:
2324 return optimizeTan(CI, Builder);
2325 case LibFunc_ceil:
2326 return replaceUnaryCall(CI, Builder, Intrinsic::ceil);
2327 case LibFunc_floor:
2328 return replaceUnaryCall(CI, Builder, Intrinsic::floor);
2329 case LibFunc_round:
2330 return replaceUnaryCall(CI, Builder, Intrinsic::round);
2331 case LibFunc_nearbyint:
2332 return replaceUnaryCall(CI, Builder, Intrinsic::nearbyint);
2333 case LibFunc_rint:
2334 return replaceUnaryCall(CI, Builder, Intrinsic::rint);
2335 case LibFunc_trunc:
2336 return replaceUnaryCall(CI, Builder, Intrinsic::trunc);
2337 case LibFunc_acos:
2338 case LibFunc_acosh:
2339 case LibFunc_asin:
2340 case LibFunc_asinh:
2341 case LibFunc_atan:
2342 case LibFunc_atanh:
2343 case LibFunc_cbrt:
2344 case LibFunc_cosh:
2345 case LibFunc_exp:
2346 case LibFunc_exp10:
2347 case LibFunc_expm1:
2348 case LibFunc_sin:
2349 case LibFunc_sinh:
2350 case LibFunc_tanh:
2351 if (UnsafeFPShrink && hasFloatVersion(CI->getCalledFunction()->getName()))
2352 return optimizeUnaryDoubleFP(CI, Builder, true);
2353 return nullptr;
2354 case LibFunc_copysign:
2355 if (hasFloatVersion(CI->getCalledFunction()->getName()))
2356 return optimizeBinaryDoubleFP(CI, Builder);
2357 return nullptr;
2358 case LibFunc_fminf:
2359 case LibFunc_fmin:
2360 case LibFunc_fminl:
2361 case LibFunc_fmaxf:
2362 case LibFunc_fmax:
2363 case LibFunc_fmaxl:
2364 return optimizeFMinFMax(CI, Builder);
Hal Finkel2ff24732017-12-16 01:26:25 +00002365 case LibFunc_cabs:
2366 case LibFunc_cabsf:
2367 case LibFunc_cabsl:
2368 return optimizeCAbs(CI, Builder);
Andrew Kaylor53a5fbb2017-08-14 21:15:13 +00002369 default:
2370 return nullptr;
2371 }
2372}
2373
Chris Bienemanad070d02014-09-17 20:55:46 +00002374Value *LibCallSimplifier::optimizeCall(CallInst *CI) {
Andrew Kaylor53a5fbb2017-08-14 21:15:13 +00002375 // TODO: Split out the code below that operates on FP calls so that
2376 // we can all non-FP calls with the StrictFP attribute to be
2377 // optimized.
Chris Bienemanad070d02014-09-17 20:55:46 +00002378 if (CI->isNoBuiltin())
2379 return nullptr;
Meador Inge4d2827c2012-11-11 05:11:20 +00002380
David L. Jonesd21529f2017-01-23 23:16:46 +00002381 LibFunc Func;
Meador Inge20255ef2013-03-12 00:08:29 +00002382 Function *Callee = CI->getCalledFunction();
David Majnemerb70e23c2016-01-06 05:01:34 +00002383
2384 SmallVector<OperandBundleDef, 2> OpBundles;
2385 CI->getOperandBundlesAsDefs(OpBundles);
2386 IRBuilder<> Builder(CI, /*FPMathTag=*/nullptr, OpBundles);
Sam Parker214f7bf2016-09-13 12:10:14 +00002387 bool isCallingConvC = isCallingConvCCompatible(CI);
Meador Inge20255ef2013-03-12 00:08:29 +00002388
Sanjay Pateld1f4f032016-01-19 18:38:52 +00002389 // Command-line parameter overrides instruction attribute.
Andrew Kaylor53a5fbb2017-08-14 21:15:13 +00002390 // This can't be moved to optimizeFloatingPointLibCall() because it may be
Sanjay Patel629c4112017-11-06 16:27:15 +00002391 // used by the intrinsic optimizations.
Sanjay Patela92fa442014-10-22 15:29:23 +00002392 if (EnableUnsafeFPShrink.getNumOccurrences() > 0)
2393 UnsafeFPShrink = EnableUnsafeFPShrink;
Sanjay Patel629c4112017-11-06 16:27:15 +00002394 else if (isa<FPMathOperator>(CI) && CI->isFast())
Davide Italianoa904e522015-10-29 02:58:44 +00002395 UnsafeFPShrink = true;
Sanjay Patela92fa442014-10-22 15:29:23 +00002396
Sanjay Patel848309d2014-10-23 21:52:45 +00002397 // First, check for intrinsics.
Meador Inge20255ef2013-03-12 00:08:29 +00002398 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(CI)) {
Chris Bienemanad070d02014-09-17 20:55:46 +00002399 if (!isCallingConvC)
2400 return nullptr;
Andrew Kaylor53a5fbb2017-08-14 21:15:13 +00002401 // The FP intrinsics have corresponding constrained versions so we don't
2402 // need to check for the StrictFP attribute here.
Meador Inge20255ef2013-03-12 00:08:29 +00002403 switch (II->getIntrinsicID()) {
2404 case Intrinsic::pow:
Chris Bienemanad070d02014-09-17 20:55:46 +00002405 return optimizePow(CI, Builder);
Meador Inge20255ef2013-03-12 00:08:29 +00002406 case Intrinsic::exp2:
Chris Bienemanad070d02014-09-17 20:55:46 +00002407 return optimizeExp2(CI, Builder);
Davide Italianob8b71332015-11-29 20:58:04 +00002408 case Intrinsic::log:
2409 return optimizeLog(CI, Builder);
Sanjay Patelc699a612014-10-16 18:48:17 +00002410 case Intrinsic::sqrt:
2411 return optimizeSqrt(CI, Builder);
Sanjay Patel980b2802016-01-26 16:17:24 +00002412 // TODO: Use foldMallocMemset() with memset intrinsic.
Meador Inge20255ef2013-03-12 00:08:29 +00002413 default:
Chris Bienemanad070d02014-09-17 20:55:46 +00002414 return nullptr;
Meador Inge20255ef2013-03-12 00:08:29 +00002415 }
2416 }
2417
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002418 // Also try to simplify calls to fortified library functions.
2419 if (Value *SimplifiedFortifiedCI = FortifiedSimplifier.optimizeCall(CI)) {
2420 // Try to further simplify the result.
Ahmed Bougacha71d7b182015-01-14 00:55:05 +00002421 CallInst *SimplifiedCI = dyn_cast<CallInst>(SimplifiedFortifiedCI);
Bruno Cardoso Lopesb491a2d2015-10-01 22:43:53 +00002422 if (SimplifiedCI && SimplifiedCI->getCalledFunction()) {
2423 // Use an IR Builder from SimplifiedCI if available instead of CI
2424 // to guarantee we reach all uses we might replace later on.
2425 IRBuilder<> TmpBuilder(SimplifiedCI);
2426 if (Value *V = optimizeStringMemoryLibCall(SimplifiedCI, TmpBuilder)) {
Ahmed Bougacha1ac93562015-01-27 21:52:16 +00002427 // If we were able to further simplify, remove the now redundant call.
2428 SimplifiedCI->replaceAllUsesWith(V);
2429 SimplifiedCI->eraseFromParent();
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002430 return V;
Ahmed Bougacha1ac93562015-01-27 21:52:16 +00002431 }
Bruno Cardoso Lopesb491a2d2015-10-01 22:43:53 +00002432 }
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002433 return SimplifiedFortifiedCI;
2434 }
2435
Meador Inge20255ef2013-03-12 00:08:29 +00002436 // Then check for known library functions.
Ahmed Bougachad765a822016-04-27 19:04:35 +00002437 if (TLI->getLibFunc(*Callee, Func) && TLI->has(Func)) {
Chris Bienemanad070d02014-09-17 20:55:46 +00002438 // We never change the calling convention.
2439 if (!ignoreCallingConv(Func) && !isCallingConvC)
2440 return nullptr;
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00002441 if (Value *V = optimizeStringMemoryLibCall(CI, Builder))
2442 return V;
Andrew Kaylor53a5fbb2017-08-14 21:15:13 +00002443 if (Value *V = optimizeFloatingPointLibCall(CI, Func, Builder))
2444 return V;
Meador Inge20255ef2013-03-12 00:08:29 +00002445 switch (Func) {
David L. Jonesd21529f2017-01-23 23:16:46 +00002446 case LibFunc_ffs:
2447 case LibFunc_ffsl:
2448 case LibFunc_ffsll:
Chris Bienemanad070d02014-09-17 20:55:46 +00002449 return optimizeFFS(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002450 case LibFunc_fls:
2451 case LibFunc_flsl:
2452 case LibFunc_flsll:
Davide Italiano85ad36b2016-12-15 23:45:11 +00002453 return optimizeFls(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002454 case LibFunc_abs:
2455 case LibFunc_labs:
2456 case LibFunc_llabs:
Chris Bienemanad070d02014-09-17 20:55:46 +00002457 return optimizeAbs(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002458 case LibFunc_isdigit:
Chris Bienemanad070d02014-09-17 20:55:46 +00002459 return optimizeIsDigit(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002460 case LibFunc_isascii:
Chris Bienemanad070d02014-09-17 20:55:46 +00002461 return optimizeIsAscii(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002462 case LibFunc_toascii:
Chris Bienemanad070d02014-09-17 20:55:46 +00002463 return optimizeToAscii(CI, Builder);
David Bolvanskycb8ca5f32018-04-25 18:58:53 +00002464 case LibFunc_atoi:
2465 case LibFunc_atol:
2466 case LibFunc_atoll:
2467 return optimizeAtoi(CI, Builder);
2468 case LibFunc_strtol:
2469 case LibFunc_strtoll:
2470 return optimizeStrtol(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002471 case LibFunc_printf:
Chris Bienemanad070d02014-09-17 20:55:46 +00002472 return optimizePrintF(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002473 case LibFunc_sprintf:
Chris Bienemanad070d02014-09-17 20:55:46 +00002474 return optimizeSPrintF(CI, Builder);
David Bolvanskycd93c4e2018-05-11 17:50:49 +00002475 case LibFunc_snprintf:
2476 return optimizeSnPrintF(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002477 case LibFunc_fprintf:
Chris Bienemanad070d02014-09-17 20:55:46 +00002478 return optimizeFPrintF(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002479 case LibFunc_fwrite:
Chris Bienemanad070d02014-09-17 20:55:46 +00002480 return optimizeFWrite(CI, Builder);
David Bolvanskyca22d422018-05-16 11:39:52 +00002481 case LibFunc_fread:
2482 return optimizeFRead(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002483 case LibFunc_fputs:
Chris Bienemanad070d02014-09-17 20:55:46 +00002484 return optimizeFPuts(CI, Builder);
David Bolvanskyca22d422018-05-16 11:39:52 +00002485 case LibFunc_fgets:
2486 return optimizeFGets(CI, Builder);
2487 case LibFunc_fputc:
2488 return optimizeFPutc(CI, Builder);
2489 case LibFunc_fgetc:
2490 return optimizeFGetc(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002491 case LibFunc_puts:
Chris Bienemanad070d02014-09-17 20:55:46 +00002492 return optimizePuts(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002493 case LibFunc_perror:
Chris Bienemanad070d02014-09-17 20:55:46 +00002494 return optimizeErrorReporting(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002495 case LibFunc_vfprintf:
2496 case LibFunc_fiprintf:
Chris Bienemanad070d02014-09-17 20:55:46 +00002497 return optimizeErrorReporting(CI, Builder, 0);
Chris Bienemanad070d02014-09-17 20:55:46 +00002498 default:
2499 return nullptr;
2500 }
Meador Inge20255ef2013-03-12 00:08:29 +00002501 }
Craig Topperf40110f2014-04-25 05:29:35 +00002502 return nullptr;
Meador Ingedf796f82012-10-13 16:45:24 +00002503}
2504
Chandler Carruth92803822015-01-21 02:11:59 +00002505LibCallSimplifier::LibCallSimplifier(
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002506 const DataLayout &DL, const TargetLibraryInfo *TLI,
Adam Nemetea06e6e2017-07-26 19:03:18 +00002507 OptimizationRemarkEmitter &ORE,
Chandler Carruth92803822015-01-21 02:11:59 +00002508 function_ref<void(Instruction *, Value *)> Replacer)
Adam Nemetea06e6e2017-07-26 19:03:18 +00002509 : FortifiedSimplifier(TLI), DL(DL), TLI(TLI), ORE(ORE),
2510 UnsafeFPShrink(false), Replacer(Replacer) {}
Chandler Carruth92803822015-01-21 02:11:59 +00002511
2512void LibCallSimplifier::replaceAllUsesWith(Instruction *I, Value *With) {
2513 // Indirect through the replacer used in this instance.
2514 Replacer(I, With);
Meador Ingedf796f82012-10-13 16:45:24 +00002515}
2516
Meador Ingedfb08a22013-06-20 19:48:07 +00002517// TODO:
2518// Additional cases that we need to add to this file:
2519//
2520// cbrt:
2521// * cbrt(expN(X)) -> expN(x/3)
2522// * cbrt(sqrt(x)) -> pow(x,1/6)
David Majnemer3354fe42015-08-26 18:30:16 +00002523// * cbrt(cbrt(x)) -> pow(x,1/9)
Meador Ingedfb08a22013-06-20 19:48:07 +00002524//
2525// exp, expf, expl:
2526// * exp(log(x)) -> x
2527//
2528// log, logf, logl:
2529// * log(exp(x)) -> x
Meador Ingedfb08a22013-06-20 19:48:07 +00002530// * log(exp(y)) -> y*log(e)
Meador Ingedfb08a22013-06-20 19:48:07 +00002531// * log(exp10(y)) -> y*log(10)
2532// * log(sqrt(x)) -> 0.5*log(x)
Meador Ingedfb08a22013-06-20 19:48:07 +00002533//
Meador Ingedfb08a22013-06-20 19:48:07 +00002534// pow, powf, powl:
Meador Ingedfb08a22013-06-20 19:48:07 +00002535// * pow(sqrt(x),y) -> pow(x,y*0.5)
2536// * pow(pow(x,y),z)-> pow(x,y*z)
2537//
Meador Ingedfb08a22013-06-20 19:48:07 +00002538// signbit:
2539// * signbit(cnst) -> cnst'
2540// * signbit(nncst) -> 0 (if pstv is a non-negative constant)
2541//
2542// sqrt, sqrtf, sqrtl:
2543// * sqrt(expN(x)) -> expN(x*0.5)
2544// * sqrt(Nroot(x)) -> pow(x,1/(2*N))
2545// * sqrt(pow(x,y)) -> pow(|x|,y*0.5)
2546//
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002547
2548//===----------------------------------------------------------------------===//
2549// Fortified Library Call Optimizations
2550//===----------------------------------------------------------------------===//
2551
2552bool FortifiedLibCallSimplifier::isFortifiedCallFoldable(CallInst *CI,
2553 unsigned ObjSizeOp,
2554 unsigned SizeOp,
2555 bool isString) {
2556 if (CI->getArgOperand(ObjSizeOp) == CI->getArgOperand(SizeOp))
2557 return true;
2558 if (ConstantInt *ObjSizeCI =
2559 dyn_cast<ConstantInt>(CI->getArgOperand(ObjSizeOp))) {
Craig Topper79ab6432017-07-06 18:39:47 +00002560 if (ObjSizeCI->isMinusOne())
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002561 return true;
2562 // If the object size wasn't -1 (unknown), bail out if we were asked to.
2563 if (OnlyLowerUnknownSize)
2564 return false;
2565 if (isString) {
David Bolvansky1f343fa2018-05-22 20:27:36 +00002566 uint64_t Len = GetStringLength(CI->getArgOperand(SizeOp));
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002567 // If the length is 0 we don't know how long it is and so we can't
2568 // remove the check.
2569 if (Len == 0)
2570 return false;
2571 return ObjSizeCI->getZExtValue() >= Len;
2572 }
2573 if (ConstantInt *SizeCI = dyn_cast<ConstantInt>(CI->getArgOperand(SizeOp)))
2574 return ObjSizeCI->getZExtValue() >= SizeCI->getZExtValue();
2575 }
2576 return false;
2577}
2578
Sanjay Pateld707db92015-12-31 16:10:49 +00002579Value *FortifiedLibCallSimplifier::optimizeMemCpyChk(CallInst *CI,
2580 IRBuilder<> &B) {
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002581 if (isFortifiedCallFoldable(CI, 3, 2, false)) {
Daniel Neilson8acd8b02018-02-05 21:23:22 +00002582 B.CreateMemCpy(CI->getArgOperand(0), 1, CI->getArgOperand(1), 1,
2583 CI->getArgOperand(2));
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002584 return CI->getArgOperand(0);
2585 }
2586 return nullptr;
2587}
2588
Sanjay Pateld707db92015-12-31 16:10:49 +00002589Value *FortifiedLibCallSimplifier::optimizeMemMoveChk(CallInst *CI,
2590 IRBuilder<> &B) {
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002591 if (isFortifiedCallFoldable(CI, 3, 2, false)) {
Daniel Neilson8acd8b02018-02-05 21:23:22 +00002592 B.CreateMemMove(CI->getArgOperand(0), 1, CI->getArgOperand(1), 1,
2593 CI->getArgOperand(2));
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002594 return CI->getArgOperand(0);
2595 }
2596 return nullptr;
2597}
2598
Sanjay Pateld707db92015-12-31 16:10:49 +00002599Value *FortifiedLibCallSimplifier::optimizeMemSetChk(CallInst *CI,
2600 IRBuilder<> &B) {
Sanjay Patel980b2802016-01-26 16:17:24 +00002601 // TODO: Try foldMallocMemset() here.
2602
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002603 if (isFortifiedCallFoldable(CI, 3, 2, false)) {
2604 Value *Val = B.CreateIntCast(CI->getArgOperand(1), B.getInt8Ty(), false);
2605 B.CreateMemSet(CI->getArgOperand(0), Val, CI->getArgOperand(2), 1);
2606 return CI->getArgOperand(0);
2607 }
2608 return nullptr;
2609}
2610
Ahmed Bougacha1ac93562015-01-27 21:52:16 +00002611Value *FortifiedLibCallSimplifier::optimizeStrpCpyChk(CallInst *CI,
2612 IRBuilder<> &B,
David L. Jonesd21529f2017-01-23 23:16:46 +00002613 LibFunc Func) {
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002614 Function *Callee = CI->getCalledFunction();
2615 StringRef Name = Callee->getName();
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002616 const DataLayout &DL = CI->getModule()->getDataLayout();
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002617 Value *Dst = CI->getArgOperand(0), *Src = CI->getArgOperand(1),
2618 *ObjSize = CI->getArgOperand(2);
2619
2620 // __stpcpy_chk(x,x,...) -> x+strlen(x)
David L. Jonesd21529f2017-01-23 23:16:46 +00002621 if (Func == LibFunc_stpcpy_chk && !OnlyLowerUnknownSize && Dst == Src) {
Sanjay Pateld3112a52016-01-19 19:46:10 +00002622 Value *StrLen = emitStrLen(Src, B, DL, TLI);
David Blaikieaa41cd52015-04-03 21:33:42 +00002623 return StrLen ? B.CreateInBoundsGEP(B.getInt8Ty(), Dst, StrLen) : nullptr;
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002624 }
2625
2626 // If a) we don't have any length information, or b) we know this will
2627 // fit then just lower to a plain st[rp]cpy. Otherwise we'll keep our
2628 // st[rp]cpy_chk call which may fail at runtime if the size is too long.
2629 // TODO: It might be nice to get a maximum length out of the possible
2630 // string lengths for varying.
David Blaikie65fab6d2015-04-03 21:32:06 +00002631 if (isFortifiedCallFoldable(CI, 2, 1, true))
Sanjay Pateld3112a52016-01-19 19:46:10 +00002632 return emitStrCpy(Dst, Src, B, TLI, Name.substr(2, 6));
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002633
David Blaikie65fab6d2015-04-03 21:32:06 +00002634 if (OnlyLowerUnknownSize)
2635 return nullptr;
2636
2637 // Maybe we can stil fold __st[rp]cpy_chk to __memcpy_chk.
David Bolvansky1f343fa2018-05-22 20:27:36 +00002638 uint64_t Len = GetStringLength(Src);
David Blaikie65fab6d2015-04-03 21:32:06 +00002639 if (Len == 0)
2640 return nullptr;
2641
2642 Type *SizeTTy = DL.getIntPtrType(CI->getContext());
2643 Value *LenV = ConstantInt::get(SizeTTy, Len);
Sanjay Pateld3112a52016-01-19 19:46:10 +00002644 Value *Ret = emitMemCpyChk(Dst, Src, LenV, ObjSize, B, DL, TLI);
David Blaikie65fab6d2015-04-03 21:32:06 +00002645 // If the function was an __stpcpy_chk, and we were able to fold it into
2646 // a __memcpy_chk, we still need to return the correct end pointer.
David L. Jonesd21529f2017-01-23 23:16:46 +00002647 if (Ret && Func == LibFunc_stpcpy_chk)
David Blaikie65fab6d2015-04-03 21:32:06 +00002648 return B.CreateGEP(B.getInt8Ty(), Dst, ConstantInt::get(SizeTTy, Len - 1));
2649 return Ret;
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002650}
2651
Ahmed Bougacha1ac93562015-01-27 21:52:16 +00002652Value *FortifiedLibCallSimplifier::optimizeStrpNCpyChk(CallInst *CI,
2653 IRBuilder<> &B,
David L. Jonesd21529f2017-01-23 23:16:46 +00002654 LibFunc Func) {
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002655 Function *Callee = CI->getCalledFunction();
2656 StringRef Name = Callee->getName();
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002657 if (isFortifiedCallFoldable(CI, 3, 2, false)) {
Sanjay Pateld3112a52016-01-19 19:46:10 +00002658 Value *Ret = emitStrNCpy(CI->getArgOperand(0), CI->getArgOperand(1),
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002659 CI->getArgOperand(2), B, TLI, Name.substr(2, 7));
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002660 return Ret;
2661 }
2662 return nullptr;
2663}
2664
2665Value *FortifiedLibCallSimplifier::optimizeCall(CallInst *CI) {
Ahmed Bougacha408d0102015-04-01 00:45:09 +00002666 // FIXME: We shouldn't be changing "nobuiltin" or TLI unavailable calls here.
2667 // Some clang users checked for _chk libcall availability using:
2668 // __has_builtin(__builtin___memcpy_chk)
2669 // When compiling with -fno-builtin, this is always true.
2670 // When passing -ffreestanding/-mkernel, which both imply -fno-builtin, we
2671 // end up with fortified libcalls, which isn't acceptable in a freestanding
2672 // environment which only provides their non-fortified counterparts.
2673 //
2674 // Until we change clang and/or teach external users to check for availability
2675 // differently, disregard the "nobuiltin" attribute and TLI::has.
2676 //
2677 // PR23093.
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002678
David L. Jonesd21529f2017-01-23 23:16:46 +00002679 LibFunc Func;
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002680 Function *Callee = CI->getCalledFunction();
David Majnemerb70e23c2016-01-06 05:01:34 +00002681
2682 SmallVector<OperandBundleDef, 2> OpBundles;
2683 CI->getOperandBundlesAsDefs(OpBundles);
2684 IRBuilder<> Builder(CI, /*FPMathTag=*/nullptr, OpBundles);
Sam Parker214f7bf2016-09-13 12:10:14 +00002685 bool isCallingConvC = isCallingConvCCompatible(CI);
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002686
Ahmed Bougachad765a822016-04-27 19:04:35 +00002687 // First, check that this is a known library functions and that the prototype
2688 // is correct.
2689 if (!TLI->getLibFunc(*Callee, Func))
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002690 return nullptr;
2691
2692 // We never change the calling convention.
2693 if (!ignoreCallingConv(Func) && !isCallingConvC)
2694 return nullptr;
2695
2696 switch (Func) {
David L. Jonesd21529f2017-01-23 23:16:46 +00002697 case LibFunc_memcpy_chk:
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002698 return optimizeMemCpyChk(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002699 case LibFunc_memmove_chk:
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002700 return optimizeMemMoveChk(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002701 case LibFunc_memset_chk:
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002702 return optimizeMemSetChk(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002703 case LibFunc_stpcpy_chk:
2704 case LibFunc_strcpy_chk:
Ahmed Bougacha1ac93562015-01-27 21:52:16 +00002705 return optimizeStrpCpyChk(CI, Builder, Func);
David L. Jonesd21529f2017-01-23 23:16:46 +00002706 case LibFunc_stpncpy_chk:
2707 case LibFunc_strncpy_chk:
Ahmed Bougacha1ac93562015-01-27 21:52:16 +00002708 return optimizeStrpNCpyChk(CI, Builder, Func);
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002709 default:
2710 break;
2711 }
2712 return nullptr;
2713}
2714
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002715FortifiedLibCallSimplifier::FortifiedLibCallSimplifier(
2716 const TargetLibraryInfo *TLI, bool OnlyLowerUnknownSize)
Sanjay Patel4b969352018-05-22 23:29:40 +00002717 : TLI(TLI), OnlyLowerUnknownSize(OnlyLowerUnknownSize) {}