ConstantFolding.cpp 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844
  1. //===-- ConstantFolding.cpp - Analyze constant folding possibilities ------===//
  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 family of functions determines the possibility of performing constant
  11. // folding.
  12. //
  13. //===----------------------------------------------------------------------===//
  14. #include "llvm/Analysis/ConstantFolding.h"
  15. #include "llvm/Constants.h"
  16. #include "llvm/DerivedTypes.h"
  17. #include "llvm/Function.h"
  18. #include "llvm/GlobalVariable.h"
  19. #include "llvm/Instructions.h"
  20. #include "llvm/Intrinsics.h"
  21. #include "llvm/LLVMContext.h"
  22. #include "llvm/ADT/SmallVector.h"
  23. #include "llvm/ADT/StringMap.h"
  24. #include "llvm/Target/TargetData.h"
  25. #include "llvm/Support/ErrorHandling.h"
  26. #include "llvm/Support/GetElementPtrTypeIterator.h"
  27. #include "llvm/Support/MathExtras.h"
  28. #include <cerrno>
  29. #include <cmath>
  30. using namespace llvm;
  31. //===----------------------------------------------------------------------===//
  32. // Constant Folding internal helper functions
  33. //===----------------------------------------------------------------------===//
  34. /// IsConstantOffsetFromGlobal - If this constant is actually a constant offset
  35. /// from a global, return the global and the constant. Because of
  36. /// constantexprs, this function is recursive.
  37. static bool IsConstantOffsetFromGlobal(Constant *C, GlobalValue *&GV,
  38. int64_t &Offset, const TargetData &TD) {
  39. // Trivial case, constant is the global.
  40. if ((GV = dyn_cast<GlobalValue>(C))) {
  41. Offset = 0;
  42. return true;
  43. }
  44. // Otherwise, if this isn't a constant expr, bail out.
  45. ConstantExpr *CE = dyn_cast<ConstantExpr>(C);
  46. if (!CE) return false;
  47. // Look through ptr->int and ptr->ptr casts.
  48. if (CE->getOpcode() == Instruction::PtrToInt ||
  49. CE->getOpcode() == Instruction::BitCast)
  50. return IsConstantOffsetFromGlobal(CE->getOperand(0), GV, Offset, TD);
  51. // i32* getelementptr ([5 x i32]* @a, i32 0, i32 5)
  52. if (CE->getOpcode() == Instruction::GetElementPtr) {
  53. // Cannot compute this if the element type of the pointer is missing size
  54. // info.
  55. if (!cast<PointerType>(CE->getOperand(0)->getType())
  56. ->getElementType()->isSized())
  57. return false;
  58. // If the base isn't a global+constant, we aren't either.
  59. if (!IsConstantOffsetFromGlobal(CE->getOperand(0), GV, Offset, TD))
  60. return false;
  61. // Otherwise, add any offset that our operands provide.
  62. gep_type_iterator GTI = gep_type_begin(CE);
  63. for (User::const_op_iterator i = CE->op_begin() + 1, e = CE->op_end();
  64. i != e; ++i, ++GTI) {
  65. ConstantInt *CI = dyn_cast<ConstantInt>(*i);
  66. if (!CI) return false; // Index isn't a simple constant?
  67. if (CI->getZExtValue() == 0) continue; // Not adding anything.
  68. if (const StructType *ST = dyn_cast<StructType>(*GTI)) {
  69. // N = N + Offset
  70. Offset += TD.getStructLayout(ST)->getElementOffset(CI->getZExtValue());
  71. } else {
  72. const SequentialType *SQT = cast<SequentialType>(*GTI);
  73. Offset += TD.getTypeAllocSize(SQT->getElementType())*CI->getSExtValue();
  74. }
  75. }
  76. return true;
  77. }
  78. return false;
  79. }
  80. /// SymbolicallyEvaluateBinop - One of Op0/Op1 is a constant expression.
  81. /// Attempt to symbolically evaluate the result of a binary operator merging
  82. /// these together. If target data info is available, it is provided as TD,
  83. /// otherwise TD is null.
  84. static Constant *SymbolicallyEvaluateBinop(unsigned Opc, Constant *Op0,
  85. Constant *Op1, const TargetData *TD,
  86. LLVMContext *Context){
  87. // SROA
  88. // Fold (and 0xffffffff00000000, (shl x, 32)) -> shl.
  89. // Fold (lshr (or X, Y), 32) -> (lshr [X/Y], 32) if one doesn't contribute
  90. // bits.
  91. // If the constant expr is something like &A[123] - &A[4].f, fold this into a
  92. // constant. This happens frequently when iterating over a global array.
  93. if (Opc == Instruction::Sub && TD) {
  94. GlobalValue *GV1, *GV2;
  95. int64_t Offs1, Offs2;
  96. if (IsConstantOffsetFromGlobal(Op0, GV1, Offs1, *TD))
  97. if (IsConstantOffsetFromGlobal(Op1, GV2, Offs2, *TD) &&
  98. GV1 == GV2) {
  99. // (&GV+C1) - (&GV+C2) -> C1-C2, pointer arithmetic cannot overflow.
  100. return Context->getConstantInt(Op0->getType(), Offs1-Offs2);
  101. }
  102. }
  103. return 0;
  104. }
  105. /// SymbolicallyEvaluateGEP - If we can symbolically evaluate the specified GEP
  106. /// constant expression, do so.
  107. static Constant *SymbolicallyEvaluateGEP(Constant* const* Ops, unsigned NumOps,
  108. const Type *ResultTy,
  109. LLVMContext *Context,
  110. const TargetData *TD) {
  111. Constant *Ptr = Ops[0];
  112. if (!TD || !cast<PointerType>(Ptr->getType())->getElementType()->isSized())
  113. return 0;
  114. uint64_t BasePtr = 0;
  115. if (!Ptr->isNullValue()) {
  116. // If this is a inttoptr from a constant int, we can fold this as the base,
  117. // otherwise we can't.
  118. if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr))
  119. if (CE->getOpcode() == Instruction::IntToPtr)
  120. if (ConstantInt *Base = dyn_cast<ConstantInt>(CE->getOperand(0)))
  121. BasePtr = Base->getZExtValue();
  122. if (BasePtr == 0)
  123. return 0;
  124. }
  125. // If this is a constant expr gep that is effectively computing an
  126. // "offsetof", fold it into 'cast int Size to T*' instead of 'gep 0, 0, 12'
  127. for (unsigned i = 1; i != NumOps; ++i)
  128. if (!isa<ConstantInt>(Ops[i]))
  129. return false;
  130. uint64_t Offset = TD->getIndexedOffset(Ptr->getType(),
  131. (Value**)Ops+1, NumOps-1);
  132. Constant *C = Context->getConstantInt(TD->getIntPtrType(), Offset+BasePtr);
  133. return Context->getConstantExprIntToPtr(C, ResultTy);
  134. }
  135. /// FoldBitCast - Constant fold bitcast, symbolically evaluating it with
  136. /// targetdata. Return 0 if unfoldable.
  137. static Constant *FoldBitCast(Constant *C, const Type *DestTy,
  138. const TargetData &TD, LLVMContext *Context) {
  139. // If this is a bitcast from constant vector -> vector, fold it.
  140. if (ConstantVector *CV = dyn_cast<ConstantVector>(C)) {
  141. if (const VectorType *DestVTy = dyn_cast<VectorType>(DestTy)) {
  142. // If the element types match, VMCore can fold it.
  143. unsigned NumDstElt = DestVTy->getNumElements();
  144. unsigned NumSrcElt = CV->getNumOperands();
  145. if (NumDstElt == NumSrcElt)
  146. return 0;
  147. const Type *SrcEltTy = CV->getType()->getElementType();
  148. const Type *DstEltTy = DestVTy->getElementType();
  149. // Otherwise, we're changing the number of elements in a vector, which
  150. // requires endianness information to do the right thing. For example,
  151. // bitcast (<2 x i64> <i64 0, i64 1> to <4 x i32>)
  152. // folds to (little endian):
  153. // <4 x i32> <i32 0, i32 0, i32 1, i32 0>
  154. // and to (big endian):
  155. // <4 x i32> <i32 0, i32 0, i32 0, i32 1>
  156. // First thing is first. We only want to think about integer here, so if
  157. // we have something in FP form, recast it as integer.
  158. if (DstEltTy->isFloatingPoint()) {
  159. // Fold to an vector of integers with same size as our FP type.
  160. unsigned FPWidth = DstEltTy->getPrimitiveSizeInBits();
  161. const Type *DestIVTy = Context->getVectorType(
  162. Context->getIntegerType(FPWidth), NumDstElt);
  163. // Recursively handle this integer conversion, if possible.
  164. C = FoldBitCast(C, DestIVTy, TD, Context);
  165. if (!C) return 0;
  166. // Finally, VMCore can handle this now that #elts line up.
  167. return Context->getConstantExprBitCast(C, DestTy);
  168. }
  169. // Okay, we know the destination is integer, if the input is FP, convert
  170. // it to integer first.
  171. if (SrcEltTy->isFloatingPoint()) {
  172. unsigned FPWidth = SrcEltTy->getPrimitiveSizeInBits();
  173. const Type *SrcIVTy = Context->getVectorType(
  174. Context->getIntegerType(FPWidth), NumSrcElt);
  175. // Ask VMCore to do the conversion now that #elts line up.
  176. C = Context->getConstantExprBitCast(C, SrcIVTy);
  177. CV = dyn_cast<ConstantVector>(C);
  178. if (!CV) return 0; // If VMCore wasn't able to fold it, bail out.
  179. }
  180. // Now we know that the input and output vectors are both integer vectors
  181. // of the same size, and that their #elements is not the same. Do the
  182. // conversion here, which depends on whether the input or output has
  183. // more elements.
  184. bool isLittleEndian = TD.isLittleEndian();
  185. SmallVector<Constant*, 32> Result;
  186. if (NumDstElt < NumSrcElt) {
  187. // Handle: bitcast (<4 x i32> <i32 0, i32 1, i32 2, i32 3> to <2 x i64>)
  188. Constant *Zero = Context->getNullValue(DstEltTy);
  189. unsigned Ratio = NumSrcElt/NumDstElt;
  190. unsigned SrcBitSize = SrcEltTy->getPrimitiveSizeInBits();
  191. unsigned SrcElt = 0;
  192. for (unsigned i = 0; i != NumDstElt; ++i) {
  193. // Build each element of the result.
  194. Constant *Elt = Zero;
  195. unsigned ShiftAmt = isLittleEndian ? 0 : SrcBitSize*(Ratio-1);
  196. for (unsigned j = 0; j != Ratio; ++j) {
  197. Constant *Src = dyn_cast<ConstantInt>(CV->getOperand(SrcElt++));
  198. if (!Src) return 0; // Reject constantexpr elements.
  199. // Zero extend the element to the right size.
  200. Src = Context->getConstantExprZExt(Src, Elt->getType());
  201. // Shift it to the right place, depending on endianness.
  202. Src = Context->getConstantExprShl(Src,
  203. Context->getConstantInt(Src->getType(), ShiftAmt));
  204. ShiftAmt += isLittleEndian ? SrcBitSize : -SrcBitSize;
  205. // Mix it in.
  206. Elt = Context->getConstantExprOr(Elt, Src);
  207. }
  208. Result.push_back(Elt);
  209. }
  210. } else {
  211. // Handle: bitcast (<2 x i64> <i64 0, i64 1> to <4 x i32>)
  212. unsigned Ratio = NumDstElt/NumSrcElt;
  213. unsigned DstBitSize = DstEltTy->getPrimitiveSizeInBits();
  214. // Loop over each source value, expanding into multiple results.
  215. for (unsigned i = 0; i != NumSrcElt; ++i) {
  216. Constant *Src = dyn_cast<ConstantInt>(CV->getOperand(i));
  217. if (!Src) return 0; // Reject constantexpr elements.
  218. unsigned ShiftAmt = isLittleEndian ? 0 : DstBitSize*(Ratio-1);
  219. for (unsigned j = 0; j != Ratio; ++j) {
  220. // Shift the piece of the value into the right place, depending on
  221. // endianness.
  222. Constant *Elt = Context->getConstantExprLShr(Src,
  223. Context->getConstantInt(Src->getType(), ShiftAmt));
  224. ShiftAmt += isLittleEndian ? DstBitSize : -DstBitSize;
  225. // Truncate and remember this piece.
  226. Result.push_back(Context->getConstantExprTrunc(Elt, DstEltTy));
  227. }
  228. }
  229. }
  230. return Context->getConstantVector(Result.data(), Result.size());
  231. }
  232. }
  233. return 0;
  234. }
  235. //===----------------------------------------------------------------------===//
  236. // Constant Folding public APIs
  237. //===----------------------------------------------------------------------===//
  238. /// ConstantFoldInstruction - Attempt to constant fold the specified
  239. /// instruction. If successful, the constant result is returned, if not, null
  240. /// is returned. Note that this function can only fail when attempting to fold
  241. /// instructions like loads and stores, which have no constant expression form.
  242. ///
  243. Constant *llvm::ConstantFoldInstruction(Instruction *I, LLVMContext *Context,
  244. const TargetData *TD) {
  245. if (PHINode *PN = dyn_cast<PHINode>(I)) {
  246. if (PN->getNumIncomingValues() == 0)
  247. return Context->getUndef(PN->getType());
  248. Constant *Result = dyn_cast<Constant>(PN->getIncomingValue(0));
  249. if (Result == 0) return 0;
  250. // Handle PHI nodes specially here...
  251. for (unsigned i = 1, e = PN->getNumIncomingValues(); i != e; ++i)
  252. if (PN->getIncomingValue(i) != Result && PN->getIncomingValue(i) != PN)
  253. return 0; // Not all the same incoming constants...
  254. // If we reach here, all incoming values are the same constant.
  255. return Result;
  256. }
  257. // Scan the operand list, checking to see if they are all constants, if so,
  258. // hand off to ConstantFoldInstOperands.
  259. SmallVector<Constant*, 8> Ops;
  260. for (User::op_iterator i = I->op_begin(), e = I->op_end(); i != e; ++i)
  261. if (Constant *Op = dyn_cast<Constant>(*i))
  262. Ops.push_back(Op);
  263. else
  264. return 0; // All operands not constant!
  265. if (const CmpInst *CI = dyn_cast<CmpInst>(I))
  266. return ConstantFoldCompareInstOperands(CI->getPredicate(),
  267. Ops.data(), Ops.size(),
  268. Context, TD);
  269. else
  270. return ConstantFoldInstOperands(I->getOpcode(), I->getType(),
  271. Ops.data(), Ops.size(), Context, TD);
  272. }
  273. /// ConstantFoldConstantExpression - Attempt to fold the constant expression
  274. /// using the specified TargetData. If successful, the constant result is
  275. /// result is returned, if not, null is returned.
  276. Constant *llvm::ConstantFoldConstantExpression(ConstantExpr *CE,
  277. LLVMContext *Context,
  278. const TargetData *TD) {
  279. SmallVector<Constant*, 8> Ops;
  280. for (User::op_iterator i = CE->op_begin(), e = CE->op_end(); i != e; ++i)
  281. Ops.push_back(cast<Constant>(*i));
  282. if (CE->isCompare())
  283. return ConstantFoldCompareInstOperands(CE->getPredicate(),
  284. Ops.data(), Ops.size(),
  285. Context, TD);
  286. else
  287. return ConstantFoldInstOperands(CE->getOpcode(), CE->getType(),
  288. Ops.data(), Ops.size(), Context, TD);
  289. }
  290. /// ConstantFoldInstOperands - Attempt to constant fold an instruction with the
  291. /// specified opcode and operands. If successful, the constant result is
  292. /// returned, if not, null is returned. Note that this function can fail when
  293. /// attempting to fold instructions like loads and stores, which have no
  294. /// constant expression form.
  295. ///
  296. Constant *llvm::ConstantFoldInstOperands(unsigned Opcode, const Type *DestTy,
  297. Constant* const* Ops, unsigned NumOps,
  298. LLVMContext *Context,
  299. const TargetData *TD) {
  300. // Handle easy binops first.
  301. if (Instruction::isBinaryOp(Opcode)) {
  302. if (isa<ConstantExpr>(Ops[0]) || isa<ConstantExpr>(Ops[1]))
  303. if (Constant *C = SymbolicallyEvaluateBinop(Opcode, Ops[0], Ops[1], TD,
  304. Context))
  305. return C;
  306. return Context->getConstantExpr(Opcode, Ops[0], Ops[1]);
  307. }
  308. switch (Opcode) {
  309. default: return 0;
  310. case Instruction::Call:
  311. if (Function *F = dyn_cast<Function>(Ops[0]))
  312. if (canConstantFoldCallTo(F))
  313. return ConstantFoldCall(F, Ops+1, NumOps-1);
  314. return 0;
  315. case Instruction::ICmp:
  316. case Instruction::FCmp:
  317. LLVM_UNREACHABLE("This function is invalid for compares: no predicate specified");
  318. case Instruction::PtrToInt:
  319. // If the input is a inttoptr, eliminate the pair. This requires knowing
  320. // the width of a pointer, so it can't be done in ConstantExpr::getCast.
  321. if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ops[0])) {
  322. if (TD && CE->getOpcode() == Instruction::IntToPtr) {
  323. Constant *Input = CE->getOperand(0);
  324. unsigned InWidth = Input->getType()->getScalarSizeInBits();
  325. if (TD->getPointerSizeInBits() < InWidth) {
  326. Constant *Mask =
  327. Context->getConstantInt(APInt::getLowBitsSet(InWidth,
  328. TD->getPointerSizeInBits()));
  329. Input = Context->getConstantExprAnd(Input, Mask);
  330. }
  331. // Do a zext or trunc to get to the dest size.
  332. return Context->getConstantExprIntegerCast(Input, DestTy, false);
  333. }
  334. }
  335. return Context->getConstantExprCast(Opcode, Ops[0], DestTy);
  336. case Instruction::IntToPtr:
  337. // If the input is a ptrtoint, turn the pair into a ptr to ptr bitcast if
  338. // the int size is >= the ptr size. This requires knowing the width of a
  339. // pointer, so it can't be done in ConstantExpr::getCast.
  340. if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ops[0])) {
  341. if (TD &&
  342. TD->getPointerSizeInBits() <=
  343. CE->getType()->getScalarSizeInBits()) {
  344. if (CE->getOpcode() == Instruction::PtrToInt) {
  345. Constant *Input = CE->getOperand(0);
  346. Constant *C = FoldBitCast(Input, DestTy, *TD, Context);
  347. return C ? C : Context->getConstantExprBitCast(Input, DestTy);
  348. }
  349. // If there's a constant offset added to the integer value before
  350. // it is casted back to a pointer, see if the expression can be
  351. // converted into a GEP.
  352. if (CE->getOpcode() == Instruction::Add)
  353. if (ConstantInt *L = dyn_cast<ConstantInt>(CE->getOperand(0)))
  354. if (ConstantExpr *R = dyn_cast<ConstantExpr>(CE->getOperand(1)))
  355. if (R->getOpcode() == Instruction::PtrToInt)
  356. if (GlobalVariable *GV =
  357. dyn_cast<GlobalVariable>(R->getOperand(0))) {
  358. const PointerType *GVTy = cast<PointerType>(GV->getType());
  359. if (const ArrayType *AT =
  360. dyn_cast<ArrayType>(GVTy->getElementType())) {
  361. const Type *ElTy = AT->getElementType();
  362. uint64_t AllocSize = TD->getTypeAllocSize(ElTy);
  363. APInt PSA(L->getValue().getBitWidth(), AllocSize);
  364. if (ElTy == cast<PointerType>(DestTy)->getElementType() &&
  365. L->getValue().urem(PSA) == 0) {
  366. APInt ElemIdx = L->getValue().udiv(PSA);
  367. if (ElemIdx.ult(APInt(ElemIdx.getBitWidth(),
  368. AT->getNumElements()))) {
  369. Constant *Index[] = {
  370. Context->getNullValue(CE->getType()),
  371. Context->getConstantInt(ElemIdx)
  372. };
  373. return
  374. Context->getConstantExprGetElementPtr(GV, &Index[0], 2);
  375. }
  376. }
  377. }
  378. }
  379. }
  380. }
  381. return Context->getConstantExprCast(Opcode, Ops[0], DestTy);
  382. case Instruction::Trunc:
  383. case Instruction::ZExt:
  384. case Instruction::SExt:
  385. case Instruction::FPTrunc:
  386. case Instruction::FPExt:
  387. case Instruction::UIToFP:
  388. case Instruction::SIToFP:
  389. case Instruction::FPToUI:
  390. case Instruction::FPToSI:
  391. return Context->getConstantExprCast(Opcode, Ops[0], DestTy);
  392. case Instruction::BitCast:
  393. if (TD)
  394. if (Constant *C = FoldBitCast(Ops[0], DestTy, *TD, Context))
  395. return C;
  396. return Context->getConstantExprBitCast(Ops[0], DestTy);
  397. case Instruction::Select:
  398. return Context->getConstantExprSelect(Ops[0], Ops[1], Ops[2]);
  399. case Instruction::ExtractElement:
  400. return Context->getConstantExprExtractElement(Ops[0], Ops[1]);
  401. case Instruction::InsertElement:
  402. return Context->getConstantExprInsertElement(Ops[0], Ops[1], Ops[2]);
  403. case Instruction::ShuffleVector:
  404. return Context->getConstantExprShuffleVector(Ops[0], Ops[1], Ops[2]);
  405. case Instruction::GetElementPtr:
  406. if (Constant *C = SymbolicallyEvaluateGEP(Ops, NumOps, DestTy, Context, TD))
  407. return C;
  408. return Context->getConstantExprGetElementPtr(Ops[0], Ops+1, NumOps-1);
  409. }
  410. }
  411. /// ConstantFoldCompareInstOperands - Attempt to constant fold a compare
  412. /// instruction (icmp/fcmp) with the specified operands. If it fails, it
  413. /// returns a constant expression of the specified operands.
  414. ///
  415. Constant *llvm::ConstantFoldCompareInstOperands(unsigned Predicate,
  416. Constant*const * Ops,
  417. unsigned NumOps,
  418. LLVMContext *Context,
  419. const TargetData *TD) {
  420. // fold: icmp (inttoptr x), null -> icmp x, 0
  421. // fold: icmp (ptrtoint x), 0 -> icmp x, null
  422. // fold: icmp (inttoptr x), (inttoptr y) -> icmp trunc/zext x, trunc/zext y
  423. // fold: icmp (ptrtoint x), (ptrtoint y) -> icmp x, y
  424. //
  425. // ConstantExpr::getCompare cannot do this, because it doesn't have TD
  426. // around to know if bit truncation is happening.
  427. if (ConstantExpr *CE0 = dyn_cast<ConstantExpr>(Ops[0])) {
  428. if (TD && Ops[1]->isNullValue()) {
  429. const Type *IntPtrTy = TD->getIntPtrType();
  430. if (CE0->getOpcode() == Instruction::IntToPtr) {
  431. // Convert the integer value to the right size to ensure we get the
  432. // proper extension or truncation.
  433. Constant *C = Context->getConstantExprIntegerCast(CE0->getOperand(0),
  434. IntPtrTy, false);
  435. Constant *NewOps[] = { C, Context->getNullValue(C->getType()) };
  436. return ConstantFoldCompareInstOperands(Predicate, NewOps, 2,
  437. Context, TD);
  438. }
  439. // Only do this transformation if the int is intptrty in size, otherwise
  440. // there is a truncation or extension that we aren't modeling.
  441. if (CE0->getOpcode() == Instruction::PtrToInt &&
  442. CE0->getType() == IntPtrTy) {
  443. Constant *C = CE0->getOperand(0);
  444. Constant *NewOps[] = { C, Context->getNullValue(C->getType()) };
  445. // FIXME!
  446. return ConstantFoldCompareInstOperands(Predicate, NewOps, 2,
  447. Context, TD);
  448. }
  449. }
  450. if (ConstantExpr *CE1 = dyn_cast<ConstantExpr>(Ops[1])) {
  451. if (TD && CE0->getOpcode() == CE1->getOpcode()) {
  452. const Type *IntPtrTy = TD->getIntPtrType();
  453. if (CE0->getOpcode() == Instruction::IntToPtr) {
  454. // Convert the integer value to the right size to ensure we get the
  455. // proper extension or truncation.
  456. Constant *C0 = Context->getConstantExprIntegerCast(CE0->getOperand(0),
  457. IntPtrTy, false);
  458. Constant *C1 = Context->getConstantExprIntegerCast(CE1->getOperand(0),
  459. IntPtrTy, false);
  460. Constant *NewOps[] = { C0, C1 };
  461. return ConstantFoldCompareInstOperands(Predicate, NewOps, 2,
  462. Context, TD);
  463. }
  464. // Only do this transformation if the int is intptrty in size, otherwise
  465. // there is a truncation or extension that we aren't modeling.
  466. if ((CE0->getOpcode() == Instruction::PtrToInt &&
  467. CE0->getType() == IntPtrTy &&
  468. CE0->getOperand(0)->getType() == CE1->getOperand(0)->getType())) {
  469. Constant *NewOps[] = {
  470. CE0->getOperand(0), CE1->getOperand(0)
  471. };
  472. return ConstantFoldCompareInstOperands(Predicate, NewOps, 2,
  473. Context, TD);
  474. }
  475. }
  476. }
  477. }
  478. return Context->getConstantExprCompare(Predicate, Ops[0], Ops[1]);
  479. }
  480. /// ConstantFoldLoadThroughGEPConstantExpr - Given a constant and a
  481. /// getelementptr constantexpr, return the constant value being addressed by the
  482. /// constant expression, or null if something is funny and we can't decide.
  483. Constant *llvm::ConstantFoldLoadThroughGEPConstantExpr(Constant *C,
  484. ConstantExpr *CE,
  485. LLVMContext *Context) {
  486. if (CE->getOperand(1) != Context->getNullValue(CE->getOperand(1)->getType()))
  487. return 0; // Do not allow stepping over the value!
  488. // Loop over all of the operands, tracking down which value we are
  489. // addressing...
  490. gep_type_iterator I = gep_type_begin(CE), E = gep_type_end(CE);
  491. for (++I; I != E; ++I)
  492. if (const StructType *STy = dyn_cast<StructType>(*I)) {
  493. ConstantInt *CU = cast<ConstantInt>(I.getOperand());
  494. assert(CU->getZExtValue() < STy->getNumElements() &&
  495. "Struct index out of range!");
  496. unsigned El = (unsigned)CU->getZExtValue();
  497. if (ConstantStruct *CS = dyn_cast<ConstantStruct>(C)) {
  498. C = CS->getOperand(El);
  499. } else if (isa<ConstantAggregateZero>(C)) {
  500. C = Context->getNullValue(STy->getElementType(El));
  501. } else if (isa<UndefValue>(C)) {
  502. C = Context->getUndef(STy->getElementType(El));
  503. } else {
  504. return 0;
  505. }
  506. } else if (ConstantInt *CI = dyn_cast<ConstantInt>(I.getOperand())) {
  507. if (const ArrayType *ATy = dyn_cast<ArrayType>(*I)) {
  508. if (CI->getZExtValue() >= ATy->getNumElements())
  509. return 0;
  510. if (ConstantArray *CA = dyn_cast<ConstantArray>(C))
  511. C = CA->getOperand(CI->getZExtValue());
  512. else if (isa<ConstantAggregateZero>(C))
  513. C = Context->getNullValue(ATy->getElementType());
  514. else if (isa<UndefValue>(C))
  515. C = Context->getUndef(ATy->getElementType());
  516. else
  517. return 0;
  518. } else if (const VectorType *PTy = dyn_cast<VectorType>(*I)) {
  519. if (CI->getZExtValue() >= PTy->getNumElements())
  520. return 0;
  521. if (ConstantVector *CP = dyn_cast<ConstantVector>(C))
  522. C = CP->getOperand(CI->getZExtValue());
  523. else if (isa<ConstantAggregateZero>(C))
  524. C = Context->getNullValue(PTy->getElementType());
  525. else if (isa<UndefValue>(C))
  526. C = Context->getUndef(PTy->getElementType());
  527. else
  528. return 0;
  529. } else {
  530. return 0;
  531. }
  532. } else {
  533. return 0;
  534. }
  535. return C;
  536. }
  537. //===----------------------------------------------------------------------===//
  538. // Constant Folding for Calls
  539. //
  540. /// canConstantFoldCallTo - Return true if its even possible to fold a call to
  541. /// the specified function.
  542. bool
  543. llvm::canConstantFoldCallTo(const Function *F) {
  544. switch (F->getIntrinsicID()) {
  545. case Intrinsic::sqrt:
  546. case Intrinsic::powi:
  547. case Intrinsic::bswap:
  548. case Intrinsic::ctpop:
  549. case Intrinsic::ctlz:
  550. case Intrinsic::cttz:
  551. return true;
  552. default: break;
  553. }
  554. if (!F->hasName()) return false;
  555. const char *Str = F->getNameStart();
  556. unsigned Len = F->getNameLen();
  557. // In these cases, the check of the length is required. We don't want to
  558. // return true for a name like "cos\0blah" which strcmp would return equal to
  559. // "cos", but has length 8.
  560. switch (Str[0]) {
  561. default: return false;
  562. case 'a':
  563. if (Len == 4)
  564. return !strcmp(Str, "acos") || !strcmp(Str, "asin") ||
  565. !strcmp(Str, "atan");
  566. else if (Len == 5)
  567. return !strcmp(Str, "atan2");
  568. return false;
  569. case 'c':
  570. if (Len == 3)
  571. return !strcmp(Str, "cos");
  572. else if (Len == 4)
  573. return !strcmp(Str, "ceil") || !strcmp(Str, "cosf") ||
  574. !strcmp(Str, "cosh");
  575. return false;
  576. case 'e':
  577. if (Len == 3)
  578. return !strcmp(Str, "exp");
  579. return false;
  580. case 'f':
  581. if (Len == 4)
  582. return !strcmp(Str, "fabs") || !strcmp(Str, "fmod");
  583. else if (Len == 5)
  584. return !strcmp(Str, "floor");
  585. return false;
  586. break;
  587. case 'l':
  588. if (Len == 3 && !strcmp(Str, "log"))
  589. return true;
  590. if (Len == 5 && !strcmp(Str, "log10"))
  591. return true;
  592. return false;
  593. case 'p':
  594. if (Len == 3 && !strcmp(Str, "pow"))
  595. return true;
  596. return false;
  597. case 's':
  598. if (Len == 3)
  599. return !strcmp(Str, "sin");
  600. if (Len == 4)
  601. return !strcmp(Str, "sinh") || !strcmp(Str, "sqrt") ||
  602. !strcmp(Str, "sinf");
  603. if (Len == 5)
  604. return !strcmp(Str, "sqrtf");
  605. return false;
  606. case 't':
  607. if (Len == 3 && !strcmp(Str, "tan"))
  608. return true;
  609. else if (Len == 4 && !strcmp(Str, "tanh"))
  610. return true;
  611. return false;
  612. }
  613. }
  614. static Constant *ConstantFoldFP(double (*NativeFP)(double), double V,
  615. const Type *Ty, LLVMContext *Context) {
  616. errno = 0;
  617. V = NativeFP(V);
  618. if (errno != 0) {
  619. errno = 0;
  620. return 0;
  621. }
  622. if (Ty == Type::FloatTy)
  623. return Context->getConstantFP(APFloat((float)V));
  624. if (Ty == Type::DoubleTy)
  625. return Context->getConstantFP(APFloat(V));
  626. LLVM_UNREACHABLE("Can only constant fold float/double");
  627. return 0; // dummy return to suppress warning
  628. }
  629. static Constant *ConstantFoldBinaryFP(double (*NativeFP)(double, double),
  630. double V, double W,
  631. const Type *Ty,
  632. LLVMContext *Context) {
  633. errno = 0;
  634. V = NativeFP(V, W);
  635. if (errno != 0) {
  636. errno = 0;
  637. return 0;
  638. }
  639. if (Ty == Type::FloatTy)
  640. return Context->getConstantFP(APFloat((float)V));
  641. if (Ty == Type::DoubleTy)
  642. return Context->getConstantFP(APFloat(V));
  643. LLVM_UNREACHABLE("Can only constant fold float/double");
  644. return 0; // dummy return to suppress warning
  645. }
  646. /// ConstantFoldCall - Attempt to constant fold a call to the specified function
  647. /// with the specified arguments, returning null if unsuccessful.
  648. Constant *
  649. llvm::ConstantFoldCall(Function *F,
  650. Constant* const* Operands, unsigned NumOperands) {
  651. if (!F->hasName()) return 0;
  652. LLVMContext *Context = F->getContext();
  653. const char *Str = F->getNameStart();
  654. unsigned Len = F->getNameLen();
  655. const Type *Ty = F->getReturnType();
  656. if (NumOperands == 1) {
  657. if (ConstantFP *Op = dyn_cast<ConstantFP>(Operands[0])) {
  658. if (Ty!=Type::FloatTy && Ty!=Type::DoubleTy)
  659. return 0;
  660. /// Currently APFloat versions of these functions do not exist, so we use
  661. /// the host native double versions. Float versions are not called
  662. /// directly but for all these it is true (float)(f((double)arg)) ==
  663. /// f(arg). Long double not supported yet.
  664. double V = Ty==Type::FloatTy ? (double)Op->getValueAPF().convertToFloat():
  665. Op->getValueAPF().convertToDouble();
  666. switch (Str[0]) {
  667. case 'a':
  668. if (Len == 4 && !strcmp(Str, "acos"))
  669. return ConstantFoldFP(acos, V, Ty, Context);
  670. else if (Len == 4 && !strcmp(Str, "asin"))
  671. return ConstantFoldFP(asin, V, Ty, Context);
  672. else if (Len == 4 && !strcmp(Str, "atan"))
  673. return ConstantFoldFP(atan, V, Ty, Context);
  674. break;
  675. case 'c':
  676. if (Len == 4 && !strcmp(Str, "ceil"))
  677. return ConstantFoldFP(ceil, V, Ty, Context);
  678. else if (Len == 3 && !strcmp(Str, "cos"))
  679. return ConstantFoldFP(cos, V, Ty, Context);
  680. else if (Len == 4 && !strcmp(Str, "cosh"))
  681. return ConstantFoldFP(cosh, V, Ty, Context);
  682. else if (Len == 4 && !strcmp(Str, "cosf"))
  683. return ConstantFoldFP(cos, V, Ty, Context);
  684. break;
  685. case 'e':
  686. if (Len == 3 && !strcmp(Str, "exp"))
  687. return ConstantFoldFP(exp, V, Ty, Context);
  688. break;
  689. case 'f':
  690. if (Len == 4 && !strcmp(Str, "fabs"))
  691. return ConstantFoldFP(fabs, V, Ty, Context);
  692. else if (Len == 5 && !strcmp(Str, "floor"))
  693. return ConstantFoldFP(floor, V, Ty, Context);
  694. break;
  695. case 'l':
  696. if (Len == 3 && !strcmp(Str, "log") && V > 0)
  697. return ConstantFoldFP(log, V, Ty, Context);
  698. else if (Len == 5 && !strcmp(Str, "log10") && V > 0)
  699. return ConstantFoldFP(log10, V, Ty, Context);
  700. else if (!strcmp(Str, "llvm.sqrt.f32") ||
  701. !strcmp(Str, "llvm.sqrt.f64")) {
  702. if (V >= -0.0)
  703. return ConstantFoldFP(sqrt, V, Ty, Context);
  704. else // Undefined
  705. return Context->getNullValue(Ty);
  706. }
  707. break;
  708. case 's':
  709. if (Len == 3 && !strcmp(Str, "sin"))
  710. return ConstantFoldFP(sin, V, Ty, Context);
  711. else if (Len == 4 && !strcmp(Str, "sinh"))
  712. return ConstantFoldFP(sinh, V, Ty, Context);
  713. else if (Len == 4 && !strcmp(Str, "sqrt") && V >= 0)
  714. return ConstantFoldFP(sqrt, V, Ty, Context);
  715. else if (Len == 5 && !strcmp(Str, "sqrtf") && V >= 0)
  716. return ConstantFoldFP(sqrt, V, Ty, Context);
  717. else if (Len == 4 && !strcmp(Str, "sinf"))
  718. return ConstantFoldFP(sin, V, Ty, Context);
  719. break;
  720. case 't':
  721. if (Len == 3 && !strcmp(Str, "tan"))
  722. return ConstantFoldFP(tan, V, Ty, Context);
  723. else if (Len == 4 && !strcmp(Str, "tanh"))
  724. return ConstantFoldFP(tanh, V, Ty, Context);
  725. break;
  726. default:
  727. break;
  728. }
  729. } else if (ConstantInt *Op = dyn_cast<ConstantInt>(Operands[0])) {
  730. if (Len > 11 && !memcmp(Str, "llvm.bswap", 10))
  731. return Context->getConstantInt(Op->getValue().byteSwap());
  732. else if (Len > 11 && !memcmp(Str, "llvm.ctpop", 10))
  733. return Context->getConstantInt(Ty, Op->getValue().countPopulation());
  734. else if (Len > 10 && !memcmp(Str, "llvm.cttz", 9))
  735. return Context->getConstantInt(Ty, Op->getValue().countTrailingZeros());
  736. else if (Len > 10 && !memcmp(Str, "llvm.ctlz", 9))
  737. return Context->getConstantInt(Ty, Op->getValue().countLeadingZeros());
  738. }
  739. } else if (NumOperands == 2) {
  740. if (ConstantFP *Op1 = dyn_cast<ConstantFP>(Operands[0])) {
  741. if (Ty!=Type::FloatTy && Ty!=Type::DoubleTy)
  742. return 0;
  743. double Op1V = Ty==Type::FloatTy ?
  744. (double)Op1->getValueAPF().convertToFloat():
  745. Op1->getValueAPF().convertToDouble();
  746. if (ConstantFP *Op2 = dyn_cast<ConstantFP>(Operands[1])) {
  747. double Op2V = Ty==Type::FloatTy ?
  748. (double)Op2->getValueAPF().convertToFloat():
  749. Op2->getValueAPF().convertToDouble();
  750. if (Len == 3 && !strcmp(Str, "pow")) {
  751. return ConstantFoldBinaryFP(pow, Op1V, Op2V, Ty, Context);
  752. } else if (Len == 4 && !strcmp(Str, "fmod")) {
  753. return ConstantFoldBinaryFP(fmod, Op1V, Op2V, Ty, Context);
  754. } else if (Len == 5 && !strcmp(Str, "atan2")) {
  755. return ConstantFoldBinaryFP(atan2, Op1V, Op2V, Ty, Context);
  756. }
  757. } else if (ConstantInt *Op2C = dyn_cast<ConstantInt>(Operands[1])) {
  758. if (!strcmp(Str, "llvm.powi.f32")) {
  759. return Context->getConstantFP(APFloat((float)std::pow((float)Op1V,
  760. (int)Op2C->getZExtValue())));
  761. } else if (!strcmp(Str, "llvm.powi.f64")) {
  762. return Context->getConstantFP(APFloat((double)std::pow((double)Op1V,
  763. (int)Op2C->getZExtValue())));
  764. }
  765. }
  766. }
  767. }
  768. return 0;
  769. }