blob: 32b845cb16bd92709a279bfe9733aeda75f7bf05 [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"
Meador Ingedf796f82012-10-13 16:45:24 +000038#include "llvm/Transforms/Utils/BuildLibCalls.h"
Hiroshi Yamauchi09e539f2019-04-15 16:49:00 +000039#include "llvm/Transforms/Utils/SizeOpts.h"
Meador Ingedf796f82012-10-13 16:45:24 +000040
41using namespace llvm;
Sanjay Patelc699a612014-10-16 18:48:17 +000042using namespace PatternMatch;
Meador Ingedf796f82012-10-13 16:45:24 +000043
Hal Finkel66cd3f12013-11-17 02:06:35 +000044static cl::opt<bool>
Sanjay Patela92fa442014-10-22 15:29:23 +000045 EnableUnsafeFPShrink("enable-double-float-shrink", cl::Hidden,
46 cl::init(false),
47 cl::desc("Enable unsafe double to float "
48 "shrinking for math lib calls"));
49
50
Meador Ingedf796f82012-10-13 16:45:24 +000051//===----------------------------------------------------------------------===//
Meador Inged589ac62012-10-31 03:33:06 +000052// Helper Functions
53//===----------------------------------------------------------------------===//
54
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
Meador Inged589ac62012-10-31 03:33:06 +0000189//===----------------------------------------------------------------------===//
Meador Inge7fb2f732012-10-13 16:45:32 +0000190// String and Memory Library Call Optimizations
191//===----------------------------------------------------------------------===//
192
Chris Bienemanad070d02014-09-17 20:55:46 +0000193Value *LibCallSimplifier::optimizeStrCat(CallInst *CI, IRBuilder<> &B) {
Chris Bienemanad070d02014-09-17 20:55:46 +0000194 // Extract some information from the instruction
195 Value *Dst = CI->getArgOperand(0);
196 Value *Src = CI->getArgOperand(1);
197
198 // See if we can get the length of the input string.
David Bolvansky1f343fa2018-05-22 20:27:36 +0000199 uint64_t Len = GetStringLength(Src);
Chris Bienemanad070d02014-09-17 20:55:46 +0000200 if (Len == 0)
201 return nullptr;
202 --Len; // Unbias length.
203
204 // Handle the simple, do-nothing case: strcat(x, "") -> x
205 if (Len == 0)
206 return Dst;
207
Chris Bienemanad070d02014-09-17 20:55:46 +0000208 return emitStrLenMemCpy(Src, Dst, Len, B);
209}
210
211Value *LibCallSimplifier::emitStrLenMemCpy(Value *Src, Value *Dst, uint64_t Len,
212 IRBuilder<> &B) {
213 // We need to find the end of the destination string. That's where the
214 // memory is to be moved to. We just generate a call to strlen.
Sanjay Pateld3112a52016-01-19 19:46:10 +0000215 Value *DstLen = emitStrLen(Dst, B, DL, TLI);
Chris Bienemanad070d02014-09-17 20:55:46 +0000216 if (!DstLen)
217 return nullptr;
218
219 // Now that we have the destination's length, we must index into the
220 // destination's pointer to get the actual memcpy destination (end of
221 // the string .. we're concatenating).
David Blaikie3909da72015-03-30 20:42:56 +0000222 Value *CpyDst = B.CreateGEP(B.getInt8Ty(), Dst, DstLen, "endptr");
Chris Bienemanad070d02014-09-17 20:55:46 +0000223
224 // We have enough information to now generate the memcpy call to do the
225 // concatenation for us. Make a memcpy to copy the nul byte with align = 1.
Daniel Neilson8acd8b02018-02-05 21:23:22 +0000226 B.CreateMemCpy(CpyDst, 1, Src, 1,
227 ConstantInt::get(DL.getIntPtrType(Src->getContext()), Len + 1));
Chris Bienemanad070d02014-09-17 20:55:46 +0000228 return Dst;
229}
230
231Value *LibCallSimplifier::optimizeStrNCat(CallInst *CI, IRBuilder<> &B) {
Sanjay Pateld707db92015-12-31 16:10:49 +0000232 // Extract some information from the instruction.
Chris Bienemanad070d02014-09-17 20:55:46 +0000233 Value *Dst = CI->getArgOperand(0);
234 Value *Src = CI->getArgOperand(1);
235 uint64_t Len;
236
Sanjay Pateld707db92015-12-31 16:10:49 +0000237 // We don't do anything if length is not constant.
Chris Bienemanad070d02014-09-17 20:55:46 +0000238 if (ConstantInt *LengthArg = dyn_cast<ConstantInt>(CI->getArgOperand(2)))
239 Len = LengthArg->getZExtValue();
240 else
241 return nullptr;
242
243 // See if we can get the length of the input string.
David Bolvansky1f343fa2018-05-22 20:27:36 +0000244 uint64_t SrcLen = GetStringLength(Src);
Chris Bienemanad070d02014-09-17 20:55:46 +0000245 if (SrcLen == 0)
246 return nullptr;
247 --SrcLen; // Unbias length.
248
249 // Handle the simple, do-nothing cases:
250 // strncat(x, "", c) -> x
251 // strncat(x, c, 0) -> x
252 if (SrcLen == 0 || Len == 0)
253 return Dst;
254
Sanjay Pateld707db92015-12-31 16:10:49 +0000255 // We don't optimize this case.
Chris Bienemanad070d02014-09-17 20:55:46 +0000256 if (Len < SrcLen)
257 return nullptr;
258
259 // strncat(x, s, c) -> strcat(x, s)
Sanjay Pateld707db92015-12-31 16:10:49 +0000260 // s is constant so the strcat can be optimized further.
Chris Bienemanad070d02014-09-17 20:55:46 +0000261 return emitStrLenMemCpy(Src, Dst, SrcLen, B);
262}
263
264Value *LibCallSimplifier::optimizeStrChr(CallInst *CI, IRBuilder<> &B) {
265 Function *Callee = CI->getCalledFunction();
Chris Bienemanad070d02014-09-17 20:55:46 +0000266 FunctionType *FT = Callee->getFunctionType();
Chris Bienemanad070d02014-09-17 20:55:46 +0000267 Value *SrcStr = CI->getArgOperand(0);
268
269 // If the second operand is non-constant, see if we can compute the length
270 // of the input string and turn this into memchr.
271 ConstantInt *CharC = dyn_cast<ConstantInt>(CI->getArgOperand(1));
272 if (!CharC) {
David Bolvansky1f343fa2018-05-22 20:27:36 +0000273 uint64_t Len = GetStringLength(SrcStr);
Chris Bienemanad070d02014-09-17 20:55:46 +0000274 if (Len == 0 || !FT->getParamType(1)->isIntegerTy(32)) // memchr needs i32.
275 return nullptr;
Meador Inge7fb2f732012-10-13 16:45:32 +0000276
Sanjay Pateld3112a52016-01-19 19:46:10 +0000277 return emitMemChr(SrcStr, CI->getArgOperand(1), // include nul.
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000278 ConstantInt::get(DL.getIntPtrType(CI->getContext()), Len),
279 B, DL, TLI);
Meador Inge7fb2f732012-10-13 16:45:32 +0000280 }
281
Chris Bienemanad070d02014-09-17 20:55:46 +0000282 // Otherwise, the character is a constant, see if the first argument is
283 // a string literal. If so, we can constant fold.
284 StringRef Str;
285 if (!getConstantStringInfo(SrcStr, Str)) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000286 if (CharC->isZero()) // strchr(p, 0) -> p + strlen(p)
Sanjay Pateld3112a52016-01-19 19:46:10 +0000287 return B.CreateGEP(B.getInt8Ty(), SrcStr, emitStrLen(SrcStr, B, DL, TLI),
Sanjay Pateld707db92015-12-31 16:10:49 +0000288 "strchr");
Chris Bienemanad070d02014-09-17 20:55:46 +0000289 return nullptr;
290 }
291
292 // Compute the offset, make sure to handle the case when we're searching for
293 // zero (a weird way to spell strlen).
294 size_t I = (0xFF & CharC->getSExtValue()) == 0
295 ? Str.size()
296 : Str.find(CharC->getSExtValue());
297 if (I == StringRef::npos) // Didn't find the char. strchr returns null.
298 return Constant::getNullValue(CI->getType());
299
300 // strchr(s+n,c) -> gep(s+n+i,c)
David Blaikie3909da72015-03-30 20:42:56 +0000301 return B.CreateGEP(B.getInt8Ty(), SrcStr, B.getInt64(I), "strchr");
Chris Bienemanad070d02014-09-17 20:55:46 +0000302}
303
304Value *LibCallSimplifier::optimizeStrRChr(CallInst *CI, IRBuilder<> &B) {
Chris Bienemanad070d02014-09-17 20:55:46 +0000305 Value *SrcStr = CI->getArgOperand(0);
306 ConstantInt *CharC = dyn_cast<ConstantInt>(CI->getArgOperand(1));
307
308 // Cannot fold anything if we're not looking for a constant.
309 if (!CharC)
310 return nullptr;
311
312 StringRef Str;
313 if (!getConstantStringInfo(SrcStr, Str)) {
314 // strrchr(s, 0) -> strchr(s, 0)
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000315 if (CharC->isZero())
Sanjay Pateld3112a52016-01-19 19:46:10 +0000316 return emitStrChr(SrcStr, '\0', B, TLI);
Chris Bienemanad070d02014-09-17 20:55:46 +0000317 return nullptr;
318 }
319
320 // Compute the offset.
321 size_t I = (0xFF & CharC->getSExtValue()) == 0
322 ? Str.size()
323 : Str.rfind(CharC->getSExtValue());
324 if (I == StringRef::npos) // Didn't find the char. Return null.
325 return Constant::getNullValue(CI->getType());
326
327 // strrchr(s+n,c) -> gep(s+n+i,c)
David Blaikie3909da72015-03-30 20:42:56 +0000328 return B.CreateGEP(B.getInt8Ty(), SrcStr, B.getInt64(I), "strrchr");
Chris Bienemanad070d02014-09-17 20:55:46 +0000329}
330
331Value *LibCallSimplifier::optimizeStrCmp(CallInst *CI, IRBuilder<> &B) {
Chris Bienemanad070d02014-09-17 20:55:46 +0000332 Value *Str1P = CI->getArgOperand(0), *Str2P = CI->getArgOperand(1);
333 if (Str1P == Str2P) // strcmp(x,x) -> 0
334 return ConstantInt::get(CI->getType(), 0);
335
336 StringRef Str1, Str2;
337 bool HasStr1 = getConstantStringInfo(Str1P, Str1);
338 bool HasStr2 = getConstantStringInfo(Str2P, Str2);
339
340 // strcmp(x, y) -> cnst (if both x and y are constant strings)
341 if (HasStr1 && HasStr2)
342 return ConstantInt::get(CI->getType(), Str1.compare(Str2));
343
344 if (HasStr1 && Str1.empty()) // strcmp("", x) -> -*x
James Y Knight14359ef2019-02-01 20:44:24 +0000345 return B.CreateNeg(B.CreateZExt(
346 B.CreateLoad(B.getInt8Ty(), Str2P, "strcmpload"), CI->getType()));
Chris Bienemanad070d02014-09-17 20:55:46 +0000347
348 if (HasStr2 && Str2.empty()) // strcmp(x,"") -> *x
James Y Knight14359ef2019-02-01 20:44:24 +0000349 return B.CreateZExt(B.CreateLoad(B.getInt8Ty(), Str1P, "strcmpload"),
350 CI->getType());
Chris Bienemanad070d02014-09-17 20:55:46 +0000351
352 // strcmp(P, "x") -> memcmp(P, "x", 2)
David Bolvansky1f343fa2018-05-22 20:27:36 +0000353 uint64_t Len1 = GetStringLength(Str1P);
354 uint64_t Len2 = GetStringLength(Str2P);
Chris Bienemanad070d02014-09-17 20:55:46 +0000355 if (Len1 && Len2) {
Sanjay Pateld3112a52016-01-19 19:46:10 +0000356 return emitMemCmp(Str1P, Str2P,
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000357 ConstantInt::get(DL.getIntPtrType(CI->getContext()),
Chris Bienemanad070d02014-09-17 20:55:46 +0000358 std::min(Len1, Len2)),
359 B, DL, TLI);
360 }
Meador Inge7fb2f732012-10-13 16:45:32 +0000361
David Bolvansky909889b2018-08-10 04:32:54 +0000362 // strcmp to memcmp
363 if (!HasStr1 && HasStr2) {
364 if (canTransformToMemCmp(CI, Str1P, Len2, DL))
365 return emitMemCmp(
366 Str1P, Str2P,
367 ConstantInt::get(DL.getIntPtrType(CI->getContext()), Len2), B, DL,
368 TLI);
369 } else if (HasStr1 && !HasStr2) {
370 if (canTransformToMemCmp(CI, Str2P, Len1, DL))
371 return emitMemCmp(
372 Str1P, Str2P,
373 ConstantInt::get(DL.getIntPtrType(CI->getContext()), Len1), B, DL,
374 TLI);
375 }
376
Chris Bienemanad070d02014-09-17 20:55:46 +0000377 return nullptr;
378}
379
380Value *LibCallSimplifier::optimizeStrNCmp(CallInst *CI, IRBuilder<> &B) {
Chris Bienemanad070d02014-09-17 20:55:46 +0000381 Value *Str1P = CI->getArgOperand(0), *Str2P = CI->getArgOperand(1);
382 if (Str1P == Str2P) // strncmp(x,x,n) -> 0
383 return ConstantInt::get(CI->getType(), 0);
384
385 // Get the length argument if it is constant.
386 uint64_t Length;
387 if (ConstantInt *LengthArg = dyn_cast<ConstantInt>(CI->getArgOperand(2)))
388 Length = LengthArg->getZExtValue();
389 else
390 return nullptr;
391
392 if (Length == 0) // strncmp(x,y,0) -> 0
393 return ConstantInt::get(CI->getType(), 0);
394
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000395 if (Length == 1) // strncmp(x,y,1) -> memcmp(x,y,1)
Sanjay Pateld3112a52016-01-19 19:46:10 +0000396 return emitMemCmp(Str1P, Str2P, CI->getArgOperand(2), B, DL, TLI);
Chris Bienemanad070d02014-09-17 20:55:46 +0000397
398 StringRef Str1, Str2;
399 bool HasStr1 = getConstantStringInfo(Str1P, Str1);
400 bool HasStr2 = getConstantStringInfo(Str2P, Str2);
401
402 // strncmp(x, y) -> cnst (if both x and y are constant strings)
403 if (HasStr1 && HasStr2) {
404 StringRef SubStr1 = Str1.substr(0, Length);
405 StringRef SubStr2 = Str2.substr(0, Length);
406 return ConstantInt::get(CI->getType(), SubStr1.compare(SubStr2));
407 }
408
409 if (HasStr1 && Str1.empty()) // strncmp("", x, n) -> -*x
James Y Knight14359ef2019-02-01 20:44:24 +0000410 return B.CreateNeg(B.CreateZExt(
411 B.CreateLoad(B.getInt8Ty(), Str2P, "strcmpload"), CI->getType()));
Chris Bienemanad070d02014-09-17 20:55:46 +0000412
413 if (HasStr2 && Str2.empty()) // strncmp(x, "", n) -> *x
James Y Knight14359ef2019-02-01 20:44:24 +0000414 return B.CreateZExt(B.CreateLoad(B.getInt8Ty(), Str1P, "strcmpload"),
415 CI->getType());
Chris Bienemanad070d02014-09-17 20:55:46 +0000416
David Bolvansky909889b2018-08-10 04:32:54 +0000417 uint64_t Len1 = GetStringLength(Str1P);
418 uint64_t Len2 = GetStringLength(Str2P);
419
420 // strncmp to memcmp
421 if (!HasStr1 && HasStr2) {
422 Len2 = std::min(Len2, Length);
423 if (canTransformToMemCmp(CI, Str1P, Len2, DL))
424 return emitMemCmp(
425 Str1P, Str2P,
426 ConstantInt::get(DL.getIntPtrType(CI->getContext()), Len2), B, DL,
427 TLI);
428 } else if (HasStr1 && !HasStr2) {
429 Len1 = std::min(Len1, Length);
430 if (canTransformToMemCmp(CI, Str2P, Len1, DL))
431 return emitMemCmp(
432 Str1P, Str2P,
433 ConstantInt::get(DL.getIntPtrType(CI->getContext()), Len1), B, DL,
434 TLI);
435 }
436
Chris Bienemanad070d02014-09-17 20:55:46 +0000437 return nullptr;
438}
439
440Value *LibCallSimplifier::optimizeStrCpy(CallInst *CI, IRBuilder<> &B) {
Chris Bienemanad070d02014-09-17 20:55:46 +0000441 Value *Dst = CI->getArgOperand(0), *Src = CI->getArgOperand(1);
442 if (Dst == Src) // strcpy(x,x) -> x
443 return Src;
444
Chris Bienemanad070d02014-09-17 20:55:46 +0000445 // See if we can get the length of the input string.
David Bolvansky1f343fa2018-05-22 20:27:36 +0000446 uint64_t Len = GetStringLength(Src);
Chris Bienemanad070d02014-09-17 20:55:46 +0000447 if (Len == 0)
448 return nullptr;
449
450 // We have enough information to now generate the memcpy call to do the
451 // copy for us. Make a memcpy to copy the nul byte with align = 1.
Daniel Neilson8acd8b02018-02-05 21:23:22 +0000452 B.CreateMemCpy(Dst, 1, Src, 1,
453 ConstantInt::get(DL.getIntPtrType(CI->getContext()), Len));
Chris Bienemanad070d02014-09-17 20:55:46 +0000454 return Dst;
455}
456
457Value *LibCallSimplifier::optimizeStpCpy(CallInst *CI, IRBuilder<> &B) {
458 Function *Callee = CI->getCalledFunction();
Chris Bienemanad070d02014-09-17 20:55:46 +0000459 Value *Dst = CI->getArgOperand(0), *Src = CI->getArgOperand(1);
460 if (Dst == Src) { // stpcpy(x,x) -> x+strlen(x)
Sanjay Pateld3112a52016-01-19 19:46:10 +0000461 Value *StrLen = emitStrLen(Src, B, DL, TLI);
David Blaikieaa41cd52015-04-03 21:33:42 +0000462 return StrLen ? B.CreateInBoundsGEP(B.getInt8Ty(), Dst, StrLen) : nullptr;
Chris Bienemanad070d02014-09-17 20:55:46 +0000463 }
464
465 // See if we can get the length of the input string.
David Bolvansky1f343fa2018-05-22 20:27:36 +0000466 uint64_t Len = GetStringLength(Src);
Chris Bienemanad070d02014-09-17 20:55:46 +0000467 if (Len == 0)
468 return nullptr;
469
Davide Italianob7487e62015-11-02 23:07:14 +0000470 Type *PT = Callee->getFunctionType()->getParamType(0);
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000471 Value *LenV = ConstantInt::get(DL.getIntPtrType(PT), Len);
Sanjay Pateld707db92015-12-31 16:10:49 +0000472 Value *DstEnd = B.CreateGEP(B.getInt8Ty(), Dst,
473 ConstantInt::get(DL.getIntPtrType(PT), Len - 1));
Chris Bienemanad070d02014-09-17 20:55:46 +0000474
475 // We have enough information to now generate the memcpy call to do the
476 // copy for us. Make a memcpy to copy the nul byte with align = 1.
Daniel Neilson8acd8b02018-02-05 21:23:22 +0000477 B.CreateMemCpy(Dst, 1, Src, 1, LenV);
Chris Bienemanad070d02014-09-17 20:55:46 +0000478 return DstEnd;
479}
480
481Value *LibCallSimplifier::optimizeStrNCpy(CallInst *CI, IRBuilder<> &B) {
482 Function *Callee = CI->getCalledFunction();
Chris Bienemanad070d02014-09-17 20:55:46 +0000483 Value *Dst = CI->getArgOperand(0);
484 Value *Src = CI->getArgOperand(1);
485 Value *LenOp = CI->getArgOperand(2);
486
487 // See if we can get the length of the input string.
David Bolvansky1f343fa2018-05-22 20:27:36 +0000488 uint64_t SrcLen = GetStringLength(Src);
Chris Bienemanad070d02014-09-17 20:55:46 +0000489 if (SrcLen == 0)
490 return nullptr;
491 --SrcLen;
492
493 if (SrcLen == 0) {
Daniel Neilson8acd8b02018-02-05 21:23:22 +0000494 // strncpy(x, "", y) -> memset(align 1 x, '\0', y)
Chris Bienemanad070d02014-09-17 20:55:46 +0000495 B.CreateMemSet(Dst, B.getInt8('\0'), LenOp, 1);
Meador Inge7fb2f732012-10-13 16:45:32 +0000496 return Dst;
497 }
Meador Inge7fb2f732012-10-13 16:45:32 +0000498
Chris Bienemanad070d02014-09-17 20:55:46 +0000499 uint64_t Len;
500 if (ConstantInt *LengthArg = dyn_cast<ConstantInt>(LenOp))
501 Len = LengthArg->getZExtValue();
502 else
503 return nullptr;
Meador Inge7fb2f732012-10-13 16:45:32 +0000504
Chris Bienemanad070d02014-09-17 20:55:46 +0000505 if (Len == 0)
506 return Dst; // strncpy(x, y, 0) -> x
Meador Inge7fb2f732012-10-13 16:45:32 +0000507
Chris Bienemanad070d02014-09-17 20:55:46 +0000508 // Let strncpy handle the zero padding
509 if (Len > SrcLen + 1)
510 return nullptr;
Meador Inge7fb2f732012-10-13 16:45:32 +0000511
Davide Italianob7487e62015-11-02 23:07:14 +0000512 Type *PT = Callee->getFunctionType()->getParamType(0);
Daniel Neilson8acd8b02018-02-05 21:23:22 +0000513 // strncpy(x, s, c) -> memcpy(align 1 x, align 1 s, c) [s and c are constant]
514 B.CreateMemCpy(Dst, 1, Src, 1, ConstantInt::get(DL.getIntPtrType(PT), Len));
Meador Inge7fb2f732012-10-13 16:45:32 +0000515
Chris Bienemanad070d02014-09-17 20:55:46 +0000516 return Dst;
517}
Meador Inge7fb2f732012-10-13 16:45:32 +0000518
Matthias Braun50ec0b52017-05-19 22:37:09 +0000519Value *LibCallSimplifier::optimizeStringLength(CallInst *CI, IRBuilder<> &B,
520 unsigned CharSize) {
Chris Bienemanad070d02014-09-17 20:55:46 +0000521 Value *Src = CI->getArgOperand(0);
522
523 // Constant folding: strlen("xyz") -> 3
David Bolvansky1f343fa2018-05-22 20:27:36 +0000524 if (uint64_t Len = GetStringLength(Src, CharSize))
Chris Bienemanad070d02014-09-17 20:55:46 +0000525 return ConstantInt::get(CI->getType(), Len - 1);
526
David L Kreitzer752c1442016-04-13 14:31:06 +0000527 // If s is a constant pointer pointing to a string literal, we can fold
Matthias Braun50ec0b52017-05-19 22:37:09 +0000528 // strlen(s + x) to strlen(s) - x, when x is known to be in the range
David L Kreitzer752c1442016-04-13 14:31:06 +0000529 // [0, strlen(s)] or the string has a single null terminator '\0' at the end.
Matthias Braun50ec0b52017-05-19 22:37:09 +0000530 // We only try to simplify strlen when the pointer s points to an array
David L Kreitzer752c1442016-04-13 14:31:06 +0000531 // of i8. Otherwise, we would need to scale the offset x before doing the
Matthias Braun50ec0b52017-05-19 22:37:09 +0000532 // subtraction. This will make the optimization more complex, and it's not
533 // very useful because calling strlen for a pointer of other types is
David L Kreitzer752c1442016-04-13 14:31:06 +0000534 // very uncommon.
535 if (GEPOperator *GEP = dyn_cast<GEPOperator>(Src)) {
Matthias Braun50ec0b52017-05-19 22:37:09 +0000536 if (!isGEPBasedOnPointerToString(GEP, CharSize))
David L Kreitzer752c1442016-04-13 14:31:06 +0000537 return nullptr;
538
Matthias Braun50ec0b52017-05-19 22:37:09 +0000539 ConstantDataArraySlice Slice;
540 if (getConstantDataArrayInfo(GEP->getOperand(0), Slice, CharSize)) {
541 uint64_t NullTermIdx;
542 if (Slice.Array == nullptr) {
543 NullTermIdx = 0;
544 } else {
545 NullTermIdx = ~((uint64_t)0);
546 for (uint64_t I = 0, E = Slice.Length; I < E; ++I) {
547 if (Slice.Array->getElementAsInteger(I + Slice.Offset) == 0) {
548 NullTermIdx = I;
549 break;
550 }
551 }
552 // If the string does not have '\0', leave it to strlen to compute
553 // its length.
554 if (NullTermIdx == ~((uint64_t)0))
555 return nullptr;
556 }
557
David L Kreitzer752c1442016-04-13 14:31:06 +0000558 Value *Offset = GEP->getOperand(2);
Craig Topper8205a1a2017-05-24 16:53:07 +0000559 KnownBits Known = computeKnownBits(Offset, DL, 0, nullptr, CI, nullptr);
Craig Topperb45eabc2017-04-26 16:39:58 +0000560 Known.Zero.flipAllBits();
Matthias Braun50ec0b52017-05-19 22:37:09 +0000561 uint64_t ArrSize =
David L Kreitzer752c1442016-04-13 14:31:06 +0000562 cast<ArrayType>(GEP->getSourceElementType())->getNumElements();
563
Matthias Braun50ec0b52017-05-19 22:37:09 +0000564 // KnownZero's bits are flipped, so zeros in KnownZero now represent
565 // bits known to be zeros in Offset, and ones in KnowZero represent
David L Kreitzer752c1442016-04-13 14:31:06 +0000566 // bits unknown in Offset. Therefore, Offset is known to be in range
Matthias Braun50ec0b52017-05-19 22:37:09 +0000567 // [0, NullTermIdx] when the flipped KnownZero is non-negative and
David L Kreitzer752c1442016-04-13 14:31:06 +0000568 // unsigned-less-than NullTermIdx.
569 //
Matthias Braun50ec0b52017-05-19 22:37:09 +0000570 // If Offset is not provably in the range [0, NullTermIdx], we can still
571 // optimize if we can prove that the program has undefined behavior when
572 // Offset is outside that range. That is the case when GEP->getOperand(0)
David L Kreitzer752c1442016-04-13 14:31:06 +0000573 // is a pointer to an object whose memory extent is NullTermIdx+1.
Matthias Braun50ec0b52017-05-19 22:37:09 +0000574 if ((Known.Zero.isNonNegative() && Known.Zero.ule(NullTermIdx)) ||
David L Kreitzer752c1442016-04-13 14:31:06 +0000575 (GEP->isInBounds() && isa<GlobalVariable>(GEP->getOperand(0)) &&
Matthias Braun50ec0b52017-05-19 22:37:09 +0000576 NullTermIdx == ArrSize - 1)) {
577 Offset = B.CreateSExtOrTrunc(Offset, CI->getType());
578 return B.CreateSub(ConstantInt::get(CI->getType(), NullTermIdx),
David L Kreitzer752c1442016-04-13 14:31:06 +0000579 Offset);
Matthias Braun50ec0b52017-05-19 22:37:09 +0000580 }
David L Kreitzer752c1442016-04-13 14:31:06 +0000581 }
582
583 return nullptr;
584 }
585
Chris Bienemanad070d02014-09-17 20:55:46 +0000586 // strlen(x?"foo":"bars") --> x ? 3 : 4
587 if (SelectInst *SI = dyn_cast<SelectInst>(Src)) {
David Bolvansky1f343fa2018-05-22 20:27:36 +0000588 uint64_t LenTrue = GetStringLength(SI->getTrueValue(), CharSize);
589 uint64_t LenFalse = GetStringLength(SI->getFalseValue(), CharSize);
Chris Bienemanad070d02014-09-17 20:55:46 +0000590 if (LenTrue && LenFalse) {
Vivek Pandya95906582017-10-11 17:12:59 +0000591 ORE.emit([&]() {
592 return OptimizationRemark("instcombine", "simplify-libcalls", CI)
593 << "folded strlen(select) to select of constants";
594 });
Chris Bienemanad070d02014-09-17 20:55:46 +0000595 return B.CreateSelect(SI->getCondition(),
596 ConstantInt::get(CI->getType(), LenTrue - 1),
597 ConstantInt::get(CI->getType(), LenFalse - 1));
598 }
Meador Inge7fb2f732012-10-13 16:45:32 +0000599 }
Meador Inge7fb2f732012-10-13 16:45:32 +0000600
Chris Bienemanad070d02014-09-17 20:55:46 +0000601 // strlen(x) != 0 --> *x != 0
602 // strlen(x) == 0 --> *x == 0
603 if (isOnlyUsedInZeroEqualityComparison(CI))
James Y Knight14359ef2019-02-01 20:44:24 +0000604 return B.CreateZExt(B.CreateLoad(B.getIntNTy(CharSize), Src, "strlenfirst"),
605 CI->getType());
Meador Inge17418502012-10-13 16:45:37 +0000606
Chris Bienemanad070d02014-09-17 20:55:46 +0000607 return nullptr;
608}
Meador Inge17418502012-10-13 16:45:37 +0000609
Matthias Braun50ec0b52017-05-19 22:37:09 +0000610Value *LibCallSimplifier::optimizeStrLen(CallInst *CI, IRBuilder<> &B) {
611 return optimizeStringLength(CI, B, 8);
612}
613
614Value *LibCallSimplifier::optimizeWcslen(CallInst *CI, IRBuilder<> &B) {
David Bolvansky5430b7372018-05-31 16:39:27 +0000615 Module &M = *CI->getModule();
Matthias Braun50ec0b52017-05-19 22:37:09 +0000616 unsigned WCharSize = TLI->getWCharSize(M) * 8;
Matthias Brauncc603ee2017-09-26 02:36:57 +0000617 // We cannot perform this optimization without wchar_size metadata.
618 if (WCharSize == 0)
619 return nullptr;
Matthias Braun50ec0b52017-05-19 22:37:09 +0000620
621 return optimizeStringLength(CI, B, WCharSize);
622}
623
Chris Bienemanad070d02014-09-17 20:55:46 +0000624Value *LibCallSimplifier::optimizeStrPBrk(CallInst *CI, IRBuilder<> &B) {
Chris Bienemanad070d02014-09-17 20:55:46 +0000625 StringRef S1, S2;
626 bool HasS1 = getConstantStringInfo(CI->getArgOperand(0), S1);
627 bool HasS2 = getConstantStringInfo(CI->getArgOperand(1), S2);
Meador Inge17418502012-10-13 16:45:37 +0000628
Reid Kleckner971c3ea2014-11-13 22:55:19 +0000629 // strpbrk(s, "") -> nullptr
630 // strpbrk("", s) -> nullptr
Chris Bienemanad070d02014-09-17 20:55:46 +0000631 if ((HasS1 && S1.empty()) || (HasS2 && S2.empty()))
632 return Constant::getNullValue(CI->getType());
Meador Inge17418502012-10-13 16:45:37 +0000633
Chris Bienemanad070d02014-09-17 20:55:46 +0000634 // Constant folding.
635 if (HasS1 && HasS2) {
636 size_t I = S1.find_first_of(S2);
637 if (I == StringRef::npos) // No match.
Meador Inge17418502012-10-13 16:45:37 +0000638 return Constant::getNullValue(CI->getType());
639
Sanjay Pateld707db92015-12-31 16:10:49 +0000640 return B.CreateGEP(B.getInt8Ty(), CI->getArgOperand(0), B.getInt64(I),
641 "strpbrk");
Meador Inge17418502012-10-13 16:45:37 +0000642 }
Meador Inge17418502012-10-13 16:45:37 +0000643
Chris Bienemanad070d02014-09-17 20:55:46 +0000644 // strpbrk(s, "a") -> strchr(s, 'a')
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000645 if (HasS2 && S2.size() == 1)
Sanjay Pateld3112a52016-01-19 19:46:10 +0000646 return emitStrChr(CI->getArgOperand(0), S2[0], B, TLI);
Chris Bienemanad070d02014-09-17 20:55:46 +0000647
648 return nullptr;
649}
650
651Value *LibCallSimplifier::optimizeStrTo(CallInst *CI, IRBuilder<> &B) {
Chris Bienemanad070d02014-09-17 20:55:46 +0000652 Value *EndPtr = CI->getArgOperand(1);
653 if (isa<ConstantPointerNull>(EndPtr)) {
654 // With a null EndPtr, this function won't capture the main argument.
655 // It would be readonly too, except that it still may write to errno.
Reid Klecknera0b45f42017-05-03 18:17:31 +0000656 CI->addParamAttr(0, Attribute::NoCapture);
Chris Bienemanad070d02014-09-17 20:55:46 +0000657 }
658
659 return nullptr;
660}
661
662Value *LibCallSimplifier::optimizeStrSpn(CallInst *CI, IRBuilder<> &B) {
Chris Bienemanad070d02014-09-17 20:55:46 +0000663 StringRef S1, S2;
664 bool HasS1 = getConstantStringInfo(CI->getArgOperand(0), S1);
665 bool HasS2 = getConstantStringInfo(CI->getArgOperand(1), S2);
666
667 // strspn(s, "") -> 0
668 // strspn("", s) -> 0
669 if ((HasS1 && S1.empty()) || (HasS2 && S2.empty()))
670 return Constant::getNullValue(CI->getType());
671
672 // Constant folding.
673 if (HasS1 && HasS2) {
674 size_t Pos = S1.find_first_not_of(S2);
675 if (Pos == StringRef::npos)
676 Pos = S1.size();
677 return ConstantInt::get(CI->getType(), Pos);
678 }
679
680 return nullptr;
681}
682
683Value *LibCallSimplifier::optimizeStrCSpn(CallInst *CI, IRBuilder<> &B) {
Chris Bienemanad070d02014-09-17 20:55:46 +0000684 StringRef S1, S2;
685 bool HasS1 = getConstantStringInfo(CI->getArgOperand(0), S1);
686 bool HasS2 = getConstantStringInfo(CI->getArgOperand(1), S2);
687
688 // strcspn("", s) -> 0
689 if (HasS1 && S1.empty())
690 return Constant::getNullValue(CI->getType());
691
692 // Constant folding.
693 if (HasS1 && HasS2) {
694 size_t Pos = S1.find_first_of(S2);
695 if (Pos == StringRef::npos)
696 Pos = S1.size();
697 return ConstantInt::get(CI->getType(), Pos);
698 }
699
700 // strcspn(s, "") -> strlen(s)
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000701 if (HasS2 && S2.empty())
Sanjay Pateld3112a52016-01-19 19:46:10 +0000702 return emitStrLen(CI->getArgOperand(0), B, DL, TLI);
Chris Bienemanad070d02014-09-17 20:55:46 +0000703
704 return nullptr;
705}
706
707Value *LibCallSimplifier::optimizeStrStr(CallInst *CI, IRBuilder<> &B) {
Chris Bienemanad070d02014-09-17 20:55:46 +0000708 // fold strstr(x, x) -> x.
709 if (CI->getArgOperand(0) == CI->getArgOperand(1))
710 return B.CreateBitCast(CI->getArgOperand(0), CI->getType());
711
712 // fold strstr(a, b) == a -> strncmp(a, b, strlen(b)) == 0
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000713 if (isOnlyUsedInEqualityComparison(CI, CI->getArgOperand(0))) {
Sanjay Pateld3112a52016-01-19 19:46:10 +0000714 Value *StrLen = emitStrLen(CI->getArgOperand(1), B, DL, TLI);
Chris Bienemanad070d02014-09-17 20:55:46 +0000715 if (!StrLen)
Craig Topperf40110f2014-04-25 05:29:35 +0000716 return nullptr;
Sanjay Pateld3112a52016-01-19 19:46:10 +0000717 Value *StrNCmp = emitStrNCmp(CI->getArgOperand(0), CI->getArgOperand(1),
Chris Bienemanad070d02014-09-17 20:55:46 +0000718 StrLen, B, DL, TLI);
719 if (!StrNCmp)
Craig Topperf40110f2014-04-25 05:29:35 +0000720 return nullptr;
Chris Bienemanad070d02014-09-17 20:55:46 +0000721 for (auto UI = CI->user_begin(), UE = CI->user_end(); UI != UE;) {
722 ICmpInst *Old = cast<ICmpInst>(*UI++);
723 Value *Cmp =
724 B.CreateICmp(Old->getPredicate(), StrNCmp,
725 ConstantInt::getNullValue(StrNCmp->getType()), "cmp");
726 replaceAllUsesWith(Old, Cmp);
Meador Inge17418502012-10-13 16:45:37 +0000727 }
Chris Bienemanad070d02014-09-17 20:55:46 +0000728 return CI;
729 }
Meador Inge17418502012-10-13 16:45:37 +0000730
Chris Bienemanad070d02014-09-17 20:55:46 +0000731 // See if either input string is a constant string.
732 StringRef SearchStr, ToFindStr;
733 bool HasStr1 = getConstantStringInfo(CI->getArgOperand(0), SearchStr);
734 bool HasStr2 = getConstantStringInfo(CI->getArgOperand(1), ToFindStr);
735
736 // fold strstr(x, "") -> x.
737 if (HasStr2 && ToFindStr.empty())
738 return B.CreateBitCast(CI->getArgOperand(0), CI->getType());
739
740 // If both strings are known, constant fold it.
741 if (HasStr1 && HasStr2) {
742 size_t Offset = SearchStr.find(ToFindStr);
743
744 if (Offset == StringRef::npos) // strstr("foo", "bar") -> null
Meador Inge17418502012-10-13 16:45:37 +0000745 return Constant::getNullValue(CI->getType());
746
Chris Bienemanad070d02014-09-17 20:55:46 +0000747 // strstr("abcd", "bc") -> gep((char*)"abcd", 1)
Sanjay Pateld3112a52016-01-19 19:46:10 +0000748 Value *Result = castToCStr(CI->getArgOperand(0), B);
James Y Knight77160752019-02-01 20:44:47 +0000749 Result =
750 B.CreateConstInBoundsGEP1_64(B.getInt8Ty(), Result, Offset, "strstr");
Chris Bienemanad070d02014-09-17 20:55:46 +0000751 return B.CreateBitCast(Result, CI->getType());
Meador Inge17418502012-10-13 16:45:37 +0000752 }
Meador Inge17418502012-10-13 16:45:37 +0000753
Chris Bienemanad070d02014-09-17 20:55:46 +0000754 // fold strstr(x, "y") -> strchr(x, 'y').
755 if (HasStr2 && ToFindStr.size() == 1) {
Sanjay Pateld3112a52016-01-19 19:46:10 +0000756 Value *StrChr = emitStrChr(CI->getArgOperand(0), ToFindStr[0], B, TLI);
Chris Bienemanad070d02014-09-17 20:55:46 +0000757 return StrChr ? B.CreateBitCast(StrChr, CI->getType()) : nullptr;
758 }
759 return nullptr;
760}
Meador Inge40b6fac2012-10-15 03:47:37 +0000761
Benjamin Kramer691363e2015-03-21 15:36:21 +0000762Value *LibCallSimplifier::optimizeMemChr(CallInst *CI, IRBuilder<> &B) {
Benjamin Kramer691363e2015-03-21 15:36:21 +0000763 Value *SrcStr = CI->getArgOperand(0);
764 ConstantInt *CharC = dyn_cast<ConstantInt>(CI->getArgOperand(1));
765 ConstantInt *LenC = dyn_cast<ConstantInt>(CI->getArgOperand(2));
766
767 // memchr(x, y, 0) -> null
Craig Topper79ab6432017-07-06 18:39:47 +0000768 if (LenC && LenC->isZero())
Benjamin Kramer691363e2015-03-21 15:36:21 +0000769 return Constant::getNullValue(CI->getType());
770
Benjamin Kramer7857d722015-03-21 21:09:33 +0000771 // From now on we need at least constant length and string.
Benjamin Kramer691363e2015-03-21 15:36:21 +0000772 StringRef Str;
Benjamin Kramer7857d722015-03-21 21:09:33 +0000773 if (!LenC || !getConstantStringInfo(SrcStr, Str, 0, /*TrimAtNul=*/false))
Benjamin Kramer691363e2015-03-21 15:36:21 +0000774 return nullptr;
775
776 // Truncate the string to LenC. If Str is smaller than LenC we will still only
777 // scan the string, as reading past the end of it is undefined and we can just
778 // return null if we don't find the char.
779 Str = Str.substr(0, LenC->getZExtValue());
780
Benjamin Kramer7857d722015-03-21 21:09:33 +0000781 // If the char is variable but the input str and length are not we can turn
782 // this memchr call into a simple bit field test. Of course this only works
783 // when the return value is only checked against null.
784 //
785 // It would be really nice to reuse switch lowering here but we can't change
786 // the CFG at this point.
787 //
Fangrui Songf2609672019-03-12 10:31:52 +0000788 // memchr("\r\n", C, 2) != nullptr -> (1 << C & ((1 << '\r') | (1 << '\n')))
789 // != 0
Benjamin Kramer7857d722015-03-21 21:09:33 +0000790 // after bounds check.
791 if (!CharC && !Str.empty() && isOnlyUsedInZeroEqualityComparison(CI)) {
Benjamin Kramerd6aa0ec2015-03-21 22:04:26 +0000792 unsigned char Max =
793 *std::max_element(reinterpret_cast<const unsigned char *>(Str.begin()),
794 reinterpret_cast<const unsigned char *>(Str.end()));
Benjamin Kramer7857d722015-03-21 21:09:33 +0000795
796 // Make sure the bit field we're about to create fits in a register on the
797 // target.
798 // FIXME: On a 64 bit architecture this prevents us from using the
799 // interesting range of alpha ascii chars. We could do better by emitting
800 // two bitfields or shifting the range by 64 if no lower chars are used.
801 if (!DL.fitsInLegalInteger(Max + 1))
802 return nullptr;
803
804 // For the bit field use a power-of-2 type with at least 8 bits to avoid
805 // creating unnecessary illegal types.
806 unsigned char Width = NextPowerOf2(std::max((unsigned char)7, Max));
807
808 // Now build the bit field.
809 APInt Bitfield(Width, 0);
810 for (char C : Str)
811 Bitfield.setBit((unsigned char)C);
812 Value *BitfieldC = B.getInt(Bitfield);
813
Eli Friedmand4e7a0d2019-01-09 23:39:26 +0000814 // Adjust width of "C" to the bitfield width, then mask off the high bits.
Benjamin Kramer7857d722015-03-21 21:09:33 +0000815 Value *C = B.CreateZExtOrTrunc(CI->getArgOperand(1), BitfieldC->getType());
Eli Friedmand4e7a0d2019-01-09 23:39:26 +0000816 C = B.CreateAnd(C, B.getIntN(Width, 0xFF));
817
818 // First check that the bit field access is within bounds.
Benjamin Kramer7857d722015-03-21 21:09:33 +0000819 Value *Bounds = B.CreateICmp(ICmpInst::ICMP_ULT, C, B.getIntN(Width, Width),
820 "memchr.bounds");
821
822 // Create code that checks if the given bit is set in the field.
823 Value *Shl = B.CreateShl(B.getIntN(Width, 1ULL), C);
824 Value *Bits = B.CreateIsNotNull(B.CreateAnd(Shl, BitfieldC), "memchr.bits");
825
826 // Finally merge both checks and cast to pointer type. The inttoptr
827 // implicitly zexts the i1 to intptr type.
828 return B.CreateIntToPtr(B.CreateAnd(Bounds, Bits, "memchr"), CI->getType());
829 }
830
831 // Check if all arguments are constants. If so, we can constant fold.
832 if (!CharC)
833 return nullptr;
834
Benjamin Kramer691363e2015-03-21 15:36:21 +0000835 // Compute the offset.
836 size_t I = Str.find(CharC->getSExtValue() & 0xFF);
837 if (I == StringRef::npos) // Didn't find the char. memchr returns null.
838 return Constant::getNullValue(CI->getType());
839
840 // memchr(s+n,c,l) -> gep(s+n+i,c)
David Blaikie3909da72015-03-30 20:42:56 +0000841 return B.CreateGEP(B.getInt8Ty(), SrcStr, B.getInt64(I), "memchr");
Benjamin Kramer691363e2015-03-21 15:36:21 +0000842}
843
Clement Courbet8e16d732019-03-08 09:07:45 +0000844static Value *optimizeMemCmpConstantSize(CallInst *CI, Value *LHS, Value *RHS,
845 uint64_t Len, IRBuilder<> &B,
846 const DataLayout &DL) {
Chris Bienemanad070d02014-09-17 20:55:46 +0000847 if (Len == 0) // memcmp(s1,s2,0) -> 0
848 return Constant::getNullValue(CI->getType());
849
850 // memcmp(S1,S2,1) -> *(unsigned char*)LHS - *(unsigned char*)RHS
851 if (Len == 1) {
James Y Knight14359ef2019-02-01 20:44:24 +0000852 Value *LHSV =
853 B.CreateZExt(B.CreateLoad(B.getInt8Ty(), castToCStr(LHS, B), "lhsc"),
854 CI->getType(), "lhsv");
855 Value *RHSV =
856 B.CreateZExt(B.CreateLoad(B.getInt8Ty(), castToCStr(RHS, B), "rhsc"),
857 CI->getType(), "rhsv");
Chris Bienemanad070d02014-09-17 20:55:46 +0000858 return B.CreateSub(LHSV, RHSV, "chardiff");
Meador Inge40b6fac2012-10-15 03:47:37 +0000859 }
Meador Inge40b6fac2012-10-15 03:47:37 +0000860
Chad Rosierdc655322015-08-28 18:30:18 +0000861 // memcmp(S1,S2,N/8)==0 -> (*(intN_t*)S1 != *(intN_t*)S2)==0
Sanjay Patel82ec8722017-08-21 19:13:14 +0000862 // TODO: The case where both inputs are constants does not need to be limited
863 // to legal integers or equality comparison. See block below this.
Chad Rosierdc655322015-08-28 18:30:18 +0000864 if (DL.isLegalInteger(Len * 8) && isOnlyUsedInZeroEqualityComparison(CI)) {
Chad Rosierdc655322015-08-28 18:30:18 +0000865 IntegerType *IntType = IntegerType::get(CI->getContext(), Len * 8);
866 unsigned PrefAlignment = DL.getPrefTypeAlignment(IntType);
867
Sanjay Patel82ec8722017-08-21 19:13:14 +0000868 // First, see if we can fold either argument to a constant.
869 Value *LHSV = nullptr;
870 if (auto *LHSC = dyn_cast<Constant>(LHS)) {
871 LHSC = ConstantExpr::getBitCast(LHSC, IntType->getPointerTo());
872 LHSV = ConstantFoldLoadFromConstPtr(LHSC, IntType, DL);
873 }
874 Value *RHSV = nullptr;
875 if (auto *RHSC = dyn_cast<Constant>(RHS)) {
876 RHSC = ConstantExpr::getBitCast(RHSC, IntType->getPointerTo());
877 RHSV = ConstantFoldLoadFromConstPtr(RHSC, IntType, DL);
878 }
Chad Rosierdc655322015-08-28 18:30:18 +0000879
Sanjay Patel82ec8722017-08-21 19:13:14 +0000880 // Don't generate unaligned loads. If either source is constant data,
881 // alignment doesn't matter for that source because there is no load.
882 if ((LHSV || getKnownAlignment(LHS, DL, CI) >= PrefAlignment) &&
883 (RHSV || getKnownAlignment(RHS, DL, CI) >= PrefAlignment)) {
884 if (!LHSV) {
885 Type *LHSPtrTy =
886 IntType->getPointerTo(LHS->getType()->getPointerAddressSpace());
James Y Knight14359ef2019-02-01 20:44:24 +0000887 LHSV = B.CreateLoad(IntType, B.CreateBitCast(LHS, LHSPtrTy), "lhsv");
Sanjay Patel82ec8722017-08-21 19:13:14 +0000888 }
889 if (!RHSV) {
890 Type *RHSPtrTy =
891 IntType->getPointerTo(RHS->getType()->getPointerAddressSpace());
James Y Knight14359ef2019-02-01 20:44:24 +0000892 RHSV = B.CreateLoad(IntType, B.CreateBitCast(RHS, RHSPtrTy), "rhsv");
Sanjay Patel82ec8722017-08-21 19:13:14 +0000893 }
Sanjay Patel7756edf2017-08-21 13:55:49 +0000894 return B.CreateZExt(B.CreateICmpNE(LHSV, RHSV), CI->getType(), "memcmp");
Sanjay Patel707f7862017-08-21 15:16:25 +0000895 }
Chad Rosierdc655322015-08-28 18:30:18 +0000896 }
897
Sanjay Patel82ec8722017-08-21 19:13:14 +0000898 // Constant folding: memcmp(x, y, Len) -> constant (all arguments are const).
899 // TODO: This is limited to i8 arrays.
Chris Bienemanad070d02014-09-17 20:55:46 +0000900 StringRef LHSStr, RHSStr;
901 if (getConstantStringInfo(LHS, LHSStr) &&
902 getConstantStringInfo(RHS, RHSStr)) {
903 // Make sure we're not reading out-of-bounds memory.
904 if (Len > LHSStr.size() || Len > RHSStr.size())
Craig Topperf40110f2014-04-25 05:29:35 +0000905 return nullptr;
Chris Bienemanad070d02014-09-17 20:55:46 +0000906 // Fold the memcmp and normalize the result. This way we get consistent
907 // results across multiple platforms.
908 uint64_t Ret = 0;
909 int Cmp = memcmp(LHSStr.data(), RHSStr.data(), Len);
910 if (Cmp < 0)
911 Ret = -1;
912 else if (Cmp > 0)
913 Ret = 1;
914 return ConstantInt::get(CI->getType(), Ret);
Meador Inge000dbcc2012-10-18 18:12:40 +0000915 }
Clement Courbet8e16d732019-03-08 09:07:45 +0000916 return nullptr;
917}
918
Clement Courbet9e1f2a72019-05-06 09:15:22 +0000919// Most simplifications for memcmp also apply to bcmp.
920Value *LibCallSimplifier::optimizeMemCmpBCmpCommon(CallInst *CI,
921 IRBuilder<> &B) {
Clement Courbet8e16d732019-03-08 09:07:45 +0000922 Value *LHS = CI->getArgOperand(0), *RHS = CI->getArgOperand(1);
923 Value *Size = CI->getArgOperand(2);
924
925 if (LHS == RHS) // memcmp(s,s,x) -> 0
926 return Constant::getNullValue(CI->getType());
927
928 // Handle constant lengths.
929 if (ConstantInt *LenC = dyn_cast<ConstantInt>(Size))
930 if (Value *Res = optimizeMemCmpConstantSize(CI, LHS, RHS,
931 LenC->getZExtValue(), B, DL))
932 return Res;
933
Clement Courbet9e1f2a72019-05-06 09:15:22 +0000934 return nullptr;
935}
936
937Value *LibCallSimplifier::optimizeMemCmp(CallInst *CI, IRBuilder<> &B) {
938 if (Value *V = optimizeMemCmpBCmpCommon(CI, B))
939 return V;
940
Clement Courbet8e16d732019-03-08 09:07:45 +0000941 // memcmp(x, y, Len) == 0 -> bcmp(x, y, Len) == 0
Evandro Menezes5cd5f9b2019-07-24 23:31:04 +0000942 // bcmp can be more efficient than memcmp because it only has to know that
943 // there is a difference, not how different one is to the other.
944 if (TLI->has(LibFunc_bcmp) && isOnlyUsedInZeroEqualityComparison(CI)) {
Clement Courbet9e1f2a72019-05-06 09:15:22 +0000945 Value *LHS = CI->getArgOperand(0);
946 Value *RHS = CI->getArgOperand(1);
947 Value *Size = CI->getArgOperand(2);
Clement Courbet8e16d732019-03-08 09:07:45 +0000948 return emitBCmp(LHS, RHS, Size, B, DL, TLI);
949 }
Meador Inge000dbcc2012-10-18 18:12:40 +0000950
Chris Bienemanad070d02014-09-17 20:55:46 +0000951 return nullptr;
952}
Meador Inge9a6a1902012-10-31 00:20:56 +0000953
Clement Courbet9e1f2a72019-05-06 09:15:22 +0000954Value *LibCallSimplifier::optimizeBCmp(CallInst *CI, IRBuilder<> &B) {
955 return optimizeMemCmpBCmpCommon(CI, B);
956}
957
Chris Bienemanad070d02014-09-17 20:55:46 +0000958Value *LibCallSimplifier::optimizeMemCpy(CallInst *CI, IRBuilder<> &B) {
Daniel Neilson8acd8b02018-02-05 21:23:22 +0000959 // memcpy(x, y, n) -> llvm.memcpy(align 1 x, align 1 y, n)
960 B.CreateMemCpy(CI->getArgOperand(0), 1, CI->getArgOperand(1), 1,
961 CI->getArgOperand(2));
Chris Bienemanad070d02014-09-17 20:55:46 +0000962 return CI->getArgOperand(0);
963}
Meador Inge05a625a2012-10-31 14:58:26 +0000964
Chris Bienemanad070d02014-09-17 20:55:46 +0000965Value *LibCallSimplifier::optimizeMemMove(CallInst *CI, IRBuilder<> &B) {
Daniel Neilson8acd8b02018-02-05 21:23:22 +0000966 // memmove(x, y, n) -> llvm.memmove(align 1 x, align 1 y, n)
967 B.CreateMemMove(CI->getArgOperand(0), 1, CI->getArgOperand(1), 1,
968 CI->getArgOperand(2));
Chris Bienemanad070d02014-09-17 20:55:46 +0000969 return CI->getArgOperand(0);
970}
Meador Ingebcd88ef72012-11-10 15:16:48 +0000971
Sanjay Patel980b2802016-01-26 16:17:24 +0000972/// Fold memset[_chk](malloc(n), 0, n) --> calloc(1, n).
Amara Emerson54f60252018-10-11 14:51:11 +0000973Value *LibCallSimplifier::foldMallocMemset(CallInst *Memset, IRBuilder<> &B) {
Sanjay Patel980b2802016-01-26 16:17:24 +0000974 // This has to be a memset of zeros (bzero).
975 auto *FillValue = dyn_cast<ConstantInt>(Memset->getArgOperand(1));
976 if (!FillValue || FillValue->getZExtValue() != 0)
977 return nullptr;
978
979 // TODO: We should handle the case where the malloc has more than one use.
980 // This is necessary to optimize common patterns such as when the result of
981 // the malloc is checked against null or when a memset intrinsic is used in
982 // place of a memset library call.
983 auto *Malloc = dyn_cast<CallInst>(Memset->getArgOperand(0));
984 if (!Malloc || !Malloc->hasOneUse())
985 return nullptr;
986
987 // Is the inner call really malloc()?
988 Function *InnerCallee = Malloc->getCalledFunction();
Matthias Braunc36a78c2017-04-25 19:44:25 +0000989 if (!InnerCallee)
990 return nullptr;
991
David L. Jonesd21529f2017-01-23 23:16:46 +0000992 LibFunc Func;
Amara Emerson54f60252018-10-11 14:51:11 +0000993 if (!TLI->getLibFunc(*InnerCallee, Func) || !TLI->has(Func) ||
David L. Jonesd21529f2017-01-23 23:16:46 +0000994 Func != LibFunc_malloc)
Sanjay Patel980b2802016-01-26 16:17:24 +0000995 return nullptr;
996
Sanjay Patel980b2802016-01-26 16:17:24 +0000997 // The memset must cover the same number of bytes that are malloc'd.
998 if (Memset->getArgOperand(2) != Malloc->getArgOperand(0))
999 return nullptr;
1000
1001 // Replace the malloc with a calloc. We need the data layout to know what the
Fangrui Songf78650a2018-07-30 19:41:25 +00001002 // actual size of a 'size_t' parameter is.
Sanjay Patel980b2802016-01-26 16:17:24 +00001003 B.SetInsertPoint(Malloc->getParent(), ++Malloc->getIterator());
1004 const DataLayout &DL = Malloc->getModule()->getDataLayout();
1005 IntegerType *SizeType = DL.getIntPtrType(B.GetInsertBlock()->getContext());
1006 Value *Calloc = emitCalloc(ConstantInt::get(SizeType, 1),
1007 Malloc->getArgOperand(0), Malloc->getAttributes(),
Amara Emerson54f60252018-10-11 14:51:11 +00001008 B, *TLI);
Sanjay Patel980b2802016-01-26 16:17:24 +00001009 if (!Calloc)
1010 return nullptr;
1011
1012 Malloc->replaceAllUsesWith(Calloc);
Amara Emerson54f60252018-10-11 14:51:11 +00001013 eraseFromParent(Malloc);
Sanjay Patel980b2802016-01-26 16:17:24 +00001014
1015 return Calloc;
1016}
1017
Chris Bienemanad070d02014-09-17 20:55:46 +00001018Value *LibCallSimplifier::optimizeMemSet(CallInst *CI, IRBuilder<> &B) {
Amara Emerson54f60252018-10-11 14:51:11 +00001019 if (auto *Calloc = foldMallocMemset(CI, B))
Sanjay Patel980b2802016-01-26 16:17:24 +00001020 return Calloc;
1021
Daniel Neilson8acd8b02018-02-05 21:23:22 +00001022 // memset(p, v, n) -> llvm.memset(align 1 p, v, n)
Chris Bienemanad070d02014-09-17 20:55:46 +00001023 Value *Val = B.CreateIntCast(CI->getArgOperand(1), B.getInt8Ty(), false);
1024 B.CreateMemSet(CI->getArgOperand(0), Val, CI->getArgOperand(2), 1);
1025 return CI->getArgOperand(0);
1026}
Meador Inged4825782012-11-11 06:49:03 +00001027
Sanjay Patelb2ab3f22018-04-18 14:21:31 +00001028Value *LibCallSimplifier::optimizeRealloc(CallInst *CI, IRBuilder<> &B) {
1029 if (isa<ConstantPointerNull>(CI->getArgOperand(0)))
1030 return emitMalloc(CI->getArgOperand(1), B, DL, TLI);
1031
1032 return nullptr;
1033}
1034
Meador Inge193e0352012-11-13 04:16:17 +00001035//===----------------------------------------------------------------------===//
1036// Math Library Optimizations
1037//===----------------------------------------------------------------------===//
1038
Evandro Menezes5aa217a2018-08-03 17:50:16 +00001039// Replace a libcall \p CI with a call to intrinsic \p IID
1040static Value *replaceUnaryCall(CallInst *CI, IRBuilder<> &B, Intrinsic::ID IID) {
1041 // Propagate fast-math flags from the existing call to the new call.
1042 IRBuilder<>::FastMathFlagGuard Guard(B);
1043 B.setFastMathFlags(CI->getFastMathFlags());
1044
1045 Module *M = CI->getModule();
1046 Value *V = CI->getArgOperand(0);
1047 Function *F = Intrinsic::getDeclaration(M, IID, CI->getType());
1048 CallInst *NewCall = B.CreateCall(F, V);
1049 NewCall->takeName(CI);
1050 return NewCall;
1051}
1052
Matthias Braund34e4d22014-12-03 21:46:33 +00001053/// Return a variant of Val with float type.
1054/// Currently this works in two cases: If Val is an FPExtension of a float
1055/// value to something bigger, simply return the operand.
1056/// If Val is a ConstantFP but can be converted to a float ConstantFP without
1057/// loss of precision do so.
1058static Value *valueHasFloatPrecision(Value *Val) {
1059 if (FPExtInst *Cast = dyn_cast<FPExtInst>(Val)) {
1060 Value *Op = Cast->getOperand(0);
1061 if (Op->getType()->isFloatTy())
1062 return Op;
1063 }
1064 if (ConstantFP *Const = dyn_cast<ConstantFP>(Val)) {
1065 APFloat F = Const->getValueAPF();
Matthias Braun395a82f2014-12-03 22:10:39 +00001066 bool losesInfo;
Stephan Bergmann17c7f702016-12-14 11:57:17 +00001067 (void)F.convert(APFloat::IEEEsingle(), APFloat::rmNearestTiesToEven,
Matthias Braun395a82f2014-12-03 22:10:39 +00001068 &losesInfo);
1069 if (!losesInfo)
Matthias Braund34e4d22014-12-03 21:46:33 +00001070 return ConstantFP::get(Const->getContext(), F);
1071 }
1072 return nullptr;
1073}
1074
Evandro Menezes5aa217a2018-08-03 17:50:16 +00001075/// Shrink double -> float functions.
1076static Value *optimizeDoubleFP(CallInst *CI, IRBuilder<> &B,
Evandro Menezes6e137cb2018-08-06 19:40:17 +00001077 bool isBinary, bool isPrecise = false) {
Simon Pilgrim364ef5d2019-05-06 19:51:54 +00001078 Function *CalleeFn = CI->getCalledFunction();
1079 if (!CI->getType()->isDoubleTy() || !CalleeFn)
Chris Bienemanad070d02014-09-17 20:55:46 +00001080 return nullptr;
Meador Inge193e0352012-11-13 04:16:17 +00001081
Evandro Menezes6e137cb2018-08-06 19:40:17 +00001082 // If not all the uses of the function are converted to float, then bail out.
1083 // This matters if the precision of the result is more important than the
1084 // precision of the arguments.
1085 if (isPrecise)
Chris Bienemanad070d02014-09-17 20:55:46 +00001086 for (User *U : CI->users()) {
1087 FPTruncInst *Cast = dyn_cast<FPTruncInst>(U);
1088 if (!Cast || !Cast->getType()->isFloatTy())
1089 return nullptr;
Meador Inge193e0352012-11-13 04:16:17 +00001090 }
Chris Bienemanad070d02014-09-17 20:55:46 +00001091
Evandro Menezes5aa217a2018-08-03 17:50:16 +00001092 // If this is something like 'g((double) float)', convert to 'gf(float)'.
1093 Value *V[2];
1094 V[0] = valueHasFloatPrecision(CI->getArgOperand(0));
1095 V[1] = isBinary ? valueHasFloatPrecision(CI->getArgOperand(1)) : nullptr;
1096 if (!V[0] || (isBinary && !V[1]))
Chris Bienemanad070d02014-09-17 20:55:46 +00001097 return nullptr;
Fangrui Songf78650a2018-07-30 19:41:25 +00001098
Evandro Menezesea349f32019-04-30 18:35:38 +00001099 StringRef CalleeNm = CalleeFn->getName();
1100 AttributeList CalleeAt = CalleeFn->getAttributes();
1101 bool CalleeIn = CalleeFn->isIntrinsic();
1102
Andrew Ng1606fc02017-04-25 12:36:14 +00001103 // If call isn't an intrinsic, check that it isn't within a function with the
Evandro Menezes5aa217a2018-08-03 17:50:16 +00001104 // same name as the float version of this call, otherwise the result is an
1105 // infinite loop. For example, from MinGW-w64:
Andrew Ng1606fc02017-04-25 12:36:14 +00001106 //
Evandro Menezes5aa217a2018-08-03 17:50:16 +00001107 // float expf(float val) { return (float) exp((double) val); }
Evandro Menezesea349f32019-04-30 18:35:38 +00001108 if (!CalleeIn) {
Evandro Menezes5aa217a2018-08-03 17:50:16 +00001109 const Function *Fn = CI->getFunction();
1110 StringRef FnName = Fn->getName();
1111 if (FnName.back() == 'f' &&
1112 FnName.size() == (CalleeNm.size() + 1) &&
1113 FnName.startswith(CalleeNm))
Andrew Ng1606fc02017-04-25 12:36:14 +00001114 return nullptr;
1115 }
1116
Evandro Menezes5aa217a2018-08-03 17:50:16 +00001117 // Propagate the math semantics from the current function to the new function.
Sanjay Patelaa231142015-12-31 21:52:31 +00001118 IRBuilder<>::FastMathFlagGuard Guard(B);
Sanjay Patela2528152016-01-12 18:03:37 +00001119 B.setFastMathFlags(CI->getFastMathFlags());
Chris Bienemanad070d02014-09-17 20:55:46 +00001120
Evandro Menezes5aa217a2018-08-03 17:50:16 +00001121 // g((double) float) -> (double) gf(float)
1122 Value *R;
Evandro Menezesea349f32019-04-30 18:35:38 +00001123 if (CalleeIn) {
Sanjay Patelaf674fb2015-12-14 17:24:23 +00001124 Module *M = CI->getModule();
Evandro Menezes5aa217a2018-08-03 17:50:16 +00001125 Intrinsic::ID IID = CalleeFn->getIntrinsicID();
1126 Function *Fn = Intrinsic::getDeclaration(M, IID, B.getFloatTy());
1127 R = isBinary ? B.CreateCall(Fn, V) : B.CreateCall(Fn, V[0]);
Sanjay Patel848309d2014-10-23 21:52:45 +00001128 }
Evandro Menezes5aa217a2018-08-03 17:50:16 +00001129 else
1130 R = isBinary ? emitBinaryFloatFnCall(V[0], V[1], CalleeNm, B, CalleeAt)
1131 : emitUnaryFloatFnCall(V[0], CalleeNm, B, CalleeAt);
Sanjay Patel848309d2014-10-23 21:52:45 +00001132
Evandro Menezes5aa217a2018-08-03 17:50:16 +00001133 return B.CreateFPExt(R, B.getDoubleTy());
Chris Bienemanad070d02014-09-17 20:55:46 +00001134}
Meador Inge193e0352012-11-13 04:16:17 +00001135
Evandro Menezes5aa217a2018-08-03 17:50:16 +00001136/// Shrink double -> float for unary functions.
1137static Value *optimizeUnaryDoubleFP(CallInst *CI, IRBuilder<> &B,
Evandro Menezes6e137cb2018-08-06 19:40:17 +00001138 bool isPrecise = false) {
1139 return optimizeDoubleFP(CI, B, false, isPrecise);
Matt Arsenault954a6242017-01-23 23:55:08 +00001140}
1141
Evandro Menezes5aa217a2018-08-03 17:50:16 +00001142/// Shrink double -> float for binary functions.
1143static Value *optimizeBinaryDoubleFP(CallInst *CI, IRBuilder<> &B,
Evandro Menezes6e137cb2018-08-06 19:40:17 +00001144 bool isPrecise = false) {
1145 return optimizeDoubleFP(CI, B, true, isPrecise);
Chris Bienemanad070d02014-09-17 20:55:46 +00001146}
1147
Hal Finkel2ff24732017-12-16 01:26:25 +00001148// cabs(z) -> sqrt((creal(z)*creal(z)) + (cimag(z)*cimag(z)))
1149Value *LibCallSimplifier::optimizeCAbs(CallInst *CI, IRBuilder<> &B) {
1150 if (!CI->isFast())
1151 return nullptr;
1152
1153 // Propagate fast-math flags from the existing call to new instructions.
1154 IRBuilder<>::FastMathFlagGuard Guard(B);
1155 B.setFastMathFlags(CI->getFastMathFlags());
1156
1157 Value *Real, *Imag;
1158 if (CI->getNumArgOperands() == 1) {
1159 Value *Op = CI->getArgOperand(0);
1160 assert(Op->getType()->isArrayTy() && "Unexpected signature for cabs!");
1161 Real = B.CreateExtractValue(Op, 0, "real");
1162 Imag = B.CreateExtractValue(Op, 1, "imag");
1163 } else {
1164 assert(CI->getNumArgOperands() == 2 && "Unexpected signature for cabs!");
1165 Real = CI->getArgOperand(0);
1166 Imag = CI->getArgOperand(1);
1167 }
1168
1169 Value *RealReal = B.CreateFMul(Real, Real);
1170 Value *ImagImag = B.CreateFMul(Imag, Imag);
1171
1172 Function *FSqrt = Intrinsic::getDeclaration(CI->getModule(), Intrinsic::sqrt,
1173 CI->getType());
1174 return B.CreateCall(FSqrt, B.CreateFAdd(RealReal, ImagImag), "cabs");
1175}
1176
Sanjay Patele45a83d2018-08-13 19:24:41 +00001177static Value *optimizeTrigReflections(CallInst *Call, LibFunc Func,
1178 IRBuilder<> &B) {
Sanjay Patel15bff182018-08-13 21:49:19 +00001179 if (!isa<FPMathOperator>(Call))
1180 return nullptr;
Clement Courbet8e16d732019-03-08 09:07:45 +00001181
Sanjay Patel15bff182018-08-13 21:49:19 +00001182 IRBuilder<>::FastMathFlagGuard Guard(B);
1183 B.setFastMathFlags(Call->getFastMathFlags());
Clement Courbet8e16d732019-03-08 09:07:45 +00001184
Sanjay Patele45a83d2018-08-13 19:24:41 +00001185 // TODO: Can this be shared to also handle LLVM intrinsics?
Sanjay Patelce4ddbe2018-08-13 17:40:49 +00001186 Value *X;
Sanjay Patele45a83d2018-08-13 19:24:41 +00001187 switch (Func) {
1188 case LibFunc_sin:
1189 case LibFunc_sinf:
1190 case LibFunc_sinl:
Sanjay Patel8ba631d2018-08-16 22:46:20 +00001191 case LibFunc_tan:
1192 case LibFunc_tanf:
1193 case LibFunc_tanl:
Sanjay Patele45a83d2018-08-13 19:24:41 +00001194 // sin(-X) --> -sin(X)
Sanjay Patel8ba631d2018-08-16 22:46:20 +00001195 // tan(-X) --> -tan(X)
Sanjay Patele45a83d2018-08-13 19:24:41 +00001196 if (match(Call->getArgOperand(0), m_OneUse(m_FNeg(m_Value(X)))))
Sanjay Patel8ba631d2018-08-16 22:46:20 +00001197 return B.CreateFNeg(B.CreateCall(Call->getCalledFunction(), X));
Sanjay Patele45a83d2018-08-13 19:24:41 +00001198 break;
1199 case LibFunc_cos:
1200 case LibFunc_cosf:
1201 case LibFunc_cosl:
1202 // cos(-X) --> cos(X)
1203 if (match(Call->getArgOperand(0), m_FNeg(m_Value(X))))
1204 return B.CreateCall(Call->getCalledFunction(), X, "cos");
1205 break;
1206 default:
1207 break;
1208 }
Sanjay Patelce4ddbe2018-08-13 17:40:49 +00001209 return nullptr;
Chris Bienemanad070d02014-09-17 20:55:46 +00001210}
Bob Wilsond8d92d92013-11-03 06:48:38 +00001211
Weiming Zhao82130722015-12-04 22:00:47 +00001212static Value *getPow(Value *InnerChain[33], unsigned Exp, IRBuilder<> &B) {
1213 // Multiplications calculated using Addition Chains.
1214 // Refer: http://wwwhomes.uni-bielefeld.de/achim/addition_chain.html
1215
1216 assert(Exp != 0 && "Incorrect exponent 0 not handled");
1217
1218 if (InnerChain[Exp])
1219 return InnerChain[Exp];
1220
1221 static const unsigned AddChain[33][2] = {
1222 {0, 0}, // Unused.
1223 {0, 0}, // Unused (base case = pow1).
1224 {1, 1}, // Unused (pre-computed).
1225 {1, 2}, {2, 2}, {2, 3}, {3, 3}, {2, 5}, {4, 4},
1226 {1, 8}, {5, 5}, {1, 10}, {6, 6}, {4, 9}, {7, 7},
1227 {3, 12}, {8, 8}, {8, 9}, {2, 16}, {1, 18}, {10, 10},
1228 {6, 15}, {11, 11}, {3, 20}, {12, 12}, {8, 17}, {13, 13},
1229 {3, 24}, {14, 14}, {4, 25}, {15, 15}, {3, 28}, {16, 16},
1230 };
1231
1232 InnerChain[Exp] = B.CreateFMul(getPow(InnerChain, AddChain[Exp][0], B),
1233 getPow(InnerChain, AddChain[Exp][1], B));
1234 return InnerChain[Exp];
1235}
1236
Evandro Menezes4b390102018-08-17 17:59:53 +00001237/// Use exp{,2}(x * y) for pow(exp{,2}(x), y);
David Bolvansky0735cc12019-07-10 14:43:27 +00001238/// exp2(n * x) for pow(2.0 ** n, x); exp10(x) for pow(10.0, x);
Evandro Menezesb2169262019-07-12 00:33:49 +00001239/// exp2(log2(n) * x) for pow(n, x).
Evandro Menezes4b390102018-08-17 17:59:53 +00001240Value *LibCallSimplifier::replacePowWithExp(CallInst *Pow, IRBuilder<> &B) {
1241 Value *Base = Pow->getArgOperand(0), *Expo = Pow->getArgOperand(1);
1242 AttributeList Attrs = Pow->getCalledFunction()->getAttributes();
1243 Module *Mod = Pow->getModule();
1244 Type *Ty = Pow->getType();
Evandro Menezes2123ea72018-08-30 19:04:51 +00001245 bool Ignored;
Evandro Menezes4b390102018-08-17 17:59:53 +00001246
1247 // Evaluate special cases related to a nested function as the base.
1248
1249 // pow(exp(x), y) -> exp(x * y)
1250 // pow(exp2(x), y) -> exp2(x * y)
Evandro Menezes253991c2018-08-27 22:11:15 +00001251 // If exp{,2}() is used only once, it is better to fold two transcendental
1252 // math functions into one. If used again, exp{,2}() would still have to be
1253 // called with the original argument, then keep both original transcendental
1254 // functions. However, this transformation is only safe with fully relaxed
1255 // math semantics, since, besides rounding differences, it changes overflow
1256 // and underflow behavior quite dramatically. For example:
Evandro Menezes4b390102018-08-17 17:59:53 +00001257 // pow(exp(1000), 0.001) = pow(inf, 0.001) = inf
1258 // Whereas:
1259 // exp(1000 * 0.001) = exp(1)
1260 // TODO: Loosen the requirement for fully relaxed math semantics.
1261 // TODO: Handle exp10() when more targets have it available.
1262 CallInst *BaseFn = dyn_cast<CallInst>(Base);
Evandro Menezes253991c2018-08-27 22:11:15 +00001263 if (BaseFn && BaseFn->hasOneUse() && BaseFn->isFast() && Pow->isFast()) {
Evandro Menezes4b390102018-08-17 17:59:53 +00001264 LibFunc LibFn;
Evandro Menezes253991c2018-08-27 22:11:15 +00001265
Evandro Menezes4b390102018-08-17 17:59:53 +00001266 Function *CalleeFn = BaseFn->getCalledFunction();
Evandro Menezes22e0bdf2018-08-29 17:59:48 +00001267 if (CalleeFn &&
1268 TLI->getLibFunc(CalleeFn->getName(), LibFn) && TLI->has(LibFn)) {
1269 StringRef ExpName;
1270 Intrinsic::ID ID;
Evandro Menezes253991c2018-08-27 22:11:15 +00001271 Value *ExpFn;
Mikael Holmene3605d02018-10-18 06:27:53 +00001272 LibFunc LibFnFloat;
1273 LibFunc LibFnDouble;
1274 LibFunc LibFnLongDouble;
Evandro Menezes253991c2018-08-27 22:11:15 +00001275
Evandro Menezes22e0bdf2018-08-29 17:59:48 +00001276 switch (LibFn) {
1277 default:
1278 return nullptr;
1279 case LibFunc_expf: case LibFunc_exp: case LibFunc_expl:
Evandro Menezes164ea102018-10-19 20:57:45 +00001280 ExpName = TLI->getName(LibFunc_exp);
Evandro Menezes22e0bdf2018-08-29 17:59:48 +00001281 ID = Intrinsic::exp;
Mikael Holmene3605d02018-10-18 06:27:53 +00001282 LibFnFloat = LibFunc_expf;
1283 LibFnDouble = LibFunc_exp;
1284 LibFnLongDouble = LibFunc_expl;
Evandro Menezes22e0bdf2018-08-29 17:59:48 +00001285 break;
1286 case LibFunc_exp2f: case LibFunc_exp2: case LibFunc_exp2l:
Evandro Menezes164ea102018-10-19 20:57:45 +00001287 ExpName = TLI->getName(LibFunc_exp2);
Evandro Menezes22e0bdf2018-08-29 17:59:48 +00001288 ID = Intrinsic::exp2;
Mikael Holmene3605d02018-10-18 06:27:53 +00001289 LibFnFloat = LibFunc_exp2f;
1290 LibFnDouble = LibFunc_exp2;
1291 LibFnLongDouble = LibFunc_exp2l;
Evandro Menezes22e0bdf2018-08-29 17:59:48 +00001292 break;
1293 }
1294
Evandro Menezes253991c2018-08-27 22:11:15 +00001295 // Create new exp{,2}() with the product as its argument.
Evandro Menezes4b390102018-08-17 17:59:53 +00001296 Value *FMul = B.CreateFMul(BaseFn->getArgOperand(0), Expo, "mul");
Evandro Menezes22e0bdf2018-08-29 17:59:48 +00001297 ExpFn = BaseFn->doesNotAccessMemory()
1298 ? B.CreateCall(Intrinsic::getDeclaration(Mod, ID, Ty),
1299 FMul, ExpName)
Mikael Holmene3605d02018-10-18 06:27:53 +00001300 : emitUnaryFloatFnCall(FMul, TLI, LibFnDouble, LibFnFloat,
1301 LibFnLongDouble, B,
1302 BaseFn->getAttributes());
Evandro Menezes253991c2018-08-27 22:11:15 +00001303
1304 // Since the new exp{,2}() is different from the original one, dead code
1305 // elimination cannot be trusted to remove it, since it may have side
1306 // effects (e.g., errno). When the only consumer for the original
1307 // exp{,2}() is pow(), then it has to be explicitly erased.
1308 BaseFn->replaceAllUsesWith(ExpFn);
Amara Emerson54f60252018-10-11 14:51:11 +00001309 eraseFromParent(BaseFn);
Evandro Menezes253991c2018-08-27 22:11:15 +00001310
1311 return ExpFn;
Evandro Menezes4b390102018-08-17 17:59:53 +00001312 }
1313 }
1314
1315 // Evaluate special cases related to a constant base.
1316
Evandro Menezes2123ea72018-08-30 19:04:51 +00001317 const APFloat *BaseF;
1318 if (!match(Pow->getArgOperand(0), m_APFloat(BaseF)))
1319 return nullptr;
1320
1321 // pow(2.0 ** n, x) -> exp2(n * x)
Evandro Menezesc6c00cd2019-08-09 16:04:18 +00001322 if (hasFloatFn(TLI, Ty, LibFunc_exp2, LibFunc_exp2f, LibFunc_exp2l)) {
Evandro Menezes2123ea72018-08-30 19:04:51 +00001323 APFloat BaseR = APFloat(1.0);
1324 BaseR.convert(BaseF->getSemantics(), APFloat::rmTowardZero, &Ignored);
1325 BaseR = BaseR / *BaseF;
David Bolvanskycb1a5a72019-07-02 15:58:45 +00001326 bool IsInteger = BaseF->isInteger(), IsReciprocal = BaseR.isInteger();
Evandro Menezes2123ea72018-08-30 19:04:51 +00001327 const APFloat *NF = IsReciprocal ? &BaseR : BaseF;
1328 APSInt NI(64, false);
1329 if ((IsInteger || IsReciprocal) &&
David Bolvanskycb1a5a72019-07-02 15:58:45 +00001330 NF->convertToInteger(NI, APFloat::rmTowardZero, &Ignored) ==
1331 APFloat::opOK &&
Evandro Menezes2123ea72018-08-30 19:04:51 +00001332 NI > 1 && NI.isPowerOf2()) {
1333 double N = NI.logBase2() * (IsReciprocal ? -1.0 : 1.0);
1334 Value *FMul = B.CreateFMul(Expo, ConstantFP::get(Ty, N), "mul");
1335 if (Pow->doesNotAccessMemory())
1336 return B.CreateCall(Intrinsic::getDeclaration(Mod, Intrinsic::exp2, Ty),
1337 FMul, "exp2");
1338 else
Mikael Holmene3605d02018-10-18 06:27:53 +00001339 return emitUnaryFloatFnCall(FMul, TLI, LibFunc_exp2, LibFunc_exp2f,
1340 LibFunc_exp2l, B, Attrs);
Evandro Menezes2123ea72018-08-30 19:04:51 +00001341 }
Evandro Menezes4b390102018-08-17 17:59:53 +00001342 }
1343
1344 // pow(10.0, x) -> exp10(x)
1345 // TODO: There is no exp10() intrinsic yet, but some day there shall be one.
1346 if (match(Base, m_SpecificFP(10.0)) &&
Evandro Menezesc6c00cd2019-08-09 16:04:18 +00001347 hasFloatFn(TLI, Ty, LibFunc_exp10, LibFunc_exp10f, LibFunc_exp10l))
Mikael Holmene3605d02018-10-18 06:27:53 +00001348 return emitUnaryFloatFnCall(Expo, TLI, LibFunc_exp10, LibFunc_exp10f,
1349 LibFunc_exp10l, B, Attrs);
Evandro Menezes4b390102018-08-17 17:59:53 +00001350
Evandro Menezesb2169262019-07-12 00:33:49 +00001351 // pow(n, x) -> exp2(log2(n) * x)
David Bolvansky0735cc12019-07-10 14:43:27 +00001352 if (Pow->hasOneUse() && Pow->hasApproxFunc() && Pow->hasNoNaNs() &&
1353 Pow->hasNoInfs() && BaseF->isNormal() && !BaseF->isNegative()) {
1354 Value *Log = nullptr;
1355 if (Ty->isFloatTy())
1356 Log = ConstantFP::get(Ty, std::log2(BaseF->convertToFloat()));
1357 else if (Ty->isDoubleTy())
1358 Log = ConstantFP::get(Ty, std::log2(BaseF->convertToDouble()));
1359
1360 if (Log) {
1361 Value *FMul = B.CreateFMul(Log, Expo, "mul");
Evandro Menezesc6c00cd2019-08-09 16:04:18 +00001362 if (Pow->doesNotAccessMemory())
David Bolvansky0735cc12019-07-10 14:43:27 +00001363 return B.CreateCall(Intrinsic::getDeclaration(Mod, Intrinsic::exp2, Ty),
1364 FMul, "exp2");
Evandro Menezesc6c00cd2019-08-09 16:04:18 +00001365 else if (hasFloatFn(TLI, Ty, LibFunc_exp2, LibFunc_exp2f, LibFunc_exp2l))
1366 return emitUnaryFloatFnCall(FMul, TLI, LibFunc_exp2, LibFunc_exp2f,
1367 LibFunc_exp2l, B, Attrs);
David Bolvansky0735cc12019-07-10 14:43:27 +00001368 }
1369 }
Evandro Menezesc6c00cd2019-08-09 16:04:18 +00001370
Evandro Menezes4b390102018-08-17 17:59:53 +00001371 return nullptr;
1372}
1373
Florian Hahncc9dc592018-09-03 17:37:39 +00001374static Value *getSqrtCall(Value *V, AttributeList Attrs, bool NoErrno,
1375 Module *M, IRBuilder<> &B,
1376 const TargetLibraryInfo *TLI) {
1377 // If errno is never set, then use the intrinsic for sqrt().
1378 if (NoErrno) {
1379 Function *SqrtFn =
1380 Intrinsic::getDeclaration(M, Intrinsic::sqrt, V->getType());
1381 return B.CreateCall(SqrtFn, V, "sqrt");
1382 }
1383
1384 // Otherwise, use the libcall for sqrt().
Evandro Menezesc6c00cd2019-08-09 16:04:18 +00001385 if (hasFloatFn(TLI, V->getType(), LibFunc_sqrt, LibFunc_sqrtf, LibFunc_sqrtl))
Florian Hahncc9dc592018-09-03 17:37:39 +00001386 // TODO: We also should check that the target can in fact lower the sqrt()
1387 // libcall. We currently have no way to ask this question, so we ask if
1388 // the target has a sqrt() libcall, which is not exactly the same.
Mikael Holmene3605d02018-10-18 06:27:53 +00001389 return emitUnaryFloatFnCall(V, TLI, LibFunc_sqrt, LibFunc_sqrtf,
1390 LibFunc_sqrtl, B, Attrs);
Florian Hahncc9dc592018-09-03 17:37:39 +00001391
1392 return nullptr;
1393}
1394
Sanjay Patelfbd3e662017-11-19 16:13:14 +00001395/// Use square root in place of pow(x, +/-0.5).
1396Value *LibCallSimplifier::replacePowWithSqrt(CallInst *Pow, IRBuilder<> &B) {
Evandro Menezesa7d48282018-07-30 16:20:04 +00001397 Value *Sqrt, *Base = Pow->getArgOperand(0), *Expo = Pow->getArgOperand(1);
Evandro Menezesc05c7e12018-08-16 15:58:08 +00001398 AttributeList Attrs = Pow->getCalledFunction()->getAttributes();
1399 Module *Mod = Pow->getModule();
Sanjay Patelfbd3e662017-11-19 16:13:14 +00001400 Type *Ty = Pow->getType();
Sanjay Patelfbd3e662017-11-19 16:13:14 +00001401
Evandro Menezesa7d48282018-07-30 16:20:04 +00001402 const APFloat *ExpoF;
1403 if (!match(Expo, m_APFloat(ExpoF)) ||
1404 (!ExpoF->isExactlyValue(0.5) && !ExpoF->isExactlyValue(-0.5)))
1405 return nullptr;
1406
Florian Hahncc9dc592018-09-03 17:37:39 +00001407 Sqrt = getSqrtCall(Base, Attrs, Pow->doesNotAccessMemory(), Mod, B, TLI);
1408 if (!Sqrt)
Evandro Menezesa7d48282018-07-30 16:20:04 +00001409 return nullptr;
1410
Evandro Menezesc05c7e12018-08-16 15:58:08 +00001411 // Handle signed zero base by expanding to fabs(sqrt(x)).
1412 if (!Pow->hasNoSignedZeros()) {
1413 Function *FAbsFn = Intrinsic::getDeclaration(Mod, Intrinsic::fabs, Ty);
1414 Sqrt = B.CreateCall(FAbsFn, Sqrt, "abs");
1415 }
1416
1417 // Handle non finite base by expanding to
1418 // (x == -infinity ? +infinity : sqrt(x)).
1419 if (!Pow->hasNoInfs()) {
1420 Value *PosInf = ConstantFP::getInfinity(Ty),
1421 *NegInf = ConstantFP::getInfinity(Ty, true);
1422 Value *FCmp = B.CreateFCmpOEQ(Base, NegInf, "isinf");
1423 Sqrt = B.CreateSelect(FCmp, PosInf, Sqrt);
1424 }
1425
Evandro Menezes61e4e402018-07-31 22:11:02 +00001426 // If the exponent is negative, then get the reciprocal.
Evandro Menezesa7d48282018-07-30 16:20:04 +00001427 if (ExpoF->isNegative())
1428 Sqrt = B.CreateFDiv(ConstantFP::get(Ty, 1.0), Sqrt, "reciprocal");
Sanjay Patelfbd3e662017-11-19 16:13:14 +00001429
1430 return Sqrt;
1431}
1432
David Bolvanskycb1a5a72019-07-02 15:58:45 +00001433static Value *createPowWithIntegerExponent(Value *Base, Value *Expo, Module *M,
1434 IRBuilder<> &B) {
1435 Value *Args[] = {Base, Expo};
1436 Function *F = Intrinsic::getDeclaration(M, Intrinsic::powi, Base->getType());
1437 return B.CreateCall(F, Args);
1438}
1439
Evandro Menezesa7d48282018-07-30 16:20:04 +00001440Value *LibCallSimplifier::optimizePow(CallInst *Pow, IRBuilder<> &B) {
David Bolvanskycb1a5a72019-07-02 15:58:45 +00001441 Value *Base = Pow->getArgOperand(0);
1442 Value *Expo = Pow->getArgOperand(1);
Evandro Menezesa7d48282018-07-30 16:20:04 +00001443 Function *Callee = Pow->getCalledFunction();
Davide Italianoa3458772015-11-05 19:18:23 +00001444 StringRef Name = Callee->getName();
Evandro Menezesa7d48282018-07-30 16:20:04 +00001445 Type *Ty = Pow->getType();
David Bolvanskycb1a5a72019-07-02 15:58:45 +00001446 Module *M = Pow->getModule();
Evandro Menezesa7d48282018-07-30 16:20:04 +00001447 Value *Shrunk = nullptr;
David Bolvanskycb1a5a72019-07-02 15:58:45 +00001448 bool AllowApprox = Pow->hasApproxFunc();
Evandro Menezesa7d48282018-07-30 16:20:04 +00001449 bool Ignored;
Bob Wilsond8d92d92013-11-03 06:48:38 +00001450
Evandro Menezes5ecd6c12018-08-13 16:12:37 +00001451 // Bail out if simplifying libcalls to pow() is disabled.
Evandro Menezesc6c00cd2019-08-09 16:04:18 +00001452 if (!hasFloatFn(TLI, Ty, LibFunc_pow, LibFunc_powf, LibFunc_powl))
Evandro Menezes5ecd6c12018-08-13 16:12:37 +00001453 return nullptr;
1454
Evandro Menezes61e4e402018-07-31 22:11:02 +00001455 // Propagate the math semantics from the call to any created instructions.
Evandro Menezesa7d48282018-07-30 16:20:04 +00001456 IRBuilder<>::FastMathFlagGuard Guard(B);
1457 B.setFastMathFlags(Pow->getFastMathFlags());
1458
Evandro Menezes6e137cb2018-08-06 19:40:17 +00001459 // Shrink pow() to powf() if the arguments are single precision,
1460 // unless the result is expected to be double precision.
David Bolvanskycb1a5a72019-07-02 15:58:45 +00001461 if (UnsafeFPShrink && Name == TLI->getName(LibFunc_pow) &&
1462 hasFloatVersion(Name))
Evandro Menezes6e137cb2018-08-06 19:40:17 +00001463 Shrunk = optimizeBinaryDoubleFP(Pow, B, true);
1464
Evandro Menezesa7d48282018-07-30 16:20:04 +00001465 // Evaluate special cases related to the base.
Davide Italiano27da1312016-08-07 20:27:03 +00001466
1467 // pow(1.0, x) -> 1.0
Evandro Menezes84e74362018-08-02 15:43:57 +00001468 if (match(Base, m_FPOne()))
Evandro Menezesa7d48282018-07-30 16:20:04 +00001469 return Base;
1470
David Bolvanskye23be092019-07-11 10:55:04 +00001471 if (Value *Exp = replacePowWithExp(Pow, B))
1472 return Exp;
1473
Evandro Menezesa7d48282018-07-30 16:20:04 +00001474 // Evaluate special cases related to the exponent.
1475
Evandro Menezesa7d48282018-07-30 16:20:04 +00001476 // pow(x, -1.0) -> 1.0 / x
Evandro Menezes5ecd6c12018-08-13 16:12:37 +00001477 if (match(Expo, m_SpecificFP(-1.0)))
Evandro Menezesa7d48282018-07-30 16:20:04 +00001478 return B.CreateFDiv(ConstantFP::get(Ty, 1.0), Base, "reciprocal");
1479
1480 // pow(x, 0.0) -> 1.0
Evandro Menezes5ecd6c12018-08-13 16:12:37 +00001481 if (match(Expo, m_SpecificFP(0.0)))
David Bolvanskycb1a5a72019-07-02 15:58:45 +00001482 return ConstantFP::get(Ty, 1.0);
Evandro Menezesa7d48282018-07-30 16:20:04 +00001483
1484 // pow(x, 1.0) -> x
Evandro Menezes5ecd6c12018-08-13 16:12:37 +00001485 if (match(Expo, m_FPOne()))
Evandro Menezesa7d48282018-07-30 16:20:04 +00001486 return Base;
1487
1488 // pow(x, 2.0) -> x * x
Evandro Menezes5ecd6c12018-08-13 16:12:37 +00001489 if (match(Expo, m_SpecificFP(2.0)))
Evandro Menezesa7d48282018-07-30 16:20:04 +00001490 return B.CreateFMul(Base, Base, "square");
Chris Bienemanad070d02014-09-17 20:55:46 +00001491
Evandro Menezes5ecd6c12018-08-13 16:12:37 +00001492 if (Value *Sqrt = replacePowWithSqrt(Pow, B))
1493 return Sqrt;
1494
Evandro Menezes5ecd6c12018-08-13 16:12:37 +00001495 // pow(x, n) -> x * x * x * ...
1496 const APFloat *ExpoF;
Evandro Menezesb2169262019-07-12 00:33:49 +00001497 if (AllowApprox && match(Expo, m_APFloat(ExpoF))) {
Evandro Menezes5ecd6c12018-08-13 16:12:37 +00001498 // We limit to a max of 7 multiplications, thus the maximum exponent is 32.
Florian Hahncc9dc592018-09-03 17:37:39 +00001499 // If the exponent is an integer+0.5 we generate a call to sqrt and an
1500 // additional fmul.
1501 // TODO: This whole transformation should be backend specific (e.g. some
1502 // backends might prefer libcalls or the limit for the exponent might
1503 // be different) and it should also consider optimizing for size.
Evandro Menezes5ecd6c12018-08-13 16:12:37 +00001504 APFloat LimF(ExpoF->getSemantics(), 33.0),
1505 ExpoA(abs(*ExpoF));
Florian Hahncc9dc592018-09-03 17:37:39 +00001506 if (ExpoA.compare(LimF) == APFloat::cmpLessThan) {
1507 // This transformation applies to integer or integer+0.5 exponents only.
1508 // For integer+0.5, we create a sqrt(Base) call.
1509 Value *Sqrt = nullptr;
1510 if (!ExpoA.isInteger()) {
1511 APFloat Expo2 = ExpoA;
1512 // To check if ExpoA is an integer + 0.5, we add it to itself. If there
1513 // is no floating point exception and the result is an integer, then
1514 // ExpoA == integer + 0.5
1515 if (Expo2.add(ExpoA, APFloat::rmNearestTiesToEven) != APFloat::opOK)
1516 return nullptr;
1517
1518 if (!Expo2.isInteger())
1519 return nullptr;
1520
David Bolvanskycb1a5a72019-07-02 15:58:45 +00001521 Sqrt = getSqrtCall(Base, Pow->getCalledFunction()->getAttributes(),
1522 Pow->doesNotAccessMemory(), M, B, TLI);
Florian Hahncc9dc592018-09-03 17:37:39 +00001523 }
1524
Evandro Menezes5ecd6c12018-08-13 16:12:37 +00001525 // We will memoize intermediate products of the Addition Chain.
1526 Value *InnerChain[33] = {nullptr};
1527 InnerChain[1] = Base;
1528 InnerChain[2] = B.CreateFMul(Base, Base, "square");
Weiming Zhao82130722015-12-04 22:00:47 +00001529
Evandro Menezes5ecd6c12018-08-13 16:12:37 +00001530 // We cannot readily convert a non-double type (like float) to a double.
1531 // So we first convert it to something which could be converted to double.
1532 ExpoA.convert(APFloat::IEEEdouble(), APFloat::rmTowardZero, &Ignored);
1533 Value *FMul = getPow(InnerChain, ExpoA.convertToDouble(), B);
Weiming Zhao82130722015-12-04 22:00:47 +00001534
Florian Hahncc9dc592018-09-03 17:37:39 +00001535 // Expand pow(x, y+0.5) to pow(x, y) * sqrt(x).
1536 if (Sqrt)
1537 FMul = B.CreateFMul(FMul, Sqrt);
1538
Evandro Menezes5ecd6c12018-08-13 16:12:37 +00001539 // If the exponent is negative, then get the reciprocal.
1540 if (ExpoF->isNegative())
1541 FMul = B.CreateFDiv(ConstantFP::get(Ty, 1.0), FMul, "reciprocal");
Evandro Menezes61e4e402018-07-31 22:11:02 +00001542
Evandro Menezes5ecd6c12018-08-13 16:12:37 +00001543 return FMul;
1544 }
David Bolvanskycb1a5a72019-07-02 15:58:45 +00001545
1546 APSInt IntExpo(32, /*isUnsigned=*/false);
Evandro Menezesb2169262019-07-12 00:33:49 +00001547 // powf(x, n) -> powi(x, n) if n is a constant signed integer value
David Bolvansky10ee3ac2019-07-02 21:16:34 +00001548 if (ExpoF->isInteger() &&
1549 ExpoF->convertToInteger(IntExpo, APFloat::rmTowardZero, &Ignored) ==
1550 APFloat::opOK) {
David Bolvanskycb1a5a72019-07-02 15:58:45 +00001551 return createPowWithIntegerExponent(
1552 Base, ConstantInt::get(B.getInt32Ty(), IntExpo), M, B);
1553 }
Weiming Zhao82130722015-12-04 22:00:47 +00001554 }
1555
Evandro Menezesb2169262019-07-12 00:33:49 +00001556 // powf(x, itofp(y)) -> powi(x, y)
1557 if (AllowApprox && (isa<SIToFPInst>(Expo) || isa<UIToFPInst>(Expo))) {
1558 Value *IntExpo = cast<Instruction>(Expo)->getOperand(0);
1559 Value *NewExpo = nullptr;
1560 unsigned BitWidth = IntExpo->getType()->getPrimitiveSizeInBits();
1561 if (isa<SIToFPInst>(Expo) && BitWidth == 32)
1562 NewExpo = IntExpo;
1563 else if (BitWidth < 32)
1564 NewExpo = isa<SIToFPInst>(Expo) ? B.CreateSExt(IntExpo, B.getInt32Ty())
1565 : B.CreateZExt(IntExpo, B.getInt32Ty());
1566 if (NewExpo)
1567 return createPowWithIntegerExponent(Base, NewExpo, M, B);
1568 }
1569
Evandro Menezes6e137cb2018-08-06 19:40:17 +00001570 return Shrunk;
Chris Bienemanad070d02014-09-17 20:55:46 +00001571}
Bob Wilsond8d92d92013-11-03 06:48:38 +00001572
Chris Bienemanad070d02014-09-17 20:55:46 +00001573Value *LibCallSimplifier::optimizeExp2(CallInst *CI, IRBuilder<> &B) {
1574 Function *Callee = CI->getCalledFunction();
Davide Italianoa3458772015-11-05 19:18:23 +00001575 StringRef Name = Callee->getName();
Evandro Menezes59fbe512019-08-09 17:22:56 +00001576 Value *Ret = nullptr;
1577 if (UnsafeFPShrink && Name == TLI->getName(LibFunc_exp2) &&
1578 hasFloatVersion(Name))
Chris Bienemanad070d02014-09-17 20:55:46 +00001579 Ret = optimizeUnaryDoubleFP(CI, B, true);
Bob Wilsond8d92d92013-11-03 06:48:38 +00001580
Evandro Menezes59fbe512019-08-09 17:22:56 +00001581 Type *Ty = CI->getType();
Chris Bienemanad070d02014-09-17 20:55:46 +00001582 Value *Op = CI->getArgOperand(0);
Evandro Menezes59fbe512019-08-09 17:22:56 +00001583
Chris Bienemanad070d02014-09-17 20:55:46 +00001584 // Turn exp2(sitofp(x)) -> ldexp(1.0, sext(x)) if sizeof(x) <= 32
1585 // Turn exp2(uitofp(x)) -> ldexp(1.0, zext(x)) if sizeof(x) < 32
Evandro Menezes59fbe512019-08-09 17:22:56 +00001586 if ((isa<SIToFPInst>(Op) || isa<UIToFPInst>(Op)) &&
1587 hasFloatFn(TLI, Ty, LibFunc_ldexp, LibFunc_ldexpf, LibFunc_ldexpl)) {
1588 Instruction *OpC = cast<Instruction>(Op);
1589 Value *Exp = OpC->getOperand(0);
1590 unsigned BitWidth = Exp->getType()->getPrimitiveSizeInBits();
Chris Bienemanad070d02014-09-17 20:55:46 +00001591
Evandro Menezes59fbe512019-08-09 17:22:56 +00001592 if (BitWidth < 32 ||
1593 (BitWidth == 32 && isa<SIToFPInst>(Op))) {
1594 Exp = isa<SIToFPInst>(Op) ? B.CreateSExt(Exp, B.getInt32Ty())
1595 : B.CreateZExt(Exp, B.getInt32Ty());
Chris Bienemanad070d02014-09-17 20:55:46 +00001596
Evandro Menezes59fbe512019-08-09 17:22:56 +00001597 return emitBinaryFloatFnCall(ConstantFP::get(Ty, 1.0), Exp, TLI,
1598 LibFunc_ldexp, LibFunc_ldexpf, LibFunc_ldexpl,
1599 B, CI->getCalledFunction()->getAttributes());
Chris Bienemanad070d02014-09-17 20:55:46 +00001600 }
1601 }
1602 return Ret;
1603}
1604
Sanjay Patel57fd1dc2015-08-16 20:18:19 +00001605Value *LibCallSimplifier::optimizeFMinFMax(CallInst *CI, IRBuilder<> &B) {
1606 // If we can shrink the call to a float function rather than a double
1607 // function, do that first.
Sanjay Patel77dc1e82019-06-29 14:28:54 +00001608 Function *Callee = CI->getCalledFunction();
Davide Italianoa3458772015-11-05 19:18:23 +00001609 StringRef Name = Callee->getName();
Sanjay Patelc7ddb7f2016-01-06 00:32:15 +00001610 if ((Name == "fmin" || Name == "fmax") && hasFloatVersion(Name))
1611 if (Value *Ret = optimizeBinaryDoubleFP(CI, B))
Sanjay Patel57fd1dc2015-08-16 20:18:19 +00001612 return Ret;
Sanjay Patel57fd1dc2015-08-16 20:18:19 +00001613
Sanjay Patel77dc1e82019-06-29 14:28:54 +00001614 // The LLVM intrinsics minnum/maxnum correspond to fmin/fmax. Canonicalize to
1615 // the intrinsics for improved optimization (for example, vectorization).
1616 // No-signed-zeros is implied by the definitions of fmax/fmin themselves.
1617 // From the C standard draft WG14/N1256:
1618 // "Ideally, fmax would be sensitive to the sign of zero, for example
1619 // fmax(-0.0, +0.0) would return +0; however, implementation in software
1620 // might be impractical."
Benjamin Kramerbb70d752015-08-16 21:16:37 +00001621 IRBuilder<>::FastMathFlagGuard Guard(B);
Sanjay Patel77dc1e82019-06-29 14:28:54 +00001622 FastMathFlags FMF = CI->getFastMathFlags();
1623 FMF.setNoSignedZeros();
Sanjay Patela2528152016-01-12 18:03:37 +00001624 B.setFastMathFlags(FMF);
Sanjay Patel57fd1dc2015-08-16 20:18:19 +00001625
Sanjay Patel77dc1e82019-06-29 14:28:54 +00001626 Intrinsic::ID IID = Callee->getName().startswith("fmin") ? Intrinsic::minnum
1627 : Intrinsic::maxnum;
1628 Function *F = Intrinsic::getDeclaration(CI->getModule(), IID, CI->getType());
1629 return B.CreateCall(F, { CI->getArgOperand(0), CI->getArgOperand(1) });
Sanjay Patel57fd1dc2015-08-16 20:18:19 +00001630}
1631
Davide Italianob8b71332015-11-29 20:58:04 +00001632Value *LibCallSimplifier::optimizeLog(CallInst *CI, IRBuilder<> &B) {
1633 Function *Callee = CI->getCalledFunction();
1634 Value *Ret = nullptr;
1635 StringRef Name = Callee->getName();
1636 if (UnsafeFPShrink && hasFloatVersion(Name))
1637 Ret = optimizeUnaryDoubleFP(CI, B, true);
Davide Italianob8b71332015-11-29 20:58:04 +00001638
Sanjay Patel629c4112017-11-06 16:27:15 +00001639 if (!CI->isFast())
Davide Italianob8b71332015-11-29 20:58:04 +00001640 return Ret;
1641 Value *Op1 = CI->getArgOperand(0);
1642 auto *OpC = dyn_cast<CallInst>(Op1);
Sanjay Patele896ede2016-01-11 23:31:48 +00001643
Sanjay Patel629c4112017-11-06 16:27:15 +00001644 // The earlier call must also be 'fast' in order to do these transforms.
1645 if (!OpC || !OpC->isFast())
Davide Italianob8b71332015-11-29 20:58:04 +00001646 return Ret;
1647
1648 // log(pow(x,y)) -> y*log(x)
1649 // This is only applicable to log, log2, log10.
1650 if (Name != "log" && Name != "log2" && Name != "log10")
1651 return Ret;
1652
1653 IRBuilder<>::FastMathFlagGuard Guard(B);
1654 FastMathFlags FMF;
Sanjay Patel629c4112017-11-06 16:27:15 +00001655 FMF.setFast();
Sanjay Patela2528152016-01-12 18:03:37 +00001656 B.setFastMathFlags(FMF);
Davide Italianob8b71332015-11-29 20:58:04 +00001657
David L. Jonesd21529f2017-01-23 23:16:46 +00001658 LibFunc Func;
Davide Italianob8b71332015-11-29 20:58:04 +00001659 Function *F = OpC->getCalledFunction();
Davide Italiano0b14f292015-11-29 21:58:56 +00001660 if (F && ((TLI->getLibFunc(F->getName(), Func) && TLI->has(Func) &&
David L. Jonesd21529f2017-01-23 23:16:46 +00001661 Func == LibFunc_pow) || F->getIntrinsicID() == Intrinsic::pow))
Davide Italianob8b71332015-11-29 20:58:04 +00001662 return B.CreateFMul(OpC->getArgOperand(1),
Sanjay Pateld3112a52016-01-19 19:46:10 +00001663 emitUnaryFloatFnCall(OpC->getOperand(0), Callee->getName(), B,
Davide Italianob8b71332015-11-29 20:58:04 +00001664 Callee->getAttributes()), "mul");
Davide Italiano1aeed6a2015-11-30 19:36:35 +00001665
1666 // log(exp2(y)) -> y*log(2)
1667 if (F && Name == "log" && TLI->getLibFunc(F->getName(), Func) &&
David L. Jonesd21529f2017-01-23 23:16:46 +00001668 TLI->has(Func) && Func == LibFunc_exp2)
Davide Italiano1aeed6a2015-11-30 19:36:35 +00001669 return B.CreateFMul(
1670 OpC->getArgOperand(0),
Sanjay Pateld3112a52016-01-19 19:46:10 +00001671 emitUnaryFloatFnCall(ConstantFP::get(CI->getType(), 2.0),
Davide Italiano1aeed6a2015-11-30 19:36:35 +00001672 Callee->getName(), B, Callee->getAttributes()),
1673 "logmul");
Davide Italianob8b71332015-11-29 20:58:04 +00001674 return Ret;
1675}
1676
Sanjay Patelc699a612014-10-16 18:48:17 +00001677Value *LibCallSimplifier::optimizeSqrt(CallInst *CI, IRBuilder<> &B) {
1678 Function *Callee = CI->getCalledFunction();
Sanjay Patelc699a612014-10-16 18:48:17 +00001679 Value *Ret = nullptr;
Justin Lebarcb9b41d2017-01-27 00:58:03 +00001680 // TODO: Once we have a way (other than checking for the existince of the
1681 // libcall) to tell whether our target can lower @llvm.sqrt, relax the
1682 // condition below.
David L. Jonesd21529f2017-01-23 23:16:46 +00001683 if (TLI->has(LibFunc_sqrtf) && (Callee->getName() == "sqrt" ||
Justin Lebarcb9b41d2017-01-27 00:58:03 +00001684 Callee->getIntrinsicID() == Intrinsic::sqrt))
Sanjay Patelc699a612014-10-16 18:48:17 +00001685 Ret = optimizeUnaryDoubleFP(CI, B, true);
Sanjay Patel683f2972016-01-11 22:34:19 +00001686
Sanjay Patel629c4112017-11-06 16:27:15 +00001687 if (!CI->isFast())
Davide Italianoa904e522015-10-29 02:58:44 +00001688 return Ret;
Sanjay Patelc699a612014-10-16 18:48:17 +00001689
Sanjay Patelc2d64612016-01-06 20:52:21 +00001690 Instruction *I = dyn_cast<Instruction>(CI->getArgOperand(0));
Sanjay Patel629c4112017-11-06 16:27:15 +00001691 if (!I || I->getOpcode() != Instruction::FMul || !I->isFast())
Sanjay Patelc2d64612016-01-06 20:52:21 +00001692 return Ret;
1693
1694 // We're looking for a repeated factor in a multiplication tree,
1695 // so we can do this fold: sqrt(x * x) -> fabs(x);
Sanjay Patel683f2972016-01-11 22:34:19 +00001696 // or this fold: sqrt((x * x) * y) -> fabs(x) * sqrt(y).
Sanjay Patelc2d64612016-01-06 20:52:21 +00001697 Value *Op0 = I->getOperand(0);
1698 Value *Op1 = I->getOperand(1);
1699 Value *RepeatOp = nullptr;
1700 Value *OtherOp = nullptr;
1701 if (Op0 == Op1) {
1702 // Simple match: the operands of the multiply are identical.
1703 RepeatOp = Op0;
1704 } else {
1705 // Look for a more complicated pattern: one of the operands is itself
1706 // a multiply, so search for a common factor in that multiply.
1707 // Note: We don't bother looking any deeper than this first level or for
1708 // variations of this pattern because instcombine's visitFMUL and/or the
1709 // reassociation pass should give us this form.
1710 Value *OtherMul0, *OtherMul1;
1711 if (match(Op0, m_FMul(m_Value(OtherMul0), m_Value(OtherMul1)))) {
1712 // Pattern: sqrt((x * y) * z)
Sanjay Patel629c4112017-11-06 16:27:15 +00001713 if (OtherMul0 == OtherMul1 && cast<Instruction>(Op0)->isFast()) {
Sanjay Patelc2d64612016-01-06 20:52:21 +00001714 // Matched: sqrt((x * x) * z)
1715 RepeatOp = OtherMul0;
1716 OtherOp = Op1;
Sanjay Patelc699a612014-10-16 18:48:17 +00001717 }
1718 }
1719 }
Sanjay Patelc2d64612016-01-06 20:52:21 +00001720 if (!RepeatOp)
1721 return Ret;
1722
1723 // Fast math flags for any created instructions should match the sqrt
1724 // and multiply.
Sanjay Patelc2d64612016-01-06 20:52:21 +00001725 IRBuilder<>::FastMathFlagGuard Guard(B);
Sanjay Patela2528152016-01-12 18:03:37 +00001726 B.setFastMathFlags(I->getFastMathFlags());
Sanjay Patel9f67dad2016-01-11 22:35:39 +00001727
Sanjay Patelc2d64612016-01-06 20:52:21 +00001728 // If we found a repeated factor, hoist it out of the square root and
1729 // replace it with the fabs of that factor.
1730 Module *M = Callee->getParent();
1731 Type *ArgType = I->getType();
James Y Knight7976eb52019-02-01 20:43:25 +00001732 Function *Fabs = Intrinsic::getDeclaration(M, Intrinsic::fabs, ArgType);
Sanjay Patelc2d64612016-01-06 20:52:21 +00001733 Value *FabsCall = B.CreateCall(Fabs, RepeatOp, "fabs");
1734 if (OtherOp) {
1735 // If we found a non-repeated factor, we still need to get its square
1736 // root. We then multiply that by the value that was simplified out
1737 // of the square root calculation.
James Y Knight7976eb52019-02-01 20:43:25 +00001738 Function *Sqrt = Intrinsic::getDeclaration(M, Intrinsic::sqrt, ArgType);
Sanjay Patelc2d64612016-01-06 20:52:21 +00001739 Value *SqrtCall = B.CreateCall(Sqrt, OtherOp, "sqrt");
1740 return B.CreateFMul(FabsCall, SqrtCall);
1741 }
1742 return FabsCall;
Sanjay Patelc699a612014-10-16 18:48:17 +00001743}
1744
Sanjay Patelcddcd722016-01-06 19:23:35 +00001745// TODO: Generalize to handle any trig function and its inverse.
Davide Italiano51507d22015-11-04 23:36:56 +00001746Value *LibCallSimplifier::optimizeTan(CallInst *CI, IRBuilder<> &B) {
1747 Function *Callee = CI->getCalledFunction();
1748 Value *Ret = nullptr;
Davide Italianoa3458772015-11-05 19:18:23 +00001749 StringRef Name = Callee->getName();
1750 if (UnsafeFPShrink && Name == "tan" && hasFloatVersion(Name))
Davide Italiano51507d22015-11-04 23:36:56 +00001751 Ret = optimizeUnaryDoubleFP(CI, B, true);
Davide Italiano51507d22015-11-04 23:36:56 +00001752
Davide Italiano51507d22015-11-04 23:36:56 +00001753 Value *Op1 = CI->getArgOperand(0);
1754 auto *OpC = dyn_cast<CallInst>(Op1);
1755 if (!OpC)
1756 return Ret;
1757
Sanjay Patel629c4112017-11-06 16:27:15 +00001758 // Both calls must be 'fast' in order to remove them.
1759 if (!CI->isFast() || !OpC->isFast())
Sanjay Patelcddcd722016-01-06 19:23:35 +00001760 return Ret;
1761
Davide Italiano51507d22015-11-04 23:36:56 +00001762 // tan(atan(x)) -> x
1763 // tanf(atanf(x)) -> x
1764 // tanl(atanl(x)) -> x
David L. Jonesd21529f2017-01-23 23:16:46 +00001765 LibFunc Func;
Davide Italiano51507d22015-11-04 23:36:56 +00001766 Function *F = OpC->getCalledFunction();
Benjamin Kramerfb419e72015-11-26 09:51:17 +00001767 if (F && TLI->getLibFunc(F->getName(), Func) && TLI->has(Func) &&
David L. Jonesd21529f2017-01-23 23:16:46 +00001768 ((Func == LibFunc_atan && Callee->getName() == "tan") ||
1769 (Func == LibFunc_atanf && Callee->getName() == "tanf") ||
1770 (Func == LibFunc_atanl && Callee->getName() == "tanl")))
Davide Italiano51507d22015-11-04 23:36:56 +00001771 Ret = OpC->getArgOperand(0);
1772 return Ret;
1773}
1774
Sanjay Patel57747212016-01-21 23:38:43 +00001775static bool isTrigLibCall(CallInst *CI) {
Sanjay Patel57747212016-01-21 23:38:43 +00001776 // We can only hope to do anything useful if we can ignore things like errno
1777 // and floating-point exceptions.
Ahmed Bougachad765a822016-04-27 19:04:35 +00001778 // We already checked the prototype.
1779 return CI->hasFnAttr(Attribute::NoUnwind) &&
1780 CI->hasFnAttr(Attribute::ReadNone);
Sanjay Patel57747212016-01-21 23:38:43 +00001781}
1782
Chris Bienemanad070d02014-09-17 20:55:46 +00001783static void insertSinCosCall(IRBuilder<> &B, Function *OrigCallee, Value *Arg,
1784 bool UseFloat, Value *&Sin, Value *&Cos,
Sanjay Patel57747212016-01-21 23:38:43 +00001785 Value *&SinCos) {
1786 Type *ArgTy = Arg->getType();
1787 Type *ResTy;
1788 StringRef Name;
1789
1790 Triple T(OrigCallee->getParent()->getTargetTriple());
1791 if (UseFloat) {
1792 Name = "__sincospif_stret";
1793
1794 assert(T.getArch() != Triple::x86 && "x86 messy and unsupported for now");
1795 // x86_64 can't use {float, float} since that would be returned in both
1796 // xmm0 and xmm1, which isn't what a real struct would do.
1797 ResTy = T.getArch() == Triple::x86_64
Serge Gueltone38003f2017-05-09 19:31:13 +00001798 ? static_cast<Type *>(VectorType::get(ArgTy, 2))
1799 : static_cast<Type *>(StructType::get(ArgTy, ArgTy));
Sanjay Patel57747212016-01-21 23:38:43 +00001800 } else {
1801 Name = "__sincospi_stret";
Serge Gueltone38003f2017-05-09 19:31:13 +00001802 ResTy = StructType::get(ArgTy, ArgTy);
Sanjay Patel57747212016-01-21 23:38:43 +00001803 }
1804
1805 Module *M = OrigCallee->getParent();
James Y Knight13680222019-02-01 02:28:03 +00001806 FunctionCallee Callee =
1807 M->getOrInsertFunction(Name, OrigCallee->getAttributes(), ResTy, ArgTy);
Sanjay Patel57747212016-01-21 23:38:43 +00001808
1809 if (Instruction *ArgInst = dyn_cast<Instruction>(Arg)) {
1810 // If the argument is an instruction, it must dominate all uses so put our
1811 // sincos call there.
1812 B.SetInsertPoint(ArgInst->getParent(), ++ArgInst->getIterator());
1813 } else {
1814 // Otherwise (e.g. for a constant) the beginning of the function is as
1815 // good a place as any.
1816 BasicBlock &EntryBB = B.GetInsertBlock()->getParent()->getEntryBlock();
1817 B.SetInsertPoint(&EntryBB, EntryBB.begin());
1818 }
1819
1820 SinCos = B.CreateCall(Callee, Arg, "sincospi");
1821
1822 if (SinCos->getType()->isStructTy()) {
1823 Sin = B.CreateExtractValue(SinCos, 0, "sinpi");
1824 Cos = B.CreateExtractValue(SinCos, 1, "cospi");
1825 } else {
1826 Sin = B.CreateExtractElement(SinCos, ConstantInt::get(B.getInt32Ty(), 0),
1827 "sinpi");
1828 Cos = B.CreateExtractElement(SinCos, ConstantInt::get(B.getInt32Ty(), 1),
1829 "cospi");
1830 }
1831}
Chris Bienemanad070d02014-09-17 20:55:46 +00001832
1833Value *LibCallSimplifier::optimizeSinCosPi(CallInst *CI, IRBuilder<> &B) {
Chris Bienemanad070d02014-09-17 20:55:46 +00001834 // Make sure the prototype is as expected, otherwise the rest of the
1835 // function is probably invalid and likely to abort.
1836 if (!isTrigLibCall(CI))
1837 return nullptr;
1838
1839 Value *Arg = CI->getArgOperand(0);
1840 SmallVector<CallInst *, 1> SinCalls;
1841 SmallVector<CallInst *, 1> CosCalls;
1842 SmallVector<CallInst *, 1> SinCosCalls;
1843
1844 bool IsFloat = Arg->getType()->isFloatTy();
1845
1846 // Look for all compatible sinpi, cospi and sincospi calls with the same
1847 // argument. If there are enough (in some sense) we can make the
1848 // substitution.
David Majnemerabae6b52016-03-19 04:53:02 +00001849 Function *F = CI->getFunction();
Chris Bienemanad070d02014-09-17 20:55:46 +00001850 for (User *U : Arg->users())
David Majnemerabae6b52016-03-19 04:53:02 +00001851 classifyArgUse(U, F, IsFloat, SinCalls, CosCalls, SinCosCalls);
Chris Bienemanad070d02014-09-17 20:55:46 +00001852
1853 // It's only worthwhile if both sinpi and cospi are actually used.
1854 if (SinCosCalls.empty() && (SinCalls.empty() || CosCalls.empty()))
1855 return nullptr;
1856
1857 Value *Sin, *Cos, *SinCos;
1858 insertSinCosCall(B, CI->getCalledFunction(), Arg, IsFloat, Sin, Cos, SinCos);
1859
Davide Italianof024a562016-12-16 02:28:38 +00001860 auto replaceTrigInsts = [this](SmallVectorImpl<CallInst *> &Calls,
1861 Value *Res) {
1862 for (CallInst *C : Calls)
1863 replaceAllUsesWith(C, Res);
1864 };
1865
Chris Bienemanad070d02014-09-17 20:55:46 +00001866 replaceTrigInsts(SinCalls, Sin);
1867 replaceTrigInsts(CosCalls, Cos);
1868 replaceTrigInsts(SinCosCalls, SinCos);
1869
1870 return nullptr;
1871}
1872
David Majnemerabae6b52016-03-19 04:53:02 +00001873void LibCallSimplifier::classifyArgUse(
1874 Value *Val, Function *F, bool IsFloat,
1875 SmallVectorImpl<CallInst *> &SinCalls,
1876 SmallVectorImpl<CallInst *> &CosCalls,
1877 SmallVectorImpl<CallInst *> &SinCosCalls) {
Chris Bienemanad070d02014-09-17 20:55:46 +00001878 CallInst *CI = dyn_cast<CallInst>(Val);
1879
1880 if (!CI)
1881 return;
1882
David Majnemerabae6b52016-03-19 04:53:02 +00001883 // Don't consider calls in other functions.
1884 if (CI->getFunction() != F)
1885 return;
1886
Chris Bienemanad070d02014-09-17 20:55:46 +00001887 Function *Callee = CI->getCalledFunction();
David L. Jonesd21529f2017-01-23 23:16:46 +00001888 LibFunc Func;
Ahmed Bougachad765a822016-04-27 19:04:35 +00001889 if (!Callee || !TLI->getLibFunc(*Callee, Func) || !TLI->has(Func) ||
Benjamin Kramer89766e52015-11-28 21:43:12 +00001890 !isTrigLibCall(CI))
Chris Bienemanad070d02014-09-17 20:55:46 +00001891 return;
1892
1893 if (IsFloat) {
David L. Jonesd21529f2017-01-23 23:16:46 +00001894 if (Func == LibFunc_sinpif)
Chris Bienemanad070d02014-09-17 20:55:46 +00001895 SinCalls.push_back(CI);
David L. Jonesd21529f2017-01-23 23:16:46 +00001896 else if (Func == LibFunc_cospif)
Chris Bienemanad070d02014-09-17 20:55:46 +00001897 CosCalls.push_back(CI);
David L. Jonesd21529f2017-01-23 23:16:46 +00001898 else if (Func == LibFunc_sincospif_stret)
Chris Bienemanad070d02014-09-17 20:55:46 +00001899 SinCosCalls.push_back(CI);
1900 } else {
David L. Jonesd21529f2017-01-23 23:16:46 +00001901 if (Func == LibFunc_sinpi)
Chris Bienemanad070d02014-09-17 20:55:46 +00001902 SinCalls.push_back(CI);
David L. Jonesd21529f2017-01-23 23:16:46 +00001903 else if (Func == LibFunc_cospi)
Chris Bienemanad070d02014-09-17 20:55:46 +00001904 CosCalls.push_back(CI);
David L. Jonesd21529f2017-01-23 23:16:46 +00001905 else if (Func == LibFunc_sincospi_stret)
Chris Bienemanad070d02014-09-17 20:55:46 +00001906 SinCosCalls.push_back(CI);
1907 }
1908}
1909
Meador Inge7415f842012-11-25 20:45:27 +00001910//===----------------------------------------------------------------------===//
1911// Integer Library Call Optimizations
1912//===----------------------------------------------------------------------===//
1913
Chris Bienemanad070d02014-09-17 20:55:46 +00001914Value *LibCallSimplifier::optimizeFFS(CallInst *CI, IRBuilder<> &B) {
Chris Bienemanad070d02014-09-17 20:55:46 +00001915 // ffs(x) -> x != 0 ? (i32)llvm.cttz(x)+1 : 0
Davide Italiano890e8502016-12-15 23:11:00 +00001916 Value *Op = CI->getArgOperand(0);
Chris Bienemanad070d02014-09-17 20:55:46 +00001917 Type *ArgType = Op->getType();
James Y Knight7976eb52019-02-01 20:43:25 +00001918 Function *F = Intrinsic::getDeclaration(CI->getCalledFunction()->getParent(),
1919 Intrinsic::cttz, ArgType);
Davide Italianoa1953862015-08-13 20:34:26 +00001920 Value *V = B.CreateCall(F, {Op, B.getTrue()}, "cttz");
Chris Bienemanad070d02014-09-17 20:55:46 +00001921 V = B.CreateAdd(V, ConstantInt::get(V->getType(), 1));
1922 V = B.CreateIntCast(V, B.getInt32Ty(), false);
Meador Ingea0b6d872012-11-26 00:24:07 +00001923
Chris Bienemanad070d02014-09-17 20:55:46 +00001924 Value *Cond = B.CreateICmpNE(Op, Constant::getNullValue(ArgType));
1925 return B.CreateSelect(Cond, V, B.getInt32(0));
1926}
Meador Ingea0b6d872012-11-26 00:24:07 +00001927
Davide Italiano85ad36b2016-12-15 23:45:11 +00001928Value *LibCallSimplifier::optimizeFls(CallInst *CI, IRBuilder<> &B) {
1929 // fls(x) -> (i32)(sizeInBits(x) - llvm.ctlz(x, false))
1930 Value *Op = CI->getArgOperand(0);
1931 Type *ArgType = Op->getType();
James Y Knight7976eb52019-02-01 20:43:25 +00001932 Function *F = Intrinsic::getDeclaration(CI->getCalledFunction()->getParent(),
1933 Intrinsic::ctlz, ArgType);
Davide Italiano85ad36b2016-12-15 23:45:11 +00001934 Value *V = B.CreateCall(F, {Op, B.getFalse()}, "ctlz");
1935 V = B.CreateSub(ConstantInt::get(V->getType(), ArgType->getIntegerBitWidth()),
1936 V);
1937 return B.CreateIntCast(V, CI->getType(), false);
1938}
1939
Chris Bienemanad070d02014-09-17 20:55:46 +00001940Value *LibCallSimplifier::optimizeAbs(CallInst *CI, IRBuilder<> &B) {
Sanjay Patel4b969352018-05-22 23:29:40 +00001941 // abs(x) -> x <s 0 ? -x : x
1942 // The negation has 'nsw' because abs of INT_MIN is undefined.
1943 Value *X = CI->getArgOperand(0);
1944 Value *IsNeg = B.CreateICmpSLT(X, Constant::getNullValue(X->getType()));
1945 Value *NegX = B.CreateNSWNeg(X, "neg");
1946 return B.CreateSelect(IsNeg, NegX, X);
Chris Bienemanad070d02014-09-17 20:55:46 +00001947}
Meador Inge9a59ab62012-11-26 02:31:59 +00001948
Chris Bienemanad070d02014-09-17 20:55:46 +00001949Value *LibCallSimplifier::optimizeIsDigit(CallInst *CI, IRBuilder<> &B) {
Chris Bienemanad070d02014-09-17 20:55:46 +00001950 // isdigit(c) -> (c-'0') <u 10
1951 Value *Op = CI->getArgOperand(0);
1952 Op = B.CreateSub(Op, B.getInt32('0'), "isdigittmp");
1953 Op = B.CreateICmpULT(Op, B.getInt32(10), "isdigit");
1954 return B.CreateZExt(Op, CI->getType());
1955}
Meador Ingea62a39e2012-11-26 03:10:07 +00001956
Chris Bienemanad070d02014-09-17 20:55:46 +00001957Value *LibCallSimplifier::optimizeIsAscii(CallInst *CI, IRBuilder<> &B) {
Chris Bienemanad070d02014-09-17 20:55:46 +00001958 // isascii(c) -> c <u 128
1959 Value *Op = CI->getArgOperand(0);
1960 Op = B.CreateICmpULT(Op, B.getInt32(128), "isascii");
1961 return B.CreateZExt(Op, CI->getType());
1962}
1963
1964Value *LibCallSimplifier::optimizeToAscii(CallInst *CI, IRBuilder<> &B) {
Chris Bienemanad070d02014-09-17 20:55:46 +00001965 // toascii(c) -> c & 0x7f
1966 return B.CreateAnd(CI->getArgOperand(0),
1967 ConstantInt::get(CI->getType(), 0x7F));
1968}
Meador Inge604937d2012-11-26 03:38:52 +00001969
David Bolvanskycb8ca5f32018-04-25 18:58:53 +00001970Value *LibCallSimplifier::optimizeAtoi(CallInst *CI, IRBuilder<> &B) {
1971 StringRef Str;
1972 if (!getConstantStringInfo(CI->getArgOperand(0), Str))
1973 return nullptr;
1974
1975 return convertStrToNumber(CI, Str, 10);
1976}
1977
1978Value *LibCallSimplifier::optimizeStrtol(CallInst *CI, IRBuilder<> &B) {
1979 StringRef Str;
1980 if (!getConstantStringInfo(CI->getArgOperand(0), Str))
1981 return nullptr;
1982
1983 if (!isa<ConstantPointerNull>(CI->getArgOperand(1)))
1984 return nullptr;
1985
1986 if (ConstantInt *CInt = dyn_cast<ConstantInt>(CI->getArgOperand(2))) {
1987 return convertStrToNumber(CI, Str, CInt->getSExtValue());
1988 }
1989
1990 return nullptr;
1991}
1992
Meador Inge08ca1152012-11-26 20:37:20 +00001993//===----------------------------------------------------------------------===//
1994// Formatting and IO Library Call Optimizations
1995//===----------------------------------------------------------------------===//
1996
Chris Bienemanad070d02014-09-17 20:55:46 +00001997static bool isReportingError(Function *Callee, CallInst *CI, int StreamArg);
Hal Finkel66cd3f12013-11-17 02:06:35 +00001998
Chris Bienemanad070d02014-09-17 20:55:46 +00001999Value *LibCallSimplifier::optimizeErrorReporting(CallInst *CI, IRBuilder<> &B,
2000 int StreamArg) {
Ahmed Bougachad765a822016-04-27 19:04:35 +00002001 Function *Callee = CI->getCalledFunction();
Chris Bienemanad070d02014-09-17 20:55:46 +00002002 // Error reporting calls should be cold, mark them as such.
2003 // This applies even to non-builtin calls: it is only a hint and applies to
2004 // functions that the frontend might not understand as builtins.
Hal Finkel66cd3f12013-11-17 02:06:35 +00002005
Chris Bienemanad070d02014-09-17 20:55:46 +00002006 // This heuristic was suggested in:
2007 // Improving Static Branch Prediction in a Compiler
2008 // Brian L. Deitrich, Ben-Chung Cheng, Wen-mei W. Hwu
2009 // Proceedings of PACT'98, Oct. 1998, IEEE
Chris Bienemanad070d02014-09-17 20:55:46 +00002010 if (!CI->hasFnAttr(Attribute::Cold) &&
2011 isReportingError(Callee, CI, StreamArg)) {
Reid Klecknerb5180542017-03-21 16:57:19 +00002012 CI->addAttribute(AttributeList::FunctionIndex, Attribute::Cold);
Chris Bienemanad070d02014-09-17 20:55:46 +00002013 }
Hal Finkel66cd3f12013-11-17 02:06:35 +00002014
Chris Bienemanad070d02014-09-17 20:55:46 +00002015 return nullptr;
2016}
2017
2018static bool isReportingError(Function *Callee, CallInst *CI, int StreamArg) {
Davide Italiano5b65f122017-04-25 03:48:47 +00002019 if (!Callee || !Callee->isDeclaration())
Chris Bienemanad070d02014-09-17 20:55:46 +00002020 return false;
2021
2022 if (StreamArg < 0)
2023 return true;
2024
2025 // These functions might be considered cold, but only if their stream
2026 // argument is stderr.
2027
2028 if (StreamArg >= (int)CI->getNumArgOperands())
2029 return false;
2030 LoadInst *LI = dyn_cast<LoadInst>(CI->getArgOperand(StreamArg));
2031 if (!LI)
2032 return false;
2033 GlobalVariable *GV = dyn_cast<GlobalVariable>(LI->getPointerOperand());
2034 if (!GV || !GV->isDeclaration())
2035 return false;
2036 return GV->getName() == "stderr";
2037}
2038
2039Value *LibCallSimplifier::optimizePrintFString(CallInst *CI, IRBuilder<> &B) {
2040 // Check for a fixed format string.
2041 StringRef FormatStr;
2042 if (!getConstantStringInfo(CI->getArgOperand(0), FormatStr))
Craig Topperf40110f2014-04-25 05:29:35 +00002043 return nullptr;
Hal Finkel66cd3f12013-11-17 02:06:35 +00002044
Chris Bienemanad070d02014-09-17 20:55:46 +00002045 // Empty format string -> noop.
2046 if (FormatStr.empty()) // Tolerate printf's declared void.
2047 return CI->use_empty() ? (Value *)CI : ConstantInt::get(CI->getType(), 0);
Hal Finkel66cd3f12013-11-17 02:06:35 +00002048
Chris Bienemanad070d02014-09-17 20:55:46 +00002049 // Do not do any of the following transformations if the printf return value
2050 // is used, in general the printf return value is not compatible with either
2051 // putchar() or puts().
2052 if (!CI->use_empty())
Craig Topperf40110f2014-04-25 05:29:35 +00002053 return nullptr;
Chris Bienemanad070d02014-09-17 20:55:46 +00002054
Joerg Sonnenberger8ffe7ab2016-05-09 14:36:16 +00002055 // printf("x") -> putchar('x'), even for "%" and "%%".
2056 if (FormatStr.size() == 1 || FormatStr == "%%")
Davide Italianod4f5a052016-04-03 01:46:52 +00002057 return emitPutChar(B.getInt32(FormatStr[0]), B, TLI);
Meador Inge08ca1152012-11-26 20:37:20 +00002058
Davide Italiano6db1dcb2016-03-28 15:54:01 +00002059 // printf("%s", "a") --> putchar('a')
2060 if (FormatStr == "%s" && CI->getNumArgOperands() > 1) {
2061 StringRef ChrStr;
2062 if (!getConstantStringInfo(CI->getOperand(1), ChrStr))
2063 return nullptr;
2064 if (ChrStr.size() != 1)
2065 return nullptr;
Davide Italianod4f5a052016-04-03 01:46:52 +00002066 return emitPutChar(B.getInt32(ChrStr[0]), B, TLI);
Davide Italiano6db1dcb2016-03-28 15:54:01 +00002067 }
2068
Chris Bienemanad070d02014-09-17 20:55:46 +00002069 // printf("foo\n") --> puts("foo")
2070 if (FormatStr[FormatStr.size() - 1] == '\n' &&
2071 FormatStr.find('%') == StringRef::npos) { // No format characters.
2072 // Create a string literal with no \n on it. We expect the constant merge
2073 // pass to be run after this pass, to merge duplicate strings.
2074 FormatStr = FormatStr.drop_back();
2075 Value *GV = B.CreateGlobalString(FormatStr, "str");
Davide Italianod4f5a052016-04-03 01:46:52 +00002076 return emitPutS(GV, B, TLI);
Chris Bienemanad070d02014-09-17 20:55:46 +00002077 }
Meador Inge08ca1152012-11-26 20:37:20 +00002078
Chris Bienemanad070d02014-09-17 20:55:46 +00002079 // Optimize specific format strings.
2080 // printf("%c", chr) --> putchar(chr)
2081 if (FormatStr == "%c" && CI->getNumArgOperands() > 1 &&
Davide Italianod4f5a052016-04-03 01:46:52 +00002082 CI->getArgOperand(1)->getType()->isIntegerTy())
2083 return emitPutChar(CI->getArgOperand(1), B, TLI);
Chris Bienemanad070d02014-09-17 20:55:46 +00002084
2085 // printf("%s\n", str) --> puts(str)
2086 if (FormatStr == "%s\n" && CI->getNumArgOperands() > 1 &&
Davide Italianod4f5a052016-04-03 01:46:52 +00002087 CI->getArgOperand(1)->getType()->isPointerTy())
Sanjay Pateld3112a52016-01-19 19:46:10 +00002088 return emitPutS(CI->getArgOperand(1), B, TLI);
Chris Bienemanad070d02014-09-17 20:55:46 +00002089 return nullptr;
2090}
2091
2092Value *LibCallSimplifier::optimizePrintF(CallInst *CI, IRBuilder<> &B) {
2093
2094 Function *Callee = CI->getCalledFunction();
Chris Bienemanad070d02014-09-17 20:55:46 +00002095 FunctionType *FT = Callee->getFunctionType();
Chris Bienemanad070d02014-09-17 20:55:46 +00002096 if (Value *V = optimizePrintFString(CI, B)) {
2097 return V;
2098 }
2099
2100 // printf(format, ...) -> iprintf(format, ...) if no floating point
2101 // arguments.
David L. Jonesd21529f2017-01-23 23:16:46 +00002102 if (TLI->has(LibFunc_iprintf) && !callHasFloatingPointArgument(CI)) {
Chris Bienemanad070d02014-09-17 20:55:46 +00002103 Module *M = B.GetInsertBlock()->getParent()->getParent();
James Y Knight13680222019-02-01 02:28:03 +00002104 FunctionCallee IPrintFFn =
Meador Inge08ca1152012-11-26 20:37:20 +00002105 M->getOrInsertFunction("iprintf", FT, Callee->getAttributes());
Chris Bienemanad070d02014-09-17 20:55:46 +00002106 CallInst *New = cast<CallInst>(CI->clone());
2107 New->setCalledFunction(IPrintFFn);
2108 B.Insert(New);
2109 return New;
Meador Inge08ca1152012-11-26 20:37:20 +00002110 }
Alon Zakaib4f99912019-04-03 01:08:35 +00002111
2112 // printf(format, ...) -> __small_printf(format, ...) if no 128-bit floating point
2113 // arguments.
2114 if (TLI->has(LibFunc_small_printf) && !callHasFP128Argument(CI)) {
2115 Module *M = B.GetInsertBlock()->getParent()->getParent();
2116 auto SmallPrintFFn =
2117 M->getOrInsertFunction(TLI->getName(LibFunc_small_printf),
2118 FT, Callee->getAttributes());
2119 CallInst *New = cast<CallInst>(CI->clone());
2120 New->setCalledFunction(SmallPrintFFn);
2121 B.Insert(New);
2122 return New;
2123 }
2124
Chris Bienemanad070d02014-09-17 20:55:46 +00002125 return nullptr;
2126}
Meador Inge08ca1152012-11-26 20:37:20 +00002127
Chris Bienemanad070d02014-09-17 20:55:46 +00002128Value *LibCallSimplifier::optimizeSPrintFString(CallInst *CI, IRBuilder<> &B) {
2129 // Check for a fixed format string.
2130 StringRef FormatStr;
2131 if (!getConstantStringInfo(CI->getArgOperand(1), FormatStr))
Craig Topperf40110f2014-04-25 05:29:35 +00002132 return nullptr;
Meador Inge25c9b3b2012-11-27 05:57:54 +00002133
Chris Bienemanad070d02014-09-17 20:55:46 +00002134 // If we just have a format string (nothing else crazy) transform it.
2135 if (CI->getNumArgOperands() == 2) {
2136 // Make sure there's no % in the constant array. We could try to handle
2137 // %% -> % in the future if we cared.
David Bolvansky5430b7372018-05-31 16:39:27 +00002138 if (FormatStr.find('%') != StringRef::npos)
2139 return nullptr; // we found a format specifier, bail out.
Hal Finkel66cd3f12013-11-17 02:06:35 +00002140
Daniel Neilson8acd8b02018-02-05 21:23:22 +00002141 // sprintf(str, fmt) -> llvm.memcpy(align 1 str, align 1 fmt, strlen(fmt)+1)
2142 B.CreateMemCpy(CI->getArgOperand(0), 1, CI->getArgOperand(1), 1,
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002143 ConstantInt::get(DL.getIntPtrType(CI->getContext()),
Daniel Neilson8acd8b02018-02-05 21:23:22 +00002144 FormatStr.size() + 1)); // Copy the null byte.
Chris Bienemanad070d02014-09-17 20:55:46 +00002145 return ConstantInt::get(CI->getType(), FormatStr.size());
Meador Ingef8e72502012-11-29 15:45:43 +00002146 }
Meador Ingef8e72502012-11-29 15:45:43 +00002147
Chris Bienemanad070d02014-09-17 20:55:46 +00002148 // The remaining optimizations require the format string to be "%s" or "%c"
2149 // and have an extra operand.
2150 if (FormatStr.size() != 2 || FormatStr[0] != '%' ||
2151 CI->getNumArgOperands() < 3)
Craig Topperf40110f2014-04-25 05:29:35 +00002152 return nullptr;
Meador Inge75798bb2012-11-29 19:15:17 +00002153
Chris Bienemanad070d02014-09-17 20:55:46 +00002154 // Decode the second character of the format string.
2155 if (FormatStr[1] == 'c') {
2156 // sprintf(dst, "%c", chr) --> *(i8*)dst = chr; *((i8*)dst+1) = 0
2157 if (!CI->getArgOperand(2)->getType()->isIntegerTy())
2158 return nullptr;
2159 Value *V = B.CreateTrunc(CI->getArgOperand(2), B.getInt8Ty(), "char");
Sanjay Pateld3112a52016-01-19 19:46:10 +00002160 Value *Ptr = castToCStr(CI->getArgOperand(0), B);
Chris Bienemanad070d02014-09-17 20:55:46 +00002161 B.CreateStore(V, Ptr);
David Blaikie3909da72015-03-30 20:42:56 +00002162 Ptr = B.CreateGEP(B.getInt8Ty(), Ptr, B.getInt32(1), "nul");
Chris Bienemanad070d02014-09-17 20:55:46 +00002163 B.CreateStore(B.getInt8(0), Ptr);
Meador Ingedf796f82012-10-13 16:45:24 +00002164
Chris Bienemanad070d02014-09-17 20:55:46 +00002165 return ConstantInt::get(CI->getType(), 1);
Meador Ingedf796f82012-10-13 16:45:24 +00002166 }
2167
Chris Bienemanad070d02014-09-17 20:55:46 +00002168 if (FormatStr[1] == 's') {
Fangrui Songf2609672019-03-12 10:31:52 +00002169 // sprintf(dest, "%s", str) -> llvm.memcpy(align 1 dest, align 1 str,
2170 // strlen(str)+1)
Chris Bienemanad070d02014-09-17 20:55:46 +00002171 if (!CI->getArgOperand(2)->getType()->isPointerTy())
2172 return nullptr;
2173
Sanjay Pateld3112a52016-01-19 19:46:10 +00002174 Value *Len = emitStrLen(CI->getArgOperand(2), B, DL, TLI);
Chris Bienemanad070d02014-09-17 20:55:46 +00002175 if (!Len)
2176 return nullptr;
David Majnemerabb9f552016-04-26 21:04:47 +00002177 Value *IncLen =
2178 B.CreateAdd(Len, ConstantInt::get(Len->getType(), 1), "leninc");
Daniel Neilson8acd8b02018-02-05 21:23:22 +00002179 B.CreateMemCpy(CI->getArgOperand(0), 1, CI->getArgOperand(2), 1, IncLen);
Chris Bienemanad070d02014-09-17 20:55:46 +00002180
2181 // The sprintf result is the unincremented number of bytes in the string.
2182 return B.CreateIntCast(Len, CI->getType(), false);
2183 }
2184 return nullptr;
2185}
2186
2187Value *LibCallSimplifier::optimizeSPrintF(CallInst *CI, IRBuilder<> &B) {
2188 Function *Callee = CI->getCalledFunction();
Chris Bienemanad070d02014-09-17 20:55:46 +00002189 FunctionType *FT = Callee->getFunctionType();
Chris Bienemanad070d02014-09-17 20:55:46 +00002190 if (Value *V = optimizeSPrintFString(CI, B)) {
2191 return V;
2192 }
2193
2194 // sprintf(str, format, ...) -> siprintf(str, format, ...) if no floating
2195 // point arguments.
David L. Jonesd21529f2017-01-23 23:16:46 +00002196 if (TLI->has(LibFunc_siprintf) && !callHasFloatingPointArgument(CI)) {
Chris Bienemanad070d02014-09-17 20:55:46 +00002197 Module *M = B.GetInsertBlock()->getParent()->getParent();
James Y Knight13680222019-02-01 02:28:03 +00002198 FunctionCallee SIPrintFFn =
Chris Bienemanad070d02014-09-17 20:55:46 +00002199 M->getOrInsertFunction("siprintf", FT, Callee->getAttributes());
2200 CallInst *New = cast<CallInst>(CI->clone());
2201 New->setCalledFunction(SIPrintFFn);
2202 B.Insert(New);
2203 return New;
2204 }
Alon Zakaib4f99912019-04-03 01:08:35 +00002205
2206 // sprintf(str, format, ...) -> __small_sprintf(str, format, ...) if no 128-bit
2207 // floating point arguments.
2208 if (TLI->has(LibFunc_small_sprintf) && !callHasFP128Argument(CI)) {
2209 Module *M = B.GetInsertBlock()->getParent()->getParent();
2210 auto SmallSPrintFFn =
2211 M->getOrInsertFunction(TLI->getName(LibFunc_small_sprintf),
2212 FT, Callee->getAttributes());
2213 CallInst *New = cast<CallInst>(CI->clone());
2214 New->setCalledFunction(SmallSPrintFFn);
2215 B.Insert(New);
2216 return New;
2217 }
2218
Chris Bienemanad070d02014-09-17 20:55:46 +00002219 return nullptr;
2220}
2221
David Bolvanskycd93c4e2018-05-11 17:50:49 +00002222Value *LibCallSimplifier::optimizeSnPrintFString(CallInst *CI, IRBuilder<> &B) {
2223 // Check for a fixed format string.
2224 StringRef FormatStr;
2225 if (!getConstantStringInfo(CI->getArgOperand(2), FormatStr))
2226 return nullptr;
2227
2228 // Check for size
2229 ConstantInt *Size = dyn_cast<ConstantInt>(CI->getArgOperand(1));
2230 if (!Size)
2231 return nullptr;
2232
2233 uint64_t N = Size->getZExtValue();
2234
2235 // If we just have a format string (nothing else crazy) transform it.
2236 if (CI->getNumArgOperands() == 3) {
2237 // Make sure there's no % in the constant array. We could try to handle
2238 // %% -> % in the future if we cared.
David Bolvansky5430b7372018-05-31 16:39:27 +00002239 if (FormatStr.find('%') != StringRef::npos)
2240 return nullptr; // we found a format specifier, bail out.
David Bolvanskycd93c4e2018-05-11 17:50:49 +00002241
2242 if (N == 0)
2243 return ConstantInt::get(CI->getType(), FormatStr.size());
2244 else if (N < FormatStr.size() + 1)
2245 return nullptr;
2246
Fangrui Songf2609672019-03-12 10:31:52 +00002247 // snprintf(dst, size, fmt) -> llvm.memcpy(align 1 dst, align 1 fmt,
David Bolvanskycd93c4e2018-05-11 17:50:49 +00002248 // strlen(fmt)+1)
2249 B.CreateMemCpy(
2250 CI->getArgOperand(0), 1, CI->getArgOperand(2), 1,
2251 ConstantInt::get(DL.getIntPtrType(CI->getContext()),
2252 FormatStr.size() + 1)); // Copy the null byte.
2253 return ConstantInt::get(CI->getType(), FormatStr.size());
2254 }
2255
2256 // The remaining optimizations require the format string to be "%s" or "%c"
2257 // and have an extra operand.
2258 if (FormatStr.size() == 2 && FormatStr[0] == '%' &&
2259 CI->getNumArgOperands() == 4) {
2260
2261 // Decode the second character of the format string.
2262 if (FormatStr[1] == 'c') {
2263 if (N == 0)
2264 return ConstantInt::get(CI->getType(), 1);
2265 else if (N == 1)
2266 return nullptr;
2267
2268 // snprintf(dst, size, "%c", chr) --> *(i8*)dst = chr; *((i8*)dst+1) = 0
2269 if (!CI->getArgOperand(3)->getType()->isIntegerTy())
2270 return nullptr;
2271 Value *V = B.CreateTrunc(CI->getArgOperand(3), B.getInt8Ty(), "char");
2272 Value *Ptr = castToCStr(CI->getArgOperand(0), B);
2273 B.CreateStore(V, Ptr);
2274 Ptr = B.CreateGEP(B.getInt8Ty(), Ptr, B.getInt32(1), "nul");
2275 B.CreateStore(B.getInt8(0), Ptr);
2276
2277 return ConstantInt::get(CI->getType(), 1);
2278 }
2279
2280 if (FormatStr[1] == 's') {
2281 // snprintf(dest, size, "%s", str) to llvm.memcpy(dest, str, len+1, 1)
2282 StringRef Str;
2283 if (!getConstantStringInfo(CI->getArgOperand(3), Str))
2284 return nullptr;
2285
2286 if (N == 0)
2287 return ConstantInt::get(CI->getType(), Str.size());
2288 else if (N < Str.size() + 1)
2289 return nullptr;
2290
2291 B.CreateMemCpy(CI->getArgOperand(0), 1, CI->getArgOperand(3), 1,
2292 ConstantInt::get(CI->getType(), Str.size() + 1));
2293
2294 // The snprintf result is the unincremented number of bytes in the string.
2295 return ConstantInt::get(CI->getType(), Str.size());
2296 }
2297 }
2298 return nullptr;
2299}
2300
2301Value *LibCallSimplifier::optimizeSnPrintF(CallInst *CI, IRBuilder<> &B) {
2302 if (Value *V = optimizeSnPrintFString(CI, B)) {
2303 return V;
2304 }
2305
2306 return nullptr;
2307}
2308
Chris Bienemanad070d02014-09-17 20:55:46 +00002309Value *LibCallSimplifier::optimizeFPrintFString(CallInst *CI, IRBuilder<> &B) {
2310 optimizeErrorReporting(CI, B, 0);
2311
2312 // All the optimizations depend on the format string.
2313 StringRef FormatStr;
2314 if (!getConstantStringInfo(CI->getArgOperand(1), FormatStr))
2315 return nullptr;
2316
2317 // Do not do any of the following transformations if the fprintf return
2318 // value is used, in general the fprintf return value is not compatible
2319 // with fwrite(), fputc() or fputs().
2320 if (!CI->use_empty())
2321 return nullptr;
2322
2323 // fprintf(F, "foo") --> fwrite("foo", 3, 1, F)
2324 if (CI->getNumArgOperands() == 2) {
David Bolvansky5430b7372018-05-31 16:39:27 +00002325 // Could handle %% -> % if we cared.
2326 if (FormatStr.find('%') != StringRef::npos)
2327 return nullptr; // We found a format specifier.
Chris Bienemanad070d02014-09-17 20:55:46 +00002328
Sanjay Pateld3112a52016-01-19 19:46:10 +00002329 return emitFWrite(
Chris Bienemanad070d02014-09-17 20:55:46 +00002330 CI->getArgOperand(1),
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002331 ConstantInt::get(DL.getIntPtrType(CI->getContext()), FormatStr.size()),
Chris Bienemanad070d02014-09-17 20:55:46 +00002332 CI->getArgOperand(0), B, DL, TLI);
2333 }
2334
2335 // The remaining optimizations require the format string to be "%s" or "%c"
2336 // and have an extra operand.
2337 if (FormatStr.size() != 2 || FormatStr[0] != '%' ||
2338 CI->getNumArgOperands() < 3)
2339 return nullptr;
2340
2341 // Decode the second character of the format string.
2342 if (FormatStr[1] == 'c') {
2343 // fprintf(F, "%c", chr) --> fputc(chr, F)
2344 if (!CI->getArgOperand(2)->getType()->isIntegerTy())
2345 return nullptr;
Sanjay Pateld3112a52016-01-19 19:46:10 +00002346 return emitFPutC(CI->getArgOperand(2), CI->getArgOperand(0), B, TLI);
Chris Bienemanad070d02014-09-17 20:55:46 +00002347 }
2348
2349 if (FormatStr[1] == 's') {
2350 // fprintf(F, "%s", str) --> fputs(str, F)
2351 if (!CI->getArgOperand(2)->getType()->isPointerTy())
2352 return nullptr;
Sanjay Pateld3112a52016-01-19 19:46:10 +00002353 return emitFPutS(CI->getArgOperand(2), CI->getArgOperand(0), B, TLI);
Chris Bienemanad070d02014-09-17 20:55:46 +00002354 }
2355 return nullptr;
2356}
2357
2358Value *LibCallSimplifier::optimizeFPrintF(CallInst *CI, IRBuilder<> &B) {
2359 Function *Callee = CI->getCalledFunction();
Chris Bienemanad070d02014-09-17 20:55:46 +00002360 FunctionType *FT = Callee->getFunctionType();
Chris Bienemanad070d02014-09-17 20:55:46 +00002361 if (Value *V = optimizeFPrintFString(CI, B)) {
2362 return V;
2363 }
2364
2365 // fprintf(stream, format, ...) -> fiprintf(stream, format, ...) if no
2366 // floating point arguments.
David L. Jonesd21529f2017-01-23 23:16:46 +00002367 if (TLI->has(LibFunc_fiprintf) && !callHasFloatingPointArgument(CI)) {
Chris Bienemanad070d02014-09-17 20:55:46 +00002368 Module *M = B.GetInsertBlock()->getParent()->getParent();
James Y Knight13680222019-02-01 02:28:03 +00002369 FunctionCallee FIPrintFFn =
Chris Bienemanad070d02014-09-17 20:55:46 +00002370 M->getOrInsertFunction("fiprintf", FT, Callee->getAttributes());
2371 CallInst *New = cast<CallInst>(CI->clone());
2372 New->setCalledFunction(FIPrintFFn);
2373 B.Insert(New);
2374 return New;
2375 }
Alon Zakaib4f99912019-04-03 01:08:35 +00002376
2377 // fprintf(stream, format, ...) -> __small_fprintf(stream, format, ...) if no
2378 // 128-bit floating point arguments.
2379 if (TLI->has(LibFunc_small_fprintf) && !callHasFP128Argument(CI)) {
2380 Module *M = B.GetInsertBlock()->getParent()->getParent();
2381 auto SmallFPrintFFn =
2382 M->getOrInsertFunction(TLI->getName(LibFunc_small_fprintf),
2383 FT, Callee->getAttributes());
2384 CallInst *New = cast<CallInst>(CI->clone());
2385 New->setCalledFunction(SmallFPrintFFn);
2386 B.Insert(New);
2387 return New;
2388 }
2389
Chris Bienemanad070d02014-09-17 20:55:46 +00002390 return nullptr;
2391}
2392
2393Value *LibCallSimplifier::optimizeFWrite(CallInst *CI, IRBuilder<> &B) {
2394 optimizeErrorReporting(CI, B, 3);
2395
Chris Bienemanad070d02014-09-17 20:55:46 +00002396 // Get the element size and count.
2397 ConstantInt *SizeC = dyn_cast<ConstantInt>(CI->getArgOperand(1));
2398 ConstantInt *CountC = dyn_cast<ConstantInt>(CI->getArgOperand(2));
David Bolvanskyca22d422018-05-16 11:39:52 +00002399 if (SizeC && CountC) {
2400 uint64_t Bytes = SizeC->getZExtValue() * CountC->getZExtValue();
Chris Bienemanad070d02014-09-17 20:55:46 +00002401
David Bolvanskyca22d422018-05-16 11:39:52 +00002402 // If this is writing zero records, remove the call (it's a noop).
2403 if (Bytes == 0)
2404 return ConstantInt::get(CI->getType(), 0);
Chris Bienemanad070d02014-09-17 20:55:46 +00002405
David Bolvanskyca22d422018-05-16 11:39:52 +00002406 // If this is writing one byte, turn it into fputc.
2407 // This optimisation is only valid, if the return value is unused.
2408 if (Bytes == 1 && CI->use_empty()) { // fwrite(S,1,1,F) -> fputc(S[0],F)
James Y Knight14359ef2019-02-01 20:44:24 +00002409 Value *Char = B.CreateLoad(B.getInt8Ty(),
2410 castToCStr(CI->getArgOperand(0), B), "char");
David Bolvanskyca22d422018-05-16 11:39:52 +00002411 Value *NewCI = emitFPutC(Char, CI->getArgOperand(3), B, TLI);
2412 return NewCI ? ConstantInt::get(CI->getType(), 1) : nullptr;
2413 }
Chris Bienemanad070d02014-09-17 20:55:46 +00002414 }
2415
David Bolvanskyca22d422018-05-16 11:39:52 +00002416 if (isLocallyOpenedFile(CI->getArgOperand(3), CI, B, TLI))
2417 return emitFWriteUnlocked(CI->getArgOperand(0), CI->getArgOperand(1),
2418 CI->getArgOperand(2), CI->getArgOperand(3), B, DL,
2419 TLI);
2420
Chris Bienemanad070d02014-09-17 20:55:46 +00002421 return nullptr;
2422}
2423
2424Value *LibCallSimplifier::optimizeFPuts(CallInst *CI, IRBuilder<> &B) {
2425 optimizeErrorReporting(CI, B, 1);
2426
Sjoerd Meijer7435a912016-07-07 14:31:19 +00002427 // Don't rewrite fputs to fwrite when optimising for size because fwrite
2428 // requires more arguments and thus extra MOVs are required.
Hiroshi Yamauchi09e539f2019-04-15 16:49:00 +00002429 bool OptForSize = CI->getFunction()->hasOptSize() ||
2430 llvm::shouldOptimizeForSize(CI->getParent(), PSI, BFI);
2431 if (OptForSize)
Sjoerd Meijer7435a912016-07-07 14:31:19 +00002432 return nullptr;
2433
David Bolvanskyca22d422018-05-16 11:39:52 +00002434 // Check if has any use
2435 if (!CI->use_empty()) {
2436 if (isLocallyOpenedFile(CI->getArgOperand(1), CI, B, TLI))
2437 return emitFPutSUnlocked(CI->getArgOperand(0), CI->getArgOperand(1), B,
2438 TLI);
2439 else
2440 // We can't optimize if return value is used.
2441 return nullptr;
2442 }
Chris Bienemanad070d02014-09-17 20:55:46 +00002443
Fangrui Songf2609672019-03-12 10:31:52 +00002444 // fputs(s,F) --> fwrite(s,strlen(s),1,F)
David Bolvansky1f343fa2018-05-22 20:27:36 +00002445 uint64_t Len = GetStringLength(CI->getArgOperand(0));
Chris Bienemanad070d02014-09-17 20:55:46 +00002446 if (!Len)
2447 return nullptr;
2448
2449 // Known to have no uses (see above).
Sanjay Pateld3112a52016-01-19 19:46:10 +00002450 return emitFWrite(
Chris Bienemanad070d02014-09-17 20:55:46 +00002451 CI->getArgOperand(0),
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002452 ConstantInt::get(DL.getIntPtrType(CI->getContext()), Len - 1),
Chris Bienemanad070d02014-09-17 20:55:46 +00002453 CI->getArgOperand(1), B, DL, TLI);
2454}
2455
David Bolvanskyca22d422018-05-16 11:39:52 +00002456Value *LibCallSimplifier::optimizeFPutc(CallInst *CI, IRBuilder<> &B) {
2457 optimizeErrorReporting(CI, B, 1);
2458
2459 if (isLocallyOpenedFile(CI->getArgOperand(1), CI, B, TLI))
2460 return emitFPutCUnlocked(CI->getArgOperand(0), CI->getArgOperand(1), B,
2461 TLI);
2462
2463 return nullptr;
2464}
2465
2466Value *LibCallSimplifier::optimizeFGetc(CallInst *CI, IRBuilder<> &B) {
2467 if (isLocallyOpenedFile(CI->getArgOperand(0), CI, B, TLI))
2468 return emitFGetCUnlocked(CI->getArgOperand(0), B, TLI);
2469
2470 return nullptr;
2471}
2472
2473Value *LibCallSimplifier::optimizeFGets(CallInst *CI, IRBuilder<> &B) {
2474 if (isLocallyOpenedFile(CI->getArgOperand(2), CI, B, TLI))
2475 return emitFGetSUnlocked(CI->getArgOperand(0), CI->getArgOperand(1),
2476 CI->getArgOperand(2), B, TLI);
2477
2478 return nullptr;
2479}
2480
2481Value *LibCallSimplifier::optimizeFRead(CallInst *CI, IRBuilder<> &B) {
2482 if (isLocallyOpenedFile(CI->getArgOperand(3), CI, B, TLI))
2483 return emitFReadUnlocked(CI->getArgOperand(0), CI->getArgOperand(1),
2484 CI->getArgOperand(2), CI->getArgOperand(3), B, DL,
2485 TLI);
2486
2487 return nullptr;
2488}
2489
Chris Bienemanad070d02014-09-17 20:55:46 +00002490Value *LibCallSimplifier::optimizePuts(CallInst *CI, IRBuilder<> &B) {
Fangrui Songb1dfbeb2019-03-12 14:20:22 +00002491 if (!CI->use_empty())
Chris Bienemanad070d02014-09-17 20:55:46 +00002492 return nullptr;
2493
Fangrui Songb1dfbeb2019-03-12 14:20:22 +00002494 // Check for a constant string.
2495 // puts("") -> putchar('\n')
2496 StringRef Str;
2497 if (getConstantStringInfo(CI->getArgOperand(0), Str) && Str.empty())
2498 return emitPutChar(B.getInt32('\n'), B, TLI);
Chris Bienemanad070d02014-09-17 20:55:46 +00002499
2500 return nullptr;
2501}
2502
2503bool LibCallSimplifier::hasFloatVersion(StringRef FuncName) {
David L. Jonesd21529f2017-01-23 23:16:46 +00002504 LibFunc Func;
Meador Inge20255ef2013-03-12 00:08:29 +00002505 SmallString<20> FloatFuncName = FuncName;
2506 FloatFuncName += 'f';
2507 if (TLI->getLibFunc(FloatFuncName, Func))
2508 return TLI->has(Func);
2509 return false;
2510}
Meador Inge7fb2f732012-10-13 16:45:32 +00002511
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00002512Value *LibCallSimplifier::optimizeStringMemoryLibCall(CallInst *CI,
2513 IRBuilder<> &Builder) {
David L. Jonesd21529f2017-01-23 23:16:46 +00002514 LibFunc Func;
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00002515 Function *Callee = CI->getCalledFunction();
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00002516 // Check for string/memory library functions.
Ahmed Bougachad765a822016-04-27 19:04:35 +00002517 if (TLI->getLibFunc(*Callee, Func) && TLI->has(Func)) {
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00002518 // Make sure we never change the calling convention.
2519 assert((ignoreCallingConv(Func) ||
Sam Parker214f7bf2016-09-13 12:10:14 +00002520 isCallingConvCCompatible(CI)) &&
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00002521 "Optimizing string/memory libcall would change the calling convention");
2522 switch (Func) {
David L. Jonesd21529f2017-01-23 23:16:46 +00002523 case LibFunc_strcat:
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00002524 return optimizeStrCat(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002525 case LibFunc_strncat:
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00002526 return optimizeStrNCat(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002527 case LibFunc_strchr:
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00002528 return optimizeStrChr(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002529 case LibFunc_strrchr:
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00002530 return optimizeStrRChr(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002531 case LibFunc_strcmp:
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00002532 return optimizeStrCmp(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002533 case LibFunc_strncmp:
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00002534 return optimizeStrNCmp(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002535 case LibFunc_strcpy:
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00002536 return optimizeStrCpy(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002537 case LibFunc_stpcpy:
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00002538 return optimizeStpCpy(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002539 case LibFunc_strncpy:
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00002540 return optimizeStrNCpy(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002541 case LibFunc_strlen:
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00002542 return optimizeStrLen(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002543 case LibFunc_strpbrk:
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00002544 return optimizeStrPBrk(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002545 case LibFunc_strtol:
2546 case LibFunc_strtod:
2547 case LibFunc_strtof:
2548 case LibFunc_strtoul:
2549 case LibFunc_strtoll:
2550 case LibFunc_strtold:
2551 case LibFunc_strtoull:
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00002552 return optimizeStrTo(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002553 case LibFunc_strspn:
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00002554 return optimizeStrSpn(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002555 case LibFunc_strcspn:
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00002556 return optimizeStrCSpn(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002557 case LibFunc_strstr:
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00002558 return optimizeStrStr(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002559 case LibFunc_memchr:
Benjamin Kramer691363e2015-03-21 15:36:21 +00002560 return optimizeMemChr(CI, Builder);
Clement Courbet9e1f2a72019-05-06 09:15:22 +00002561 case LibFunc_bcmp:
2562 return optimizeBCmp(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002563 case LibFunc_memcmp:
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00002564 return optimizeMemCmp(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002565 case LibFunc_memcpy:
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00002566 return optimizeMemCpy(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002567 case LibFunc_memmove:
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00002568 return optimizeMemMove(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002569 case LibFunc_memset:
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00002570 return optimizeMemSet(CI, Builder);
Sanjay Patelb2ab3f22018-04-18 14:21:31 +00002571 case LibFunc_realloc:
2572 return optimizeRealloc(CI, Builder);
Matthias Braun50ec0b52017-05-19 22:37:09 +00002573 case LibFunc_wcslen:
2574 return optimizeWcslen(CI, Builder);
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00002575 default:
2576 break;
2577 }
2578 }
2579 return nullptr;
2580}
2581
Andrew Kaylor53a5fbb2017-08-14 21:15:13 +00002582Value *LibCallSimplifier::optimizeFloatingPointLibCall(CallInst *CI,
2583 LibFunc Func,
2584 IRBuilder<> &Builder) {
2585 // Don't optimize calls that require strict floating point semantics.
2586 if (CI->isStrictFP())
2587 return nullptr;
2588
Sanjay Patele45a83d2018-08-13 19:24:41 +00002589 if (Value *V = optimizeTrigReflections(CI, Func, Builder))
2590 return V;
2591
Andrew Kaylor53a5fbb2017-08-14 21:15:13 +00002592 switch (Func) {
Andrew Kaylor53a5fbb2017-08-14 21:15:13 +00002593 case LibFunc_sinpif:
2594 case LibFunc_sinpi:
2595 case LibFunc_cospif:
2596 case LibFunc_cospi:
2597 return optimizeSinCosPi(CI, Builder);
2598 case LibFunc_powf:
2599 case LibFunc_pow:
2600 case LibFunc_powl:
2601 return optimizePow(CI, Builder);
2602 case LibFunc_exp2l:
2603 case LibFunc_exp2:
2604 case LibFunc_exp2f:
2605 return optimizeExp2(CI, Builder);
2606 case LibFunc_fabsf:
2607 case LibFunc_fabs:
2608 case LibFunc_fabsl:
2609 return replaceUnaryCall(CI, Builder, Intrinsic::fabs);
2610 case LibFunc_sqrtf:
2611 case LibFunc_sqrt:
2612 case LibFunc_sqrtl:
2613 return optimizeSqrt(CI, Builder);
2614 case LibFunc_log:
2615 case LibFunc_log10:
2616 case LibFunc_log1p:
2617 case LibFunc_log2:
2618 case LibFunc_logb:
2619 return optimizeLog(CI, Builder);
2620 case LibFunc_tan:
2621 case LibFunc_tanf:
2622 case LibFunc_tanl:
2623 return optimizeTan(CI, Builder);
2624 case LibFunc_ceil:
2625 return replaceUnaryCall(CI, Builder, Intrinsic::ceil);
2626 case LibFunc_floor:
2627 return replaceUnaryCall(CI, Builder, Intrinsic::floor);
2628 case LibFunc_round:
2629 return replaceUnaryCall(CI, Builder, Intrinsic::round);
2630 case LibFunc_nearbyint:
2631 return replaceUnaryCall(CI, Builder, Intrinsic::nearbyint);
2632 case LibFunc_rint:
2633 return replaceUnaryCall(CI, Builder, Intrinsic::rint);
2634 case LibFunc_trunc:
2635 return replaceUnaryCall(CI, Builder, Intrinsic::trunc);
2636 case LibFunc_acos:
2637 case LibFunc_acosh:
2638 case LibFunc_asin:
2639 case LibFunc_asinh:
2640 case LibFunc_atan:
2641 case LibFunc_atanh:
2642 case LibFunc_cbrt:
2643 case LibFunc_cosh:
2644 case LibFunc_exp:
2645 case LibFunc_exp10:
2646 case LibFunc_expm1:
Sanjay Patele45a83d2018-08-13 19:24:41 +00002647 case LibFunc_cos:
Andrew Kaylor53a5fbb2017-08-14 21:15:13 +00002648 case LibFunc_sin:
2649 case LibFunc_sinh:
2650 case LibFunc_tanh:
2651 if (UnsafeFPShrink && hasFloatVersion(CI->getCalledFunction()->getName()))
2652 return optimizeUnaryDoubleFP(CI, Builder, true);
2653 return nullptr;
2654 case LibFunc_copysign:
2655 if (hasFloatVersion(CI->getCalledFunction()->getName()))
2656 return optimizeBinaryDoubleFP(CI, Builder);
2657 return nullptr;
2658 case LibFunc_fminf:
2659 case LibFunc_fmin:
2660 case LibFunc_fminl:
2661 case LibFunc_fmaxf:
2662 case LibFunc_fmax:
2663 case LibFunc_fmaxl:
2664 return optimizeFMinFMax(CI, Builder);
Hal Finkel2ff24732017-12-16 01:26:25 +00002665 case LibFunc_cabs:
2666 case LibFunc_cabsf:
2667 case LibFunc_cabsl:
2668 return optimizeCAbs(CI, Builder);
Andrew Kaylor53a5fbb2017-08-14 21:15:13 +00002669 default:
2670 return nullptr;
2671 }
2672}
2673
Chris Bienemanad070d02014-09-17 20:55:46 +00002674Value *LibCallSimplifier::optimizeCall(CallInst *CI) {
Andrew Kaylor53a5fbb2017-08-14 21:15:13 +00002675 // TODO: Split out the code below that operates on FP calls so that
2676 // we can all non-FP calls with the StrictFP attribute to be
2677 // optimized.
Chris Bienemanad070d02014-09-17 20:55:46 +00002678 if (CI->isNoBuiltin())
2679 return nullptr;
Meador Inge4d2827c2012-11-11 05:11:20 +00002680
David L. Jonesd21529f2017-01-23 23:16:46 +00002681 LibFunc Func;
Meador Inge20255ef2013-03-12 00:08:29 +00002682 Function *Callee = CI->getCalledFunction();
David Majnemerb70e23c2016-01-06 05:01:34 +00002683
2684 SmallVector<OperandBundleDef, 2> OpBundles;
2685 CI->getOperandBundlesAsDefs(OpBundles);
2686 IRBuilder<> Builder(CI, /*FPMathTag=*/nullptr, OpBundles);
Sam Parker214f7bf2016-09-13 12:10:14 +00002687 bool isCallingConvC = isCallingConvCCompatible(CI);
Meador Inge20255ef2013-03-12 00:08:29 +00002688
Sanjay Pateld1f4f032016-01-19 18:38:52 +00002689 // Command-line parameter overrides instruction attribute.
Andrew Kaylor53a5fbb2017-08-14 21:15:13 +00002690 // This can't be moved to optimizeFloatingPointLibCall() because it may be
Sanjay Patel629c4112017-11-06 16:27:15 +00002691 // used by the intrinsic optimizations.
Sanjay Patela92fa442014-10-22 15:29:23 +00002692 if (EnableUnsafeFPShrink.getNumOccurrences() > 0)
2693 UnsafeFPShrink = EnableUnsafeFPShrink;
Sanjay Patel629c4112017-11-06 16:27:15 +00002694 else if (isa<FPMathOperator>(CI) && CI->isFast())
Davide Italianoa904e522015-10-29 02:58:44 +00002695 UnsafeFPShrink = true;
Sanjay Patela92fa442014-10-22 15:29:23 +00002696
Sanjay Patel848309d2014-10-23 21:52:45 +00002697 // First, check for intrinsics.
Meador Inge20255ef2013-03-12 00:08:29 +00002698 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(CI)) {
Chris Bienemanad070d02014-09-17 20:55:46 +00002699 if (!isCallingConvC)
2700 return nullptr;
Andrew Kaylor53a5fbb2017-08-14 21:15:13 +00002701 // The FP intrinsics have corresponding constrained versions so we don't
2702 // need to check for the StrictFP attribute here.
Meador Inge20255ef2013-03-12 00:08:29 +00002703 switch (II->getIntrinsicID()) {
2704 case Intrinsic::pow:
Chris Bienemanad070d02014-09-17 20:55:46 +00002705 return optimizePow(CI, Builder);
Meador Inge20255ef2013-03-12 00:08:29 +00002706 case Intrinsic::exp2:
Chris Bienemanad070d02014-09-17 20:55:46 +00002707 return optimizeExp2(CI, Builder);
Davide Italianob8b71332015-11-29 20:58:04 +00002708 case Intrinsic::log:
2709 return optimizeLog(CI, Builder);
Sanjay Patelc699a612014-10-16 18:48:17 +00002710 case Intrinsic::sqrt:
2711 return optimizeSqrt(CI, Builder);
Sanjay Patel980b2802016-01-26 16:17:24 +00002712 // TODO: Use foldMallocMemset() with memset intrinsic.
Meador Inge20255ef2013-03-12 00:08:29 +00002713 default:
Chris Bienemanad070d02014-09-17 20:55:46 +00002714 return nullptr;
Meador Inge20255ef2013-03-12 00:08:29 +00002715 }
2716 }
2717
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002718 // Also try to simplify calls to fortified library functions.
2719 if (Value *SimplifiedFortifiedCI = FortifiedSimplifier.optimizeCall(CI)) {
2720 // Try to further simplify the result.
Ahmed Bougacha71d7b182015-01-14 00:55:05 +00002721 CallInst *SimplifiedCI = dyn_cast<CallInst>(SimplifiedFortifiedCI);
Bruno Cardoso Lopesb491a2d2015-10-01 22:43:53 +00002722 if (SimplifiedCI && SimplifiedCI->getCalledFunction()) {
2723 // Use an IR Builder from SimplifiedCI if available instead of CI
2724 // to guarantee we reach all uses we might replace later on.
2725 IRBuilder<> TmpBuilder(SimplifiedCI);
2726 if (Value *V = optimizeStringMemoryLibCall(SimplifiedCI, TmpBuilder)) {
Ahmed Bougacha1ac93562015-01-27 21:52:16 +00002727 // If we were able to further simplify, remove the now redundant call.
2728 SimplifiedCI->replaceAllUsesWith(V);
Amara Emerson54f60252018-10-11 14:51:11 +00002729 eraseFromParent(SimplifiedCI);
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002730 return V;
Ahmed Bougacha1ac93562015-01-27 21:52:16 +00002731 }
Bruno Cardoso Lopesb491a2d2015-10-01 22:43:53 +00002732 }
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002733 return SimplifiedFortifiedCI;
2734 }
2735
Meador Inge20255ef2013-03-12 00:08:29 +00002736 // Then check for known library functions.
Ahmed Bougachad765a822016-04-27 19:04:35 +00002737 if (TLI->getLibFunc(*Callee, Func) && TLI->has(Func)) {
Chris Bienemanad070d02014-09-17 20:55:46 +00002738 // We never change the calling convention.
2739 if (!ignoreCallingConv(Func) && !isCallingConvC)
2740 return nullptr;
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00002741 if (Value *V = optimizeStringMemoryLibCall(CI, Builder))
2742 return V;
Andrew Kaylor53a5fbb2017-08-14 21:15:13 +00002743 if (Value *V = optimizeFloatingPointLibCall(CI, Func, Builder))
2744 return V;
Meador Inge20255ef2013-03-12 00:08:29 +00002745 switch (Func) {
David L. Jonesd21529f2017-01-23 23:16:46 +00002746 case LibFunc_ffs:
2747 case LibFunc_ffsl:
2748 case LibFunc_ffsll:
Chris Bienemanad070d02014-09-17 20:55:46 +00002749 return optimizeFFS(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002750 case LibFunc_fls:
2751 case LibFunc_flsl:
2752 case LibFunc_flsll:
Davide Italiano85ad36b2016-12-15 23:45:11 +00002753 return optimizeFls(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002754 case LibFunc_abs:
2755 case LibFunc_labs:
2756 case LibFunc_llabs:
Chris Bienemanad070d02014-09-17 20:55:46 +00002757 return optimizeAbs(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002758 case LibFunc_isdigit:
Chris Bienemanad070d02014-09-17 20:55:46 +00002759 return optimizeIsDigit(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002760 case LibFunc_isascii:
Chris Bienemanad070d02014-09-17 20:55:46 +00002761 return optimizeIsAscii(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002762 case LibFunc_toascii:
Chris Bienemanad070d02014-09-17 20:55:46 +00002763 return optimizeToAscii(CI, Builder);
David Bolvanskycb8ca5f32018-04-25 18:58:53 +00002764 case LibFunc_atoi:
2765 case LibFunc_atol:
2766 case LibFunc_atoll:
2767 return optimizeAtoi(CI, Builder);
2768 case LibFunc_strtol:
2769 case LibFunc_strtoll:
2770 return optimizeStrtol(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002771 case LibFunc_printf:
Chris Bienemanad070d02014-09-17 20:55:46 +00002772 return optimizePrintF(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002773 case LibFunc_sprintf:
Chris Bienemanad070d02014-09-17 20:55:46 +00002774 return optimizeSPrintF(CI, Builder);
David Bolvanskycd93c4e2018-05-11 17:50:49 +00002775 case LibFunc_snprintf:
2776 return optimizeSnPrintF(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002777 case LibFunc_fprintf:
Chris Bienemanad070d02014-09-17 20:55:46 +00002778 return optimizeFPrintF(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002779 case LibFunc_fwrite:
Chris Bienemanad070d02014-09-17 20:55:46 +00002780 return optimizeFWrite(CI, Builder);
David Bolvanskyca22d422018-05-16 11:39:52 +00002781 case LibFunc_fread:
2782 return optimizeFRead(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002783 case LibFunc_fputs:
Chris Bienemanad070d02014-09-17 20:55:46 +00002784 return optimizeFPuts(CI, Builder);
David Bolvanskyca22d422018-05-16 11:39:52 +00002785 case LibFunc_fgets:
2786 return optimizeFGets(CI, Builder);
2787 case LibFunc_fputc:
2788 return optimizeFPutc(CI, Builder);
2789 case LibFunc_fgetc:
2790 return optimizeFGetc(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002791 case LibFunc_puts:
Chris Bienemanad070d02014-09-17 20:55:46 +00002792 return optimizePuts(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002793 case LibFunc_perror:
Chris Bienemanad070d02014-09-17 20:55:46 +00002794 return optimizeErrorReporting(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002795 case LibFunc_vfprintf:
2796 case LibFunc_fiprintf:
Chris Bienemanad070d02014-09-17 20:55:46 +00002797 return optimizeErrorReporting(CI, Builder, 0);
Chris Bienemanad070d02014-09-17 20:55:46 +00002798 default:
2799 return nullptr;
2800 }
Meador Inge20255ef2013-03-12 00:08:29 +00002801 }
Craig Topperf40110f2014-04-25 05:29:35 +00002802 return nullptr;
Meador Ingedf796f82012-10-13 16:45:24 +00002803}
2804
Chandler Carruth92803822015-01-21 02:11:59 +00002805LibCallSimplifier::LibCallSimplifier(
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002806 const DataLayout &DL, const TargetLibraryInfo *TLI,
Adam Nemetea06e6e2017-07-26 19:03:18 +00002807 OptimizationRemarkEmitter &ORE,
Hiroshi Yamauchi09e539f2019-04-15 16:49:00 +00002808 BlockFrequencyInfo *BFI, ProfileSummaryInfo *PSI,
Amara Emerson54f60252018-10-11 14:51:11 +00002809 function_ref<void(Instruction *, Value *)> Replacer,
2810 function_ref<void(Instruction *)> Eraser)
Hiroshi Yamauchi09e539f2019-04-15 16:49:00 +00002811 : FortifiedSimplifier(TLI), DL(DL), TLI(TLI), ORE(ORE), BFI(BFI), PSI(PSI),
Amara Emerson54f60252018-10-11 14:51:11 +00002812 UnsafeFPShrink(false), Replacer(Replacer), Eraser(Eraser) {}
Chandler Carruth92803822015-01-21 02:11:59 +00002813
2814void LibCallSimplifier::replaceAllUsesWith(Instruction *I, Value *With) {
2815 // Indirect through the replacer used in this instance.
2816 Replacer(I, With);
Meador Ingedf796f82012-10-13 16:45:24 +00002817}
2818
Amara Emerson54f60252018-10-11 14:51:11 +00002819void LibCallSimplifier::eraseFromParent(Instruction *I) {
2820 Eraser(I);
2821}
2822
Meador Ingedfb08a22013-06-20 19:48:07 +00002823// TODO:
2824// Additional cases that we need to add to this file:
2825//
2826// cbrt:
2827// * cbrt(expN(X)) -> expN(x/3)
2828// * cbrt(sqrt(x)) -> pow(x,1/6)
David Majnemer3354fe42015-08-26 18:30:16 +00002829// * cbrt(cbrt(x)) -> pow(x,1/9)
Meador Ingedfb08a22013-06-20 19:48:07 +00002830//
2831// exp, expf, expl:
2832// * exp(log(x)) -> x
2833//
2834// log, logf, logl:
2835// * log(exp(x)) -> x
Meador Ingedfb08a22013-06-20 19:48:07 +00002836// * log(exp(y)) -> y*log(e)
Meador Ingedfb08a22013-06-20 19:48:07 +00002837// * log(exp10(y)) -> y*log(10)
2838// * log(sqrt(x)) -> 0.5*log(x)
Meador Ingedfb08a22013-06-20 19:48:07 +00002839//
Meador Ingedfb08a22013-06-20 19:48:07 +00002840// pow, powf, powl:
Meador Ingedfb08a22013-06-20 19:48:07 +00002841// * pow(sqrt(x),y) -> pow(x,y*0.5)
2842// * pow(pow(x,y),z)-> pow(x,y*z)
2843//
Meador Ingedfb08a22013-06-20 19:48:07 +00002844// signbit:
2845// * signbit(cnst) -> cnst'
2846// * signbit(nncst) -> 0 (if pstv is a non-negative constant)
2847//
2848// sqrt, sqrtf, sqrtl:
2849// * sqrt(expN(x)) -> expN(x*0.5)
2850// * sqrt(Nroot(x)) -> pow(x,1/(2*N))
2851// * sqrt(pow(x,y)) -> pow(|x|,y*0.5)
2852//
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002853
2854//===----------------------------------------------------------------------===//
2855// Fortified Library Call Optimizations
2856//===----------------------------------------------------------------------===//
2857
Erik Pilkingtonabb2a932019-05-31 22:41:36 +00002858bool
2859FortifiedLibCallSimplifier::isFortifiedCallFoldable(CallInst *CI,
2860 unsigned ObjSizeOp,
2861 Optional<unsigned> SizeOp,
2862 Optional<unsigned> StrOp,
2863 Optional<unsigned> FlagOp) {
2864 // If this function takes a flag argument, the implementation may use it to
2865 // perform extra checks. Don't fold into the non-checking variant.
2866 if (FlagOp) {
2867 ConstantInt *Flag = dyn_cast<ConstantInt>(CI->getArgOperand(*FlagOp));
2868 if (!Flag || !Flag->isZero())
2869 return false;
2870 }
2871
2872 if (SizeOp && CI->getArgOperand(ObjSizeOp) == CI->getArgOperand(*SizeOp))
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002873 return true;
Erik Pilkingtonabb2a932019-05-31 22:41:36 +00002874
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002875 if (ConstantInt *ObjSizeCI =
2876 dyn_cast<ConstantInt>(CI->getArgOperand(ObjSizeOp))) {
Craig Topper79ab6432017-07-06 18:39:47 +00002877 if (ObjSizeCI->isMinusOne())
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002878 return true;
2879 // If the object size wasn't -1 (unknown), bail out if we were asked to.
2880 if (OnlyLowerUnknownSize)
2881 return false;
Erik Pilkingtonabb2a932019-05-31 22:41:36 +00002882 if (StrOp) {
2883 uint64_t Len = GetStringLength(CI->getArgOperand(*StrOp));
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002884 // If the length is 0 we don't know how long it is and so we can't
2885 // remove the check.
2886 if (Len == 0)
2887 return false;
2888 return ObjSizeCI->getZExtValue() >= Len;
2889 }
Erik Pilkingtonabb2a932019-05-31 22:41:36 +00002890
2891 if (SizeOp) {
2892 if (ConstantInt *SizeCI =
2893 dyn_cast<ConstantInt>(CI->getArgOperand(*SizeOp)))
2894 return ObjSizeCI->getZExtValue() >= SizeCI->getZExtValue();
2895 }
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002896 }
2897 return false;
2898}
2899
Sanjay Pateld707db92015-12-31 16:10:49 +00002900Value *FortifiedLibCallSimplifier::optimizeMemCpyChk(CallInst *CI,
2901 IRBuilder<> &B) {
Erik Pilkingtonabb2a932019-05-31 22:41:36 +00002902 if (isFortifiedCallFoldable(CI, 3, 2)) {
Daniel Neilson8acd8b02018-02-05 21:23:22 +00002903 B.CreateMemCpy(CI->getArgOperand(0), 1, CI->getArgOperand(1), 1,
2904 CI->getArgOperand(2));
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002905 return CI->getArgOperand(0);
2906 }
2907 return nullptr;
2908}
2909
Sanjay Pateld707db92015-12-31 16:10:49 +00002910Value *FortifiedLibCallSimplifier::optimizeMemMoveChk(CallInst *CI,
2911 IRBuilder<> &B) {
Erik Pilkingtonabb2a932019-05-31 22:41:36 +00002912 if (isFortifiedCallFoldable(CI, 3, 2)) {
Daniel Neilson8acd8b02018-02-05 21:23:22 +00002913 B.CreateMemMove(CI->getArgOperand(0), 1, CI->getArgOperand(1), 1,
2914 CI->getArgOperand(2));
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002915 return CI->getArgOperand(0);
2916 }
2917 return nullptr;
2918}
2919
Sanjay Pateld707db92015-12-31 16:10:49 +00002920Value *FortifiedLibCallSimplifier::optimizeMemSetChk(CallInst *CI,
2921 IRBuilder<> &B) {
Sanjay Patel980b2802016-01-26 16:17:24 +00002922 // TODO: Try foldMallocMemset() here.
2923
Erik Pilkingtonabb2a932019-05-31 22:41:36 +00002924 if (isFortifiedCallFoldable(CI, 3, 2)) {
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002925 Value *Val = B.CreateIntCast(CI->getArgOperand(1), B.getInt8Ty(), false);
2926 B.CreateMemSet(CI->getArgOperand(0), Val, CI->getArgOperand(2), 1);
2927 return CI->getArgOperand(0);
2928 }
2929 return nullptr;
2930}
2931
Ahmed Bougacha1ac93562015-01-27 21:52:16 +00002932Value *FortifiedLibCallSimplifier::optimizeStrpCpyChk(CallInst *CI,
2933 IRBuilder<> &B,
David L. Jonesd21529f2017-01-23 23:16:46 +00002934 LibFunc Func) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002935 const DataLayout &DL = CI->getModule()->getDataLayout();
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002936 Value *Dst = CI->getArgOperand(0), *Src = CI->getArgOperand(1),
2937 *ObjSize = CI->getArgOperand(2);
2938
2939 // __stpcpy_chk(x,x,...) -> x+strlen(x)
David L. Jonesd21529f2017-01-23 23:16:46 +00002940 if (Func == LibFunc_stpcpy_chk && !OnlyLowerUnknownSize && Dst == Src) {
Sanjay Pateld3112a52016-01-19 19:46:10 +00002941 Value *StrLen = emitStrLen(Src, B, DL, TLI);
David Blaikieaa41cd52015-04-03 21:33:42 +00002942 return StrLen ? B.CreateInBoundsGEP(B.getInt8Ty(), Dst, StrLen) : nullptr;
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002943 }
2944
2945 // If a) we don't have any length information, or b) we know this will
2946 // fit then just lower to a plain st[rp]cpy. Otherwise we'll keep our
2947 // st[rp]cpy_chk call which may fail at runtime if the size is too long.
2948 // TODO: It might be nice to get a maximum length out of the possible
2949 // string lengths for varying.
Erik Pilkingtonabb2a932019-05-31 22:41:36 +00002950 if (isFortifiedCallFoldable(CI, 2, None, 1)) {
Erik Pilkington52349212019-05-31 22:41:31 +00002951 if (Func == LibFunc_strcpy_chk)
2952 return emitStrCpy(Dst, Src, B, TLI);
2953 else
2954 return emitStpCpy(Dst, Src, B, TLI);
2955 }
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002956
David Blaikie65fab6d2015-04-03 21:32:06 +00002957 if (OnlyLowerUnknownSize)
2958 return nullptr;
2959
2960 // Maybe we can stil fold __st[rp]cpy_chk to __memcpy_chk.
David Bolvansky1f343fa2018-05-22 20:27:36 +00002961 uint64_t Len = GetStringLength(Src);
David Blaikie65fab6d2015-04-03 21:32:06 +00002962 if (Len == 0)
2963 return nullptr;
2964
2965 Type *SizeTTy = DL.getIntPtrType(CI->getContext());
2966 Value *LenV = ConstantInt::get(SizeTTy, Len);
Sanjay Pateld3112a52016-01-19 19:46:10 +00002967 Value *Ret = emitMemCpyChk(Dst, Src, LenV, ObjSize, B, DL, TLI);
David Blaikie65fab6d2015-04-03 21:32:06 +00002968 // If the function was an __stpcpy_chk, and we were able to fold it into
2969 // a __memcpy_chk, we still need to return the correct end pointer.
David L. Jonesd21529f2017-01-23 23:16:46 +00002970 if (Ret && Func == LibFunc_stpcpy_chk)
David Blaikie65fab6d2015-04-03 21:32:06 +00002971 return B.CreateGEP(B.getInt8Ty(), Dst, ConstantInt::get(SizeTTy, Len - 1));
2972 return Ret;
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002973}
2974
Ahmed Bougacha1ac93562015-01-27 21:52:16 +00002975Value *FortifiedLibCallSimplifier::optimizeStrpNCpyChk(CallInst *CI,
2976 IRBuilder<> &B,
David L. Jonesd21529f2017-01-23 23:16:46 +00002977 LibFunc Func) {
Erik Pilkingtonabb2a932019-05-31 22:41:36 +00002978 if (isFortifiedCallFoldable(CI, 3, 2)) {
Erik Pilkington52349212019-05-31 22:41:31 +00002979 if (Func == LibFunc_strncpy_chk)
2980 return emitStrNCpy(CI->getArgOperand(0), CI->getArgOperand(1),
Erik Pilkingtonabb2a932019-05-31 22:41:36 +00002981 CI->getArgOperand(2), B, TLI);
Erik Pilkington52349212019-05-31 22:41:31 +00002982 else
2983 return emitStpNCpy(CI->getArgOperand(0), CI->getArgOperand(1),
2984 CI->getArgOperand(2), B, TLI);
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002985 }
Erik Pilkington52349212019-05-31 22:41:31 +00002986
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002987 return nullptr;
2988}
2989
Erik Pilkingtonabb2a932019-05-31 22:41:36 +00002990Value *FortifiedLibCallSimplifier::optimizeMemCCpyChk(CallInst *CI,
2991 IRBuilder<> &B) {
2992 if (isFortifiedCallFoldable(CI, 4, 3))
2993 return emitMemCCpy(CI->getArgOperand(0), CI->getArgOperand(1),
2994 CI->getArgOperand(2), CI->getArgOperand(3), B, TLI);
2995
2996 return nullptr;
2997}
2998
2999Value *FortifiedLibCallSimplifier::optimizeSNPrintfChk(CallInst *CI,
3000 IRBuilder<> &B) {
3001 if (isFortifiedCallFoldable(CI, 3, 1, None, 2)) {
3002 SmallVector<Value *, 8> VariadicArgs(CI->arg_begin() + 5, CI->arg_end());
3003 return emitSNPrintf(CI->getArgOperand(0), CI->getArgOperand(1),
3004 CI->getArgOperand(4), VariadicArgs, B, TLI);
3005 }
3006
3007 return nullptr;
3008}
3009
3010Value *FortifiedLibCallSimplifier::optimizeSPrintfChk(CallInst *CI,
3011 IRBuilder<> &B) {
3012 if (isFortifiedCallFoldable(CI, 2, None, None, 1)) {
3013 SmallVector<Value *, 8> VariadicArgs(CI->arg_begin() + 4, CI->arg_end());
3014 return emitSPrintf(CI->getArgOperand(0), CI->getArgOperand(3), VariadicArgs,
3015 B, TLI);
3016 }
3017
3018 return nullptr;
3019}
3020
3021Value *FortifiedLibCallSimplifier::optimizeStrCatChk(CallInst *CI,
3022 IRBuilder<> &B) {
3023 if (isFortifiedCallFoldable(CI, 2))
3024 return emitStrCat(CI->getArgOperand(0), CI->getArgOperand(1), B, TLI);
3025
3026 return nullptr;
3027}
3028
3029Value *FortifiedLibCallSimplifier::optimizeStrLCat(CallInst *CI,
3030 IRBuilder<> &B) {
3031 if (isFortifiedCallFoldable(CI, 3))
3032 return emitStrLCat(CI->getArgOperand(0), CI->getArgOperand(1),
3033 CI->getArgOperand(2), B, TLI);
3034
3035 return nullptr;
3036}
3037
3038Value *FortifiedLibCallSimplifier::optimizeStrNCatChk(CallInst *CI,
3039 IRBuilder<> &B) {
3040 if (isFortifiedCallFoldable(CI, 3))
3041 return emitStrNCat(CI->getArgOperand(0), CI->getArgOperand(1),
3042 CI->getArgOperand(2), B, TLI);
3043
3044 return nullptr;
3045}
3046
3047Value *FortifiedLibCallSimplifier::optimizeStrLCpyChk(CallInst *CI,
3048 IRBuilder<> &B) {
3049 if (isFortifiedCallFoldable(CI, 3))
3050 return emitStrLCpy(CI->getArgOperand(0), CI->getArgOperand(1),
3051 CI->getArgOperand(2), B, TLI);
3052
3053 return nullptr;
3054}
3055
3056Value *FortifiedLibCallSimplifier::optimizeVSNPrintfChk(CallInst *CI,
3057 IRBuilder<> &B) {
3058 if (isFortifiedCallFoldable(CI, 3, 1, None, 2))
3059 return emitVSNPrintf(CI->getArgOperand(0), CI->getArgOperand(1),
3060 CI->getArgOperand(4), CI->getArgOperand(5), B, TLI);
3061
3062 return nullptr;
3063}
3064
3065Value *FortifiedLibCallSimplifier::optimizeVSPrintfChk(CallInst *CI,
3066 IRBuilder<> &B) {
3067 if (isFortifiedCallFoldable(CI, 2, None, None, 1))
3068 return emitVSPrintf(CI->getArgOperand(0), CI->getArgOperand(3),
3069 CI->getArgOperand(4), B, TLI);
3070
3071 return nullptr;
3072}
3073
Ahmed Bougachae03bef72015-01-12 17:22:43 +00003074Value *FortifiedLibCallSimplifier::optimizeCall(CallInst *CI) {
Ahmed Bougacha408d0102015-04-01 00:45:09 +00003075 // FIXME: We shouldn't be changing "nobuiltin" or TLI unavailable calls here.
3076 // Some clang users checked for _chk libcall availability using:
3077 // __has_builtin(__builtin___memcpy_chk)
3078 // When compiling with -fno-builtin, this is always true.
3079 // When passing -ffreestanding/-mkernel, which both imply -fno-builtin, we
3080 // end up with fortified libcalls, which isn't acceptable in a freestanding
3081 // environment which only provides their non-fortified counterparts.
3082 //
3083 // Until we change clang and/or teach external users to check for availability
3084 // differently, disregard the "nobuiltin" attribute and TLI::has.
3085 //
3086 // PR23093.
Ahmed Bougachae03bef72015-01-12 17:22:43 +00003087
David L. Jonesd21529f2017-01-23 23:16:46 +00003088 LibFunc Func;
Ahmed Bougachae03bef72015-01-12 17:22:43 +00003089 Function *Callee = CI->getCalledFunction();
David Majnemerb70e23c2016-01-06 05:01:34 +00003090
3091 SmallVector<OperandBundleDef, 2> OpBundles;
3092 CI->getOperandBundlesAsDefs(OpBundles);
3093 IRBuilder<> Builder(CI, /*FPMathTag=*/nullptr, OpBundles);
Sam Parker214f7bf2016-09-13 12:10:14 +00003094 bool isCallingConvC = isCallingConvCCompatible(CI);
Ahmed Bougachae03bef72015-01-12 17:22:43 +00003095
Ahmed Bougachad765a822016-04-27 19:04:35 +00003096 // First, check that this is a known library functions and that the prototype
3097 // is correct.
3098 if (!TLI->getLibFunc(*Callee, Func))
Ahmed Bougachae03bef72015-01-12 17:22:43 +00003099 return nullptr;
3100
3101 // We never change the calling convention.
3102 if (!ignoreCallingConv(Func) && !isCallingConvC)
3103 return nullptr;
3104
3105 switch (Func) {
David L. Jonesd21529f2017-01-23 23:16:46 +00003106 case LibFunc_memcpy_chk:
Ahmed Bougachae03bef72015-01-12 17:22:43 +00003107 return optimizeMemCpyChk(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00003108 case LibFunc_memmove_chk:
Ahmed Bougachae03bef72015-01-12 17:22:43 +00003109 return optimizeMemMoveChk(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00003110 case LibFunc_memset_chk:
Ahmed Bougachae03bef72015-01-12 17:22:43 +00003111 return optimizeMemSetChk(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00003112 case LibFunc_stpcpy_chk:
3113 case LibFunc_strcpy_chk:
Ahmed Bougacha1ac93562015-01-27 21:52:16 +00003114 return optimizeStrpCpyChk(CI, Builder, Func);
David L. Jonesd21529f2017-01-23 23:16:46 +00003115 case LibFunc_stpncpy_chk:
3116 case LibFunc_strncpy_chk:
Ahmed Bougacha1ac93562015-01-27 21:52:16 +00003117 return optimizeStrpNCpyChk(CI, Builder, Func);
Erik Pilkingtonabb2a932019-05-31 22:41:36 +00003118 case LibFunc_memccpy_chk:
3119 return optimizeMemCCpyChk(CI, Builder);
3120 case LibFunc_snprintf_chk:
3121 return optimizeSNPrintfChk(CI, Builder);
3122 case LibFunc_sprintf_chk:
3123 return optimizeSPrintfChk(CI, Builder);
3124 case LibFunc_strcat_chk:
3125 return optimizeStrCatChk(CI, Builder);
3126 case LibFunc_strlcat_chk:
3127 return optimizeStrLCat(CI, Builder);
3128 case LibFunc_strncat_chk:
3129 return optimizeStrNCatChk(CI, Builder);
3130 case LibFunc_strlcpy_chk:
3131 return optimizeStrLCpyChk(CI, Builder);
3132 case LibFunc_vsnprintf_chk:
3133 return optimizeVSNPrintfChk(CI, Builder);
3134 case LibFunc_vsprintf_chk:
3135 return optimizeVSPrintfChk(CI, Builder);
Ahmed Bougachae03bef72015-01-12 17:22:43 +00003136 default:
3137 break;
3138 }
3139 return nullptr;
3140}
3141
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003142FortifiedLibCallSimplifier::FortifiedLibCallSimplifier(
3143 const TargetLibraryInfo *TLI, bool OnlyLowerUnknownSize)
Evandro Menezesb2169262019-07-12 00:33:49 +00003144 : TLI(TLI), OnlyLowerUnknownSize(OnlyLowerUnknownSize) {}