Move ConstantExpr to 2.5 API.
[llvm/avr.git] / lib / Transforms / Scalar / SimplifyLibCalls.cpp
blobfef19f0ba0ea7ae8e176ed9619c75dc8bf7dc6c8
1 //===- SimplifyLibCalls.cpp - Optimize specific well-known library calls --===//
2 //
3 // The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file implements a simple pass that applies a variety of small
11 // optimizations for calls to specific well-known function calls (e.g. runtime
12 // library functions). For example, a call to the function "exit(3)" that
13 // occurs within the main() function can be transformed into a simple "return 3"
14 // instruction. Any optimization that takes this form (replace call to library
15 // function with simpler code that provides the same result) belongs in this
16 // file.
18 //===----------------------------------------------------------------------===//
20 #define DEBUG_TYPE "simplify-libcalls"
21 #include "llvm/Transforms/Scalar.h"
22 #include "llvm/Intrinsics.h"
23 #include "llvm/LLVMContext.h"
24 #include "llvm/Module.h"
25 #include "llvm/Pass.h"
26 #include "llvm/Support/IRBuilder.h"
27 #include "llvm/Analysis/ValueTracking.h"
28 #include "llvm/Target/TargetData.h"
29 #include "llvm/ADT/SmallPtrSet.h"
30 #include "llvm/ADT/StringMap.h"
31 #include "llvm/ADT/Statistic.h"
32 #include "llvm/Support/Compiler.h"
33 #include "llvm/Support/Debug.h"
34 #include "llvm/Support/raw_ostream.h"
35 #include "llvm/Config/config.h"
36 using namespace llvm;
38 STATISTIC(NumSimplified, "Number of library calls simplified");
39 STATISTIC(NumAnnotated, "Number of attributes added to library functions");
41 //===----------------------------------------------------------------------===//
42 // Optimizer Base Class
43 //===----------------------------------------------------------------------===//
45 /// This class is the abstract base class for the set of optimizations that
46 /// corresponds to one library call.
47 namespace {
48 class VISIBILITY_HIDDEN LibCallOptimization {
49 protected:
50 Function *Caller;
51 const TargetData *TD;
52 LLVMContext* Context;
53 public:
54 LibCallOptimization() { }
55 virtual ~LibCallOptimization() {}
57 /// CallOptimizer - This pure virtual method is implemented by base classes to
58 /// do various optimizations. If this returns null then no transformation was
59 /// performed. If it returns CI, then it transformed the call and CI is to be
60 /// deleted. If it returns something else, replace CI with the new value and
61 /// delete CI.
62 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B)
63 =0;
65 Value *OptimizeCall(CallInst *CI, const TargetData &TD, IRBuilder<> &B) {
66 Caller = CI->getParent()->getParent();
67 this->TD = &TD;
68 if (CI->getCalledFunction())
69 Context = &CI->getCalledFunction()->getContext();
70 return CallOptimizer(CI->getCalledFunction(), CI, B);
73 /// CastToCStr - Return V if it is an i8*, otherwise cast it to i8*.
74 Value *CastToCStr(Value *V, IRBuilder<> &B);
76 /// EmitStrLen - Emit a call to the strlen function to the builder, for the
77 /// specified pointer. Ptr is required to be some pointer type, and the
78 /// return value has 'intptr_t' type.
79 Value *EmitStrLen(Value *Ptr, IRBuilder<> &B);
81 /// EmitMemCpy - Emit a call to the memcpy function to the builder. This
82 /// always expects that the size has type 'intptr_t' and Dst/Src are pointers.
83 Value *EmitMemCpy(Value *Dst, Value *Src, Value *Len,
84 unsigned Align, IRBuilder<> &B);
86 /// EmitMemChr - Emit a call to the memchr function. This assumes that Ptr is
87 /// a pointer, Val is an i32 value, and Len is an 'intptr_t' value.
88 Value *EmitMemChr(Value *Ptr, Value *Val, Value *Len, IRBuilder<> &B);
90 /// EmitMemCmp - Emit a call to the memcmp function.
91 Value *EmitMemCmp(Value *Ptr1, Value *Ptr2, Value *Len, IRBuilder<> &B);
93 /// EmitMemSet - Emit a call to the memset function
94 Value *EmitMemSet(Value *Dst, Value *Val, Value *Len, IRBuilder<> &B);
96 /// EmitUnaryFloatFnCall - Emit a call to the unary function named 'Name' (e.g.
97 /// 'floor'). This function is known to take a single of type matching 'Op'
98 /// and returns one value with the same type. If 'Op' is a long double, 'l'
99 /// is added as the suffix of name, if 'Op' is a float, we add a 'f' suffix.
100 Value *EmitUnaryFloatFnCall(Value *Op, const char *Name, IRBuilder<> &B);
102 /// EmitPutChar - Emit a call to the putchar function. This assumes that Char
103 /// is an integer.
104 void EmitPutChar(Value *Char, IRBuilder<> &B);
106 /// EmitPutS - Emit a call to the puts function. This assumes that Str is
107 /// some pointer.
108 void EmitPutS(Value *Str, IRBuilder<> &B);
110 /// EmitFPutC - Emit a call to the fputc function. This assumes that Char is
111 /// an i32, and File is a pointer to FILE.
112 void EmitFPutC(Value *Char, Value *File, IRBuilder<> &B);
114 /// EmitFPutS - Emit a call to the puts function. Str is required to be a
115 /// pointer and File is a pointer to FILE.
116 void EmitFPutS(Value *Str, Value *File, IRBuilder<> &B);
118 /// EmitFWrite - Emit a call to the fwrite function. This assumes that Ptr is
119 /// a pointer, Size is an 'intptr_t', and File is a pointer to FILE.
120 void EmitFWrite(Value *Ptr, Value *Size, Value *File, IRBuilder<> &B);
123 } // End anonymous namespace.
125 /// CastToCStr - Return V if it is an i8*, otherwise cast it to i8*.
126 Value *LibCallOptimization::CastToCStr(Value *V, IRBuilder<> &B) {
127 return
128 B.CreateBitCast(V, Context->getPointerTypeUnqual(Type::Int8Ty), "cstr");
131 /// EmitStrLen - Emit a call to the strlen function to the builder, for the
132 /// specified pointer. This always returns an integer value of size intptr_t.
133 Value *LibCallOptimization::EmitStrLen(Value *Ptr, IRBuilder<> &B) {
134 Module *M = Caller->getParent();
135 AttributeWithIndex AWI[2];
136 AWI[0] = AttributeWithIndex::get(1, Attribute::NoCapture);
137 AWI[1] = AttributeWithIndex::get(~0u, Attribute::ReadOnly |
138 Attribute::NoUnwind);
140 Constant *StrLen =M->getOrInsertFunction("strlen", AttrListPtr::get(AWI, 2),
141 TD->getIntPtrType(),
142 Context->getPointerTypeUnqual(Type::Int8Ty),
143 NULL);
144 CallInst *CI = B.CreateCall(StrLen, CastToCStr(Ptr, B), "strlen");
145 if (const Function *F = dyn_cast<Function>(StrLen->stripPointerCasts()))
146 CI->setCallingConv(F->getCallingConv());
148 return CI;
151 /// EmitMemCpy - Emit a call to the memcpy function to the builder. This always
152 /// expects that the size has type 'intptr_t' and Dst/Src are pointers.
153 Value *LibCallOptimization::EmitMemCpy(Value *Dst, Value *Src, Value *Len,
154 unsigned Align, IRBuilder<> &B) {
155 Module *M = Caller->getParent();
156 Intrinsic::ID IID = Intrinsic::memcpy;
157 const Type *Tys[1];
158 Tys[0] = Len->getType();
159 Value *MemCpy = Intrinsic::getDeclaration(M, IID, Tys, 1);
160 return B.CreateCall4(MemCpy, CastToCStr(Dst, B), CastToCStr(Src, B), Len,
161 ConstantInt::get(Type::Int32Ty, Align));
164 /// EmitMemChr - Emit a call to the memchr function. This assumes that Ptr is
165 /// a pointer, Val is an i32 value, and Len is an 'intptr_t' value.
166 Value *LibCallOptimization::EmitMemChr(Value *Ptr, Value *Val,
167 Value *Len, IRBuilder<> &B) {
168 Module *M = Caller->getParent();
169 AttributeWithIndex AWI;
170 AWI = AttributeWithIndex::get(~0u, Attribute::ReadOnly | Attribute::NoUnwind);
172 Value *MemChr = M->getOrInsertFunction("memchr", AttrListPtr::get(&AWI, 1),
173 Context->getPointerTypeUnqual(Type::Int8Ty),
174 Context->getPointerTypeUnqual(Type::Int8Ty),
175 Type::Int32Ty, TD->getIntPtrType(),
176 NULL);
177 CallInst *CI = B.CreateCall3(MemChr, CastToCStr(Ptr, B), Val, Len, "memchr");
179 if (const Function *F = dyn_cast<Function>(MemChr->stripPointerCasts()))
180 CI->setCallingConv(F->getCallingConv());
182 return CI;
185 /// EmitMemCmp - Emit a call to the memcmp function.
186 Value *LibCallOptimization::EmitMemCmp(Value *Ptr1, Value *Ptr2,
187 Value *Len, IRBuilder<> &B) {
188 Module *M = Caller->getParent();
189 AttributeWithIndex AWI[3];
190 AWI[0] = AttributeWithIndex::get(1, Attribute::NoCapture);
191 AWI[1] = AttributeWithIndex::get(2, Attribute::NoCapture);
192 AWI[2] = AttributeWithIndex::get(~0u, Attribute::ReadOnly |
193 Attribute::NoUnwind);
195 Value *MemCmp = M->getOrInsertFunction("memcmp", AttrListPtr::get(AWI, 3),
196 Type::Int32Ty,
197 Context->getPointerTypeUnqual(Type::Int8Ty),
198 Context->getPointerTypeUnqual(Type::Int8Ty),
199 TD->getIntPtrType(), NULL);
200 CallInst *CI = B.CreateCall3(MemCmp, CastToCStr(Ptr1, B), CastToCStr(Ptr2, B),
201 Len, "memcmp");
203 if (const Function *F = dyn_cast<Function>(MemCmp->stripPointerCasts()))
204 CI->setCallingConv(F->getCallingConv());
206 return CI;
209 /// EmitMemSet - Emit a call to the memset function
210 Value *LibCallOptimization::EmitMemSet(Value *Dst, Value *Val,
211 Value *Len, IRBuilder<> &B) {
212 Module *M = Caller->getParent();
213 Intrinsic::ID IID = Intrinsic::memset;
214 const Type *Tys[1];
215 Tys[0] = Len->getType();
216 Value *MemSet = Intrinsic::getDeclaration(M, IID, Tys, 1);
217 Value *Align = ConstantInt::get(Type::Int32Ty, 1);
218 return B.CreateCall4(MemSet, CastToCStr(Dst, B), Val, Len, Align);
221 /// EmitUnaryFloatFnCall - Emit a call to the unary function named 'Name' (e.g.
222 /// 'floor'). This function is known to take a single of type matching 'Op' and
223 /// returns one value with the same type. If 'Op' is a long double, 'l' is
224 /// added as the suffix of name, if 'Op' is a float, we add a 'f' suffix.
225 Value *LibCallOptimization::EmitUnaryFloatFnCall(Value *Op, const char *Name,
226 IRBuilder<> &B) {
227 char NameBuffer[20];
228 if (Op->getType() != Type::DoubleTy) {
229 // If we need to add a suffix, copy into NameBuffer.
230 unsigned NameLen = strlen(Name);
231 assert(NameLen < sizeof(NameBuffer)-2);
232 memcpy(NameBuffer, Name, NameLen);
233 if (Op->getType() == Type::FloatTy)
234 NameBuffer[NameLen] = 'f'; // floorf
235 else
236 NameBuffer[NameLen] = 'l'; // floorl
237 NameBuffer[NameLen+1] = 0;
238 Name = NameBuffer;
241 Module *M = Caller->getParent();
242 Value *Callee = M->getOrInsertFunction(Name, Op->getType(),
243 Op->getType(), NULL);
244 CallInst *CI = B.CreateCall(Callee, Op, Name);
246 if (const Function *F = dyn_cast<Function>(Callee->stripPointerCasts()))
247 CI->setCallingConv(F->getCallingConv());
249 return CI;
252 /// EmitPutChar - Emit a call to the putchar function. This assumes that Char
253 /// is an integer.
254 void LibCallOptimization::EmitPutChar(Value *Char, IRBuilder<> &B) {
255 Module *M = Caller->getParent();
256 Value *PutChar = M->getOrInsertFunction("putchar", Type::Int32Ty,
257 Type::Int32Ty, NULL);
258 CallInst *CI = B.CreateCall(PutChar,
259 B.CreateIntCast(Char, Type::Int32Ty, "chari"),
260 "putchar");
262 if (const Function *F = dyn_cast<Function>(PutChar->stripPointerCasts()))
263 CI->setCallingConv(F->getCallingConv());
266 /// EmitPutS - Emit a call to the puts function. This assumes that Str is
267 /// some pointer.
268 void LibCallOptimization::EmitPutS(Value *Str, IRBuilder<> &B) {
269 Module *M = Caller->getParent();
270 AttributeWithIndex AWI[2];
271 AWI[0] = AttributeWithIndex::get(1, Attribute::NoCapture);
272 AWI[1] = AttributeWithIndex::get(~0u, Attribute::NoUnwind);
274 Value *PutS = M->getOrInsertFunction("puts", AttrListPtr::get(AWI, 2),
275 Type::Int32Ty,
276 Context->getPointerTypeUnqual(Type::Int8Ty),
277 NULL);
278 CallInst *CI = B.CreateCall(PutS, CastToCStr(Str, B), "puts");
279 if (const Function *F = dyn_cast<Function>(PutS->stripPointerCasts()))
280 CI->setCallingConv(F->getCallingConv());
284 /// EmitFPutC - Emit a call to the fputc function. This assumes that Char is
285 /// an integer and File is a pointer to FILE.
286 void LibCallOptimization::EmitFPutC(Value *Char, Value *File, IRBuilder<> &B) {
287 Module *M = Caller->getParent();
288 AttributeWithIndex AWI[2];
289 AWI[0] = AttributeWithIndex::get(2, Attribute::NoCapture);
290 AWI[1] = AttributeWithIndex::get(~0u, Attribute::NoUnwind);
291 Constant *F;
292 if (isa<PointerType>(File->getType()))
293 F = M->getOrInsertFunction("fputc", AttrListPtr::get(AWI, 2), Type::Int32Ty,
294 Type::Int32Ty, File->getType(), NULL);
295 else
296 F = M->getOrInsertFunction("fputc", Type::Int32Ty, Type::Int32Ty,
297 File->getType(), NULL);
298 Char = B.CreateIntCast(Char, Type::Int32Ty, "chari");
299 CallInst *CI = B.CreateCall2(F, Char, File, "fputc");
301 if (const Function *Fn = dyn_cast<Function>(F->stripPointerCasts()))
302 CI->setCallingConv(Fn->getCallingConv());
305 /// EmitFPutS - Emit a call to the puts function. Str is required to be a
306 /// pointer and File is a pointer to FILE.
307 void LibCallOptimization::EmitFPutS(Value *Str, Value *File, IRBuilder<> &B) {
308 Module *M = Caller->getParent();
309 AttributeWithIndex AWI[3];
310 AWI[0] = AttributeWithIndex::get(1, Attribute::NoCapture);
311 AWI[1] = AttributeWithIndex::get(2, Attribute::NoCapture);
312 AWI[2] = AttributeWithIndex::get(~0u, Attribute::NoUnwind);
313 Constant *F;
314 if (isa<PointerType>(File->getType()))
315 F = M->getOrInsertFunction("fputs", AttrListPtr::get(AWI, 3), Type::Int32Ty,
316 Context->getPointerTypeUnqual(Type::Int8Ty),
317 File->getType(), NULL);
318 else
319 F = M->getOrInsertFunction("fputs", Type::Int32Ty,
320 Context->getPointerTypeUnqual(Type::Int8Ty),
321 File->getType(), NULL);
322 CallInst *CI = B.CreateCall2(F, CastToCStr(Str, B), File, "fputs");
324 if (const Function *Fn = dyn_cast<Function>(F->stripPointerCasts()))
325 CI->setCallingConv(Fn->getCallingConv());
328 /// EmitFWrite - Emit a call to the fwrite function. This assumes that Ptr is
329 /// a pointer, Size is an 'intptr_t', and File is a pointer to FILE.
330 void LibCallOptimization::EmitFWrite(Value *Ptr, Value *Size, Value *File,
331 IRBuilder<> &B) {
332 Module *M = Caller->getParent();
333 AttributeWithIndex AWI[3];
334 AWI[0] = AttributeWithIndex::get(1, Attribute::NoCapture);
335 AWI[1] = AttributeWithIndex::get(4, Attribute::NoCapture);
336 AWI[2] = AttributeWithIndex::get(~0u, Attribute::NoUnwind);
337 Constant *F;
338 if (isa<PointerType>(File->getType()))
339 F = M->getOrInsertFunction("fwrite", AttrListPtr::get(AWI, 3),
340 TD->getIntPtrType(),
341 Context->getPointerTypeUnqual(Type::Int8Ty),
342 TD->getIntPtrType(), TD->getIntPtrType(),
343 File->getType(), NULL);
344 else
345 F = M->getOrInsertFunction("fwrite", TD->getIntPtrType(),
346 Context->getPointerTypeUnqual(Type::Int8Ty),
347 TD->getIntPtrType(), TD->getIntPtrType(),
348 File->getType(), NULL);
349 CallInst *CI = B.CreateCall4(F, CastToCStr(Ptr, B), Size,
350 ConstantInt::get(TD->getIntPtrType(), 1), File);
352 if (const Function *Fn = dyn_cast<Function>(F->stripPointerCasts()))
353 CI->setCallingConv(Fn->getCallingConv());
356 //===----------------------------------------------------------------------===//
357 // Helper Functions
358 //===----------------------------------------------------------------------===//
360 /// GetStringLengthH - If we can compute the length of the string pointed to by
361 /// the specified pointer, return 'len+1'. If we can't, return 0.
362 static uint64_t GetStringLengthH(Value *V, SmallPtrSet<PHINode*, 32> &PHIs) {
363 // Look through noop bitcast instructions.
364 if (BitCastInst *BCI = dyn_cast<BitCastInst>(V))
365 return GetStringLengthH(BCI->getOperand(0), PHIs);
367 // If this is a PHI node, there are two cases: either we have already seen it
368 // or we haven't.
369 if (PHINode *PN = dyn_cast<PHINode>(V)) {
370 if (!PHIs.insert(PN))
371 return ~0ULL; // already in the set.
373 // If it was new, see if all the input strings are the same length.
374 uint64_t LenSoFar = ~0ULL;
375 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
376 uint64_t Len = GetStringLengthH(PN->getIncomingValue(i), PHIs);
377 if (Len == 0) return 0; // Unknown length -> unknown.
379 if (Len == ~0ULL) continue;
381 if (Len != LenSoFar && LenSoFar != ~0ULL)
382 return 0; // Disagree -> unknown.
383 LenSoFar = Len;
386 // Success, all agree.
387 return LenSoFar;
390 // strlen(select(c,x,y)) -> strlen(x) ^ strlen(y)
391 if (SelectInst *SI = dyn_cast<SelectInst>(V)) {
392 uint64_t Len1 = GetStringLengthH(SI->getTrueValue(), PHIs);
393 if (Len1 == 0) return 0;
394 uint64_t Len2 = GetStringLengthH(SI->getFalseValue(), PHIs);
395 if (Len2 == 0) return 0;
396 if (Len1 == ~0ULL) return Len2;
397 if (Len2 == ~0ULL) return Len1;
398 if (Len1 != Len2) return 0;
399 return Len1;
402 // If the value is not a GEP instruction nor a constant expression with a
403 // GEP instruction, then return unknown.
404 User *GEP = 0;
405 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(V)) {
406 GEP = GEPI;
407 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V)) {
408 if (CE->getOpcode() != Instruction::GetElementPtr)
409 return 0;
410 GEP = CE;
411 } else {
412 return 0;
415 // Make sure the GEP has exactly three arguments.
416 if (GEP->getNumOperands() != 3)
417 return 0;
419 // Check to make sure that the first operand of the GEP is an integer and
420 // has value 0 so that we are sure we're indexing into the initializer.
421 if (ConstantInt *Idx = dyn_cast<ConstantInt>(GEP->getOperand(1))) {
422 if (!Idx->isZero())
423 return 0;
424 } else
425 return 0;
427 // If the second index isn't a ConstantInt, then this is a variable index
428 // into the array. If this occurs, we can't say anything meaningful about
429 // the string.
430 uint64_t StartIdx = 0;
431 if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(2)))
432 StartIdx = CI->getZExtValue();
433 else
434 return 0;
436 // The GEP instruction, constant or instruction, must reference a global
437 // variable that is a constant and is initialized. The referenced constant
438 // initializer is the array that we'll use for optimization.
439 GlobalVariable* GV = dyn_cast<GlobalVariable>(GEP->getOperand(0));
440 if (!GV || !GV->isConstant() || !GV->hasInitializer())
441 return 0;
442 Constant *GlobalInit = GV->getInitializer();
444 // Handle the ConstantAggregateZero case, which is a degenerate case. The
445 // initializer is constant zero so the length of the string must be zero.
446 if (isa<ConstantAggregateZero>(GlobalInit))
447 return 1; // Len = 0 offset by 1.
449 // Must be a Constant Array
450 ConstantArray *Array = dyn_cast<ConstantArray>(GlobalInit);
451 if (!Array || Array->getType()->getElementType() != Type::Int8Ty)
452 return false;
454 // Get the number of elements in the array
455 uint64_t NumElts = Array->getType()->getNumElements();
457 // Traverse the constant array from StartIdx (derived above) which is
458 // the place the GEP refers to in the array.
459 for (unsigned i = StartIdx; i != NumElts; ++i) {
460 Constant *Elt = Array->getOperand(i);
461 ConstantInt *CI = dyn_cast<ConstantInt>(Elt);
462 if (!CI) // This array isn't suitable, non-int initializer.
463 return 0;
464 if (CI->isZero())
465 return i-StartIdx+1; // We found end of string, success!
468 return 0; // The array isn't null terminated, conservatively return 'unknown'.
471 /// GetStringLength - If we can compute the length of the string pointed to by
472 /// the specified pointer, return 'len+1'. If we can't, return 0.
473 static uint64_t GetStringLength(Value *V) {
474 if (!isa<PointerType>(V->getType())) return 0;
476 SmallPtrSet<PHINode*, 32> PHIs;
477 uint64_t Len = GetStringLengthH(V, PHIs);
478 // If Len is ~0ULL, we had an infinite phi cycle: this is dead code, so return
479 // an empty string as a length.
480 return Len == ~0ULL ? 1 : Len;
483 /// IsOnlyUsedInZeroEqualityComparison - Return true if it only matters that the
484 /// value is equal or not-equal to zero.
485 static bool IsOnlyUsedInZeroEqualityComparison(Value *V) {
486 for (Value::use_iterator UI = V->use_begin(), E = V->use_end();
487 UI != E; ++UI) {
488 if (ICmpInst *IC = dyn_cast<ICmpInst>(*UI))
489 if (IC->isEquality())
490 if (Constant *C = dyn_cast<Constant>(IC->getOperand(1)))
491 if (C->isNullValue())
492 continue;
493 // Unknown instruction.
494 return false;
496 return true;
499 //===----------------------------------------------------------------------===//
500 // Miscellaneous LibCall Optimizations
501 //===----------------------------------------------------------------------===//
503 namespace {
504 //===---------------------------------------===//
505 // 'exit' Optimizations
507 /// ExitOpt - int main() { exit(4); } --> int main() { return 4; }
508 struct VISIBILITY_HIDDEN ExitOpt : public LibCallOptimization {
509 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
510 // Verify we have a reasonable prototype for exit.
511 if (Callee->arg_size() == 0 || !CI->use_empty())
512 return 0;
514 // Verify the caller is main, and that the result type of main matches the
515 // argument type of exit.
516 if (Caller->getName() != "main" || !Caller->hasExternalLinkage() ||
517 Caller->getReturnType() != CI->getOperand(1)->getType())
518 return 0;
520 TerminatorInst *OldTI = CI->getParent()->getTerminator();
522 // Drop all successor phi node entries.
523 for (unsigned i = 0, e = OldTI->getNumSuccessors(); i != e; ++i)
524 OldTI->getSuccessor(i)->removePredecessor(CI->getParent());
526 // Split the basic block after the call to exit.
527 BasicBlock::iterator FirstDead = CI; ++FirstDead;
528 CI->getParent()->splitBasicBlock(FirstDead);
529 B.SetInsertPoint(B.GetInsertBlock());
531 // Remove the branch that splitBB created and insert a return instead.
532 CI->getParent()->getTerminator()->eraseFromParent();
533 B.CreateRet(CI->getOperand(1));
535 return CI;
539 //===----------------------------------------------------------------------===//
540 // String and Memory LibCall Optimizations
541 //===----------------------------------------------------------------------===//
543 //===---------------------------------------===//
544 // 'strcat' Optimizations
546 struct VISIBILITY_HIDDEN StrCatOpt : public LibCallOptimization {
547 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
548 // Verify the "strcat" function prototype.
549 const FunctionType *FT = Callee->getFunctionType();
550 if (FT->getNumParams() != 2 ||
551 FT->getReturnType() != Context->getPointerTypeUnqual(Type::Int8Ty) ||
552 FT->getParamType(0) != FT->getReturnType() ||
553 FT->getParamType(1) != FT->getReturnType())
554 return 0;
556 // Extract some information from the instruction
557 Value *Dst = CI->getOperand(1);
558 Value *Src = CI->getOperand(2);
560 // See if we can get the length of the input string.
561 uint64_t Len = GetStringLength(Src);
562 if (Len == 0) return 0;
563 --Len; // Unbias length.
565 // Handle the simple, do-nothing case: strcat(x, "") -> x
566 if (Len == 0)
567 return Dst;
569 EmitStrLenMemCpy(Src, Dst, Len, B);
570 return Dst;
573 void EmitStrLenMemCpy(Value *Src, Value *Dst, uint64_t Len, IRBuilder<> &B) {
574 // We need to find the end of the destination string. That's where the
575 // memory is to be moved to. We just generate a call to strlen.
576 Value *DstLen = EmitStrLen(Dst, B);
578 // Now that we have the destination's length, we must index into the
579 // destination's pointer to get the actual memcpy destination (end of
580 // the string .. we're concatenating).
581 Value *CpyDst = B.CreateGEP(Dst, DstLen, "endptr");
583 // We have enough information to now generate the memcpy call to do the
584 // concatenation for us. Make a memcpy to copy the nul byte with align = 1.
585 EmitMemCpy(CpyDst, Src,
586 ConstantInt::get(TD->getIntPtrType(), Len+1), 1, B);
590 //===---------------------------------------===//
591 // 'strncat' Optimizations
593 struct VISIBILITY_HIDDEN StrNCatOpt : public StrCatOpt {
594 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
595 // Verify the "strncat" function prototype.
596 const FunctionType *FT = Callee->getFunctionType();
597 if (FT->getNumParams() != 3 ||
598 FT->getReturnType() != Context->getPointerTypeUnqual(Type::Int8Ty) ||
599 FT->getParamType(0) != FT->getReturnType() ||
600 FT->getParamType(1) != FT->getReturnType() ||
601 !isa<IntegerType>(FT->getParamType(2)))
602 return 0;
604 // Extract some information from the instruction
605 Value *Dst = CI->getOperand(1);
606 Value *Src = CI->getOperand(2);
607 uint64_t Len;
609 // We don't do anything if length is not constant
610 if (ConstantInt *LengthArg = dyn_cast<ConstantInt>(CI->getOperand(3)))
611 Len = LengthArg->getZExtValue();
612 else
613 return 0;
615 // See if we can get the length of the input string.
616 uint64_t SrcLen = GetStringLength(Src);
617 if (SrcLen == 0) return 0;
618 --SrcLen; // Unbias length.
620 // Handle the simple, do-nothing cases:
621 // strncat(x, "", c) -> x
622 // strncat(x, c, 0) -> x
623 if (SrcLen == 0 || Len == 0) return Dst;
625 // We don't optimize this case
626 if (Len < SrcLen) return 0;
628 // strncat(x, s, c) -> strcat(x, s)
629 // s is constant so the strcat can be optimized further
630 EmitStrLenMemCpy(Src, Dst, SrcLen, B);
631 return Dst;
635 //===---------------------------------------===//
636 // 'strchr' Optimizations
638 struct VISIBILITY_HIDDEN StrChrOpt : public LibCallOptimization {
639 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
640 // Verify the "strchr" function prototype.
641 const FunctionType *FT = Callee->getFunctionType();
642 if (FT->getNumParams() != 2 ||
643 FT->getReturnType() != Context->getPointerTypeUnqual(Type::Int8Ty) ||
644 FT->getParamType(0) != FT->getReturnType())
645 return 0;
647 Value *SrcStr = CI->getOperand(1);
649 // If the second operand is non-constant, see if we can compute the length
650 // of the input string and turn this into memchr.
651 ConstantInt *CharC = dyn_cast<ConstantInt>(CI->getOperand(2));
652 if (CharC == 0) {
653 uint64_t Len = GetStringLength(SrcStr);
654 if (Len == 0 || FT->getParamType(1) != Type::Int32Ty) // memchr needs i32.
655 return 0;
657 return EmitMemChr(SrcStr, CI->getOperand(2), // include nul.
658 ConstantInt::get(TD->getIntPtrType(), Len), B);
661 // Otherwise, the character is a constant, see if the first argument is
662 // a string literal. If so, we can constant fold.
663 std::string Str;
664 if (!GetConstantStringInfo(SrcStr, Str))
665 return 0;
667 // strchr can find the nul character.
668 Str += '\0';
669 char CharValue = CharC->getSExtValue();
671 // Compute the offset.
672 uint64_t i = 0;
673 while (1) {
674 if (i == Str.size()) // Didn't find the char. strchr returns null.
675 return Context->getNullValue(CI->getType());
676 // Did we find our match?
677 if (Str[i] == CharValue)
678 break;
679 ++i;
682 // strchr(s+n,c) -> gep(s+n+i,c)
683 Value *Idx = ConstantInt::get(Type::Int64Ty, i);
684 return B.CreateGEP(SrcStr, Idx, "strchr");
688 //===---------------------------------------===//
689 // 'strcmp' Optimizations
691 struct VISIBILITY_HIDDEN StrCmpOpt : public LibCallOptimization {
692 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
693 // Verify the "strcmp" function prototype.
694 const FunctionType *FT = Callee->getFunctionType();
695 if (FT->getNumParams() != 2 || FT->getReturnType() != Type::Int32Ty ||
696 FT->getParamType(0) != FT->getParamType(1) ||
697 FT->getParamType(0) != Context->getPointerTypeUnqual(Type::Int8Ty))
698 return 0;
700 Value *Str1P = CI->getOperand(1), *Str2P = CI->getOperand(2);
701 if (Str1P == Str2P) // strcmp(x,x) -> 0
702 return ConstantInt::get(CI->getType(), 0);
704 std::string Str1, Str2;
705 bool HasStr1 = GetConstantStringInfo(Str1P, Str1);
706 bool HasStr2 = GetConstantStringInfo(Str2P, Str2);
708 if (HasStr1 && Str1.empty()) // strcmp("", x) -> *x
709 return B.CreateZExt(B.CreateLoad(Str2P, "strcmpload"), CI->getType());
711 if (HasStr2 && Str2.empty()) // strcmp(x,"") -> *x
712 return B.CreateZExt(B.CreateLoad(Str1P, "strcmpload"), CI->getType());
714 // strcmp(x, y) -> cnst (if both x and y are constant strings)
715 if (HasStr1 && HasStr2)
716 return ConstantInt::get(CI->getType(),
717 strcmp(Str1.c_str(),Str2.c_str()));
719 // strcmp(P, "x") -> memcmp(P, "x", 2)
720 uint64_t Len1 = GetStringLength(Str1P);
721 uint64_t Len2 = GetStringLength(Str2P);
722 if (Len1 && Len2) {
723 return EmitMemCmp(Str1P, Str2P,
724 ConstantInt::get(TD->getIntPtrType(),
725 std::min(Len1, Len2)), B);
728 return 0;
732 //===---------------------------------------===//
733 // 'strncmp' Optimizations
735 struct VISIBILITY_HIDDEN StrNCmpOpt : public LibCallOptimization {
736 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
737 // Verify the "strncmp" function prototype.
738 const FunctionType *FT = Callee->getFunctionType();
739 if (FT->getNumParams() != 3 || FT->getReturnType() != Type::Int32Ty ||
740 FT->getParamType(0) != FT->getParamType(1) ||
741 FT->getParamType(0) != Context->getPointerTypeUnqual(Type::Int8Ty) ||
742 !isa<IntegerType>(FT->getParamType(2)))
743 return 0;
745 Value *Str1P = CI->getOperand(1), *Str2P = CI->getOperand(2);
746 if (Str1P == Str2P) // strncmp(x,x,n) -> 0
747 return ConstantInt::get(CI->getType(), 0);
749 // Get the length argument if it is constant.
750 uint64_t Length;
751 if (ConstantInt *LengthArg = dyn_cast<ConstantInt>(CI->getOperand(3)))
752 Length = LengthArg->getZExtValue();
753 else
754 return 0;
756 if (Length == 0) // strncmp(x,y,0) -> 0
757 return ConstantInt::get(CI->getType(), 0);
759 std::string Str1, Str2;
760 bool HasStr1 = GetConstantStringInfo(Str1P, Str1);
761 bool HasStr2 = GetConstantStringInfo(Str2P, Str2);
763 if (HasStr1 && Str1.empty()) // strncmp("", x, n) -> *x
764 return B.CreateZExt(B.CreateLoad(Str2P, "strcmpload"), CI->getType());
766 if (HasStr2 && Str2.empty()) // strncmp(x, "", n) -> *x
767 return B.CreateZExt(B.CreateLoad(Str1P, "strcmpload"), CI->getType());
769 // strncmp(x, y) -> cnst (if both x and y are constant strings)
770 if (HasStr1 && HasStr2)
771 return ConstantInt::get(CI->getType(),
772 strncmp(Str1.c_str(), Str2.c_str(), Length));
773 return 0;
778 //===---------------------------------------===//
779 // 'strcpy' Optimizations
781 struct VISIBILITY_HIDDEN StrCpyOpt : public LibCallOptimization {
782 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
783 // Verify the "strcpy" function prototype.
784 const FunctionType *FT = Callee->getFunctionType();
785 if (FT->getNumParams() != 2 || FT->getReturnType() != FT->getParamType(0) ||
786 FT->getParamType(0) != FT->getParamType(1) ||
787 FT->getParamType(0) != Context->getPointerTypeUnqual(Type::Int8Ty))
788 return 0;
790 Value *Dst = CI->getOperand(1), *Src = CI->getOperand(2);
791 if (Dst == Src) // strcpy(x,x) -> x
792 return Src;
794 // See if we can get the length of the input string.
795 uint64_t Len = GetStringLength(Src);
796 if (Len == 0) return 0;
798 // We have enough information to now generate the memcpy call to do the
799 // concatenation for us. Make a memcpy to copy the nul byte with align = 1.
800 EmitMemCpy(Dst, Src,
801 ConstantInt::get(TD->getIntPtrType(), Len), 1, B);
802 return Dst;
806 //===---------------------------------------===//
807 // 'strncpy' Optimizations
809 struct VISIBILITY_HIDDEN StrNCpyOpt : public LibCallOptimization {
810 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
811 const FunctionType *FT = Callee->getFunctionType();
812 if (FT->getNumParams() != 3 || FT->getReturnType() != FT->getParamType(0) ||
813 FT->getParamType(0) != FT->getParamType(1) ||
814 FT->getParamType(0) != Context->getPointerTypeUnqual(Type::Int8Ty) ||
815 !isa<IntegerType>(FT->getParamType(2)))
816 return 0;
818 Value *Dst = CI->getOperand(1);
819 Value *Src = CI->getOperand(2);
820 Value *LenOp = CI->getOperand(3);
822 // See if we can get the length of the input string.
823 uint64_t SrcLen = GetStringLength(Src);
824 if (SrcLen == 0) return 0;
825 --SrcLen;
827 if (SrcLen == 0) {
828 // strncpy(x, "", y) -> memset(x, '\0', y, 1)
829 EmitMemSet(Dst, ConstantInt::get(Type::Int8Ty, '\0'), LenOp, B);
830 return Dst;
833 uint64_t Len;
834 if (ConstantInt *LengthArg = dyn_cast<ConstantInt>(LenOp))
835 Len = LengthArg->getZExtValue();
836 else
837 return 0;
839 if (Len == 0) return Dst; // strncpy(x, y, 0) -> x
841 // Let strncpy handle the zero padding
842 if (Len > SrcLen+1) return 0;
844 // strncpy(x, s, c) -> memcpy(x, s, c, 1) [s and c are constant]
845 EmitMemCpy(Dst, Src,
846 ConstantInt::get(TD->getIntPtrType(), Len), 1, B);
848 return Dst;
852 //===---------------------------------------===//
853 // 'strlen' Optimizations
855 struct VISIBILITY_HIDDEN StrLenOpt : public LibCallOptimization {
856 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
857 const FunctionType *FT = Callee->getFunctionType();
858 if (FT->getNumParams() != 1 ||
859 FT->getParamType(0) != Context->getPointerTypeUnqual(Type::Int8Ty) ||
860 !isa<IntegerType>(FT->getReturnType()))
861 return 0;
863 Value *Src = CI->getOperand(1);
865 // Constant folding: strlen("xyz") -> 3
866 if (uint64_t Len = GetStringLength(Src))
867 return ConstantInt::get(CI->getType(), Len-1);
869 // Handle strlen(p) != 0.
870 if (!IsOnlyUsedInZeroEqualityComparison(CI)) return 0;
872 // strlen(x) != 0 --> *x != 0
873 // strlen(x) == 0 --> *x == 0
874 return B.CreateZExt(B.CreateLoad(Src, "strlenfirst"), CI->getType());
878 //===---------------------------------------===//
879 // 'strto*' Optimizations
881 struct VISIBILITY_HIDDEN StrToOpt : public LibCallOptimization {
882 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
883 const FunctionType *FT = Callee->getFunctionType();
884 if ((FT->getNumParams() != 2 && FT->getNumParams() != 3) ||
885 !isa<PointerType>(FT->getParamType(0)) ||
886 !isa<PointerType>(FT->getParamType(1)))
887 return 0;
889 Value *EndPtr = CI->getOperand(2);
890 if (isa<ConstantPointerNull>(EndPtr)) {
891 CI->setOnlyReadsMemory();
892 CI->addAttribute(1, Attribute::NoCapture);
895 return 0;
900 //===---------------------------------------===//
901 // 'memcmp' Optimizations
903 struct VISIBILITY_HIDDEN MemCmpOpt : public LibCallOptimization {
904 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
905 const FunctionType *FT = Callee->getFunctionType();
906 if (FT->getNumParams() != 3 || !isa<PointerType>(FT->getParamType(0)) ||
907 !isa<PointerType>(FT->getParamType(1)) ||
908 FT->getReturnType() != Type::Int32Ty)
909 return 0;
911 Value *LHS = CI->getOperand(1), *RHS = CI->getOperand(2);
913 if (LHS == RHS) // memcmp(s,s,x) -> 0
914 return Context->getNullValue(CI->getType());
916 // Make sure we have a constant length.
917 ConstantInt *LenC = dyn_cast<ConstantInt>(CI->getOperand(3));
918 if (!LenC) return 0;
919 uint64_t Len = LenC->getZExtValue();
921 if (Len == 0) // memcmp(s1,s2,0) -> 0
922 return Context->getNullValue(CI->getType());
924 if (Len == 1) { // memcmp(S1,S2,1) -> *LHS - *RHS
925 Value *LHSV = B.CreateLoad(CastToCStr(LHS, B), "lhsv");
926 Value *RHSV = B.CreateLoad(CastToCStr(RHS, B), "rhsv");
927 return B.CreateSExt(B.CreateSub(LHSV, RHSV, "chardiff"), CI->getType());
930 // memcmp(S1,S2,2) != 0 -> (*(short*)LHS ^ *(short*)RHS) != 0
931 // memcmp(S1,S2,4) != 0 -> (*(int*)LHS ^ *(int*)RHS) != 0
932 if ((Len == 2 || Len == 4) && IsOnlyUsedInZeroEqualityComparison(CI)) {
933 const Type *PTy = Context->getPointerTypeUnqual(Len == 2 ?
934 Type::Int16Ty : Type::Int32Ty);
935 LHS = B.CreateBitCast(LHS, PTy, "tmp");
936 RHS = B.CreateBitCast(RHS, PTy, "tmp");
937 LoadInst *LHSV = B.CreateLoad(LHS, "lhsv");
938 LoadInst *RHSV = B.CreateLoad(RHS, "rhsv");
939 LHSV->setAlignment(1); RHSV->setAlignment(1); // Unaligned loads.
940 return B.CreateZExt(B.CreateXor(LHSV, RHSV, "shortdiff"), CI->getType());
943 return 0;
947 //===---------------------------------------===//
948 // 'memcpy' Optimizations
950 struct VISIBILITY_HIDDEN MemCpyOpt : public LibCallOptimization {
951 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
952 const FunctionType *FT = Callee->getFunctionType();
953 if (FT->getNumParams() != 3 || FT->getReturnType() != FT->getParamType(0) ||
954 !isa<PointerType>(FT->getParamType(0)) ||
955 !isa<PointerType>(FT->getParamType(1)) ||
956 FT->getParamType(2) != TD->getIntPtrType())
957 return 0;
959 // memcpy(x, y, n) -> llvm.memcpy(x, y, n, 1)
960 EmitMemCpy(CI->getOperand(1), CI->getOperand(2), CI->getOperand(3), 1, B);
961 return CI->getOperand(1);
965 //===---------------------------------------===//
966 // 'memmove' Optimizations
968 struct VISIBILITY_HIDDEN MemMoveOpt : public LibCallOptimization {
969 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
970 const FunctionType *FT = Callee->getFunctionType();
971 if (FT->getNumParams() != 3 || FT->getReturnType() != FT->getParamType(0) ||
972 !isa<PointerType>(FT->getParamType(0)) ||
973 !isa<PointerType>(FT->getParamType(1)) ||
974 FT->getParamType(2) != TD->getIntPtrType())
975 return 0;
977 // memmove(x, y, n) -> llvm.memmove(x, y, n, 1)
978 Module *M = Caller->getParent();
979 Intrinsic::ID IID = Intrinsic::memmove;
980 const Type *Tys[1];
981 Tys[0] = TD->getIntPtrType();
982 Value *MemMove = Intrinsic::getDeclaration(M, IID, Tys, 1);
983 Value *Dst = CastToCStr(CI->getOperand(1), B);
984 Value *Src = CastToCStr(CI->getOperand(2), B);
985 Value *Size = CI->getOperand(3);
986 Value *Align = ConstantInt::get(Type::Int32Ty, 1);
987 B.CreateCall4(MemMove, Dst, Src, Size, Align);
988 return CI->getOperand(1);
992 //===---------------------------------------===//
993 // 'memset' Optimizations
995 struct VISIBILITY_HIDDEN MemSetOpt : public LibCallOptimization {
996 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
997 const FunctionType *FT = Callee->getFunctionType();
998 if (FT->getNumParams() != 3 || FT->getReturnType() != FT->getParamType(0) ||
999 !isa<PointerType>(FT->getParamType(0)) ||
1000 !isa<IntegerType>(FT->getParamType(1)) ||
1001 FT->getParamType(2) != TD->getIntPtrType())
1002 return 0;
1004 // memset(p, v, n) -> llvm.memset(p, v, n, 1)
1005 Value *Val = B.CreateIntCast(CI->getOperand(2), Type::Int8Ty, false);
1006 EmitMemSet(CI->getOperand(1), Val, CI->getOperand(3), B);
1007 return CI->getOperand(1);
1011 //===----------------------------------------------------------------------===//
1012 // Math Library Optimizations
1013 //===----------------------------------------------------------------------===//
1015 //===---------------------------------------===//
1016 // 'pow*' Optimizations
1018 struct VISIBILITY_HIDDEN PowOpt : public LibCallOptimization {
1019 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
1020 const FunctionType *FT = Callee->getFunctionType();
1021 // Just make sure this has 2 arguments of the same FP type, which match the
1022 // result type.
1023 if (FT->getNumParams() != 2 || FT->getReturnType() != FT->getParamType(0) ||
1024 FT->getParamType(0) != FT->getParamType(1) ||
1025 !FT->getParamType(0)->isFloatingPoint())
1026 return 0;
1028 Value *Op1 = CI->getOperand(1), *Op2 = CI->getOperand(2);
1029 if (ConstantFP *Op1C = dyn_cast<ConstantFP>(Op1)) {
1030 if (Op1C->isExactlyValue(1.0)) // pow(1.0, x) -> 1.0
1031 return Op1C;
1032 if (Op1C->isExactlyValue(2.0)) // pow(2.0, x) -> exp2(x)
1033 return EmitUnaryFloatFnCall(Op2, "exp2", B);
1036 ConstantFP *Op2C = dyn_cast<ConstantFP>(Op2);
1037 if (Op2C == 0) return 0;
1039 if (Op2C->getValueAPF().isZero()) // pow(x, 0.0) -> 1.0
1040 return ConstantFP::get(CI->getType(), 1.0);
1042 if (Op2C->isExactlyValue(0.5)) {
1043 // FIXME: This is not safe for -0.0 and -inf. This can only be done when
1044 // 'unsafe' math optimizations are allowed.
1045 // x pow(x, 0.5) sqrt(x)
1046 // ---------------------------------------------
1047 // -0.0 +0.0 -0.0
1048 // -inf +inf NaN
1049 #if 0
1050 // pow(x, 0.5) -> sqrt(x)
1051 return B.CreateCall(get_sqrt(), Op1, "sqrt");
1052 #endif
1055 if (Op2C->isExactlyValue(1.0)) // pow(x, 1.0) -> x
1056 return Op1;
1057 if (Op2C->isExactlyValue(2.0)) // pow(x, 2.0) -> x*x
1058 return B.CreateFMul(Op1, Op1, "pow2");
1059 if (Op2C->isExactlyValue(-1.0)) // pow(x, -1.0) -> 1.0/x
1060 return B.CreateFDiv(ConstantFP::get(CI->getType(), 1.0),
1061 Op1, "powrecip");
1062 return 0;
1066 //===---------------------------------------===//
1067 // 'exp2' Optimizations
1069 struct VISIBILITY_HIDDEN Exp2Opt : public LibCallOptimization {
1070 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
1071 const FunctionType *FT = Callee->getFunctionType();
1072 // Just make sure this has 1 argument of FP type, which matches the
1073 // result type.
1074 if (FT->getNumParams() != 1 || FT->getReturnType() != FT->getParamType(0) ||
1075 !FT->getParamType(0)->isFloatingPoint())
1076 return 0;
1078 Value *Op = CI->getOperand(1);
1079 // Turn exp2(sitofp(x)) -> ldexp(1.0, sext(x)) if sizeof(x) <= 32
1080 // Turn exp2(uitofp(x)) -> ldexp(1.0, zext(x)) if sizeof(x) < 32
1081 Value *LdExpArg = 0;
1082 if (SIToFPInst *OpC = dyn_cast<SIToFPInst>(Op)) {
1083 if (OpC->getOperand(0)->getType()->getPrimitiveSizeInBits() <= 32)
1084 LdExpArg = B.CreateSExt(OpC->getOperand(0), Type::Int32Ty, "tmp");
1085 } else if (UIToFPInst *OpC = dyn_cast<UIToFPInst>(Op)) {
1086 if (OpC->getOperand(0)->getType()->getPrimitiveSizeInBits() < 32)
1087 LdExpArg = B.CreateZExt(OpC->getOperand(0), Type::Int32Ty, "tmp");
1090 if (LdExpArg) {
1091 const char *Name;
1092 if (Op->getType() == Type::FloatTy)
1093 Name = "ldexpf";
1094 else if (Op->getType() == Type::DoubleTy)
1095 Name = "ldexp";
1096 else
1097 Name = "ldexpl";
1099 Constant *One = ConstantFP::get(*Context, APFloat(1.0f));
1100 if (Op->getType() != Type::FloatTy)
1101 One = ConstantExpr::getFPExtend(One, Op->getType());
1103 Module *M = Caller->getParent();
1104 Value *Callee = M->getOrInsertFunction(Name, Op->getType(),
1105 Op->getType(), Type::Int32Ty,NULL);
1106 CallInst *CI = B.CreateCall2(Callee, One, LdExpArg);
1107 if (const Function *F = dyn_cast<Function>(Callee->stripPointerCasts()))
1108 CI->setCallingConv(F->getCallingConv());
1110 return CI;
1112 return 0;
1116 //===---------------------------------------===//
1117 // Double -> Float Shrinking Optimizations for Unary Functions like 'floor'
1119 struct VISIBILITY_HIDDEN UnaryDoubleFPOpt : public LibCallOptimization {
1120 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
1121 const FunctionType *FT = Callee->getFunctionType();
1122 if (FT->getNumParams() != 1 || FT->getReturnType() != Type::DoubleTy ||
1123 FT->getParamType(0) != Type::DoubleTy)
1124 return 0;
1126 // If this is something like 'floor((double)floatval)', convert to floorf.
1127 FPExtInst *Cast = dyn_cast<FPExtInst>(CI->getOperand(1));
1128 if (Cast == 0 || Cast->getOperand(0)->getType() != Type::FloatTy)
1129 return 0;
1131 // floor((double)floatval) -> (double)floorf(floatval)
1132 Value *V = Cast->getOperand(0);
1133 V = EmitUnaryFloatFnCall(V, Callee->getName().data(), B);
1134 return B.CreateFPExt(V, Type::DoubleTy);
1138 //===----------------------------------------------------------------------===//
1139 // Integer Optimizations
1140 //===----------------------------------------------------------------------===//
1142 //===---------------------------------------===//
1143 // 'ffs*' Optimizations
1145 struct VISIBILITY_HIDDEN FFSOpt : public LibCallOptimization {
1146 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
1147 const FunctionType *FT = Callee->getFunctionType();
1148 // Just make sure this has 2 arguments of the same FP type, which match the
1149 // result type.
1150 if (FT->getNumParams() != 1 || FT->getReturnType() != Type::Int32Ty ||
1151 !isa<IntegerType>(FT->getParamType(0)))
1152 return 0;
1154 Value *Op = CI->getOperand(1);
1156 // Constant fold.
1157 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op)) {
1158 if (CI->getValue() == 0) // ffs(0) -> 0.
1159 return Context->getNullValue(CI->getType());
1160 return ConstantInt::get(Type::Int32Ty, // ffs(c) -> cttz(c)+1
1161 CI->getValue().countTrailingZeros()+1);
1164 // ffs(x) -> x != 0 ? (i32)llvm.cttz(x)+1 : 0
1165 const Type *ArgType = Op->getType();
1166 Value *F = Intrinsic::getDeclaration(Callee->getParent(),
1167 Intrinsic::cttz, &ArgType, 1);
1168 Value *V = B.CreateCall(F, Op, "cttz");
1169 V = B.CreateAdd(V, ConstantInt::get(V->getType(), 1), "tmp");
1170 V = B.CreateIntCast(V, Type::Int32Ty, false, "tmp");
1172 Value *Cond = B.CreateICmpNE(Op, Context->getNullValue(ArgType), "tmp");
1173 return B.CreateSelect(Cond, V, ConstantInt::get(Type::Int32Ty, 0));
1177 //===---------------------------------------===//
1178 // 'isdigit' Optimizations
1180 struct VISIBILITY_HIDDEN IsDigitOpt : public LibCallOptimization {
1181 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
1182 const FunctionType *FT = Callee->getFunctionType();
1183 // We require integer(i32)
1184 if (FT->getNumParams() != 1 || !isa<IntegerType>(FT->getReturnType()) ||
1185 FT->getParamType(0) != Type::Int32Ty)
1186 return 0;
1188 // isdigit(c) -> (c-'0') <u 10
1189 Value *Op = CI->getOperand(1);
1190 Op = B.CreateSub(Op, ConstantInt::get(Type::Int32Ty, '0'),
1191 "isdigittmp");
1192 Op = B.CreateICmpULT(Op, ConstantInt::get(Type::Int32Ty, 10),
1193 "isdigit");
1194 return B.CreateZExt(Op, CI->getType());
1198 //===---------------------------------------===//
1199 // 'isascii' Optimizations
1201 struct VISIBILITY_HIDDEN IsAsciiOpt : public LibCallOptimization {
1202 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
1203 const FunctionType *FT = Callee->getFunctionType();
1204 // We require integer(i32)
1205 if (FT->getNumParams() != 1 || !isa<IntegerType>(FT->getReturnType()) ||
1206 FT->getParamType(0) != Type::Int32Ty)
1207 return 0;
1209 // isascii(c) -> c <u 128
1210 Value *Op = CI->getOperand(1);
1211 Op = B.CreateICmpULT(Op, ConstantInt::get(Type::Int32Ty, 128),
1212 "isascii");
1213 return B.CreateZExt(Op, CI->getType());
1217 //===---------------------------------------===//
1218 // 'abs', 'labs', 'llabs' Optimizations
1220 struct VISIBILITY_HIDDEN AbsOpt : public LibCallOptimization {
1221 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
1222 const FunctionType *FT = Callee->getFunctionType();
1223 // We require integer(integer) where the types agree.
1224 if (FT->getNumParams() != 1 || !isa<IntegerType>(FT->getReturnType()) ||
1225 FT->getParamType(0) != FT->getReturnType())
1226 return 0;
1228 // abs(x) -> x >s -1 ? x : -x
1229 Value *Op = CI->getOperand(1);
1230 Value *Pos = B.CreateICmpSGT(Op,
1231 Context->getAllOnesValue(Op->getType()),
1232 "ispos");
1233 Value *Neg = B.CreateNeg(Op, "neg");
1234 return B.CreateSelect(Pos, Op, Neg);
1239 //===---------------------------------------===//
1240 // 'toascii' Optimizations
1242 struct VISIBILITY_HIDDEN ToAsciiOpt : public LibCallOptimization {
1243 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
1244 const FunctionType *FT = Callee->getFunctionType();
1245 // We require i32(i32)
1246 if (FT->getNumParams() != 1 || FT->getReturnType() != FT->getParamType(0) ||
1247 FT->getParamType(0) != Type::Int32Ty)
1248 return 0;
1250 // isascii(c) -> c & 0x7f
1251 return B.CreateAnd(CI->getOperand(1),
1252 ConstantInt::get(CI->getType(),0x7F));
1256 //===----------------------------------------------------------------------===//
1257 // Formatting and IO Optimizations
1258 //===----------------------------------------------------------------------===//
1260 //===---------------------------------------===//
1261 // 'printf' Optimizations
1263 struct VISIBILITY_HIDDEN PrintFOpt : public LibCallOptimization {
1264 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
1265 // Require one fixed pointer argument and an integer/void result.
1266 const FunctionType *FT = Callee->getFunctionType();
1267 if (FT->getNumParams() < 1 || !isa<PointerType>(FT->getParamType(0)) ||
1268 !(isa<IntegerType>(FT->getReturnType()) ||
1269 FT->getReturnType() == Type::VoidTy))
1270 return 0;
1272 // Check for a fixed format string.
1273 std::string FormatStr;
1274 if (!GetConstantStringInfo(CI->getOperand(1), FormatStr))
1275 return 0;
1277 // Empty format string -> noop.
1278 if (FormatStr.empty()) // Tolerate printf's declared void.
1279 return CI->use_empty() ? (Value*)CI :
1280 ConstantInt::get(CI->getType(), 0);
1282 // printf("x") -> putchar('x'), even for '%'.
1283 if (FormatStr.size() == 1) {
1284 EmitPutChar(ConstantInt::get(Type::Int32Ty, FormatStr[0]), B);
1285 return CI->use_empty() ? (Value*)CI :
1286 ConstantInt::get(CI->getType(), 1);
1289 // printf("foo\n") --> puts("foo")
1290 if (FormatStr[FormatStr.size()-1] == '\n' &&
1291 FormatStr.find('%') == std::string::npos) { // no format characters.
1292 // Create a string literal with no \n on it. We expect the constant merge
1293 // pass to be run after this pass, to merge duplicate strings.
1294 FormatStr.erase(FormatStr.end()-1);
1295 Constant *C = ConstantArray::get(FormatStr, true);
1296 C = new GlobalVariable(*Callee->getParent(), C->getType(), true,
1297 GlobalVariable::InternalLinkage, C, "str");
1298 EmitPutS(C, B);
1299 return CI->use_empty() ? (Value*)CI :
1300 ConstantInt::get(CI->getType(), FormatStr.size()+1);
1303 // Optimize specific format strings.
1304 // printf("%c", chr) --> putchar(*(i8*)dst)
1305 if (FormatStr == "%c" && CI->getNumOperands() > 2 &&
1306 isa<IntegerType>(CI->getOperand(2)->getType())) {
1307 EmitPutChar(CI->getOperand(2), B);
1308 return CI->use_empty() ? (Value*)CI :
1309 ConstantInt::get(CI->getType(), 1);
1312 // printf("%s\n", str) --> puts(str)
1313 if (FormatStr == "%s\n" && CI->getNumOperands() > 2 &&
1314 isa<PointerType>(CI->getOperand(2)->getType()) &&
1315 CI->use_empty()) {
1316 EmitPutS(CI->getOperand(2), B);
1317 return CI;
1319 return 0;
1323 //===---------------------------------------===//
1324 // 'sprintf' Optimizations
1326 struct VISIBILITY_HIDDEN SPrintFOpt : public LibCallOptimization {
1327 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
1328 // Require two fixed pointer arguments and an integer result.
1329 const FunctionType *FT = Callee->getFunctionType();
1330 if (FT->getNumParams() != 2 || !isa<PointerType>(FT->getParamType(0)) ||
1331 !isa<PointerType>(FT->getParamType(1)) ||
1332 !isa<IntegerType>(FT->getReturnType()))
1333 return 0;
1335 // Check for a fixed format string.
1336 std::string FormatStr;
1337 if (!GetConstantStringInfo(CI->getOperand(2), FormatStr))
1338 return 0;
1340 // If we just have a format string (nothing else crazy) transform it.
1341 if (CI->getNumOperands() == 3) {
1342 // Make sure there's no % in the constant array. We could try to handle
1343 // %% -> % in the future if we cared.
1344 for (unsigned i = 0, e = FormatStr.size(); i != e; ++i)
1345 if (FormatStr[i] == '%')
1346 return 0; // we found a format specifier, bail out.
1348 // sprintf(str, fmt) -> llvm.memcpy(str, fmt, strlen(fmt)+1, 1)
1349 EmitMemCpy(CI->getOperand(1), CI->getOperand(2), // Copy the nul byte.
1350 ConstantInt::get(TD->getIntPtrType(), FormatStr.size()+1),1,B);
1351 return ConstantInt::get(CI->getType(), FormatStr.size());
1354 // The remaining optimizations require the format string to be "%s" or "%c"
1355 // and have an extra operand.
1356 if (FormatStr.size() != 2 || FormatStr[0] != '%' || CI->getNumOperands() <4)
1357 return 0;
1359 // Decode the second character of the format string.
1360 if (FormatStr[1] == 'c') {
1361 // sprintf(dst, "%c", chr) --> *(i8*)dst = chr; *((i8*)dst+1) = 0
1362 if (!isa<IntegerType>(CI->getOperand(3)->getType())) return 0;
1363 Value *V = B.CreateTrunc(CI->getOperand(3), Type::Int8Ty, "char");
1364 Value *Ptr = CastToCStr(CI->getOperand(1), B);
1365 B.CreateStore(V, Ptr);
1366 Ptr = B.CreateGEP(Ptr, ConstantInt::get(Type::Int32Ty, 1), "nul");
1367 B.CreateStore(Context->getNullValue(Type::Int8Ty), Ptr);
1369 return ConstantInt::get(CI->getType(), 1);
1372 if (FormatStr[1] == 's') {
1373 // sprintf(dest, "%s", str) -> llvm.memcpy(dest, str, strlen(str)+1, 1)
1374 if (!isa<PointerType>(CI->getOperand(3)->getType())) return 0;
1376 Value *Len = EmitStrLen(CI->getOperand(3), B);
1377 Value *IncLen = B.CreateAdd(Len,
1378 ConstantInt::get(Len->getType(), 1),
1379 "leninc");
1380 EmitMemCpy(CI->getOperand(1), CI->getOperand(3), IncLen, 1, B);
1382 // The sprintf result is the unincremented number of bytes in the string.
1383 return B.CreateIntCast(Len, CI->getType(), false);
1385 return 0;
1389 //===---------------------------------------===//
1390 // 'fwrite' Optimizations
1392 struct VISIBILITY_HIDDEN FWriteOpt : public LibCallOptimization {
1393 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
1394 // Require a pointer, an integer, an integer, a pointer, returning integer.
1395 const FunctionType *FT = Callee->getFunctionType();
1396 if (FT->getNumParams() != 4 || !isa<PointerType>(FT->getParamType(0)) ||
1397 !isa<IntegerType>(FT->getParamType(1)) ||
1398 !isa<IntegerType>(FT->getParamType(2)) ||
1399 !isa<PointerType>(FT->getParamType(3)) ||
1400 !isa<IntegerType>(FT->getReturnType()))
1401 return 0;
1403 // Get the element size and count.
1404 ConstantInt *SizeC = dyn_cast<ConstantInt>(CI->getOperand(2));
1405 ConstantInt *CountC = dyn_cast<ConstantInt>(CI->getOperand(3));
1406 if (!SizeC || !CountC) return 0;
1407 uint64_t Bytes = SizeC->getZExtValue()*CountC->getZExtValue();
1409 // If this is writing zero records, remove the call (it's a noop).
1410 if (Bytes == 0)
1411 return ConstantInt::get(CI->getType(), 0);
1413 // If this is writing one byte, turn it into fputc.
1414 if (Bytes == 1) { // fwrite(S,1,1,F) -> fputc(S[0],F)
1415 Value *Char = B.CreateLoad(CastToCStr(CI->getOperand(1), B), "char");
1416 EmitFPutC(Char, CI->getOperand(4), B);
1417 return ConstantInt::get(CI->getType(), 1);
1420 return 0;
1424 //===---------------------------------------===//
1425 // 'fputs' Optimizations
1427 struct VISIBILITY_HIDDEN FPutsOpt : public LibCallOptimization {
1428 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
1429 // Require two pointers. Also, we can't optimize if return value is used.
1430 const FunctionType *FT = Callee->getFunctionType();
1431 if (FT->getNumParams() != 2 || !isa<PointerType>(FT->getParamType(0)) ||
1432 !isa<PointerType>(FT->getParamType(1)) ||
1433 !CI->use_empty())
1434 return 0;
1436 // fputs(s,F) --> fwrite(s,1,strlen(s),F)
1437 uint64_t Len = GetStringLength(CI->getOperand(1));
1438 if (!Len) return 0;
1439 EmitFWrite(CI->getOperand(1),
1440 ConstantInt::get(TD->getIntPtrType(), Len-1),
1441 CI->getOperand(2), B);
1442 return CI; // Known to have no uses (see above).
1446 //===---------------------------------------===//
1447 // 'fprintf' Optimizations
1449 struct VISIBILITY_HIDDEN FPrintFOpt : public LibCallOptimization {
1450 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
1451 // Require two fixed paramters as pointers and integer result.
1452 const FunctionType *FT = Callee->getFunctionType();
1453 if (FT->getNumParams() != 2 || !isa<PointerType>(FT->getParamType(0)) ||
1454 !isa<PointerType>(FT->getParamType(1)) ||
1455 !isa<IntegerType>(FT->getReturnType()))
1456 return 0;
1458 // All the optimizations depend on the format string.
1459 std::string FormatStr;
1460 if (!GetConstantStringInfo(CI->getOperand(2), FormatStr))
1461 return 0;
1463 // fprintf(F, "foo") --> fwrite("foo", 3, 1, F)
1464 if (CI->getNumOperands() == 3) {
1465 for (unsigned i = 0, e = FormatStr.size(); i != e; ++i)
1466 if (FormatStr[i] == '%') // Could handle %% -> % if we cared.
1467 return 0; // We found a format specifier.
1469 EmitFWrite(CI->getOperand(2), ConstantInt::get(TD->getIntPtrType(),
1470 FormatStr.size()),
1471 CI->getOperand(1), B);
1472 return ConstantInt::get(CI->getType(), FormatStr.size());
1475 // The remaining optimizations require the format string to be "%s" or "%c"
1476 // and have an extra operand.
1477 if (FormatStr.size() != 2 || FormatStr[0] != '%' || CI->getNumOperands() <4)
1478 return 0;
1480 // Decode the second character of the format string.
1481 if (FormatStr[1] == 'c') {
1482 // fprintf(F, "%c", chr) --> *(i8*)dst = chr
1483 if (!isa<IntegerType>(CI->getOperand(3)->getType())) return 0;
1484 EmitFPutC(CI->getOperand(3), CI->getOperand(1), B);
1485 return ConstantInt::get(CI->getType(), 1);
1488 if (FormatStr[1] == 's') {
1489 // fprintf(F, "%s", str) -> fputs(str, F)
1490 if (!isa<PointerType>(CI->getOperand(3)->getType()) || !CI->use_empty())
1491 return 0;
1492 EmitFPutS(CI->getOperand(3), CI->getOperand(1), B);
1493 return CI;
1495 return 0;
1499 } // end anonymous namespace.
1501 //===----------------------------------------------------------------------===//
1502 // SimplifyLibCalls Pass Implementation
1503 //===----------------------------------------------------------------------===//
1505 namespace {
1506 /// This pass optimizes well known library functions from libc and libm.
1508 class VISIBILITY_HIDDEN SimplifyLibCalls : public FunctionPass {
1509 StringMap<LibCallOptimization*> Optimizations;
1510 // Miscellaneous LibCall Optimizations
1511 ExitOpt Exit;
1512 // String and Memory LibCall Optimizations
1513 StrCatOpt StrCat; StrNCatOpt StrNCat; StrChrOpt StrChr; StrCmpOpt StrCmp;
1514 StrNCmpOpt StrNCmp; StrCpyOpt StrCpy; StrNCpyOpt StrNCpy; StrLenOpt StrLen;
1515 StrToOpt StrTo; MemCmpOpt MemCmp; MemCpyOpt MemCpy; MemMoveOpt MemMove;
1516 MemSetOpt MemSet;
1517 // Math Library Optimizations
1518 PowOpt Pow; Exp2Opt Exp2; UnaryDoubleFPOpt UnaryDoubleFP;
1519 // Integer Optimizations
1520 FFSOpt FFS; AbsOpt Abs; IsDigitOpt IsDigit; IsAsciiOpt IsAscii;
1521 ToAsciiOpt ToAscii;
1522 // Formatting and IO Optimizations
1523 SPrintFOpt SPrintF; PrintFOpt PrintF;
1524 FWriteOpt FWrite; FPutsOpt FPuts; FPrintFOpt FPrintF;
1526 bool Modified; // This is only used by doInitialization.
1527 public:
1528 static char ID; // Pass identification
1529 SimplifyLibCalls() : FunctionPass(&ID) {}
1531 void InitOptimizations();
1532 bool runOnFunction(Function &F);
1534 void setDoesNotAccessMemory(Function &F);
1535 void setOnlyReadsMemory(Function &F);
1536 void setDoesNotThrow(Function &F);
1537 void setDoesNotCapture(Function &F, unsigned n);
1538 void setDoesNotAlias(Function &F, unsigned n);
1539 bool doInitialization(Module &M);
1541 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
1542 AU.addRequired<TargetData>();
1545 char SimplifyLibCalls::ID = 0;
1546 } // end anonymous namespace.
1548 static RegisterPass<SimplifyLibCalls>
1549 X("simplify-libcalls", "Simplify well-known library calls");
1551 // Public interface to the Simplify LibCalls pass.
1552 FunctionPass *llvm::createSimplifyLibCallsPass() {
1553 return new SimplifyLibCalls();
1556 /// Optimizations - Populate the Optimizations map with all the optimizations
1557 /// we know.
1558 void SimplifyLibCalls::InitOptimizations() {
1559 // Miscellaneous LibCall Optimizations
1560 Optimizations["exit"] = &Exit;
1562 // String and Memory LibCall Optimizations
1563 Optimizations["strcat"] = &StrCat;
1564 Optimizations["strncat"] = &StrNCat;
1565 Optimizations["strchr"] = &StrChr;
1566 Optimizations["strcmp"] = &StrCmp;
1567 Optimizations["strncmp"] = &StrNCmp;
1568 Optimizations["strcpy"] = &StrCpy;
1569 Optimizations["strncpy"] = &StrNCpy;
1570 Optimizations["strlen"] = &StrLen;
1571 Optimizations["strtol"] = &StrTo;
1572 Optimizations["strtod"] = &StrTo;
1573 Optimizations["strtof"] = &StrTo;
1574 Optimizations["strtoul"] = &StrTo;
1575 Optimizations["strtoll"] = &StrTo;
1576 Optimizations["strtold"] = &StrTo;
1577 Optimizations["strtoull"] = &StrTo;
1578 Optimizations["memcmp"] = &MemCmp;
1579 Optimizations["memcpy"] = &MemCpy;
1580 Optimizations["memmove"] = &MemMove;
1581 Optimizations["memset"] = &MemSet;
1583 // Math Library Optimizations
1584 Optimizations["powf"] = &Pow;
1585 Optimizations["pow"] = &Pow;
1586 Optimizations["powl"] = &Pow;
1587 Optimizations["llvm.pow.f32"] = &Pow;
1588 Optimizations["llvm.pow.f64"] = &Pow;
1589 Optimizations["llvm.pow.f80"] = &Pow;
1590 Optimizations["llvm.pow.f128"] = &Pow;
1591 Optimizations["llvm.pow.ppcf128"] = &Pow;
1592 Optimizations["exp2l"] = &Exp2;
1593 Optimizations["exp2"] = &Exp2;
1594 Optimizations["exp2f"] = &Exp2;
1595 Optimizations["llvm.exp2.ppcf128"] = &Exp2;
1596 Optimizations["llvm.exp2.f128"] = &Exp2;
1597 Optimizations["llvm.exp2.f80"] = &Exp2;
1598 Optimizations["llvm.exp2.f64"] = &Exp2;
1599 Optimizations["llvm.exp2.f32"] = &Exp2;
1601 #ifdef HAVE_FLOORF
1602 Optimizations["floor"] = &UnaryDoubleFP;
1603 #endif
1604 #ifdef HAVE_CEILF
1605 Optimizations["ceil"] = &UnaryDoubleFP;
1606 #endif
1607 #ifdef HAVE_ROUNDF
1608 Optimizations["round"] = &UnaryDoubleFP;
1609 #endif
1610 #ifdef HAVE_RINTF
1611 Optimizations["rint"] = &UnaryDoubleFP;
1612 #endif
1613 #ifdef HAVE_NEARBYINTF
1614 Optimizations["nearbyint"] = &UnaryDoubleFP;
1615 #endif
1617 // Integer Optimizations
1618 Optimizations["ffs"] = &FFS;
1619 Optimizations["ffsl"] = &FFS;
1620 Optimizations["ffsll"] = &FFS;
1621 Optimizations["abs"] = &Abs;
1622 Optimizations["labs"] = &Abs;
1623 Optimizations["llabs"] = &Abs;
1624 Optimizations["isdigit"] = &IsDigit;
1625 Optimizations["isascii"] = &IsAscii;
1626 Optimizations["toascii"] = &ToAscii;
1628 // Formatting and IO Optimizations
1629 Optimizations["sprintf"] = &SPrintF;
1630 Optimizations["printf"] = &PrintF;
1631 Optimizations["fwrite"] = &FWrite;
1632 Optimizations["fputs"] = &FPuts;
1633 Optimizations["fprintf"] = &FPrintF;
1637 /// runOnFunction - Top level algorithm.
1639 bool SimplifyLibCalls::runOnFunction(Function &F) {
1640 if (Optimizations.empty())
1641 InitOptimizations();
1643 const TargetData &TD = getAnalysis<TargetData>();
1645 IRBuilder<> Builder(F.getContext());
1647 bool Changed = false;
1648 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB) {
1649 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ) {
1650 // Ignore non-calls.
1651 CallInst *CI = dyn_cast<CallInst>(I++);
1652 if (!CI) continue;
1654 // Ignore indirect calls and calls to non-external functions.
1655 Function *Callee = CI->getCalledFunction();
1656 if (Callee == 0 || !Callee->isDeclaration() ||
1657 !(Callee->hasExternalLinkage() || Callee->hasDLLImportLinkage()))
1658 continue;
1660 // Ignore unknown calls.
1661 LibCallOptimization *LCO = Optimizations.lookup(Callee->getName());
1662 if (!LCO) continue;
1664 // Set the builder to the instruction after the call.
1665 Builder.SetInsertPoint(BB, I);
1667 // Try to optimize this call.
1668 Value *Result = LCO->OptimizeCall(CI, TD, Builder);
1669 if (Result == 0) continue;
1671 DEBUG(errs() << "SimplifyLibCalls simplified: " << *CI;
1672 errs() << " into: " << *Result << "\n");
1674 // Something changed!
1675 Changed = true;
1676 ++NumSimplified;
1678 // Inspect the instruction after the call (which was potentially just
1679 // added) next.
1680 I = CI; ++I;
1682 if (CI != Result && !CI->use_empty()) {
1683 CI->replaceAllUsesWith(Result);
1684 if (!Result->hasName())
1685 Result->takeName(CI);
1687 CI->eraseFromParent();
1690 return Changed;
1693 // Utility methods for doInitialization.
1695 void SimplifyLibCalls::setDoesNotAccessMemory(Function &F) {
1696 if (!F.doesNotAccessMemory()) {
1697 F.setDoesNotAccessMemory();
1698 ++NumAnnotated;
1699 Modified = true;
1702 void SimplifyLibCalls::setOnlyReadsMemory(Function &F) {
1703 if (!F.onlyReadsMemory()) {
1704 F.setOnlyReadsMemory();
1705 ++NumAnnotated;
1706 Modified = true;
1709 void SimplifyLibCalls::setDoesNotThrow(Function &F) {
1710 if (!F.doesNotThrow()) {
1711 F.setDoesNotThrow();
1712 ++NumAnnotated;
1713 Modified = true;
1716 void SimplifyLibCalls::setDoesNotCapture(Function &F, unsigned n) {
1717 if (!F.doesNotCapture(n)) {
1718 F.setDoesNotCapture(n);
1719 ++NumAnnotated;
1720 Modified = true;
1723 void SimplifyLibCalls::setDoesNotAlias(Function &F, unsigned n) {
1724 if (!F.doesNotAlias(n)) {
1725 F.setDoesNotAlias(n);
1726 ++NumAnnotated;
1727 Modified = true;
1731 /// doInitialization - Add attributes to well-known functions.
1733 bool SimplifyLibCalls::doInitialization(Module &M) {
1734 Modified = false;
1735 for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I) {
1736 Function &F = *I;
1737 if (!F.isDeclaration())
1738 continue;
1740 if (!F.hasName())
1741 continue;
1743 const FunctionType *FTy = F.getFunctionType();
1745 StringRef Name = F.getName();
1746 switch (Name[0]) {
1747 case 's':
1748 if (Name == "strlen") {
1749 if (FTy->getNumParams() != 1 ||
1750 !isa<PointerType>(FTy->getParamType(0)))
1751 continue;
1752 setOnlyReadsMemory(F);
1753 setDoesNotThrow(F);
1754 setDoesNotCapture(F, 1);
1755 } else if (Name == "strcpy" ||
1756 Name == "stpcpy" ||
1757 Name == "strcat" ||
1758 Name == "strtol" ||
1759 Name == "strtod" ||
1760 Name == "strtof" ||
1761 Name == "strtoul" ||
1762 Name == "strtoll" ||
1763 Name == "strtold" ||
1764 Name == "strncat" ||
1765 Name == "strncpy" ||
1766 Name == "strtoull") {
1767 if (FTy->getNumParams() < 2 ||
1768 !isa<PointerType>(FTy->getParamType(1)))
1769 continue;
1770 setDoesNotThrow(F);
1771 setDoesNotCapture(F, 2);
1772 } else if (Name == "strxfrm") {
1773 if (FTy->getNumParams() != 3 ||
1774 !isa<PointerType>(FTy->getParamType(0)) ||
1775 !isa<PointerType>(FTy->getParamType(1)))
1776 continue;
1777 setDoesNotThrow(F);
1778 setDoesNotCapture(F, 1);
1779 setDoesNotCapture(F, 2);
1780 } else if (Name == "strcmp" ||
1781 Name == "strspn" ||
1782 Name == "strncmp" ||
1783 Name ==" strcspn" ||
1784 Name == "strcoll" ||
1785 Name == "strcasecmp" ||
1786 Name == "strncasecmp") {
1787 if (FTy->getNumParams() < 2 ||
1788 !isa<PointerType>(FTy->getParamType(0)) ||
1789 !isa<PointerType>(FTy->getParamType(1)))
1790 continue;
1791 setOnlyReadsMemory(F);
1792 setDoesNotThrow(F);
1793 setDoesNotCapture(F, 1);
1794 setDoesNotCapture(F, 2);
1795 } else if (Name == "strstr" ||
1796 Name == "strpbrk") {
1797 if (FTy->getNumParams() != 2 ||
1798 !isa<PointerType>(FTy->getParamType(1)))
1799 continue;
1800 setOnlyReadsMemory(F);
1801 setDoesNotThrow(F);
1802 setDoesNotCapture(F, 2);
1803 } else if (Name == "strtok" ||
1804 Name == "strtok_r") {
1805 if (FTy->getNumParams() < 2 ||
1806 !isa<PointerType>(FTy->getParamType(1)))
1807 continue;
1808 setDoesNotThrow(F);
1809 setDoesNotCapture(F, 2);
1810 } else if (Name == "scanf" ||
1811 Name == "setbuf" ||
1812 Name == "setvbuf") {
1813 if (FTy->getNumParams() < 1 ||
1814 !isa<PointerType>(FTy->getParamType(0)))
1815 continue;
1816 setDoesNotThrow(F);
1817 setDoesNotCapture(F, 1);
1818 } else if (Name == "strdup" ||
1819 Name == "strndup") {
1820 if (FTy->getNumParams() < 1 ||
1821 !isa<PointerType>(FTy->getReturnType()) ||
1822 !isa<PointerType>(FTy->getParamType(0)))
1823 continue;
1824 setDoesNotThrow(F);
1825 setDoesNotAlias(F, 0);
1826 setDoesNotCapture(F, 1);
1827 } else if (Name == "stat" ||
1828 Name == "sscanf" ||
1829 Name == "sprintf" ||
1830 Name == "statvfs") {
1831 if (FTy->getNumParams() < 2 ||
1832 !isa<PointerType>(FTy->getParamType(0)) ||
1833 !isa<PointerType>(FTy->getParamType(1)))
1834 continue;
1835 setDoesNotThrow(F);
1836 setDoesNotCapture(F, 1);
1837 setDoesNotCapture(F, 2);
1838 } else if (Name == "snprintf") {
1839 if (FTy->getNumParams() != 3 ||
1840 !isa<PointerType>(FTy->getParamType(0)) ||
1841 !isa<PointerType>(FTy->getParamType(2)))
1842 continue;
1843 setDoesNotThrow(F);
1844 setDoesNotCapture(F, 1);
1845 setDoesNotCapture(F, 3);
1846 } else if (Name == "setitimer") {
1847 if (FTy->getNumParams() != 3 ||
1848 !isa<PointerType>(FTy->getParamType(1)) ||
1849 !isa<PointerType>(FTy->getParamType(2)))
1850 continue;
1851 setDoesNotThrow(F);
1852 setDoesNotCapture(F, 2);
1853 setDoesNotCapture(F, 3);
1854 } else if (Name == "system") {
1855 if (FTy->getNumParams() != 1 ||
1856 !isa<PointerType>(FTy->getParamType(0)))
1857 continue;
1858 // May throw; "system" is a valid pthread cancellation point.
1859 setDoesNotCapture(F, 1);
1861 break;
1862 case 'm':
1863 if (Name == "memcmp") {
1864 if (FTy->getNumParams() != 3 ||
1865 !isa<PointerType>(FTy->getParamType(0)) ||
1866 !isa<PointerType>(FTy->getParamType(1)))
1867 continue;
1868 setOnlyReadsMemory(F);
1869 setDoesNotThrow(F);
1870 setDoesNotCapture(F, 1);
1871 setDoesNotCapture(F, 2);
1872 } else if (Name == "memchr" ||
1873 Name == "memrchr") {
1874 if (FTy->getNumParams() != 3)
1875 continue;
1876 setOnlyReadsMemory(F);
1877 setDoesNotThrow(F);
1878 } else if (Name == "modf" ||
1879 Name == "modff" ||
1880 Name == "modfl" ||
1881 Name == "memcpy" ||
1882 Name == "memccpy" ||
1883 Name == "memmove") {
1884 if (FTy->getNumParams() < 2 ||
1885 !isa<PointerType>(FTy->getParamType(1)))
1886 continue;
1887 setDoesNotThrow(F);
1888 setDoesNotCapture(F, 2);
1889 } else if (Name == "memalign") {
1890 if (!isa<PointerType>(FTy->getReturnType()))
1891 continue;
1892 setDoesNotAlias(F, 0);
1893 } else if (Name == "mkdir" ||
1894 Name == "mktime") {
1895 if (FTy->getNumParams() == 0 ||
1896 !isa<PointerType>(FTy->getParamType(0)))
1897 continue;
1898 setDoesNotThrow(F);
1899 setDoesNotCapture(F, 1);
1901 break;
1902 case 'r':
1903 if (Name == "realloc") {
1904 if (FTy->getNumParams() != 2 ||
1905 !isa<PointerType>(FTy->getParamType(0)) ||
1906 !isa<PointerType>(FTy->getReturnType()))
1907 continue;
1908 setDoesNotThrow(F);
1909 setDoesNotAlias(F, 0);
1910 setDoesNotCapture(F, 1);
1911 } else if (Name == "read") {
1912 if (FTy->getNumParams() != 3 ||
1913 !isa<PointerType>(FTy->getParamType(1)))
1914 continue;
1915 // May throw; "read" is a valid pthread cancellation point.
1916 setDoesNotCapture(F, 2);
1917 } else if (Name == "rmdir" ||
1918 Name == "rewind" ||
1919 Name == "remove" ||
1920 Name == "realpath") {
1921 if (FTy->getNumParams() < 1 ||
1922 !isa<PointerType>(FTy->getParamType(0)))
1923 continue;
1924 setDoesNotThrow(F);
1925 setDoesNotCapture(F, 1);
1926 } else if (Name == "rename" ||
1927 Name == "readlink") {
1928 if (FTy->getNumParams() < 2 ||
1929 !isa<PointerType>(FTy->getParamType(0)) ||
1930 !isa<PointerType>(FTy->getParamType(1)))
1931 continue;
1932 setDoesNotThrow(F);
1933 setDoesNotCapture(F, 1);
1934 setDoesNotCapture(F, 2);
1936 break;
1937 case 'w':
1938 if (Name == "write") {
1939 if (FTy->getNumParams() != 3 ||
1940 !isa<PointerType>(FTy->getParamType(1)))
1941 continue;
1942 // May throw; "write" is a valid pthread cancellation point.
1943 setDoesNotCapture(F, 2);
1945 break;
1946 case 'b':
1947 if (Name == "bcopy") {
1948 if (FTy->getNumParams() != 3 ||
1949 !isa<PointerType>(FTy->getParamType(0)) ||
1950 !isa<PointerType>(FTy->getParamType(1)))
1951 continue;
1952 setDoesNotThrow(F);
1953 setDoesNotCapture(F, 1);
1954 setDoesNotCapture(F, 2);
1955 } else if (Name == "bcmp") {
1956 if (FTy->getNumParams() != 3 ||
1957 !isa<PointerType>(FTy->getParamType(0)) ||
1958 !isa<PointerType>(FTy->getParamType(1)))
1959 continue;
1960 setDoesNotThrow(F);
1961 setOnlyReadsMemory(F);
1962 setDoesNotCapture(F, 1);
1963 setDoesNotCapture(F, 2);
1964 } else if (Name == "bzero") {
1965 if (FTy->getNumParams() != 2 ||
1966 !isa<PointerType>(FTy->getParamType(0)))
1967 continue;
1968 setDoesNotThrow(F);
1969 setDoesNotCapture(F, 1);
1971 break;
1972 case 'c':
1973 if (Name == "calloc") {
1974 if (FTy->getNumParams() != 2 ||
1975 !isa<PointerType>(FTy->getReturnType()))
1976 continue;
1977 setDoesNotThrow(F);
1978 setDoesNotAlias(F, 0);
1979 } else if (Name == "chmod" ||
1980 Name == "chown" ||
1981 Name == "ctermid" ||
1982 Name == "clearerr" ||
1983 Name == "closedir") {
1984 if (FTy->getNumParams() == 0 ||
1985 !isa<PointerType>(FTy->getParamType(0)))
1986 continue;
1987 setDoesNotThrow(F);
1988 setDoesNotCapture(F, 1);
1990 break;
1991 case 'a':
1992 if (Name == "atoi" ||
1993 Name == "atol" ||
1994 Name == "atof" ||
1995 Name == "atoll") {
1996 if (FTy->getNumParams() != 1 ||
1997 !isa<PointerType>(FTy->getParamType(0)))
1998 continue;
1999 setDoesNotThrow(F);
2000 setOnlyReadsMemory(F);
2001 setDoesNotCapture(F, 1);
2002 } else if (Name == "access") {
2003 if (FTy->getNumParams() != 2 ||
2004 !isa<PointerType>(FTy->getParamType(0)))
2005 continue;
2006 setDoesNotThrow(F);
2007 setDoesNotCapture(F, 1);
2009 break;
2010 case 'f':
2011 if (Name == "fopen") {
2012 if (FTy->getNumParams() != 2 ||
2013 !isa<PointerType>(FTy->getReturnType()) ||
2014 !isa<PointerType>(FTy->getParamType(0)) ||
2015 !isa<PointerType>(FTy->getParamType(1)))
2016 continue;
2017 setDoesNotThrow(F);
2018 setDoesNotAlias(F, 0);
2019 setDoesNotCapture(F, 1);
2020 setDoesNotCapture(F, 2);
2021 } else if (Name == "fdopen") {
2022 if (FTy->getNumParams() != 2 ||
2023 !isa<PointerType>(FTy->getReturnType()) ||
2024 !isa<PointerType>(FTy->getParamType(1)))
2025 continue;
2026 setDoesNotThrow(F);
2027 setDoesNotAlias(F, 0);
2028 setDoesNotCapture(F, 2);
2029 } else if (Name == "feof" ||
2030 Name == "free" ||
2031 Name == "fseek" ||
2032 Name == "ftell" ||
2033 Name == "fgetc" ||
2034 Name == "fseeko" ||
2035 Name == "ftello" ||
2036 Name == "fileno" ||
2037 Name == "fflush" ||
2038 Name == "fclose" ||
2039 Name == "fsetpos" ||
2040 Name == "flockfile" ||
2041 Name == "funlockfile" ||
2042 Name == "ftrylockfile") {
2043 if (FTy->getNumParams() == 0 ||
2044 !isa<PointerType>(FTy->getParamType(0)))
2045 continue;
2046 setDoesNotThrow(F);
2047 setDoesNotCapture(F, 1);
2048 } else if (Name == "ferror") {
2049 if (FTy->getNumParams() != 1 ||
2050 !isa<PointerType>(FTy->getParamType(0)))
2051 continue;
2052 setDoesNotThrow(F);
2053 setDoesNotCapture(F, 1);
2054 setOnlyReadsMemory(F);
2055 } else if (Name == "fputc" ||
2056 Name == "fstat" ||
2057 Name == "frexp" ||
2058 Name == "frexpf" ||
2059 Name == "frexpl" ||
2060 Name == "fstatvfs") {
2061 if (FTy->getNumParams() != 2 ||
2062 !isa<PointerType>(FTy->getParamType(1)))
2063 continue;
2064 setDoesNotThrow(F);
2065 setDoesNotCapture(F, 2);
2066 } else if (Name == "fgets") {
2067 if (FTy->getNumParams() != 3 ||
2068 !isa<PointerType>(FTy->getParamType(0)) ||
2069 !isa<PointerType>(FTy->getParamType(2)))
2070 continue;
2071 setDoesNotThrow(F);
2072 setDoesNotCapture(F, 3);
2073 } else if (Name == "fread" ||
2074 Name == "fwrite") {
2075 if (FTy->getNumParams() != 4 ||
2076 !isa<PointerType>(FTy->getParamType(0)) ||
2077 !isa<PointerType>(FTy->getParamType(3)))
2078 continue;
2079 setDoesNotThrow(F);
2080 setDoesNotCapture(F, 1);
2081 setDoesNotCapture(F, 4);
2082 } else if (Name == "fputs" ||
2083 Name == "fscanf" ||
2084 Name == "fprintf" ||
2085 Name == "fgetpos") {
2086 if (FTy->getNumParams() < 2 ||
2087 !isa<PointerType>(FTy->getParamType(0)) ||
2088 !isa<PointerType>(FTy->getParamType(1)))
2089 continue;
2090 setDoesNotThrow(F);
2091 setDoesNotCapture(F, 1);
2092 setDoesNotCapture(F, 2);
2094 break;
2095 case 'g':
2096 if (Name == "getc" ||
2097 Name == "getlogin_r" ||
2098 Name == "getc_unlocked") {
2099 if (FTy->getNumParams() == 0 ||
2100 !isa<PointerType>(FTy->getParamType(0)))
2101 continue;
2102 setDoesNotThrow(F);
2103 setDoesNotCapture(F, 1);
2104 } else if (Name == "getenv") {
2105 if (FTy->getNumParams() != 1 ||
2106 !isa<PointerType>(FTy->getParamType(0)))
2107 continue;
2108 setDoesNotThrow(F);
2109 setOnlyReadsMemory(F);
2110 setDoesNotCapture(F, 1);
2111 } else if (Name == "gets" ||
2112 Name == "getchar") {
2113 setDoesNotThrow(F);
2114 } else if (Name == "getitimer") {
2115 if (FTy->getNumParams() != 2 ||
2116 !isa<PointerType>(FTy->getParamType(1)))
2117 continue;
2118 setDoesNotThrow(F);
2119 setDoesNotCapture(F, 2);
2120 } else if (Name == "getpwnam") {
2121 if (FTy->getNumParams() != 1 ||
2122 !isa<PointerType>(FTy->getParamType(0)))
2123 continue;
2124 setDoesNotThrow(F);
2125 setDoesNotCapture(F, 1);
2127 break;
2128 case 'u':
2129 if (Name == "ungetc") {
2130 if (FTy->getNumParams() != 2 ||
2131 !isa<PointerType>(FTy->getParamType(1)))
2132 continue;
2133 setDoesNotThrow(F);
2134 setDoesNotCapture(F, 2);
2135 } else if (Name == "uname" ||
2136 Name == "unlink" ||
2137 Name == "unsetenv") {
2138 if (FTy->getNumParams() != 1 ||
2139 !isa<PointerType>(FTy->getParamType(0)))
2140 continue;
2141 setDoesNotThrow(F);
2142 setDoesNotCapture(F, 1);
2143 } else if (Name == "utime" ||
2144 Name == "utimes") {
2145 if (FTy->getNumParams() != 2 ||
2146 !isa<PointerType>(FTy->getParamType(0)) ||
2147 !isa<PointerType>(FTy->getParamType(1)))
2148 continue;
2149 setDoesNotThrow(F);
2150 setDoesNotCapture(F, 1);
2151 setDoesNotCapture(F, 2);
2153 break;
2154 case 'p':
2155 if (Name == "putc") {
2156 if (FTy->getNumParams() != 2 ||
2157 !isa<PointerType>(FTy->getParamType(1)))
2158 continue;
2159 setDoesNotThrow(F);
2160 setDoesNotCapture(F, 2);
2161 } else if (Name == "puts" ||
2162 Name == "printf" ||
2163 Name == "perror") {
2164 if (FTy->getNumParams() != 1 ||
2165 !isa<PointerType>(FTy->getParamType(0)))
2166 continue;
2167 setDoesNotThrow(F);
2168 setDoesNotCapture(F, 1);
2169 } else if (Name == "pread" ||
2170 Name == "pwrite") {
2171 if (FTy->getNumParams() != 4 ||
2172 !isa<PointerType>(FTy->getParamType(1)))
2173 continue;
2174 // May throw; these are valid pthread cancellation points.
2175 setDoesNotCapture(F, 2);
2176 } else if (Name == "putchar") {
2177 setDoesNotThrow(F);
2178 } else if (Name == "popen") {
2179 if (FTy->getNumParams() != 2 ||
2180 !isa<PointerType>(FTy->getReturnType()) ||
2181 !isa<PointerType>(FTy->getParamType(0)) ||
2182 !isa<PointerType>(FTy->getParamType(1)))
2183 continue;
2184 setDoesNotThrow(F);
2185 setDoesNotAlias(F, 0);
2186 setDoesNotCapture(F, 1);
2187 setDoesNotCapture(F, 2);
2188 } else if (Name == "pclose") {
2189 if (FTy->getNumParams() != 1 ||
2190 !isa<PointerType>(FTy->getParamType(0)))
2191 continue;
2192 setDoesNotThrow(F);
2193 setDoesNotCapture(F, 1);
2195 break;
2196 case 'v':
2197 if (Name == "vscanf") {
2198 if (FTy->getNumParams() != 2 ||
2199 !isa<PointerType>(FTy->getParamType(1)))
2200 continue;
2201 setDoesNotThrow(F);
2202 setDoesNotCapture(F, 1);
2203 } else if (Name == "vsscanf" ||
2204 Name == "vfscanf") {
2205 if (FTy->getNumParams() != 3 ||
2206 !isa<PointerType>(FTy->getParamType(1)) ||
2207 !isa<PointerType>(FTy->getParamType(2)))
2208 continue;
2209 setDoesNotThrow(F);
2210 setDoesNotCapture(F, 1);
2211 setDoesNotCapture(F, 2);
2212 } else if (Name == "valloc") {
2213 if (!isa<PointerType>(FTy->getReturnType()))
2214 continue;
2215 setDoesNotThrow(F);
2216 setDoesNotAlias(F, 0);
2217 } else if (Name == "vprintf") {
2218 if (FTy->getNumParams() != 2 ||
2219 !isa<PointerType>(FTy->getParamType(0)))
2220 continue;
2221 setDoesNotThrow(F);
2222 setDoesNotCapture(F, 1);
2223 } else if (Name == "vfprintf" ||
2224 Name == "vsprintf") {
2225 if (FTy->getNumParams() != 3 ||
2226 !isa<PointerType>(FTy->getParamType(0)) ||
2227 !isa<PointerType>(FTy->getParamType(1)))
2228 continue;
2229 setDoesNotThrow(F);
2230 setDoesNotCapture(F, 1);
2231 setDoesNotCapture(F, 2);
2232 } else if (Name == "vsnprintf") {
2233 if (FTy->getNumParams() != 4 ||
2234 !isa<PointerType>(FTy->getParamType(0)) ||
2235 !isa<PointerType>(FTy->getParamType(2)))
2236 continue;
2237 setDoesNotThrow(F);
2238 setDoesNotCapture(F, 1);
2239 setDoesNotCapture(F, 3);
2241 break;
2242 case 'o':
2243 if (Name == "open") {
2244 if (FTy->getNumParams() < 2 ||
2245 !isa<PointerType>(FTy->getParamType(0)))
2246 continue;
2247 // May throw; "open" is a valid pthread cancellation point.
2248 setDoesNotCapture(F, 1);
2249 } else if (Name == "opendir") {
2250 if (FTy->getNumParams() != 1 ||
2251 !isa<PointerType>(FTy->getReturnType()) ||
2252 !isa<PointerType>(FTy->getParamType(0)))
2253 continue;
2254 setDoesNotThrow(F);
2255 setDoesNotAlias(F, 0);
2256 setDoesNotCapture(F, 1);
2258 break;
2259 case 't':
2260 if (Name == "tmpfile") {
2261 if (!isa<PointerType>(FTy->getReturnType()))
2262 continue;
2263 setDoesNotThrow(F);
2264 setDoesNotAlias(F, 0);
2265 } else if (Name == "times") {
2266 if (FTy->getNumParams() != 1 ||
2267 !isa<PointerType>(FTy->getParamType(0)))
2268 continue;
2269 setDoesNotThrow(F);
2270 setDoesNotCapture(F, 1);
2272 break;
2273 case 'h':
2274 if (Name == "htonl" ||
2275 Name == "htons") {
2276 setDoesNotThrow(F);
2277 setDoesNotAccessMemory(F);
2279 break;
2280 case 'n':
2281 if (Name == "ntohl" ||
2282 Name == "ntohs") {
2283 setDoesNotThrow(F);
2284 setDoesNotAccessMemory(F);
2286 break;
2287 case 'l':
2288 if (Name == "lstat") {
2289 if (FTy->getNumParams() != 2 ||
2290 !isa<PointerType>(FTy->getParamType(0)) ||
2291 !isa<PointerType>(FTy->getParamType(1)))
2292 continue;
2293 setDoesNotThrow(F);
2294 setDoesNotCapture(F, 1);
2295 setDoesNotCapture(F, 2);
2296 } else if (Name == "lchown") {
2297 if (FTy->getNumParams() != 3 ||
2298 !isa<PointerType>(FTy->getParamType(0)))
2299 continue;
2300 setDoesNotThrow(F);
2301 setDoesNotCapture(F, 1);
2303 break;
2304 case 'q':
2305 if (Name == "qsort") {
2306 if (FTy->getNumParams() != 4 ||
2307 !isa<PointerType>(FTy->getParamType(3)))
2308 continue;
2309 // May throw; places call through function pointer.
2310 setDoesNotCapture(F, 4);
2312 break;
2313 case '_':
2314 if (Name == "__strdup" ||
2315 Name == "__strndup") {
2316 if (FTy->getNumParams() < 1 ||
2317 !isa<PointerType>(FTy->getReturnType()) ||
2318 !isa<PointerType>(FTy->getParamType(0)))
2319 continue;
2320 setDoesNotThrow(F);
2321 setDoesNotAlias(F, 0);
2322 setDoesNotCapture(F, 1);
2323 } else if (Name == "__strtok_r") {
2324 if (FTy->getNumParams() != 3 ||
2325 !isa<PointerType>(FTy->getParamType(1)))
2326 continue;
2327 setDoesNotThrow(F);
2328 setDoesNotCapture(F, 2);
2329 } else if (Name == "_IO_getc") {
2330 if (FTy->getNumParams() != 1 ||
2331 !isa<PointerType>(FTy->getParamType(0)))
2332 continue;
2333 setDoesNotThrow(F);
2334 setDoesNotCapture(F, 1);
2335 } else if (Name == "_IO_putc") {
2336 if (FTy->getNumParams() != 2 ||
2337 !isa<PointerType>(FTy->getParamType(1)))
2338 continue;
2339 setDoesNotThrow(F);
2340 setDoesNotCapture(F, 2);
2342 break;
2343 case 1:
2344 if (Name == "\1__isoc99_scanf") {
2345 if (FTy->getNumParams() < 1 ||
2346 !isa<PointerType>(FTy->getParamType(0)))
2347 continue;
2348 setDoesNotThrow(F);
2349 setDoesNotCapture(F, 1);
2350 } else if (Name == "\1stat64" ||
2351 Name == "\1lstat64" ||
2352 Name == "\1statvfs64" ||
2353 Name == "\1__isoc99_sscanf") {
2354 if (FTy->getNumParams() < 1 ||
2355 !isa<PointerType>(FTy->getParamType(0)) ||
2356 !isa<PointerType>(FTy->getParamType(1)))
2357 continue;
2358 setDoesNotThrow(F);
2359 setDoesNotCapture(F, 1);
2360 setDoesNotCapture(F, 2);
2361 } else if (Name == "\1fopen64") {
2362 if (FTy->getNumParams() != 2 ||
2363 !isa<PointerType>(FTy->getReturnType()) ||
2364 !isa<PointerType>(FTy->getParamType(0)) ||
2365 !isa<PointerType>(FTy->getParamType(1)))
2366 continue;
2367 setDoesNotThrow(F);
2368 setDoesNotAlias(F, 0);
2369 setDoesNotCapture(F, 1);
2370 setDoesNotCapture(F, 2);
2371 } else if (Name == "\1fseeko64" ||
2372 Name == "\1ftello64") {
2373 if (FTy->getNumParams() == 0 ||
2374 !isa<PointerType>(FTy->getParamType(0)))
2375 continue;
2376 setDoesNotThrow(F);
2377 setDoesNotCapture(F, 1);
2378 } else if (Name == "\1tmpfile64") {
2379 if (!isa<PointerType>(FTy->getReturnType()))
2380 continue;
2381 setDoesNotThrow(F);
2382 setDoesNotAlias(F, 0);
2383 } else if (Name == "\1fstat64" ||
2384 Name == "\1fstatvfs64") {
2385 if (FTy->getNumParams() != 2 ||
2386 !isa<PointerType>(FTy->getParamType(1)))
2387 continue;
2388 setDoesNotThrow(F);
2389 setDoesNotCapture(F, 2);
2390 } else if (Name == "\1open64") {
2391 if (FTy->getNumParams() < 2 ||
2392 !isa<PointerType>(FTy->getParamType(0)))
2393 continue;
2394 // May throw; "open" is a valid pthread cancellation point.
2395 setDoesNotCapture(F, 1);
2397 break;
2400 return Modified;
2403 // TODO:
2404 // Additional cases that we need to add to this file:
2406 // cbrt:
2407 // * cbrt(expN(X)) -> expN(x/3)
2408 // * cbrt(sqrt(x)) -> pow(x,1/6)
2409 // * cbrt(sqrt(x)) -> pow(x,1/9)
2411 // cos, cosf, cosl:
2412 // * cos(-x) -> cos(x)
2414 // exp, expf, expl:
2415 // * exp(log(x)) -> x
2417 // log, logf, logl:
2418 // * log(exp(x)) -> x
2419 // * log(x**y) -> y*log(x)
2420 // * log(exp(y)) -> y*log(e)
2421 // * log(exp2(y)) -> y*log(2)
2422 // * log(exp10(y)) -> y*log(10)
2423 // * log(sqrt(x)) -> 0.5*log(x)
2424 // * log(pow(x,y)) -> y*log(x)
2426 // lround, lroundf, lroundl:
2427 // * lround(cnst) -> cnst'
2429 // memcmp:
2430 // * memcmp(x,y,l) -> cnst
2431 // (if all arguments are constant and strlen(x) <= l and strlen(y) <= l)
2433 // pow, powf, powl:
2434 // * pow(exp(x),y) -> exp(x*y)
2435 // * pow(sqrt(x),y) -> pow(x,y*0.5)
2436 // * pow(pow(x,y),z)-> pow(x,y*z)
2438 // puts:
2439 // * puts("") -> putchar("\n")
2441 // round, roundf, roundl:
2442 // * round(cnst) -> cnst'
2444 // signbit:
2445 // * signbit(cnst) -> cnst'
2446 // * signbit(nncst) -> 0 (if pstv is a non-negative constant)
2448 // sqrt, sqrtf, sqrtl:
2449 // * sqrt(expN(x)) -> expN(x*0.5)
2450 // * sqrt(Nroot(x)) -> pow(x,1/(2*N))
2451 // * sqrt(pow(x,y)) -> pow(|x|,y*0.5)
2453 // stpcpy:
2454 // * stpcpy(str, "literal") ->
2455 // llvm.memcpy(str,"literal",strlen("literal")+1,1)
2456 // strrchr:
2457 // * strrchr(s,c) -> reverse_offset_of_in(c,s)
2458 // (if c is a constant integer and s is a constant string)
2459 // * strrchr(s1,0) -> strchr(s1,0)
2461 // strpbrk:
2462 // * strpbrk(s,a) -> offset_in_for(s,a)
2463 // (if s and a are both constant strings)
2464 // * strpbrk(s,"") -> 0
2465 // * strpbrk(s,a) -> strchr(s,a[0]) (if a is constant string of length 1)
2467 // strspn, strcspn:
2468 // * strspn(s,a) -> const_int (if both args are constant)
2469 // * strspn("",a) -> 0
2470 // * strspn(s,"") -> 0
2471 // * strcspn(s,a) -> const_int (if both args are constant)
2472 // * strcspn("",a) -> 0
2473 // * strcspn(s,"") -> strlen(a)
2475 // strstr:
2476 // * strstr(x,x) -> x
2477 // * strstr(s1,s2) -> offset_of_s2_in(s1)
2478 // (if s1 and s2 are constant strings)
2480 // tan, tanf, tanl:
2481 // * tan(atan(x)) -> x
2483 // trunc, truncf, truncl:
2484 // * trunc(cnst) -> cnst'