blob: 3920736a8d51ed460411385a69b20c6024cf5142 [file] [log] [blame]
Meador Ingedf796f82012-10-13 16:45:24 +00001//===------ SimplifyLibCalls.cpp - Library calls simplifier ---------------===//
2//
Chandler Carruth2946cd72019-01-19 08:50:56 +00003// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
Meador Ingedf796f82012-10-13 16:45:24 +00006//
7//===----------------------------------------------------------------------===//
8//
Craig Topper2915bc02018-03-01 20:05:09 +00009// This file implements the library calls simplifier. It does not implement
10// any pass, but can't be used by other passes to do simplifications.
Meador Ingedf796f82012-10-13 16:45:24 +000011//
12//===----------------------------------------------------------------------===//
13
14#include "llvm/Transforms/Utils/SimplifyLibCalls.h"
Evandro Menezes2123ea72018-08-30 19:04:51 +000015#include "llvm/ADT/APSInt.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 Blaikie31b98d22018-06-04 21:23:21 +000022#include "llvm/Transforms/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"
David Bolvansky909889b2018-08-10 04:32:54 +000025#include "llvm/Analysis/Loads.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000026#include "llvm/IR/DataLayout.h"
27#include "llvm/IR/Function.h"
28#include "llvm/IR/IRBuilder.h"
Meador Inge20255ef2013-03-12 00:08:29 +000029#include "llvm/IR/IntrinsicInst.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000030#include "llvm/IR/Intrinsics.h"
31#include "llvm/IR/LLVMContext.h"
32#include "llvm/IR/Module.h"
Sanjay Patelc699a612014-10-16 18:48:17 +000033#include "llvm/IR/PatternMatch.h"
Hal Finkel66cd3f12013-11-17 02:06:35 +000034#include "llvm/Support/CommandLine.h"
Craig Topperb45eabc2017-04-26 16:39:58 +000035#include "llvm/Support/KnownBits.h"
Meador Ingedf796f82012-10-13 16:45:24 +000036#include "llvm/Transforms/Utils/BuildLibCalls.h"
37
38using namespace llvm;
Sanjay Patelc699a612014-10-16 18:48:17 +000039using namespace PatternMatch;
Meador Ingedf796f82012-10-13 16:45:24 +000040
Hal Finkel66cd3f12013-11-17 02:06:35 +000041static cl::opt<bool>
Sanjay Patela92fa442014-10-22 15:29:23 +000042 EnableUnsafeFPShrink("enable-double-float-shrink", cl::Hidden,
43 cl::init(false),
44 cl::desc("Enable unsafe double to float "
45 "shrinking for math lib calls"));
46
47
Meador Ingedf796f82012-10-13 16:45:24 +000048//===----------------------------------------------------------------------===//
Meador Inged589ac62012-10-31 03:33:06 +000049// Helper Functions
50//===----------------------------------------------------------------------===//
51
David L. Jonesd21529f2017-01-23 23:16:46 +000052static bool ignoreCallingConv(LibFunc Func) {
53 return Func == LibFunc_abs || Func == LibFunc_labs ||
54 Func == LibFunc_llabs || Func == LibFunc_strlen;
Chris Bienemanad070d02014-09-17 20:55:46 +000055}
56
Sam Parker214f7bf2016-09-13 12:10:14 +000057static bool isCallingConvCCompatible(CallInst *CI) {
58 switch(CI->getCallingConv()) {
59 default:
60 return false;
61 case llvm::CallingConv::C:
62 return true;
63 case llvm::CallingConv::ARM_APCS:
64 case llvm::CallingConv::ARM_AAPCS:
65 case llvm::CallingConv::ARM_AAPCS_VFP: {
66
67 // The iOS ABI diverges from the standard in some cases, so for now don't
68 // try to simplify those calls.
69 if (Triple(CI->getModule()->getTargetTriple()).isiOS())
70 return false;
71
72 auto *FuncTy = CI->getFunctionType();
73
74 if (!FuncTy->getReturnType()->isPointerTy() &&
75 !FuncTy->getReturnType()->isIntegerTy() &&
76 !FuncTy->getReturnType()->isVoidTy())
77 return false;
78
79 for (auto Param : FuncTy->params()) {
80 if (!Param->isPointerTy() && !Param->isIntegerTy())
81 return false;
82 }
83 return true;
84 }
85 }
86 return false;
87}
88
Sanjay Pateld707db92015-12-31 16:10:49 +000089/// Return true if it is only used in equality comparisons with With.
Meador Inge56edbc92012-11-11 03:51:48 +000090static bool isOnlyUsedInEqualityComparison(Value *V, Value *With) {
Chandler Carruthcdf47882014-03-09 03:16:01 +000091 for (User *U : V->users()) {
92 if (ICmpInst *IC = dyn_cast<ICmpInst>(U))
Meador Inge56edbc92012-11-11 03:51:48 +000093 if (IC->isEquality() && IC->getOperand(1) == With)
94 continue;
95 // Unknown instruction.
96 return false;
97 }
98 return true;
99}
100
Meador Inge08ca1152012-11-26 20:37:20 +0000101static bool callHasFloatingPointArgument(const CallInst *CI) {
David Majnemer0a16c222016-08-11 21:15:00 +0000102 return any_of(CI->operands(), [](const Use &OI) {
Davide Italianoda3beeb2015-11-28 22:27:48 +0000103 return OI->getType()->isFloatingPointTy();
104 });
Meador Inge08ca1152012-11-26 20:37:20 +0000105}
106
David Bolvanskycb8ca5f32018-04-25 18:58:53 +0000107static Value *convertStrToNumber(CallInst *CI, StringRef &Str, int64_t Base) {
108 if (Base < 2 || Base > 36)
109 // handle special zero base
110 if (Base != 0)
111 return nullptr;
112
113 char *End;
114 std::string nptr = Str.str();
115 errno = 0;
116 long long int Result = strtoll(nptr.c_str(), &End, Base);
117 if (errno)
118 return nullptr;
119
120 // if we assume all possible target locales are ASCII supersets,
121 // then if strtoll successfully parses a number on the host,
122 // it will also successfully parse the same way on the target
123 if (*End != '\0')
124 return nullptr;
125
126 if (!isIntN(CI->getType()->getPrimitiveSizeInBits(), Result))
127 return nullptr;
128
129 return ConstantInt::get(CI->getType(), Result);
130}
131
David Bolvanskyca22d422018-05-16 11:39:52 +0000132static bool isLocallyOpenedFile(Value *File, CallInst *CI, IRBuilder<> &B,
133 const TargetLibraryInfo *TLI) {
134 CallInst *FOpen = dyn_cast<CallInst>(File);
135 if (!FOpen)
136 return false;
137
138 Function *InnerCallee = FOpen->getCalledFunction();
139 if (!InnerCallee)
140 return false;
141
142 LibFunc Func;
143 if (!TLI->getLibFunc(*InnerCallee, Func) || !TLI->has(Func) ||
144 Func != LibFunc_fopen)
145 return false;
146
David Bolvansky7c7760d2018-10-16 21:18:31 +0000147 inferLibFuncAttributes(*CI->getCalledFunction(), *TLI);
David Bolvanskyca22d422018-05-16 11:39:52 +0000148 if (PointerMayBeCaptured(File, true, true))
149 return false;
150
151 return true;
152}
153
David Bolvansky909889b2018-08-10 04:32:54 +0000154static bool isOnlyUsedInComparisonWithZero(Value *V) {
155 for (User *U : V->users()) {
156 if (ICmpInst *IC = dyn_cast<ICmpInst>(U))
157 if (Constant *C = dyn_cast<Constant>(IC->getOperand(1)))
158 if (C->isNullValue())
159 continue;
160 // Unknown instruction.
161 return false;
162 }
163 return true;
164}
165
166static bool canTransformToMemCmp(CallInst *CI, Value *Str, uint64_t Len,
167 const DataLayout &DL) {
168 if (!isOnlyUsedInComparisonWithZero(CI))
169 return false;
170
171 if (!isDereferenceableAndAlignedPointer(Str, 1, APInt(64, Len), DL))
172 return false;
Matt Morehousee62fc3d2018-09-19 19:37:24 +0000173
174 if (CI->getFunction()->hasFnAttribute(Attribute::SanitizeMemory))
175 return false;
176
David Bolvansky909889b2018-08-10 04:32:54 +0000177 return true;
178}
179
Meador Inged589ac62012-10-31 03:33:06 +0000180//===----------------------------------------------------------------------===//
Meador Inge7fb2f732012-10-13 16:45:32 +0000181// String and Memory Library Call Optimizations
182//===----------------------------------------------------------------------===//
183
Chris Bienemanad070d02014-09-17 20:55:46 +0000184Value *LibCallSimplifier::optimizeStrCat(CallInst *CI, IRBuilder<> &B) {
Chris Bienemanad070d02014-09-17 20:55:46 +0000185 // Extract some information from the instruction
186 Value *Dst = CI->getArgOperand(0);
187 Value *Src = CI->getArgOperand(1);
188
189 // See if we can get the length of the input string.
David Bolvansky1f343fa2018-05-22 20:27:36 +0000190 uint64_t Len = GetStringLength(Src);
Chris Bienemanad070d02014-09-17 20:55:46 +0000191 if (Len == 0)
192 return nullptr;
193 --Len; // Unbias length.
194
195 // Handle the simple, do-nothing case: strcat(x, "") -> x
196 if (Len == 0)
197 return Dst;
198
Chris Bienemanad070d02014-09-17 20:55:46 +0000199 return emitStrLenMemCpy(Src, Dst, Len, B);
200}
201
202Value *LibCallSimplifier::emitStrLenMemCpy(Value *Src, Value *Dst, uint64_t Len,
203 IRBuilder<> &B) {
204 // We need to find the end of the destination string. That's where the
205 // memory is to be moved to. We just generate a call to strlen.
Sanjay Pateld3112a52016-01-19 19:46:10 +0000206 Value *DstLen = emitStrLen(Dst, B, DL, TLI);
Chris Bienemanad070d02014-09-17 20:55:46 +0000207 if (!DstLen)
208 return nullptr;
209
210 // Now that we have the destination's length, we must index into the
211 // destination's pointer to get the actual memcpy destination (end of
212 // the string .. we're concatenating).
David Blaikie3909da72015-03-30 20:42:56 +0000213 Value *CpyDst = B.CreateGEP(B.getInt8Ty(), Dst, DstLen, "endptr");
Chris Bienemanad070d02014-09-17 20:55:46 +0000214
215 // We have enough information to now generate the memcpy call to do the
216 // concatenation for us. Make a memcpy to copy the nul byte with align = 1.
Daniel Neilson8acd8b02018-02-05 21:23:22 +0000217 B.CreateMemCpy(CpyDst, 1, Src, 1,
218 ConstantInt::get(DL.getIntPtrType(Src->getContext()), Len + 1));
Chris Bienemanad070d02014-09-17 20:55:46 +0000219 return Dst;
220}
221
222Value *LibCallSimplifier::optimizeStrNCat(CallInst *CI, IRBuilder<> &B) {
Sanjay Pateld707db92015-12-31 16:10:49 +0000223 // Extract some information from the instruction.
Chris Bienemanad070d02014-09-17 20:55:46 +0000224 Value *Dst = CI->getArgOperand(0);
225 Value *Src = CI->getArgOperand(1);
226 uint64_t Len;
227
Sanjay Pateld707db92015-12-31 16:10:49 +0000228 // We don't do anything if length is not constant.
Chris Bienemanad070d02014-09-17 20:55:46 +0000229 if (ConstantInt *LengthArg = dyn_cast<ConstantInt>(CI->getArgOperand(2)))
230 Len = LengthArg->getZExtValue();
231 else
232 return nullptr;
233
234 // See if we can get the length of the input string.
David Bolvansky1f343fa2018-05-22 20:27:36 +0000235 uint64_t SrcLen = GetStringLength(Src);
Chris Bienemanad070d02014-09-17 20:55:46 +0000236 if (SrcLen == 0)
237 return nullptr;
238 --SrcLen; // Unbias length.
239
240 // Handle the simple, do-nothing cases:
241 // strncat(x, "", c) -> x
242 // strncat(x, c, 0) -> x
243 if (SrcLen == 0 || Len == 0)
244 return Dst;
245
Sanjay Pateld707db92015-12-31 16:10:49 +0000246 // We don't optimize this case.
Chris Bienemanad070d02014-09-17 20:55:46 +0000247 if (Len < SrcLen)
248 return nullptr;
249
250 // strncat(x, s, c) -> strcat(x, s)
Sanjay Pateld707db92015-12-31 16:10:49 +0000251 // s is constant so the strcat can be optimized further.
Chris Bienemanad070d02014-09-17 20:55:46 +0000252 return emitStrLenMemCpy(Src, Dst, SrcLen, B);
253}
254
255Value *LibCallSimplifier::optimizeStrChr(CallInst *CI, IRBuilder<> &B) {
256 Function *Callee = CI->getCalledFunction();
Chris Bienemanad070d02014-09-17 20:55:46 +0000257 FunctionType *FT = Callee->getFunctionType();
Chris Bienemanad070d02014-09-17 20:55:46 +0000258 Value *SrcStr = CI->getArgOperand(0);
259
260 // If the second operand is non-constant, see if we can compute the length
261 // of the input string and turn this into memchr.
262 ConstantInt *CharC = dyn_cast<ConstantInt>(CI->getArgOperand(1));
263 if (!CharC) {
David Bolvansky1f343fa2018-05-22 20:27:36 +0000264 uint64_t Len = GetStringLength(SrcStr);
Chris Bienemanad070d02014-09-17 20:55:46 +0000265 if (Len == 0 || !FT->getParamType(1)->isIntegerTy(32)) // memchr needs i32.
266 return nullptr;
Meador Inge7fb2f732012-10-13 16:45:32 +0000267
Sanjay Pateld3112a52016-01-19 19:46:10 +0000268 return emitMemChr(SrcStr, CI->getArgOperand(1), // include nul.
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000269 ConstantInt::get(DL.getIntPtrType(CI->getContext()), Len),
270 B, DL, TLI);
Meador Inge7fb2f732012-10-13 16:45:32 +0000271 }
272
Chris Bienemanad070d02014-09-17 20:55:46 +0000273 // Otherwise, the character is a constant, see if the first argument is
274 // a string literal. If so, we can constant fold.
275 StringRef Str;
276 if (!getConstantStringInfo(SrcStr, Str)) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000277 if (CharC->isZero()) // strchr(p, 0) -> p + strlen(p)
Sanjay Pateld3112a52016-01-19 19:46:10 +0000278 return B.CreateGEP(B.getInt8Ty(), SrcStr, emitStrLen(SrcStr, B, DL, TLI),
Sanjay Pateld707db92015-12-31 16:10:49 +0000279 "strchr");
Chris Bienemanad070d02014-09-17 20:55:46 +0000280 return nullptr;
281 }
282
283 // Compute the offset, make sure to handle the case when we're searching for
284 // zero (a weird way to spell strlen).
285 size_t I = (0xFF & CharC->getSExtValue()) == 0
286 ? Str.size()
287 : Str.find(CharC->getSExtValue());
288 if (I == StringRef::npos) // Didn't find the char. strchr returns null.
289 return Constant::getNullValue(CI->getType());
290
291 // strchr(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), "strchr");
Chris Bienemanad070d02014-09-17 20:55:46 +0000293}
294
295Value *LibCallSimplifier::optimizeStrRChr(CallInst *CI, IRBuilder<> &B) {
Chris Bienemanad070d02014-09-17 20:55:46 +0000296 Value *SrcStr = CI->getArgOperand(0);
297 ConstantInt *CharC = dyn_cast<ConstantInt>(CI->getArgOperand(1));
298
299 // Cannot fold anything if we're not looking for a constant.
300 if (!CharC)
301 return nullptr;
302
303 StringRef Str;
304 if (!getConstantStringInfo(SrcStr, Str)) {
305 // strrchr(s, 0) -> strchr(s, 0)
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000306 if (CharC->isZero())
Sanjay Pateld3112a52016-01-19 19:46:10 +0000307 return emitStrChr(SrcStr, '\0', B, TLI);
Chris Bienemanad070d02014-09-17 20:55:46 +0000308 return nullptr;
309 }
310
311 // Compute the offset.
312 size_t I = (0xFF & CharC->getSExtValue()) == 0
313 ? Str.size()
314 : Str.rfind(CharC->getSExtValue());
315 if (I == StringRef::npos) // Didn't find the char. Return null.
316 return Constant::getNullValue(CI->getType());
317
318 // strrchr(s+n,c) -> gep(s+n+i,c)
David Blaikie3909da72015-03-30 20:42:56 +0000319 return B.CreateGEP(B.getInt8Ty(), SrcStr, B.getInt64(I), "strrchr");
Chris Bienemanad070d02014-09-17 20:55:46 +0000320}
321
322Value *LibCallSimplifier::optimizeStrCmp(CallInst *CI, IRBuilder<> &B) {
Chris Bienemanad070d02014-09-17 20:55:46 +0000323 Value *Str1P = CI->getArgOperand(0), *Str2P = CI->getArgOperand(1);
324 if (Str1P == Str2P) // strcmp(x,x) -> 0
325 return ConstantInt::get(CI->getType(), 0);
326
327 StringRef Str1, Str2;
328 bool HasStr1 = getConstantStringInfo(Str1P, Str1);
329 bool HasStr2 = getConstantStringInfo(Str2P, Str2);
330
331 // strcmp(x, y) -> cnst (if both x and y are constant strings)
332 if (HasStr1 && HasStr2)
333 return ConstantInt::get(CI->getType(), Str1.compare(Str2));
334
335 if (HasStr1 && Str1.empty()) // strcmp("", x) -> -*x
James Y Knight14359ef2019-02-01 20:44:24 +0000336 return B.CreateNeg(B.CreateZExt(
337 B.CreateLoad(B.getInt8Ty(), Str2P, "strcmpload"), CI->getType()));
Chris Bienemanad070d02014-09-17 20:55:46 +0000338
339 if (HasStr2 && Str2.empty()) // strcmp(x,"") -> *x
James Y Knight14359ef2019-02-01 20:44:24 +0000340 return B.CreateZExt(B.CreateLoad(B.getInt8Ty(), Str1P, "strcmpload"),
341 CI->getType());
Chris Bienemanad070d02014-09-17 20:55:46 +0000342
343 // strcmp(P, "x") -> memcmp(P, "x", 2)
David Bolvansky1f343fa2018-05-22 20:27:36 +0000344 uint64_t Len1 = GetStringLength(Str1P);
345 uint64_t Len2 = GetStringLength(Str2P);
Chris Bienemanad070d02014-09-17 20:55:46 +0000346 if (Len1 && Len2) {
Sanjay Pateld3112a52016-01-19 19:46:10 +0000347 return emitMemCmp(Str1P, Str2P,
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000348 ConstantInt::get(DL.getIntPtrType(CI->getContext()),
Chris Bienemanad070d02014-09-17 20:55:46 +0000349 std::min(Len1, Len2)),
350 B, DL, TLI);
351 }
Meador Inge7fb2f732012-10-13 16:45:32 +0000352
David Bolvansky909889b2018-08-10 04:32:54 +0000353 // strcmp to memcmp
354 if (!HasStr1 && HasStr2) {
355 if (canTransformToMemCmp(CI, Str1P, Len2, DL))
356 return emitMemCmp(
357 Str1P, Str2P,
358 ConstantInt::get(DL.getIntPtrType(CI->getContext()), Len2), B, DL,
359 TLI);
360 } else if (HasStr1 && !HasStr2) {
361 if (canTransformToMemCmp(CI, Str2P, Len1, DL))
362 return emitMemCmp(
363 Str1P, Str2P,
364 ConstantInt::get(DL.getIntPtrType(CI->getContext()), Len1), B, DL,
365 TLI);
366 }
367
Chris Bienemanad070d02014-09-17 20:55:46 +0000368 return nullptr;
369}
370
371Value *LibCallSimplifier::optimizeStrNCmp(CallInst *CI, IRBuilder<> &B) {
Chris Bienemanad070d02014-09-17 20:55:46 +0000372 Value *Str1P = CI->getArgOperand(0), *Str2P = CI->getArgOperand(1);
373 if (Str1P == Str2P) // strncmp(x,x,n) -> 0
374 return ConstantInt::get(CI->getType(), 0);
375
376 // Get the length argument if it is constant.
377 uint64_t Length;
378 if (ConstantInt *LengthArg = dyn_cast<ConstantInt>(CI->getArgOperand(2)))
379 Length = LengthArg->getZExtValue();
380 else
381 return nullptr;
382
383 if (Length == 0) // strncmp(x,y,0) -> 0
384 return ConstantInt::get(CI->getType(), 0);
385
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000386 if (Length == 1) // strncmp(x,y,1) -> memcmp(x,y,1)
Sanjay Pateld3112a52016-01-19 19:46:10 +0000387 return emitMemCmp(Str1P, Str2P, CI->getArgOperand(2), B, DL, TLI);
Chris Bienemanad070d02014-09-17 20:55:46 +0000388
389 StringRef Str1, Str2;
390 bool HasStr1 = getConstantStringInfo(Str1P, Str1);
391 bool HasStr2 = getConstantStringInfo(Str2P, Str2);
392
393 // strncmp(x, y) -> cnst (if both x and y are constant strings)
394 if (HasStr1 && HasStr2) {
395 StringRef SubStr1 = Str1.substr(0, Length);
396 StringRef SubStr2 = Str2.substr(0, Length);
397 return ConstantInt::get(CI->getType(), SubStr1.compare(SubStr2));
398 }
399
400 if (HasStr1 && Str1.empty()) // strncmp("", x, n) -> -*x
James Y Knight14359ef2019-02-01 20:44:24 +0000401 return B.CreateNeg(B.CreateZExt(
402 B.CreateLoad(B.getInt8Ty(), Str2P, "strcmpload"), CI->getType()));
Chris Bienemanad070d02014-09-17 20:55:46 +0000403
404 if (HasStr2 && Str2.empty()) // strncmp(x, "", n) -> *x
James Y Knight14359ef2019-02-01 20:44:24 +0000405 return B.CreateZExt(B.CreateLoad(B.getInt8Ty(), Str1P, "strcmpload"),
406 CI->getType());
Chris Bienemanad070d02014-09-17 20:55:46 +0000407
David Bolvansky909889b2018-08-10 04:32:54 +0000408 uint64_t Len1 = GetStringLength(Str1P);
409 uint64_t Len2 = GetStringLength(Str2P);
410
411 // strncmp to memcmp
412 if (!HasStr1 && HasStr2) {
413 Len2 = std::min(Len2, Length);
414 if (canTransformToMemCmp(CI, Str1P, Len2, DL))
415 return emitMemCmp(
416 Str1P, Str2P,
417 ConstantInt::get(DL.getIntPtrType(CI->getContext()), Len2), B, DL,
418 TLI);
419 } else if (HasStr1 && !HasStr2) {
420 Len1 = std::min(Len1, Length);
421 if (canTransformToMemCmp(CI, Str2P, Len1, DL))
422 return emitMemCmp(
423 Str1P, Str2P,
424 ConstantInt::get(DL.getIntPtrType(CI->getContext()), Len1), B, DL,
425 TLI);
426 }
427
Chris Bienemanad070d02014-09-17 20:55:46 +0000428 return nullptr;
429}
430
431Value *LibCallSimplifier::optimizeStrCpy(CallInst *CI, IRBuilder<> &B) {
Chris Bienemanad070d02014-09-17 20:55:46 +0000432 Value *Dst = CI->getArgOperand(0), *Src = CI->getArgOperand(1);
433 if (Dst == Src) // strcpy(x,x) -> x
434 return Src;
435
Chris Bienemanad070d02014-09-17 20:55:46 +0000436 // See if we can get the length of the input string.
David Bolvansky1f343fa2018-05-22 20:27:36 +0000437 uint64_t Len = GetStringLength(Src);
Chris Bienemanad070d02014-09-17 20:55:46 +0000438 if (Len == 0)
439 return nullptr;
440
441 // We have enough information to now generate the memcpy call to do the
442 // copy for us. Make a memcpy to copy the nul byte with align = 1.
Daniel Neilson8acd8b02018-02-05 21:23:22 +0000443 B.CreateMemCpy(Dst, 1, Src, 1,
444 ConstantInt::get(DL.getIntPtrType(CI->getContext()), Len));
Chris Bienemanad070d02014-09-17 20:55:46 +0000445 return Dst;
446}
447
448Value *LibCallSimplifier::optimizeStpCpy(CallInst *CI, IRBuilder<> &B) {
449 Function *Callee = CI->getCalledFunction();
Chris Bienemanad070d02014-09-17 20:55:46 +0000450 Value *Dst = CI->getArgOperand(0), *Src = CI->getArgOperand(1);
451 if (Dst == Src) { // stpcpy(x,x) -> x+strlen(x)
Sanjay Pateld3112a52016-01-19 19:46:10 +0000452 Value *StrLen = emitStrLen(Src, B, DL, TLI);
David Blaikieaa41cd52015-04-03 21:33:42 +0000453 return StrLen ? B.CreateInBoundsGEP(B.getInt8Ty(), Dst, StrLen) : nullptr;
Chris Bienemanad070d02014-09-17 20:55:46 +0000454 }
455
456 // See if we can get the length of the input string.
David Bolvansky1f343fa2018-05-22 20:27:36 +0000457 uint64_t Len = GetStringLength(Src);
Chris Bienemanad070d02014-09-17 20:55:46 +0000458 if (Len == 0)
459 return nullptr;
460
Davide Italianob7487e62015-11-02 23:07:14 +0000461 Type *PT = Callee->getFunctionType()->getParamType(0);
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000462 Value *LenV = ConstantInt::get(DL.getIntPtrType(PT), Len);
Sanjay Pateld707db92015-12-31 16:10:49 +0000463 Value *DstEnd = B.CreateGEP(B.getInt8Ty(), Dst,
464 ConstantInt::get(DL.getIntPtrType(PT), Len - 1));
Chris Bienemanad070d02014-09-17 20:55:46 +0000465
466 // We have enough information to now generate the memcpy call to do the
467 // copy for us. Make a memcpy to copy the nul byte with align = 1.
Daniel Neilson8acd8b02018-02-05 21:23:22 +0000468 B.CreateMemCpy(Dst, 1, Src, 1, LenV);
Chris Bienemanad070d02014-09-17 20:55:46 +0000469 return DstEnd;
470}
471
472Value *LibCallSimplifier::optimizeStrNCpy(CallInst *CI, IRBuilder<> &B) {
473 Function *Callee = CI->getCalledFunction();
Chris Bienemanad070d02014-09-17 20:55:46 +0000474 Value *Dst = CI->getArgOperand(0);
475 Value *Src = CI->getArgOperand(1);
476 Value *LenOp = CI->getArgOperand(2);
477
478 // See if we can get the length of the input string.
David Bolvansky1f343fa2018-05-22 20:27:36 +0000479 uint64_t SrcLen = GetStringLength(Src);
Chris Bienemanad070d02014-09-17 20:55:46 +0000480 if (SrcLen == 0)
481 return nullptr;
482 --SrcLen;
483
484 if (SrcLen == 0) {
Daniel Neilson8acd8b02018-02-05 21:23:22 +0000485 // strncpy(x, "", y) -> memset(align 1 x, '\0', y)
Chris Bienemanad070d02014-09-17 20:55:46 +0000486 B.CreateMemSet(Dst, B.getInt8('\0'), LenOp, 1);
Meador Inge7fb2f732012-10-13 16:45:32 +0000487 return Dst;
488 }
Meador Inge7fb2f732012-10-13 16:45:32 +0000489
Chris Bienemanad070d02014-09-17 20:55:46 +0000490 uint64_t Len;
491 if (ConstantInt *LengthArg = dyn_cast<ConstantInt>(LenOp))
492 Len = LengthArg->getZExtValue();
493 else
494 return nullptr;
Meador Inge7fb2f732012-10-13 16:45:32 +0000495
Chris Bienemanad070d02014-09-17 20:55:46 +0000496 if (Len == 0)
497 return Dst; // strncpy(x, y, 0) -> x
Meador Inge7fb2f732012-10-13 16:45:32 +0000498
Chris Bienemanad070d02014-09-17 20:55:46 +0000499 // Let strncpy handle the zero padding
500 if (Len > SrcLen + 1)
501 return nullptr;
Meador Inge7fb2f732012-10-13 16:45:32 +0000502
Davide Italianob7487e62015-11-02 23:07:14 +0000503 Type *PT = Callee->getFunctionType()->getParamType(0);
Daniel Neilson8acd8b02018-02-05 21:23:22 +0000504 // strncpy(x, s, c) -> memcpy(align 1 x, align 1 s, c) [s and c are constant]
505 B.CreateMemCpy(Dst, 1, Src, 1, ConstantInt::get(DL.getIntPtrType(PT), Len));
Meador Inge7fb2f732012-10-13 16:45:32 +0000506
Chris Bienemanad070d02014-09-17 20:55:46 +0000507 return Dst;
508}
Meador Inge7fb2f732012-10-13 16:45:32 +0000509
Matthias Braun50ec0b52017-05-19 22:37:09 +0000510Value *LibCallSimplifier::optimizeStringLength(CallInst *CI, IRBuilder<> &B,
511 unsigned CharSize) {
Chris Bienemanad070d02014-09-17 20:55:46 +0000512 Value *Src = CI->getArgOperand(0);
513
514 // Constant folding: strlen("xyz") -> 3
David Bolvansky1f343fa2018-05-22 20:27:36 +0000515 if (uint64_t Len = GetStringLength(Src, CharSize))
Chris Bienemanad070d02014-09-17 20:55:46 +0000516 return ConstantInt::get(CI->getType(), Len - 1);
517
David L Kreitzer752c1442016-04-13 14:31:06 +0000518 // If s is a constant pointer pointing to a string literal, we can fold
Matthias Braun50ec0b52017-05-19 22:37:09 +0000519 // strlen(s + x) to strlen(s) - x, when x is known to be in the range
David L Kreitzer752c1442016-04-13 14:31:06 +0000520 // [0, strlen(s)] or the string has a single null terminator '\0' at the end.
Matthias Braun50ec0b52017-05-19 22:37:09 +0000521 // We only try to simplify strlen when the pointer s points to an array
David L Kreitzer752c1442016-04-13 14:31:06 +0000522 // of i8. Otherwise, we would need to scale the offset x before doing the
Matthias Braun50ec0b52017-05-19 22:37:09 +0000523 // subtraction. This will make the optimization more complex, and it's not
524 // very useful because calling strlen for a pointer of other types is
David L Kreitzer752c1442016-04-13 14:31:06 +0000525 // very uncommon.
526 if (GEPOperator *GEP = dyn_cast<GEPOperator>(Src)) {
Matthias Braun50ec0b52017-05-19 22:37:09 +0000527 if (!isGEPBasedOnPointerToString(GEP, CharSize))
David L Kreitzer752c1442016-04-13 14:31:06 +0000528 return nullptr;
529
Matthias Braun50ec0b52017-05-19 22:37:09 +0000530 ConstantDataArraySlice Slice;
531 if (getConstantDataArrayInfo(GEP->getOperand(0), Slice, CharSize)) {
532 uint64_t NullTermIdx;
533 if (Slice.Array == nullptr) {
534 NullTermIdx = 0;
535 } else {
536 NullTermIdx = ~((uint64_t)0);
537 for (uint64_t I = 0, E = Slice.Length; I < E; ++I) {
538 if (Slice.Array->getElementAsInteger(I + Slice.Offset) == 0) {
539 NullTermIdx = I;
540 break;
541 }
542 }
543 // If the string does not have '\0', leave it to strlen to compute
544 // its length.
545 if (NullTermIdx == ~((uint64_t)0))
546 return nullptr;
547 }
548
David L Kreitzer752c1442016-04-13 14:31:06 +0000549 Value *Offset = GEP->getOperand(2);
Craig Topper8205a1a2017-05-24 16:53:07 +0000550 KnownBits Known = computeKnownBits(Offset, DL, 0, nullptr, CI, nullptr);
Craig Topperb45eabc2017-04-26 16:39:58 +0000551 Known.Zero.flipAllBits();
Matthias Braun50ec0b52017-05-19 22:37:09 +0000552 uint64_t ArrSize =
David L Kreitzer752c1442016-04-13 14:31:06 +0000553 cast<ArrayType>(GEP->getSourceElementType())->getNumElements();
554
Matthias Braun50ec0b52017-05-19 22:37:09 +0000555 // KnownZero's bits are flipped, so zeros in KnownZero now represent
556 // bits known to be zeros in Offset, and ones in KnowZero represent
David L Kreitzer752c1442016-04-13 14:31:06 +0000557 // bits unknown in Offset. Therefore, Offset is known to be in range
Matthias Braun50ec0b52017-05-19 22:37:09 +0000558 // [0, NullTermIdx] when the flipped KnownZero is non-negative and
David L Kreitzer752c1442016-04-13 14:31:06 +0000559 // unsigned-less-than NullTermIdx.
560 //
Matthias Braun50ec0b52017-05-19 22:37:09 +0000561 // If Offset is not provably in the range [0, NullTermIdx], we can still
562 // optimize if we can prove that the program has undefined behavior when
563 // Offset is outside that range. That is the case when GEP->getOperand(0)
David L Kreitzer752c1442016-04-13 14:31:06 +0000564 // is a pointer to an object whose memory extent is NullTermIdx+1.
Matthias Braun50ec0b52017-05-19 22:37:09 +0000565 if ((Known.Zero.isNonNegative() && Known.Zero.ule(NullTermIdx)) ||
David L Kreitzer752c1442016-04-13 14:31:06 +0000566 (GEP->isInBounds() && isa<GlobalVariable>(GEP->getOperand(0)) &&
Matthias Braun50ec0b52017-05-19 22:37:09 +0000567 NullTermIdx == ArrSize - 1)) {
568 Offset = B.CreateSExtOrTrunc(Offset, CI->getType());
569 return B.CreateSub(ConstantInt::get(CI->getType(), NullTermIdx),
David L Kreitzer752c1442016-04-13 14:31:06 +0000570 Offset);
Matthias Braun50ec0b52017-05-19 22:37:09 +0000571 }
David L Kreitzer752c1442016-04-13 14:31:06 +0000572 }
573
574 return nullptr;
575 }
576
Chris Bienemanad070d02014-09-17 20:55:46 +0000577 // strlen(x?"foo":"bars") --> x ? 3 : 4
578 if (SelectInst *SI = dyn_cast<SelectInst>(Src)) {
David Bolvansky1f343fa2018-05-22 20:27:36 +0000579 uint64_t LenTrue = GetStringLength(SI->getTrueValue(), CharSize);
580 uint64_t LenFalse = GetStringLength(SI->getFalseValue(), CharSize);
Chris Bienemanad070d02014-09-17 20:55:46 +0000581 if (LenTrue && LenFalse) {
Vivek Pandya95906582017-10-11 17:12:59 +0000582 ORE.emit([&]() {
583 return OptimizationRemark("instcombine", "simplify-libcalls", CI)
584 << "folded strlen(select) to select of constants";
585 });
Chris Bienemanad070d02014-09-17 20:55:46 +0000586 return B.CreateSelect(SI->getCondition(),
587 ConstantInt::get(CI->getType(), LenTrue - 1),
588 ConstantInt::get(CI->getType(), LenFalse - 1));
589 }
Meador Inge7fb2f732012-10-13 16:45:32 +0000590 }
Meador Inge7fb2f732012-10-13 16:45:32 +0000591
Chris Bienemanad070d02014-09-17 20:55:46 +0000592 // strlen(x) != 0 --> *x != 0
593 // strlen(x) == 0 --> *x == 0
594 if (isOnlyUsedInZeroEqualityComparison(CI))
James Y Knight14359ef2019-02-01 20:44:24 +0000595 return B.CreateZExt(B.CreateLoad(B.getIntNTy(CharSize), Src, "strlenfirst"),
596 CI->getType());
Meador Inge17418502012-10-13 16:45:37 +0000597
Chris Bienemanad070d02014-09-17 20:55:46 +0000598 return nullptr;
599}
Meador Inge17418502012-10-13 16:45:37 +0000600
Matthias Braun50ec0b52017-05-19 22:37:09 +0000601Value *LibCallSimplifier::optimizeStrLen(CallInst *CI, IRBuilder<> &B) {
602 return optimizeStringLength(CI, B, 8);
603}
604
605Value *LibCallSimplifier::optimizeWcslen(CallInst *CI, IRBuilder<> &B) {
David Bolvansky5430b7372018-05-31 16:39:27 +0000606 Module &M = *CI->getModule();
Matthias Braun50ec0b52017-05-19 22:37:09 +0000607 unsigned WCharSize = TLI->getWCharSize(M) * 8;
Matthias Brauncc603ee2017-09-26 02:36:57 +0000608 // We cannot perform this optimization without wchar_size metadata.
609 if (WCharSize == 0)
610 return nullptr;
Matthias Braun50ec0b52017-05-19 22:37:09 +0000611
612 return optimizeStringLength(CI, B, WCharSize);
613}
614
Chris Bienemanad070d02014-09-17 20:55:46 +0000615Value *LibCallSimplifier::optimizeStrPBrk(CallInst *CI, IRBuilder<> &B) {
Chris Bienemanad070d02014-09-17 20:55:46 +0000616 StringRef S1, S2;
617 bool HasS1 = getConstantStringInfo(CI->getArgOperand(0), S1);
618 bool HasS2 = getConstantStringInfo(CI->getArgOperand(1), S2);
Meador Inge17418502012-10-13 16:45:37 +0000619
Reid Kleckner971c3ea2014-11-13 22:55:19 +0000620 // strpbrk(s, "") -> nullptr
621 // strpbrk("", s) -> nullptr
Chris Bienemanad070d02014-09-17 20:55:46 +0000622 if ((HasS1 && S1.empty()) || (HasS2 && S2.empty()))
623 return Constant::getNullValue(CI->getType());
Meador Inge17418502012-10-13 16:45:37 +0000624
Chris Bienemanad070d02014-09-17 20:55:46 +0000625 // Constant folding.
626 if (HasS1 && HasS2) {
627 size_t I = S1.find_first_of(S2);
628 if (I == StringRef::npos) // No match.
Meador Inge17418502012-10-13 16:45:37 +0000629 return Constant::getNullValue(CI->getType());
630
Sanjay Pateld707db92015-12-31 16:10:49 +0000631 return B.CreateGEP(B.getInt8Ty(), CI->getArgOperand(0), B.getInt64(I),
632 "strpbrk");
Meador Inge17418502012-10-13 16:45:37 +0000633 }
Meador Inge17418502012-10-13 16:45:37 +0000634
Chris Bienemanad070d02014-09-17 20:55:46 +0000635 // strpbrk(s, "a") -> strchr(s, 'a')
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000636 if (HasS2 && S2.size() == 1)
Sanjay Pateld3112a52016-01-19 19:46:10 +0000637 return emitStrChr(CI->getArgOperand(0), S2[0], B, TLI);
Chris Bienemanad070d02014-09-17 20:55:46 +0000638
639 return nullptr;
640}
641
642Value *LibCallSimplifier::optimizeStrTo(CallInst *CI, IRBuilder<> &B) {
Chris Bienemanad070d02014-09-17 20:55:46 +0000643 Value *EndPtr = CI->getArgOperand(1);
644 if (isa<ConstantPointerNull>(EndPtr)) {
645 // With a null EndPtr, this function won't capture the main argument.
646 // It would be readonly too, except that it still may write to errno.
Reid Klecknera0b45f42017-05-03 18:17:31 +0000647 CI->addParamAttr(0, Attribute::NoCapture);
Chris Bienemanad070d02014-09-17 20:55:46 +0000648 }
649
650 return nullptr;
651}
652
653Value *LibCallSimplifier::optimizeStrSpn(CallInst *CI, IRBuilder<> &B) {
Chris Bienemanad070d02014-09-17 20:55:46 +0000654 StringRef S1, S2;
655 bool HasS1 = getConstantStringInfo(CI->getArgOperand(0), S1);
656 bool HasS2 = getConstantStringInfo(CI->getArgOperand(1), S2);
657
658 // strspn(s, "") -> 0
659 // strspn("", s) -> 0
660 if ((HasS1 && S1.empty()) || (HasS2 && S2.empty()))
661 return Constant::getNullValue(CI->getType());
662
663 // Constant folding.
664 if (HasS1 && HasS2) {
665 size_t Pos = S1.find_first_not_of(S2);
666 if (Pos == StringRef::npos)
667 Pos = S1.size();
668 return ConstantInt::get(CI->getType(), Pos);
669 }
670
671 return nullptr;
672}
673
674Value *LibCallSimplifier::optimizeStrCSpn(CallInst *CI, IRBuilder<> &B) {
Chris Bienemanad070d02014-09-17 20:55:46 +0000675 StringRef S1, S2;
676 bool HasS1 = getConstantStringInfo(CI->getArgOperand(0), S1);
677 bool HasS2 = getConstantStringInfo(CI->getArgOperand(1), S2);
678
679 // strcspn("", s) -> 0
680 if (HasS1 && S1.empty())
681 return Constant::getNullValue(CI->getType());
682
683 // Constant folding.
684 if (HasS1 && HasS2) {
685 size_t Pos = S1.find_first_of(S2);
686 if (Pos == StringRef::npos)
687 Pos = S1.size();
688 return ConstantInt::get(CI->getType(), Pos);
689 }
690
691 // strcspn(s, "") -> strlen(s)
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000692 if (HasS2 && S2.empty())
Sanjay Pateld3112a52016-01-19 19:46:10 +0000693 return emitStrLen(CI->getArgOperand(0), B, DL, TLI);
Chris Bienemanad070d02014-09-17 20:55:46 +0000694
695 return nullptr;
696}
697
698Value *LibCallSimplifier::optimizeStrStr(CallInst *CI, IRBuilder<> &B) {
Chris Bienemanad070d02014-09-17 20:55:46 +0000699 // fold strstr(x, x) -> x.
700 if (CI->getArgOperand(0) == CI->getArgOperand(1))
701 return B.CreateBitCast(CI->getArgOperand(0), CI->getType());
702
703 // fold strstr(a, b) == a -> strncmp(a, b, strlen(b)) == 0
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000704 if (isOnlyUsedInEqualityComparison(CI, CI->getArgOperand(0))) {
Sanjay Pateld3112a52016-01-19 19:46:10 +0000705 Value *StrLen = emitStrLen(CI->getArgOperand(1), B, DL, TLI);
Chris Bienemanad070d02014-09-17 20:55:46 +0000706 if (!StrLen)
Craig Topperf40110f2014-04-25 05:29:35 +0000707 return nullptr;
Sanjay Pateld3112a52016-01-19 19:46:10 +0000708 Value *StrNCmp = emitStrNCmp(CI->getArgOperand(0), CI->getArgOperand(1),
Chris Bienemanad070d02014-09-17 20:55:46 +0000709 StrLen, B, DL, TLI);
710 if (!StrNCmp)
Craig Topperf40110f2014-04-25 05:29:35 +0000711 return nullptr;
Chris Bienemanad070d02014-09-17 20:55:46 +0000712 for (auto UI = CI->user_begin(), UE = CI->user_end(); UI != UE;) {
713 ICmpInst *Old = cast<ICmpInst>(*UI++);
714 Value *Cmp =
715 B.CreateICmp(Old->getPredicate(), StrNCmp,
716 ConstantInt::getNullValue(StrNCmp->getType()), "cmp");
717 replaceAllUsesWith(Old, Cmp);
Meador Inge17418502012-10-13 16:45:37 +0000718 }
Chris Bienemanad070d02014-09-17 20:55:46 +0000719 return CI;
720 }
Meador Inge17418502012-10-13 16:45:37 +0000721
Chris Bienemanad070d02014-09-17 20:55:46 +0000722 // See if either input string is a constant string.
723 StringRef SearchStr, ToFindStr;
724 bool HasStr1 = getConstantStringInfo(CI->getArgOperand(0), SearchStr);
725 bool HasStr2 = getConstantStringInfo(CI->getArgOperand(1), ToFindStr);
726
727 // fold strstr(x, "") -> x.
728 if (HasStr2 && ToFindStr.empty())
729 return B.CreateBitCast(CI->getArgOperand(0), CI->getType());
730
731 // If both strings are known, constant fold it.
732 if (HasStr1 && HasStr2) {
733 size_t Offset = SearchStr.find(ToFindStr);
734
735 if (Offset == StringRef::npos) // strstr("foo", "bar") -> null
Meador Inge17418502012-10-13 16:45:37 +0000736 return Constant::getNullValue(CI->getType());
737
Chris Bienemanad070d02014-09-17 20:55:46 +0000738 // strstr("abcd", "bc") -> gep((char*)"abcd", 1)
Sanjay Pateld3112a52016-01-19 19:46:10 +0000739 Value *Result = castToCStr(CI->getArgOperand(0), B);
James Y Knight77160752019-02-01 20:44:47 +0000740 Result =
741 B.CreateConstInBoundsGEP1_64(B.getInt8Ty(), Result, Offset, "strstr");
Chris Bienemanad070d02014-09-17 20:55:46 +0000742 return B.CreateBitCast(Result, CI->getType());
Meador Inge17418502012-10-13 16:45:37 +0000743 }
Meador Inge17418502012-10-13 16:45:37 +0000744
Chris Bienemanad070d02014-09-17 20:55:46 +0000745 // fold strstr(x, "y") -> strchr(x, 'y').
746 if (HasStr2 && ToFindStr.size() == 1) {
Sanjay Pateld3112a52016-01-19 19:46:10 +0000747 Value *StrChr = emitStrChr(CI->getArgOperand(0), ToFindStr[0], B, TLI);
Chris Bienemanad070d02014-09-17 20:55:46 +0000748 return StrChr ? B.CreateBitCast(StrChr, CI->getType()) : nullptr;
749 }
750 return nullptr;
751}
Meador Inge40b6fac2012-10-15 03:47:37 +0000752
Benjamin Kramer691363e2015-03-21 15:36:21 +0000753Value *LibCallSimplifier::optimizeMemChr(CallInst *CI, IRBuilder<> &B) {
Benjamin Kramer691363e2015-03-21 15:36:21 +0000754 Value *SrcStr = CI->getArgOperand(0);
755 ConstantInt *CharC = dyn_cast<ConstantInt>(CI->getArgOperand(1));
756 ConstantInt *LenC = dyn_cast<ConstantInt>(CI->getArgOperand(2));
757
758 // memchr(x, y, 0) -> null
Craig Topper79ab6432017-07-06 18:39:47 +0000759 if (LenC && LenC->isZero())
Benjamin Kramer691363e2015-03-21 15:36:21 +0000760 return Constant::getNullValue(CI->getType());
761
Benjamin Kramer7857d722015-03-21 21:09:33 +0000762 // From now on we need at least constant length and string.
Benjamin Kramer691363e2015-03-21 15:36:21 +0000763 StringRef Str;
Benjamin Kramer7857d722015-03-21 21:09:33 +0000764 if (!LenC || !getConstantStringInfo(SrcStr, Str, 0, /*TrimAtNul=*/false))
Benjamin Kramer691363e2015-03-21 15:36:21 +0000765 return nullptr;
766
767 // Truncate the string to LenC. If Str is smaller than LenC we will still only
768 // scan the string, as reading past the end of it is undefined and we can just
769 // return null if we don't find the char.
770 Str = Str.substr(0, LenC->getZExtValue());
771
Benjamin Kramer7857d722015-03-21 21:09:33 +0000772 // If the char is variable but the input str and length are not we can turn
773 // this memchr call into a simple bit field test. Of course this only works
774 // when the return value is only checked against null.
775 //
776 // It would be really nice to reuse switch lowering here but we can't change
777 // the CFG at this point.
778 //
Fangrui Songf2609672019-03-12 10:31:52 +0000779 // memchr("\r\n", C, 2) != nullptr -> (1 << C & ((1 << '\r') | (1 << '\n')))
780 // != 0
Benjamin Kramer7857d722015-03-21 21:09:33 +0000781 // after bounds check.
782 if (!CharC && !Str.empty() && isOnlyUsedInZeroEqualityComparison(CI)) {
Benjamin Kramerd6aa0ec2015-03-21 22:04:26 +0000783 unsigned char Max =
784 *std::max_element(reinterpret_cast<const unsigned char *>(Str.begin()),
785 reinterpret_cast<const unsigned char *>(Str.end()));
Benjamin Kramer7857d722015-03-21 21:09:33 +0000786
787 // Make sure the bit field we're about to create fits in a register on the
788 // target.
789 // FIXME: On a 64 bit architecture this prevents us from using the
790 // interesting range of alpha ascii chars. We could do better by emitting
791 // two bitfields or shifting the range by 64 if no lower chars are used.
792 if (!DL.fitsInLegalInteger(Max + 1))
793 return nullptr;
794
795 // For the bit field use a power-of-2 type with at least 8 bits to avoid
796 // creating unnecessary illegal types.
797 unsigned char Width = NextPowerOf2(std::max((unsigned char)7, Max));
798
799 // Now build the bit field.
800 APInt Bitfield(Width, 0);
801 for (char C : Str)
802 Bitfield.setBit((unsigned char)C);
803 Value *BitfieldC = B.getInt(Bitfield);
804
Eli Friedmand4e7a0d2019-01-09 23:39:26 +0000805 // Adjust width of "C" to the bitfield width, then mask off the high bits.
Benjamin Kramer7857d722015-03-21 21:09:33 +0000806 Value *C = B.CreateZExtOrTrunc(CI->getArgOperand(1), BitfieldC->getType());
Eli Friedmand4e7a0d2019-01-09 23:39:26 +0000807 C = B.CreateAnd(C, B.getIntN(Width, 0xFF));
808
809 // First check that the bit field access is within bounds.
Benjamin Kramer7857d722015-03-21 21:09:33 +0000810 Value *Bounds = B.CreateICmp(ICmpInst::ICMP_ULT, C, B.getIntN(Width, Width),
811 "memchr.bounds");
812
813 // Create code that checks if the given bit is set in the field.
814 Value *Shl = B.CreateShl(B.getIntN(Width, 1ULL), C);
815 Value *Bits = B.CreateIsNotNull(B.CreateAnd(Shl, BitfieldC), "memchr.bits");
816
817 // Finally merge both checks and cast to pointer type. The inttoptr
818 // implicitly zexts the i1 to intptr type.
819 return B.CreateIntToPtr(B.CreateAnd(Bounds, Bits, "memchr"), CI->getType());
820 }
821
822 // Check if all arguments are constants. If so, we can constant fold.
823 if (!CharC)
824 return nullptr;
825
Benjamin Kramer691363e2015-03-21 15:36:21 +0000826 // Compute the offset.
827 size_t I = Str.find(CharC->getSExtValue() & 0xFF);
828 if (I == StringRef::npos) // Didn't find the char. memchr returns null.
829 return Constant::getNullValue(CI->getType());
830
831 // memchr(s+n,c,l) -> gep(s+n+i,c)
David Blaikie3909da72015-03-30 20:42:56 +0000832 return B.CreateGEP(B.getInt8Ty(), SrcStr, B.getInt64(I), "memchr");
Benjamin Kramer691363e2015-03-21 15:36:21 +0000833}
834
Clement Courbet8e16d732019-03-08 09:07:45 +0000835static Value *optimizeMemCmpConstantSize(CallInst *CI, Value *LHS, Value *RHS,
836 uint64_t Len, IRBuilder<> &B,
837 const DataLayout &DL) {
Chris Bienemanad070d02014-09-17 20:55:46 +0000838 if (Len == 0) // memcmp(s1,s2,0) -> 0
839 return Constant::getNullValue(CI->getType());
840
841 // memcmp(S1,S2,1) -> *(unsigned char*)LHS - *(unsigned char*)RHS
842 if (Len == 1) {
James Y Knight14359ef2019-02-01 20:44:24 +0000843 Value *LHSV =
844 B.CreateZExt(B.CreateLoad(B.getInt8Ty(), castToCStr(LHS, B), "lhsc"),
845 CI->getType(), "lhsv");
846 Value *RHSV =
847 B.CreateZExt(B.CreateLoad(B.getInt8Ty(), castToCStr(RHS, B), "rhsc"),
848 CI->getType(), "rhsv");
Chris Bienemanad070d02014-09-17 20:55:46 +0000849 return B.CreateSub(LHSV, RHSV, "chardiff");
Meador Inge40b6fac2012-10-15 03:47:37 +0000850 }
Meador Inge40b6fac2012-10-15 03:47:37 +0000851
Chad Rosierdc655322015-08-28 18:30:18 +0000852 // memcmp(S1,S2,N/8)==0 -> (*(intN_t*)S1 != *(intN_t*)S2)==0
Sanjay Patel82ec8722017-08-21 19:13:14 +0000853 // TODO: The case where both inputs are constants does not need to be limited
854 // to legal integers or equality comparison. See block below this.
Chad Rosierdc655322015-08-28 18:30:18 +0000855 if (DL.isLegalInteger(Len * 8) && isOnlyUsedInZeroEqualityComparison(CI)) {
Chad Rosierdc655322015-08-28 18:30:18 +0000856 IntegerType *IntType = IntegerType::get(CI->getContext(), Len * 8);
857 unsigned PrefAlignment = DL.getPrefTypeAlignment(IntType);
858
Sanjay Patel82ec8722017-08-21 19:13:14 +0000859 // First, see if we can fold either argument to a constant.
860 Value *LHSV = nullptr;
861 if (auto *LHSC = dyn_cast<Constant>(LHS)) {
862 LHSC = ConstantExpr::getBitCast(LHSC, IntType->getPointerTo());
863 LHSV = ConstantFoldLoadFromConstPtr(LHSC, IntType, DL);
864 }
865 Value *RHSV = nullptr;
866 if (auto *RHSC = dyn_cast<Constant>(RHS)) {
867 RHSC = ConstantExpr::getBitCast(RHSC, IntType->getPointerTo());
868 RHSV = ConstantFoldLoadFromConstPtr(RHSC, IntType, DL);
869 }
Chad Rosierdc655322015-08-28 18:30:18 +0000870
Sanjay Patel82ec8722017-08-21 19:13:14 +0000871 // Don't generate unaligned loads. If either source is constant data,
872 // alignment doesn't matter for that source because there is no load.
873 if ((LHSV || getKnownAlignment(LHS, DL, CI) >= PrefAlignment) &&
874 (RHSV || getKnownAlignment(RHS, DL, CI) >= PrefAlignment)) {
875 if (!LHSV) {
876 Type *LHSPtrTy =
877 IntType->getPointerTo(LHS->getType()->getPointerAddressSpace());
James Y Knight14359ef2019-02-01 20:44:24 +0000878 LHSV = B.CreateLoad(IntType, B.CreateBitCast(LHS, LHSPtrTy), "lhsv");
Sanjay Patel82ec8722017-08-21 19:13:14 +0000879 }
880 if (!RHSV) {
881 Type *RHSPtrTy =
882 IntType->getPointerTo(RHS->getType()->getPointerAddressSpace());
James Y Knight14359ef2019-02-01 20:44:24 +0000883 RHSV = B.CreateLoad(IntType, B.CreateBitCast(RHS, RHSPtrTy), "rhsv");
Sanjay Patel82ec8722017-08-21 19:13:14 +0000884 }
Sanjay Patel7756edf2017-08-21 13:55:49 +0000885 return B.CreateZExt(B.CreateICmpNE(LHSV, RHSV), CI->getType(), "memcmp");
Sanjay Patel707f7862017-08-21 15:16:25 +0000886 }
Chad Rosierdc655322015-08-28 18:30:18 +0000887 }
888
Sanjay Patel82ec8722017-08-21 19:13:14 +0000889 // Constant folding: memcmp(x, y, Len) -> constant (all arguments are const).
890 // TODO: This is limited to i8 arrays.
Chris Bienemanad070d02014-09-17 20:55:46 +0000891 StringRef LHSStr, RHSStr;
892 if (getConstantStringInfo(LHS, LHSStr) &&
893 getConstantStringInfo(RHS, RHSStr)) {
894 // Make sure we're not reading out-of-bounds memory.
895 if (Len > LHSStr.size() || Len > RHSStr.size())
Craig Topperf40110f2014-04-25 05:29:35 +0000896 return nullptr;
Chris Bienemanad070d02014-09-17 20:55:46 +0000897 // Fold the memcmp and normalize the result. This way we get consistent
898 // results across multiple platforms.
899 uint64_t Ret = 0;
900 int Cmp = memcmp(LHSStr.data(), RHSStr.data(), Len);
901 if (Cmp < 0)
902 Ret = -1;
903 else if (Cmp > 0)
904 Ret = 1;
905 return ConstantInt::get(CI->getType(), Ret);
Meador Inge000dbcc2012-10-18 18:12:40 +0000906 }
Clement Courbet8e16d732019-03-08 09:07:45 +0000907 return nullptr;
908}
909
910Value *LibCallSimplifier::optimizeMemCmp(CallInst *CI, IRBuilder<> &B) {
911 Value *LHS = CI->getArgOperand(0), *RHS = CI->getArgOperand(1);
912 Value *Size = CI->getArgOperand(2);
913
914 if (LHS == RHS) // memcmp(s,s,x) -> 0
915 return Constant::getNullValue(CI->getType());
916
917 // Handle constant lengths.
918 if (ConstantInt *LenC = dyn_cast<ConstantInt>(Size))
919 if (Value *Res = optimizeMemCmpConstantSize(CI, LHS, RHS,
920 LenC->getZExtValue(), B, DL))
921 return Res;
922
923 // memcmp(x, y, Len) == 0 -> bcmp(x, y, Len) == 0
924 // `bcmp` can be more efficient than memcmp because it only has to know that
Fangrui Songf2609672019-03-12 10:31:52 +0000925 // there is a difference, not where it is.
Clement Courbet8e16d732019-03-08 09:07:45 +0000926 if (isOnlyUsedInZeroEqualityComparison(CI) && TLI->has(LibFunc_bcmp)) {
927 return emitBCmp(LHS, RHS, Size, B, DL, TLI);
928 }
Meador Inge000dbcc2012-10-18 18:12:40 +0000929
Chris Bienemanad070d02014-09-17 20:55:46 +0000930 return nullptr;
931}
Meador Inge9a6a1902012-10-31 00:20:56 +0000932
Chris Bienemanad070d02014-09-17 20:55:46 +0000933Value *LibCallSimplifier::optimizeMemCpy(CallInst *CI, IRBuilder<> &B) {
Daniel Neilson8acd8b02018-02-05 21:23:22 +0000934 // memcpy(x, y, n) -> llvm.memcpy(align 1 x, align 1 y, n)
935 B.CreateMemCpy(CI->getArgOperand(0), 1, CI->getArgOperand(1), 1,
936 CI->getArgOperand(2));
Chris Bienemanad070d02014-09-17 20:55:46 +0000937 return CI->getArgOperand(0);
938}
Meador Inge05a625a2012-10-31 14:58:26 +0000939
Chris Bienemanad070d02014-09-17 20:55:46 +0000940Value *LibCallSimplifier::optimizeMemMove(CallInst *CI, IRBuilder<> &B) {
Daniel Neilson8acd8b02018-02-05 21:23:22 +0000941 // memmove(x, y, n) -> llvm.memmove(align 1 x, align 1 y, n)
942 B.CreateMemMove(CI->getArgOperand(0), 1, CI->getArgOperand(1), 1,
943 CI->getArgOperand(2));
Chris Bienemanad070d02014-09-17 20:55:46 +0000944 return CI->getArgOperand(0);
945}
Meador Ingebcd88ef72012-11-10 15:16:48 +0000946
Sanjay Patel980b2802016-01-26 16:17:24 +0000947/// Fold memset[_chk](malloc(n), 0, n) --> calloc(1, n).
Amara Emerson54f60252018-10-11 14:51:11 +0000948Value *LibCallSimplifier::foldMallocMemset(CallInst *Memset, IRBuilder<> &B) {
Sanjay Patel980b2802016-01-26 16:17:24 +0000949 // This has to be a memset of zeros (bzero).
950 auto *FillValue = dyn_cast<ConstantInt>(Memset->getArgOperand(1));
951 if (!FillValue || FillValue->getZExtValue() != 0)
952 return nullptr;
953
954 // TODO: We should handle the case where the malloc has more than one use.
955 // This is necessary to optimize common patterns such as when the result of
956 // the malloc is checked against null or when a memset intrinsic is used in
957 // place of a memset library call.
958 auto *Malloc = dyn_cast<CallInst>(Memset->getArgOperand(0));
959 if (!Malloc || !Malloc->hasOneUse())
960 return nullptr;
961
962 // Is the inner call really malloc()?
963 Function *InnerCallee = Malloc->getCalledFunction();
Matthias Braunc36a78c2017-04-25 19:44:25 +0000964 if (!InnerCallee)
965 return nullptr;
966
David L. Jonesd21529f2017-01-23 23:16:46 +0000967 LibFunc Func;
Amara Emerson54f60252018-10-11 14:51:11 +0000968 if (!TLI->getLibFunc(*InnerCallee, Func) || !TLI->has(Func) ||
David L. Jonesd21529f2017-01-23 23:16:46 +0000969 Func != LibFunc_malloc)
Sanjay Patel980b2802016-01-26 16:17:24 +0000970 return nullptr;
971
Sanjay Patel980b2802016-01-26 16:17:24 +0000972 // The memset must cover the same number of bytes that are malloc'd.
973 if (Memset->getArgOperand(2) != Malloc->getArgOperand(0))
974 return nullptr;
975
976 // Replace the malloc with a calloc. We need the data layout to know what the
Fangrui Songf78650a2018-07-30 19:41:25 +0000977 // actual size of a 'size_t' parameter is.
Sanjay Patel980b2802016-01-26 16:17:24 +0000978 B.SetInsertPoint(Malloc->getParent(), ++Malloc->getIterator());
979 const DataLayout &DL = Malloc->getModule()->getDataLayout();
980 IntegerType *SizeType = DL.getIntPtrType(B.GetInsertBlock()->getContext());
981 Value *Calloc = emitCalloc(ConstantInt::get(SizeType, 1),
982 Malloc->getArgOperand(0), Malloc->getAttributes(),
Amara Emerson54f60252018-10-11 14:51:11 +0000983 B, *TLI);
Sanjay Patel980b2802016-01-26 16:17:24 +0000984 if (!Calloc)
985 return nullptr;
986
987 Malloc->replaceAllUsesWith(Calloc);
Amara Emerson54f60252018-10-11 14:51:11 +0000988 eraseFromParent(Malloc);
Sanjay Patel980b2802016-01-26 16:17:24 +0000989
990 return Calloc;
991}
992
Chris Bienemanad070d02014-09-17 20:55:46 +0000993Value *LibCallSimplifier::optimizeMemSet(CallInst *CI, IRBuilder<> &B) {
Amara Emerson54f60252018-10-11 14:51:11 +0000994 if (auto *Calloc = foldMallocMemset(CI, B))
Sanjay Patel980b2802016-01-26 16:17:24 +0000995 return Calloc;
996
Daniel Neilson8acd8b02018-02-05 21:23:22 +0000997 // memset(p, v, n) -> llvm.memset(align 1 p, v, n)
Chris Bienemanad070d02014-09-17 20:55:46 +0000998 Value *Val = B.CreateIntCast(CI->getArgOperand(1), B.getInt8Ty(), false);
999 B.CreateMemSet(CI->getArgOperand(0), Val, CI->getArgOperand(2), 1);
1000 return CI->getArgOperand(0);
1001}
Meador Inged4825782012-11-11 06:49:03 +00001002
Sanjay Patelb2ab3f22018-04-18 14:21:31 +00001003Value *LibCallSimplifier::optimizeRealloc(CallInst *CI, IRBuilder<> &B) {
1004 if (isa<ConstantPointerNull>(CI->getArgOperand(0)))
1005 return emitMalloc(CI->getArgOperand(1), B, DL, TLI);
1006
1007 return nullptr;
1008}
1009
Meador Inge193e0352012-11-13 04:16:17 +00001010//===----------------------------------------------------------------------===//
1011// Math Library Optimizations
1012//===----------------------------------------------------------------------===//
1013
Evandro Menezes5aa217a2018-08-03 17:50:16 +00001014// Replace a libcall \p CI with a call to intrinsic \p IID
1015static Value *replaceUnaryCall(CallInst *CI, IRBuilder<> &B, Intrinsic::ID IID) {
1016 // Propagate fast-math flags from the existing call to the new call.
1017 IRBuilder<>::FastMathFlagGuard Guard(B);
1018 B.setFastMathFlags(CI->getFastMathFlags());
1019
1020 Module *M = CI->getModule();
1021 Value *V = CI->getArgOperand(0);
1022 Function *F = Intrinsic::getDeclaration(M, IID, CI->getType());
1023 CallInst *NewCall = B.CreateCall(F, V);
1024 NewCall->takeName(CI);
1025 return NewCall;
1026}
1027
Matthias Braund34e4d22014-12-03 21:46:33 +00001028/// Return a variant of Val with float type.
1029/// Currently this works in two cases: If Val is an FPExtension of a float
1030/// value to something bigger, simply return the operand.
1031/// If Val is a ConstantFP but can be converted to a float ConstantFP without
1032/// loss of precision do so.
1033static Value *valueHasFloatPrecision(Value *Val) {
1034 if (FPExtInst *Cast = dyn_cast<FPExtInst>(Val)) {
1035 Value *Op = Cast->getOperand(0);
1036 if (Op->getType()->isFloatTy())
1037 return Op;
1038 }
1039 if (ConstantFP *Const = dyn_cast<ConstantFP>(Val)) {
1040 APFloat F = Const->getValueAPF();
Matthias Braun395a82f2014-12-03 22:10:39 +00001041 bool losesInfo;
Stephan Bergmann17c7f702016-12-14 11:57:17 +00001042 (void)F.convert(APFloat::IEEEsingle(), APFloat::rmNearestTiesToEven,
Matthias Braun395a82f2014-12-03 22:10:39 +00001043 &losesInfo);
1044 if (!losesInfo)
Matthias Braund34e4d22014-12-03 21:46:33 +00001045 return ConstantFP::get(Const->getContext(), F);
1046 }
1047 return nullptr;
1048}
1049
Evandro Menezes5aa217a2018-08-03 17:50:16 +00001050/// Shrink double -> float functions.
1051static Value *optimizeDoubleFP(CallInst *CI, IRBuilder<> &B,
Evandro Menezes6e137cb2018-08-06 19:40:17 +00001052 bool isBinary, bool isPrecise = false) {
Ahmed Bougachad765a822016-04-27 19:04:35 +00001053 if (!CI->getType()->isDoubleTy())
Chris Bienemanad070d02014-09-17 20:55:46 +00001054 return nullptr;
Meador Inge193e0352012-11-13 04:16:17 +00001055
Evandro Menezes6e137cb2018-08-06 19:40:17 +00001056 // If not all the uses of the function are converted to float, then bail out.
1057 // This matters if the precision of the result is more important than the
1058 // precision of the arguments.
1059 if (isPrecise)
Chris Bienemanad070d02014-09-17 20:55:46 +00001060 for (User *U : CI->users()) {
1061 FPTruncInst *Cast = dyn_cast<FPTruncInst>(U);
1062 if (!Cast || !Cast->getType()->isFloatTy())
1063 return nullptr;
Meador Inge193e0352012-11-13 04:16:17 +00001064 }
Chris Bienemanad070d02014-09-17 20:55:46 +00001065
Evandro Menezes5aa217a2018-08-03 17:50:16 +00001066 // If this is something like 'g((double) float)', convert to 'gf(float)'.
1067 Value *V[2];
1068 V[0] = valueHasFloatPrecision(CI->getArgOperand(0));
1069 V[1] = isBinary ? valueHasFloatPrecision(CI->getArgOperand(1)) : nullptr;
1070 if (!V[0] || (isBinary && !V[1]))
Chris Bienemanad070d02014-09-17 20:55:46 +00001071 return nullptr;
Fangrui Songf78650a2018-07-30 19:41:25 +00001072
Andrew Ng1606fc02017-04-25 12:36:14 +00001073 // If call isn't an intrinsic, check that it isn't within a function with the
Evandro Menezes5aa217a2018-08-03 17:50:16 +00001074 // same name as the float version of this call, otherwise the result is an
1075 // infinite loop. For example, from MinGW-w64:
Andrew Ng1606fc02017-04-25 12:36:14 +00001076 //
Evandro Menezes5aa217a2018-08-03 17:50:16 +00001077 // float expf(float val) { return (float) exp((double) val); }
1078 Function *CalleeFn = CI->getCalledFunction();
1079 StringRef CalleeNm = CalleeFn->getName();
1080 AttributeList CalleeAt = CalleeFn->getAttributes();
1081 if (CalleeFn && !CalleeFn->isIntrinsic()) {
1082 const Function *Fn = CI->getFunction();
1083 StringRef FnName = Fn->getName();
1084 if (FnName.back() == 'f' &&
1085 FnName.size() == (CalleeNm.size() + 1) &&
1086 FnName.startswith(CalleeNm))
Andrew Ng1606fc02017-04-25 12:36:14 +00001087 return nullptr;
1088 }
1089
Evandro Menezes5aa217a2018-08-03 17:50:16 +00001090 // Propagate the math semantics from the current function to the new function.
Sanjay Patelaa231142015-12-31 21:52:31 +00001091 IRBuilder<>::FastMathFlagGuard Guard(B);
Sanjay Patela2528152016-01-12 18:03:37 +00001092 B.setFastMathFlags(CI->getFastMathFlags());
Chris Bienemanad070d02014-09-17 20:55:46 +00001093
Evandro Menezes5aa217a2018-08-03 17:50:16 +00001094 // g((double) float) -> (double) gf(float)
1095 Value *R;
1096 if (CalleeFn->isIntrinsic()) {
Sanjay Patelaf674fb2015-12-14 17:24:23 +00001097 Module *M = CI->getModule();
Evandro Menezes5aa217a2018-08-03 17:50:16 +00001098 Intrinsic::ID IID = CalleeFn->getIntrinsicID();
1099 Function *Fn = Intrinsic::getDeclaration(M, IID, B.getFloatTy());
1100 R = isBinary ? B.CreateCall(Fn, V) : B.CreateCall(Fn, V[0]);
Sanjay Patel848309d2014-10-23 21:52:45 +00001101 }
Evandro Menezes5aa217a2018-08-03 17:50:16 +00001102 else
1103 R = isBinary ? emitBinaryFloatFnCall(V[0], V[1], CalleeNm, B, CalleeAt)
1104 : emitUnaryFloatFnCall(V[0], CalleeNm, B, CalleeAt);
Sanjay Patel848309d2014-10-23 21:52:45 +00001105
Evandro Menezes5aa217a2018-08-03 17:50:16 +00001106 return B.CreateFPExt(R, B.getDoubleTy());
Chris Bienemanad070d02014-09-17 20:55:46 +00001107}
Meador Inge193e0352012-11-13 04:16:17 +00001108
Evandro Menezes5aa217a2018-08-03 17:50:16 +00001109/// Shrink double -> float for unary functions.
1110static Value *optimizeUnaryDoubleFP(CallInst *CI, IRBuilder<> &B,
Evandro Menezes6e137cb2018-08-06 19:40:17 +00001111 bool isPrecise = false) {
1112 return optimizeDoubleFP(CI, B, false, isPrecise);
Matt Arsenault954a6242017-01-23 23:55:08 +00001113}
1114
Evandro Menezes5aa217a2018-08-03 17:50:16 +00001115/// Shrink double -> float for binary functions.
1116static Value *optimizeBinaryDoubleFP(CallInst *CI, IRBuilder<> &B,
Evandro Menezes6e137cb2018-08-06 19:40:17 +00001117 bool isPrecise = false) {
1118 return optimizeDoubleFP(CI, B, true, isPrecise);
Chris Bienemanad070d02014-09-17 20:55:46 +00001119}
1120
Hal Finkel2ff24732017-12-16 01:26:25 +00001121// cabs(z) -> sqrt((creal(z)*creal(z)) + (cimag(z)*cimag(z)))
1122Value *LibCallSimplifier::optimizeCAbs(CallInst *CI, IRBuilder<> &B) {
1123 if (!CI->isFast())
1124 return nullptr;
1125
1126 // Propagate fast-math flags from the existing call to new instructions.
1127 IRBuilder<>::FastMathFlagGuard Guard(B);
1128 B.setFastMathFlags(CI->getFastMathFlags());
1129
1130 Value *Real, *Imag;
1131 if (CI->getNumArgOperands() == 1) {
1132 Value *Op = CI->getArgOperand(0);
1133 assert(Op->getType()->isArrayTy() && "Unexpected signature for cabs!");
1134 Real = B.CreateExtractValue(Op, 0, "real");
1135 Imag = B.CreateExtractValue(Op, 1, "imag");
1136 } else {
1137 assert(CI->getNumArgOperands() == 2 && "Unexpected signature for cabs!");
1138 Real = CI->getArgOperand(0);
1139 Imag = CI->getArgOperand(1);
1140 }
1141
1142 Value *RealReal = B.CreateFMul(Real, Real);
1143 Value *ImagImag = B.CreateFMul(Imag, Imag);
1144
1145 Function *FSqrt = Intrinsic::getDeclaration(CI->getModule(), Intrinsic::sqrt,
1146 CI->getType());
1147 return B.CreateCall(FSqrt, B.CreateFAdd(RealReal, ImagImag), "cabs");
1148}
1149
Sanjay Patele45a83d2018-08-13 19:24:41 +00001150static Value *optimizeTrigReflections(CallInst *Call, LibFunc Func,
1151 IRBuilder<> &B) {
Sanjay Patel15bff182018-08-13 21:49:19 +00001152 if (!isa<FPMathOperator>(Call))
1153 return nullptr;
Clement Courbet8e16d732019-03-08 09:07:45 +00001154
Sanjay Patel15bff182018-08-13 21:49:19 +00001155 IRBuilder<>::FastMathFlagGuard Guard(B);
1156 B.setFastMathFlags(Call->getFastMathFlags());
Clement Courbet8e16d732019-03-08 09:07:45 +00001157
Sanjay Patele45a83d2018-08-13 19:24:41 +00001158 // TODO: Can this be shared to also handle LLVM intrinsics?
Sanjay Patelce4ddbe2018-08-13 17:40:49 +00001159 Value *X;
Sanjay Patele45a83d2018-08-13 19:24:41 +00001160 switch (Func) {
1161 case LibFunc_sin:
1162 case LibFunc_sinf:
1163 case LibFunc_sinl:
Sanjay Patel8ba631d2018-08-16 22:46:20 +00001164 case LibFunc_tan:
1165 case LibFunc_tanf:
1166 case LibFunc_tanl:
Sanjay Patele45a83d2018-08-13 19:24:41 +00001167 // sin(-X) --> -sin(X)
Sanjay Patel8ba631d2018-08-16 22:46:20 +00001168 // tan(-X) --> -tan(X)
Sanjay Patele45a83d2018-08-13 19:24:41 +00001169 if (match(Call->getArgOperand(0), m_OneUse(m_FNeg(m_Value(X)))))
Sanjay Patel8ba631d2018-08-16 22:46:20 +00001170 return B.CreateFNeg(B.CreateCall(Call->getCalledFunction(), X));
Sanjay Patele45a83d2018-08-13 19:24:41 +00001171 break;
1172 case LibFunc_cos:
1173 case LibFunc_cosf:
1174 case LibFunc_cosl:
1175 // cos(-X) --> cos(X)
1176 if (match(Call->getArgOperand(0), m_FNeg(m_Value(X))))
1177 return B.CreateCall(Call->getCalledFunction(), X, "cos");
1178 break;
1179 default:
1180 break;
1181 }
Sanjay Patelce4ddbe2018-08-13 17:40:49 +00001182 return nullptr;
Chris Bienemanad070d02014-09-17 20:55:46 +00001183}
Bob Wilsond8d92d92013-11-03 06:48:38 +00001184
Weiming Zhao82130722015-12-04 22:00:47 +00001185static Value *getPow(Value *InnerChain[33], unsigned Exp, IRBuilder<> &B) {
1186 // Multiplications calculated using Addition Chains.
1187 // Refer: http://wwwhomes.uni-bielefeld.de/achim/addition_chain.html
1188
1189 assert(Exp != 0 && "Incorrect exponent 0 not handled");
1190
1191 if (InnerChain[Exp])
1192 return InnerChain[Exp];
1193
1194 static const unsigned AddChain[33][2] = {
1195 {0, 0}, // Unused.
1196 {0, 0}, // Unused (base case = pow1).
1197 {1, 1}, // Unused (pre-computed).
1198 {1, 2}, {2, 2}, {2, 3}, {3, 3}, {2, 5}, {4, 4},
1199 {1, 8}, {5, 5}, {1, 10}, {6, 6}, {4, 9}, {7, 7},
1200 {3, 12}, {8, 8}, {8, 9}, {2, 16}, {1, 18}, {10, 10},
1201 {6, 15}, {11, 11}, {3, 20}, {12, 12}, {8, 17}, {13, 13},
1202 {3, 24}, {14, 14}, {4, 25}, {15, 15}, {3, 28}, {16, 16},
1203 };
1204
1205 InnerChain[Exp] = B.CreateFMul(getPow(InnerChain, AddChain[Exp][0], B),
1206 getPow(InnerChain, AddChain[Exp][1], B));
1207 return InnerChain[Exp];
1208}
1209
Evandro Menezes4b390102018-08-17 17:59:53 +00001210/// Use exp{,2}(x * y) for pow(exp{,2}(x), y);
Evandro Menezes2123ea72018-08-30 19:04:51 +00001211/// exp2(n * x) for pow(2.0 ** n, x); exp10(x) for pow(10.0, x).
Evandro Menezes4b390102018-08-17 17:59:53 +00001212Value *LibCallSimplifier::replacePowWithExp(CallInst *Pow, IRBuilder<> &B) {
1213 Value *Base = Pow->getArgOperand(0), *Expo = Pow->getArgOperand(1);
1214 AttributeList Attrs = Pow->getCalledFunction()->getAttributes();
1215 Module *Mod = Pow->getModule();
1216 Type *Ty = Pow->getType();
Evandro Menezes2123ea72018-08-30 19:04:51 +00001217 bool Ignored;
Evandro Menezes4b390102018-08-17 17:59:53 +00001218
1219 // Evaluate special cases related to a nested function as the base.
1220
1221 // pow(exp(x), y) -> exp(x * y)
1222 // pow(exp2(x), y) -> exp2(x * y)
Evandro Menezes253991c2018-08-27 22:11:15 +00001223 // If exp{,2}() is used only once, it is better to fold two transcendental
1224 // math functions into one. If used again, exp{,2}() would still have to be
1225 // called with the original argument, then keep both original transcendental
1226 // functions. However, this transformation is only safe with fully relaxed
1227 // math semantics, since, besides rounding differences, it changes overflow
1228 // and underflow behavior quite dramatically. For example:
Evandro Menezes4b390102018-08-17 17:59:53 +00001229 // pow(exp(1000), 0.001) = pow(inf, 0.001) = inf
1230 // Whereas:
1231 // exp(1000 * 0.001) = exp(1)
1232 // TODO: Loosen the requirement for fully relaxed math semantics.
1233 // TODO: Handle exp10() when more targets have it available.
1234 CallInst *BaseFn = dyn_cast<CallInst>(Base);
Evandro Menezes253991c2018-08-27 22:11:15 +00001235 if (BaseFn && BaseFn->hasOneUse() && BaseFn->isFast() && Pow->isFast()) {
Evandro Menezes4b390102018-08-17 17:59:53 +00001236 LibFunc LibFn;
Evandro Menezes253991c2018-08-27 22:11:15 +00001237
Evandro Menezes4b390102018-08-17 17:59:53 +00001238 Function *CalleeFn = BaseFn->getCalledFunction();
Evandro Menezes22e0bdf2018-08-29 17:59:48 +00001239 if (CalleeFn &&
1240 TLI->getLibFunc(CalleeFn->getName(), LibFn) && TLI->has(LibFn)) {
1241 StringRef ExpName;
1242 Intrinsic::ID ID;
Evandro Menezes253991c2018-08-27 22:11:15 +00001243 Value *ExpFn;
Mikael Holmene3605d02018-10-18 06:27:53 +00001244 LibFunc LibFnFloat;
1245 LibFunc LibFnDouble;
1246 LibFunc LibFnLongDouble;
Evandro Menezes253991c2018-08-27 22:11:15 +00001247
Evandro Menezes22e0bdf2018-08-29 17:59:48 +00001248 switch (LibFn) {
1249 default:
1250 return nullptr;
1251 case LibFunc_expf: case LibFunc_exp: case LibFunc_expl:
Evandro Menezes164ea102018-10-19 20:57:45 +00001252 ExpName = TLI->getName(LibFunc_exp);
Evandro Menezes22e0bdf2018-08-29 17:59:48 +00001253 ID = Intrinsic::exp;
Mikael Holmene3605d02018-10-18 06:27:53 +00001254 LibFnFloat = LibFunc_expf;
1255 LibFnDouble = LibFunc_exp;
1256 LibFnLongDouble = LibFunc_expl;
Evandro Menezes22e0bdf2018-08-29 17:59:48 +00001257 break;
1258 case LibFunc_exp2f: case LibFunc_exp2: case LibFunc_exp2l:
Evandro Menezes164ea102018-10-19 20:57:45 +00001259 ExpName = TLI->getName(LibFunc_exp2);
Evandro Menezes22e0bdf2018-08-29 17:59:48 +00001260 ID = Intrinsic::exp2;
Mikael Holmene3605d02018-10-18 06:27:53 +00001261 LibFnFloat = LibFunc_exp2f;
1262 LibFnDouble = LibFunc_exp2;
1263 LibFnLongDouble = LibFunc_exp2l;
Evandro Menezes22e0bdf2018-08-29 17:59:48 +00001264 break;
1265 }
1266
Evandro Menezes253991c2018-08-27 22:11:15 +00001267 // Create new exp{,2}() with the product as its argument.
Evandro Menezes4b390102018-08-17 17:59:53 +00001268 Value *FMul = B.CreateFMul(BaseFn->getArgOperand(0), Expo, "mul");
Evandro Menezes22e0bdf2018-08-29 17:59:48 +00001269 ExpFn = BaseFn->doesNotAccessMemory()
1270 ? B.CreateCall(Intrinsic::getDeclaration(Mod, ID, Ty),
1271 FMul, ExpName)
Mikael Holmene3605d02018-10-18 06:27:53 +00001272 : emitUnaryFloatFnCall(FMul, TLI, LibFnDouble, LibFnFloat,
1273 LibFnLongDouble, B,
1274 BaseFn->getAttributes());
Evandro Menezes253991c2018-08-27 22:11:15 +00001275
1276 // Since the new exp{,2}() is different from the original one, dead code
1277 // elimination cannot be trusted to remove it, since it may have side
1278 // effects (e.g., errno). When the only consumer for the original
1279 // exp{,2}() is pow(), then it has to be explicitly erased.
1280 BaseFn->replaceAllUsesWith(ExpFn);
Amara Emerson54f60252018-10-11 14:51:11 +00001281 eraseFromParent(BaseFn);
Evandro Menezes253991c2018-08-27 22:11:15 +00001282
1283 return ExpFn;
Evandro Menezes4b390102018-08-17 17:59:53 +00001284 }
1285 }
1286
1287 // Evaluate special cases related to a constant base.
1288
Evandro Menezes2123ea72018-08-30 19:04:51 +00001289 const APFloat *BaseF;
1290 if (!match(Pow->getArgOperand(0), m_APFloat(BaseF)))
1291 return nullptr;
1292
1293 // pow(2.0 ** n, x) -> exp2(n * x)
1294 if (hasUnaryFloatFn(TLI, Ty, LibFunc_exp2, LibFunc_exp2f, LibFunc_exp2l)) {
1295 APFloat BaseR = APFloat(1.0);
1296 BaseR.convert(BaseF->getSemantics(), APFloat::rmTowardZero, &Ignored);
1297 BaseR = BaseR / *BaseF;
1298 bool IsInteger = BaseF->isInteger(),
1299 IsReciprocal = BaseR.isInteger();
1300 const APFloat *NF = IsReciprocal ? &BaseR : BaseF;
1301 APSInt NI(64, false);
1302 if ((IsInteger || IsReciprocal) &&
1303 !NF->convertToInteger(NI, APFloat::rmTowardZero, &Ignored) &&
1304 NI > 1 && NI.isPowerOf2()) {
1305 double N = NI.logBase2() * (IsReciprocal ? -1.0 : 1.0);
1306 Value *FMul = B.CreateFMul(Expo, ConstantFP::get(Ty, N), "mul");
1307 if (Pow->doesNotAccessMemory())
1308 return B.CreateCall(Intrinsic::getDeclaration(Mod, Intrinsic::exp2, Ty),
1309 FMul, "exp2");
1310 else
Mikael Holmene3605d02018-10-18 06:27:53 +00001311 return emitUnaryFloatFnCall(FMul, TLI, LibFunc_exp2, LibFunc_exp2f,
1312 LibFunc_exp2l, B, Attrs);
Evandro Menezes2123ea72018-08-30 19:04:51 +00001313 }
Evandro Menezes4b390102018-08-17 17:59:53 +00001314 }
1315
1316 // pow(10.0, x) -> exp10(x)
1317 // TODO: There is no exp10() intrinsic yet, but some day there shall be one.
1318 if (match(Base, m_SpecificFP(10.0)) &&
1319 hasUnaryFloatFn(TLI, Ty, LibFunc_exp10, LibFunc_exp10f, LibFunc_exp10l))
Mikael Holmene3605d02018-10-18 06:27:53 +00001320 return emitUnaryFloatFnCall(Expo, TLI, LibFunc_exp10, LibFunc_exp10f,
1321 LibFunc_exp10l, B, Attrs);
Evandro Menezes4b390102018-08-17 17:59:53 +00001322
1323 return nullptr;
1324}
1325
Florian Hahncc9dc592018-09-03 17:37:39 +00001326static Value *getSqrtCall(Value *V, AttributeList Attrs, bool NoErrno,
1327 Module *M, IRBuilder<> &B,
1328 const TargetLibraryInfo *TLI) {
1329 // If errno is never set, then use the intrinsic for sqrt().
1330 if (NoErrno) {
1331 Function *SqrtFn =
1332 Intrinsic::getDeclaration(M, Intrinsic::sqrt, V->getType());
1333 return B.CreateCall(SqrtFn, V, "sqrt");
1334 }
1335
1336 // Otherwise, use the libcall for sqrt().
1337 if (hasUnaryFloatFn(TLI, V->getType(), LibFunc_sqrt, LibFunc_sqrtf,
1338 LibFunc_sqrtl))
1339 // TODO: We also should check that the target can in fact lower the sqrt()
1340 // libcall. We currently have no way to ask this question, so we ask if
1341 // the target has a sqrt() libcall, which is not exactly the same.
Mikael Holmene3605d02018-10-18 06:27:53 +00001342 return emitUnaryFloatFnCall(V, TLI, LibFunc_sqrt, LibFunc_sqrtf,
1343 LibFunc_sqrtl, B, Attrs);
Florian Hahncc9dc592018-09-03 17:37:39 +00001344
1345 return nullptr;
1346}
1347
Sanjay Patelfbd3e662017-11-19 16:13:14 +00001348/// Use square root in place of pow(x, +/-0.5).
1349Value *LibCallSimplifier::replacePowWithSqrt(CallInst *Pow, IRBuilder<> &B) {
Evandro Menezesa7d48282018-07-30 16:20:04 +00001350 Value *Sqrt, *Base = Pow->getArgOperand(0), *Expo = Pow->getArgOperand(1);
Evandro Menezesc05c7e12018-08-16 15:58:08 +00001351 AttributeList Attrs = Pow->getCalledFunction()->getAttributes();
1352 Module *Mod = Pow->getModule();
Sanjay Patelfbd3e662017-11-19 16:13:14 +00001353 Type *Ty = Pow->getType();
Sanjay Patelfbd3e662017-11-19 16:13:14 +00001354
Evandro Menezesa7d48282018-07-30 16:20:04 +00001355 const APFloat *ExpoF;
1356 if (!match(Expo, m_APFloat(ExpoF)) ||
1357 (!ExpoF->isExactlyValue(0.5) && !ExpoF->isExactlyValue(-0.5)))
1358 return nullptr;
1359
Florian Hahncc9dc592018-09-03 17:37:39 +00001360 Sqrt = getSqrtCall(Base, Attrs, Pow->doesNotAccessMemory(), Mod, B, TLI);
1361 if (!Sqrt)
Evandro Menezesa7d48282018-07-30 16:20:04 +00001362 return nullptr;
1363
Evandro Menezesc05c7e12018-08-16 15:58:08 +00001364 // Handle signed zero base by expanding to fabs(sqrt(x)).
1365 if (!Pow->hasNoSignedZeros()) {
1366 Function *FAbsFn = Intrinsic::getDeclaration(Mod, Intrinsic::fabs, Ty);
1367 Sqrt = B.CreateCall(FAbsFn, Sqrt, "abs");
1368 }
1369
1370 // Handle non finite base by expanding to
1371 // (x == -infinity ? +infinity : sqrt(x)).
1372 if (!Pow->hasNoInfs()) {
1373 Value *PosInf = ConstantFP::getInfinity(Ty),
1374 *NegInf = ConstantFP::getInfinity(Ty, true);
1375 Value *FCmp = B.CreateFCmpOEQ(Base, NegInf, "isinf");
1376 Sqrt = B.CreateSelect(FCmp, PosInf, Sqrt);
1377 }
1378
Evandro Menezes61e4e402018-07-31 22:11:02 +00001379 // If the exponent is negative, then get the reciprocal.
Evandro Menezesa7d48282018-07-30 16:20:04 +00001380 if (ExpoF->isNegative())
1381 Sqrt = B.CreateFDiv(ConstantFP::get(Ty, 1.0), Sqrt, "reciprocal");
Sanjay Patelfbd3e662017-11-19 16:13:14 +00001382
1383 return Sqrt;
1384}
1385
Evandro Menezesa7d48282018-07-30 16:20:04 +00001386Value *LibCallSimplifier::optimizePow(CallInst *Pow, IRBuilder<> &B) {
1387 Value *Base = Pow->getArgOperand(0), *Expo = Pow->getArgOperand(1);
1388 Function *Callee = Pow->getCalledFunction();
Davide Italianoa3458772015-11-05 19:18:23 +00001389 StringRef Name = Callee->getName();
Evandro Menezesa7d48282018-07-30 16:20:04 +00001390 Type *Ty = Pow->getType();
1391 Value *Shrunk = nullptr;
1392 bool Ignored;
Bob Wilsond8d92d92013-11-03 06:48:38 +00001393
Evandro Menezes5ecd6c12018-08-13 16:12:37 +00001394 // Bail out if simplifying libcalls to pow() is disabled.
1395 if (!hasUnaryFloatFn(TLI, Ty, LibFunc_pow, LibFunc_powf, LibFunc_powl))
1396 return nullptr;
1397
Evandro Menezes61e4e402018-07-31 22:11:02 +00001398 // Propagate the math semantics from the call to any created instructions.
Evandro Menezesa7d48282018-07-30 16:20:04 +00001399 IRBuilder<>::FastMathFlagGuard Guard(B);
1400 B.setFastMathFlags(Pow->getFastMathFlags());
1401
Evandro Menezes6e137cb2018-08-06 19:40:17 +00001402 // Shrink pow() to powf() if the arguments are single precision,
1403 // unless the result is expected to be double precision.
1404 if (UnsafeFPShrink &&
1405 Name == TLI->getName(LibFunc_pow) && hasFloatVersion(Name))
1406 Shrunk = optimizeBinaryDoubleFP(Pow, B, true);
1407
Evandro Menezesa7d48282018-07-30 16:20:04 +00001408 // Evaluate special cases related to the base.
Davide Italiano27da1312016-08-07 20:27:03 +00001409
1410 // pow(1.0, x) -> 1.0
Evandro Menezes84e74362018-08-02 15:43:57 +00001411 if (match(Base, m_FPOne()))
Evandro Menezesa7d48282018-07-30 16:20:04 +00001412 return Base;
1413
Evandro Menezes4b390102018-08-17 17:59:53 +00001414 if (Value *Exp = replacePowWithExp(Pow, B))
1415 return Exp;
Davide Italianoc8a79132015-11-03 20:32:23 +00001416
Evandro Menezesa7d48282018-07-30 16:20:04 +00001417 // Evaluate special cases related to the exponent.
1418
Evandro Menezesa7d48282018-07-30 16:20:04 +00001419 // pow(x, -1.0) -> 1.0 / x
Evandro Menezes5ecd6c12018-08-13 16:12:37 +00001420 if (match(Expo, m_SpecificFP(-1.0)))
Evandro Menezesa7d48282018-07-30 16:20:04 +00001421 return B.CreateFDiv(ConstantFP::get(Ty, 1.0), Base, "reciprocal");
1422
1423 // pow(x, 0.0) -> 1.0
Evandro Menezes5ecd6c12018-08-13 16:12:37 +00001424 if (match(Expo, m_SpecificFP(0.0)))
1425 return ConstantFP::get(Ty, 1.0);
Evandro Menezesa7d48282018-07-30 16:20:04 +00001426
1427 // pow(x, 1.0) -> x
Evandro Menezes5ecd6c12018-08-13 16:12:37 +00001428 if (match(Expo, m_FPOne()))
Evandro Menezesa7d48282018-07-30 16:20:04 +00001429 return Base;
1430
1431 // pow(x, 2.0) -> x * x
Evandro Menezes5ecd6c12018-08-13 16:12:37 +00001432 if (match(Expo, m_SpecificFP(2.0)))
Evandro Menezesa7d48282018-07-30 16:20:04 +00001433 return B.CreateFMul(Base, Base, "square");
Chris Bienemanad070d02014-09-17 20:55:46 +00001434
Evandro Menezes5ecd6c12018-08-13 16:12:37 +00001435 if (Value *Sqrt = replacePowWithSqrt(Pow, B))
1436 return Sqrt;
1437
Evandro Menezes5ecd6c12018-08-13 16:12:37 +00001438 // pow(x, n) -> x * x * x * ...
1439 const APFloat *ExpoF;
1440 if (Pow->isFast() && match(Expo, m_APFloat(ExpoF))) {
1441 // We limit to a max of 7 multiplications, thus the maximum exponent is 32.
Florian Hahncc9dc592018-09-03 17:37:39 +00001442 // If the exponent is an integer+0.5 we generate a call to sqrt and an
1443 // additional fmul.
1444 // TODO: This whole transformation should be backend specific (e.g. some
1445 // backends might prefer libcalls or the limit for the exponent might
1446 // be different) and it should also consider optimizing for size.
Evandro Menezes5ecd6c12018-08-13 16:12:37 +00001447 APFloat LimF(ExpoF->getSemantics(), 33.0),
1448 ExpoA(abs(*ExpoF));
Florian Hahncc9dc592018-09-03 17:37:39 +00001449 if (ExpoA.compare(LimF) == APFloat::cmpLessThan) {
1450 // This transformation applies to integer or integer+0.5 exponents only.
1451 // For integer+0.5, we create a sqrt(Base) call.
1452 Value *Sqrt = nullptr;
1453 if (!ExpoA.isInteger()) {
1454 APFloat Expo2 = ExpoA;
1455 // To check if ExpoA is an integer + 0.5, we add it to itself. If there
1456 // is no floating point exception and the result is an integer, then
1457 // ExpoA == integer + 0.5
1458 if (Expo2.add(ExpoA, APFloat::rmNearestTiesToEven) != APFloat::opOK)
1459 return nullptr;
1460
1461 if (!Expo2.isInteger())
1462 return nullptr;
1463
1464 Sqrt =
1465 getSqrtCall(Base, Pow->getCalledFunction()->getAttributes(),
1466 Pow->doesNotAccessMemory(), Pow->getModule(), B, TLI);
1467 }
1468
Evandro Menezes5ecd6c12018-08-13 16:12:37 +00001469 // We will memoize intermediate products of the Addition Chain.
1470 Value *InnerChain[33] = {nullptr};
1471 InnerChain[1] = Base;
1472 InnerChain[2] = B.CreateFMul(Base, Base, "square");
Weiming Zhao82130722015-12-04 22:00:47 +00001473
Evandro Menezes5ecd6c12018-08-13 16:12:37 +00001474 // We cannot readily convert a non-double type (like float) to a double.
1475 // So we first convert it to something which could be converted to double.
1476 ExpoA.convert(APFloat::IEEEdouble(), APFloat::rmTowardZero, &Ignored);
1477 Value *FMul = getPow(InnerChain, ExpoA.convertToDouble(), B);
Weiming Zhao82130722015-12-04 22:00:47 +00001478
Florian Hahncc9dc592018-09-03 17:37:39 +00001479 // Expand pow(x, y+0.5) to pow(x, y) * sqrt(x).
1480 if (Sqrt)
1481 FMul = B.CreateFMul(FMul, Sqrt);
1482
Evandro Menezes5ecd6c12018-08-13 16:12:37 +00001483 // If the exponent is negative, then get the reciprocal.
1484 if (ExpoF->isNegative())
1485 FMul = B.CreateFDiv(ConstantFP::get(Ty, 1.0), FMul, "reciprocal");
Evandro Menezes61e4e402018-07-31 22:11:02 +00001486
Evandro Menezes5ecd6c12018-08-13 16:12:37 +00001487 return FMul;
1488 }
Weiming Zhao82130722015-12-04 22:00:47 +00001489 }
1490
Evandro Menezes6e137cb2018-08-06 19:40:17 +00001491 return Shrunk;
Chris Bienemanad070d02014-09-17 20:55:46 +00001492}
Bob Wilsond8d92d92013-11-03 06:48:38 +00001493
Chris Bienemanad070d02014-09-17 20:55:46 +00001494Value *LibCallSimplifier::optimizeExp2(CallInst *CI, IRBuilder<> &B) {
1495 Function *Callee = CI->getCalledFunction();
Chris Bienemanad070d02014-09-17 20:55:46 +00001496 Value *Ret = nullptr;
Davide Italianoa3458772015-11-05 19:18:23 +00001497 StringRef Name = Callee->getName();
1498 if (UnsafeFPShrink && Name == "exp2" && hasFloatVersion(Name))
Chris Bienemanad070d02014-09-17 20:55:46 +00001499 Ret = optimizeUnaryDoubleFP(CI, B, true);
Bob Wilsond8d92d92013-11-03 06:48:38 +00001500
Chris Bienemanad070d02014-09-17 20:55:46 +00001501 Value *Op = CI->getArgOperand(0);
1502 // Turn exp2(sitofp(x)) -> ldexp(1.0, sext(x)) if sizeof(x) <= 32
1503 // Turn exp2(uitofp(x)) -> ldexp(1.0, zext(x)) if sizeof(x) < 32
David L. Jonesd21529f2017-01-23 23:16:46 +00001504 LibFunc LdExp = LibFunc_ldexpl;
Chris Bienemanad070d02014-09-17 20:55:46 +00001505 if (Op->getType()->isFloatTy())
David L. Jonesd21529f2017-01-23 23:16:46 +00001506 LdExp = LibFunc_ldexpf;
Chris Bienemanad070d02014-09-17 20:55:46 +00001507 else if (Op->getType()->isDoubleTy())
David L. Jonesd21529f2017-01-23 23:16:46 +00001508 LdExp = LibFunc_ldexp;
Chris Bienemanad070d02014-09-17 20:55:46 +00001509
1510 if (TLI->has(LdExp)) {
1511 Value *LdExpArg = nullptr;
1512 if (SIToFPInst *OpC = dyn_cast<SIToFPInst>(Op)) {
1513 if (OpC->getOperand(0)->getType()->getPrimitiveSizeInBits() <= 32)
1514 LdExpArg = B.CreateSExt(OpC->getOperand(0), B.getInt32Ty());
1515 } else if (UIToFPInst *OpC = dyn_cast<UIToFPInst>(Op)) {
1516 if (OpC->getOperand(0)->getType()->getPrimitiveSizeInBits() < 32)
1517 LdExpArg = B.CreateZExt(OpC->getOperand(0), B.getInt32Ty());
1518 }
1519
1520 if (LdExpArg) {
1521 Constant *One = ConstantFP::get(CI->getContext(), APFloat(1.0f));
1522 if (!Op->getType()->isFloatTy())
1523 One = ConstantExpr::getFPExtend(One, Op->getType());
1524
Sanjay Patel0e603fc2016-01-21 22:31:18 +00001525 Module *M = CI->getModule();
James Y Knight13680222019-02-01 02:28:03 +00001526 FunctionCallee NewCallee = M->getOrInsertFunction(
1527 TLI->getName(LdExp), Op->getType(), Op->getType(), B.getInt32Ty());
Sanjay Patel042aed902016-01-21 22:41:16 +00001528 CallInst *CI = B.CreateCall(NewCallee, {One, LdExpArg});
Chris Bienemanad070d02014-09-17 20:55:46 +00001529 if (const Function *F = dyn_cast<Function>(Callee->stripPointerCasts()))
1530 CI->setCallingConv(F->getCallingConv());
1531
1532 return CI;
1533 }
1534 }
1535 return Ret;
1536}
1537
Sanjay Patel57fd1dc2015-08-16 20:18:19 +00001538Value *LibCallSimplifier::optimizeFMinFMax(CallInst *CI, IRBuilder<> &B) {
Sanjay Patel9beec212016-01-21 22:58:01 +00001539 Function *Callee = CI->getCalledFunction();
Sanjay Patel57fd1dc2015-08-16 20:18:19 +00001540 // If we can shrink the call to a float function rather than a double
1541 // function, do that first.
Davide Italianoa3458772015-11-05 19:18:23 +00001542 StringRef Name = Callee->getName();
Sanjay Patelc7ddb7f2016-01-06 00:32:15 +00001543 if ((Name == "fmin" || Name == "fmax") && hasFloatVersion(Name))
1544 if (Value *Ret = optimizeBinaryDoubleFP(CI, B))
Sanjay Patel57fd1dc2015-08-16 20:18:19 +00001545 return Ret;
Sanjay Patel57fd1dc2015-08-16 20:18:19 +00001546
Benjamin Kramerbb70d752015-08-16 21:16:37 +00001547 IRBuilder<>::FastMathFlagGuard Guard(B);
Sanjay Patel57fd1dc2015-08-16 20:18:19 +00001548 FastMathFlags FMF;
Sanjay Patel629c4112017-11-06 16:27:15 +00001549 if (CI->isFast()) {
1550 // If the call is 'fast', then anything we create here will also be 'fast'.
1551 FMF.setFast();
Sanjay Patel57fd1dc2015-08-16 20:18:19 +00001552 } else {
1553 // At a minimum, no-nans-fp-math must be true.
Sanjay Patel29095ea2016-01-05 20:46:19 +00001554 if (!CI->hasNoNaNs())
Sanjay Patel57fd1dc2015-08-16 20:18:19 +00001555 return nullptr;
1556 // No-signed-zeros is implied by the definitions of fmax/fmin themselves:
1557 // "Ideally, fmax would be sensitive to the sign of zero, for example
NAKAMURA Takumi0d725392015-09-07 00:26:54 +00001558 // fmax(-0. 0, +0. 0) would return +0; however, implementation in software
Sanjay Patel57fd1dc2015-08-16 20:18:19 +00001559 // might be impractical."
1560 FMF.setNoSignedZeros();
1561 FMF.setNoNaNs();
1562 }
Sanjay Patela2528152016-01-12 18:03:37 +00001563 B.setFastMathFlags(FMF);
Sanjay Patel57fd1dc2015-08-16 20:18:19 +00001564
1565 // We have a relaxed floating-point environment. We can ignore NaN-handling
1566 // and transform to a compare and select. We do not have to consider errno or
1567 // exceptions, because fmin/fmax do not have those.
1568 Value *Op0 = CI->getArgOperand(0);
1569 Value *Op1 = CI->getArgOperand(1);
1570 Value *Cmp = Callee->getName().startswith("fmin") ?
1571 B.CreateFCmpOLT(Op0, Op1) : B.CreateFCmpOGT(Op0, Op1);
1572 return B.CreateSelect(Cmp, Op0, Op1);
1573}
1574
Davide Italianob8b71332015-11-29 20:58:04 +00001575Value *LibCallSimplifier::optimizeLog(CallInst *CI, IRBuilder<> &B) {
1576 Function *Callee = CI->getCalledFunction();
1577 Value *Ret = nullptr;
1578 StringRef Name = Callee->getName();
1579 if (UnsafeFPShrink && hasFloatVersion(Name))
1580 Ret = optimizeUnaryDoubleFP(CI, B, true);
Davide Italianob8b71332015-11-29 20:58:04 +00001581
Sanjay Patel629c4112017-11-06 16:27:15 +00001582 if (!CI->isFast())
Davide Italianob8b71332015-11-29 20:58:04 +00001583 return Ret;
1584 Value *Op1 = CI->getArgOperand(0);
1585 auto *OpC = dyn_cast<CallInst>(Op1);
Sanjay Patele896ede2016-01-11 23:31:48 +00001586
Sanjay Patel629c4112017-11-06 16:27:15 +00001587 // The earlier call must also be 'fast' in order to do these transforms.
1588 if (!OpC || !OpC->isFast())
Davide Italianob8b71332015-11-29 20:58:04 +00001589 return Ret;
1590
1591 // log(pow(x,y)) -> y*log(x)
1592 // This is only applicable to log, log2, log10.
1593 if (Name != "log" && Name != "log2" && Name != "log10")
1594 return Ret;
1595
1596 IRBuilder<>::FastMathFlagGuard Guard(B);
1597 FastMathFlags FMF;
Sanjay Patel629c4112017-11-06 16:27:15 +00001598 FMF.setFast();
Sanjay Patela2528152016-01-12 18:03:37 +00001599 B.setFastMathFlags(FMF);
Davide Italianob8b71332015-11-29 20:58:04 +00001600
David L. Jonesd21529f2017-01-23 23:16:46 +00001601 LibFunc Func;
Davide Italianob8b71332015-11-29 20:58:04 +00001602 Function *F = OpC->getCalledFunction();
Davide Italiano0b14f292015-11-29 21:58:56 +00001603 if (F && ((TLI->getLibFunc(F->getName(), Func) && TLI->has(Func) &&
David L. Jonesd21529f2017-01-23 23:16:46 +00001604 Func == LibFunc_pow) || F->getIntrinsicID() == Intrinsic::pow))
Davide Italianob8b71332015-11-29 20:58:04 +00001605 return B.CreateFMul(OpC->getArgOperand(1),
Sanjay Pateld3112a52016-01-19 19:46:10 +00001606 emitUnaryFloatFnCall(OpC->getOperand(0), Callee->getName(), B,
Davide Italianob8b71332015-11-29 20:58:04 +00001607 Callee->getAttributes()), "mul");
Davide Italiano1aeed6a2015-11-30 19:36:35 +00001608
1609 // log(exp2(y)) -> y*log(2)
1610 if (F && Name == "log" && TLI->getLibFunc(F->getName(), Func) &&
David L. Jonesd21529f2017-01-23 23:16:46 +00001611 TLI->has(Func) && Func == LibFunc_exp2)
Davide Italiano1aeed6a2015-11-30 19:36:35 +00001612 return B.CreateFMul(
1613 OpC->getArgOperand(0),
Sanjay Pateld3112a52016-01-19 19:46:10 +00001614 emitUnaryFloatFnCall(ConstantFP::get(CI->getType(), 2.0),
Davide Italiano1aeed6a2015-11-30 19:36:35 +00001615 Callee->getName(), B, Callee->getAttributes()),
1616 "logmul");
Davide Italianob8b71332015-11-29 20:58:04 +00001617 return Ret;
1618}
1619
Sanjay Patelc699a612014-10-16 18:48:17 +00001620Value *LibCallSimplifier::optimizeSqrt(CallInst *CI, IRBuilder<> &B) {
1621 Function *Callee = CI->getCalledFunction();
Sanjay Patelc699a612014-10-16 18:48:17 +00001622 Value *Ret = nullptr;
Justin Lebarcb9b41d2017-01-27 00:58:03 +00001623 // TODO: Once we have a way (other than checking for the existince of the
1624 // libcall) to tell whether our target can lower @llvm.sqrt, relax the
1625 // condition below.
David L. Jonesd21529f2017-01-23 23:16:46 +00001626 if (TLI->has(LibFunc_sqrtf) && (Callee->getName() == "sqrt" ||
Justin Lebarcb9b41d2017-01-27 00:58:03 +00001627 Callee->getIntrinsicID() == Intrinsic::sqrt))
Sanjay Patelc699a612014-10-16 18:48:17 +00001628 Ret = optimizeUnaryDoubleFP(CI, B, true);
Sanjay Patel683f2972016-01-11 22:34:19 +00001629
Sanjay Patel629c4112017-11-06 16:27:15 +00001630 if (!CI->isFast())
Davide Italianoa904e522015-10-29 02:58:44 +00001631 return Ret;
Sanjay Patelc699a612014-10-16 18:48:17 +00001632
Sanjay Patelc2d64612016-01-06 20:52:21 +00001633 Instruction *I = dyn_cast<Instruction>(CI->getArgOperand(0));
Sanjay Patel629c4112017-11-06 16:27:15 +00001634 if (!I || I->getOpcode() != Instruction::FMul || !I->isFast())
Sanjay Patelc2d64612016-01-06 20:52:21 +00001635 return Ret;
1636
1637 // We're looking for a repeated factor in a multiplication tree,
1638 // so we can do this fold: sqrt(x * x) -> fabs(x);
Sanjay Patel683f2972016-01-11 22:34:19 +00001639 // or this fold: sqrt((x * x) * y) -> fabs(x) * sqrt(y).
Sanjay Patelc2d64612016-01-06 20:52:21 +00001640 Value *Op0 = I->getOperand(0);
1641 Value *Op1 = I->getOperand(1);
1642 Value *RepeatOp = nullptr;
1643 Value *OtherOp = nullptr;
1644 if (Op0 == Op1) {
1645 // Simple match: the operands of the multiply are identical.
1646 RepeatOp = Op0;
1647 } else {
1648 // Look for a more complicated pattern: one of the operands is itself
1649 // a multiply, so search for a common factor in that multiply.
1650 // Note: We don't bother looking any deeper than this first level or for
1651 // variations of this pattern because instcombine's visitFMUL and/or the
1652 // reassociation pass should give us this form.
1653 Value *OtherMul0, *OtherMul1;
1654 if (match(Op0, m_FMul(m_Value(OtherMul0), m_Value(OtherMul1)))) {
1655 // Pattern: sqrt((x * y) * z)
Sanjay Patel629c4112017-11-06 16:27:15 +00001656 if (OtherMul0 == OtherMul1 && cast<Instruction>(Op0)->isFast()) {
Sanjay Patelc2d64612016-01-06 20:52:21 +00001657 // Matched: sqrt((x * x) * z)
1658 RepeatOp = OtherMul0;
1659 OtherOp = Op1;
Sanjay Patelc699a612014-10-16 18:48:17 +00001660 }
1661 }
1662 }
Sanjay Patelc2d64612016-01-06 20:52:21 +00001663 if (!RepeatOp)
1664 return Ret;
1665
1666 // Fast math flags for any created instructions should match the sqrt
1667 // and multiply.
Sanjay Patelc2d64612016-01-06 20:52:21 +00001668 IRBuilder<>::FastMathFlagGuard Guard(B);
Sanjay Patela2528152016-01-12 18:03:37 +00001669 B.setFastMathFlags(I->getFastMathFlags());
Sanjay Patel9f67dad2016-01-11 22:35:39 +00001670
Sanjay Patelc2d64612016-01-06 20:52:21 +00001671 // If we found a repeated factor, hoist it out of the square root and
1672 // replace it with the fabs of that factor.
1673 Module *M = Callee->getParent();
1674 Type *ArgType = I->getType();
James Y Knight7976eb52019-02-01 20:43:25 +00001675 Function *Fabs = Intrinsic::getDeclaration(M, Intrinsic::fabs, ArgType);
Sanjay Patelc2d64612016-01-06 20:52:21 +00001676 Value *FabsCall = B.CreateCall(Fabs, RepeatOp, "fabs");
1677 if (OtherOp) {
1678 // If we found a non-repeated factor, we still need to get its square
1679 // root. We then multiply that by the value that was simplified out
1680 // of the square root calculation.
James Y Knight7976eb52019-02-01 20:43:25 +00001681 Function *Sqrt = Intrinsic::getDeclaration(M, Intrinsic::sqrt, ArgType);
Sanjay Patelc2d64612016-01-06 20:52:21 +00001682 Value *SqrtCall = B.CreateCall(Sqrt, OtherOp, "sqrt");
1683 return B.CreateFMul(FabsCall, SqrtCall);
1684 }
1685 return FabsCall;
Sanjay Patelc699a612014-10-16 18:48:17 +00001686}
1687
Sanjay Patelcddcd722016-01-06 19:23:35 +00001688// TODO: Generalize to handle any trig function and its inverse.
Davide Italiano51507d22015-11-04 23:36:56 +00001689Value *LibCallSimplifier::optimizeTan(CallInst *CI, IRBuilder<> &B) {
1690 Function *Callee = CI->getCalledFunction();
1691 Value *Ret = nullptr;
Davide Italianoa3458772015-11-05 19:18:23 +00001692 StringRef Name = Callee->getName();
1693 if (UnsafeFPShrink && Name == "tan" && hasFloatVersion(Name))
Davide Italiano51507d22015-11-04 23:36:56 +00001694 Ret = optimizeUnaryDoubleFP(CI, B, true);
Davide Italiano51507d22015-11-04 23:36:56 +00001695
Davide Italiano51507d22015-11-04 23:36:56 +00001696 Value *Op1 = CI->getArgOperand(0);
1697 auto *OpC = dyn_cast<CallInst>(Op1);
1698 if (!OpC)
1699 return Ret;
1700
Sanjay Patel629c4112017-11-06 16:27:15 +00001701 // Both calls must be 'fast' in order to remove them.
1702 if (!CI->isFast() || !OpC->isFast())
Sanjay Patelcddcd722016-01-06 19:23:35 +00001703 return Ret;
1704
Davide Italiano51507d22015-11-04 23:36:56 +00001705 // tan(atan(x)) -> x
1706 // tanf(atanf(x)) -> x
1707 // tanl(atanl(x)) -> x
David L. Jonesd21529f2017-01-23 23:16:46 +00001708 LibFunc Func;
Davide Italiano51507d22015-11-04 23:36:56 +00001709 Function *F = OpC->getCalledFunction();
Benjamin Kramerfb419e72015-11-26 09:51:17 +00001710 if (F && TLI->getLibFunc(F->getName(), Func) && TLI->has(Func) &&
David L. Jonesd21529f2017-01-23 23:16:46 +00001711 ((Func == LibFunc_atan && Callee->getName() == "tan") ||
1712 (Func == LibFunc_atanf && Callee->getName() == "tanf") ||
1713 (Func == LibFunc_atanl && Callee->getName() == "tanl")))
Davide Italiano51507d22015-11-04 23:36:56 +00001714 Ret = OpC->getArgOperand(0);
1715 return Ret;
1716}
1717
Sanjay Patel57747212016-01-21 23:38:43 +00001718static bool isTrigLibCall(CallInst *CI) {
Sanjay Patel57747212016-01-21 23:38:43 +00001719 // We can only hope to do anything useful if we can ignore things like errno
1720 // and floating-point exceptions.
Ahmed Bougachad765a822016-04-27 19:04:35 +00001721 // We already checked the prototype.
1722 return CI->hasFnAttr(Attribute::NoUnwind) &&
1723 CI->hasFnAttr(Attribute::ReadNone);
Sanjay Patel57747212016-01-21 23:38:43 +00001724}
1725
Chris Bienemanad070d02014-09-17 20:55:46 +00001726static void insertSinCosCall(IRBuilder<> &B, Function *OrigCallee, Value *Arg,
1727 bool UseFloat, Value *&Sin, Value *&Cos,
Sanjay Patel57747212016-01-21 23:38:43 +00001728 Value *&SinCos) {
1729 Type *ArgTy = Arg->getType();
1730 Type *ResTy;
1731 StringRef Name;
1732
1733 Triple T(OrigCallee->getParent()->getTargetTriple());
1734 if (UseFloat) {
1735 Name = "__sincospif_stret";
1736
1737 assert(T.getArch() != Triple::x86 && "x86 messy and unsupported for now");
1738 // x86_64 can't use {float, float} since that would be returned in both
1739 // xmm0 and xmm1, which isn't what a real struct would do.
1740 ResTy = T.getArch() == Triple::x86_64
Serge Gueltone38003f2017-05-09 19:31:13 +00001741 ? static_cast<Type *>(VectorType::get(ArgTy, 2))
1742 : static_cast<Type *>(StructType::get(ArgTy, ArgTy));
Sanjay Patel57747212016-01-21 23:38:43 +00001743 } else {
1744 Name = "__sincospi_stret";
Serge Gueltone38003f2017-05-09 19:31:13 +00001745 ResTy = StructType::get(ArgTy, ArgTy);
Sanjay Patel57747212016-01-21 23:38:43 +00001746 }
1747
1748 Module *M = OrigCallee->getParent();
James Y Knight13680222019-02-01 02:28:03 +00001749 FunctionCallee Callee =
1750 M->getOrInsertFunction(Name, OrigCallee->getAttributes(), ResTy, ArgTy);
Sanjay Patel57747212016-01-21 23:38:43 +00001751
1752 if (Instruction *ArgInst = dyn_cast<Instruction>(Arg)) {
1753 // If the argument is an instruction, it must dominate all uses so put our
1754 // sincos call there.
1755 B.SetInsertPoint(ArgInst->getParent(), ++ArgInst->getIterator());
1756 } else {
1757 // Otherwise (e.g. for a constant) the beginning of the function is as
1758 // good a place as any.
1759 BasicBlock &EntryBB = B.GetInsertBlock()->getParent()->getEntryBlock();
1760 B.SetInsertPoint(&EntryBB, EntryBB.begin());
1761 }
1762
1763 SinCos = B.CreateCall(Callee, Arg, "sincospi");
1764
1765 if (SinCos->getType()->isStructTy()) {
1766 Sin = B.CreateExtractValue(SinCos, 0, "sinpi");
1767 Cos = B.CreateExtractValue(SinCos, 1, "cospi");
1768 } else {
1769 Sin = B.CreateExtractElement(SinCos, ConstantInt::get(B.getInt32Ty(), 0),
1770 "sinpi");
1771 Cos = B.CreateExtractElement(SinCos, ConstantInt::get(B.getInt32Ty(), 1),
1772 "cospi");
1773 }
1774}
Chris Bienemanad070d02014-09-17 20:55:46 +00001775
1776Value *LibCallSimplifier::optimizeSinCosPi(CallInst *CI, IRBuilder<> &B) {
Chris Bienemanad070d02014-09-17 20:55:46 +00001777 // Make sure the prototype is as expected, otherwise the rest of the
1778 // function is probably invalid and likely to abort.
1779 if (!isTrigLibCall(CI))
1780 return nullptr;
1781
1782 Value *Arg = CI->getArgOperand(0);
1783 SmallVector<CallInst *, 1> SinCalls;
1784 SmallVector<CallInst *, 1> CosCalls;
1785 SmallVector<CallInst *, 1> SinCosCalls;
1786
1787 bool IsFloat = Arg->getType()->isFloatTy();
1788
1789 // Look for all compatible sinpi, cospi and sincospi calls with the same
1790 // argument. If there are enough (in some sense) we can make the
1791 // substitution.
David Majnemerabae6b52016-03-19 04:53:02 +00001792 Function *F = CI->getFunction();
Chris Bienemanad070d02014-09-17 20:55:46 +00001793 for (User *U : Arg->users())
David Majnemerabae6b52016-03-19 04:53:02 +00001794 classifyArgUse(U, F, IsFloat, SinCalls, CosCalls, SinCosCalls);
Chris Bienemanad070d02014-09-17 20:55:46 +00001795
1796 // It's only worthwhile if both sinpi and cospi are actually used.
1797 if (SinCosCalls.empty() && (SinCalls.empty() || CosCalls.empty()))
1798 return nullptr;
1799
1800 Value *Sin, *Cos, *SinCos;
1801 insertSinCosCall(B, CI->getCalledFunction(), Arg, IsFloat, Sin, Cos, SinCos);
1802
Davide Italianof024a562016-12-16 02:28:38 +00001803 auto replaceTrigInsts = [this](SmallVectorImpl<CallInst *> &Calls,
1804 Value *Res) {
1805 for (CallInst *C : Calls)
1806 replaceAllUsesWith(C, Res);
1807 };
1808
Chris Bienemanad070d02014-09-17 20:55:46 +00001809 replaceTrigInsts(SinCalls, Sin);
1810 replaceTrigInsts(CosCalls, Cos);
1811 replaceTrigInsts(SinCosCalls, SinCos);
1812
1813 return nullptr;
1814}
1815
David Majnemerabae6b52016-03-19 04:53:02 +00001816void LibCallSimplifier::classifyArgUse(
1817 Value *Val, Function *F, bool IsFloat,
1818 SmallVectorImpl<CallInst *> &SinCalls,
1819 SmallVectorImpl<CallInst *> &CosCalls,
1820 SmallVectorImpl<CallInst *> &SinCosCalls) {
Chris Bienemanad070d02014-09-17 20:55:46 +00001821 CallInst *CI = dyn_cast<CallInst>(Val);
1822
1823 if (!CI)
1824 return;
1825
David Majnemerabae6b52016-03-19 04:53:02 +00001826 // Don't consider calls in other functions.
1827 if (CI->getFunction() != F)
1828 return;
1829
Chris Bienemanad070d02014-09-17 20:55:46 +00001830 Function *Callee = CI->getCalledFunction();
David L. Jonesd21529f2017-01-23 23:16:46 +00001831 LibFunc Func;
Ahmed Bougachad765a822016-04-27 19:04:35 +00001832 if (!Callee || !TLI->getLibFunc(*Callee, Func) || !TLI->has(Func) ||
Benjamin Kramer89766e52015-11-28 21:43:12 +00001833 !isTrigLibCall(CI))
Chris Bienemanad070d02014-09-17 20:55:46 +00001834 return;
1835
1836 if (IsFloat) {
David L. Jonesd21529f2017-01-23 23:16:46 +00001837 if (Func == LibFunc_sinpif)
Chris Bienemanad070d02014-09-17 20:55:46 +00001838 SinCalls.push_back(CI);
David L. Jonesd21529f2017-01-23 23:16:46 +00001839 else if (Func == LibFunc_cospif)
Chris Bienemanad070d02014-09-17 20:55:46 +00001840 CosCalls.push_back(CI);
David L. Jonesd21529f2017-01-23 23:16:46 +00001841 else if (Func == LibFunc_sincospif_stret)
Chris Bienemanad070d02014-09-17 20:55:46 +00001842 SinCosCalls.push_back(CI);
1843 } else {
David L. Jonesd21529f2017-01-23 23:16:46 +00001844 if (Func == LibFunc_sinpi)
Chris Bienemanad070d02014-09-17 20:55:46 +00001845 SinCalls.push_back(CI);
David L. Jonesd21529f2017-01-23 23:16:46 +00001846 else if (Func == LibFunc_cospi)
Chris Bienemanad070d02014-09-17 20:55:46 +00001847 CosCalls.push_back(CI);
David L. Jonesd21529f2017-01-23 23:16:46 +00001848 else if (Func == LibFunc_sincospi_stret)
Chris Bienemanad070d02014-09-17 20:55:46 +00001849 SinCosCalls.push_back(CI);
1850 }
1851}
1852
Meador Inge7415f842012-11-25 20:45:27 +00001853//===----------------------------------------------------------------------===//
1854// Integer Library Call Optimizations
1855//===----------------------------------------------------------------------===//
1856
Chris Bienemanad070d02014-09-17 20:55:46 +00001857Value *LibCallSimplifier::optimizeFFS(CallInst *CI, IRBuilder<> &B) {
Chris Bienemanad070d02014-09-17 20:55:46 +00001858 // ffs(x) -> x != 0 ? (i32)llvm.cttz(x)+1 : 0
Davide Italiano890e8502016-12-15 23:11:00 +00001859 Value *Op = CI->getArgOperand(0);
Chris Bienemanad070d02014-09-17 20:55:46 +00001860 Type *ArgType = Op->getType();
James Y Knight7976eb52019-02-01 20:43:25 +00001861 Function *F = Intrinsic::getDeclaration(CI->getCalledFunction()->getParent(),
1862 Intrinsic::cttz, ArgType);
Davide Italianoa1953862015-08-13 20:34:26 +00001863 Value *V = B.CreateCall(F, {Op, B.getTrue()}, "cttz");
Chris Bienemanad070d02014-09-17 20:55:46 +00001864 V = B.CreateAdd(V, ConstantInt::get(V->getType(), 1));
1865 V = B.CreateIntCast(V, B.getInt32Ty(), false);
Meador Ingea0b6d872012-11-26 00:24:07 +00001866
Chris Bienemanad070d02014-09-17 20:55:46 +00001867 Value *Cond = B.CreateICmpNE(Op, Constant::getNullValue(ArgType));
1868 return B.CreateSelect(Cond, V, B.getInt32(0));
1869}
Meador Ingea0b6d872012-11-26 00:24:07 +00001870
Davide Italiano85ad36b2016-12-15 23:45:11 +00001871Value *LibCallSimplifier::optimizeFls(CallInst *CI, IRBuilder<> &B) {
1872 // fls(x) -> (i32)(sizeInBits(x) - llvm.ctlz(x, false))
1873 Value *Op = CI->getArgOperand(0);
1874 Type *ArgType = Op->getType();
James Y Knight7976eb52019-02-01 20:43:25 +00001875 Function *F = Intrinsic::getDeclaration(CI->getCalledFunction()->getParent(),
1876 Intrinsic::ctlz, ArgType);
Davide Italiano85ad36b2016-12-15 23:45:11 +00001877 Value *V = B.CreateCall(F, {Op, B.getFalse()}, "ctlz");
1878 V = B.CreateSub(ConstantInt::get(V->getType(), ArgType->getIntegerBitWidth()),
1879 V);
1880 return B.CreateIntCast(V, CI->getType(), false);
1881}
1882
Chris Bienemanad070d02014-09-17 20:55:46 +00001883Value *LibCallSimplifier::optimizeAbs(CallInst *CI, IRBuilder<> &B) {
Sanjay Patel4b969352018-05-22 23:29:40 +00001884 // abs(x) -> x <s 0 ? -x : x
1885 // The negation has 'nsw' because abs of INT_MIN is undefined.
1886 Value *X = CI->getArgOperand(0);
1887 Value *IsNeg = B.CreateICmpSLT(X, Constant::getNullValue(X->getType()));
1888 Value *NegX = B.CreateNSWNeg(X, "neg");
1889 return B.CreateSelect(IsNeg, NegX, X);
Chris Bienemanad070d02014-09-17 20:55:46 +00001890}
Meador Inge9a59ab62012-11-26 02:31:59 +00001891
Chris Bienemanad070d02014-09-17 20:55:46 +00001892Value *LibCallSimplifier::optimizeIsDigit(CallInst *CI, IRBuilder<> &B) {
Chris Bienemanad070d02014-09-17 20:55:46 +00001893 // isdigit(c) -> (c-'0') <u 10
1894 Value *Op = CI->getArgOperand(0);
1895 Op = B.CreateSub(Op, B.getInt32('0'), "isdigittmp");
1896 Op = B.CreateICmpULT(Op, B.getInt32(10), "isdigit");
1897 return B.CreateZExt(Op, CI->getType());
1898}
Meador Ingea62a39e2012-11-26 03:10:07 +00001899
Chris Bienemanad070d02014-09-17 20:55:46 +00001900Value *LibCallSimplifier::optimizeIsAscii(CallInst *CI, IRBuilder<> &B) {
Chris Bienemanad070d02014-09-17 20:55:46 +00001901 // isascii(c) -> c <u 128
1902 Value *Op = CI->getArgOperand(0);
1903 Op = B.CreateICmpULT(Op, B.getInt32(128), "isascii");
1904 return B.CreateZExt(Op, CI->getType());
1905}
1906
1907Value *LibCallSimplifier::optimizeToAscii(CallInst *CI, IRBuilder<> &B) {
Chris Bienemanad070d02014-09-17 20:55:46 +00001908 // toascii(c) -> c & 0x7f
1909 return B.CreateAnd(CI->getArgOperand(0),
1910 ConstantInt::get(CI->getType(), 0x7F));
1911}
Meador Inge604937d2012-11-26 03:38:52 +00001912
David Bolvanskycb8ca5f32018-04-25 18:58:53 +00001913Value *LibCallSimplifier::optimizeAtoi(CallInst *CI, IRBuilder<> &B) {
1914 StringRef Str;
1915 if (!getConstantStringInfo(CI->getArgOperand(0), Str))
1916 return nullptr;
1917
1918 return convertStrToNumber(CI, Str, 10);
1919}
1920
1921Value *LibCallSimplifier::optimizeStrtol(CallInst *CI, IRBuilder<> &B) {
1922 StringRef Str;
1923 if (!getConstantStringInfo(CI->getArgOperand(0), Str))
1924 return nullptr;
1925
1926 if (!isa<ConstantPointerNull>(CI->getArgOperand(1)))
1927 return nullptr;
1928
1929 if (ConstantInt *CInt = dyn_cast<ConstantInt>(CI->getArgOperand(2))) {
1930 return convertStrToNumber(CI, Str, CInt->getSExtValue());
1931 }
1932
1933 return nullptr;
1934}
1935
Meador Inge08ca1152012-11-26 20:37:20 +00001936//===----------------------------------------------------------------------===//
1937// Formatting and IO Library Call Optimizations
1938//===----------------------------------------------------------------------===//
1939
Chris Bienemanad070d02014-09-17 20:55:46 +00001940static bool isReportingError(Function *Callee, CallInst *CI, int StreamArg);
Hal Finkel66cd3f12013-11-17 02:06:35 +00001941
Chris Bienemanad070d02014-09-17 20:55:46 +00001942Value *LibCallSimplifier::optimizeErrorReporting(CallInst *CI, IRBuilder<> &B,
1943 int StreamArg) {
Ahmed Bougachad765a822016-04-27 19:04:35 +00001944 Function *Callee = CI->getCalledFunction();
Chris Bienemanad070d02014-09-17 20:55:46 +00001945 // Error reporting calls should be cold, mark them as such.
1946 // This applies even to non-builtin calls: it is only a hint and applies to
1947 // functions that the frontend might not understand as builtins.
Hal Finkel66cd3f12013-11-17 02:06:35 +00001948
Chris Bienemanad070d02014-09-17 20:55:46 +00001949 // This heuristic was suggested in:
1950 // Improving Static Branch Prediction in a Compiler
1951 // Brian L. Deitrich, Ben-Chung Cheng, Wen-mei W. Hwu
1952 // Proceedings of PACT'98, Oct. 1998, IEEE
Chris Bienemanad070d02014-09-17 20:55:46 +00001953 if (!CI->hasFnAttr(Attribute::Cold) &&
1954 isReportingError(Callee, CI, StreamArg)) {
Reid Klecknerb5180542017-03-21 16:57:19 +00001955 CI->addAttribute(AttributeList::FunctionIndex, Attribute::Cold);
Chris Bienemanad070d02014-09-17 20:55:46 +00001956 }
Hal Finkel66cd3f12013-11-17 02:06:35 +00001957
Chris Bienemanad070d02014-09-17 20:55:46 +00001958 return nullptr;
1959}
1960
1961static bool isReportingError(Function *Callee, CallInst *CI, int StreamArg) {
Davide Italiano5b65f122017-04-25 03:48:47 +00001962 if (!Callee || !Callee->isDeclaration())
Chris Bienemanad070d02014-09-17 20:55:46 +00001963 return false;
1964
1965 if (StreamArg < 0)
1966 return true;
1967
1968 // These functions might be considered cold, but only if their stream
1969 // argument is stderr.
1970
1971 if (StreamArg >= (int)CI->getNumArgOperands())
1972 return false;
1973 LoadInst *LI = dyn_cast<LoadInst>(CI->getArgOperand(StreamArg));
1974 if (!LI)
1975 return false;
1976 GlobalVariable *GV = dyn_cast<GlobalVariable>(LI->getPointerOperand());
1977 if (!GV || !GV->isDeclaration())
1978 return false;
1979 return GV->getName() == "stderr";
1980}
1981
1982Value *LibCallSimplifier::optimizePrintFString(CallInst *CI, IRBuilder<> &B) {
1983 // Check for a fixed format string.
1984 StringRef FormatStr;
1985 if (!getConstantStringInfo(CI->getArgOperand(0), FormatStr))
Craig Topperf40110f2014-04-25 05:29:35 +00001986 return nullptr;
Hal Finkel66cd3f12013-11-17 02:06:35 +00001987
Chris Bienemanad070d02014-09-17 20:55:46 +00001988 // Empty format string -> noop.
1989 if (FormatStr.empty()) // Tolerate printf's declared void.
1990 return CI->use_empty() ? (Value *)CI : ConstantInt::get(CI->getType(), 0);
Hal Finkel66cd3f12013-11-17 02:06:35 +00001991
Chris Bienemanad070d02014-09-17 20:55:46 +00001992 // Do not do any of the following transformations if the printf return value
1993 // is used, in general the printf return value is not compatible with either
1994 // putchar() or puts().
1995 if (!CI->use_empty())
Craig Topperf40110f2014-04-25 05:29:35 +00001996 return nullptr;
Chris Bienemanad070d02014-09-17 20:55:46 +00001997
Joerg Sonnenberger8ffe7ab2016-05-09 14:36:16 +00001998 // printf("x") -> putchar('x'), even for "%" and "%%".
1999 if (FormatStr.size() == 1 || FormatStr == "%%")
Davide Italianod4f5a052016-04-03 01:46:52 +00002000 return emitPutChar(B.getInt32(FormatStr[0]), B, TLI);
Meador Inge08ca1152012-11-26 20:37:20 +00002001
Davide Italiano6db1dcb2016-03-28 15:54:01 +00002002 // printf("%s", "a") --> putchar('a')
2003 if (FormatStr == "%s" && CI->getNumArgOperands() > 1) {
2004 StringRef ChrStr;
2005 if (!getConstantStringInfo(CI->getOperand(1), ChrStr))
2006 return nullptr;
2007 if (ChrStr.size() != 1)
2008 return nullptr;
Davide Italianod4f5a052016-04-03 01:46:52 +00002009 return emitPutChar(B.getInt32(ChrStr[0]), B, TLI);
Davide Italiano6db1dcb2016-03-28 15:54:01 +00002010 }
2011
Chris Bienemanad070d02014-09-17 20:55:46 +00002012 // printf("foo\n") --> puts("foo")
2013 if (FormatStr[FormatStr.size() - 1] == '\n' &&
2014 FormatStr.find('%') == StringRef::npos) { // No format characters.
2015 // Create a string literal with no \n on it. We expect the constant merge
2016 // pass to be run after this pass, to merge duplicate strings.
2017 FormatStr = FormatStr.drop_back();
2018 Value *GV = B.CreateGlobalString(FormatStr, "str");
Davide Italianod4f5a052016-04-03 01:46:52 +00002019 return emitPutS(GV, B, TLI);
Chris Bienemanad070d02014-09-17 20:55:46 +00002020 }
Meador Inge08ca1152012-11-26 20:37:20 +00002021
Chris Bienemanad070d02014-09-17 20:55:46 +00002022 // Optimize specific format strings.
2023 // printf("%c", chr) --> putchar(chr)
2024 if (FormatStr == "%c" && CI->getNumArgOperands() > 1 &&
Davide Italianod4f5a052016-04-03 01:46:52 +00002025 CI->getArgOperand(1)->getType()->isIntegerTy())
2026 return emitPutChar(CI->getArgOperand(1), B, TLI);
Chris Bienemanad070d02014-09-17 20:55:46 +00002027
2028 // printf("%s\n", str) --> puts(str)
2029 if (FormatStr == "%s\n" && CI->getNumArgOperands() > 1 &&
Davide Italianod4f5a052016-04-03 01:46:52 +00002030 CI->getArgOperand(1)->getType()->isPointerTy())
Sanjay Pateld3112a52016-01-19 19:46:10 +00002031 return emitPutS(CI->getArgOperand(1), B, TLI);
Chris Bienemanad070d02014-09-17 20:55:46 +00002032 return nullptr;
2033}
2034
2035Value *LibCallSimplifier::optimizePrintF(CallInst *CI, IRBuilder<> &B) {
2036
2037 Function *Callee = CI->getCalledFunction();
Chris Bienemanad070d02014-09-17 20:55:46 +00002038 FunctionType *FT = Callee->getFunctionType();
Chris Bienemanad070d02014-09-17 20:55:46 +00002039 if (Value *V = optimizePrintFString(CI, B)) {
2040 return V;
2041 }
2042
2043 // printf(format, ...) -> iprintf(format, ...) if no floating point
2044 // arguments.
David L. Jonesd21529f2017-01-23 23:16:46 +00002045 if (TLI->has(LibFunc_iprintf) && !callHasFloatingPointArgument(CI)) {
Chris Bienemanad070d02014-09-17 20:55:46 +00002046 Module *M = B.GetInsertBlock()->getParent()->getParent();
James Y Knight13680222019-02-01 02:28:03 +00002047 FunctionCallee IPrintFFn =
Meador Inge08ca1152012-11-26 20:37:20 +00002048 M->getOrInsertFunction("iprintf", FT, Callee->getAttributes());
Chris Bienemanad070d02014-09-17 20:55:46 +00002049 CallInst *New = cast<CallInst>(CI->clone());
2050 New->setCalledFunction(IPrintFFn);
2051 B.Insert(New);
2052 return New;
Meador Inge08ca1152012-11-26 20:37:20 +00002053 }
Chris Bienemanad070d02014-09-17 20:55:46 +00002054 return nullptr;
2055}
Meador Inge08ca1152012-11-26 20:37:20 +00002056
Chris Bienemanad070d02014-09-17 20:55:46 +00002057Value *LibCallSimplifier::optimizeSPrintFString(CallInst *CI, IRBuilder<> &B) {
2058 // Check for a fixed format string.
2059 StringRef FormatStr;
2060 if (!getConstantStringInfo(CI->getArgOperand(1), FormatStr))
Craig Topperf40110f2014-04-25 05:29:35 +00002061 return nullptr;
Meador Inge25c9b3b2012-11-27 05:57:54 +00002062
Chris Bienemanad070d02014-09-17 20:55:46 +00002063 // If we just have a format string (nothing else crazy) transform it.
2064 if (CI->getNumArgOperands() == 2) {
2065 // Make sure there's no % in the constant array. We could try to handle
2066 // %% -> % in the future if we cared.
David Bolvansky5430b7372018-05-31 16:39:27 +00002067 if (FormatStr.find('%') != StringRef::npos)
2068 return nullptr; // we found a format specifier, bail out.
Hal Finkel66cd3f12013-11-17 02:06:35 +00002069
Daniel Neilson8acd8b02018-02-05 21:23:22 +00002070 // sprintf(str, fmt) -> llvm.memcpy(align 1 str, align 1 fmt, strlen(fmt)+1)
2071 B.CreateMemCpy(CI->getArgOperand(0), 1, CI->getArgOperand(1), 1,
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002072 ConstantInt::get(DL.getIntPtrType(CI->getContext()),
Daniel Neilson8acd8b02018-02-05 21:23:22 +00002073 FormatStr.size() + 1)); // Copy the null byte.
Chris Bienemanad070d02014-09-17 20:55:46 +00002074 return ConstantInt::get(CI->getType(), FormatStr.size());
Meador Ingef8e72502012-11-29 15:45:43 +00002075 }
Meador Ingef8e72502012-11-29 15:45:43 +00002076
Chris Bienemanad070d02014-09-17 20:55:46 +00002077 // The remaining optimizations require the format string to be "%s" or "%c"
2078 // and have an extra operand.
2079 if (FormatStr.size() != 2 || FormatStr[0] != '%' ||
2080 CI->getNumArgOperands() < 3)
Craig Topperf40110f2014-04-25 05:29:35 +00002081 return nullptr;
Meador Inge75798bb2012-11-29 19:15:17 +00002082
Chris Bienemanad070d02014-09-17 20:55:46 +00002083 // Decode the second character of the format string.
2084 if (FormatStr[1] == 'c') {
2085 // sprintf(dst, "%c", chr) --> *(i8*)dst = chr; *((i8*)dst+1) = 0
2086 if (!CI->getArgOperand(2)->getType()->isIntegerTy())
2087 return nullptr;
2088 Value *V = B.CreateTrunc(CI->getArgOperand(2), B.getInt8Ty(), "char");
Sanjay Pateld3112a52016-01-19 19:46:10 +00002089 Value *Ptr = castToCStr(CI->getArgOperand(0), B);
Chris Bienemanad070d02014-09-17 20:55:46 +00002090 B.CreateStore(V, Ptr);
David Blaikie3909da72015-03-30 20:42:56 +00002091 Ptr = B.CreateGEP(B.getInt8Ty(), Ptr, B.getInt32(1), "nul");
Chris Bienemanad070d02014-09-17 20:55:46 +00002092 B.CreateStore(B.getInt8(0), Ptr);
Meador Ingedf796f82012-10-13 16:45:24 +00002093
Chris Bienemanad070d02014-09-17 20:55:46 +00002094 return ConstantInt::get(CI->getType(), 1);
Meador Ingedf796f82012-10-13 16:45:24 +00002095 }
2096
Chris Bienemanad070d02014-09-17 20:55:46 +00002097 if (FormatStr[1] == 's') {
Fangrui Songf2609672019-03-12 10:31:52 +00002098 // sprintf(dest, "%s", str) -> llvm.memcpy(align 1 dest, align 1 str,
2099 // strlen(str)+1)
Chris Bienemanad070d02014-09-17 20:55:46 +00002100 if (!CI->getArgOperand(2)->getType()->isPointerTy())
2101 return nullptr;
2102
Sanjay Pateld3112a52016-01-19 19:46:10 +00002103 Value *Len = emitStrLen(CI->getArgOperand(2), B, DL, TLI);
Chris Bienemanad070d02014-09-17 20:55:46 +00002104 if (!Len)
2105 return nullptr;
David Majnemerabb9f552016-04-26 21:04:47 +00002106 Value *IncLen =
2107 B.CreateAdd(Len, ConstantInt::get(Len->getType(), 1), "leninc");
Daniel Neilson8acd8b02018-02-05 21:23:22 +00002108 B.CreateMemCpy(CI->getArgOperand(0), 1, CI->getArgOperand(2), 1, IncLen);
Chris Bienemanad070d02014-09-17 20:55:46 +00002109
2110 // The sprintf result is the unincremented number of bytes in the string.
2111 return B.CreateIntCast(Len, CI->getType(), false);
2112 }
2113 return nullptr;
2114}
2115
2116Value *LibCallSimplifier::optimizeSPrintF(CallInst *CI, IRBuilder<> &B) {
2117 Function *Callee = CI->getCalledFunction();
Chris Bienemanad070d02014-09-17 20:55:46 +00002118 FunctionType *FT = Callee->getFunctionType();
Chris Bienemanad070d02014-09-17 20:55:46 +00002119 if (Value *V = optimizeSPrintFString(CI, B)) {
2120 return V;
2121 }
2122
2123 // sprintf(str, format, ...) -> siprintf(str, format, ...) if no floating
2124 // point arguments.
David L. Jonesd21529f2017-01-23 23:16:46 +00002125 if (TLI->has(LibFunc_siprintf) && !callHasFloatingPointArgument(CI)) {
Chris Bienemanad070d02014-09-17 20:55:46 +00002126 Module *M = B.GetInsertBlock()->getParent()->getParent();
James Y Knight13680222019-02-01 02:28:03 +00002127 FunctionCallee SIPrintFFn =
Chris Bienemanad070d02014-09-17 20:55:46 +00002128 M->getOrInsertFunction("siprintf", FT, Callee->getAttributes());
2129 CallInst *New = cast<CallInst>(CI->clone());
2130 New->setCalledFunction(SIPrintFFn);
2131 B.Insert(New);
2132 return New;
2133 }
2134 return nullptr;
2135}
2136
David Bolvanskycd93c4e2018-05-11 17:50:49 +00002137Value *LibCallSimplifier::optimizeSnPrintFString(CallInst *CI, IRBuilder<> &B) {
2138 // Check for a fixed format string.
2139 StringRef FormatStr;
2140 if (!getConstantStringInfo(CI->getArgOperand(2), FormatStr))
2141 return nullptr;
2142
2143 // Check for size
2144 ConstantInt *Size = dyn_cast<ConstantInt>(CI->getArgOperand(1));
2145 if (!Size)
2146 return nullptr;
2147
2148 uint64_t N = Size->getZExtValue();
2149
2150 // If we just have a format string (nothing else crazy) transform it.
2151 if (CI->getNumArgOperands() == 3) {
2152 // Make sure there's no % in the constant array. We could try to handle
2153 // %% -> % in the future if we cared.
David Bolvansky5430b7372018-05-31 16:39:27 +00002154 if (FormatStr.find('%') != StringRef::npos)
2155 return nullptr; // we found a format specifier, bail out.
David Bolvanskycd93c4e2018-05-11 17:50:49 +00002156
2157 if (N == 0)
2158 return ConstantInt::get(CI->getType(), FormatStr.size());
2159 else if (N < FormatStr.size() + 1)
2160 return nullptr;
2161
Fangrui Songf2609672019-03-12 10:31:52 +00002162 // snprintf(dst, size, fmt) -> llvm.memcpy(align 1 dst, align 1 fmt,
David Bolvanskycd93c4e2018-05-11 17:50:49 +00002163 // strlen(fmt)+1)
2164 B.CreateMemCpy(
2165 CI->getArgOperand(0), 1, CI->getArgOperand(2), 1,
2166 ConstantInt::get(DL.getIntPtrType(CI->getContext()),
2167 FormatStr.size() + 1)); // Copy the null byte.
2168 return ConstantInt::get(CI->getType(), FormatStr.size());
2169 }
2170
2171 // The remaining optimizations require the format string to be "%s" or "%c"
2172 // and have an extra operand.
2173 if (FormatStr.size() == 2 && FormatStr[0] == '%' &&
2174 CI->getNumArgOperands() == 4) {
2175
2176 // Decode the second character of the format string.
2177 if (FormatStr[1] == 'c') {
2178 if (N == 0)
2179 return ConstantInt::get(CI->getType(), 1);
2180 else if (N == 1)
2181 return nullptr;
2182
2183 // snprintf(dst, size, "%c", chr) --> *(i8*)dst = chr; *((i8*)dst+1) = 0
2184 if (!CI->getArgOperand(3)->getType()->isIntegerTy())
2185 return nullptr;
2186 Value *V = B.CreateTrunc(CI->getArgOperand(3), B.getInt8Ty(), "char");
2187 Value *Ptr = castToCStr(CI->getArgOperand(0), B);
2188 B.CreateStore(V, Ptr);
2189 Ptr = B.CreateGEP(B.getInt8Ty(), Ptr, B.getInt32(1), "nul");
2190 B.CreateStore(B.getInt8(0), Ptr);
2191
2192 return ConstantInt::get(CI->getType(), 1);
2193 }
2194
2195 if (FormatStr[1] == 's') {
2196 // snprintf(dest, size, "%s", str) to llvm.memcpy(dest, str, len+1, 1)
2197 StringRef Str;
2198 if (!getConstantStringInfo(CI->getArgOperand(3), Str))
2199 return nullptr;
2200
2201 if (N == 0)
2202 return ConstantInt::get(CI->getType(), Str.size());
2203 else if (N < Str.size() + 1)
2204 return nullptr;
2205
2206 B.CreateMemCpy(CI->getArgOperand(0), 1, CI->getArgOperand(3), 1,
2207 ConstantInt::get(CI->getType(), Str.size() + 1));
2208
2209 // The snprintf result is the unincremented number of bytes in the string.
2210 return ConstantInt::get(CI->getType(), Str.size());
2211 }
2212 }
2213 return nullptr;
2214}
2215
2216Value *LibCallSimplifier::optimizeSnPrintF(CallInst *CI, IRBuilder<> &B) {
2217 if (Value *V = optimizeSnPrintFString(CI, B)) {
2218 return V;
2219 }
2220
2221 return nullptr;
2222}
2223
Chris Bienemanad070d02014-09-17 20:55:46 +00002224Value *LibCallSimplifier::optimizeFPrintFString(CallInst *CI, IRBuilder<> &B) {
2225 optimizeErrorReporting(CI, B, 0);
2226
2227 // All the optimizations depend on the format string.
2228 StringRef FormatStr;
2229 if (!getConstantStringInfo(CI->getArgOperand(1), FormatStr))
2230 return nullptr;
2231
2232 // Do not do any of the following transformations if the fprintf return
2233 // value is used, in general the fprintf return value is not compatible
2234 // with fwrite(), fputc() or fputs().
2235 if (!CI->use_empty())
2236 return nullptr;
2237
2238 // fprintf(F, "foo") --> fwrite("foo", 3, 1, F)
2239 if (CI->getNumArgOperands() == 2) {
David Bolvansky5430b7372018-05-31 16:39:27 +00002240 // Could handle %% -> % if we cared.
2241 if (FormatStr.find('%') != StringRef::npos)
2242 return nullptr; // We found a format specifier.
Chris Bienemanad070d02014-09-17 20:55:46 +00002243
Sanjay Pateld3112a52016-01-19 19:46:10 +00002244 return emitFWrite(
Chris Bienemanad070d02014-09-17 20:55:46 +00002245 CI->getArgOperand(1),
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002246 ConstantInt::get(DL.getIntPtrType(CI->getContext()), FormatStr.size()),
Chris Bienemanad070d02014-09-17 20:55:46 +00002247 CI->getArgOperand(0), B, DL, TLI);
2248 }
2249
2250 // The remaining optimizations require the format string to be "%s" or "%c"
2251 // and have an extra operand.
2252 if (FormatStr.size() != 2 || FormatStr[0] != '%' ||
2253 CI->getNumArgOperands() < 3)
2254 return nullptr;
2255
2256 // Decode the second character of the format string.
2257 if (FormatStr[1] == 'c') {
2258 // fprintf(F, "%c", chr) --> fputc(chr, F)
2259 if (!CI->getArgOperand(2)->getType()->isIntegerTy())
2260 return nullptr;
Sanjay Pateld3112a52016-01-19 19:46:10 +00002261 return emitFPutC(CI->getArgOperand(2), CI->getArgOperand(0), B, TLI);
Chris Bienemanad070d02014-09-17 20:55:46 +00002262 }
2263
2264 if (FormatStr[1] == 's') {
2265 // fprintf(F, "%s", str) --> fputs(str, F)
2266 if (!CI->getArgOperand(2)->getType()->isPointerTy())
2267 return nullptr;
Sanjay Pateld3112a52016-01-19 19:46:10 +00002268 return emitFPutS(CI->getArgOperand(2), CI->getArgOperand(0), B, TLI);
Chris Bienemanad070d02014-09-17 20:55:46 +00002269 }
2270 return nullptr;
2271}
2272
2273Value *LibCallSimplifier::optimizeFPrintF(CallInst *CI, IRBuilder<> &B) {
2274 Function *Callee = CI->getCalledFunction();
Chris Bienemanad070d02014-09-17 20:55:46 +00002275 FunctionType *FT = Callee->getFunctionType();
Chris Bienemanad070d02014-09-17 20:55:46 +00002276 if (Value *V = optimizeFPrintFString(CI, B)) {
2277 return V;
2278 }
2279
2280 // fprintf(stream, format, ...) -> fiprintf(stream, format, ...) if no
2281 // floating point arguments.
David L. Jonesd21529f2017-01-23 23:16:46 +00002282 if (TLI->has(LibFunc_fiprintf) && !callHasFloatingPointArgument(CI)) {
Chris Bienemanad070d02014-09-17 20:55:46 +00002283 Module *M = B.GetInsertBlock()->getParent()->getParent();
James Y Knight13680222019-02-01 02:28:03 +00002284 FunctionCallee FIPrintFFn =
Chris Bienemanad070d02014-09-17 20:55:46 +00002285 M->getOrInsertFunction("fiprintf", FT, Callee->getAttributes());
2286 CallInst *New = cast<CallInst>(CI->clone());
2287 New->setCalledFunction(FIPrintFFn);
2288 B.Insert(New);
2289 return New;
2290 }
2291 return nullptr;
2292}
2293
2294Value *LibCallSimplifier::optimizeFWrite(CallInst *CI, IRBuilder<> &B) {
2295 optimizeErrorReporting(CI, B, 3);
2296
Chris Bienemanad070d02014-09-17 20:55:46 +00002297 // Get the element size and count.
2298 ConstantInt *SizeC = dyn_cast<ConstantInt>(CI->getArgOperand(1));
2299 ConstantInt *CountC = dyn_cast<ConstantInt>(CI->getArgOperand(2));
David Bolvanskyca22d422018-05-16 11:39:52 +00002300 if (SizeC && CountC) {
2301 uint64_t Bytes = SizeC->getZExtValue() * CountC->getZExtValue();
Chris Bienemanad070d02014-09-17 20:55:46 +00002302
David Bolvanskyca22d422018-05-16 11:39:52 +00002303 // If this is writing zero records, remove the call (it's a noop).
2304 if (Bytes == 0)
2305 return ConstantInt::get(CI->getType(), 0);
Chris Bienemanad070d02014-09-17 20:55:46 +00002306
David Bolvanskyca22d422018-05-16 11:39:52 +00002307 // If this is writing one byte, turn it into fputc.
2308 // This optimisation is only valid, if the return value is unused.
2309 if (Bytes == 1 && CI->use_empty()) { // fwrite(S,1,1,F) -> fputc(S[0],F)
James Y Knight14359ef2019-02-01 20:44:24 +00002310 Value *Char = B.CreateLoad(B.getInt8Ty(),
2311 castToCStr(CI->getArgOperand(0), B), "char");
David Bolvanskyca22d422018-05-16 11:39:52 +00002312 Value *NewCI = emitFPutC(Char, CI->getArgOperand(3), B, TLI);
2313 return NewCI ? ConstantInt::get(CI->getType(), 1) : nullptr;
2314 }
Chris Bienemanad070d02014-09-17 20:55:46 +00002315 }
2316
David Bolvanskyca22d422018-05-16 11:39:52 +00002317 if (isLocallyOpenedFile(CI->getArgOperand(3), CI, B, TLI))
2318 return emitFWriteUnlocked(CI->getArgOperand(0), CI->getArgOperand(1),
2319 CI->getArgOperand(2), CI->getArgOperand(3), B, DL,
2320 TLI);
2321
Chris Bienemanad070d02014-09-17 20:55:46 +00002322 return nullptr;
2323}
2324
2325Value *LibCallSimplifier::optimizeFPuts(CallInst *CI, IRBuilder<> &B) {
2326 optimizeErrorReporting(CI, B, 1);
2327
Sjoerd Meijer7435a912016-07-07 14:31:19 +00002328 // Don't rewrite fputs to fwrite when optimising for size because fwrite
2329 // requires more arguments and thus extra MOVs are required.
David Bolvansky5430b7372018-05-31 16:39:27 +00002330 if (CI->getFunction()->optForSize())
Sjoerd Meijer7435a912016-07-07 14:31:19 +00002331 return nullptr;
2332
David Bolvanskyca22d422018-05-16 11:39:52 +00002333 // Check if has any use
2334 if (!CI->use_empty()) {
2335 if (isLocallyOpenedFile(CI->getArgOperand(1), CI, B, TLI))
2336 return emitFPutSUnlocked(CI->getArgOperand(0), CI->getArgOperand(1), B,
2337 TLI);
2338 else
2339 // We can't optimize if return value is used.
2340 return nullptr;
2341 }
Chris Bienemanad070d02014-09-17 20:55:46 +00002342
Fangrui Songf2609672019-03-12 10:31:52 +00002343 // fputs(s,F) --> fwrite(s,strlen(s),1,F)
David Bolvansky1f343fa2018-05-22 20:27:36 +00002344 uint64_t Len = GetStringLength(CI->getArgOperand(0));
Chris Bienemanad070d02014-09-17 20:55:46 +00002345 if (!Len)
2346 return nullptr;
2347
2348 // Known to have no uses (see above).
Sanjay Pateld3112a52016-01-19 19:46:10 +00002349 return emitFWrite(
Chris Bienemanad070d02014-09-17 20:55:46 +00002350 CI->getArgOperand(0),
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002351 ConstantInt::get(DL.getIntPtrType(CI->getContext()), Len - 1),
Chris Bienemanad070d02014-09-17 20:55:46 +00002352 CI->getArgOperand(1), B, DL, TLI);
2353}
2354
David Bolvanskyca22d422018-05-16 11:39:52 +00002355Value *LibCallSimplifier::optimizeFPutc(CallInst *CI, IRBuilder<> &B) {
2356 optimizeErrorReporting(CI, B, 1);
2357
2358 if (isLocallyOpenedFile(CI->getArgOperand(1), CI, B, TLI))
2359 return emitFPutCUnlocked(CI->getArgOperand(0), CI->getArgOperand(1), B,
2360 TLI);
2361
2362 return nullptr;
2363}
2364
2365Value *LibCallSimplifier::optimizeFGetc(CallInst *CI, IRBuilder<> &B) {
2366 if (isLocallyOpenedFile(CI->getArgOperand(0), CI, B, TLI))
2367 return emitFGetCUnlocked(CI->getArgOperand(0), B, TLI);
2368
2369 return nullptr;
2370}
2371
2372Value *LibCallSimplifier::optimizeFGets(CallInst *CI, IRBuilder<> &B) {
2373 if (isLocallyOpenedFile(CI->getArgOperand(2), CI, B, TLI))
2374 return emitFGetSUnlocked(CI->getArgOperand(0), CI->getArgOperand(1),
2375 CI->getArgOperand(2), B, TLI);
2376
2377 return nullptr;
2378}
2379
2380Value *LibCallSimplifier::optimizeFRead(CallInst *CI, IRBuilder<> &B) {
2381 if (isLocallyOpenedFile(CI->getArgOperand(3), CI, B, TLI))
2382 return emitFReadUnlocked(CI->getArgOperand(0), CI->getArgOperand(1),
2383 CI->getArgOperand(2), CI->getArgOperand(3), B, DL,
2384 TLI);
2385
2386 return nullptr;
2387}
2388
Chris Bienemanad070d02014-09-17 20:55:46 +00002389Value *LibCallSimplifier::optimizePuts(CallInst *CI, IRBuilder<> &B) {
Fangrui Songb1dfbeb2019-03-12 14:20:22 +00002390 if (!CI->use_empty())
Chris Bienemanad070d02014-09-17 20:55:46 +00002391 return nullptr;
2392
Fangrui Songb1dfbeb2019-03-12 14:20:22 +00002393 // Check for a constant string.
2394 // puts("") -> putchar('\n')
2395 StringRef Str;
2396 if (getConstantStringInfo(CI->getArgOperand(0), Str) && Str.empty())
2397 return emitPutChar(B.getInt32('\n'), B, TLI);
Chris Bienemanad070d02014-09-17 20:55:46 +00002398
2399 return nullptr;
2400}
2401
2402bool LibCallSimplifier::hasFloatVersion(StringRef FuncName) {
David L. Jonesd21529f2017-01-23 23:16:46 +00002403 LibFunc Func;
Meador Inge20255ef2013-03-12 00:08:29 +00002404 SmallString<20> FloatFuncName = FuncName;
2405 FloatFuncName += 'f';
2406 if (TLI->getLibFunc(FloatFuncName, Func))
2407 return TLI->has(Func);
2408 return false;
2409}
Meador Inge7fb2f732012-10-13 16:45:32 +00002410
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00002411Value *LibCallSimplifier::optimizeStringMemoryLibCall(CallInst *CI,
2412 IRBuilder<> &Builder) {
David L. Jonesd21529f2017-01-23 23:16:46 +00002413 LibFunc Func;
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00002414 Function *Callee = CI->getCalledFunction();
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00002415 // Check for string/memory library functions.
Ahmed Bougachad765a822016-04-27 19:04:35 +00002416 if (TLI->getLibFunc(*Callee, Func) && TLI->has(Func)) {
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00002417 // Make sure we never change the calling convention.
2418 assert((ignoreCallingConv(Func) ||
Sam Parker214f7bf2016-09-13 12:10:14 +00002419 isCallingConvCCompatible(CI)) &&
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00002420 "Optimizing string/memory libcall would change the calling convention");
2421 switch (Func) {
David L. Jonesd21529f2017-01-23 23:16:46 +00002422 case LibFunc_strcat:
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00002423 return optimizeStrCat(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002424 case LibFunc_strncat:
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00002425 return optimizeStrNCat(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002426 case LibFunc_strchr:
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00002427 return optimizeStrChr(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002428 case LibFunc_strrchr:
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00002429 return optimizeStrRChr(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002430 case LibFunc_strcmp:
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00002431 return optimizeStrCmp(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002432 case LibFunc_strncmp:
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00002433 return optimizeStrNCmp(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002434 case LibFunc_strcpy:
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00002435 return optimizeStrCpy(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002436 case LibFunc_stpcpy:
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00002437 return optimizeStpCpy(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002438 case LibFunc_strncpy:
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00002439 return optimizeStrNCpy(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002440 case LibFunc_strlen:
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00002441 return optimizeStrLen(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002442 case LibFunc_strpbrk:
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00002443 return optimizeStrPBrk(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002444 case LibFunc_strtol:
2445 case LibFunc_strtod:
2446 case LibFunc_strtof:
2447 case LibFunc_strtoul:
2448 case LibFunc_strtoll:
2449 case LibFunc_strtold:
2450 case LibFunc_strtoull:
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00002451 return optimizeStrTo(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002452 case LibFunc_strspn:
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00002453 return optimizeStrSpn(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002454 case LibFunc_strcspn:
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00002455 return optimizeStrCSpn(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002456 case LibFunc_strstr:
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00002457 return optimizeStrStr(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002458 case LibFunc_memchr:
Benjamin Kramer691363e2015-03-21 15:36:21 +00002459 return optimizeMemChr(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002460 case LibFunc_memcmp:
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00002461 return optimizeMemCmp(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002462 case LibFunc_memcpy:
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00002463 return optimizeMemCpy(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002464 case LibFunc_memmove:
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00002465 return optimizeMemMove(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002466 case LibFunc_memset:
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00002467 return optimizeMemSet(CI, Builder);
Sanjay Patelb2ab3f22018-04-18 14:21:31 +00002468 case LibFunc_realloc:
2469 return optimizeRealloc(CI, Builder);
Matthias Braun50ec0b52017-05-19 22:37:09 +00002470 case LibFunc_wcslen:
2471 return optimizeWcslen(CI, Builder);
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00002472 default:
2473 break;
2474 }
2475 }
2476 return nullptr;
2477}
2478
Andrew Kaylor53a5fbb2017-08-14 21:15:13 +00002479Value *LibCallSimplifier::optimizeFloatingPointLibCall(CallInst *CI,
2480 LibFunc Func,
2481 IRBuilder<> &Builder) {
2482 // Don't optimize calls that require strict floating point semantics.
2483 if (CI->isStrictFP())
2484 return nullptr;
2485
Sanjay Patele45a83d2018-08-13 19:24:41 +00002486 if (Value *V = optimizeTrigReflections(CI, Func, Builder))
2487 return V;
2488
Andrew Kaylor53a5fbb2017-08-14 21:15:13 +00002489 switch (Func) {
Andrew Kaylor53a5fbb2017-08-14 21:15:13 +00002490 case LibFunc_sinpif:
2491 case LibFunc_sinpi:
2492 case LibFunc_cospif:
2493 case LibFunc_cospi:
2494 return optimizeSinCosPi(CI, Builder);
2495 case LibFunc_powf:
2496 case LibFunc_pow:
2497 case LibFunc_powl:
2498 return optimizePow(CI, Builder);
2499 case LibFunc_exp2l:
2500 case LibFunc_exp2:
2501 case LibFunc_exp2f:
2502 return optimizeExp2(CI, Builder);
2503 case LibFunc_fabsf:
2504 case LibFunc_fabs:
2505 case LibFunc_fabsl:
2506 return replaceUnaryCall(CI, Builder, Intrinsic::fabs);
2507 case LibFunc_sqrtf:
2508 case LibFunc_sqrt:
2509 case LibFunc_sqrtl:
2510 return optimizeSqrt(CI, Builder);
2511 case LibFunc_log:
2512 case LibFunc_log10:
2513 case LibFunc_log1p:
2514 case LibFunc_log2:
2515 case LibFunc_logb:
2516 return optimizeLog(CI, Builder);
2517 case LibFunc_tan:
2518 case LibFunc_tanf:
2519 case LibFunc_tanl:
2520 return optimizeTan(CI, Builder);
2521 case LibFunc_ceil:
2522 return replaceUnaryCall(CI, Builder, Intrinsic::ceil);
2523 case LibFunc_floor:
2524 return replaceUnaryCall(CI, Builder, Intrinsic::floor);
2525 case LibFunc_round:
2526 return replaceUnaryCall(CI, Builder, Intrinsic::round);
2527 case LibFunc_nearbyint:
2528 return replaceUnaryCall(CI, Builder, Intrinsic::nearbyint);
2529 case LibFunc_rint:
2530 return replaceUnaryCall(CI, Builder, Intrinsic::rint);
2531 case LibFunc_trunc:
2532 return replaceUnaryCall(CI, Builder, Intrinsic::trunc);
2533 case LibFunc_acos:
2534 case LibFunc_acosh:
2535 case LibFunc_asin:
2536 case LibFunc_asinh:
2537 case LibFunc_atan:
2538 case LibFunc_atanh:
2539 case LibFunc_cbrt:
2540 case LibFunc_cosh:
2541 case LibFunc_exp:
2542 case LibFunc_exp10:
2543 case LibFunc_expm1:
Sanjay Patele45a83d2018-08-13 19:24:41 +00002544 case LibFunc_cos:
Andrew Kaylor53a5fbb2017-08-14 21:15:13 +00002545 case LibFunc_sin:
2546 case LibFunc_sinh:
2547 case LibFunc_tanh:
2548 if (UnsafeFPShrink && hasFloatVersion(CI->getCalledFunction()->getName()))
2549 return optimizeUnaryDoubleFP(CI, Builder, true);
2550 return nullptr;
2551 case LibFunc_copysign:
2552 if (hasFloatVersion(CI->getCalledFunction()->getName()))
2553 return optimizeBinaryDoubleFP(CI, Builder);
2554 return nullptr;
2555 case LibFunc_fminf:
2556 case LibFunc_fmin:
2557 case LibFunc_fminl:
2558 case LibFunc_fmaxf:
2559 case LibFunc_fmax:
2560 case LibFunc_fmaxl:
2561 return optimizeFMinFMax(CI, Builder);
Hal Finkel2ff24732017-12-16 01:26:25 +00002562 case LibFunc_cabs:
2563 case LibFunc_cabsf:
2564 case LibFunc_cabsl:
2565 return optimizeCAbs(CI, Builder);
Andrew Kaylor53a5fbb2017-08-14 21:15:13 +00002566 default:
2567 return nullptr;
2568 }
2569}
2570
Chris Bienemanad070d02014-09-17 20:55:46 +00002571Value *LibCallSimplifier::optimizeCall(CallInst *CI) {
Andrew Kaylor53a5fbb2017-08-14 21:15:13 +00002572 // TODO: Split out the code below that operates on FP calls so that
2573 // we can all non-FP calls with the StrictFP attribute to be
2574 // optimized.
Chris Bienemanad070d02014-09-17 20:55:46 +00002575 if (CI->isNoBuiltin())
2576 return nullptr;
Meador Inge4d2827c2012-11-11 05:11:20 +00002577
David L. Jonesd21529f2017-01-23 23:16:46 +00002578 LibFunc Func;
Meador Inge20255ef2013-03-12 00:08:29 +00002579 Function *Callee = CI->getCalledFunction();
David Majnemerb70e23c2016-01-06 05:01:34 +00002580
2581 SmallVector<OperandBundleDef, 2> OpBundles;
2582 CI->getOperandBundlesAsDefs(OpBundles);
2583 IRBuilder<> Builder(CI, /*FPMathTag=*/nullptr, OpBundles);
Sam Parker214f7bf2016-09-13 12:10:14 +00002584 bool isCallingConvC = isCallingConvCCompatible(CI);
Meador Inge20255ef2013-03-12 00:08:29 +00002585
Sanjay Pateld1f4f032016-01-19 18:38:52 +00002586 // Command-line parameter overrides instruction attribute.
Andrew Kaylor53a5fbb2017-08-14 21:15:13 +00002587 // This can't be moved to optimizeFloatingPointLibCall() because it may be
Sanjay Patel629c4112017-11-06 16:27:15 +00002588 // used by the intrinsic optimizations.
Sanjay Patela92fa442014-10-22 15:29:23 +00002589 if (EnableUnsafeFPShrink.getNumOccurrences() > 0)
2590 UnsafeFPShrink = EnableUnsafeFPShrink;
Sanjay Patel629c4112017-11-06 16:27:15 +00002591 else if (isa<FPMathOperator>(CI) && CI->isFast())
Davide Italianoa904e522015-10-29 02:58:44 +00002592 UnsafeFPShrink = true;
Sanjay Patela92fa442014-10-22 15:29:23 +00002593
Sanjay Patel848309d2014-10-23 21:52:45 +00002594 // First, check for intrinsics.
Meador Inge20255ef2013-03-12 00:08:29 +00002595 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(CI)) {
Chris Bienemanad070d02014-09-17 20:55:46 +00002596 if (!isCallingConvC)
2597 return nullptr;
Andrew Kaylor53a5fbb2017-08-14 21:15:13 +00002598 // The FP intrinsics have corresponding constrained versions so we don't
2599 // need to check for the StrictFP attribute here.
Meador Inge20255ef2013-03-12 00:08:29 +00002600 switch (II->getIntrinsicID()) {
2601 case Intrinsic::pow:
Chris Bienemanad070d02014-09-17 20:55:46 +00002602 return optimizePow(CI, Builder);
Meador Inge20255ef2013-03-12 00:08:29 +00002603 case Intrinsic::exp2:
Chris Bienemanad070d02014-09-17 20:55:46 +00002604 return optimizeExp2(CI, Builder);
Davide Italianob8b71332015-11-29 20:58:04 +00002605 case Intrinsic::log:
2606 return optimizeLog(CI, Builder);
Sanjay Patelc699a612014-10-16 18:48:17 +00002607 case Intrinsic::sqrt:
2608 return optimizeSqrt(CI, Builder);
Sanjay Patel980b2802016-01-26 16:17:24 +00002609 // TODO: Use foldMallocMemset() with memset intrinsic.
Meador Inge20255ef2013-03-12 00:08:29 +00002610 default:
Chris Bienemanad070d02014-09-17 20:55:46 +00002611 return nullptr;
Meador Inge20255ef2013-03-12 00:08:29 +00002612 }
2613 }
2614
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002615 // Also try to simplify calls to fortified library functions.
2616 if (Value *SimplifiedFortifiedCI = FortifiedSimplifier.optimizeCall(CI)) {
2617 // Try to further simplify the result.
Ahmed Bougacha71d7b182015-01-14 00:55:05 +00002618 CallInst *SimplifiedCI = dyn_cast<CallInst>(SimplifiedFortifiedCI);
Bruno Cardoso Lopesb491a2d2015-10-01 22:43:53 +00002619 if (SimplifiedCI && SimplifiedCI->getCalledFunction()) {
2620 // Use an IR Builder from SimplifiedCI if available instead of CI
2621 // to guarantee we reach all uses we might replace later on.
2622 IRBuilder<> TmpBuilder(SimplifiedCI);
2623 if (Value *V = optimizeStringMemoryLibCall(SimplifiedCI, TmpBuilder)) {
Ahmed Bougacha1ac93562015-01-27 21:52:16 +00002624 // If we were able to further simplify, remove the now redundant call.
2625 SimplifiedCI->replaceAllUsesWith(V);
Amara Emerson54f60252018-10-11 14:51:11 +00002626 eraseFromParent(SimplifiedCI);
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002627 return V;
Ahmed Bougacha1ac93562015-01-27 21:52:16 +00002628 }
Bruno Cardoso Lopesb491a2d2015-10-01 22:43:53 +00002629 }
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002630 return SimplifiedFortifiedCI;
2631 }
2632
Meador Inge20255ef2013-03-12 00:08:29 +00002633 // Then check for known library functions.
Ahmed Bougachad765a822016-04-27 19:04:35 +00002634 if (TLI->getLibFunc(*Callee, Func) && TLI->has(Func)) {
Chris Bienemanad070d02014-09-17 20:55:46 +00002635 // We never change the calling convention.
2636 if (!ignoreCallingConv(Func) && !isCallingConvC)
2637 return nullptr;
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00002638 if (Value *V = optimizeStringMemoryLibCall(CI, Builder))
2639 return V;
Andrew Kaylor53a5fbb2017-08-14 21:15:13 +00002640 if (Value *V = optimizeFloatingPointLibCall(CI, Func, Builder))
2641 return V;
Meador Inge20255ef2013-03-12 00:08:29 +00002642 switch (Func) {
David L. Jonesd21529f2017-01-23 23:16:46 +00002643 case LibFunc_ffs:
2644 case LibFunc_ffsl:
2645 case LibFunc_ffsll:
Chris Bienemanad070d02014-09-17 20:55:46 +00002646 return optimizeFFS(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002647 case LibFunc_fls:
2648 case LibFunc_flsl:
2649 case LibFunc_flsll:
Davide Italiano85ad36b2016-12-15 23:45:11 +00002650 return optimizeFls(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002651 case LibFunc_abs:
2652 case LibFunc_labs:
2653 case LibFunc_llabs:
Chris Bienemanad070d02014-09-17 20:55:46 +00002654 return optimizeAbs(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002655 case LibFunc_isdigit:
Chris Bienemanad070d02014-09-17 20:55:46 +00002656 return optimizeIsDigit(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002657 case LibFunc_isascii:
Chris Bienemanad070d02014-09-17 20:55:46 +00002658 return optimizeIsAscii(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002659 case LibFunc_toascii:
Chris Bienemanad070d02014-09-17 20:55:46 +00002660 return optimizeToAscii(CI, Builder);
David Bolvanskycb8ca5f32018-04-25 18:58:53 +00002661 case LibFunc_atoi:
2662 case LibFunc_atol:
2663 case LibFunc_atoll:
2664 return optimizeAtoi(CI, Builder);
2665 case LibFunc_strtol:
2666 case LibFunc_strtoll:
2667 return optimizeStrtol(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002668 case LibFunc_printf:
Chris Bienemanad070d02014-09-17 20:55:46 +00002669 return optimizePrintF(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002670 case LibFunc_sprintf:
Chris Bienemanad070d02014-09-17 20:55:46 +00002671 return optimizeSPrintF(CI, Builder);
David Bolvanskycd93c4e2018-05-11 17:50:49 +00002672 case LibFunc_snprintf:
2673 return optimizeSnPrintF(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002674 case LibFunc_fprintf:
Chris Bienemanad070d02014-09-17 20:55:46 +00002675 return optimizeFPrintF(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002676 case LibFunc_fwrite:
Chris Bienemanad070d02014-09-17 20:55:46 +00002677 return optimizeFWrite(CI, Builder);
David Bolvanskyca22d422018-05-16 11:39:52 +00002678 case LibFunc_fread:
2679 return optimizeFRead(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002680 case LibFunc_fputs:
Chris Bienemanad070d02014-09-17 20:55:46 +00002681 return optimizeFPuts(CI, Builder);
David Bolvanskyca22d422018-05-16 11:39:52 +00002682 case LibFunc_fgets:
2683 return optimizeFGets(CI, Builder);
2684 case LibFunc_fputc:
2685 return optimizeFPutc(CI, Builder);
2686 case LibFunc_fgetc:
2687 return optimizeFGetc(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002688 case LibFunc_puts:
Chris Bienemanad070d02014-09-17 20:55:46 +00002689 return optimizePuts(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002690 case LibFunc_perror:
Chris Bienemanad070d02014-09-17 20:55:46 +00002691 return optimizeErrorReporting(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002692 case LibFunc_vfprintf:
2693 case LibFunc_fiprintf:
Chris Bienemanad070d02014-09-17 20:55:46 +00002694 return optimizeErrorReporting(CI, Builder, 0);
Chris Bienemanad070d02014-09-17 20:55:46 +00002695 default:
2696 return nullptr;
2697 }
Meador Inge20255ef2013-03-12 00:08:29 +00002698 }
Craig Topperf40110f2014-04-25 05:29:35 +00002699 return nullptr;
Meador Ingedf796f82012-10-13 16:45:24 +00002700}
2701
Chandler Carruth92803822015-01-21 02:11:59 +00002702LibCallSimplifier::LibCallSimplifier(
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002703 const DataLayout &DL, const TargetLibraryInfo *TLI,
Adam Nemetea06e6e2017-07-26 19:03:18 +00002704 OptimizationRemarkEmitter &ORE,
Amara Emerson54f60252018-10-11 14:51:11 +00002705 function_ref<void(Instruction *, Value *)> Replacer,
2706 function_ref<void(Instruction *)> Eraser)
Adam Nemetea06e6e2017-07-26 19:03:18 +00002707 : FortifiedSimplifier(TLI), DL(DL), TLI(TLI), ORE(ORE),
Amara Emerson54f60252018-10-11 14:51:11 +00002708 UnsafeFPShrink(false), Replacer(Replacer), Eraser(Eraser) {}
Chandler Carruth92803822015-01-21 02:11:59 +00002709
2710void LibCallSimplifier::replaceAllUsesWith(Instruction *I, Value *With) {
2711 // Indirect through the replacer used in this instance.
2712 Replacer(I, With);
Meador Ingedf796f82012-10-13 16:45:24 +00002713}
2714
Amara Emerson54f60252018-10-11 14:51:11 +00002715void LibCallSimplifier::eraseFromParent(Instruction *I) {
2716 Eraser(I);
2717}
2718
Meador Ingedfb08a22013-06-20 19:48:07 +00002719// TODO:
2720// Additional cases that we need to add to this file:
2721//
2722// cbrt:
2723// * cbrt(expN(X)) -> expN(x/3)
2724// * cbrt(sqrt(x)) -> pow(x,1/6)
David Majnemer3354fe42015-08-26 18:30:16 +00002725// * cbrt(cbrt(x)) -> pow(x,1/9)
Meador Ingedfb08a22013-06-20 19:48:07 +00002726//
2727// exp, expf, expl:
2728// * exp(log(x)) -> x
2729//
2730// log, logf, logl:
2731// * log(exp(x)) -> x
Meador Ingedfb08a22013-06-20 19:48:07 +00002732// * log(exp(y)) -> y*log(e)
Meador Ingedfb08a22013-06-20 19:48:07 +00002733// * log(exp10(y)) -> y*log(10)
2734// * log(sqrt(x)) -> 0.5*log(x)
Meador Ingedfb08a22013-06-20 19:48:07 +00002735//
Meador Ingedfb08a22013-06-20 19:48:07 +00002736// pow, powf, powl:
Meador Ingedfb08a22013-06-20 19:48:07 +00002737// * pow(sqrt(x),y) -> pow(x,y*0.5)
2738// * pow(pow(x,y),z)-> pow(x,y*z)
2739//
Meador Ingedfb08a22013-06-20 19:48:07 +00002740// signbit:
2741// * signbit(cnst) -> cnst'
2742// * signbit(nncst) -> 0 (if pstv is a non-negative constant)
2743//
2744// sqrt, sqrtf, sqrtl:
2745// * sqrt(expN(x)) -> expN(x*0.5)
2746// * sqrt(Nroot(x)) -> pow(x,1/(2*N))
2747// * sqrt(pow(x,y)) -> pow(|x|,y*0.5)
2748//
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002749
2750//===----------------------------------------------------------------------===//
2751// Fortified Library Call Optimizations
2752//===----------------------------------------------------------------------===//
2753
2754bool FortifiedLibCallSimplifier::isFortifiedCallFoldable(CallInst *CI,
2755 unsigned ObjSizeOp,
2756 unsigned SizeOp,
2757 bool isString) {
2758 if (CI->getArgOperand(ObjSizeOp) == CI->getArgOperand(SizeOp))
2759 return true;
2760 if (ConstantInt *ObjSizeCI =
2761 dyn_cast<ConstantInt>(CI->getArgOperand(ObjSizeOp))) {
Craig Topper79ab6432017-07-06 18:39:47 +00002762 if (ObjSizeCI->isMinusOne())
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002763 return true;
2764 // If the object size wasn't -1 (unknown), bail out if we were asked to.
2765 if (OnlyLowerUnknownSize)
2766 return false;
2767 if (isString) {
David Bolvansky1f343fa2018-05-22 20:27:36 +00002768 uint64_t Len = GetStringLength(CI->getArgOperand(SizeOp));
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002769 // If the length is 0 we don't know how long it is and so we can't
2770 // remove the check.
2771 if (Len == 0)
2772 return false;
2773 return ObjSizeCI->getZExtValue() >= Len;
2774 }
2775 if (ConstantInt *SizeCI = dyn_cast<ConstantInt>(CI->getArgOperand(SizeOp)))
2776 return ObjSizeCI->getZExtValue() >= SizeCI->getZExtValue();
2777 }
2778 return false;
2779}
2780
Sanjay Pateld707db92015-12-31 16:10:49 +00002781Value *FortifiedLibCallSimplifier::optimizeMemCpyChk(CallInst *CI,
2782 IRBuilder<> &B) {
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002783 if (isFortifiedCallFoldable(CI, 3, 2, false)) {
Daniel Neilson8acd8b02018-02-05 21:23:22 +00002784 B.CreateMemCpy(CI->getArgOperand(0), 1, CI->getArgOperand(1), 1,
2785 CI->getArgOperand(2));
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002786 return CI->getArgOperand(0);
2787 }
2788 return nullptr;
2789}
2790
Sanjay Pateld707db92015-12-31 16:10:49 +00002791Value *FortifiedLibCallSimplifier::optimizeMemMoveChk(CallInst *CI,
2792 IRBuilder<> &B) {
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002793 if (isFortifiedCallFoldable(CI, 3, 2, false)) {
Daniel Neilson8acd8b02018-02-05 21:23:22 +00002794 B.CreateMemMove(CI->getArgOperand(0), 1, CI->getArgOperand(1), 1,
2795 CI->getArgOperand(2));
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002796 return CI->getArgOperand(0);
2797 }
2798 return nullptr;
2799}
2800
Sanjay Pateld707db92015-12-31 16:10:49 +00002801Value *FortifiedLibCallSimplifier::optimizeMemSetChk(CallInst *CI,
2802 IRBuilder<> &B) {
Sanjay Patel980b2802016-01-26 16:17:24 +00002803 // TODO: Try foldMallocMemset() here.
2804
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002805 if (isFortifiedCallFoldable(CI, 3, 2, false)) {
2806 Value *Val = B.CreateIntCast(CI->getArgOperand(1), B.getInt8Ty(), false);
2807 B.CreateMemSet(CI->getArgOperand(0), Val, CI->getArgOperand(2), 1);
2808 return CI->getArgOperand(0);
2809 }
2810 return nullptr;
2811}
2812
Ahmed Bougacha1ac93562015-01-27 21:52:16 +00002813Value *FortifiedLibCallSimplifier::optimizeStrpCpyChk(CallInst *CI,
2814 IRBuilder<> &B,
David L. Jonesd21529f2017-01-23 23:16:46 +00002815 LibFunc Func) {
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002816 Function *Callee = CI->getCalledFunction();
2817 StringRef Name = Callee->getName();
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002818 const DataLayout &DL = CI->getModule()->getDataLayout();
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002819 Value *Dst = CI->getArgOperand(0), *Src = CI->getArgOperand(1),
2820 *ObjSize = CI->getArgOperand(2);
2821
2822 // __stpcpy_chk(x,x,...) -> x+strlen(x)
David L. Jonesd21529f2017-01-23 23:16:46 +00002823 if (Func == LibFunc_stpcpy_chk && !OnlyLowerUnknownSize && Dst == Src) {
Sanjay Pateld3112a52016-01-19 19:46:10 +00002824 Value *StrLen = emitStrLen(Src, B, DL, TLI);
David Blaikieaa41cd52015-04-03 21:33:42 +00002825 return StrLen ? B.CreateInBoundsGEP(B.getInt8Ty(), Dst, StrLen) : nullptr;
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002826 }
2827
2828 // If a) we don't have any length information, or b) we know this will
2829 // fit then just lower to a plain st[rp]cpy. Otherwise we'll keep our
2830 // st[rp]cpy_chk call which may fail at runtime if the size is too long.
2831 // TODO: It might be nice to get a maximum length out of the possible
2832 // string lengths for varying.
David Blaikie65fab6d2015-04-03 21:32:06 +00002833 if (isFortifiedCallFoldable(CI, 2, 1, true))
Sanjay Pateld3112a52016-01-19 19:46:10 +00002834 return emitStrCpy(Dst, Src, B, TLI, Name.substr(2, 6));
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002835
David Blaikie65fab6d2015-04-03 21:32:06 +00002836 if (OnlyLowerUnknownSize)
2837 return nullptr;
2838
2839 // Maybe we can stil fold __st[rp]cpy_chk to __memcpy_chk.
David Bolvansky1f343fa2018-05-22 20:27:36 +00002840 uint64_t Len = GetStringLength(Src);
David Blaikie65fab6d2015-04-03 21:32:06 +00002841 if (Len == 0)
2842 return nullptr;
2843
2844 Type *SizeTTy = DL.getIntPtrType(CI->getContext());
2845 Value *LenV = ConstantInt::get(SizeTTy, Len);
Sanjay Pateld3112a52016-01-19 19:46:10 +00002846 Value *Ret = emitMemCpyChk(Dst, Src, LenV, ObjSize, B, DL, TLI);
David Blaikie65fab6d2015-04-03 21:32:06 +00002847 // If the function was an __stpcpy_chk, and we were able to fold it into
2848 // a __memcpy_chk, we still need to return the correct end pointer.
David L. Jonesd21529f2017-01-23 23:16:46 +00002849 if (Ret && Func == LibFunc_stpcpy_chk)
David Blaikie65fab6d2015-04-03 21:32:06 +00002850 return B.CreateGEP(B.getInt8Ty(), Dst, ConstantInt::get(SizeTTy, Len - 1));
2851 return Ret;
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002852}
2853
Ahmed Bougacha1ac93562015-01-27 21:52:16 +00002854Value *FortifiedLibCallSimplifier::optimizeStrpNCpyChk(CallInst *CI,
2855 IRBuilder<> &B,
David L. Jonesd21529f2017-01-23 23:16:46 +00002856 LibFunc Func) {
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002857 Function *Callee = CI->getCalledFunction();
2858 StringRef Name = Callee->getName();
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002859 if (isFortifiedCallFoldable(CI, 3, 2, false)) {
Sanjay Pateld3112a52016-01-19 19:46:10 +00002860 Value *Ret = emitStrNCpy(CI->getArgOperand(0), CI->getArgOperand(1),
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002861 CI->getArgOperand(2), B, TLI, Name.substr(2, 7));
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002862 return Ret;
2863 }
2864 return nullptr;
2865}
2866
2867Value *FortifiedLibCallSimplifier::optimizeCall(CallInst *CI) {
Ahmed Bougacha408d0102015-04-01 00:45:09 +00002868 // FIXME: We shouldn't be changing "nobuiltin" or TLI unavailable calls here.
2869 // Some clang users checked for _chk libcall availability using:
2870 // __has_builtin(__builtin___memcpy_chk)
2871 // When compiling with -fno-builtin, this is always true.
2872 // When passing -ffreestanding/-mkernel, which both imply -fno-builtin, we
2873 // end up with fortified libcalls, which isn't acceptable in a freestanding
2874 // environment which only provides their non-fortified counterparts.
2875 //
2876 // Until we change clang and/or teach external users to check for availability
2877 // differently, disregard the "nobuiltin" attribute and TLI::has.
2878 //
2879 // PR23093.
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002880
David L. Jonesd21529f2017-01-23 23:16:46 +00002881 LibFunc Func;
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002882 Function *Callee = CI->getCalledFunction();
David Majnemerb70e23c2016-01-06 05:01:34 +00002883
2884 SmallVector<OperandBundleDef, 2> OpBundles;
2885 CI->getOperandBundlesAsDefs(OpBundles);
2886 IRBuilder<> Builder(CI, /*FPMathTag=*/nullptr, OpBundles);
Sam Parker214f7bf2016-09-13 12:10:14 +00002887 bool isCallingConvC = isCallingConvCCompatible(CI);
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002888
Ahmed Bougachad765a822016-04-27 19:04:35 +00002889 // First, check that this is a known library functions and that the prototype
2890 // is correct.
2891 if (!TLI->getLibFunc(*Callee, Func))
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002892 return nullptr;
2893
2894 // We never change the calling convention.
2895 if (!ignoreCallingConv(Func) && !isCallingConvC)
2896 return nullptr;
2897
2898 switch (Func) {
David L. Jonesd21529f2017-01-23 23:16:46 +00002899 case LibFunc_memcpy_chk:
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002900 return optimizeMemCpyChk(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002901 case LibFunc_memmove_chk:
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002902 return optimizeMemMoveChk(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002903 case LibFunc_memset_chk:
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002904 return optimizeMemSetChk(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002905 case LibFunc_stpcpy_chk:
2906 case LibFunc_strcpy_chk:
Ahmed Bougacha1ac93562015-01-27 21:52:16 +00002907 return optimizeStrpCpyChk(CI, Builder, Func);
David L. Jonesd21529f2017-01-23 23:16:46 +00002908 case LibFunc_stpncpy_chk:
2909 case LibFunc_strncpy_chk:
Ahmed Bougacha1ac93562015-01-27 21:52:16 +00002910 return optimizeStrpNCpyChk(CI, Builder, Func);
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002911 default:
2912 break;
2913 }
2914 return nullptr;
2915}
2916
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002917FortifiedLibCallSimplifier::FortifiedLibCallSimplifier(
2918 const TargetLibraryInfo *TLI, bool OnlyLowerUnknownSize)
Sanjay Patel4b969352018-05-22 23:29:40 +00002919 : TLI(TLI), OnlyLowerUnknownSize(OnlyLowerUnknownSize) {}