blob: 461a5e2cba0d631c170c8b2e4a81b5f4d371877b [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"
Hiroshi Yamauchi09e539f2019-04-15 16:49:00 +000019#include "llvm/Analysis/BlockFrequencyInfo.h"
Sanjay Patel82ec8722017-08-21 19:13:14 +000020#include "llvm/Analysis/ConstantFolding.h"
Adam Nemet0965da22017-10-09 23:19:02 +000021#include "llvm/Analysis/OptimizationRemarkEmitter.h"
Hiroshi Yamauchi09e539f2019-04-15 16:49:00 +000022#include "llvm/Analysis/ProfileSummaryInfo.h"
Weiming Zhao45d4cb92015-11-24 18:57:06 +000023#include "llvm/Analysis/TargetLibraryInfo.h"
David Blaikie31b98d22018-06-04 21:23:21 +000024#include "llvm/Transforms/Utils/Local.h"
Meador Ingedf796f82012-10-13 16:45:24 +000025#include "llvm/Analysis/ValueTracking.h"
David Bolvanskyca22d422018-05-16 11:39:52 +000026#include "llvm/Analysis/CaptureTracking.h"
David Bolvansky909889b2018-08-10 04:32:54 +000027#include "llvm/Analysis/Loads.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000028#include "llvm/IR/DataLayout.h"
29#include "llvm/IR/Function.h"
30#include "llvm/IR/IRBuilder.h"
Meador Inge20255ef2013-03-12 00:08:29 +000031#include "llvm/IR/IntrinsicInst.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000032#include "llvm/IR/Intrinsics.h"
33#include "llvm/IR/LLVMContext.h"
34#include "llvm/IR/Module.h"
Sanjay Patelc699a612014-10-16 18:48:17 +000035#include "llvm/IR/PatternMatch.h"
Hal Finkel66cd3f12013-11-17 02:06:35 +000036#include "llvm/Support/CommandLine.h"
Craig Topperb45eabc2017-04-26 16:39:58 +000037#include "llvm/Support/KnownBits.h"
Evandro Menezes110b1132019-09-30 20:52:21 +000038#include "llvm/Support/MathExtras.h"
Meador Ingedf796f82012-10-13 16:45:24 +000039#include "llvm/Transforms/Utils/BuildLibCalls.h"
Hiroshi Yamauchi09e539f2019-04-15 16:49:00 +000040#include "llvm/Transforms/Utils/SizeOpts.h"
Meador Ingedf796f82012-10-13 16:45:24 +000041
42using namespace llvm;
Sanjay Patelc699a612014-10-16 18:48:17 +000043using namespace PatternMatch;
Meador Ingedf796f82012-10-13 16:45:24 +000044
Hal Finkel66cd3f12013-11-17 02:06:35 +000045static cl::opt<bool>
Sanjay Patela92fa442014-10-22 15:29:23 +000046 EnableUnsafeFPShrink("enable-double-float-shrink", cl::Hidden,
47 cl::init(false),
48 cl::desc("Enable unsafe double to float "
49 "shrinking for math lib calls"));
50
Meador Ingedf796f82012-10-13 16:45:24 +000051//===----------------------------------------------------------------------===//
Meador Inged589ac62012-10-31 03:33:06 +000052// Helper Functions
53//===----------------------------------------------------------------------===//
54
David L. Jonesd21529f2017-01-23 23:16:46 +000055static bool ignoreCallingConv(LibFunc Func) {
56 return Func == LibFunc_abs || Func == LibFunc_labs ||
57 Func == LibFunc_llabs || Func == LibFunc_strlen;
Chris Bienemanad070d02014-09-17 20:55:46 +000058}
59
Sam Parker214f7bf2016-09-13 12:10:14 +000060static bool isCallingConvCCompatible(CallInst *CI) {
61 switch(CI->getCallingConv()) {
62 default:
63 return false;
64 case llvm::CallingConv::C:
65 return true;
66 case llvm::CallingConv::ARM_APCS:
67 case llvm::CallingConv::ARM_AAPCS:
68 case llvm::CallingConv::ARM_AAPCS_VFP: {
69
70 // The iOS ABI diverges from the standard in some cases, so for now don't
71 // try to simplify those calls.
72 if (Triple(CI->getModule()->getTargetTriple()).isiOS())
73 return false;
74
75 auto *FuncTy = CI->getFunctionType();
76
77 if (!FuncTy->getReturnType()->isPointerTy() &&
78 !FuncTy->getReturnType()->isIntegerTy() &&
79 !FuncTy->getReturnType()->isVoidTy())
80 return false;
81
82 for (auto Param : FuncTy->params()) {
83 if (!Param->isPointerTy() && !Param->isIntegerTy())
84 return false;
85 }
86 return true;
87 }
88 }
89 return false;
90}
91
Sanjay Pateld707db92015-12-31 16:10:49 +000092/// Return true if it is only used in equality comparisons with With.
Meador Inge56edbc92012-11-11 03:51:48 +000093static bool isOnlyUsedInEqualityComparison(Value *V, Value *With) {
Chandler Carruthcdf47882014-03-09 03:16:01 +000094 for (User *U : V->users()) {
95 if (ICmpInst *IC = dyn_cast<ICmpInst>(U))
Meador Inge56edbc92012-11-11 03:51:48 +000096 if (IC->isEquality() && IC->getOperand(1) == With)
97 continue;
98 // Unknown instruction.
99 return false;
100 }
101 return true;
102}
103
Meador Inge08ca1152012-11-26 20:37:20 +0000104static bool callHasFloatingPointArgument(const CallInst *CI) {
David Majnemer0a16c222016-08-11 21:15:00 +0000105 return any_of(CI->operands(), [](const Use &OI) {
Davide Italianoda3beeb2015-11-28 22:27:48 +0000106 return OI->getType()->isFloatingPointTy();
107 });
Meador Inge08ca1152012-11-26 20:37:20 +0000108}
109
Alon Zakaib4f99912019-04-03 01:08:35 +0000110static bool callHasFP128Argument(const CallInst *CI) {
111 return any_of(CI->operands(), [](const Use &OI) {
112 return OI->getType()->isFP128Ty();
113 });
114}
115
David Bolvanskycb8ca5f32018-04-25 18:58:53 +0000116static Value *convertStrToNumber(CallInst *CI, StringRef &Str, int64_t Base) {
117 if (Base < 2 || Base > 36)
118 // handle special zero base
119 if (Base != 0)
120 return nullptr;
121
122 char *End;
123 std::string nptr = Str.str();
124 errno = 0;
125 long long int Result = strtoll(nptr.c_str(), &End, Base);
126 if (errno)
127 return nullptr;
128
129 // if we assume all possible target locales are ASCII supersets,
130 // then if strtoll successfully parses a number on the host,
131 // it will also successfully parse the same way on the target
132 if (*End != '\0')
133 return nullptr;
134
135 if (!isIntN(CI->getType()->getPrimitiveSizeInBits(), Result))
136 return nullptr;
137
138 return ConstantInt::get(CI->getType(), Result);
139}
140
David Bolvanskyca22d422018-05-16 11:39:52 +0000141static bool isLocallyOpenedFile(Value *File, CallInst *CI, IRBuilder<> &B,
142 const TargetLibraryInfo *TLI) {
143 CallInst *FOpen = dyn_cast<CallInst>(File);
144 if (!FOpen)
145 return false;
146
147 Function *InnerCallee = FOpen->getCalledFunction();
148 if (!InnerCallee)
149 return false;
150
151 LibFunc Func;
152 if (!TLI->getLibFunc(*InnerCallee, Func) || !TLI->has(Func) ||
153 Func != LibFunc_fopen)
154 return false;
155
David Bolvansky7c7760d2018-10-16 21:18:31 +0000156 inferLibFuncAttributes(*CI->getCalledFunction(), *TLI);
David Bolvanskyca22d422018-05-16 11:39:52 +0000157 if (PointerMayBeCaptured(File, true, true))
158 return false;
159
160 return true;
161}
162
David Bolvansky909889b2018-08-10 04:32:54 +0000163static bool isOnlyUsedInComparisonWithZero(Value *V) {
164 for (User *U : V->users()) {
165 if (ICmpInst *IC = dyn_cast<ICmpInst>(U))
166 if (Constant *C = dyn_cast<Constant>(IC->getOperand(1)))
167 if (C->isNullValue())
168 continue;
169 // Unknown instruction.
170 return false;
171 }
172 return true;
173}
174
175static bool canTransformToMemCmp(CallInst *CI, Value *Str, uint64_t Len,
176 const DataLayout &DL) {
177 if (!isOnlyUsedInComparisonWithZero(CI))
178 return false;
179
180 if (!isDereferenceableAndAlignedPointer(Str, 1, APInt(64, Len), DL))
181 return false;
Matt Morehousee62fc3d2018-09-19 19:37:24 +0000182
183 if (CI->getFunction()->hasFnAttribute(Attribute::SanitizeMemory))
184 return false;
185
David Bolvansky909889b2018-08-10 04:32:54 +0000186 return true;
187}
188
David Bolvansky39130312019-08-13 09:11:49 +0000189static void annotateDereferenceableBytes(CallInst *CI,
190 ArrayRef<unsigned> ArgNos,
David Bolvansky90a30fd2019-08-13 16:44:16 +0000191 uint64_t DereferenceableBytes) {
David Bolvanskye80fcf02019-09-17 09:32:52 +0000192 const Function *F = CI->getCaller();
David Bolvanskyf94460d2019-08-14 17:15:20 +0000193 if (!F)
194 return;
David Bolvansky39130312019-08-13 09:11:49 +0000195 for (unsigned ArgNo : ArgNos) {
David Bolvanskyf94460d2019-08-14 17:15:20 +0000196 uint64_t DerefBytes = DereferenceableBytes;
197 unsigned AS = CI->getArgOperand(ArgNo)->getType()->getPointerAddressSpace();
David Bolvanskye80fcf02019-09-17 09:32:52 +0000198 if (!llvm::NullPointerIsDefined(F, AS) ||
199 CI->paramHasAttr(ArgNo, Attribute::NonNull))
David Bolvanskyf94460d2019-08-14 17:15:20 +0000200 DerefBytes = std::max(CI->getDereferenceableOrNullBytes(
201 ArgNo + AttributeList::FirstArgIndex),
202 DereferenceableBytes);
David Bolvanskye80fcf02019-09-17 09:32:52 +0000203
David Bolvansky39130312019-08-13 09:11:49 +0000204 if (CI->getDereferenceableBytes(ArgNo + AttributeList::FirstArgIndex) <
205 DerefBytes) {
206 CI->removeParamAttr(ArgNo, Attribute::Dereferenceable);
David Bolvanskye80fcf02019-09-17 09:32:52 +0000207 if (!llvm::NullPointerIsDefined(F, AS) ||
208 CI->paramHasAttr(ArgNo, Attribute::NonNull))
David Bolvanskyf94460d2019-08-14 17:15:20 +0000209 CI->removeParamAttr(ArgNo, Attribute::DereferenceableOrNull);
David Bolvansky39130312019-08-13 09:11:49 +0000210 CI->addParamAttr(ArgNo, Attribute::getWithDereferenceableBytes(
211 CI->getContext(), DerefBytes));
212 }
213 }
214}
215
David Bolvanskye80fcf02019-09-17 09:32:52 +0000216static void annotateNonNullBasedOnAccess(CallInst *CI,
217 ArrayRef<unsigned> ArgNos) {
218 Function *F = CI->getCaller();
219 if (!F)
220 return;
221
222 for (unsigned ArgNo : ArgNos) {
223 if (CI->paramHasAttr(ArgNo, Attribute::NonNull))
224 continue;
225 unsigned AS = CI->getArgOperand(ArgNo)->getType()->getPointerAddressSpace();
226 if (llvm::NullPointerIsDefined(F, AS))
227 continue;
228
229 CI->addParamAttr(ArgNo, Attribute::NonNull);
230 annotateDereferenceableBytes(CI, ArgNo, 1);
231 }
232}
233
234static void annotateNonNullAndDereferenceable(CallInst *CI, ArrayRef<unsigned> ArgNos,
235 Value *Size, const DataLayout &DL) {
236 if (ConstantInt *LenC = dyn_cast<ConstantInt>(Size)) {
237 annotateNonNullBasedOnAccess(CI, ArgNos);
238 annotateDereferenceableBytes(CI, ArgNos, LenC->getZExtValue());
239 } else if (isKnownNonZero(Size, DL)) {
240 annotateNonNullBasedOnAccess(CI, ArgNos);
241 const APInt *X, *Y;
242 uint64_t DerefMin = 1;
243 if (match(Size, m_Select(m_Value(), m_APInt(X), m_APInt(Y)))) {
244 DerefMin = std::min(X->getZExtValue(), Y->getZExtValue());
245 annotateDereferenceableBytes(CI, ArgNos, DerefMin);
246 }
247 }
248}
249
Meador Inged589ac62012-10-31 03:33:06 +0000250//===----------------------------------------------------------------------===//
Meador Inge7fb2f732012-10-13 16:45:32 +0000251// String and Memory Library Call Optimizations
252//===----------------------------------------------------------------------===//
253
Chris Bienemanad070d02014-09-17 20:55:46 +0000254Value *LibCallSimplifier::optimizeStrCat(CallInst *CI, IRBuilder<> &B) {
Chris Bienemanad070d02014-09-17 20:55:46 +0000255 // Extract some information from the instruction
256 Value *Dst = CI->getArgOperand(0);
257 Value *Src = CI->getArgOperand(1);
David Bolvanskye80fcf02019-09-17 09:32:52 +0000258 annotateNonNullBasedOnAccess(CI, {0, 1});
Chris Bienemanad070d02014-09-17 20:55:46 +0000259
260 // See if we can get the length of the input string.
David Bolvansky1f343fa2018-05-22 20:27:36 +0000261 uint64_t Len = GetStringLength(Src);
David Bolvanskye80fcf02019-09-17 09:32:52 +0000262 if (Len)
263 annotateDereferenceableBytes(CI, 1, Len);
264 else
Chris Bienemanad070d02014-09-17 20:55:46 +0000265 return nullptr;
266 --Len; // Unbias length.
267
268 // Handle the simple, do-nothing case: strcat(x, "") -> x
269 if (Len == 0)
270 return Dst;
271
Chris Bienemanad070d02014-09-17 20:55:46 +0000272 return emitStrLenMemCpy(Src, Dst, Len, B);
273}
274
275Value *LibCallSimplifier::emitStrLenMemCpy(Value *Src, Value *Dst, uint64_t Len,
276 IRBuilder<> &B) {
277 // We need to find the end of the destination string. That's where the
278 // memory is to be moved to. We just generate a call to strlen.
Sanjay Pateld3112a52016-01-19 19:46:10 +0000279 Value *DstLen = emitStrLen(Dst, B, DL, TLI);
Chris Bienemanad070d02014-09-17 20:55:46 +0000280 if (!DstLen)
281 return nullptr;
282
283 // Now that we have the destination's length, we must index into the
284 // destination's pointer to get the actual memcpy destination (end of
285 // the string .. we're concatenating).
David Blaikie3909da72015-03-30 20:42:56 +0000286 Value *CpyDst = B.CreateGEP(B.getInt8Ty(), Dst, DstLen, "endptr");
Chris Bienemanad070d02014-09-17 20:55:46 +0000287
288 // We have enough information to now generate the memcpy call to do the
289 // concatenation for us. Make a memcpy to copy the nul byte with align = 1.
Daniel Neilson8acd8b02018-02-05 21:23:22 +0000290 B.CreateMemCpy(CpyDst, 1, Src, 1,
291 ConstantInt::get(DL.getIntPtrType(Src->getContext()), Len + 1));
Chris Bienemanad070d02014-09-17 20:55:46 +0000292 return Dst;
293}
294
295Value *LibCallSimplifier::optimizeStrNCat(CallInst *CI, IRBuilder<> &B) {
Sanjay Pateld707db92015-12-31 16:10:49 +0000296 // Extract some information from the instruction.
Chris Bienemanad070d02014-09-17 20:55:46 +0000297 Value *Dst = CI->getArgOperand(0);
298 Value *Src = CI->getArgOperand(1);
David Bolvanskye80fcf02019-09-17 09:32:52 +0000299 Value *Size = CI->getArgOperand(2);
Chris Bienemanad070d02014-09-17 20:55:46 +0000300 uint64_t Len;
David Bolvanskye80fcf02019-09-17 09:32:52 +0000301 annotateNonNullBasedOnAccess(CI, 0);
302 if (isKnownNonZero(Size, DL))
303 annotateNonNullBasedOnAccess(CI, 1);
Chris Bienemanad070d02014-09-17 20:55:46 +0000304
Sanjay Pateld707db92015-12-31 16:10:49 +0000305 // We don't do anything if length is not constant.
David Bolvanskye80fcf02019-09-17 09:32:52 +0000306 ConstantInt *LengthArg = dyn_cast<ConstantInt>(Size);
307 if (LengthArg) {
Chris Bienemanad070d02014-09-17 20:55:46 +0000308 Len = LengthArg->getZExtValue();
David Bolvanskye80fcf02019-09-17 09:32:52 +0000309 // strncat(x, c, 0) -> x
310 if (!Len)
311 return Dst;
312 } else {
Chris Bienemanad070d02014-09-17 20:55:46 +0000313 return nullptr;
David Bolvanskye80fcf02019-09-17 09:32:52 +0000314 }
Chris Bienemanad070d02014-09-17 20:55:46 +0000315
316 // See if we can get the length of the input string.
David Bolvansky1f343fa2018-05-22 20:27:36 +0000317 uint64_t SrcLen = GetStringLength(Src);
David Bolvanskye80fcf02019-09-17 09:32:52 +0000318 if (SrcLen) {
319 annotateDereferenceableBytes(CI, 1, SrcLen);
320 --SrcLen; // Unbias length.
321 } else {
Chris Bienemanad070d02014-09-17 20:55:46 +0000322 return nullptr;
David Bolvanskye80fcf02019-09-17 09:32:52 +0000323 }
Chris Bienemanad070d02014-09-17 20:55:46 +0000324
Chris Bienemanad070d02014-09-17 20:55:46 +0000325 // strncat(x, "", c) -> x
David Bolvanskye80fcf02019-09-17 09:32:52 +0000326 if (SrcLen == 0)
Chris Bienemanad070d02014-09-17 20:55:46 +0000327 return Dst;
328
Sanjay Pateld707db92015-12-31 16:10:49 +0000329 // We don't optimize this case.
Chris Bienemanad070d02014-09-17 20:55:46 +0000330 if (Len < SrcLen)
331 return nullptr;
332
333 // strncat(x, s, c) -> strcat(x, s)
Sanjay Pateld707db92015-12-31 16:10:49 +0000334 // s is constant so the strcat can be optimized further.
Chris Bienemanad070d02014-09-17 20:55:46 +0000335 return emitStrLenMemCpy(Src, Dst, SrcLen, B);
336}
337
338Value *LibCallSimplifier::optimizeStrChr(CallInst *CI, IRBuilder<> &B) {
339 Function *Callee = CI->getCalledFunction();
Chris Bienemanad070d02014-09-17 20:55:46 +0000340 FunctionType *FT = Callee->getFunctionType();
Chris Bienemanad070d02014-09-17 20:55:46 +0000341 Value *SrcStr = CI->getArgOperand(0);
David Bolvanskye80fcf02019-09-17 09:32:52 +0000342 annotateNonNullBasedOnAccess(CI, 0);
Chris Bienemanad070d02014-09-17 20:55:46 +0000343
344 // If the second operand is non-constant, see if we can compute the length
345 // of the input string and turn this into memchr.
346 ConstantInt *CharC = dyn_cast<ConstantInt>(CI->getArgOperand(1));
347 if (!CharC) {
David Bolvansky1f343fa2018-05-22 20:27:36 +0000348 uint64_t Len = GetStringLength(SrcStr);
David Bolvanskye80fcf02019-09-17 09:32:52 +0000349 if (Len)
350 annotateDereferenceableBytes(CI, 0, Len);
351 else
352 return nullptr;
353 if (!FT->getParamType(1)->isIntegerTy(32)) // memchr needs i32.
Chris Bienemanad070d02014-09-17 20:55:46 +0000354 return nullptr;
Meador Inge7fb2f732012-10-13 16:45:32 +0000355
Sanjay Pateld3112a52016-01-19 19:46:10 +0000356 return emitMemChr(SrcStr, CI->getArgOperand(1), // include nul.
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000357 ConstantInt::get(DL.getIntPtrType(CI->getContext()), Len),
358 B, DL, TLI);
Meador Inge7fb2f732012-10-13 16:45:32 +0000359 }
360
Chris Bienemanad070d02014-09-17 20:55:46 +0000361 // Otherwise, the character is a constant, see if the first argument is
362 // a string literal. If so, we can constant fold.
363 StringRef Str;
364 if (!getConstantStringInfo(SrcStr, Str)) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000365 if (CharC->isZero()) // strchr(p, 0) -> p + strlen(p)
Sanjay Pateld3112a52016-01-19 19:46:10 +0000366 return B.CreateGEP(B.getInt8Ty(), SrcStr, emitStrLen(SrcStr, B, DL, TLI),
Sanjay Pateld707db92015-12-31 16:10:49 +0000367 "strchr");
Chris Bienemanad070d02014-09-17 20:55:46 +0000368 return nullptr;
369 }
370
371 // Compute the offset, make sure to handle the case when we're searching for
372 // zero (a weird way to spell strlen).
373 size_t I = (0xFF & CharC->getSExtValue()) == 0
374 ? Str.size()
375 : Str.find(CharC->getSExtValue());
376 if (I == StringRef::npos) // Didn't find the char. strchr returns null.
377 return Constant::getNullValue(CI->getType());
378
379 // strchr(s+n,c) -> gep(s+n+i,c)
David Blaikie3909da72015-03-30 20:42:56 +0000380 return B.CreateGEP(B.getInt8Ty(), SrcStr, B.getInt64(I), "strchr");
Chris Bienemanad070d02014-09-17 20:55:46 +0000381}
382
383Value *LibCallSimplifier::optimizeStrRChr(CallInst *CI, IRBuilder<> &B) {
Chris Bienemanad070d02014-09-17 20:55:46 +0000384 Value *SrcStr = CI->getArgOperand(0);
385 ConstantInt *CharC = dyn_cast<ConstantInt>(CI->getArgOperand(1));
David Bolvanskye80fcf02019-09-17 09:32:52 +0000386 annotateNonNullBasedOnAccess(CI, 0);
Chris Bienemanad070d02014-09-17 20:55:46 +0000387
388 // Cannot fold anything if we're not looking for a constant.
389 if (!CharC)
390 return nullptr;
391
392 StringRef Str;
393 if (!getConstantStringInfo(SrcStr, Str)) {
394 // strrchr(s, 0) -> strchr(s, 0)
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000395 if (CharC->isZero())
Sanjay Pateld3112a52016-01-19 19:46:10 +0000396 return emitStrChr(SrcStr, '\0', B, TLI);
Chris Bienemanad070d02014-09-17 20:55:46 +0000397 return nullptr;
398 }
399
400 // Compute the offset.
401 size_t I = (0xFF & CharC->getSExtValue()) == 0
402 ? Str.size()
403 : Str.rfind(CharC->getSExtValue());
404 if (I == StringRef::npos) // Didn't find the char. Return null.
405 return Constant::getNullValue(CI->getType());
406
407 // strrchr(s+n,c) -> gep(s+n+i,c)
David Blaikie3909da72015-03-30 20:42:56 +0000408 return B.CreateGEP(B.getInt8Ty(), SrcStr, B.getInt64(I), "strrchr");
Chris Bienemanad070d02014-09-17 20:55:46 +0000409}
410
411Value *LibCallSimplifier::optimizeStrCmp(CallInst *CI, IRBuilder<> &B) {
Chris Bienemanad070d02014-09-17 20:55:46 +0000412 Value *Str1P = CI->getArgOperand(0), *Str2P = CI->getArgOperand(1);
413 if (Str1P == Str2P) // strcmp(x,x) -> 0
414 return ConstantInt::get(CI->getType(), 0);
415
416 StringRef Str1, Str2;
417 bool HasStr1 = getConstantStringInfo(Str1P, Str1);
418 bool HasStr2 = getConstantStringInfo(Str2P, Str2);
419
420 // strcmp(x, y) -> cnst (if both x and y are constant strings)
421 if (HasStr1 && HasStr2)
422 return ConstantInt::get(CI->getType(), Str1.compare(Str2));
423
424 if (HasStr1 && Str1.empty()) // strcmp("", x) -> -*x
James Y Knight14359ef2019-02-01 20:44:24 +0000425 return B.CreateNeg(B.CreateZExt(
426 B.CreateLoad(B.getInt8Ty(), Str2P, "strcmpload"), CI->getType()));
Chris Bienemanad070d02014-09-17 20:55:46 +0000427
428 if (HasStr2 && Str2.empty()) // strcmp(x,"") -> *x
James Y Knight14359ef2019-02-01 20:44:24 +0000429 return B.CreateZExt(B.CreateLoad(B.getInt8Ty(), Str1P, "strcmpload"),
430 CI->getType());
Chris Bienemanad070d02014-09-17 20:55:46 +0000431
432 // strcmp(P, "x") -> memcmp(P, "x", 2)
David Bolvansky1f343fa2018-05-22 20:27:36 +0000433 uint64_t Len1 = GetStringLength(Str1P);
David Bolvanskye80fcf02019-09-17 09:32:52 +0000434 if (Len1)
435 annotateDereferenceableBytes(CI, 0, Len1);
David Bolvansky1f343fa2018-05-22 20:27:36 +0000436 uint64_t Len2 = GetStringLength(Str2P);
David Bolvanskye80fcf02019-09-17 09:32:52 +0000437 if (Len2)
438 annotateDereferenceableBytes(CI, 1, Len2);
439
Chris Bienemanad070d02014-09-17 20:55:46 +0000440 if (Len1 && Len2) {
Sanjay Pateld3112a52016-01-19 19:46:10 +0000441 return emitMemCmp(Str1P, Str2P,
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000442 ConstantInt::get(DL.getIntPtrType(CI->getContext()),
Chris Bienemanad070d02014-09-17 20:55:46 +0000443 std::min(Len1, Len2)),
444 B, DL, TLI);
445 }
Meador Inge7fb2f732012-10-13 16:45:32 +0000446
David Bolvansky909889b2018-08-10 04:32:54 +0000447 // strcmp to memcmp
448 if (!HasStr1 && HasStr2) {
449 if (canTransformToMemCmp(CI, Str1P, Len2, DL))
450 return emitMemCmp(
451 Str1P, Str2P,
452 ConstantInt::get(DL.getIntPtrType(CI->getContext()), Len2), B, DL,
453 TLI);
454 } else if (HasStr1 && !HasStr2) {
455 if (canTransformToMemCmp(CI, Str2P, Len1, DL))
456 return emitMemCmp(
457 Str1P, Str2P,
458 ConstantInt::get(DL.getIntPtrType(CI->getContext()), Len1), B, DL,
459 TLI);
460 }
461
David Bolvanskye80fcf02019-09-17 09:32:52 +0000462 annotateNonNullBasedOnAccess(CI, {0, 1});
Chris Bienemanad070d02014-09-17 20:55:46 +0000463 return nullptr;
464}
465
466Value *LibCallSimplifier::optimizeStrNCmp(CallInst *CI, IRBuilder<> &B) {
David Bolvanskye80fcf02019-09-17 09:32:52 +0000467 Value *Str1P = CI->getArgOperand(0);
468 Value *Str2P = CI->getArgOperand(1);
469 Value *Size = CI->getArgOperand(2);
Chris Bienemanad070d02014-09-17 20:55:46 +0000470 if (Str1P == Str2P) // strncmp(x,x,n) -> 0
471 return ConstantInt::get(CI->getType(), 0);
472
David Bolvanskye80fcf02019-09-17 09:32:52 +0000473 if (isKnownNonZero(Size, DL))
474 annotateNonNullBasedOnAccess(CI, {0, 1});
Chris Bienemanad070d02014-09-17 20:55:46 +0000475 // Get the length argument if it is constant.
476 uint64_t Length;
David Bolvanskye80fcf02019-09-17 09:32:52 +0000477 if (ConstantInt *LengthArg = dyn_cast<ConstantInt>(Size))
Chris Bienemanad070d02014-09-17 20:55:46 +0000478 Length = LengthArg->getZExtValue();
479 else
480 return nullptr;
481
482 if (Length == 0) // strncmp(x,y,0) -> 0
483 return ConstantInt::get(CI->getType(), 0);
484
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000485 if (Length == 1) // strncmp(x,y,1) -> memcmp(x,y,1)
David Bolvanskye80fcf02019-09-17 09:32:52 +0000486 return emitMemCmp(Str1P, Str2P, Size, B, DL, TLI);
Chris Bienemanad070d02014-09-17 20:55:46 +0000487
488 StringRef Str1, Str2;
489 bool HasStr1 = getConstantStringInfo(Str1P, Str1);
490 bool HasStr2 = getConstantStringInfo(Str2P, Str2);
491
492 // strncmp(x, y) -> cnst (if both x and y are constant strings)
493 if (HasStr1 && HasStr2) {
494 StringRef SubStr1 = Str1.substr(0, Length);
495 StringRef SubStr2 = Str2.substr(0, Length);
496 return ConstantInt::get(CI->getType(), SubStr1.compare(SubStr2));
497 }
498
499 if (HasStr1 && Str1.empty()) // strncmp("", x, n) -> -*x
James Y Knight14359ef2019-02-01 20:44:24 +0000500 return B.CreateNeg(B.CreateZExt(
501 B.CreateLoad(B.getInt8Ty(), Str2P, "strcmpload"), CI->getType()));
Chris Bienemanad070d02014-09-17 20:55:46 +0000502
503 if (HasStr2 && Str2.empty()) // strncmp(x, "", n) -> *x
James Y Knight14359ef2019-02-01 20:44:24 +0000504 return B.CreateZExt(B.CreateLoad(B.getInt8Ty(), Str1P, "strcmpload"),
505 CI->getType());
Chris Bienemanad070d02014-09-17 20:55:46 +0000506
David Bolvansky909889b2018-08-10 04:32:54 +0000507 uint64_t Len1 = GetStringLength(Str1P);
David Bolvanskye80fcf02019-09-17 09:32:52 +0000508 if (Len1)
509 annotateDereferenceableBytes(CI, 0, Len1);
David Bolvansky909889b2018-08-10 04:32:54 +0000510 uint64_t Len2 = GetStringLength(Str2P);
David Bolvanskye80fcf02019-09-17 09:32:52 +0000511 if (Len2)
512 annotateDereferenceableBytes(CI, 1, Len2);
David Bolvansky909889b2018-08-10 04:32:54 +0000513
514 // strncmp to memcmp
515 if (!HasStr1 && HasStr2) {
516 Len2 = std::min(Len2, Length);
517 if (canTransformToMemCmp(CI, Str1P, Len2, DL))
518 return emitMemCmp(
519 Str1P, Str2P,
520 ConstantInt::get(DL.getIntPtrType(CI->getContext()), Len2), B, DL,
521 TLI);
522 } else if (HasStr1 && !HasStr2) {
523 Len1 = std::min(Len1, Length);
524 if (canTransformToMemCmp(CI, Str2P, Len1, DL))
525 return emitMemCmp(
526 Str1P, Str2P,
527 ConstantInt::get(DL.getIntPtrType(CI->getContext()), Len1), B, DL,
528 TLI);
529 }
530
Chris Bienemanad070d02014-09-17 20:55:46 +0000531 return nullptr;
532}
533
David Bolvansky8d520162019-09-23 18:20:01 +0000534Value *LibCallSimplifier::optimizeStrNDup(CallInst *CI, IRBuilder<> &B) {
535 Value *Src = CI->getArgOperand(0);
536 ConstantInt *Size = dyn_cast<ConstantInt>(CI->getArgOperand(1));
537 uint64_t SrcLen = GetStringLength(Src);
538 if (SrcLen && Size) {
539 annotateDereferenceableBytes(CI, 0, SrcLen);
540 if (SrcLen <= Size->getZExtValue() + 1)
541 return emitStrDup(Src, B, TLI);
542 }
543
544 return nullptr;
545}
546
Chris Bienemanad070d02014-09-17 20:55:46 +0000547Value *LibCallSimplifier::optimizeStrCpy(CallInst *CI, IRBuilder<> &B) {
Chris Bienemanad070d02014-09-17 20:55:46 +0000548 Value *Dst = CI->getArgOperand(0), *Src = CI->getArgOperand(1);
549 if (Dst == Src) // strcpy(x,x) -> x
550 return Src;
David Bolvanskye80fcf02019-09-17 09:32:52 +0000551
552 annotateNonNullBasedOnAccess(CI, {0, 1});
Chris Bienemanad070d02014-09-17 20:55:46 +0000553 // See if we can get the length of the input string.
David Bolvansky1f343fa2018-05-22 20:27:36 +0000554 uint64_t Len = GetStringLength(Src);
David Bolvanskye80fcf02019-09-17 09:32:52 +0000555 if (Len)
556 annotateDereferenceableBytes(CI, 1, Len);
557 else
Chris Bienemanad070d02014-09-17 20:55:46 +0000558 return nullptr;
559
560 // We have enough information to now generate the memcpy call to do the
561 // copy for us. Make a memcpy to copy the nul byte with align = 1.
David Bolvanskye80fcf02019-09-17 09:32:52 +0000562 CallInst *NewCI =
563 B.CreateMemCpy(Dst, 1, Src, 1,
564 ConstantInt::get(DL.getIntPtrType(CI->getContext()), Len));
565 NewCI->setAttributes(CI->getAttributes());
Chris Bienemanad070d02014-09-17 20:55:46 +0000566 return Dst;
567}
568
569Value *LibCallSimplifier::optimizeStpCpy(CallInst *CI, IRBuilder<> &B) {
570 Function *Callee = CI->getCalledFunction();
Chris Bienemanad070d02014-09-17 20:55:46 +0000571 Value *Dst = CI->getArgOperand(0), *Src = CI->getArgOperand(1);
572 if (Dst == Src) { // stpcpy(x,x) -> x+strlen(x)
Sanjay Pateld3112a52016-01-19 19:46:10 +0000573 Value *StrLen = emitStrLen(Src, B, DL, TLI);
David Blaikieaa41cd52015-04-03 21:33:42 +0000574 return StrLen ? B.CreateInBoundsGEP(B.getInt8Ty(), Dst, StrLen) : nullptr;
Chris Bienemanad070d02014-09-17 20:55:46 +0000575 }
576
577 // See if we can get the length of the input string.
David Bolvansky1f343fa2018-05-22 20:27:36 +0000578 uint64_t Len = GetStringLength(Src);
David Bolvanskye80fcf02019-09-17 09:32:52 +0000579 if (Len)
580 annotateDereferenceableBytes(CI, 1, Len);
581 else
Chris Bienemanad070d02014-09-17 20:55:46 +0000582 return nullptr;
583
Davide Italianob7487e62015-11-02 23:07:14 +0000584 Type *PT = Callee->getFunctionType()->getParamType(0);
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000585 Value *LenV = ConstantInt::get(DL.getIntPtrType(PT), Len);
Sanjay Pateld707db92015-12-31 16:10:49 +0000586 Value *DstEnd = B.CreateGEP(B.getInt8Ty(), Dst,
587 ConstantInt::get(DL.getIntPtrType(PT), Len - 1));
Chris Bienemanad070d02014-09-17 20:55:46 +0000588
589 // We have enough information to now generate the memcpy call to do the
590 // copy for us. Make a memcpy to copy the nul byte with align = 1.
David Bolvanskye80fcf02019-09-17 09:32:52 +0000591 CallInst *NewCI = B.CreateMemCpy(Dst, 1, Src, 1, LenV);
592 NewCI->setAttributes(CI->getAttributes());
Chris Bienemanad070d02014-09-17 20:55:46 +0000593 return DstEnd;
594}
595
596Value *LibCallSimplifier::optimizeStrNCpy(CallInst *CI, IRBuilder<> &B) {
597 Function *Callee = CI->getCalledFunction();
Chris Bienemanad070d02014-09-17 20:55:46 +0000598 Value *Dst = CI->getArgOperand(0);
599 Value *Src = CI->getArgOperand(1);
David Bolvanskye80fcf02019-09-17 09:32:52 +0000600 Value *Size = CI->getArgOperand(2);
601 annotateNonNullBasedOnAccess(CI, 0);
602 if (isKnownNonZero(Size, DL))
603 annotateNonNullBasedOnAccess(CI, 1);
Meador Inge7fb2f732012-10-13 16:45:32 +0000604
Chris Bienemanad070d02014-09-17 20:55:46 +0000605 uint64_t Len;
David Bolvanskye80fcf02019-09-17 09:32:52 +0000606 if (ConstantInt *LengthArg = dyn_cast<ConstantInt>(Size))
Chris Bienemanad070d02014-09-17 20:55:46 +0000607 Len = LengthArg->getZExtValue();
608 else
609 return nullptr;
Meador Inge7fb2f732012-10-13 16:45:32 +0000610
David Bolvanskye80fcf02019-09-17 09:32:52 +0000611 // strncpy(x, y, 0) -> x
Chris Bienemanad070d02014-09-17 20:55:46 +0000612 if (Len == 0)
David Bolvanskye80fcf02019-09-17 09:32:52 +0000613 return Dst;
614
615 // See if we can get the length of the input string.
616 uint64_t SrcLen = GetStringLength(Src);
617 if (SrcLen) {
618 annotateDereferenceableBytes(CI, 1, SrcLen);
619 --SrcLen; // Unbias length.
620 } else {
621 return nullptr;
622 }
623
624 if (SrcLen == 0) {
625 // strncpy(x, "", y) -> memset(align 1 x, '\0', y)
David Bolvansky0c0de792019-09-17 17:12:24 +0000626 CallInst *NewCI = B.CreateMemSet(Dst, B.getInt8('\0'), Size, 1);
627 AttrBuilder ArgAttrs(CI->getAttributes().getParamAttributes(0));
628 NewCI->setAttributes(NewCI->getAttributes().addParamAttributes(
629 CI->getContext(), 0, ArgAttrs));
David Bolvanskye80fcf02019-09-17 09:32:52 +0000630 return Dst;
631 }
Meador Inge7fb2f732012-10-13 16:45:32 +0000632
Chris Bienemanad070d02014-09-17 20:55:46 +0000633 // Let strncpy handle the zero padding
634 if (Len > SrcLen + 1)
635 return nullptr;
Meador Inge7fb2f732012-10-13 16:45:32 +0000636
Davide Italianob7487e62015-11-02 23:07:14 +0000637 Type *PT = Callee->getFunctionType()->getParamType(0);
Daniel Neilson8acd8b02018-02-05 21:23:22 +0000638 // strncpy(x, s, c) -> memcpy(align 1 x, align 1 s, c) [s and c are constant]
David Bolvanskye80fcf02019-09-17 09:32:52 +0000639 CallInst *NewCI = B.CreateMemCpy(Dst, 1, Src, 1, ConstantInt::get(DL.getIntPtrType(PT), Len));
David Bolvanskye80fcf02019-09-17 09:32:52 +0000640 NewCI->setAttributes(CI->getAttributes());
Chris Bienemanad070d02014-09-17 20:55:46 +0000641 return Dst;
642}
Meador Inge7fb2f732012-10-13 16:45:32 +0000643
Matthias Braun50ec0b52017-05-19 22:37:09 +0000644Value *LibCallSimplifier::optimizeStringLength(CallInst *CI, IRBuilder<> &B,
645 unsigned CharSize) {
Chris Bienemanad070d02014-09-17 20:55:46 +0000646 Value *Src = CI->getArgOperand(0);
647
648 // Constant folding: strlen("xyz") -> 3
David Bolvansky1f343fa2018-05-22 20:27:36 +0000649 if (uint64_t Len = GetStringLength(Src, CharSize))
Chris Bienemanad070d02014-09-17 20:55:46 +0000650 return ConstantInt::get(CI->getType(), Len - 1);
651
David L Kreitzer752c1442016-04-13 14:31:06 +0000652 // If s is a constant pointer pointing to a string literal, we can fold
Matthias Braun50ec0b52017-05-19 22:37:09 +0000653 // strlen(s + x) to strlen(s) - x, when x is known to be in the range
David L Kreitzer752c1442016-04-13 14:31:06 +0000654 // [0, strlen(s)] or the string has a single null terminator '\0' at the end.
Matthias Braun50ec0b52017-05-19 22:37:09 +0000655 // We only try to simplify strlen when the pointer s points to an array
David L Kreitzer752c1442016-04-13 14:31:06 +0000656 // of i8. Otherwise, we would need to scale the offset x before doing the
Matthias Braun50ec0b52017-05-19 22:37:09 +0000657 // subtraction. This will make the optimization more complex, and it's not
658 // very useful because calling strlen for a pointer of other types is
David L Kreitzer752c1442016-04-13 14:31:06 +0000659 // very uncommon.
660 if (GEPOperator *GEP = dyn_cast<GEPOperator>(Src)) {
Matthias Braun50ec0b52017-05-19 22:37:09 +0000661 if (!isGEPBasedOnPointerToString(GEP, CharSize))
David L Kreitzer752c1442016-04-13 14:31:06 +0000662 return nullptr;
663
Matthias Braun50ec0b52017-05-19 22:37:09 +0000664 ConstantDataArraySlice Slice;
665 if (getConstantDataArrayInfo(GEP->getOperand(0), Slice, CharSize)) {
666 uint64_t NullTermIdx;
667 if (Slice.Array == nullptr) {
668 NullTermIdx = 0;
669 } else {
670 NullTermIdx = ~((uint64_t)0);
671 for (uint64_t I = 0, E = Slice.Length; I < E; ++I) {
672 if (Slice.Array->getElementAsInteger(I + Slice.Offset) == 0) {
673 NullTermIdx = I;
674 break;
675 }
676 }
677 // If the string does not have '\0', leave it to strlen to compute
678 // its length.
679 if (NullTermIdx == ~((uint64_t)0))
680 return nullptr;
681 }
682
David L Kreitzer752c1442016-04-13 14:31:06 +0000683 Value *Offset = GEP->getOperand(2);
Craig Topper8205a1a2017-05-24 16:53:07 +0000684 KnownBits Known = computeKnownBits(Offset, DL, 0, nullptr, CI, nullptr);
Craig Topperb45eabc2017-04-26 16:39:58 +0000685 Known.Zero.flipAllBits();
Matthias Braun50ec0b52017-05-19 22:37:09 +0000686 uint64_t ArrSize =
David L Kreitzer752c1442016-04-13 14:31:06 +0000687 cast<ArrayType>(GEP->getSourceElementType())->getNumElements();
688
Matthias Braun50ec0b52017-05-19 22:37:09 +0000689 // KnownZero's bits are flipped, so zeros in KnownZero now represent
690 // bits known to be zeros in Offset, and ones in KnowZero represent
David L Kreitzer752c1442016-04-13 14:31:06 +0000691 // bits unknown in Offset. Therefore, Offset is known to be in range
Matthias Braun50ec0b52017-05-19 22:37:09 +0000692 // [0, NullTermIdx] when the flipped KnownZero is non-negative and
David L Kreitzer752c1442016-04-13 14:31:06 +0000693 // unsigned-less-than NullTermIdx.
694 //
Matthias Braun50ec0b52017-05-19 22:37:09 +0000695 // If Offset is not provably in the range [0, NullTermIdx], we can still
696 // optimize if we can prove that the program has undefined behavior when
697 // Offset is outside that range. That is the case when GEP->getOperand(0)
David L Kreitzer752c1442016-04-13 14:31:06 +0000698 // is a pointer to an object whose memory extent is NullTermIdx+1.
Matthias Braun50ec0b52017-05-19 22:37:09 +0000699 if ((Known.Zero.isNonNegative() && Known.Zero.ule(NullTermIdx)) ||
David L Kreitzer752c1442016-04-13 14:31:06 +0000700 (GEP->isInBounds() && isa<GlobalVariable>(GEP->getOperand(0)) &&
Matthias Braun50ec0b52017-05-19 22:37:09 +0000701 NullTermIdx == ArrSize - 1)) {
702 Offset = B.CreateSExtOrTrunc(Offset, CI->getType());
703 return B.CreateSub(ConstantInt::get(CI->getType(), NullTermIdx),
David L Kreitzer752c1442016-04-13 14:31:06 +0000704 Offset);
Matthias Braun50ec0b52017-05-19 22:37:09 +0000705 }
David L Kreitzer752c1442016-04-13 14:31:06 +0000706 }
707
708 return nullptr;
709 }
710
Chris Bienemanad070d02014-09-17 20:55:46 +0000711 // strlen(x?"foo":"bars") --> x ? 3 : 4
712 if (SelectInst *SI = dyn_cast<SelectInst>(Src)) {
David Bolvansky1f343fa2018-05-22 20:27:36 +0000713 uint64_t LenTrue = GetStringLength(SI->getTrueValue(), CharSize);
714 uint64_t LenFalse = GetStringLength(SI->getFalseValue(), CharSize);
Chris Bienemanad070d02014-09-17 20:55:46 +0000715 if (LenTrue && LenFalse) {
Vivek Pandya95906582017-10-11 17:12:59 +0000716 ORE.emit([&]() {
717 return OptimizationRemark("instcombine", "simplify-libcalls", CI)
718 << "folded strlen(select) to select of constants";
719 });
Chris Bienemanad070d02014-09-17 20:55:46 +0000720 return B.CreateSelect(SI->getCondition(),
721 ConstantInt::get(CI->getType(), LenTrue - 1),
722 ConstantInt::get(CI->getType(), LenFalse - 1));
723 }
Meador Inge7fb2f732012-10-13 16:45:32 +0000724 }
Meador Inge7fb2f732012-10-13 16:45:32 +0000725
Chris Bienemanad070d02014-09-17 20:55:46 +0000726 // strlen(x) != 0 --> *x != 0
727 // strlen(x) == 0 --> *x == 0
728 if (isOnlyUsedInZeroEqualityComparison(CI))
James Y Knight14359ef2019-02-01 20:44:24 +0000729 return B.CreateZExt(B.CreateLoad(B.getIntNTy(CharSize), Src, "strlenfirst"),
730 CI->getType());
Meador Inge17418502012-10-13 16:45:37 +0000731
Chris Bienemanad070d02014-09-17 20:55:46 +0000732 return nullptr;
733}
Meador Inge17418502012-10-13 16:45:37 +0000734
Matthias Braun50ec0b52017-05-19 22:37:09 +0000735Value *LibCallSimplifier::optimizeStrLen(CallInst *CI, IRBuilder<> &B) {
David Bolvanskye80fcf02019-09-17 09:32:52 +0000736 if (Value *V = optimizeStringLength(CI, B, 8))
737 return V;
738 annotateNonNullBasedOnAccess(CI, 0);
739 return nullptr;
Matthias Braun50ec0b52017-05-19 22:37:09 +0000740}
741
742Value *LibCallSimplifier::optimizeWcslen(CallInst *CI, IRBuilder<> &B) {
David Bolvansky5430b7372018-05-31 16:39:27 +0000743 Module &M = *CI->getModule();
Matthias Braun50ec0b52017-05-19 22:37:09 +0000744 unsigned WCharSize = TLI->getWCharSize(M) * 8;
Matthias Brauncc603ee2017-09-26 02:36:57 +0000745 // We cannot perform this optimization without wchar_size metadata.
746 if (WCharSize == 0)
747 return nullptr;
Matthias Braun50ec0b52017-05-19 22:37:09 +0000748
749 return optimizeStringLength(CI, B, WCharSize);
750}
751
Chris Bienemanad070d02014-09-17 20:55:46 +0000752Value *LibCallSimplifier::optimizeStrPBrk(CallInst *CI, IRBuilder<> &B) {
Chris Bienemanad070d02014-09-17 20:55:46 +0000753 StringRef S1, S2;
754 bool HasS1 = getConstantStringInfo(CI->getArgOperand(0), S1);
755 bool HasS2 = getConstantStringInfo(CI->getArgOperand(1), S2);
Meador Inge17418502012-10-13 16:45:37 +0000756
Reid Kleckner971c3ea2014-11-13 22:55:19 +0000757 // strpbrk(s, "") -> nullptr
758 // strpbrk("", s) -> nullptr
Chris Bienemanad070d02014-09-17 20:55:46 +0000759 if ((HasS1 && S1.empty()) || (HasS2 && S2.empty()))
760 return Constant::getNullValue(CI->getType());
Meador Inge17418502012-10-13 16:45:37 +0000761
Chris Bienemanad070d02014-09-17 20:55:46 +0000762 // Constant folding.
763 if (HasS1 && HasS2) {
764 size_t I = S1.find_first_of(S2);
765 if (I == StringRef::npos) // No match.
Meador Inge17418502012-10-13 16:45:37 +0000766 return Constant::getNullValue(CI->getType());
767
Sanjay Pateld707db92015-12-31 16:10:49 +0000768 return B.CreateGEP(B.getInt8Ty(), CI->getArgOperand(0), B.getInt64(I),
769 "strpbrk");
Meador Inge17418502012-10-13 16:45:37 +0000770 }
Meador Inge17418502012-10-13 16:45:37 +0000771
Chris Bienemanad070d02014-09-17 20:55:46 +0000772 // strpbrk(s, "a") -> strchr(s, 'a')
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000773 if (HasS2 && S2.size() == 1)
Sanjay Pateld3112a52016-01-19 19:46:10 +0000774 return emitStrChr(CI->getArgOperand(0), S2[0], B, TLI);
Chris Bienemanad070d02014-09-17 20:55:46 +0000775
776 return nullptr;
777}
778
779Value *LibCallSimplifier::optimizeStrTo(CallInst *CI, IRBuilder<> &B) {
Chris Bienemanad070d02014-09-17 20:55:46 +0000780 Value *EndPtr = CI->getArgOperand(1);
781 if (isa<ConstantPointerNull>(EndPtr)) {
782 // With a null EndPtr, this function won't capture the main argument.
783 // It would be readonly too, except that it still may write to errno.
Reid Klecknera0b45f42017-05-03 18:17:31 +0000784 CI->addParamAttr(0, Attribute::NoCapture);
Chris Bienemanad070d02014-09-17 20:55:46 +0000785 }
786
787 return nullptr;
788}
789
790Value *LibCallSimplifier::optimizeStrSpn(CallInst *CI, IRBuilder<> &B) {
Chris Bienemanad070d02014-09-17 20:55:46 +0000791 StringRef S1, S2;
792 bool HasS1 = getConstantStringInfo(CI->getArgOperand(0), S1);
793 bool HasS2 = getConstantStringInfo(CI->getArgOperand(1), S2);
794
795 // strspn(s, "") -> 0
796 // strspn("", s) -> 0
797 if ((HasS1 && S1.empty()) || (HasS2 && S2.empty()))
798 return Constant::getNullValue(CI->getType());
799
800 // Constant folding.
801 if (HasS1 && HasS2) {
802 size_t Pos = S1.find_first_not_of(S2);
803 if (Pos == StringRef::npos)
804 Pos = S1.size();
805 return ConstantInt::get(CI->getType(), Pos);
806 }
807
808 return nullptr;
809}
810
811Value *LibCallSimplifier::optimizeStrCSpn(CallInst *CI, IRBuilder<> &B) {
Chris Bienemanad070d02014-09-17 20:55:46 +0000812 StringRef S1, S2;
813 bool HasS1 = getConstantStringInfo(CI->getArgOperand(0), S1);
814 bool HasS2 = getConstantStringInfo(CI->getArgOperand(1), S2);
815
816 // strcspn("", s) -> 0
817 if (HasS1 && S1.empty())
818 return Constant::getNullValue(CI->getType());
819
820 // Constant folding.
821 if (HasS1 && HasS2) {
822 size_t Pos = S1.find_first_of(S2);
823 if (Pos == StringRef::npos)
824 Pos = S1.size();
825 return ConstantInt::get(CI->getType(), Pos);
826 }
827
828 // strcspn(s, "") -> strlen(s)
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000829 if (HasS2 && S2.empty())
Sanjay Pateld3112a52016-01-19 19:46:10 +0000830 return emitStrLen(CI->getArgOperand(0), B, DL, TLI);
Chris Bienemanad070d02014-09-17 20:55:46 +0000831
832 return nullptr;
833}
834
835Value *LibCallSimplifier::optimizeStrStr(CallInst *CI, IRBuilder<> &B) {
Chris Bienemanad070d02014-09-17 20:55:46 +0000836 // fold strstr(x, x) -> x.
837 if (CI->getArgOperand(0) == CI->getArgOperand(1))
838 return B.CreateBitCast(CI->getArgOperand(0), CI->getType());
839
840 // fold strstr(a, b) == a -> strncmp(a, b, strlen(b)) == 0
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000841 if (isOnlyUsedInEqualityComparison(CI, CI->getArgOperand(0))) {
Sanjay Pateld3112a52016-01-19 19:46:10 +0000842 Value *StrLen = emitStrLen(CI->getArgOperand(1), B, DL, TLI);
Chris Bienemanad070d02014-09-17 20:55:46 +0000843 if (!StrLen)
Craig Topperf40110f2014-04-25 05:29:35 +0000844 return nullptr;
Sanjay Pateld3112a52016-01-19 19:46:10 +0000845 Value *StrNCmp = emitStrNCmp(CI->getArgOperand(0), CI->getArgOperand(1),
Chris Bienemanad070d02014-09-17 20:55:46 +0000846 StrLen, B, DL, TLI);
847 if (!StrNCmp)
Craig Topperf40110f2014-04-25 05:29:35 +0000848 return nullptr;
Chris Bienemanad070d02014-09-17 20:55:46 +0000849 for (auto UI = CI->user_begin(), UE = CI->user_end(); UI != UE;) {
850 ICmpInst *Old = cast<ICmpInst>(*UI++);
851 Value *Cmp =
852 B.CreateICmp(Old->getPredicate(), StrNCmp,
853 ConstantInt::getNullValue(StrNCmp->getType()), "cmp");
854 replaceAllUsesWith(Old, Cmp);
Meador Inge17418502012-10-13 16:45:37 +0000855 }
Chris Bienemanad070d02014-09-17 20:55:46 +0000856 return CI;
857 }
Meador Inge17418502012-10-13 16:45:37 +0000858
Chris Bienemanad070d02014-09-17 20:55:46 +0000859 // See if either input string is a constant string.
860 StringRef SearchStr, ToFindStr;
861 bool HasStr1 = getConstantStringInfo(CI->getArgOperand(0), SearchStr);
862 bool HasStr2 = getConstantStringInfo(CI->getArgOperand(1), ToFindStr);
863
864 // fold strstr(x, "") -> x.
865 if (HasStr2 && ToFindStr.empty())
866 return B.CreateBitCast(CI->getArgOperand(0), CI->getType());
867
868 // If both strings are known, constant fold it.
869 if (HasStr1 && HasStr2) {
870 size_t Offset = SearchStr.find(ToFindStr);
871
872 if (Offset == StringRef::npos) // strstr("foo", "bar") -> null
Meador Inge17418502012-10-13 16:45:37 +0000873 return Constant::getNullValue(CI->getType());
874
Chris Bienemanad070d02014-09-17 20:55:46 +0000875 // strstr("abcd", "bc") -> gep((char*)"abcd", 1)
Sanjay Pateld3112a52016-01-19 19:46:10 +0000876 Value *Result = castToCStr(CI->getArgOperand(0), B);
James Y Knight77160752019-02-01 20:44:47 +0000877 Result =
878 B.CreateConstInBoundsGEP1_64(B.getInt8Ty(), Result, Offset, "strstr");
Chris Bienemanad070d02014-09-17 20:55:46 +0000879 return B.CreateBitCast(Result, CI->getType());
Meador Inge17418502012-10-13 16:45:37 +0000880 }
Meador Inge17418502012-10-13 16:45:37 +0000881
Chris Bienemanad070d02014-09-17 20:55:46 +0000882 // fold strstr(x, "y") -> strchr(x, 'y').
883 if (HasStr2 && ToFindStr.size() == 1) {
Sanjay Pateld3112a52016-01-19 19:46:10 +0000884 Value *StrChr = emitStrChr(CI->getArgOperand(0), ToFindStr[0], B, TLI);
Chris Bienemanad070d02014-09-17 20:55:46 +0000885 return StrChr ? B.CreateBitCast(StrChr, CI->getType()) : nullptr;
886 }
David Bolvanskye80fcf02019-09-17 09:32:52 +0000887
888 annotateNonNullBasedOnAccess(CI, {0, 1});
889 return nullptr;
890}
891
892Value *LibCallSimplifier::optimizeMemRChr(CallInst *CI, IRBuilder<> &B) {
893 if (isKnownNonZero(CI->getOperand(2), DL))
894 annotateNonNullBasedOnAccess(CI, 0);
Chris Bienemanad070d02014-09-17 20:55:46 +0000895 return nullptr;
896}
Meador Inge40b6fac2012-10-15 03:47:37 +0000897
Benjamin Kramer691363e2015-03-21 15:36:21 +0000898Value *LibCallSimplifier::optimizeMemChr(CallInst *CI, IRBuilder<> &B) {
Benjamin Kramer691363e2015-03-21 15:36:21 +0000899 Value *SrcStr = CI->getArgOperand(0);
David Bolvanskye80fcf02019-09-17 09:32:52 +0000900 Value *Size = CI->getArgOperand(2);
901 annotateNonNullAndDereferenceable(CI, 0, Size, DL);
Benjamin Kramer691363e2015-03-21 15:36:21 +0000902 ConstantInt *CharC = dyn_cast<ConstantInt>(CI->getArgOperand(1));
David Bolvanskye80fcf02019-09-17 09:32:52 +0000903 ConstantInt *LenC = dyn_cast<ConstantInt>(Size);
Benjamin Kramer691363e2015-03-21 15:36:21 +0000904
905 // memchr(x, y, 0) -> null
David Bolvansky39130312019-08-13 09:11:49 +0000906 if (LenC) {
907 if (LenC->isZero())
908 return Constant::getNullValue(CI->getType());
David Bolvanskye80fcf02019-09-17 09:32:52 +0000909 } else {
910 // From now on we need at least constant length and string.
911 return nullptr;
David Bolvansky39130312019-08-13 09:11:49 +0000912 }
David Bolvanskye80fcf02019-09-17 09:32:52 +0000913
Benjamin Kramer691363e2015-03-21 15:36:21 +0000914 StringRef Str;
David Bolvanskye80fcf02019-09-17 09:32:52 +0000915 if (!getConstantStringInfo(SrcStr, Str, 0, /*TrimAtNul=*/false))
Benjamin Kramer691363e2015-03-21 15:36:21 +0000916 return nullptr;
917
918 // Truncate the string to LenC. If Str is smaller than LenC we will still only
919 // scan the string, as reading past the end of it is undefined and we can just
920 // return null if we don't find the char.
921 Str = Str.substr(0, LenC->getZExtValue());
922
Benjamin Kramer7857d722015-03-21 21:09:33 +0000923 // If the char is variable but the input str and length are not we can turn
924 // this memchr call into a simple bit field test. Of course this only works
925 // when the return value is only checked against null.
926 //
927 // It would be really nice to reuse switch lowering here but we can't change
928 // the CFG at this point.
929 //
Fangrui Songf2609672019-03-12 10:31:52 +0000930 // memchr("\r\n", C, 2) != nullptr -> (1 << C & ((1 << '\r') | (1 << '\n')))
931 // != 0
Benjamin Kramer7857d722015-03-21 21:09:33 +0000932 // after bounds check.
933 if (!CharC && !Str.empty() && isOnlyUsedInZeroEqualityComparison(CI)) {
Benjamin Kramerd6aa0ec2015-03-21 22:04:26 +0000934 unsigned char Max =
935 *std::max_element(reinterpret_cast<const unsigned char *>(Str.begin()),
936 reinterpret_cast<const unsigned char *>(Str.end()));
Benjamin Kramer7857d722015-03-21 21:09:33 +0000937
938 // Make sure the bit field we're about to create fits in a register on the
939 // target.
940 // FIXME: On a 64 bit architecture this prevents us from using the
941 // interesting range of alpha ascii chars. We could do better by emitting
942 // two bitfields or shifting the range by 64 if no lower chars are used.
943 if (!DL.fitsInLegalInteger(Max + 1))
944 return nullptr;
945
946 // For the bit field use a power-of-2 type with at least 8 bits to avoid
947 // creating unnecessary illegal types.
948 unsigned char Width = NextPowerOf2(std::max((unsigned char)7, Max));
949
950 // Now build the bit field.
951 APInt Bitfield(Width, 0);
952 for (char C : Str)
953 Bitfield.setBit((unsigned char)C);
954 Value *BitfieldC = B.getInt(Bitfield);
955
Eli Friedmand4e7a0d2019-01-09 23:39:26 +0000956 // Adjust width of "C" to the bitfield width, then mask off the high bits.
Benjamin Kramer7857d722015-03-21 21:09:33 +0000957 Value *C = B.CreateZExtOrTrunc(CI->getArgOperand(1), BitfieldC->getType());
Eli Friedmand4e7a0d2019-01-09 23:39:26 +0000958 C = B.CreateAnd(C, B.getIntN(Width, 0xFF));
959
960 // First check that the bit field access is within bounds.
Benjamin Kramer7857d722015-03-21 21:09:33 +0000961 Value *Bounds = B.CreateICmp(ICmpInst::ICMP_ULT, C, B.getIntN(Width, Width),
962 "memchr.bounds");
963
964 // Create code that checks if the given bit is set in the field.
965 Value *Shl = B.CreateShl(B.getIntN(Width, 1ULL), C);
966 Value *Bits = B.CreateIsNotNull(B.CreateAnd(Shl, BitfieldC), "memchr.bits");
967
968 // Finally merge both checks and cast to pointer type. The inttoptr
969 // implicitly zexts the i1 to intptr type.
970 return B.CreateIntToPtr(B.CreateAnd(Bounds, Bits, "memchr"), CI->getType());
971 }
972
973 // Check if all arguments are constants. If so, we can constant fold.
974 if (!CharC)
975 return nullptr;
976
Benjamin Kramer691363e2015-03-21 15:36:21 +0000977 // Compute the offset.
978 size_t I = Str.find(CharC->getSExtValue() & 0xFF);
979 if (I == StringRef::npos) // Didn't find the char. memchr returns null.
980 return Constant::getNullValue(CI->getType());
981
982 // memchr(s+n,c,l) -> gep(s+n+i,c)
David Blaikie3909da72015-03-30 20:42:56 +0000983 return B.CreateGEP(B.getInt8Ty(), SrcStr, B.getInt64(I), "memchr");
Benjamin Kramer691363e2015-03-21 15:36:21 +0000984}
985
Clement Courbet8e16d732019-03-08 09:07:45 +0000986static Value *optimizeMemCmpConstantSize(CallInst *CI, Value *LHS, Value *RHS,
987 uint64_t Len, IRBuilder<> &B,
988 const DataLayout &DL) {
Chris Bienemanad070d02014-09-17 20:55:46 +0000989 if (Len == 0) // memcmp(s1,s2,0) -> 0
990 return Constant::getNullValue(CI->getType());
991
992 // memcmp(S1,S2,1) -> *(unsigned char*)LHS - *(unsigned char*)RHS
993 if (Len == 1) {
James Y Knight14359ef2019-02-01 20:44:24 +0000994 Value *LHSV =
995 B.CreateZExt(B.CreateLoad(B.getInt8Ty(), castToCStr(LHS, B), "lhsc"),
996 CI->getType(), "lhsv");
997 Value *RHSV =
998 B.CreateZExt(B.CreateLoad(B.getInt8Ty(), castToCStr(RHS, B), "rhsc"),
999 CI->getType(), "rhsv");
Chris Bienemanad070d02014-09-17 20:55:46 +00001000 return B.CreateSub(LHSV, RHSV, "chardiff");
Meador Inge40b6fac2012-10-15 03:47:37 +00001001 }
Meador Inge40b6fac2012-10-15 03:47:37 +00001002
Chad Rosierdc655322015-08-28 18:30:18 +00001003 // memcmp(S1,S2,N/8)==0 -> (*(intN_t*)S1 != *(intN_t*)S2)==0
Sanjay Patel82ec8722017-08-21 19:13:14 +00001004 // TODO: The case where both inputs are constants does not need to be limited
1005 // to legal integers or equality comparison. See block below this.
Chad Rosierdc655322015-08-28 18:30:18 +00001006 if (DL.isLegalInteger(Len * 8) && isOnlyUsedInZeroEqualityComparison(CI)) {
Chad Rosierdc655322015-08-28 18:30:18 +00001007 IntegerType *IntType = IntegerType::get(CI->getContext(), Len * 8);
1008 unsigned PrefAlignment = DL.getPrefTypeAlignment(IntType);
1009
Sanjay Patel82ec8722017-08-21 19:13:14 +00001010 // First, see if we can fold either argument to a constant.
1011 Value *LHSV = nullptr;
1012 if (auto *LHSC = dyn_cast<Constant>(LHS)) {
1013 LHSC = ConstantExpr::getBitCast(LHSC, IntType->getPointerTo());
1014 LHSV = ConstantFoldLoadFromConstPtr(LHSC, IntType, DL);
1015 }
1016 Value *RHSV = nullptr;
1017 if (auto *RHSC = dyn_cast<Constant>(RHS)) {
1018 RHSC = ConstantExpr::getBitCast(RHSC, IntType->getPointerTo());
1019 RHSV = ConstantFoldLoadFromConstPtr(RHSC, IntType, DL);
1020 }
Chad Rosierdc655322015-08-28 18:30:18 +00001021
Sanjay Patel82ec8722017-08-21 19:13:14 +00001022 // Don't generate unaligned loads. If either source is constant data,
1023 // alignment doesn't matter for that source because there is no load.
1024 if ((LHSV || getKnownAlignment(LHS, DL, CI) >= PrefAlignment) &&
1025 (RHSV || getKnownAlignment(RHS, DL, CI) >= PrefAlignment)) {
1026 if (!LHSV) {
1027 Type *LHSPtrTy =
1028 IntType->getPointerTo(LHS->getType()->getPointerAddressSpace());
James Y Knight14359ef2019-02-01 20:44:24 +00001029 LHSV = B.CreateLoad(IntType, B.CreateBitCast(LHS, LHSPtrTy), "lhsv");
Sanjay Patel82ec8722017-08-21 19:13:14 +00001030 }
1031 if (!RHSV) {
1032 Type *RHSPtrTy =
1033 IntType->getPointerTo(RHS->getType()->getPointerAddressSpace());
James Y Knight14359ef2019-02-01 20:44:24 +00001034 RHSV = B.CreateLoad(IntType, B.CreateBitCast(RHS, RHSPtrTy), "rhsv");
Sanjay Patel82ec8722017-08-21 19:13:14 +00001035 }
Sanjay Patel7756edf2017-08-21 13:55:49 +00001036 return B.CreateZExt(B.CreateICmpNE(LHSV, RHSV), CI->getType(), "memcmp");
Sanjay Patel707f7862017-08-21 15:16:25 +00001037 }
Chad Rosierdc655322015-08-28 18:30:18 +00001038 }
1039
Sanjay Patel82ec8722017-08-21 19:13:14 +00001040 // Constant folding: memcmp(x, y, Len) -> constant (all arguments are const).
1041 // TODO: This is limited to i8 arrays.
Chris Bienemanad070d02014-09-17 20:55:46 +00001042 StringRef LHSStr, RHSStr;
1043 if (getConstantStringInfo(LHS, LHSStr) &&
1044 getConstantStringInfo(RHS, RHSStr)) {
1045 // Make sure we're not reading out-of-bounds memory.
1046 if (Len > LHSStr.size() || Len > RHSStr.size())
Craig Topperf40110f2014-04-25 05:29:35 +00001047 return nullptr;
Chris Bienemanad070d02014-09-17 20:55:46 +00001048 // Fold the memcmp and normalize the result. This way we get consistent
1049 // results across multiple platforms.
1050 uint64_t Ret = 0;
1051 int Cmp = memcmp(LHSStr.data(), RHSStr.data(), Len);
1052 if (Cmp < 0)
1053 Ret = -1;
1054 else if (Cmp > 0)
1055 Ret = 1;
1056 return ConstantInt::get(CI->getType(), Ret);
Meador Inge000dbcc2012-10-18 18:12:40 +00001057 }
David Bolvanskye80fcf02019-09-17 09:32:52 +00001058
Clement Courbet8e16d732019-03-08 09:07:45 +00001059 return nullptr;
1060}
1061
Clement Courbet9e1f2a72019-05-06 09:15:22 +00001062// Most simplifications for memcmp also apply to bcmp.
1063Value *LibCallSimplifier::optimizeMemCmpBCmpCommon(CallInst *CI,
1064 IRBuilder<> &B) {
Clement Courbet8e16d732019-03-08 09:07:45 +00001065 Value *LHS = CI->getArgOperand(0), *RHS = CI->getArgOperand(1);
1066 Value *Size = CI->getArgOperand(2);
1067
1068 if (LHS == RHS) // memcmp(s,s,x) -> 0
1069 return Constant::getNullValue(CI->getType());
1070
David Bolvanskye80fcf02019-09-17 09:32:52 +00001071 annotateNonNullAndDereferenceable(CI, {0, 1}, Size, DL);
Clement Courbet8e16d732019-03-08 09:07:45 +00001072 // Handle constant lengths.
David Bolvanskye80fcf02019-09-17 09:32:52 +00001073 ConstantInt *LenC = dyn_cast<ConstantInt>(Size);
1074 if (!LenC)
1075 return nullptr;
Clement Courbet8e16d732019-03-08 09:07:45 +00001076
David Bolvanskye80fcf02019-09-17 09:32:52 +00001077 // memcmp(d,s,0) -> 0
1078 if (LenC->getZExtValue() == 0)
1079 return Constant::getNullValue(CI->getType());
1080
1081 if (Value *Res =
1082 optimizeMemCmpConstantSize(CI, LHS, RHS, LenC->getZExtValue(), B, DL))
1083 return Res;
Clement Courbet9e1f2a72019-05-06 09:15:22 +00001084 return nullptr;
1085}
1086
1087Value *LibCallSimplifier::optimizeMemCmp(CallInst *CI, IRBuilder<> &B) {
1088 if (Value *V = optimizeMemCmpBCmpCommon(CI, B))
1089 return V;
1090
Clement Courbet8e16d732019-03-08 09:07:45 +00001091 // memcmp(x, y, Len) == 0 -> bcmp(x, y, Len) == 0
Evandro Menezes5cd5f9b2019-07-24 23:31:04 +00001092 // bcmp can be more efficient than memcmp because it only has to know that
1093 // there is a difference, not how different one is to the other.
1094 if (TLI->has(LibFunc_bcmp) && isOnlyUsedInZeroEqualityComparison(CI)) {
Clement Courbet9e1f2a72019-05-06 09:15:22 +00001095 Value *LHS = CI->getArgOperand(0);
1096 Value *RHS = CI->getArgOperand(1);
1097 Value *Size = CI->getArgOperand(2);
Clement Courbet8e16d732019-03-08 09:07:45 +00001098 return emitBCmp(LHS, RHS, Size, B, DL, TLI);
1099 }
Meador Inge000dbcc2012-10-18 18:12:40 +00001100
Chris Bienemanad070d02014-09-17 20:55:46 +00001101 return nullptr;
1102}
Meador Inge9a6a1902012-10-31 00:20:56 +00001103
Clement Courbet9e1f2a72019-05-06 09:15:22 +00001104Value *LibCallSimplifier::optimizeBCmp(CallInst *CI, IRBuilder<> &B) {
1105 return optimizeMemCmpBCmpCommon(CI, B);
1106}
1107
David Bolvanskye80fcf02019-09-17 09:32:52 +00001108Value *LibCallSimplifier::optimizeMemCpy(CallInst *CI, IRBuilder<> &B) {
David Bolvansky39130312019-08-13 09:11:49 +00001109 Value *Size = CI->getArgOperand(2);
David Bolvanskye80fcf02019-09-17 09:32:52 +00001110 annotateNonNullAndDereferenceable(CI, {0, 1}, Size, DL);
1111 if (isa<IntrinsicInst>(CI))
David Bolvansky39130312019-08-13 09:11:49 +00001112 return nullptr;
1113
Daniel Neilson8acd8b02018-02-05 21:23:22 +00001114 // memcpy(x, y, n) -> llvm.memcpy(align 1 x, align 1 y, n)
David Bolvanskye80fcf02019-09-17 09:32:52 +00001115 CallInst *NewCI =
1116 B.CreateMemCpy(CI->getArgOperand(0), 1, CI->getArgOperand(1), 1, Size);
1117 NewCI->setAttributes(CI->getAttributes());
Chris Bienemanad070d02014-09-17 20:55:46 +00001118 return CI->getArgOperand(0);
1119}
Meador Inge05a625a2012-10-31 14:58:26 +00001120
David Bolvanskyff0ad3c2019-08-31 18:19:05 +00001121Value *LibCallSimplifier::optimizeMemPCpy(CallInst *CI, IRBuilder<> &B) {
1122 Value *Dst = CI->getArgOperand(0);
1123 Value *N = CI->getArgOperand(2);
1124 // mempcpy(x, y, n) -> llvm.memcpy(align 1 x, align 1 y, n), x + n
1125 CallInst *NewCI = B.CreateMemCpy(Dst, 1, CI->getArgOperand(1), 1, N);
1126 NewCI->setAttributes(CI->getAttributes());
1127 return B.CreateInBoundsGEP(B.getInt8Ty(), Dst, N);
1128}
1129
David Bolvanskye80fcf02019-09-17 09:32:52 +00001130Value *LibCallSimplifier::optimizeMemMove(CallInst *CI, IRBuilder<> &B) {
David Bolvansky39130312019-08-13 09:11:49 +00001131 Value *Size = CI->getArgOperand(2);
David Bolvanskye80fcf02019-09-17 09:32:52 +00001132 annotateNonNullAndDereferenceable(CI, {0, 1}, Size, DL);
1133 if (isa<IntrinsicInst>(CI))
David Bolvansky39130312019-08-13 09:11:49 +00001134 return nullptr;
1135
Daniel Neilson8acd8b02018-02-05 21:23:22 +00001136 // memmove(x, y, n) -> llvm.memmove(align 1 x, align 1 y, n)
David Bolvanskye80fcf02019-09-17 09:32:52 +00001137 CallInst *NewCI =
1138 B.CreateMemMove(CI->getArgOperand(0), 1, CI->getArgOperand(1), 1, Size);
1139 NewCI->setAttributes(CI->getAttributes());
1140 return CI->getArgOperand(0);
Chris Bienemanad070d02014-09-17 20:55:46 +00001141}
Meador Ingebcd88ef72012-11-10 15:16:48 +00001142
Sanjay Patel980b2802016-01-26 16:17:24 +00001143/// Fold memset[_chk](malloc(n), 0, n) --> calloc(1, n).
Amara Emerson54f60252018-10-11 14:51:11 +00001144Value *LibCallSimplifier::foldMallocMemset(CallInst *Memset, IRBuilder<> &B) {
Sanjay Patel980b2802016-01-26 16:17:24 +00001145 // This has to be a memset of zeros (bzero).
1146 auto *FillValue = dyn_cast<ConstantInt>(Memset->getArgOperand(1));
1147 if (!FillValue || FillValue->getZExtValue() != 0)
1148 return nullptr;
1149
1150 // TODO: We should handle the case where the malloc has more than one use.
1151 // This is necessary to optimize common patterns such as when the result of
1152 // the malloc is checked against null or when a memset intrinsic is used in
1153 // place of a memset library call.
1154 auto *Malloc = dyn_cast<CallInst>(Memset->getArgOperand(0));
1155 if (!Malloc || !Malloc->hasOneUse())
1156 return nullptr;
1157
1158 // Is the inner call really malloc()?
1159 Function *InnerCallee = Malloc->getCalledFunction();
Matthias Braunc36a78c2017-04-25 19:44:25 +00001160 if (!InnerCallee)
1161 return nullptr;
1162
David L. Jonesd21529f2017-01-23 23:16:46 +00001163 LibFunc Func;
Amara Emerson54f60252018-10-11 14:51:11 +00001164 if (!TLI->getLibFunc(*InnerCallee, Func) || !TLI->has(Func) ||
David L. Jonesd21529f2017-01-23 23:16:46 +00001165 Func != LibFunc_malloc)
Sanjay Patel980b2802016-01-26 16:17:24 +00001166 return nullptr;
1167
Sanjay Patel980b2802016-01-26 16:17:24 +00001168 // The memset must cover the same number of bytes that are malloc'd.
1169 if (Memset->getArgOperand(2) != Malloc->getArgOperand(0))
1170 return nullptr;
1171
1172 // Replace the malloc with a calloc. We need the data layout to know what the
Fangrui Songf78650a2018-07-30 19:41:25 +00001173 // actual size of a 'size_t' parameter is.
Sanjay Patel980b2802016-01-26 16:17:24 +00001174 B.SetInsertPoint(Malloc->getParent(), ++Malloc->getIterator());
1175 const DataLayout &DL = Malloc->getModule()->getDataLayout();
1176 IntegerType *SizeType = DL.getIntPtrType(B.GetInsertBlock()->getContext());
Evandro Menezes7d677ad2019-09-06 22:07:11 +00001177 if (Value *Calloc = emitCalloc(ConstantInt::get(SizeType, 1),
1178 Malloc->getArgOperand(0),
1179 Malloc->getAttributes(), B, *TLI)) {
1180 substituteInParent(Malloc, Calloc);
1181 return Calloc;
1182 }
Sanjay Patel980b2802016-01-26 16:17:24 +00001183
Evandro Menezes7d677ad2019-09-06 22:07:11 +00001184 return nullptr;
Sanjay Patel980b2802016-01-26 16:17:24 +00001185}
1186
David Bolvanskye80fcf02019-09-17 09:32:52 +00001187Value *LibCallSimplifier::optimizeMemSet(CallInst *CI, IRBuilder<> &B) {
David Bolvansky39130312019-08-13 09:11:49 +00001188 Value *Size = CI->getArgOperand(2);
David Bolvanskye80fcf02019-09-17 09:32:52 +00001189 annotateNonNullAndDereferenceable(CI, 0, Size, DL);
1190 if (isa<IntrinsicInst>(CI))
David Bolvansky39130312019-08-13 09:11:49 +00001191 return nullptr;
1192
Amara Emerson54f60252018-10-11 14:51:11 +00001193 if (auto *Calloc = foldMallocMemset(CI, B))
Sanjay Patel980b2802016-01-26 16:17:24 +00001194 return Calloc;
1195
Daniel Neilson8acd8b02018-02-05 21:23:22 +00001196 // memset(p, v, n) -> llvm.memset(align 1 p, v, n)
Chris Bienemanad070d02014-09-17 20:55:46 +00001197 Value *Val = B.CreateIntCast(CI->getArgOperand(1), B.getInt8Ty(), false);
David Bolvanskye80fcf02019-09-17 09:32:52 +00001198 CallInst *NewCI = B.CreateMemSet(CI->getArgOperand(0), Val, Size, 1);
1199 NewCI->setAttributes(CI->getAttributes());
Chris Bienemanad070d02014-09-17 20:55:46 +00001200 return CI->getArgOperand(0);
1201}
Meador Inged4825782012-11-11 06:49:03 +00001202
Sanjay Patelb2ab3f22018-04-18 14:21:31 +00001203Value *LibCallSimplifier::optimizeRealloc(CallInst *CI, IRBuilder<> &B) {
1204 if (isa<ConstantPointerNull>(CI->getArgOperand(0)))
1205 return emitMalloc(CI->getArgOperand(1), B, DL, TLI);
1206
1207 return nullptr;
1208}
1209
Meador Inge193e0352012-11-13 04:16:17 +00001210//===----------------------------------------------------------------------===//
1211// Math Library Optimizations
1212//===----------------------------------------------------------------------===//
1213
Evandro Menezes5aa217a2018-08-03 17:50:16 +00001214// Replace a libcall \p CI with a call to intrinsic \p IID
1215static Value *replaceUnaryCall(CallInst *CI, IRBuilder<> &B, Intrinsic::ID IID) {
1216 // Propagate fast-math flags from the existing call to the new call.
1217 IRBuilder<>::FastMathFlagGuard Guard(B);
1218 B.setFastMathFlags(CI->getFastMathFlags());
1219
1220 Module *M = CI->getModule();
1221 Value *V = CI->getArgOperand(0);
1222 Function *F = Intrinsic::getDeclaration(M, IID, CI->getType());
1223 CallInst *NewCall = B.CreateCall(F, V);
1224 NewCall->takeName(CI);
1225 return NewCall;
1226}
1227
Matthias Braund34e4d22014-12-03 21:46:33 +00001228/// Return a variant of Val with float type.
1229/// Currently this works in two cases: If Val is an FPExtension of a float
1230/// value to something bigger, simply return the operand.
1231/// If Val is a ConstantFP but can be converted to a float ConstantFP without
1232/// loss of precision do so.
1233static Value *valueHasFloatPrecision(Value *Val) {
1234 if (FPExtInst *Cast = dyn_cast<FPExtInst>(Val)) {
1235 Value *Op = Cast->getOperand(0);
1236 if (Op->getType()->isFloatTy())
1237 return Op;
1238 }
1239 if (ConstantFP *Const = dyn_cast<ConstantFP>(Val)) {
1240 APFloat F = Const->getValueAPF();
Matthias Braun395a82f2014-12-03 22:10:39 +00001241 bool losesInfo;
Stephan Bergmann17c7f702016-12-14 11:57:17 +00001242 (void)F.convert(APFloat::IEEEsingle(), APFloat::rmNearestTiesToEven,
Matthias Braun395a82f2014-12-03 22:10:39 +00001243 &losesInfo);
1244 if (!losesInfo)
Matthias Braund34e4d22014-12-03 21:46:33 +00001245 return ConstantFP::get(Const->getContext(), F);
1246 }
1247 return nullptr;
1248}
1249
Evandro Menezes5aa217a2018-08-03 17:50:16 +00001250/// Shrink double -> float functions.
1251static Value *optimizeDoubleFP(CallInst *CI, IRBuilder<> &B,
Evandro Menezes6e137cb2018-08-06 19:40:17 +00001252 bool isBinary, bool isPrecise = false) {
Simon Pilgrim364ef5d2019-05-06 19:51:54 +00001253 Function *CalleeFn = CI->getCalledFunction();
1254 if (!CI->getType()->isDoubleTy() || !CalleeFn)
Chris Bienemanad070d02014-09-17 20:55:46 +00001255 return nullptr;
Meador Inge193e0352012-11-13 04:16:17 +00001256
Evandro Menezes6e137cb2018-08-06 19:40:17 +00001257 // If not all the uses of the function are converted to float, then bail out.
1258 // This matters if the precision of the result is more important than the
1259 // precision of the arguments.
1260 if (isPrecise)
Chris Bienemanad070d02014-09-17 20:55:46 +00001261 for (User *U : CI->users()) {
1262 FPTruncInst *Cast = dyn_cast<FPTruncInst>(U);
1263 if (!Cast || !Cast->getType()->isFloatTy())
1264 return nullptr;
Meador Inge193e0352012-11-13 04:16:17 +00001265 }
Chris Bienemanad070d02014-09-17 20:55:46 +00001266
Evandro Menezes5aa217a2018-08-03 17:50:16 +00001267 // If this is something like 'g((double) float)', convert to 'gf(float)'.
1268 Value *V[2];
1269 V[0] = valueHasFloatPrecision(CI->getArgOperand(0));
1270 V[1] = isBinary ? valueHasFloatPrecision(CI->getArgOperand(1)) : nullptr;
1271 if (!V[0] || (isBinary && !V[1]))
Chris Bienemanad070d02014-09-17 20:55:46 +00001272 return nullptr;
Fangrui Songf78650a2018-07-30 19:41:25 +00001273
Andrew Ng1606fc02017-04-25 12:36:14 +00001274 // If call isn't an intrinsic, check that it isn't within a function with the
Evandro Menezes5aa217a2018-08-03 17:50:16 +00001275 // same name as the float version of this call, otherwise the result is an
1276 // infinite loop. For example, from MinGW-w64:
Andrew Ng1606fc02017-04-25 12:36:14 +00001277 //
Evandro Menezes5aa217a2018-08-03 17:50:16 +00001278 // float expf(float val) { return (float) exp((double) val); }
Sanjay Pateld46bf632019-09-18 14:33:40 +00001279 StringRef CalleeName = CalleeFn->getName();
1280 bool IsIntrinsic = CalleeFn->isIntrinsic();
1281 if (!IsIntrinsic) {
1282 StringRef CallerName = CI->getFunction()->getName();
1283 if (!CallerName.empty() && CallerName.back() == 'f' &&
1284 CallerName.size() == (CalleeName.size() + 1) &&
1285 CallerName.startswith(CalleeName))
Andrew Ng1606fc02017-04-25 12:36:14 +00001286 return nullptr;
1287 }
1288
Evandro Menezes5aa217a2018-08-03 17:50:16 +00001289 // Propagate the math semantics from the current function to the new function.
Sanjay Patelaa231142015-12-31 21:52:31 +00001290 IRBuilder<>::FastMathFlagGuard Guard(B);
Sanjay Patela2528152016-01-12 18:03:37 +00001291 B.setFastMathFlags(CI->getFastMathFlags());
Chris Bienemanad070d02014-09-17 20:55:46 +00001292
Evandro Menezes5aa217a2018-08-03 17:50:16 +00001293 // g((double) float) -> (double) gf(float)
1294 Value *R;
Sanjay Pateld46bf632019-09-18 14:33:40 +00001295 if (IsIntrinsic) {
Sanjay Patelaf674fb2015-12-14 17:24:23 +00001296 Module *M = CI->getModule();
Evandro Menezes5aa217a2018-08-03 17:50:16 +00001297 Intrinsic::ID IID = CalleeFn->getIntrinsicID();
1298 Function *Fn = Intrinsic::getDeclaration(M, IID, B.getFloatTy());
1299 R = isBinary ? B.CreateCall(Fn, V) : B.CreateCall(Fn, V[0]);
Sanjay Pateld46bf632019-09-18 14:33:40 +00001300 } else {
1301 AttributeList CalleeAttrs = CalleeFn->getAttributes();
1302 R = isBinary ? emitBinaryFloatFnCall(V[0], V[1], CalleeName, B, CalleeAttrs)
1303 : emitUnaryFloatFnCall(V[0], CalleeName, B, CalleeAttrs);
Sanjay Patel848309d2014-10-23 21:52:45 +00001304 }
Evandro Menezes5aa217a2018-08-03 17:50:16 +00001305 return B.CreateFPExt(R, B.getDoubleTy());
Chris Bienemanad070d02014-09-17 20:55:46 +00001306}
Meador Inge193e0352012-11-13 04:16:17 +00001307
Evandro Menezes5aa217a2018-08-03 17:50:16 +00001308/// Shrink double -> float for unary functions.
1309static Value *optimizeUnaryDoubleFP(CallInst *CI, IRBuilder<> &B,
Evandro Menezes6e137cb2018-08-06 19:40:17 +00001310 bool isPrecise = false) {
1311 return optimizeDoubleFP(CI, B, false, isPrecise);
Matt Arsenault954a6242017-01-23 23:55:08 +00001312}
1313
Evandro Menezes5aa217a2018-08-03 17:50:16 +00001314/// Shrink double -> float for binary functions.
1315static Value *optimizeBinaryDoubleFP(CallInst *CI, IRBuilder<> &B,
Evandro Menezes6e137cb2018-08-06 19:40:17 +00001316 bool isPrecise = false) {
1317 return optimizeDoubleFP(CI, B, true, isPrecise);
Chris Bienemanad070d02014-09-17 20:55:46 +00001318}
1319
Hal Finkel2ff24732017-12-16 01:26:25 +00001320// cabs(z) -> sqrt((creal(z)*creal(z)) + (cimag(z)*cimag(z)))
1321Value *LibCallSimplifier::optimizeCAbs(CallInst *CI, IRBuilder<> &B) {
1322 if (!CI->isFast())
1323 return nullptr;
1324
1325 // Propagate fast-math flags from the existing call to new instructions.
1326 IRBuilder<>::FastMathFlagGuard Guard(B);
1327 B.setFastMathFlags(CI->getFastMathFlags());
1328
1329 Value *Real, *Imag;
1330 if (CI->getNumArgOperands() == 1) {
1331 Value *Op = CI->getArgOperand(0);
1332 assert(Op->getType()->isArrayTy() && "Unexpected signature for cabs!");
1333 Real = B.CreateExtractValue(Op, 0, "real");
1334 Imag = B.CreateExtractValue(Op, 1, "imag");
1335 } else {
1336 assert(CI->getNumArgOperands() == 2 && "Unexpected signature for cabs!");
1337 Real = CI->getArgOperand(0);
1338 Imag = CI->getArgOperand(1);
1339 }
1340
1341 Value *RealReal = B.CreateFMul(Real, Real);
1342 Value *ImagImag = B.CreateFMul(Imag, Imag);
1343
1344 Function *FSqrt = Intrinsic::getDeclaration(CI->getModule(), Intrinsic::sqrt,
1345 CI->getType());
1346 return B.CreateCall(FSqrt, B.CreateFAdd(RealReal, ImagImag), "cabs");
1347}
1348
Sanjay Patele45a83d2018-08-13 19:24:41 +00001349static Value *optimizeTrigReflections(CallInst *Call, LibFunc Func,
1350 IRBuilder<> &B) {
Sanjay Patel15bff182018-08-13 21:49:19 +00001351 if (!isa<FPMathOperator>(Call))
1352 return nullptr;
Clement Courbet8e16d732019-03-08 09:07:45 +00001353
Sanjay Patel15bff182018-08-13 21:49:19 +00001354 IRBuilder<>::FastMathFlagGuard Guard(B);
1355 B.setFastMathFlags(Call->getFastMathFlags());
Clement Courbet8e16d732019-03-08 09:07:45 +00001356
Sanjay Patele45a83d2018-08-13 19:24:41 +00001357 // TODO: Can this be shared to also handle LLVM intrinsics?
Sanjay Patelce4ddbe2018-08-13 17:40:49 +00001358 Value *X;
Sanjay Patele45a83d2018-08-13 19:24:41 +00001359 switch (Func) {
1360 case LibFunc_sin:
1361 case LibFunc_sinf:
1362 case LibFunc_sinl:
Sanjay Patel8ba631d2018-08-16 22:46:20 +00001363 case LibFunc_tan:
1364 case LibFunc_tanf:
1365 case LibFunc_tanl:
Sanjay Patele45a83d2018-08-13 19:24:41 +00001366 // sin(-X) --> -sin(X)
Sanjay Patel8ba631d2018-08-16 22:46:20 +00001367 // tan(-X) --> -tan(X)
Sanjay Patele45a83d2018-08-13 19:24:41 +00001368 if (match(Call->getArgOperand(0), m_OneUse(m_FNeg(m_Value(X)))))
Sanjay Patel8ba631d2018-08-16 22:46:20 +00001369 return B.CreateFNeg(B.CreateCall(Call->getCalledFunction(), X));
Sanjay Patele45a83d2018-08-13 19:24:41 +00001370 break;
1371 case LibFunc_cos:
1372 case LibFunc_cosf:
1373 case LibFunc_cosl:
1374 // cos(-X) --> cos(X)
1375 if (match(Call->getArgOperand(0), m_FNeg(m_Value(X))))
1376 return B.CreateCall(Call->getCalledFunction(), X, "cos");
1377 break;
1378 default:
1379 break;
1380 }
Sanjay Patelce4ddbe2018-08-13 17:40:49 +00001381 return nullptr;
Chris Bienemanad070d02014-09-17 20:55:46 +00001382}
Bob Wilsond8d92d92013-11-03 06:48:38 +00001383
Weiming Zhao82130722015-12-04 22:00:47 +00001384static Value *getPow(Value *InnerChain[33], unsigned Exp, IRBuilder<> &B) {
1385 // Multiplications calculated using Addition Chains.
1386 // Refer: http://wwwhomes.uni-bielefeld.de/achim/addition_chain.html
1387
1388 assert(Exp != 0 && "Incorrect exponent 0 not handled");
1389
1390 if (InnerChain[Exp])
1391 return InnerChain[Exp];
1392
1393 static const unsigned AddChain[33][2] = {
1394 {0, 0}, // Unused.
1395 {0, 0}, // Unused (base case = pow1).
1396 {1, 1}, // Unused (pre-computed).
1397 {1, 2}, {2, 2}, {2, 3}, {3, 3}, {2, 5}, {4, 4},
1398 {1, 8}, {5, 5}, {1, 10}, {6, 6}, {4, 9}, {7, 7},
1399 {3, 12}, {8, 8}, {8, 9}, {2, 16}, {1, 18}, {10, 10},
1400 {6, 15}, {11, 11}, {3, 20}, {12, 12}, {8, 17}, {13, 13},
1401 {3, 24}, {14, 14}, {4, 25}, {15, 15}, {3, 28}, {16, 16},
1402 };
1403
1404 InnerChain[Exp] = B.CreateFMul(getPow(InnerChain, AddChain[Exp][0], B),
1405 getPow(InnerChain, AddChain[Exp][1], B));
1406 return InnerChain[Exp];
1407}
1408
Evandro Menezes05e9c2a2019-08-16 15:33:41 +00001409// Return a properly extended 32-bit integer if the operation is an itofp.
1410static Value *getIntToFPVal(Value *I2F, IRBuilder<> &B) {
1411 if (isa<SIToFPInst>(I2F) || isa<UIToFPInst>(I2F)) {
1412 Value *Op = cast<Instruction>(I2F)->getOperand(0);
1413 // Make sure that the exponent fits inside an int32_t,
1414 // thus avoiding any range issues that FP has not.
1415 unsigned BitWidth = Op->getType()->getPrimitiveSizeInBits();
1416 if (BitWidth < 32 ||
1417 (BitWidth == 32 && isa<SIToFPInst>(I2F)))
1418 return isa<SIToFPInst>(I2F) ? B.CreateSExt(Op, B.getInt32Ty())
1419 : B.CreateZExt(Op, B.getInt32Ty());
1420 }
1421
1422 return nullptr;
1423}
1424
Evandro Menezes4b390102018-08-17 17:59:53 +00001425/// Use exp{,2}(x * y) for pow(exp{,2}(x), y);
Evandro Menezes05e9c2a2019-08-16 15:33:41 +00001426/// ldexp(1.0, x) for pow(2.0, itofp(x)); exp2(n * x) for pow(2.0 ** n, x);
1427/// exp10(x) for pow(10.0, x); exp2(log2(n) * x) for pow(n, x).
Evandro Menezes4b390102018-08-17 17:59:53 +00001428Value *LibCallSimplifier::replacePowWithExp(CallInst *Pow, IRBuilder<> &B) {
1429 Value *Base = Pow->getArgOperand(0), *Expo = Pow->getArgOperand(1);
1430 AttributeList Attrs = Pow->getCalledFunction()->getAttributes();
1431 Module *Mod = Pow->getModule();
1432 Type *Ty = Pow->getType();
Evandro Menezes2123ea72018-08-30 19:04:51 +00001433 bool Ignored;
Evandro Menezes4b390102018-08-17 17:59:53 +00001434
1435 // Evaluate special cases related to a nested function as the base.
1436
1437 // pow(exp(x), y) -> exp(x * y)
1438 // pow(exp2(x), y) -> exp2(x * y)
Evandro Menezes253991c2018-08-27 22:11:15 +00001439 // If exp{,2}() is used only once, it is better to fold two transcendental
1440 // math functions into one. If used again, exp{,2}() would still have to be
1441 // called with the original argument, then keep both original transcendental
1442 // functions. However, this transformation is only safe with fully relaxed
1443 // math semantics, since, besides rounding differences, it changes overflow
1444 // and underflow behavior quite dramatically. For example:
Evandro Menezes4b390102018-08-17 17:59:53 +00001445 // pow(exp(1000), 0.001) = pow(inf, 0.001) = inf
1446 // Whereas:
1447 // exp(1000 * 0.001) = exp(1)
1448 // TODO: Loosen the requirement for fully relaxed math semantics.
1449 // TODO: Handle exp10() when more targets have it available.
1450 CallInst *BaseFn = dyn_cast<CallInst>(Base);
Evandro Menezes253991c2018-08-27 22:11:15 +00001451 if (BaseFn && BaseFn->hasOneUse() && BaseFn->isFast() && Pow->isFast()) {
Evandro Menezes4b390102018-08-17 17:59:53 +00001452 LibFunc LibFn;
Evandro Menezes253991c2018-08-27 22:11:15 +00001453
Evandro Menezes4b390102018-08-17 17:59:53 +00001454 Function *CalleeFn = BaseFn->getCalledFunction();
Evandro Menezes22e0bdf2018-08-29 17:59:48 +00001455 if (CalleeFn &&
1456 TLI->getLibFunc(CalleeFn->getName(), LibFn) && TLI->has(LibFn)) {
1457 StringRef ExpName;
1458 Intrinsic::ID ID;
Evandro Menezes253991c2018-08-27 22:11:15 +00001459 Value *ExpFn;
Evandro Menezes110b1132019-09-30 20:52:21 +00001460 LibFunc LibFnFloat, LibFnDouble, LibFnLongDouble;
Evandro Menezes253991c2018-08-27 22:11:15 +00001461
Evandro Menezes22e0bdf2018-08-29 17:59:48 +00001462 switch (LibFn) {
1463 default:
1464 return nullptr;
1465 case LibFunc_expf: case LibFunc_exp: case LibFunc_expl:
Evandro Menezes164ea102018-10-19 20:57:45 +00001466 ExpName = TLI->getName(LibFunc_exp);
Evandro Menezes22e0bdf2018-08-29 17:59:48 +00001467 ID = Intrinsic::exp;
Mikael Holmene3605d02018-10-18 06:27:53 +00001468 LibFnFloat = LibFunc_expf;
1469 LibFnDouble = LibFunc_exp;
1470 LibFnLongDouble = LibFunc_expl;
Evandro Menezes22e0bdf2018-08-29 17:59:48 +00001471 break;
1472 case LibFunc_exp2f: case LibFunc_exp2: case LibFunc_exp2l:
Evandro Menezes164ea102018-10-19 20:57:45 +00001473 ExpName = TLI->getName(LibFunc_exp2);
Evandro Menezes22e0bdf2018-08-29 17:59:48 +00001474 ID = Intrinsic::exp2;
Mikael Holmene3605d02018-10-18 06:27:53 +00001475 LibFnFloat = LibFunc_exp2f;
1476 LibFnDouble = LibFunc_exp2;
1477 LibFnLongDouble = LibFunc_exp2l;
Evandro Menezes22e0bdf2018-08-29 17:59:48 +00001478 break;
1479 }
1480
Evandro Menezes253991c2018-08-27 22:11:15 +00001481 // Create new exp{,2}() with the product as its argument.
Evandro Menezes4b390102018-08-17 17:59:53 +00001482 Value *FMul = B.CreateFMul(BaseFn->getArgOperand(0), Expo, "mul");
Evandro Menezes22e0bdf2018-08-29 17:59:48 +00001483 ExpFn = BaseFn->doesNotAccessMemory()
1484 ? B.CreateCall(Intrinsic::getDeclaration(Mod, ID, Ty),
1485 FMul, ExpName)
Mikael Holmene3605d02018-10-18 06:27:53 +00001486 : emitUnaryFloatFnCall(FMul, TLI, LibFnDouble, LibFnFloat,
1487 LibFnLongDouble, B,
1488 BaseFn->getAttributes());
Evandro Menezes253991c2018-08-27 22:11:15 +00001489
1490 // Since the new exp{,2}() is different from the original one, dead code
1491 // elimination cannot be trusted to remove it, since it may have side
1492 // effects (e.g., errno). When the only consumer for the original
1493 // exp{,2}() is pow(), then it has to be explicitly erased.
Evandro Menezes7d677ad2019-09-06 22:07:11 +00001494 substituteInParent(BaseFn, ExpFn);
Evandro Menezes253991c2018-08-27 22:11:15 +00001495 return ExpFn;
Evandro Menezes4b390102018-08-17 17:59:53 +00001496 }
1497 }
1498
1499 // Evaluate special cases related to a constant base.
1500
Evandro Menezes2123ea72018-08-30 19:04:51 +00001501 const APFloat *BaseF;
1502 if (!match(Pow->getArgOperand(0), m_APFloat(BaseF)))
1503 return nullptr;
1504
Evandro Menezes05e9c2a2019-08-16 15:33:41 +00001505 // pow(2.0, itofp(x)) -> ldexp(1.0, x)
1506 if (match(Base, m_SpecificFP(2.0)) &&
1507 (isa<SIToFPInst>(Expo) || isa<UIToFPInst>(Expo)) &&
1508 hasFloatFn(TLI, Ty, LibFunc_ldexp, LibFunc_ldexpf, LibFunc_ldexpl)) {
1509 if (Value *ExpoI = getIntToFPVal(Expo, B))
1510 return emitBinaryFloatFnCall(ConstantFP::get(Ty, 1.0), ExpoI, TLI,
1511 LibFunc_ldexp, LibFunc_ldexpf, LibFunc_ldexpl,
1512 B, Attrs);
1513 }
1514
Evandro Menezes2123ea72018-08-30 19:04:51 +00001515 // pow(2.0 ** n, x) -> exp2(n * x)
Evandro Menezesc6c00cd2019-08-09 16:04:18 +00001516 if (hasFloatFn(TLI, Ty, LibFunc_exp2, LibFunc_exp2f, LibFunc_exp2l)) {
Evandro Menezes2123ea72018-08-30 19:04:51 +00001517 APFloat BaseR = APFloat(1.0);
1518 BaseR.convert(BaseF->getSemantics(), APFloat::rmTowardZero, &Ignored);
1519 BaseR = BaseR / *BaseF;
David Bolvanskycb1a5a72019-07-02 15:58:45 +00001520 bool IsInteger = BaseF->isInteger(), IsReciprocal = BaseR.isInteger();
Evandro Menezes2123ea72018-08-30 19:04:51 +00001521 const APFloat *NF = IsReciprocal ? &BaseR : BaseF;
1522 APSInt NI(64, false);
1523 if ((IsInteger || IsReciprocal) &&
David Bolvanskycb1a5a72019-07-02 15:58:45 +00001524 NF->convertToInteger(NI, APFloat::rmTowardZero, &Ignored) ==
1525 APFloat::opOK &&
Evandro Menezes2123ea72018-08-30 19:04:51 +00001526 NI > 1 && NI.isPowerOf2()) {
1527 double N = NI.logBase2() * (IsReciprocal ? -1.0 : 1.0);
1528 Value *FMul = B.CreateFMul(Expo, ConstantFP::get(Ty, N), "mul");
1529 if (Pow->doesNotAccessMemory())
1530 return B.CreateCall(Intrinsic::getDeclaration(Mod, Intrinsic::exp2, Ty),
1531 FMul, "exp2");
1532 else
Mikael Holmene3605d02018-10-18 06:27:53 +00001533 return emitUnaryFloatFnCall(FMul, TLI, LibFunc_exp2, LibFunc_exp2f,
1534 LibFunc_exp2l, B, Attrs);
Evandro Menezes2123ea72018-08-30 19:04:51 +00001535 }
Evandro Menezes4b390102018-08-17 17:59:53 +00001536 }
1537
1538 // pow(10.0, x) -> exp10(x)
1539 // TODO: There is no exp10() intrinsic yet, but some day there shall be one.
1540 if (match(Base, m_SpecificFP(10.0)) &&
Evandro Menezesc6c00cd2019-08-09 16:04:18 +00001541 hasFloatFn(TLI, Ty, LibFunc_exp10, LibFunc_exp10f, LibFunc_exp10l))
Mikael Holmene3605d02018-10-18 06:27:53 +00001542 return emitUnaryFloatFnCall(Expo, TLI, LibFunc_exp10, LibFunc_exp10f,
1543 LibFunc_exp10l, B, Attrs);
Evandro Menezes4b390102018-08-17 17:59:53 +00001544
Evandro Menezesb2169262019-07-12 00:33:49 +00001545 // pow(n, x) -> exp2(log2(n) * x)
David Bolvansky0735cc12019-07-10 14:43:27 +00001546 if (Pow->hasOneUse() && Pow->hasApproxFunc() && Pow->hasNoNaNs() &&
1547 Pow->hasNoInfs() && BaseF->isNormal() && !BaseF->isNegative()) {
1548 Value *Log = nullptr;
1549 if (Ty->isFloatTy())
1550 Log = ConstantFP::get(Ty, std::log2(BaseF->convertToFloat()));
1551 else if (Ty->isDoubleTy())
1552 Log = ConstantFP::get(Ty, std::log2(BaseF->convertToDouble()));
1553
1554 if (Log) {
1555 Value *FMul = B.CreateFMul(Log, Expo, "mul");
Evandro Menezesc6c00cd2019-08-09 16:04:18 +00001556 if (Pow->doesNotAccessMemory())
David Bolvansky0735cc12019-07-10 14:43:27 +00001557 return B.CreateCall(Intrinsic::getDeclaration(Mod, Intrinsic::exp2, Ty),
1558 FMul, "exp2");
Evandro Menezesc6c00cd2019-08-09 16:04:18 +00001559 else if (hasFloatFn(TLI, Ty, LibFunc_exp2, LibFunc_exp2f, LibFunc_exp2l))
1560 return emitUnaryFloatFnCall(FMul, TLI, LibFunc_exp2, LibFunc_exp2f,
1561 LibFunc_exp2l, B, Attrs);
David Bolvansky0735cc12019-07-10 14:43:27 +00001562 }
1563 }
Evandro Menezesc6c00cd2019-08-09 16:04:18 +00001564
Evandro Menezes4b390102018-08-17 17:59:53 +00001565 return nullptr;
1566}
1567
Florian Hahncc9dc592018-09-03 17:37:39 +00001568static Value *getSqrtCall(Value *V, AttributeList Attrs, bool NoErrno,
1569 Module *M, IRBuilder<> &B,
1570 const TargetLibraryInfo *TLI) {
1571 // If errno is never set, then use the intrinsic for sqrt().
1572 if (NoErrno) {
1573 Function *SqrtFn =
1574 Intrinsic::getDeclaration(M, Intrinsic::sqrt, V->getType());
1575 return B.CreateCall(SqrtFn, V, "sqrt");
1576 }
1577
1578 // Otherwise, use the libcall for sqrt().
Evandro Menezesc6c00cd2019-08-09 16:04:18 +00001579 if (hasFloatFn(TLI, V->getType(), LibFunc_sqrt, LibFunc_sqrtf, LibFunc_sqrtl))
Florian Hahncc9dc592018-09-03 17:37:39 +00001580 // TODO: We also should check that the target can in fact lower the sqrt()
1581 // libcall. We currently have no way to ask this question, so we ask if
1582 // the target has a sqrt() libcall, which is not exactly the same.
Mikael Holmene3605d02018-10-18 06:27:53 +00001583 return emitUnaryFloatFnCall(V, TLI, LibFunc_sqrt, LibFunc_sqrtf,
1584 LibFunc_sqrtl, B, Attrs);
Florian Hahncc9dc592018-09-03 17:37:39 +00001585
1586 return nullptr;
1587}
1588
Sanjay Patelfbd3e662017-11-19 16:13:14 +00001589/// Use square root in place of pow(x, +/-0.5).
1590Value *LibCallSimplifier::replacePowWithSqrt(CallInst *Pow, IRBuilder<> &B) {
Evandro Menezesa7d48282018-07-30 16:20:04 +00001591 Value *Sqrt, *Base = Pow->getArgOperand(0), *Expo = Pow->getArgOperand(1);
Evandro Menezesc05c7e12018-08-16 15:58:08 +00001592 AttributeList Attrs = Pow->getCalledFunction()->getAttributes();
1593 Module *Mod = Pow->getModule();
Sanjay Patelfbd3e662017-11-19 16:13:14 +00001594 Type *Ty = Pow->getType();
Sanjay Patelfbd3e662017-11-19 16:13:14 +00001595
Evandro Menezesa7d48282018-07-30 16:20:04 +00001596 const APFloat *ExpoF;
1597 if (!match(Expo, m_APFloat(ExpoF)) ||
1598 (!ExpoF->isExactlyValue(0.5) && !ExpoF->isExactlyValue(-0.5)))
1599 return nullptr;
1600
Florian Hahncc9dc592018-09-03 17:37:39 +00001601 Sqrt = getSqrtCall(Base, Attrs, Pow->doesNotAccessMemory(), Mod, B, TLI);
1602 if (!Sqrt)
Evandro Menezesa7d48282018-07-30 16:20:04 +00001603 return nullptr;
1604
Evandro Menezesc05c7e12018-08-16 15:58:08 +00001605 // Handle signed zero base by expanding to fabs(sqrt(x)).
1606 if (!Pow->hasNoSignedZeros()) {
1607 Function *FAbsFn = Intrinsic::getDeclaration(Mod, Intrinsic::fabs, Ty);
1608 Sqrt = B.CreateCall(FAbsFn, Sqrt, "abs");
1609 }
1610
1611 // Handle non finite base by expanding to
1612 // (x == -infinity ? +infinity : sqrt(x)).
1613 if (!Pow->hasNoInfs()) {
1614 Value *PosInf = ConstantFP::getInfinity(Ty),
1615 *NegInf = ConstantFP::getInfinity(Ty, true);
1616 Value *FCmp = B.CreateFCmpOEQ(Base, NegInf, "isinf");
1617 Sqrt = B.CreateSelect(FCmp, PosInf, Sqrt);
1618 }
1619
Evandro Menezes61e4e402018-07-31 22:11:02 +00001620 // If the exponent is negative, then get the reciprocal.
Evandro Menezesa7d48282018-07-30 16:20:04 +00001621 if (ExpoF->isNegative())
1622 Sqrt = B.CreateFDiv(ConstantFP::get(Ty, 1.0), Sqrt, "reciprocal");
Sanjay Patelfbd3e662017-11-19 16:13:14 +00001623
1624 return Sqrt;
1625}
1626
David Bolvanskycb1a5a72019-07-02 15:58:45 +00001627static Value *createPowWithIntegerExponent(Value *Base, Value *Expo, Module *M,
1628 IRBuilder<> &B) {
1629 Value *Args[] = {Base, Expo};
1630 Function *F = Intrinsic::getDeclaration(M, Intrinsic::powi, Base->getType());
1631 return B.CreateCall(F, Args);
1632}
1633
Evandro Menezesa7d48282018-07-30 16:20:04 +00001634Value *LibCallSimplifier::optimizePow(CallInst *Pow, IRBuilder<> &B) {
David Bolvanskycb1a5a72019-07-02 15:58:45 +00001635 Value *Base = Pow->getArgOperand(0);
1636 Value *Expo = Pow->getArgOperand(1);
Evandro Menezesa7d48282018-07-30 16:20:04 +00001637 Function *Callee = Pow->getCalledFunction();
Davide Italianoa3458772015-11-05 19:18:23 +00001638 StringRef Name = Callee->getName();
Evandro Menezesa7d48282018-07-30 16:20:04 +00001639 Type *Ty = Pow->getType();
David Bolvanskycb1a5a72019-07-02 15:58:45 +00001640 Module *M = Pow->getModule();
Evandro Menezesa7d48282018-07-30 16:20:04 +00001641 Value *Shrunk = nullptr;
David Bolvanskycb1a5a72019-07-02 15:58:45 +00001642 bool AllowApprox = Pow->hasApproxFunc();
Evandro Menezesa7d48282018-07-30 16:20:04 +00001643 bool Ignored;
Bob Wilsond8d92d92013-11-03 06:48:38 +00001644
Evandro Menezes5ecd6c12018-08-13 16:12:37 +00001645 // Bail out if simplifying libcalls to pow() is disabled.
Evandro Menezesc6c00cd2019-08-09 16:04:18 +00001646 if (!hasFloatFn(TLI, Ty, LibFunc_pow, LibFunc_powf, LibFunc_powl))
Evandro Menezes5ecd6c12018-08-13 16:12:37 +00001647 return nullptr;
1648
Evandro Menezes61e4e402018-07-31 22:11:02 +00001649 // Propagate the math semantics from the call to any created instructions.
Evandro Menezesa7d48282018-07-30 16:20:04 +00001650 IRBuilder<>::FastMathFlagGuard Guard(B);
1651 B.setFastMathFlags(Pow->getFastMathFlags());
1652
Evandro Menezes6e137cb2018-08-06 19:40:17 +00001653 // Shrink pow() to powf() if the arguments are single precision,
1654 // unless the result is expected to be double precision.
David Bolvanskycb1a5a72019-07-02 15:58:45 +00001655 if (UnsafeFPShrink && Name == TLI->getName(LibFunc_pow) &&
1656 hasFloatVersion(Name))
Evandro Menezes6e137cb2018-08-06 19:40:17 +00001657 Shrunk = optimizeBinaryDoubleFP(Pow, B, true);
1658
Evandro Menezesa7d48282018-07-30 16:20:04 +00001659 // Evaluate special cases related to the base.
Davide Italiano27da1312016-08-07 20:27:03 +00001660
1661 // pow(1.0, x) -> 1.0
Evandro Menezes84e74362018-08-02 15:43:57 +00001662 if (match(Base, m_FPOne()))
Evandro Menezesa7d48282018-07-30 16:20:04 +00001663 return Base;
1664
David Bolvanskye23be092019-07-11 10:55:04 +00001665 if (Value *Exp = replacePowWithExp(Pow, B))
1666 return Exp;
1667
Evandro Menezesa7d48282018-07-30 16:20:04 +00001668 // Evaluate special cases related to the exponent.
1669
Evandro Menezesa7d48282018-07-30 16:20:04 +00001670 // pow(x, -1.0) -> 1.0 / x
Evandro Menezes5ecd6c12018-08-13 16:12:37 +00001671 if (match(Expo, m_SpecificFP(-1.0)))
Evandro Menezesa7d48282018-07-30 16:20:04 +00001672 return B.CreateFDiv(ConstantFP::get(Ty, 1.0), Base, "reciprocal");
1673
Sanjay Patel4f0e4292019-09-06 16:10:18 +00001674 // pow(x, +/-0.0) -> 1.0
1675 if (match(Expo, m_AnyZeroFP()))
David Bolvanskycb1a5a72019-07-02 15:58:45 +00001676 return ConstantFP::get(Ty, 1.0);
Evandro Menezesa7d48282018-07-30 16:20:04 +00001677
1678 // pow(x, 1.0) -> x
Evandro Menezes5ecd6c12018-08-13 16:12:37 +00001679 if (match(Expo, m_FPOne()))
Evandro Menezesa7d48282018-07-30 16:20:04 +00001680 return Base;
1681
1682 // pow(x, 2.0) -> x * x
Evandro Menezes5ecd6c12018-08-13 16:12:37 +00001683 if (match(Expo, m_SpecificFP(2.0)))
Evandro Menezesa7d48282018-07-30 16:20:04 +00001684 return B.CreateFMul(Base, Base, "square");
Chris Bienemanad070d02014-09-17 20:55:46 +00001685
Evandro Menezes5ecd6c12018-08-13 16:12:37 +00001686 if (Value *Sqrt = replacePowWithSqrt(Pow, B))
1687 return Sqrt;
1688
Evandro Menezes5ecd6c12018-08-13 16:12:37 +00001689 // pow(x, n) -> x * x * x * ...
1690 const APFloat *ExpoF;
Evandro Menezesb2169262019-07-12 00:33:49 +00001691 if (AllowApprox && match(Expo, m_APFloat(ExpoF))) {
Evandro Menezes5ecd6c12018-08-13 16:12:37 +00001692 // We limit to a max of 7 multiplications, thus the maximum exponent is 32.
Florian Hahncc9dc592018-09-03 17:37:39 +00001693 // If the exponent is an integer+0.5 we generate a call to sqrt and an
1694 // additional fmul.
1695 // TODO: This whole transformation should be backend specific (e.g. some
1696 // backends might prefer libcalls or the limit for the exponent might
1697 // be different) and it should also consider optimizing for size.
Evandro Menezes5ecd6c12018-08-13 16:12:37 +00001698 APFloat LimF(ExpoF->getSemantics(), 33.0),
1699 ExpoA(abs(*ExpoF));
Florian Hahncc9dc592018-09-03 17:37:39 +00001700 if (ExpoA.compare(LimF) == APFloat::cmpLessThan) {
1701 // This transformation applies to integer or integer+0.5 exponents only.
1702 // For integer+0.5, we create a sqrt(Base) call.
1703 Value *Sqrt = nullptr;
1704 if (!ExpoA.isInteger()) {
1705 APFloat Expo2 = ExpoA;
1706 // To check if ExpoA is an integer + 0.5, we add it to itself. If there
1707 // is no floating point exception and the result is an integer, then
1708 // ExpoA == integer + 0.5
1709 if (Expo2.add(ExpoA, APFloat::rmNearestTiesToEven) != APFloat::opOK)
1710 return nullptr;
1711
1712 if (!Expo2.isInteger())
1713 return nullptr;
1714
David Bolvanskycb1a5a72019-07-02 15:58:45 +00001715 Sqrt = getSqrtCall(Base, Pow->getCalledFunction()->getAttributes(),
1716 Pow->doesNotAccessMemory(), M, B, TLI);
Florian Hahncc9dc592018-09-03 17:37:39 +00001717 }
1718
Evandro Menezes5ecd6c12018-08-13 16:12:37 +00001719 // We will memoize intermediate products of the Addition Chain.
1720 Value *InnerChain[33] = {nullptr};
1721 InnerChain[1] = Base;
1722 InnerChain[2] = B.CreateFMul(Base, Base, "square");
Weiming Zhao82130722015-12-04 22:00:47 +00001723
Evandro Menezes5ecd6c12018-08-13 16:12:37 +00001724 // We cannot readily convert a non-double type (like float) to a double.
1725 // So we first convert it to something which could be converted to double.
1726 ExpoA.convert(APFloat::IEEEdouble(), APFloat::rmTowardZero, &Ignored);
1727 Value *FMul = getPow(InnerChain, ExpoA.convertToDouble(), B);
Weiming Zhao82130722015-12-04 22:00:47 +00001728
Florian Hahncc9dc592018-09-03 17:37:39 +00001729 // Expand pow(x, y+0.5) to pow(x, y) * sqrt(x).
1730 if (Sqrt)
1731 FMul = B.CreateFMul(FMul, Sqrt);
1732
Evandro Menezes5ecd6c12018-08-13 16:12:37 +00001733 // If the exponent is negative, then get the reciprocal.
1734 if (ExpoF->isNegative())
1735 FMul = B.CreateFDiv(ConstantFP::get(Ty, 1.0), FMul, "reciprocal");
Evandro Menezes61e4e402018-07-31 22:11:02 +00001736
Evandro Menezes5ecd6c12018-08-13 16:12:37 +00001737 return FMul;
1738 }
David Bolvanskycb1a5a72019-07-02 15:58:45 +00001739
1740 APSInt IntExpo(32, /*isUnsigned=*/false);
Evandro Menezesb2169262019-07-12 00:33:49 +00001741 // powf(x, n) -> powi(x, n) if n is a constant signed integer value
David Bolvansky10ee3ac2019-07-02 21:16:34 +00001742 if (ExpoF->isInteger() &&
1743 ExpoF->convertToInteger(IntExpo, APFloat::rmTowardZero, &Ignored) ==
1744 APFloat::opOK) {
David Bolvanskycb1a5a72019-07-02 15:58:45 +00001745 return createPowWithIntegerExponent(
1746 Base, ConstantInt::get(B.getInt32Ty(), IntExpo), M, B);
1747 }
Weiming Zhao82130722015-12-04 22:00:47 +00001748 }
1749
Evandro Menezesb2169262019-07-12 00:33:49 +00001750 // powf(x, itofp(y)) -> powi(x, y)
1751 if (AllowApprox && (isa<SIToFPInst>(Expo) || isa<UIToFPInst>(Expo))) {
Evandro Menezes05e9c2a2019-08-16 15:33:41 +00001752 if (Value *ExpoI = getIntToFPVal(Expo, B))
1753 return createPowWithIntegerExponent(Base, ExpoI, M, B);
Evandro Menezesb2169262019-07-12 00:33:49 +00001754 }
1755
Evandro Menezes6e137cb2018-08-06 19:40:17 +00001756 return Shrunk;
Chris Bienemanad070d02014-09-17 20:55:46 +00001757}
Bob Wilsond8d92d92013-11-03 06:48:38 +00001758
Chris Bienemanad070d02014-09-17 20:55:46 +00001759Value *LibCallSimplifier::optimizeExp2(CallInst *CI, IRBuilder<> &B) {
1760 Function *Callee = CI->getCalledFunction();
Davide Italianoa3458772015-11-05 19:18:23 +00001761 StringRef Name = Callee->getName();
Evandro Menezes59fbe512019-08-09 17:22:56 +00001762 Value *Ret = nullptr;
1763 if (UnsafeFPShrink && Name == TLI->getName(LibFunc_exp2) &&
1764 hasFloatVersion(Name))
Chris Bienemanad070d02014-09-17 20:55:46 +00001765 Ret = optimizeUnaryDoubleFP(CI, B, true);
Bob Wilsond8d92d92013-11-03 06:48:38 +00001766
Evandro Menezes59fbe512019-08-09 17:22:56 +00001767 Type *Ty = CI->getType();
Chris Bienemanad070d02014-09-17 20:55:46 +00001768 Value *Op = CI->getArgOperand(0);
Evandro Menezes59fbe512019-08-09 17:22:56 +00001769
Chris Bienemanad070d02014-09-17 20:55:46 +00001770 // Turn exp2(sitofp(x)) -> ldexp(1.0, sext(x)) if sizeof(x) <= 32
1771 // Turn exp2(uitofp(x)) -> ldexp(1.0, zext(x)) if sizeof(x) < 32
Evandro Menezes59fbe512019-08-09 17:22:56 +00001772 if ((isa<SIToFPInst>(Op) || isa<UIToFPInst>(Op)) &&
1773 hasFloatFn(TLI, Ty, LibFunc_ldexp, LibFunc_ldexpf, LibFunc_ldexpl)) {
Evandro Menezes05e9c2a2019-08-16 15:33:41 +00001774 if (Value *Exp = getIntToFPVal(Op, B))
Evandro Menezes59fbe512019-08-09 17:22:56 +00001775 return emitBinaryFloatFnCall(ConstantFP::get(Ty, 1.0), Exp, TLI,
1776 LibFunc_ldexp, LibFunc_ldexpf, LibFunc_ldexpl,
1777 B, CI->getCalledFunction()->getAttributes());
Chris Bienemanad070d02014-09-17 20:55:46 +00001778 }
Evandro Menezes05e9c2a2019-08-16 15:33:41 +00001779
Chris Bienemanad070d02014-09-17 20:55:46 +00001780 return Ret;
1781}
1782
Sanjay Patel57fd1dc2015-08-16 20:18:19 +00001783Value *LibCallSimplifier::optimizeFMinFMax(CallInst *CI, IRBuilder<> &B) {
1784 // If we can shrink the call to a float function rather than a double
1785 // function, do that first.
Sanjay Patel77dc1e82019-06-29 14:28:54 +00001786 Function *Callee = CI->getCalledFunction();
Davide Italianoa3458772015-11-05 19:18:23 +00001787 StringRef Name = Callee->getName();
Sanjay Patelc7ddb7f2016-01-06 00:32:15 +00001788 if ((Name == "fmin" || Name == "fmax") && hasFloatVersion(Name))
1789 if (Value *Ret = optimizeBinaryDoubleFP(CI, B))
Sanjay Patel57fd1dc2015-08-16 20:18:19 +00001790 return Ret;
Sanjay Patel57fd1dc2015-08-16 20:18:19 +00001791
Sanjay Patel77dc1e82019-06-29 14:28:54 +00001792 // The LLVM intrinsics minnum/maxnum correspond to fmin/fmax. Canonicalize to
1793 // the intrinsics for improved optimization (for example, vectorization).
1794 // No-signed-zeros is implied by the definitions of fmax/fmin themselves.
1795 // From the C standard draft WG14/N1256:
1796 // "Ideally, fmax would be sensitive to the sign of zero, for example
1797 // fmax(-0.0, +0.0) would return +0; however, implementation in software
1798 // might be impractical."
Benjamin Kramerbb70d752015-08-16 21:16:37 +00001799 IRBuilder<>::FastMathFlagGuard Guard(B);
Sanjay Patel77dc1e82019-06-29 14:28:54 +00001800 FastMathFlags FMF = CI->getFastMathFlags();
1801 FMF.setNoSignedZeros();
Sanjay Patela2528152016-01-12 18:03:37 +00001802 B.setFastMathFlags(FMF);
Sanjay Patel57fd1dc2015-08-16 20:18:19 +00001803
Sanjay Patel77dc1e82019-06-29 14:28:54 +00001804 Intrinsic::ID IID = Callee->getName().startswith("fmin") ? Intrinsic::minnum
1805 : Intrinsic::maxnum;
1806 Function *F = Intrinsic::getDeclaration(CI->getModule(), IID, CI->getType());
1807 return B.CreateCall(F, { CI->getArgOperand(0), CI->getArgOperand(1) });
Sanjay Patel57fd1dc2015-08-16 20:18:19 +00001808}
1809
Evandro Menezes110b1132019-09-30 20:52:21 +00001810Value *LibCallSimplifier::optimizeLog(CallInst *Log, IRBuilder<> &B) {
1811 Function *LogFn = Log->getCalledFunction();
1812 AttributeList Attrs = LogFn->getAttributes();
1813 StringRef LogNm = LogFn->getName();
1814 Intrinsic::ID LogID = LogFn->getIntrinsicID();
1815 Module *Mod = Log->getModule();
1816 Type *Ty = Log->getType();
Davide Italianob8b71332015-11-29 20:58:04 +00001817 Value *Ret = nullptr;
Davide Italianob8b71332015-11-29 20:58:04 +00001818
Evandro Menezes110b1132019-09-30 20:52:21 +00001819 if (UnsafeFPShrink && hasFloatVersion(LogNm))
1820 Ret = optimizeUnaryDoubleFP(Log, B, true);
Sanjay Patele896ede2016-01-11 23:31:48 +00001821
Sanjay Patel629c4112017-11-06 16:27:15 +00001822 // The earlier call must also be 'fast' in order to do these transforms.
Evandro Menezes110b1132019-09-30 20:52:21 +00001823 CallInst *Arg = dyn_cast<CallInst>(Log->getArgOperand(0));
1824 if (!Log->isFast() || !Arg || !Arg->isFast() || !Arg->hasOneUse())
Davide Italianob8b71332015-11-29 20:58:04 +00001825 return Ret;
1826
Evandro Menezes110b1132019-09-30 20:52:21 +00001827 LibFunc LogLb, ExpLb, Exp2Lb, Exp10Lb, PowLb;
1828
1829 // This is only applicable to log(), log2(), log10().
1830 if (TLI->getLibFunc(LogNm, LogLb))
1831 switch (LogLb) {
1832 case LibFunc_logf:
1833 LogID = Intrinsic::log;
1834 ExpLb = LibFunc_expf;
1835 Exp2Lb = LibFunc_exp2f;
1836 Exp10Lb = LibFunc_exp10f;
1837 PowLb = LibFunc_powf;
1838 break;
1839 case LibFunc_log:
1840 LogID = Intrinsic::log;
1841 ExpLb = LibFunc_exp;
1842 Exp2Lb = LibFunc_exp2;
1843 Exp10Lb = LibFunc_exp10;
1844 PowLb = LibFunc_pow;
1845 break;
1846 case LibFunc_logl:
1847 LogID = Intrinsic::log;
1848 ExpLb = LibFunc_expl;
1849 Exp2Lb = LibFunc_exp2l;
1850 Exp10Lb = LibFunc_exp10l;
1851 PowLb = LibFunc_powl;
1852 break;
1853 case LibFunc_log2f:
1854 LogID = Intrinsic::log2;
1855 ExpLb = LibFunc_expf;
1856 Exp2Lb = LibFunc_exp2f;
1857 Exp10Lb = LibFunc_exp10f;
1858 PowLb = LibFunc_powf;
1859 break;
1860 case LibFunc_log2:
1861 LogID = Intrinsic::log2;
1862 ExpLb = LibFunc_exp;
1863 Exp2Lb = LibFunc_exp2;
1864 Exp10Lb = LibFunc_exp10;
1865 PowLb = LibFunc_pow;
1866 break;
1867 case LibFunc_log2l:
1868 LogID = Intrinsic::log2;
1869 ExpLb = LibFunc_expl;
1870 Exp2Lb = LibFunc_exp2l;
1871 Exp10Lb = LibFunc_exp10l;
1872 PowLb = LibFunc_powl;
1873 break;
1874 case LibFunc_log10f:
1875 LogID = Intrinsic::log10;
1876 ExpLb = LibFunc_expf;
1877 Exp2Lb = LibFunc_exp2f;
1878 Exp10Lb = LibFunc_exp10f;
1879 PowLb = LibFunc_powf;
1880 break;
1881 case LibFunc_log10:
1882 LogID = Intrinsic::log10;
1883 ExpLb = LibFunc_exp;
1884 Exp2Lb = LibFunc_exp2;
1885 Exp10Lb = LibFunc_exp10;
1886 PowLb = LibFunc_pow;
1887 break;
1888 case LibFunc_log10l:
1889 LogID = Intrinsic::log10;
1890 ExpLb = LibFunc_expl;
1891 Exp2Lb = LibFunc_exp2l;
1892 Exp10Lb = LibFunc_exp10l;
1893 PowLb = LibFunc_powl;
1894 break;
1895 default:
1896 return Ret;
1897 }
1898 else if (LogID == Intrinsic::log || LogID == Intrinsic::log2 ||
1899 LogID == Intrinsic::log10) {
1900 if (Ty->getScalarType()->isFloatTy()) {
1901 ExpLb = LibFunc_expf;
1902 Exp2Lb = LibFunc_exp2f;
1903 Exp10Lb = LibFunc_exp10f;
1904 PowLb = LibFunc_powf;
1905 } else if (Ty->getScalarType()->isDoubleTy()) {
1906 ExpLb = LibFunc_exp;
1907 Exp2Lb = LibFunc_exp2;
1908 Exp10Lb = LibFunc_exp10;
1909 PowLb = LibFunc_pow;
1910 } else
1911 return Ret;
1912 } else
Davide Italianob8b71332015-11-29 20:58:04 +00001913 return Ret;
1914
1915 IRBuilder<>::FastMathFlagGuard Guard(B);
Evandro Menezes110b1132019-09-30 20:52:21 +00001916 B.setFastMathFlags(FastMathFlags::getFast());
Davide Italianob8b71332015-11-29 20:58:04 +00001917
Evandro Menezes110b1132019-09-30 20:52:21 +00001918 Function *ArgFn = Arg->getCalledFunction();
1919 StringRef ArgNm = ArgFn->getName();
1920 Intrinsic::ID ArgID = ArgFn->getIntrinsicID();
1921 LibFunc ArgLb = NotLibFunc;
1922 TLI->getLibFunc(ArgNm, ArgLb);
Davide Italiano1aeed6a2015-11-30 19:36:35 +00001923
Evandro Menezes110b1132019-09-30 20:52:21 +00001924 // log(pow(x,y)) -> y*log(x)
1925 if (ArgLb == PowLb || ArgID == Intrinsic::pow) {
1926 Value *LogX =
1927 Log->doesNotAccessMemory()
1928 ? B.CreateCall(Intrinsic::getDeclaration(Mod, LogID, Ty),
1929 Arg->getOperand(0), "log")
1930 : emitUnaryFloatFnCall(Arg->getOperand(0), LogNm, B, Attrs);
1931 Value *MulY = B.CreateFMul(Arg->getArgOperand(1), LogX, "mul");
1932 // Since pow() may have side effects, e.g. errno,
1933 // dead code elimination may not be trusted to remove it.
1934 substituteInParent(Arg, MulY);
1935 return MulY;
1936 }
1937 // log(exp{,2,10}(y)) -> y*log({e,2,10})
1938 // TODO: There is no exp10() intrinsic yet.
1939 else if (ArgLb == ExpLb || ArgLb == Exp2Lb || ArgLb == Exp10Lb ||
1940 ArgID == Intrinsic::exp || ArgID == Intrinsic::exp2) {
1941 Constant *Eul;
1942 if (ArgLb == ExpLb || ArgID == Intrinsic::exp)
Evandro Menezese60415a2019-10-09 19:58:01 +00001943 // FIXME: Add more precise value of e for long double.
1944 Eul = ConstantFP::get(Log->getType(), numbers::e);
Evandro Menezes110b1132019-09-30 20:52:21 +00001945 else if (ArgLb == Exp2Lb || ArgID == Intrinsic::exp2)
1946 Eul = ConstantFP::get(Log->getType(), 2.0);
1947 else
1948 Eul = ConstantFP::get(Log->getType(), 10.0);
1949 Value *LogE = Log->doesNotAccessMemory()
1950 ? B.CreateCall(Intrinsic::getDeclaration(Mod, LogID, Ty),
1951 Eul, "log")
1952 : emitUnaryFloatFnCall(Eul, LogNm, B, Attrs);
1953 Value *MulY = B.CreateFMul(Arg->getArgOperand(0), LogE, "mul");
1954 // Since exp() may have side effects, e.g. errno,
1955 // dead code elimination may not be trusted to remove it.
1956 substituteInParent(Arg, MulY);
1957 return MulY;
1958 }
1959
Davide Italianob8b71332015-11-29 20:58:04 +00001960 return Ret;
1961}
1962
Sanjay Patelc699a612014-10-16 18:48:17 +00001963Value *LibCallSimplifier::optimizeSqrt(CallInst *CI, IRBuilder<> &B) {
1964 Function *Callee = CI->getCalledFunction();
Sanjay Patelc699a612014-10-16 18:48:17 +00001965 Value *Ret = nullptr;
Justin Lebarcb9b41d2017-01-27 00:58:03 +00001966 // TODO: Once we have a way (other than checking for the existince of the
1967 // libcall) to tell whether our target can lower @llvm.sqrt, relax the
1968 // condition below.
David L. Jonesd21529f2017-01-23 23:16:46 +00001969 if (TLI->has(LibFunc_sqrtf) && (Callee->getName() == "sqrt" ||
Justin Lebarcb9b41d2017-01-27 00:58:03 +00001970 Callee->getIntrinsicID() == Intrinsic::sqrt))
Sanjay Patelc699a612014-10-16 18:48:17 +00001971 Ret = optimizeUnaryDoubleFP(CI, B, true);
Sanjay Patel683f2972016-01-11 22:34:19 +00001972
Sanjay Patel629c4112017-11-06 16:27:15 +00001973 if (!CI->isFast())
Davide Italianoa904e522015-10-29 02:58:44 +00001974 return Ret;
Sanjay Patelc699a612014-10-16 18:48:17 +00001975
Sanjay Patelc2d64612016-01-06 20:52:21 +00001976 Instruction *I = dyn_cast<Instruction>(CI->getArgOperand(0));
Sanjay Patel629c4112017-11-06 16:27:15 +00001977 if (!I || I->getOpcode() != Instruction::FMul || !I->isFast())
Sanjay Patelc2d64612016-01-06 20:52:21 +00001978 return Ret;
1979
1980 // We're looking for a repeated factor in a multiplication tree,
1981 // so we can do this fold: sqrt(x * x) -> fabs(x);
Sanjay Patel683f2972016-01-11 22:34:19 +00001982 // or this fold: sqrt((x * x) * y) -> fabs(x) * sqrt(y).
Sanjay Patelc2d64612016-01-06 20:52:21 +00001983 Value *Op0 = I->getOperand(0);
1984 Value *Op1 = I->getOperand(1);
1985 Value *RepeatOp = nullptr;
1986 Value *OtherOp = nullptr;
1987 if (Op0 == Op1) {
1988 // Simple match: the operands of the multiply are identical.
1989 RepeatOp = Op0;
1990 } else {
1991 // Look for a more complicated pattern: one of the operands is itself
1992 // a multiply, so search for a common factor in that multiply.
1993 // Note: We don't bother looking any deeper than this first level or for
1994 // variations of this pattern because instcombine's visitFMUL and/or the
1995 // reassociation pass should give us this form.
1996 Value *OtherMul0, *OtherMul1;
1997 if (match(Op0, m_FMul(m_Value(OtherMul0), m_Value(OtherMul1)))) {
1998 // Pattern: sqrt((x * y) * z)
Sanjay Patel629c4112017-11-06 16:27:15 +00001999 if (OtherMul0 == OtherMul1 && cast<Instruction>(Op0)->isFast()) {
Sanjay Patelc2d64612016-01-06 20:52:21 +00002000 // Matched: sqrt((x * x) * z)
2001 RepeatOp = OtherMul0;
2002 OtherOp = Op1;
Sanjay Patelc699a612014-10-16 18:48:17 +00002003 }
2004 }
2005 }
Sanjay Patelc2d64612016-01-06 20:52:21 +00002006 if (!RepeatOp)
2007 return Ret;
2008
2009 // Fast math flags for any created instructions should match the sqrt
2010 // and multiply.
Sanjay Patelc2d64612016-01-06 20:52:21 +00002011 IRBuilder<>::FastMathFlagGuard Guard(B);
Sanjay Patela2528152016-01-12 18:03:37 +00002012 B.setFastMathFlags(I->getFastMathFlags());
Sanjay Patel9f67dad2016-01-11 22:35:39 +00002013
Sanjay Patelc2d64612016-01-06 20:52:21 +00002014 // If we found a repeated factor, hoist it out of the square root and
2015 // replace it with the fabs of that factor.
2016 Module *M = Callee->getParent();
2017 Type *ArgType = I->getType();
James Y Knight7976eb52019-02-01 20:43:25 +00002018 Function *Fabs = Intrinsic::getDeclaration(M, Intrinsic::fabs, ArgType);
Sanjay Patelc2d64612016-01-06 20:52:21 +00002019 Value *FabsCall = B.CreateCall(Fabs, RepeatOp, "fabs");
2020 if (OtherOp) {
2021 // If we found a non-repeated factor, we still need to get its square
2022 // root. We then multiply that by the value that was simplified out
2023 // of the square root calculation.
James Y Knight7976eb52019-02-01 20:43:25 +00002024 Function *Sqrt = Intrinsic::getDeclaration(M, Intrinsic::sqrt, ArgType);
Sanjay Patelc2d64612016-01-06 20:52:21 +00002025 Value *SqrtCall = B.CreateCall(Sqrt, OtherOp, "sqrt");
2026 return B.CreateFMul(FabsCall, SqrtCall);
2027 }
2028 return FabsCall;
Sanjay Patelc699a612014-10-16 18:48:17 +00002029}
2030
Sanjay Patelcddcd722016-01-06 19:23:35 +00002031// TODO: Generalize to handle any trig function and its inverse.
Davide Italiano51507d22015-11-04 23:36:56 +00002032Value *LibCallSimplifier::optimizeTan(CallInst *CI, IRBuilder<> &B) {
2033 Function *Callee = CI->getCalledFunction();
2034 Value *Ret = nullptr;
Davide Italianoa3458772015-11-05 19:18:23 +00002035 StringRef Name = Callee->getName();
2036 if (UnsafeFPShrink && Name == "tan" && hasFloatVersion(Name))
Davide Italiano51507d22015-11-04 23:36:56 +00002037 Ret = optimizeUnaryDoubleFP(CI, B, true);
Davide Italiano51507d22015-11-04 23:36:56 +00002038
Davide Italiano51507d22015-11-04 23:36:56 +00002039 Value *Op1 = CI->getArgOperand(0);
2040 auto *OpC = dyn_cast<CallInst>(Op1);
2041 if (!OpC)
2042 return Ret;
2043
Sanjay Patel629c4112017-11-06 16:27:15 +00002044 // Both calls must be 'fast' in order to remove them.
2045 if (!CI->isFast() || !OpC->isFast())
Sanjay Patelcddcd722016-01-06 19:23:35 +00002046 return Ret;
2047
Davide Italiano51507d22015-11-04 23:36:56 +00002048 // tan(atan(x)) -> x
2049 // tanf(atanf(x)) -> x
2050 // tanl(atanl(x)) -> x
David L. Jonesd21529f2017-01-23 23:16:46 +00002051 LibFunc Func;
Davide Italiano51507d22015-11-04 23:36:56 +00002052 Function *F = OpC->getCalledFunction();
Benjamin Kramerfb419e72015-11-26 09:51:17 +00002053 if (F && TLI->getLibFunc(F->getName(), Func) && TLI->has(Func) &&
David L. Jonesd21529f2017-01-23 23:16:46 +00002054 ((Func == LibFunc_atan && Callee->getName() == "tan") ||
2055 (Func == LibFunc_atanf && Callee->getName() == "tanf") ||
2056 (Func == LibFunc_atanl && Callee->getName() == "tanl")))
Davide Italiano51507d22015-11-04 23:36:56 +00002057 Ret = OpC->getArgOperand(0);
2058 return Ret;
2059}
2060
Sanjay Patel57747212016-01-21 23:38:43 +00002061static bool isTrigLibCall(CallInst *CI) {
Sanjay Patel57747212016-01-21 23:38:43 +00002062 // We can only hope to do anything useful if we can ignore things like errno
2063 // and floating-point exceptions.
Ahmed Bougachad765a822016-04-27 19:04:35 +00002064 // We already checked the prototype.
2065 return CI->hasFnAttr(Attribute::NoUnwind) &&
2066 CI->hasFnAttr(Attribute::ReadNone);
Sanjay Patel57747212016-01-21 23:38:43 +00002067}
2068
Chris Bienemanad070d02014-09-17 20:55:46 +00002069static void insertSinCosCall(IRBuilder<> &B, Function *OrigCallee, Value *Arg,
2070 bool UseFloat, Value *&Sin, Value *&Cos,
Sanjay Patel57747212016-01-21 23:38:43 +00002071 Value *&SinCos) {
2072 Type *ArgTy = Arg->getType();
2073 Type *ResTy;
2074 StringRef Name;
2075
2076 Triple T(OrigCallee->getParent()->getTargetTriple());
2077 if (UseFloat) {
2078 Name = "__sincospif_stret";
2079
2080 assert(T.getArch() != Triple::x86 && "x86 messy and unsupported for now");
2081 // x86_64 can't use {float, float} since that would be returned in both
2082 // xmm0 and xmm1, which isn't what a real struct would do.
2083 ResTy = T.getArch() == Triple::x86_64
Serge Gueltone38003f2017-05-09 19:31:13 +00002084 ? static_cast<Type *>(VectorType::get(ArgTy, 2))
2085 : static_cast<Type *>(StructType::get(ArgTy, ArgTy));
Sanjay Patel57747212016-01-21 23:38:43 +00002086 } else {
2087 Name = "__sincospi_stret";
Serge Gueltone38003f2017-05-09 19:31:13 +00002088 ResTy = StructType::get(ArgTy, ArgTy);
Sanjay Patel57747212016-01-21 23:38:43 +00002089 }
2090
2091 Module *M = OrigCallee->getParent();
James Y Knight13680222019-02-01 02:28:03 +00002092 FunctionCallee Callee =
2093 M->getOrInsertFunction(Name, OrigCallee->getAttributes(), ResTy, ArgTy);
Sanjay Patel57747212016-01-21 23:38:43 +00002094
2095 if (Instruction *ArgInst = dyn_cast<Instruction>(Arg)) {
2096 // If the argument is an instruction, it must dominate all uses so put our
2097 // sincos call there.
2098 B.SetInsertPoint(ArgInst->getParent(), ++ArgInst->getIterator());
2099 } else {
2100 // Otherwise (e.g. for a constant) the beginning of the function is as
2101 // good a place as any.
2102 BasicBlock &EntryBB = B.GetInsertBlock()->getParent()->getEntryBlock();
2103 B.SetInsertPoint(&EntryBB, EntryBB.begin());
2104 }
2105
2106 SinCos = B.CreateCall(Callee, Arg, "sincospi");
2107
2108 if (SinCos->getType()->isStructTy()) {
2109 Sin = B.CreateExtractValue(SinCos, 0, "sinpi");
2110 Cos = B.CreateExtractValue(SinCos, 1, "cospi");
2111 } else {
2112 Sin = B.CreateExtractElement(SinCos, ConstantInt::get(B.getInt32Ty(), 0),
2113 "sinpi");
2114 Cos = B.CreateExtractElement(SinCos, ConstantInt::get(B.getInt32Ty(), 1),
2115 "cospi");
2116 }
2117}
Chris Bienemanad070d02014-09-17 20:55:46 +00002118
2119Value *LibCallSimplifier::optimizeSinCosPi(CallInst *CI, IRBuilder<> &B) {
Chris Bienemanad070d02014-09-17 20:55:46 +00002120 // Make sure the prototype is as expected, otherwise the rest of the
2121 // function is probably invalid and likely to abort.
2122 if (!isTrigLibCall(CI))
2123 return nullptr;
2124
2125 Value *Arg = CI->getArgOperand(0);
2126 SmallVector<CallInst *, 1> SinCalls;
2127 SmallVector<CallInst *, 1> CosCalls;
2128 SmallVector<CallInst *, 1> SinCosCalls;
2129
2130 bool IsFloat = Arg->getType()->isFloatTy();
2131
2132 // Look for all compatible sinpi, cospi and sincospi calls with the same
2133 // argument. If there are enough (in some sense) we can make the
2134 // substitution.
David Majnemerabae6b52016-03-19 04:53:02 +00002135 Function *F = CI->getFunction();
Chris Bienemanad070d02014-09-17 20:55:46 +00002136 for (User *U : Arg->users())
David Majnemerabae6b52016-03-19 04:53:02 +00002137 classifyArgUse(U, F, IsFloat, SinCalls, CosCalls, SinCosCalls);
Chris Bienemanad070d02014-09-17 20:55:46 +00002138
2139 // It's only worthwhile if both sinpi and cospi are actually used.
2140 if (SinCosCalls.empty() && (SinCalls.empty() || CosCalls.empty()))
2141 return nullptr;
2142
2143 Value *Sin, *Cos, *SinCos;
2144 insertSinCosCall(B, CI->getCalledFunction(), Arg, IsFloat, Sin, Cos, SinCos);
2145
Davide Italianof024a562016-12-16 02:28:38 +00002146 auto replaceTrigInsts = [this](SmallVectorImpl<CallInst *> &Calls,
2147 Value *Res) {
2148 for (CallInst *C : Calls)
2149 replaceAllUsesWith(C, Res);
2150 };
2151
Chris Bienemanad070d02014-09-17 20:55:46 +00002152 replaceTrigInsts(SinCalls, Sin);
2153 replaceTrigInsts(CosCalls, Cos);
2154 replaceTrigInsts(SinCosCalls, SinCos);
2155
2156 return nullptr;
2157}
2158
David Majnemerabae6b52016-03-19 04:53:02 +00002159void LibCallSimplifier::classifyArgUse(
2160 Value *Val, Function *F, bool IsFloat,
2161 SmallVectorImpl<CallInst *> &SinCalls,
2162 SmallVectorImpl<CallInst *> &CosCalls,
2163 SmallVectorImpl<CallInst *> &SinCosCalls) {
Chris Bienemanad070d02014-09-17 20:55:46 +00002164 CallInst *CI = dyn_cast<CallInst>(Val);
2165
2166 if (!CI)
2167 return;
2168
David Majnemerabae6b52016-03-19 04:53:02 +00002169 // Don't consider calls in other functions.
2170 if (CI->getFunction() != F)
2171 return;
2172
Chris Bienemanad070d02014-09-17 20:55:46 +00002173 Function *Callee = CI->getCalledFunction();
David L. Jonesd21529f2017-01-23 23:16:46 +00002174 LibFunc Func;
Ahmed Bougachad765a822016-04-27 19:04:35 +00002175 if (!Callee || !TLI->getLibFunc(*Callee, Func) || !TLI->has(Func) ||
Benjamin Kramer89766e52015-11-28 21:43:12 +00002176 !isTrigLibCall(CI))
Chris Bienemanad070d02014-09-17 20:55:46 +00002177 return;
2178
2179 if (IsFloat) {
David L. Jonesd21529f2017-01-23 23:16:46 +00002180 if (Func == LibFunc_sinpif)
Chris Bienemanad070d02014-09-17 20:55:46 +00002181 SinCalls.push_back(CI);
David L. Jonesd21529f2017-01-23 23:16:46 +00002182 else if (Func == LibFunc_cospif)
Chris Bienemanad070d02014-09-17 20:55:46 +00002183 CosCalls.push_back(CI);
David L. Jonesd21529f2017-01-23 23:16:46 +00002184 else if (Func == LibFunc_sincospif_stret)
Chris Bienemanad070d02014-09-17 20:55:46 +00002185 SinCosCalls.push_back(CI);
2186 } else {
David L. Jonesd21529f2017-01-23 23:16:46 +00002187 if (Func == LibFunc_sinpi)
Chris Bienemanad070d02014-09-17 20:55:46 +00002188 SinCalls.push_back(CI);
David L. Jonesd21529f2017-01-23 23:16:46 +00002189 else if (Func == LibFunc_cospi)
Chris Bienemanad070d02014-09-17 20:55:46 +00002190 CosCalls.push_back(CI);
David L. Jonesd21529f2017-01-23 23:16:46 +00002191 else if (Func == LibFunc_sincospi_stret)
Chris Bienemanad070d02014-09-17 20:55:46 +00002192 SinCosCalls.push_back(CI);
2193 }
2194}
2195
Meador Inge7415f842012-11-25 20:45:27 +00002196//===----------------------------------------------------------------------===//
2197// Integer Library Call Optimizations
2198//===----------------------------------------------------------------------===//
2199
Chris Bienemanad070d02014-09-17 20:55:46 +00002200Value *LibCallSimplifier::optimizeFFS(CallInst *CI, IRBuilder<> &B) {
Chris Bienemanad070d02014-09-17 20:55:46 +00002201 // ffs(x) -> x != 0 ? (i32)llvm.cttz(x)+1 : 0
Davide Italiano890e8502016-12-15 23:11:00 +00002202 Value *Op = CI->getArgOperand(0);
Chris Bienemanad070d02014-09-17 20:55:46 +00002203 Type *ArgType = Op->getType();
James Y Knight7976eb52019-02-01 20:43:25 +00002204 Function *F = Intrinsic::getDeclaration(CI->getCalledFunction()->getParent(),
2205 Intrinsic::cttz, ArgType);
Davide Italianoa1953862015-08-13 20:34:26 +00002206 Value *V = B.CreateCall(F, {Op, B.getTrue()}, "cttz");
Chris Bienemanad070d02014-09-17 20:55:46 +00002207 V = B.CreateAdd(V, ConstantInt::get(V->getType(), 1));
2208 V = B.CreateIntCast(V, B.getInt32Ty(), false);
Meador Ingea0b6d872012-11-26 00:24:07 +00002209
Chris Bienemanad070d02014-09-17 20:55:46 +00002210 Value *Cond = B.CreateICmpNE(Op, Constant::getNullValue(ArgType));
2211 return B.CreateSelect(Cond, V, B.getInt32(0));
2212}
Meador Ingea0b6d872012-11-26 00:24:07 +00002213
Davide Italiano85ad36b2016-12-15 23:45:11 +00002214Value *LibCallSimplifier::optimizeFls(CallInst *CI, IRBuilder<> &B) {
2215 // fls(x) -> (i32)(sizeInBits(x) - llvm.ctlz(x, false))
2216 Value *Op = CI->getArgOperand(0);
2217 Type *ArgType = Op->getType();
James Y Knight7976eb52019-02-01 20:43:25 +00002218 Function *F = Intrinsic::getDeclaration(CI->getCalledFunction()->getParent(),
2219 Intrinsic::ctlz, ArgType);
Davide Italiano85ad36b2016-12-15 23:45:11 +00002220 Value *V = B.CreateCall(F, {Op, B.getFalse()}, "ctlz");
2221 V = B.CreateSub(ConstantInt::get(V->getType(), ArgType->getIntegerBitWidth()),
2222 V);
2223 return B.CreateIntCast(V, CI->getType(), false);
2224}
2225
Chris Bienemanad070d02014-09-17 20:55:46 +00002226Value *LibCallSimplifier::optimizeAbs(CallInst *CI, IRBuilder<> &B) {
Sanjay Patel4b969352018-05-22 23:29:40 +00002227 // abs(x) -> x <s 0 ? -x : x
2228 // The negation has 'nsw' because abs of INT_MIN is undefined.
2229 Value *X = CI->getArgOperand(0);
2230 Value *IsNeg = B.CreateICmpSLT(X, Constant::getNullValue(X->getType()));
2231 Value *NegX = B.CreateNSWNeg(X, "neg");
2232 return B.CreateSelect(IsNeg, NegX, X);
Chris Bienemanad070d02014-09-17 20:55:46 +00002233}
Meador Inge9a59ab62012-11-26 02:31:59 +00002234
Chris Bienemanad070d02014-09-17 20:55:46 +00002235Value *LibCallSimplifier::optimizeIsDigit(CallInst *CI, IRBuilder<> &B) {
Chris Bienemanad070d02014-09-17 20:55:46 +00002236 // isdigit(c) -> (c-'0') <u 10
2237 Value *Op = CI->getArgOperand(0);
2238 Op = B.CreateSub(Op, B.getInt32('0'), "isdigittmp");
2239 Op = B.CreateICmpULT(Op, B.getInt32(10), "isdigit");
2240 return B.CreateZExt(Op, CI->getType());
2241}
Meador Ingea62a39e2012-11-26 03:10:07 +00002242
Chris Bienemanad070d02014-09-17 20:55:46 +00002243Value *LibCallSimplifier::optimizeIsAscii(CallInst *CI, IRBuilder<> &B) {
Chris Bienemanad070d02014-09-17 20:55:46 +00002244 // isascii(c) -> c <u 128
2245 Value *Op = CI->getArgOperand(0);
2246 Op = B.CreateICmpULT(Op, B.getInt32(128), "isascii");
2247 return B.CreateZExt(Op, CI->getType());
2248}
2249
2250Value *LibCallSimplifier::optimizeToAscii(CallInst *CI, IRBuilder<> &B) {
Chris Bienemanad070d02014-09-17 20:55:46 +00002251 // toascii(c) -> c & 0x7f
2252 return B.CreateAnd(CI->getArgOperand(0),
2253 ConstantInt::get(CI->getType(), 0x7F));
2254}
Meador Inge604937d2012-11-26 03:38:52 +00002255
David Bolvanskycb8ca5f32018-04-25 18:58:53 +00002256Value *LibCallSimplifier::optimizeAtoi(CallInst *CI, IRBuilder<> &B) {
2257 StringRef Str;
2258 if (!getConstantStringInfo(CI->getArgOperand(0), Str))
2259 return nullptr;
2260
2261 return convertStrToNumber(CI, Str, 10);
2262}
2263
2264Value *LibCallSimplifier::optimizeStrtol(CallInst *CI, IRBuilder<> &B) {
2265 StringRef Str;
2266 if (!getConstantStringInfo(CI->getArgOperand(0), Str))
2267 return nullptr;
2268
2269 if (!isa<ConstantPointerNull>(CI->getArgOperand(1)))
2270 return nullptr;
2271
2272 if (ConstantInt *CInt = dyn_cast<ConstantInt>(CI->getArgOperand(2))) {
2273 return convertStrToNumber(CI, Str, CInt->getSExtValue());
2274 }
2275
2276 return nullptr;
2277}
2278
Meador Inge08ca1152012-11-26 20:37:20 +00002279//===----------------------------------------------------------------------===//
2280// Formatting and IO Library Call Optimizations
2281//===----------------------------------------------------------------------===//
2282
Chris Bienemanad070d02014-09-17 20:55:46 +00002283static bool isReportingError(Function *Callee, CallInst *CI, int StreamArg);
Hal Finkel66cd3f12013-11-17 02:06:35 +00002284
Chris Bienemanad070d02014-09-17 20:55:46 +00002285Value *LibCallSimplifier::optimizeErrorReporting(CallInst *CI, IRBuilder<> &B,
2286 int StreamArg) {
Ahmed Bougachad765a822016-04-27 19:04:35 +00002287 Function *Callee = CI->getCalledFunction();
Chris Bienemanad070d02014-09-17 20:55:46 +00002288 // Error reporting calls should be cold, mark them as such.
2289 // This applies even to non-builtin calls: it is only a hint and applies to
2290 // functions that the frontend might not understand as builtins.
Hal Finkel66cd3f12013-11-17 02:06:35 +00002291
Chris Bienemanad070d02014-09-17 20:55:46 +00002292 // This heuristic was suggested in:
2293 // Improving Static Branch Prediction in a Compiler
2294 // Brian L. Deitrich, Ben-Chung Cheng, Wen-mei W. Hwu
2295 // Proceedings of PACT'98, Oct. 1998, IEEE
Chris Bienemanad070d02014-09-17 20:55:46 +00002296 if (!CI->hasFnAttr(Attribute::Cold) &&
2297 isReportingError(Callee, CI, StreamArg)) {
Reid Klecknerb5180542017-03-21 16:57:19 +00002298 CI->addAttribute(AttributeList::FunctionIndex, Attribute::Cold);
Chris Bienemanad070d02014-09-17 20:55:46 +00002299 }
Hal Finkel66cd3f12013-11-17 02:06:35 +00002300
Chris Bienemanad070d02014-09-17 20:55:46 +00002301 return nullptr;
2302}
2303
2304static bool isReportingError(Function *Callee, CallInst *CI, int StreamArg) {
Davide Italiano5b65f122017-04-25 03:48:47 +00002305 if (!Callee || !Callee->isDeclaration())
Chris Bienemanad070d02014-09-17 20:55:46 +00002306 return false;
2307
2308 if (StreamArg < 0)
2309 return true;
2310
2311 // These functions might be considered cold, but only if their stream
2312 // argument is stderr.
2313
2314 if (StreamArg >= (int)CI->getNumArgOperands())
2315 return false;
2316 LoadInst *LI = dyn_cast<LoadInst>(CI->getArgOperand(StreamArg));
2317 if (!LI)
2318 return false;
2319 GlobalVariable *GV = dyn_cast<GlobalVariable>(LI->getPointerOperand());
2320 if (!GV || !GV->isDeclaration())
2321 return false;
2322 return GV->getName() == "stderr";
2323}
2324
2325Value *LibCallSimplifier::optimizePrintFString(CallInst *CI, IRBuilder<> &B) {
2326 // Check for a fixed format string.
2327 StringRef FormatStr;
2328 if (!getConstantStringInfo(CI->getArgOperand(0), FormatStr))
Craig Topperf40110f2014-04-25 05:29:35 +00002329 return nullptr;
Hal Finkel66cd3f12013-11-17 02:06:35 +00002330
Chris Bienemanad070d02014-09-17 20:55:46 +00002331 // Empty format string -> noop.
2332 if (FormatStr.empty()) // Tolerate printf's declared void.
2333 return CI->use_empty() ? (Value *)CI : ConstantInt::get(CI->getType(), 0);
Hal Finkel66cd3f12013-11-17 02:06:35 +00002334
Chris Bienemanad070d02014-09-17 20:55:46 +00002335 // Do not do any of the following transformations if the printf return value
2336 // is used, in general the printf return value is not compatible with either
2337 // putchar() or puts().
2338 if (!CI->use_empty())
Craig Topperf40110f2014-04-25 05:29:35 +00002339 return nullptr;
Chris Bienemanad070d02014-09-17 20:55:46 +00002340
Joerg Sonnenberger8ffe7ab2016-05-09 14:36:16 +00002341 // printf("x") -> putchar('x'), even for "%" and "%%".
2342 if (FormatStr.size() == 1 || FormatStr == "%%")
Davide Italianod4f5a052016-04-03 01:46:52 +00002343 return emitPutChar(B.getInt32(FormatStr[0]), B, TLI);
Meador Inge08ca1152012-11-26 20:37:20 +00002344
Davide Italiano6db1dcb2016-03-28 15:54:01 +00002345 // printf("%s", "a") --> putchar('a')
2346 if (FormatStr == "%s" && CI->getNumArgOperands() > 1) {
2347 StringRef ChrStr;
2348 if (!getConstantStringInfo(CI->getOperand(1), ChrStr))
2349 return nullptr;
2350 if (ChrStr.size() != 1)
2351 return nullptr;
Davide Italianod4f5a052016-04-03 01:46:52 +00002352 return emitPutChar(B.getInt32(ChrStr[0]), B, TLI);
Davide Italiano6db1dcb2016-03-28 15:54:01 +00002353 }
2354
Chris Bienemanad070d02014-09-17 20:55:46 +00002355 // printf("foo\n") --> puts("foo")
2356 if (FormatStr[FormatStr.size() - 1] == '\n' &&
2357 FormatStr.find('%') == StringRef::npos) { // No format characters.
2358 // Create a string literal with no \n on it. We expect the constant merge
2359 // pass to be run after this pass, to merge duplicate strings.
2360 FormatStr = FormatStr.drop_back();
2361 Value *GV = B.CreateGlobalString(FormatStr, "str");
Davide Italianod4f5a052016-04-03 01:46:52 +00002362 return emitPutS(GV, B, TLI);
Chris Bienemanad070d02014-09-17 20:55:46 +00002363 }
Meador Inge08ca1152012-11-26 20:37:20 +00002364
Chris Bienemanad070d02014-09-17 20:55:46 +00002365 // Optimize specific format strings.
2366 // printf("%c", chr) --> putchar(chr)
2367 if (FormatStr == "%c" && CI->getNumArgOperands() > 1 &&
Davide Italianod4f5a052016-04-03 01:46:52 +00002368 CI->getArgOperand(1)->getType()->isIntegerTy())
2369 return emitPutChar(CI->getArgOperand(1), B, TLI);
Chris Bienemanad070d02014-09-17 20:55:46 +00002370
2371 // printf("%s\n", str) --> puts(str)
2372 if (FormatStr == "%s\n" && CI->getNumArgOperands() > 1 &&
Davide Italianod4f5a052016-04-03 01:46:52 +00002373 CI->getArgOperand(1)->getType()->isPointerTy())
Sanjay Pateld3112a52016-01-19 19:46:10 +00002374 return emitPutS(CI->getArgOperand(1), B, TLI);
Chris Bienemanad070d02014-09-17 20:55:46 +00002375 return nullptr;
2376}
2377
2378Value *LibCallSimplifier::optimizePrintF(CallInst *CI, IRBuilder<> &B) {
2379
2380 Function *Callee = CI->getCalledFunction();
Chris Bienemanad070d02014-09-17 20:55:46 +00002381 FunctionType *FT = Callee->getFunctionType();
Chris Bienemanad070d02014-09-17 20:55:46 +00002382 if (Value *V = optimizePrintFString(CI, B)) {
2383 return V;
2384 }
2385
2386 // printf(format, ...) -> iprintf(format, ...) if no floating point
2387 // arguments.
David L. Jonesd21529f2017-01-23 23:16:46 +00002388 if (TLI->has(LibFunc_iprintf) && !callHasFloatingPointArgument(CI)) {
Chris Bienemanad070d02014-09-17 20:55:46 +00002389 Module *M = B.GetInsertBlock()->getParent()->getParent();
James Y Knight13680222019-02-01 02:28:03 +00002390 FunctionCallee IPrintFFn =
Meador Inge08ca1152012-11-26 20:37:20 +00002391 M->getOrInsertFunction("iprintf", FT, Callee->getAttributes());
Chris Bienemanad070d02014-09-17 20:55:46 +00002392 CallInst *New = cast<CallInst>(CI->clone());
2393 New->setCalledFunction(IPrintFFn);
2394 B.Insert(New);
2395 return New;
Meador Inge08ca1152012-11-26 20:37:20 +00002396 }
Alon Zakaib4f99912019-04-03 01:08:35 +00002397
2398 // printf(format, ...) -> __small_printf(format, ...) if no 128-bit floating point
2399 // arguments.
2400 if (TLI->has(LibFunc_small_printf) && !callHasFP128Argument(CI)) {
2401 Module *M = B.GetInsertBlock()->getParent()->getParent();
2402 auto SmallPrintFFn =
2403 M->getOrInsertFunction(TLI->getName(LibFunc_small_printf),
2404 FT, Callee->getAttributes());
2405 CallInst *New = cast<CallInst>(CI->clone());
2406 New->setCalledFunction(SmallPrintFFn);
2407 B.Insert(New);
2408 return New;
2409 }
2410
David Bolvanskye80fcf02019-09-17 09:32:52 +00002411 annotateNonNullBasedOnAccess(CI, 0);
Chris Bienemanad070d02014-09-17 20:55:46 +00002412 return nullptr;
2413}
Meador Inge08ca1152012-11-26 20:37:20 +00002414
Chris Bienemanad070d02014-09-17 20:55:46 +00002415Value *LibCallSimplifier::optimizeSPrintFString(CallInst *CI, IRBuilder<> &B) {
2416 // Check for a fixed format string.
2417 StringRef FormatStr;
David Bolvansky40375822019-10-01 13:19:04 +00002418 if (!getConstantStringInfo(CI->getArgOperand(1), FormatStr))
Craig Topperf40110f2014-04-25 05:29:35 +00002419 return nullptr;
Meador Inge25c9b3b2012-11-27 05:57:54 +00002420
Chris Bienemanad070d02014-09-17 20:55:46 +00002421 // If we just have a format string (nothing else crazy) transform it.
2422 if (CI->getNumArgOperands() == 2) {
2423 // Make sure there's no % in the constant array. We could try to handle
2424 // %% -> % in the future if we cared.
David Bolvansky5430b7372018-05-31 16:39:27 +00002425 if (FormatStr.find('%') != StringRef::npos)
2426 return nullptr; // we found a format specifier, bail out.
Hal Finkel66cd3f12013-11-17 02:06:35 +00002427
Daniel Neilson8acd8b02018-02-05 21:23:22 +00002428 // sprintf(str, fmt) -> llvm.memcpy(align 1 str, align 1 fmt, strlen(fmt)+1)
David Bolvansky40375822019-10-01 13:19:04 +00002429 B.CreateMemCpy(CI->getArgOperand(0), 1, CI->getArgOperand(1), 1,
2430 ConstantInt::get(DL.getIntPtrType(CI->getContext()),
2431 FormatStr.size() + 1)); // Copy the null byte.
Chris Bienemanad070d02014-09-17 20:55:46 +00002432 return ConstantInt::get(CI->getType(), FormatStr.size());
Meador Ingef8e72502012-11-29 15:45:43 +00002433 }
Meador Ingef8e72502012-11-29 15:45:43 +00002434
Chris Bienemanad070d02014-09-17 20:55:46 +00002435 // The remaining optimizations require the format string to be "%s" or "%c"
2436 // and have an extra operand.
2437 if (FormatStr.size() != 2 || FormatStr[0] != '%' ||
2438 CI->getNumArgOperands() < 3)
Craig Topperf40110f2014-04-25 05:29:35 +00002439 return nullptr;
Meador Inge75798bb2012-11-29 19:15:17 +00002440
Chris Bienemanad070d02014-09-17 20:55:46 +00002441 // Decode the second character of the format string.
2442 if (FormatStr[1] == 'c') {
2443 // sprintf(dst, "%c", chr) --> *(i8*)dst = chr; *((i8*)dst+1) = 0
David Bolvansky40375822019-10-01 13:19:04 +00002444 if (!CI->getArgOperand(2)->getType()->isIntegerTy())
Chris Bienemanad070d02014-09-17 20:55:46 +00002445 return nullptr;
David Bolvansky40375822019-10-01 13:19:04 +00002446 Value *V = B.CreateTrunc(CI->getArgOperand(2), B.getInt8Ty(), "char");
2447 Value *Ptr = castToCStr(CI->getArgOperand(0), B);
Chris Bienemanad070d02014-09-17 20:55:46 +00002448 B.CreateStore(V, Ptr);
David Blaikie3909da72015-03-30 20:42:56 +00002449 Ptr = B.CreateGEP(B.getInt8Ty(), Ptr, B.getInt32(1), "nul");
Chris Bienemanad070d02014-09-17 20:55:46 +00002450 B.CreateStore(B.getInt8(0), Ptr);
Meador Ingedf796f82012-10-13 16:45:24 +00002451
Chris Bienemanad070d02014-09-17 20:55:46 +00002452 return ConstantInt::get(CI->getType(), 1);
Meador Ingedf796f82012-10-13 16:45:24 +00002453 }
2454
Chris Bienemanad070d02014-09-17 20:55:46 +00002455 if (FormatStr[1] == 's') {
Fangrui Songf2609672019-03-12 10:31:52 +00002456 // sprintf(dest, "%s", str) -> llvm.memcpy(align 1 dest, align 1 str,
2457 // strlen(str)+1)
David Bolvansky40375822019-10-01 13:19:04 +00002458 if (!CI->getArgOperand(2)->getType()->isPointerTy())
2459 return nullptr;
2460
2461 Value *Len = emitStrLen(CI->getArgOperand(2), B, DL, TLI);
Chris Bienemanad070d02014-09-17 20:55:46 +00002462 if (!Len)
2463 return nullptr;
David Majnemerabb9f552016-04-26 21:04:47 +00002464 Value *IncLen =
2465 B.CreateAdd(Len, ConstantInt::get(Len->getType(), 1), "leninc");
David Bolvansky40375822019-10-01 13:19:04 +00002466 B.CreateMemCpy(CI->getArgOperand(0), 1, CI->getArgOperand(2), 1, IncLen);
Chris Bienemanad070d02014-09-17 20:55:46 +00002467
2468 // The sprintf result is the unincremented number of bytes in the string.
2469 return B.CreateIntCast(Len, CI->getType(), false);
2470 }
2471 return nullptr;
2472}
2473
2474Value *LibCallSimplifier::optimizeSPrintF(CallInst *CI, IRBuilder<> &B) {
2475 Function *Callee = CI->getCalledFunction();
Chris Bienemanad070d02014-09-17 20:55:46 +00002476 FunctionType *FT = Callee->getFunctionType();
Chris Bienemanad070d02014-09-17 20:55:46 +00002477 if (Value *V = optimizeSPrintFString(CI, B)) {
2478 return V;
2479 }
2480
2481 // sprintf(str, format, ...) -> siprintf(str, format, ...) if no floating
2482 // point arguments.
David L. Jonesd21529f2017-01-23 23:16:46 +00002483 if (TLI->has(LibFunc_siprintf) && !callHasFloatingPointArgument(CI)) {
Chris Bienemanad070d02014-09-17 20:55:46 +00002484 Module *M = B.GetInsertBlock()->getParent()->getParent();
James Y Knight13680222019-02-01 02:28:03 +00002485 FunctionCallee SIPrintFFn =
Chris Bienemanad070d02014-09-17 20:55:46 +00002486 M->getOrInsertFunction("siprintf", FT, Callee->getAttributes());
2487 CallInst *New = cast<CallInst>(CI->clone());
2488 New->setCalledFunction(SIPrintFFn);
2489 B.Insert(New);
2490 return New;
2491 }
Alon Zakaib4f99912019-04-03 01:08:35 +00002492
2493 // sprintf(str, format, ...) -> __small_sprintf(str, format, ...) if no 128-bit
2494 // floating point arguments.
2495 if (TLI->has(LibFunc_small_sprintf) && !callHasFP128Argument(CI)) {
2496 Module *M = B.GetInsertBlock()->getParent()->getParent();
2497 auto SmallSPrintFFn =
2498 M->getOrInsertFunction(TLI->getName(LibFunc_small_sprintf),
2499 FT, Callee->getAttributes());
2500 CallInst *New = cast<CallInst>(CI->clone());
2501 New->setCalledFunction(SmallSPrintFFn);
2502 B.Insert(New);
2503 return New;
2504 }
2505
David Bolvanskye80fcf02019-09-17 09:32:52 +00002506 annotateNonNullBasedOnAccess(CI, {0, 1});
Chris Bienemanad070d02014-09-17 20:55:46 +00002507 return nullptr;
2508}
2509
David Bolvanskycd93c4e2018-05-11 17:50:49 +00002510Value *LibCallSimplifier::optimizeSnPrintFString(CallInst *CI, IRBuilder<> &B) {
David Bolvanskycd93c4e2018-05-11 17:50:49 +00002511 // Check for size
2512 ConstantInt *Size = dyn_cast<ConstantInt>(CI->getArgOperand(1));
2513 if (!Size)
2514 return nullptr;
2515
2516 uint64_t N = Size->getZExtValue();
David Bolvanskye80fcf02019-09-17 09:32:52 +00002517 // Check for a fixed format string.
2518 StringRef FormatStr;
2519 if (!getConstantStringInfo(CI->getArgOperand(2), FormatStr))
2520 return nullptr;
David Bolvanskycd93c4e2018-05-11 17:50:49 +00002521
2522 // If we just have a format string (nothing else crazy) transform it.
2523 if (CI->getNumArgOperands() == 3) {
2524 // Make sure there's no % in the constant array. We could try to handle
2525 // %% -> % in the future if we cared.
David Bolvansky5430b7372018-05-31 16:39:27 +00002526 if (FormatStr.find('%') != StringRef::npos)
2527 return nullptr; // we found a format specifier, bail out.
David Bolvanskycd93c4e2018-05-11 17:50:49 +00002528
2529 if (N == 0)
2530 return ConstantInt::get(CI->getType(), FormatStr.size());
2531 else if (N < FormatStr.size() + 1)
2532 return nullptr;
2533
Fangrui Songf2609672019-03-12 10:31:52 +00002534 // snprintf(dst, size, fmt) -> llvm.memcpy(align 1 dst, align 1 fmt,
David Bolvanskycd93c4e2018-05-11 17:50:49 +00002535 // strlen(fmt)+1)
2536 B.CreateMemCpy(
2537 CI->getArgOperand(0), 1, CI->getArgOperand(2), 1,
2538 ConstantInt::get(DL.getIntPtrType(CI->getContext()),
2539 FormatStr.size() + 1)); // Copy the null byte.
2540 return ConstantInt::get(CI->getType(), FormatStr.size());
2541 }
2542
2543 // The remaining optimizations require the format string to be "%s" or "%c"
2544 // and have an extra operand.
2545 if (FormatStr.size() == 2 && FormatStr[0] == '%' &&
2546 CI->getNumArgOperands() == 4) {
2547
2548 // Decode the second character of the format string.
2549 if (FormatStr[1] == 'c') {
2550 if (N == 0)
2551 return ConstantInt::get(CI->getType(), 1);
2552 else if (N == 1)
2553 return nullptr;
2554
2555 // snprintf(dst, size, "%c", chr) --> *(i8*)dst = chr; *((i8*)dst+1) = 0
2556 if (!CI->getArgOperand(3)->getType()->isIntegerTy())
2557 return nullptr;
2558 Value *V = B.CreateTrunc(CI->getArgOperand(3), B.getInt8Ty(), "char");
2559 Value *Ptr = castToCStr(CI->getArgOperand(0), B);
2560 B.CreateStore(V, Ptr);
2561 Ptr = B.CreateGEP(B.getInt8Ty(), Ptr, B.getInt32(1), "nul");
2562 B.CreateStore(B.getInt8(0), Ptr);
2563
2564 return ConstantInt::get(CI->getType(), 1);
2565 }
2566
2567 if (FormatStr[1] == 's') {
2568 // snprintf(dest, size, "%s", str) to llvm.memcpy(dest, str, len+1, 1)
2569 StringRef Str;
2570 if (!getConstantStringInfo(CI->getArgOperand(3), Str))
2571 return nullptr;
2572
2573 if (N == 0)
2574 return ConstantInt::get(CI->getType(), Str.size());
2575 else if (N < Str.size() + 1)
2576 return nullptr;
2577
2578 B.CreateMemCpy(CI->getArgOperand(0), 1, CI->getArgOperand(3), 1,
2579 ConstantInt::get(CI->getType(), Str.size() + 1));
2580
2581 // The snprintf result is the unincremented number of bytes in the string.
2582 return ConstantInt::get(CI->getType(), Str.size());
2583 }
2584 }
2585 return nullptr;
2586}
2587
2588Value *LibCallSimplifier::optimizeSnPrintF(CallInst *CI, IRBuilder<> &B) {
2589 if (Value *V = optimizeSnPrintFString(CI, B)) {
2590 return V;
2591 }
2592
David Bolvanskye80fcf02019-09-17 09:32:52 +00002593 if (isKnownNonZero(CI->getOperand(1), DL))
2594 annotateNonNullBasedOnAccess(CI, 0);
David Bolvanskycd93c4e2018-05-11 17:50:49 +00002595 return nullptr;
2596}
2597
Chris Bienemanad070d02014-09-17 20:55:46 +00002598Value *LibCallSimplifier::optimizeFPrintFString(CallInst *CI, IRBuilder<> &B) {
2599 optimizeErrorReporting(CI, B, 0);
2600
2601 // All the optimizations depend on the format string.
2602 StringRef FormatStr;
2603 if (!getConstantStringInfo(CI->getArgOperand(1), FormatStr))
2604 return nullptr;
2605
2606 // Do not do any of the following transformations if the fprintf return
2607 // value is used, in general the fprintf return value is not compatible
2608 // with fwrite(), fputc() or fputs().
2609 if (!CI->use_empty())
2610 return nullptr;
2611
2612 // fprintf(F, "foo") --> fwrite("foo", 3, 1, F)
2613 if (CI->getNumArgOperands() == 2) {
David Bolvansky5430b7372018-05-31 16:39:27 +00002614 // Could handle %% -> % if we cared.
2615 if (FormatStr.find('%') != StringRef::npos)
2616 return nullptr; // We found a format specifier.
Chris Bienemanad070d02014-09-17 20:55:46 +00002617
Sanjay Pateld3112a52016-01-19 19:46:10 +00002618 return emitFWrite(
Chris Bienemanad070d02014-09-17 20:55:46 +00002619 CI->getArgOperand(1),
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002620 ConstantInt::get(DL.getIntPtrType(CI->getContext()), FormatStr.size()),
Chris Bienemanad070d02014-09-17 20:55:46 +00002621 CI->getArgOperand(0), B, DL, TLI);
2622 }
2623
2624 // The remaining optimizations require the format string to be "%s" or "%c"
2625 // and have an extra operand.
2626 if (FormatStr.size() != 2 || FormatStr[0] != '%' ||
2627 CI->getNumArgOperands() < 3)
2628 return nullptr;
2629
2630 // Decode the second character of the format string.
2631 if (FormatStr[1] == 'c') {
2632 // fprintf(F, "%c", chr) --> fputc(chr, F)
2633 if (!CI->getArgOperand(2)->getType()->isIntegerTy())
2634 return nullptr;
Sanjay Pateld3112a52016-01-19 19:46:10 +00002635 return emitFPutC(CI->getArgOperand(2), CI->getArgOperand(0), B, TLI);
Chris Bienemanad070d02014-09-17 20:55:46 +00002636 }
2637
2638 if (FormatStr[1] == 's') {
2639 // fprintf(F, "%s", str) --> fputs(str, F)
2640 if (!CI->getArgOperand(2)->getType()->isPointerTy())
2641 return nullptr;
Sanjay Pateld3112a52016-01-19 19:46:10 +00002642 return emitFPutS(CI->getArgOperand(2), CI->getArgOperand(0), B, TLI);
Chris Bienemanad070d02014-09-17 20:55:46 +00002643 }
2644 return nullptr;
2645}
2646
2647Value *LibCallSimplifier::optimizeFPrintF(CallInst *CI, IRBuilder<> &B) {
2648 Function *Callee = CI->getCalledFunction();
Chris Bienemanad070d02014-09-17 20:55:46 +00002649 FunctionType *FT = Callee->getFunctionType();
Chris Bienemanad070d02014-09-17 20:55:46 +00002650 if (Value *V = optimizeFPrintFString(CI, B)) {
2651 return V;
2652 }
2653
2654 // fprintf(stream, format, ...) -> fiprintf(stream, format, ...) if no
2655 // floating point arguments.
David L. Jonesd21529f2017-01-23 23:16:46 +00002656 if (TLI->has(LibFunc_fiprintf) && !callHasFloatingPointArgument(CI)) {
Chris Bienemanad070d02014-09-17 20:55:46 +00002657 Module *M = B.GetInsertBlock()->getParent()->getParent();
James Y Knight13680222019-02-01 02:28:03 +00002658 FunctionCallee FIPrintFFn =
Chris Bienemanad070d02014-09-17 20:55:46 +00002659 M->getOrInsertFunction("fiprintf", FT, Callee->getAttributes());
2660 CallInst *New = cast<CallInst>(CI->clone());
2661 New->setCalledFunction(FIPrintFFn);
2662 B.Insert(New);
2663 return New;
2664 }
Alon Zakaib4f99912019-04-03 01:08:35 +00002665
2666 // fprintf(stream, format, ...) -> __small_fprintf(stream, format, ...) if no
2667 // 128-bit floating point arguments.
2668 if (TLI->has(LibFunc_small_fprintf) && !callHasFP128Argument(CI)) {
2669 Module *M = B.GetInsertBlock()->getParent()->getParent();
2670 auto SmallFPrintFFn =
2671 M->getOrInsertFunction(TLI->getName(LibFunc_small_fprintf),
2672 FT, Callee->getAttributes());
2673 CallInst *New = cast<CallInst>(CI->clone());
2674 New->setCalledFunction(SmallFPrintFFn);
2675 B.Insert(New);
2676 return New;
2677 }
2678
Chris Bienemanad070d02014-09-17 20:55:46 +00002679 return nullptr;
2680}
2681
2682Value *LibCallSimplifier::optimizeFWrite(CallInst *CI, IRBuilder<> &B) {
2683 optimizeErrorReporting(CI, B, 3);
2684
Chris Bienemanad070d02014-09-17 20:55:46 +00002685 // Get the element size and count.
2686 ConstantInt *SizeC = dyn_cast<ConstantInt>(CI->getArgOperand(1));
2687 ConstantInt *CountC = dyn_cast<ConstantInt>(CI->getArgOperand(2));
David Bolvanskyca22d422018-05-16 11:39:52 +00002688 if (SizeC && CountC) {
2689 uint64_t Bytes = SizeC->getZExtValue() * CountC->getZExtValue();
Chris Bienemanad070d02014-09-17 20:55:46 +00002690
David Bolvanskyca22d422018-05-16 11:39:52 +00002691 // If this is writing zero records, remove the call (it's a noop).
2692 if (Bytes == 0)
2693 return ConstantInt::get(CI->getType(), 0);
Chris Bienemanad070d02014-09-17 20:55:46 +00002694
David Bolvanskyca22d422018-05-16 11:39:52 +00002695 // If this is writing one byte, turn it into fputc.
2696 // This optimisation is only valid, if the return value is unused.
2697 if (Bytes == 1 && CI->use_empty()) { // fwrite(S,1,1,F) -> fputc(S[0],F)
James Y Knight14359ef2019-02-01 20:44:24 +00002698 Value *Char = B.CreateLoad(B.getInt8Ty(),
2699 castToCStr(CI->getArgOperand(0), B), "char");
David Bolvanskyca22d422018-05-16 11:39:52 +00002700 Value *NewCI = emitFPutC(Char, CI->getArgOperand(3), B, TLI);
2701 return NewCI ? ConstantInt::get(CI->getType(), 1) : nullptr;
2702 }
Chris Bienemanad070d02014-09-17 20:55:46 +00002703 }
2704
David Bolvanskyca22d422018-05-16 11:39:52 +00002705 if (isLocallyOpenedFile(CI->getArgOperand(3), CI, B, TLI))
2706 return emitFWriteUnlocked(CI->getArgOperand(0), CI->getArgOperand(1),
2707 CI->getArgOperand(2), CI->getArgOperand(3), B, DL,
2708 TLI);
2709
Chris Bienemanad070d02014-09-17 20:55:46 +00002710 return nullptr;
2711}
2712
2713Value *LibCallSimplifier::optimizeFPuts(CallInst *CI, IRBuilder<> &B) {
2714 optimizeErrorReporting(CI, B, 1);
2715
Sjoerd Meijer7435a912016-07-07 14:31:19 +00002716 // Don't rewrite fputs to fwrite when optimising for size because fwrite
2717 // requires more arguments and thus extra MOVs are required.
Hiroshi Yamauchi09e539f2019-04-15 16:49:00 +00002718 bool OptForSize = CI->getFunction()->hasOptSize() ||
2719 llvm::shouldOptimizeForSize(CI->getParent(), PSI, BFI);
2720 if (OptForSize)
Sjoerd Meijer7435a912016-07-07 14:31:19 +00002721 return nullptr;
2722
David Bolvanskyca22d422018-05-16 11:39:52 +00002723 // Check if has any use
2724 if (!CI->use_empty()) {
2725 if (isLocallyOpenedFile(CI->getArgOperand(1), CI, B, TLI))
2726 return emitFPutSUnlocked(CI->getArgOperand(0), CI->getArgOperand(1), B,
2727 TLI);
2728 else
2729 // We can't optimize if return value is used.
2730 return nullptr;
2731 }
Chris Bienemanad070d02014-09-17 20:55:46 +00002732
Fangrui Songf2609672019-03-12 10:31:52 +00002733 // fputs(s,F) --> fwrite(s,strlen(s),1,F)
David Bolvansky1f343fa2018-05-22 20:27:36 +00002734 uint64_t Len = GetStringLength(CI->getArgOperand(0));
Chris Bienemanad070d02014-09-17 20:55:46 +00002735 if (!Len)
2736 return nullptr;
2737
2738 // Known to have no uses (see above).
Sanjay Pateld3112a52016-01-19 19:46:10 +00002739 return emitFWrite(
Chris Bienemanad070d02014-09-17 20:55:46 +00002740 CI->getArgOperand(0),
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002741 ConstantInt::get(DL.getIntPtrType(CI->getContext()), Len - 1),
Chris Bienemanad070d02014-09-17 20:55:46 +00002742 CI->getArgOperand(1), B, DL, TLI);
2743}
2744
David Bolvanskyca22d422018-05-16 11:39:52 +00002745Value *LibCallSimplifier::optimizeFPutc(CallInst *CI, IRBuilder<> &B) {
2746 optimizeErrorReporting(CI, B, 1);
2747
2748 if (isLocallyOpenedFile(CI->getArgOperand(1), CI, B, TLI))
2749 return emitFPutCUnlocked(CI->getArgOperand(0), CI->getArgOperand(1), B,
2750 TLI);
2751
2752 return nullptr;
2753}
2754
2755Value *LibCallSimplifier::optimizeFGetc(CallInst *CI, IRBuilder<> &B) {
2756 if (isLocallyOpenedFile(CI->getArgOperand(0), CI, B, TLI))
2757 return emitFGetCUnlocked(CI->getArgOperand(0), B, TLI);
2758
2759 return nullptr;
2760}
2761
2762Value *LibCallSimplifier::optimizeFGets(CallInst *CI, IRBuilder<> &B) {
2763 if (isLocallyOpenedFile(CI->getArgOperand(2), CI, B, TLI))
2764 return emitFGetSUnlocked(CI->getArgOperand(0), CI->getArgOperand(1),
2765 CI->getArgOperand(2), B, TLI);
2766
2767 return nullptr;
2768}
2769
2770Value *LibCallSimplifier::optimizeFRead(CallInst *CI, IRBuilder<> &B) {
2771 if (isLocallyOpenedFile(CI->getArgOperand(3), CI, B, TLI))
2772 return emitFReadUnlocked(CI->getArgOperand(0), CI->getArgOperand(1),
2773 CI->getArgOperand(2), CI->getArgOperand(3), B, DL,
2774 TLI);
2775
2776 return nullptr;
2777}
2778
Chris Bienemanad070d02014-09-17 20:55:46 +00002779Value *LibCallSimplifier::optimizePuts(CallInst *CI, IRBuilder<> &B) {
David Bolvanskye80fcf02019-09-17 09:32:52 +00002780 annotateNonNullBasedOnAccess(CI, 0);
Fangrui Songb1dfbeb2019-03-12 14:20:22 +00002781 if (!CI->use_empty())
Chris Bienemanad070d02014-09-17 20:55:46 +00002782 return nullptr;
2783
Fangrui Songb1dfbeb2019-03-12 14:20:22 +00002784 // Check for a constant string.
2785 // puts("") -> putchar('\n')
2786 StringRef Str;
2787 if (getConstantStringInfo(CI->getArgOperand(0), Str) && Str.empty())
2788 return emitPutChar(B.getInt32('\n'), B, TLI);
Chris Bienemanad070d02014-09-17 20:55:46 +00002789
2790 return nullptr;
2791}
2792
David Bolvansky6b4502962019-10-02 22:49:20 +00002793Value *LibCallSimplifier::optimizeBCopy(CallInst *CI, IRBuilder<> &B) {
2794 // bcopy(src, dst, n) -> llvm.memmove(dst, src, n)
2795 return B.CreateMemMove(CI->getArgOperand(1), 1, CI->getArgOperand(0), 1,
2796 CI->getArgOperand(2));
2797}
2798
Chris Bienemanad070d02014-09-17 20:55:46 +00002799bool LibCallSimplifier::hasFloatVersion(StringRef FuncName) {
David L. Jonesd21529f2017-01-23 23:16:46 +00002800 LibFunc Func;
Meador Inge20255ef2013-03-12 00:08:29 +00002801 SmallString<20> FloatFuncName = FuncName;
2802 FloatFuncName += 'f';
2803 if (TLI->getLibFunc(FloatFuncName, Func))
2804 return TLI->has(Func);
2805 return false;
2806}
Meador Inge7fb2f732012-10-13 16:45:32 +00002807
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00002808Value *LibCallSimplifier::optimizeStringMemoryLibCall(CallInst *CI,
2809 IRBuilder<> &Builder) {
David L. Jonesd21529f2017-01-23 23:16:46 +00002810 LibFunc Func;
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00002811 Function *Callee = CI->getCalledFunction();
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00002812 // Check for string/memory library functions.
Ahmed Bougachad765a822016-04-27 19:04:35 +00002813 if (TLI->getLibFunc(*Callee, Func) && TLI->has(Func)) {
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00002814 // Make sure we never change the calling convention.
2815 assert((ignoreCallingConv(Func) ||
Sam Parker214f7bf2016-09-13 12:10:14 +00002816 isCallingConvCCompatible(CI)) &&
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00002817 "Optimizing string/memory libcall would change the calling convention");
2818 switch (Func) {
David L. Jonesd21529f2017-01-23 23:16:46 +00002819 case LibFunc_strcat:
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00002820 return optimizeStrCat(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002821 case LibFunc_strncat:
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00002822 return optimizeStrNCat(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002823 case LibFunc_strchr:
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00002824 return optimizeStrChr(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002825 case LibFunc_strrchr:
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00002826 return optimizeStrRChr(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002827 case LibFunc_strcmp:
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00002828 return optimizeStrCmp(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002829 case LibFunc_strncmp:
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00002830 return optimizeStrNCmp(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002831 case LibFunc_strcpy:
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00002832 return optimizeStrCpy(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002833 case LibFunc_stpcpy:
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00002834 return optimizeStpCpy(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002835 case LibFunc_strncpy:
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00002836 return optimizeStrNCpy(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002837 case LibFunc_strlen:
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00002838 return optimizeStrLen(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002839 case LibFunc_strpbrk:
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00002840 return optimizeStrPBrk(CI, Builder);
David Bolvansky8d520162019-09-23 18:20:01 +00002841 case LibFunc_strndup:
2842 return optimizeStrNDup(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002843 case LibFunc_strtol:
2844 case LibFunc_strtod:
2845 case LibFunc_strtof:
2846 case LibFunc_strtoul:
2847 case LibFunc_strtoll:
2848 case LibFunc_strtold:
2849 case LibFunc_strtoull:
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00002850 return optimizeStrTo(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002851 case LibFunc_strspn:
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00002852 return optimizeStrSpn(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002853 case LibFunc_strcspn:
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00002854 return optimizeStrCSpn(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002855 case LibFunc_strstr:
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00002856 return optimizeStrStr(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002857 case LibFunc_memchr:
Benjamin Kramer691363e2015-03-21 15:36:21 +00002858 return optimizeMemChr(CI, Builder);
David Bolvanskye80fcf02019-09-17 09:32:52 +00002859 case LibFunc_memrchr:
2860 return optimizeMemRChr(CI, Builder);
Clement Courbet9e1f2a72019-05-06 09:15:22 +00002861 case LibFunc_bcmp:
2862 return optimizeBCmp(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002863 case LibFunc_memcmp:
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00002864 return optimizeMemCmp(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002865 case LibFunc_memcpy:
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00002866 return optimizeMemCpy(CI, Builder);
David Bolvanskyff0ad3c2019-08-31 18:19:05 +00002867 case LibFunc_mempcpy:
2868 return optimizeMemPCpy(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002869 case LibFunc_memmove:
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00002870 return optimizeMemMove(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002871 case LibFunc_memset:
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00002872 return optimizeMemSet(CI, Builder);
Sanjay Patelb2ab3f22018-04-18 14:21:31 +00002873 case LibFunc_realloc:
2874 return optimizeRealloc(CI, Builder);
Matthias Braun50ec0b52017-05-19 22:37:09 +00002875 case LibFunc_wcslen:
2876 return optimizeWcslen(CI, Builder);
David Bolvansky6b4502962019-10-02 22:49:20 +00002877 case LibFunc_bcopy:
2878 return optimizeBCopy(CI, Builder);
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00002879 default:
2880 break;
2881 }
2882 }
2883 return nullptr;
2884}
2885
Andrew Kaylor53a5fbb2017-08-14 21:15:13 +00002886Value *LibCallSimplifier::optimizeFloatingPointLibCall(CallInst *CI,
2887 LibFunc Func,
2888 IRBuilder<> &Builder) {
2889 // Don't optimize calls that require strict floating point semantics.
2890 if (CI->isStrictFP())
2891 return nullptr;
2892
Sanjay Patele45a83d2018-08-13 19:24:41 +00002893 if (Value *V = optimizeTrigReflections(CI, Func, Builder))
2894 return V;
2895
Andrew Kaylor53a5fbb2017-08-14 21:15:13 +00002896 switch (Func) {
Andrew Kaylor53a5fbb2017-08-14 21:15:13 +00002897 case LibFunc_sinpif:
2898 case LibFunc_sinpi:
2899 case LibFunc_cospif:
2900 case LibFunc_cospi:
2901 return optimizeSinCosPi(CI, Builder);
2902 case LibFunc_powf:
2903 case LibFunc_pow:
2904 case LibFunc_powl:
2905 return optimizePow(CI, Builder);
2906 case LibFunc_exp2l:
2907 case LibFunc_exp2:
2908 case LibFunc_exp2f:
2909 return optimizeExp2(CI, Builder);
2910 case LibFunc_fabsf:
2911 case LibFunc_fabs:
2912 case LibFunc_fabsl:
2913 return replaceUnaryCall(CI, Builder, Intrinsic::fabs);
2914 case LibFunc_sqrtf:
2915 case LibFunc_sqrt:
2916 case LibFunc_sqrtl:
2917 return optimizeSqrt(CI, Builder);
Evandro Menezes110b1132019-09-30 20:52:21 +00002918 case LibFunc_logf:
Andrew Kaylor53a5fbb2017-08-14 21:15:13 +00002919 case LibFunc_log:
Evandro Menezes110b1132019-09-30 20:52:21 +00002920 case LibFunc_logl:
2921 case LibFunc_log10f:
Andrew Kaylor53a5fbb2017-08-14 21:15:13 +00002922 case LibFunc_log10:
Evandro Menezes110b1132019-09-30 20:52:21 +00002923 case LibFunc_log10l:
2924 case LibFunc_log1pf:
Andrew Kaylor53a5fbb2017-08-14 21:15:13 +00002925 case LibFunc_log1p:
Evandro Menezes110b1132019-09-30 20:52:21 +00002926 case LibFunc_log1pl:
2927 case LibFunc_log2f:
Andrew Kaylor53a5fbb2017-08-14 21:15:13 +00002928 case LibFunc_log2:
Evandro Menezes110b1132019-09-30 20:52:21 +00002929 case LibFunc_log2l:
2930 case LibFunc_logbf:
Andrew Kaylor53a5fbb2017-08-14 21:15:13 +00002931 case LibFunc_logb:
Evandro Menezes110b1132019-09-30 20:52:21 +00002932 case LibFunc_logbl:
Andrew Kaylor53a5fbb2017-08-14 21:15:13 +00002933 return optimizeLog(CI, Builder);
2934 case LibFunc_tan:
2935 case LibFunc_tanf:
2936 case LibFunc_tanl:
2937 return optimizeTan(CI, Builder);
2938 case LibFunc_ceil:
2939 return replaceUnaryCall(CI, Builder, Intrinsic::ceil);
2940 case LibFunc_floor:
2941 return replaceUnaryCall(CI, Builder, Intrinsic::floor);
2942 case LibFunc_round:
2943 return replaceUnaryCall(CI, Builder, Intrinsic::round);
2944 case LibFunc_nearbyint:
2945 return replaceUnaryCall(CI, Builder, Intrinsic::nearbyint);
2946 case LibFunc_rint:
2947 return replaceUnaryCall(CI, Builder, Intrinsic::rint);
2948 case LibFunc_trunc:
2949 return replaceUnaryCall(CI, Builder, Intrinsic::trunc);
2950 case LibFunc_acos:
2951 case LibFunc_acosh:
2952 case LibFunc_asin:
2953 case LibFunc_asinh:
2954 case LibFunc_atan:
2955 case LibFunc_atanh:
2956 case LibFunc_cbrt:
2957 case LibFunc_cosh:
2958 case LibFunc_exp:
2959 case LibFunc_exp10:
2960 case LibFunc_expm1:
Sanjay Patele45a83d2018-08-13 19:24:41 +00002961 case LibFunc_cos:
Andrew Kaylor53a5fbb2017-08-14 21:15:13 +00002962 case LibFunc_sin:
2963 case LibFunc_sinh:
2964 case LibFunc_tanh:
2965 if (UnsafeFPShrink && hasFloatVersion(CI->getCalledFunction()->getName()))
2966 return optimizeUnaryDoubleFP(CI, Builder, true);
2967 return nullptr;
2968 case LibFunc_copysign:
2969 if (hasFloatVersion(CI->getCalledFunction()->getName()))
2970 return optimizeBinaryDoubleFP(CI, Builder);
2971 return nullptr;
2972 case LibFunc_fminf:
2973 case LibFunc_fmin:
2974 case LibFunc_fminl:
2975 case LibFunc_fmaxf:
2976 case LibFunc_fmax:
2977 case LibFunc_fmaxl:
2978 return optimizeFMinFMax(CI, Builder);
Hal Finkel2ff24732017-12-16 01:26:25 +00002979 case LibFunc_cabs:
2980 case LibFunc_cabsf:
2981 case LibFunc_cabsl:
2982 return optimizeCAbs(CI, Builder);
Andrew Kaylor53a5fbb2017-08-14 21:15:13 +00002983 default:
2984 return nullptr;
2985 }
2986}
2987
Chris Bienemanad070d02014-09-17 20:55:46 +00002988Value *LibCallSimplifier::optimizeCall(CallInst *CI) {
Andrew Kaylor53a5fbb2017-08-14 21:15:13 +00002989 // TODO: Split out the code below that operates on FP calls so that
2990 // we can all non-FP calls with the StrictFP attribute to be
2991 // optimized.
Chris Bienemanad070d02014-09-17 20:55:46 +00002992 if (CI->isNoBuiltin())
2993 return nullptr;
Meador Inge4d2827c2012-11-11 05:11:20 +00002994
David L. Jonesd21529f2017-01-23 23:16:46 +00002995 LibFunc Func;
Meador Inge20255ef2013-03-12 00:08:29 +00002996 Function *Callee = CI->getCalledFunction();
David Majnemerb70e23c2016-01-06 05:01:34 +00002997
2998 SmallVector<OperandBundleDef, 2> OpBundles;
2999 CI->getOperandBundlesAsDefs(OpBundles);
3000 IRBuilder<> Builder(CI, /*FPMathTag=*/nullptr, OpBundles);
Sam Parker214f7bf2016-09-13 12:10:14 +00003001 bool isCallingConvC = isCallingConvCCompatible(CI);
Meador Inge20255ef2013-03-12 00:08:29 +00003002
Sanjay Pateld1f4f032016-01-19 18:38:52 +00003003 // Command-line parameter overrides instruction attribute.
Andrew Kaylor53a5fbb2017-08-14 21:15:13 +00003004 // This can't be moved to optimizeFloatingPointLibCall() because it may be
Sanjay Patel629c4112017-11-06 16:27:15 +00003005 // used by the intrinsic optimizations.
Sanjay Patela92fa442014-10-22 15:29:23 +00003006 if (EnableUnsafeFPShrink.getNumOccurrences() > 0)
3007 UnsafeFPShrink = EnableUnsafeFPShrink;
Sanjay Patel629c4112017-11-06 16:27:15 +00003008 else if (isa<FPMathOperator>(CI) && CI->isFast())
Davide Italianoa904e522015-10-29 02:58:44 +00003009 UnsafeFPShrink = true;
Sanjay Patela92fa442014-10-22 15:29:23 +00003010
Sanjay Patel848309d2014-10-23 21:52:45 +00003011 // First, check for intrinsics.
Meador Inge20255ef2013-03-12 00:08:29 +00003012 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(CI)) {
Chris Bienemanad070d02014-09-17 20:55:46 +00003013 if (!isCallingConvC)
3014 return nullptr;
Andrew Kaylor53a5fbb2017-08-14 21:15:13 +00003015 // The FP intrinsics have corresponding constrained versions so we don't
3016 // need to check for the StrictFP attribute here.
Meador Inge20255ef2013-03-12 00:08:29 +00003017 switch (II->getIntrinsicID()) {
3018 case Intrinsic::pow:
Chris Bienemanad070d02014-09-17 20:55:46 +00003019 return optimizePow(CI, Builder);
Meador Inge20255ef2013-03-12 00:08:29 +00003020 case Intrinsic::exp2:
Chris Bienemanad070d02014-09-17 20:55:46 +00003021 return optimizeExp2(CI, Builder);
Davide Italianob8b71332015-11-29 20:58:04 +00003022 case Intrinsic::log:
Evandro Menezes110b1132019-09-30 20:52:21 +00003023 case Intrinsic::log2:
3024 case Intrinsic::log10:
Davide Italianob8b71332015-11-29 20:58:04 +00003025 return optimizeLog(CI, Builder);
Sanjay Patelc699a612014-10-16 18:48:17 +00003026 case Intrinsic::sqrt:
3027 return optimizeSqrt(CI, Builder);
Sanjay Patel980b2802016-01-26 16:17:24 +00003028 // TODO: Use foldMallocMemset() with memset intrinsic.
David Bolvansky39130312019-08-13 09:11:49 +00003029 case Intrinsic::memset:
David Bolvanskye80fcf02019-09-17 09:32:52 +00003030 return optimizeMemSet(CI, Builder);
David Bolvansky39130312019-08-13 09:11:49 +00003031 case Intrinsic::memcpy:
David Bolvanskye80fcf02019-09-17 09:32:52 +00003032 return optimizeMemCpy(CI, Builder);
David Bolvansky39130312019-08-13 09:11:49 +00003033 case Intrinsic::memmove:
David Bolvanskye80fcf02019-09-17 09:32:52 +00003034 return optimizeMemMove(CI, Builder);
Meador Inge20255ef2013-03-12 00:08:29 +00003035 default:
Chris Bienemanad070d02014-09-17 20:55:46 +00003036 return nullptr;
Meador Inge20255ef2013-03-12 00:08:29 +00003037 }
3038 }
3039
Ahmed Bougachae03bef72015-01-12 17:22:43 +00003040 // Also try to simplify calls to fortified library functions.
3041 if (Value *SimplifiedFortifiedCI = FortifiedSimplifier.optimizeCall(CI)) {
3042 // Try to further simplify the result.
Ahmed Bougacha71d7b182015-01-14 00:55:05 +00003043 CallInst *SimplifiedCI = dyn_cast<CallInst>(SimplifiedFortifiedCI);
Bruno Cardoso Lopesb491a2d2015-10-01 22:43:53 +00003044 if (SimplifiedCI && SimplifiedCI->getCalledFunction()) {
3045 // Use an IR Builder from SimplifiedCI if available instead of CI
3046 // to guarantee we reach all uses we might replace later on.
3047 IRBuilder<> TmpBuilder(SimplifiedCI);
3048 if (Value *V = optimizeStringMemoryLibCall(SimplifiedCI, TmpBuilder)) {
Ahmed Bougacha1ac93562015-01-27 21:52:16 +00003049 // If we were able to further simplify, remove the now redundant call.
Evandro Menezes7d677ad2019-09-06 22:07:11 +00003050 substituteInParent(SimplifiedCI, V);
Ahmed Bougachae03bef72015-01-12 17:22:43 +00003051 return V;
Ahmed Bougacha1ac93562015-01-27 21:52:16 +00003052 }
Bruno Cardoso Lopesb491a2d2015-10-01 22:43:53 +00003053 }
Ahmed Bougachae03bef72015-01-12 17:22:43 +00003054 return SimplifiedFortifiedCI;
3055 }
3056
Meador Inge20255ef2013-03-12 00:08:29 +00003057 // Then check for known library functions.
Ahmed Bougachad765a822016-04-27 19:04:35 +00003058 if (TLI->getLibFunc(*Callee, Func) && TLI->has(Func)) {
Chris Bienemanad070d02014-09-17 20:55:46 +00003059 // We never change the calling convention.
3060 if (!ignoreCallingConv(Func) && !isCallingConvC)
3061 return nullptr;
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00003062 if (Value *V = optimizeStringMemoryLibCall(CI, Builder))
3063 return V;
Andrew Kaylor53a5fbb2017-08-14 21:15:13 +00003064 if (Value *V = optimizeFloatingPointLibCall(CI, Func, Builder))
3065 return V;
Meador Inge20255ef2013-03-12 00:08:29 +00003066 switch (Func) {
David L. Jonesd21529f2017-01-23 23:16:46 +00003067 case LibFunc_ffs:
3068 case LibFunc_ffsl:
3069 case LibFunc_ffsll:
Chris Bienemanad070d02014-09-17 20:55:46 +00003070 return optimizeFFS(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00003071 case LibFunc_fls:
3072 case LibFunc_flsl:
3073 case LibFunc_flsll:
Davide Italiano85ad36b2016-12-15 23:45:11 +00003074 return optimizeFls(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00003075 case LibFunc_abs:
3076 case LibFunc_labs:
3077 case LibFunc_llabs:
Chris Bienemanad070d02014-09-17 20:55:46 +00003078 return optimizeAbs(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00003079 case LibFunc_isdigit:
Chris Bienemanad070d02014-09-17 20:55:46 +00003080 return optimizeIsDigit(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00003081 case LibFunc_isascii:
Chris Bienemanad070d02014-09-17 20:55:46 +00003082 return optimizeIsAscii(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00003083 case LibFunc_toascii:
Chris Bienemanad070d02014-09-17 20:55:46 +00003084 return optimizeToAscii(CI, Builder);
David Bolvanskycb8ca5f32018-04-25 18:58:53 +00003085 case LibFunc_atoi:
3086 case LibFunc_atol:
3087 case LibFunc_atoll:
3088 return optimizeAtoi(CI, Builder);
3089 case LibFunc_strtol:
3090 case LibFunc_strtoll:
3091 return optimizeStrtol(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00003092 case LibFunc_printf:
Chris Bienemanad070d02014-09-17 20:55:46 +00003093 return optimizePrintF(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00003094 case LibFunc_sprintf:
Chris Bienemanad070d02014-09-17 20:55:46 +00003095 return optimizeSPrintF(CI, Builder);
David Bolvanskycd93c4e2018-05-11 17:50:49 +00003096 case LibFunc_snprintf:
3097 return optimizeSnPrintF(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00003098 case LibFunc_fprintf:
Chris Bienemanad070d02014-09-17 20:55:46 +00003099 return optimizeFPrintF(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00003100 case LibFunc_fwrite:
Chris Bienemanad070d02014-09-17 20:55:46 +00003101 return optimizeFWrite(CI, Builder);
David Bolvanskyca22d422018-05-16 11:39:52 +00003102 case LibFunc_fread:
3103 return optimizeFRead(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00003104 case LibFunc_fputs:
Chris Bienemanad070d02014-09-17 20:55:46 +00003105 return optimizeFPuts(CI, Builder);
David Bolvanskyca22d422018-05-16 11:39:52 +00003106 case LibFunc_fgets:
3107 return optimizeFGets(CI, Builder);
3108 case LibFunc_fputc:
3109 return optimizeFPutc(CI, Builder);
3110 case LibFunc_fgetc:
3111 return optimizeFGetc(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00003112 case LibFunc_puts:
Chris Bienemanad070d02014-09-17 20:55:46 +00003113 return optimizePuts(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00003114 case LibFunc_perror:
Chris Bienemanad070d02014-09-17 20:55:46 +00003115 return optimizeErrorReporting(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00003116 case LibFunc_vfprintf:
3117 case LibFunc_fiprintf:
Chris Bienemanad070d02014-09-17 20:55:46 +00003118 return optimizeErrorReporting(CI, Builder, 0);
Chris Bienemanad070d02014-09-17 20:55:46 +00003119 default:
3120 return nullptr;
3121 }
Meador Inge20255ef2013-03-12 00:08:29 +00003122 }
Craig Topperf40110f2014-04-25 05:29:35 +00003123 return nullptr;
Meador Ingedf796f82012-10-13 16:45:24 +00003124}
3125
Chandler Carruth92803822015-01-21 02:11:59 +00003126LibCallSimplifier::LibCallSimplifier(
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003127 const DataLayout &DL, const TargetLibraryInfo *TLI,
Adam Nemetea06e6e2017-07-26 19:03:18 +00003128 OptimizationRemarkEmitter &ORE,
Hiroshi Yamauchi09e539f2019-04-15 16:49:00 +00003129 BlockFrequencyInfo *BFI, ProfileSummaryInfo *PSI,
Amara Emerson54f60252018-10-11 14:51:11 +00003130 function_ref<void(Instruction *, Value *)> Replacer,
3131 function_ref<void(Instruction *)> Eraser)
Hiroshi Yamauchi09e539f2019-04-15 16:49:00 +00003132 : FortifiedSimplifier(TLI), DL(DL), TLI(TLI), ORE(ORE), BFI(BFI), PSI(PSI),
Amara Emerson54f60252018-10-11 14:51:11 +00003133 UnsafeFPShrink(false), Replacer(Replacer), Eraser(Eraser) {}
Chandler Carruth92803822015-01-21 02:11:59 +00003134
3135void LibCallSimplifier::replaceAllUsesWith(Instruction *I, Value *With) {
3136 // Indirect through the replacer used in this instance.
3137 Replacer(I, With);
Meador Ingedf796f82012-10-13 16:45:24 +00003138}
3139
Amara Emerson54f60252018-10-11 14:51:11 +00003140void LibCallSimplifier::eraseFromParent(Instruction *I) {
3141 Eraser(I);
3142}
3143
Meador Ingedfb08a22013-06-20 19:48:07 +00003144// TODO:
3145// Additional cases that we need to add to this file:
3146//
3147// cbrt:
3148// * cbrt(expN(X)) -> expN(x/3)
3149// * cbrt(sqrt(x)) -> pow(x,1/6)
David Majnemer3354fe42015-08-26 18:30:16 +00003150// * cbrt(cbrt(x)) -> pow(x,1/9)
Meador Ingedfb08a22013-06-20 19:48:07 +00003151//
3152// exp, expf, expl:
3153// * exp(log(x)) -> x
3154//
3155// log, logf, logl:
3156// * log(exp(x)) -> x
Meador Ingedfb08a22013-06-20 19:48:07 +00003157// * log(exp(y)) -> y*log(e)
Meador Ingedfb08a22013-06-20 19:48:07 +00003158// * log(exp10(y)) -> y*log(10)
3159// * log(sqrt(x)) -> 0.5*log(x)
Meador Ingedfb08a22013-06-20 19:48:07 +00003160//
Meador Ingedfb08a22013-06-20 19:48:07 +00003161// pow, powf, powl:
Meador Ingedfb08a22013-06-20 19:48:07 +00003162// * pow(sqrt(x),y) -> pow(x,y*0.5)
3163// * pow(pow(x,y),z)-> pow(x,y*z)
3164//
Meador Ingedfb08a22013-06-20 19:48:07 +00003165// signbit:
3166// * signbit(cnst) -> cnst'
3167// * signbit(nncst) -> 0 (if pstv is a non-negative constant)
3168//
3169// sqrt, sqrtf, sqrtl:
3170// * sqrt(expN(x)) -> expN(x*0.5)
3171// * sqrt(Nroot(x)) -> pow(x,1/(2*N))
3172// * sqrt(pow(x,y)) -> pow(|x|,y*0.5)
3173//
Ahmed Bougachae03bef72015-01-12 17:22:43 +00003174
3175//===----------------------------------------------------------------------===//
3176// Fortified Library Call Optimizations
3177//===----------------------------------------------------------------------===//
3178
Erik Pilkingtonabb2a932019-05-31 22:41:36 +00003179bool
3180FortifiedLibCallSimplifier::isFortifiedCallFoldable(CallInst *CI,
3181 unsigned ObjSizeOp,
3182 Optional<unsigned> SizeOp,
3183 Optional<unsigned> StrOp,
3184 Optional<unsigned> FlagOp) {
3185 // If this function takes a flag argument, the implementation may use it to
3186 // perform extra checks. Don't fold into the non-checking variant.
3187 if (FlagOp) {
3188 ConstantInt *Flag = dyn_cast<ConstantInt>(CI->getArgOperand(*FlagOp));
3189 if (!Flag || !Flag->isZero())
3190 return false;
3191 }
3192
3193 if (SizeOp && CI->getArgOperand(ObjSizeOp) == CI->getArgOperand(*SizeOp))
Ahmed Bougachae03bef72015-01-12 17:22:43 +00003194 return true;
Erik Pilkingtonabb2a932019-05-31 22:41:36 +00003195
Ahmed Bougachae03bef72015-01-12 17:22:43 +00003196 if (ConstantInt *ObjSizeCI =
3197 dyn_cast<ConstantInt>(CI->getArgOperand(ObjSizeOp))) {
Craig Topper79ab6432017-07-06 18:39:47 +00003198 if (ObjSizeCI->isMinusOne())
Ahmed Bougachae03bef72015-01-12 17:22:43 +00003199 return true;
3200 // If the object size wasn't -1 (unknown), bail out if we were asked to.
3201 if (OnlyLowerUnknownSize)
3202 return false;
Erik Pilkingtonabb2a932019-05-31 22:41:36 +00003203 if (StrOp) {
3204 uint64_t Len = GetStringLength(CI->getArgOperand(*StrOp));
Ahmed Bougachae03bef72015-01-12 17:22:43 +00003205 // If the length is 0 we don't know how long it is and so we can't
3206 // remove the check.
David Bolvanskye80fcf02019-09-17 09:32:52 +00003207 if (Len)
3208 annotateDereferenceableBytes(CI, *StrOp, Len);
3209 else
Ahmed Bougachae03bef72015-01-12 17:22:43 +00003210 return false;
3211 return ObjSizeCI->getZExtValue() >= Len;
3212 }
Erik Pilkingtonabb2a932019-05-31 22:41:36 +00003213
3214 if (SizeOp) {
3215 if (ConstantInt *SizeCI =
3216 dyn_cast<ConstantInt>(CI->getArgOperand(*SizeOp)))
3217 return ObjSizeCI->getZExtValue() >= SizeCI->getZExtValue();
3218 }
Ahmed Bougachae03bef72015-01-12 17:22:43 +00003219 }
3220 return false;
3221}
3222
Sanjay Pateld707db92015-12-31 16:10:49 +00003223Value *FortifiedLibCallSimplifier::optimizeMemCpyChk(CallInst *CI,
3224 IRBuilder<> &B) {
Erik Pilkingtonabb2a932019-05-31 22:41:36 +00003225 if (isFortifiedCallFoldable(CI, 3, 2)) {
David Bolvanskye80fcf02019-09-17 09:32:52 +00003226 CallInst *NewCI = B.CreateMemCpy(
3227 CI->getArgOperand(0), 1, CI->getArgOperand(1), 1, CI->getArgOperand(2));
3228 NewCI->setAttributes(CI->getAttributes());
Ahmed Bougachae03bef72015-01-12 17:22:43 +00003229 return CI->getArgOperand(0);
3230 }
3231 return nullptr;
3232}
3233
Sanjay Pateld707db92015-12-31 16:10:49 +00003234Value *FortifiedLibCallSimplifier::optimizeMemMoveChk(CallInst *CI,
3235 IRBuilder<> &B) {
Erik Pilkingtonabb2a932019-05-31 22:41:36 +00003236 if (isFortifiedCallFoldable(CI, 3, 2)) {
David Bolvanskye80fcf02019-09-17 09:32:52 +00003237 CallInst *NewCI = B.CreateMemMove(
3238 CI->getArgOperand(0), 1, CI->getArgOperand(1), 1, CI->getArgOperand(2));
3239 NewCI->setAttributes(CI->getAttributes());
Ahmed Bougachae03bef72015-01-12 17:22:43 +00003240 return CI->getArgOperand(0);
3241 }
3242 return nullptr;
3243}
3244
Sanjay Pateld707db92015-12-31 16:10:49 +00003245Value *FortifiedLibCallSimplifier::optimizeMemSetChk(CallInst *CI,
3246 IRBuilder<> &B) {
Sanjay Patel980b2802016-01-26 16:17:24 +00003247 // TODO: Try foldMallocMemset() here.
3248
Erik Pilkingtonabb2a932019-05-31 22:41:36 +00003249 if (isFortifiedCallFoldable(CI, 3, 2)) {
Ahmed Bougachae03bef72015-01-12 17:22:43 +00003250 Value *Val = B.CreateIntCast(CI->getArgOperand(1), B.getInt8Ty(), false);
David Bolvanskye80fcf02019-09-17 09:32:52 +00003251 CallInst *NewCI =
3252 B.CreateMemSet(CI->getArgOperand(0), Val, CI->getArgOperand(2), 1);
3253 NewCI->setAttributes(CI->getAttributes());
Ahmed Bougachae03bef72015-01-12 17:22:43 +00003254 return CI->getArgOperand(0);
3255 }
3256 return nullptr;
3257}
3258
Ahmed Bougacha1ac93562015-01-27 21:52:16 +00003259Value *FortifiedLibCallSimplifier::optimizeStrpCpyChk(CallInst *CI,
3260 IRBuilder<> &B,
David L. Jonesd21529f2017-01-23 23:16:46 +00003261 LibFunc Func) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003262 const DataLayout &DL = CI->getModule()->getDataLayout();
Ahmed Bougachae03bef72015-01-12 17:22:43 +00003263 Value *Dst = CI->getArgOperand(0), *Src = CI->getArgOperand(1),
3264 *ObjSize = CI->getArgOperand(2);
3265
3266 // __stpcpy_chk(x,x,...) -> x+strlen(x)
David L. Jonesd21529f2017-01-23 23:16:46 +00003267 if (Func == LibFunc_stpcpy_chk && !OnlyLowerUnknownSize && Dst == Src) {
Sanjay Pateld3112a52016-01-19 19:46:10 +00003268 Value *StrLen = emitStrLen(Src, B, DL, TLI);
David Blaikieaa41cd52015-04-03 21:33:42 +00003269 return StrLen ? B.CreateInBoundsGEP(B.getInt8Ty(), Dst, StrLen) : nullptr;
Ahmed Bougachae03bef72015-01-12 17:22:43 +00003270 }
3271
3272 // If a) we don't have any length information, or b) we know this will
3273 // fit then just lower to a plain st[rp]cpy. Otherwise we'll keep our
3274 // st[rp]cpy_chk call which may fail at runtime if the size is too long.
3275 // TODO: It might be nice to get a maximum length out of the possible
3276 // string lengths for varying.
Erik Pilkingtonabb2a932019-05-31 22:41:36 +00003277 if (isFortifiedCallFoldable(CI, 2, None, 1)) {
Erik Pilkington52349212019-05-31 22:41:31 +00003278 if (Func == LibFunc_strcpy_chk)
3279 return emitStrCpy(Dst, Src, B, TLI);
3280 else
3281 return emitStpCpy(Dst, Src, B, TLI);
3282 }
Ahmed Bougachae03bef72015-01-12 17:22:43 +00003283
David Blaikie65fab6d2015-04-03 21:32:06 +00003284 if (OnlyLowerUnknownSize)
3285 return nullptr;
3286
3287 // Maybe we can stil fold __st[rp]cpy_chk to __memcpy_chk.
David Bolvansky1f343fa2018-05-22 20:27:36 +00003288 uint64_t Len = GetStringLength(Src);
David Bolvanskye80fcf02019-09-17 09:32:52 +00003289 if (Len)
3290 annotateDereferenceableBytes(CI, 1, Len);
3291 else
David Blaikie65fab6d2015-04-03 21:32:06 +00003292 return nullptr;
3293
3294 Type *SizeTTy = DL.getIntPtrType(CI->getContext());
3295 Value *LenV = ConstantInt::get(SizeTTy, Len);
Sanjay Pateld3112a52016-01-19 19:46:10 +00003296 Value *Ret = emitMemCpyChk(Dst, Src, LenV, ObjSize, B, DL, TLI);
David Blaikie65fab6d2015-04-03 21:32:06 +00003297 // If the function was an __stpcpy_chk, and we were able to fold it into
3298 // a __memcpy_chk, we still need to return the correct end pointer.
David L. Jonesd21529f2017-01-23 23:16:46 +00003299 if (Ret && Func == LibFunc_stpcpy_chk)
David Blaikie65fab6d2015-04-03 21:32:06 +00003300 return B.CreateGEP(B.getInt8Ty(), Dst, ConstantInt::get(SizeTTy, Len - 1));
3301 return Ret;
Ahmed Bougachae03bef72015-01-12 17:22:43 +00003302}
3303
Ahmed Bougacha1ac93562015-01-27 21:52:16 +00003304Value *FortifiedLibCallSimplifier::optimizeStrpNCpyChk(CallInst *CI,
3305 IRBuilder<> &B,
David L. Jonesd21529f2017-01-23 23:16:46 +00003306 LibFunc Func) {
Erik Pilkingtonabb2a932019-05-31 22:41:36 +00003307 if (isFortifiedCallFoldable(CI, 3, 2)) {
Erik Pilkington52349212019-05-31 22:41:31 +00003308 if (Func == LibFunc_strncpy_chk)
3309 return emitStrNCpy(CI->getArgOperand(0), CI->getArgOperand(1),
Erik Pilkingtonabb2a932019-05-31 22:41:36 +00003310 CI->getArgOperand(2), B, TLI);
Erik Pilkington52349212019-05-31 22:41:31 +00003311 else
3312 return emitStpNCpy(CI->getArgOperand(0), CI->getArgOperand(1),
3313 CI->getArgOperand(2), B, TLI);
Ahmed Bougachae03bef72015-01-12 17:22:43 +00003314 }
Erik Pilkington52349212019-05-31 22:41:31 +00003315
Ahmed Bougachae03bef72015-01-12 17:22:43 +00003316 return nullptr;
3317}
3318
Erik Pilkingtonabb2a932019-05-31 22:41:36 +00003319Value *FortifiedLibCallSimplifier::optimizeMemCCpyChk(CallInst *CI,
3320 IRBuilder<> &B) {
3321 if (isFortifiedCallFoldable(CI, 4, 3))
3322 return emitMemCCpy(CI->getArgOperand(0), CI->getArgOperand(1),
3323 CI->getArgOperand(2), CI->getArgOperand(3), B, TLI);
3324
3325 return nullptr;
3326}
3327
3328Value *FortifiedLibCallSimplifier::optimizeSNPrintfChk(CallInst *CI,
3329 IRBuilder<> &B) {
3330 if (isFortifiedCallFoldable(CI, 3, 1, None, 2)) {
3331 SmallVector<Value *, 8> VariadicArgs(CI->arg_begin() + 5, CI->arg_end());
3332 return emitSNPrintf(CI->getArgOperand(0), CI->getArgOperand(1),
3333 CI->getArgOperand(4), VariadicArgs, B, TLI);
3334 }
3335
3336 return nullptr;
3337}
3338
3339Value *FortifiedLibCallSimplifier::optimizeSPrintfChk(CallInst *CI,
3340 IRBuilder<> &B) {
3341 if (isFortifiedCallFoldable(CI, 2, None, None, 1)) {
3342 SmallVector<Value *, 8> VariadicArgs(CI->arg_begin() + 4, CI->arg_end());
3343 return emitSPrintf(CI->getArgOperand(0), CI->getArgOperand(3), VariadicArgs,
3344 B, TLI);
3345 }
3346
3347 return nullptr;
3348}
3349
3350Value *FortifiedLibCallSimplifier::optimizeStrCatChk(CallInst *CI,
3351 IRBuilder<> &B) {
3352 if (isFortifiedCallFoldable(CI, 2))
3353 return emitStrCat(CI->getArgOperand(0), CI->getArgOperand(1), B, TLI);
3354
3355 return nullptr;
3356}
3357
3358Value *FortifiedLibCallSimplifier::optimizeStrLCat(CallInst *CI,
3359 IRBuilder<> &B) {
3360 if (isFortifiedCallFoldable(CI, 3))
3361 return emitStrLCat(CI->getArgOperand(0), CI->getArgOperand(1),
3362 CI->getArgOperand(2), B, TLI);
3363
3364 return nullptr;
3365}
3366
3367Value *FortifiedLibCallSimplifier::optimizeStrNCatChk(CallInst *CI,
3368 IRBuilder<> &B) {
3369 if (isFortifiedCallFoldable(CI, 3))
3370 return emitStrNCat(CI->getArgOperand(0), CI->getArgOperand(1),
3371 CI->getArgOperand(2), B, TLI);
3372
3373 return nullptr;
3374}
3375
3376Value *FortifiedLibCallSimplifier::optimizeStrLCpyChk(CallInst *CI,
3377 IRBuilder<> &B) {
3378 if (isFortifiedCallFoldable(CI, 3))
3379 return emitStrLCpy(CI->getArgOperand(0), CI->getArgOperand(1),
3380 CI->getArgOperand(2), B, TLI);
3381
3382 return nullptr;
3383}
3384
3385Value *FortifiedLibCallSimplifier::optimizeVSNPrintfChk(CallInst *CI,
3386 IRBuilder<> &B) {
3387 if (isFortifiedCallFoldable(CI, 3, 1, None, 2))
3388 return emitVSNPrintf(CI->getArgOperand(0), CI->getArgOperand(1),
3389 CI->getArgOperand(4), CI->getArgOperand(5), B, TLI);
3390
3391 return nullptr;
3392}
3393
3394Value *FortifiedLibCallSimplifier::optimizeVSPrintfChk(CallInst *CI,
3395 IRBuilder<> &B) {
3396 if (isFortifiedCallFoldable(CI, 2, None, None, 1))
3397 return emitVSPrintf(CI->getArgOperand(0), CI->getArgOperand(3),
3398 CI->getArgOperand(4), B, TLI);
3399
3400 return nullptr;
3401}
3402
Ahmed Bougachae03bef72015-01-12 17:22:43 +00003403Value *FortifiedLibCallSimplifier::optimizeCall(CallInst *CI) {
Ahmed Bougacha408d0102015-04-01 00:45:09 +00003404 // FIXME: We shouldn't be changing "nobuiltin" or TLI unavailable calls here.
3405 // Some clang users checked for _chk libcall availability using:
3406 // __has_builtin(__builtin___memcpy_chk)
3407 // When compiling with -fno-builtin, this is always true.
3408 // When passing -ffreestanding/-mkernel, which both imply -fno-builtin, we
3409 // end up with fortified libcalls, which isn't acceptable in a freestanding
3410 // environment which only provides their non-fortified counterparts.
3411 //
3412 // Until we change clang and/or teach external users to check for availability
3413 // differently, disregard the "nobuiltin" attribute and TLI::has.
3414 //
3415 // PR23093.
Ahmed Bougachae03bef72015-01-12 17:22:43 +00003416
David L. Jonesd21529f2017-01-23 23:16:46 +00003417 LibFunc Func;
Ahmed Bougachae03bef72015-01-12 17:22:43 +00003418 Function *Callee = CI->getCalledFunction();
David Majnemerb70e23c2016-01-06 05:01:34 +00003419
3420 SmallVector<OperandBundleDef, 2> OpBundles;
3421 CI->getOperandBundlesAsDefs(OpBundles);
3422 IRBuilder<> Builder(CI, /*FPMathTag=*/nullptr, OpBundles);
Sam Parker214f7bf2016-09-13 12:10:14 +00003423 bool isCallingConvC = isCallingConvCCompatible(CI);
Ahmed Bougachae03bef72015-01-12 17:22:43 +00003424
Ahmed Bougachad765a822016-04-27 19:04:35 +00003425 // First, check that this is a known library functions and that the prototype
3426 // is correct.
3427 if (!TLI->getLibFunc(*Callee, Func))
Ahmed Bougachae03bef72015-01-12 17:22:43 +00003428 return nullptr;
3429
3430 // We never change the calling convention.
3431 if (!ignoreCallingConv(Func) && !isCallingConvC)
3432 return nullptr;
3433
3434 switch (Func) {
David L. Jonesd21529f2017-01-23 23:16:46 +00003435 case LibFunc_memcpy_chk:
Ahmed Bougachae03bef72015-01-12 17:22:43 +00003436 return optimizeMemCpyChk(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00003437 case LibFunc_memmove_chk:
Ahmed Bougachae03bef72015-01-12 17:22:43 +00003438 return optimizeMemMoveChk(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00003439 case LibFunc_memset_chk:
Ahmed Bougachae03bef72015-01-12 17:22:43 +00003440 return optimizeMemSetChk(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00003441 case LibFunc_stpcpy_chk:
3442 case LibFunc_strcpy_chk:
Ahmed Bougacha1ac93562015-01-27 21:52:16 +00003443 return optimizeStrpCpyChk(CI, Builder, Func);
David L. Jonesd21529f2017-01-23 23:16:46 +00003444 case LibFunc_stpncpy_chk:
3445 case LibFunc_strncpy_chk:
Ahmed Bougacha1ac93562015-01-27 21:52:16 +00003446 return optimizeStrpNCpyChk(CI, Builder, Func);
Erik Pilkingtonabb2a932019-05-31 22:41:36 +00003447 case LibFunc_memccpy_chk:
3448 return optimizeMemCCpyChk(CI, Builder);
3449 case LibFunc_snprintf_chk:
3450 return optimizeSNPrintfChk(CI, Builder);
3451 case LibFunc_sprintf_chk:
3452 return optimizeSPrintfChk(CI, Builder);
3453 case LibFunc_strcat_chk:
3454 return optimizeStrCatChk(CI, Builder);
3455 case LibFunc_strlcat_chk:
3456 return optimizeStrLCat(CI, Builder);
3457 case LibFunc_strncat_chk:
3458 return optimizeStrNCatChk(CI, Builder);
3459 case LibFunc_strlcpy_chk:
3460 return optimizeStrLCpyChk(CI, Builder);
3461 case LibFunc_vsnprintf_chk:
3462 return optimizeVSNPrintfChk(CI, Builder);
3463 case LibFunc_vsprintf_chk:
3464 return optimizeVSPrintfChk(CI, Builder);
Ahmed Bougachae03bef72015-01-12 17:22:43 +00003465 default:
3466 break;
3467 }
3468 return nullptr;
3469}
3470
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003471FortifiedLibCallSimplifier::FortifiedLibCallSimplifier(
3472 const TargetLibraryInfo *TLI, bool OnlyLowerUnknownSize)
Evandro Menezesb2169262019-07-12 00:33:49 +00003473 : TLI(TLI), OnlyLowerUnknownSize(OnlyLowerUnknownSize) {}