blob: bf93d4f95663534061449634a5552b7daa0ea39c [file] [log] [blame]
Reid Spencer9472c372007-02-27 06:23:51 +00001//===- ConstantFold.cpp - LLVM constant folder ----------------------------===//
Misha Brukmanfd939082005-04-21 23:48:37 +00002//
John Criswellb576c942003-10-20 19:43:21 +00003// The LLVM Compiler Infrastructure
4//
Chris Lattner4ee451d2007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Misha Brukmanfd939082005-04-21 23:48:37 +00007//
John Criswellb576c942003-10-20 19:43:21 +00008//===----------------------------------------------------------------------===//
Chris Lattner00950542001-06-06 20:29:01 +00009//
Chris Lattnercbfd4062004-01-12 21:13:12 +000010// This file implements folding of constants for LLVM. This implements the
Reid Spencer9472c372007-02-27 06:23:51 +000011// (internal) ConstantFold.h interface, which is used by the
Chris Lattnercbfd4062004-01-12 21:13:12 +000012// ConstantExpr::get* methods to automatically fold constants when possible.
Chris Lattner00950542001-06-06 20:29:01 +000013//
Chris Lattnereab20b52004-01-12 22:07:24 +000014// The current constant folding implementation is implemented in two pieces: the
Micah Villmow3574eca2012-10-08 16:38:25 +000015// pieces that don't need DataLayout, and the pieces that do. This is to avoid
Chandler Carruthc2c50cd2013-01-02 09:10:48 +000016// a dependence in IR on Target.
Chris Lattnereab20b52004-01-12 22:07:24 +000017//
Chris Lattner00950542001-06-06 20:29:01 +000018//===----------------------------------------------------------------------===//
19
Chris Lattner92f6fea2007-02-27 03:05:06 +000020#include "ConstantFold.h"
Chandler Carruthd04a8d42012-12-03 16:50:05 +000021#include "llvm/ADT/SmallVector.h"
Chandler Carruth0b8c9a82013-01-02 11:36:10 +000022#include "llvm/IR/Constants.h"
23#include "llvm/IR/DerivedTypes.h"
24#include "llvm/IR/Function.h"
25#include "llvm/IR/GlobalAlias.h"
26#include "llvm/IR/GlobalVariable.h"
27#include "llvm/IR/Instructions.h"
28#include "llvm/IR/Operator.h"
Chris Lattnera4f0b3a2006-08-27 12:54:02 +000029#include "llvm/Support/Compiler.h"
Torok Edwinc25e7582009-07-11 20:10:48 +000030#include "llvm/Support/ErrorHandling.h"
Chris Lattner0eff5ad2006-10-13 17:22:21 +000031#include "llvm/Support/GetElementPtrTypeIterator.h"
32#include "llvm/Support/ManagedStatic.h"
33#include "llvm/Support/MathExtras.h"
Jeff Cohena97e8db2005-05-03 03:13:01 +000034#include <limits>
Chris Lattner0dc39692003-11-17 19:05:17 +000035using namespace llvm;
Chris Lattner14712a62001-09-09 21:01:20 +000036
Chris Lattnereab20b52004-01-12 22:07:24 +000037//===----------------------------------------------------------------------===//
38// ConstantFold*Instruction Implementations
39//===----------------------------------------------------------------------===//
Chris Lattnereab20b52004-01-12 22:07:24 +000040
Chris Lattnerd59ae902012-01-26 02:32:04 +000041/// BitCastConstantVector - Convert the specified vector Constant node to the
Reid Spencerac9dcb92007-02-15 03:39:18 +000042/// specified vector type. At this point, we know that the elements of the
Dan Gohman07a96762007-07-16 14:29:03 +000043/// input vector constant are all simple integer or FP values.
Chris Lattnerd59ae902012-01-26 02:32:04 +000044static Constant *BitCastConstantVector(Constant *CV, VectorType *DstTy) {
Nadav Rotemd2f27ea2011-02-11 19:37:55 +000045
Nadav Rotem093399c2011-02-17 21:22:27 +000046 if (CV->isAllOnesValue()) return Constant::getAllOnesValue(DstTy);
Nadav Rotemd2f27ea2011-02-11 19:37:55 +000047 if (CV->isNullValue()) return Constant::getNullValue(DstTy);
48
Chris Lattner9eaa8352007-12-11 06:07:39 +000049 // If this cast changes element count then we can't handle it here:
50 // doing so requires endianness information. This should be handled by
51 // Analysis/ConstantFolding.cpp
52 unsigned NumElts = DstTy->getNumElements();
Chris Lattnerd59ae902012-01-26 02:32:04 +000053 if (NumElts != CV->getType()->getVectorNumElements())
Chris Lattner9eaa8352007-12-11 06:07:39 +000054 return 0;
Chris Lattnerd59ae902012-01-26 02:32:04 +000055
56 Type *DstEltTy = DstTy->getElementType();
Dan Gohmanf8a87e82009-08-29 23:35:16 +000057
Chris Lattnerd59ae902012-01-26 02:32:04 +000058 SmallVector<Constant*, 16> Result;
Dan Gohman03e091f2012-04-27 17:50:22 +000059 Type *Ty = IntegerType::get(CV->getContext(), 32);
Chris Lattner9eaa8352007-12-11 06:07:39 +000060 for (unsigned i = 0; i != NumElts; ++i) {
Dan Gohman03e091f2012-04-27 17:50:22 +000061 Constant *C =
62 ConstantExpr::getExtractElement(CV, ConstantInt::get(Ty, i));
Chris Lattnerd59ae902012-01-26 02:32:04 +000063 C = ConstantExpr::getBitCast(C, DstEltTy);
Chris Lattnerd59ae902012-01-26 02:32:04 +000064 Result.push_back(C);
Chris Lattner4460f402006-04-02 01:38:28 +000065 }
Chris Lattner9eaa8352007-12-11 06:07:39 +000066
Owen Andersonaf7ec972009-07-28 21:19:26 +000067 return ConstantVector::get(Result);
Chris Lattner4460f402006-04-02 01:38:28 +000068}
69
Reid Spencer3da59db2006-11-27 01:05:10 +000070/// This function determines which opcode to use to fold two constant cast
71/// expressions together. It uses CastInst::isEliminableCastPair to determine
72/// the opcode. Consequently its just a wrapper around that function.
Reid Spencerdaa10a42007-08-05 19:27:01 +000073/// @brief Determine if it is valid to fold a cast of a cast
Reid Spencer3da59db2006-11-27 01:05:10 +000074static unsigned
75foldConstantCastPair(
76 unsigned opc, ///< opcode of the second cast constant expression
Nick Lewycky33c06ad2009-09-20 01:35:59 +000077 ConstantExpr *Op, ///< the first cast constant expression
Chris Lattnerdb125cf2011-07-18 04:54:35 +000078 Type *DstTy ///< desintation type of the first cast
Reid Spencer3da59db2006-11-27 01:05:10 +000079) {
80 assert(Op && Op->isCast() && "Can't fold cast of cast without a cast!");
81 assert(DstTy && DstTy->isFirstClassType() && "Invalid cast destination type");
82 assert(CastInst::isCast(opc) && "Invalid cast opcode");
Dan Gohmanf8a87e82009-08-29 23:35:16 +000083
Reid Spencer3da59db2006-11-27 01:05:10 +000084 // The the types and opcodes for the two Cast constant expressions
Chris Lattnerdb125cf2011-07-18 04:54:35 +000085 Type *SrcTy = Op->getOperand(0)->getType();
86 Type *MidTy = Op->getType();
Reid Spencer3da59db2006-11-27 01:05:10 +000087 Instruction::CastOps firstOp = Instruction::CastOps(Op->getOpcode());
88 Instruction::CastOps secondOp = Instruction::CastOps(opc);
Chris Lattner4460f402006-04-02 01:38:28 +000089
Duncan Sands446cf942012-10-30 16:03:32 +000090 // Assume that pointers are never more than 64 bits wide.
91 IntegerType *FakeIntPtrTy = Type::getInt64Ty(DstTy->getContext());
92
Reid Spencer3da59db2006-11-27 01:05:10 +000093 // Let CastInst::isEliminableCastPair do the heavy lifting.
94 return CastInst::isEliminableCastPair(firstOp, secondOp, SrcTy, MidTy, DstTy,
Duncan Sands446cf942012-10-30 16:03:32 +000095 FakeIntPtrTy, FakeIntPtrTy,
96 FakeIntPtrTy);
Reid Spencer3da59db2006-11-27 01:05:10 +000097}
98
Chris Lattnerdb125cf2011-07-18 04:54:35 +000099static Constant *FoldBitCast(Constant *V, Type *DestTy) {
100 Type *SrcTy = V->getType();
Chris Lattner2b0f8062007-12-11 05:55:02 +0000101 if (SrcTy == DestTy)
102 return V; // no-op cast
Dan Gohmanf8a87e82009-08-29 23:35:16 +0000103
Chris Lattner2b0f8062007-12-11 05:55:02 +0000104 // Check to see if we are casting a pointer to an aggregate to a pointer to
105 // the first element. If so, return the appropriate GEP instruction.
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000106 if (PointerType *PTy = dyn_cast<PointerType>(V->getType()))
107 if (PointerType *DPTy = dyn_cast<PointerType>(DestTy))
Duncan Sands1876abe2012-01-11 12:20:08 +0000108 if (PTy->getAddressSpace() == DPTy->getAddressSpace()
109 && DPTy->getElementType()->isSized()) {
Nate Begeman83ad90a2008-03-31 00:22:16 +0000110 SmallVector<Value*, 8> IdxList;
Chris Lattnerb29d5962010-02-01 20:48:08 +0000111 Value *Zero =
112 Constant::getNullValue(Type::getInt32Ty(DPTy->getContext()));
Dan Gohmanc7520642009-08-12 00:32:55 +0000113 IdxList.push_back(Zero);
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000114 Type *ElTy = PTy->getElementType();
Nate Begeman83ad90a2008-03-31 00:22:16 +0000115 while (ElTy != DPTy->getElementType()) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000116 if (StructType *STy = dyn_cast<StructType>(ElTy)) {
Nate Begeman83ad90a2008-03-31 00:22:16 +0000117 if (STy->getNumElements() == 0) break;
118 ElTy = STy->getElementType(0);
Dan Gohmanc7520642009-08-12 00:32:55 +0000119 IdxList.push_back(Zero);
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000120 } else if (SequentialType *STy =
Nate Begeman83ad90a2008-03-31 00:22:16 +0000121 dyn_cast<SequentialType>(ElTy)) {
Duncan Sands1df98592010-02-16 11:11:14 +0000122 if (ElTy->isPointerTy()) break; // Can't index into pointers!
Nate Begeman83ad90a2008-03-31 00:22:16 +0000123 ElTy = STy->getElementType();
Dan Gohmanc7520642009-08-12 00:32:55 +0000124 IdxList.push_back(Zero);
Nate Begeman83ad90a2008-03-31 00:22:16 +0000125 } else {
126 break;
127 }
Chris Lattner2b0f8062007-12-11 05:55:02 +0000128 }
Dan Gohmanf8a87e82009-08-29 23:35:16 +0000129
Nate Begeman83ad90a2008-03-31 00:22:16 +0000130 if (ElTy == DPTy->getElementType())
Dan Gohman6e7ad952009-09-03 23:34:49 +0000131 // This GEP is inbounds because all indices are zero.
Jay Foaddab3d292011-07-21 14:31:17 +0000132 return ConstantExpr::getInBoundsGetElementPtr(V, IdxList);
Chris Lattner2b0f8062007-12-11 05:55:02 +0000133 }
Dan Gohmanf8a87e82009-08-29 23:35:16 +0000134
Chris Lattner2b0f8062007-12-11 05:55:02 +0000135 // Handle casts from one vector constant to another. We know that the src
136 // and dest type have the same size (otherwise its an illegal cast).
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000137 if (VectorType *DestPTy = dyn_cast<VectorType>(DestTy)) {
138 if (VectorType *SrcTy = dyn_cast<VectorType>(V->getType())) {
Chris Lattner2b0f8062007-12-11 05:55:02 +0000139 assert(DestPTy->getBitWidth() == SrcTy->getBitWidth() &&
140 "Not cast between same sized vectors!");
Devang Patelb6dc9352008-11-03 23:20:04 +0000141 SrcTy = NULL;
Chris Lattner2b0f8062007-12-11 05:55:02 +0000142 // First, check for null. Undef is already handled.
143 if (isa<ConstantAggregateZero>(V))
Owen Andersona7235ea2009-07-31 20:28:14 +0000144 return Constant::getNullValue(DestTy);
Dan Gohmanf8a87e82009-08-29 23:35:16 +0000145
Chris Lattnerd59ae902012-01-26 02:32:04 +0000146 // Handle ConstantVector and ConstantAggregateVector.
147 return BitCastConstantVector(V, DestPTy);
Chris Lattner2b0f8062007-12-11 05:55:02 +0000148 }
Chris Lattner86851032008-10-16 05:26:51 +0000149
150 // Canonicalize scalar-to-vector bitcasts into vector-to-vector bitcasts
151 // This allows for other simplifications (although some of them
152 // can only be handled by Analysis/ConstantFolding.cpp).
153 if (isa<ConstantInt>(V) || isa<ConstantFP>(V))
Chris Lattner2ca5c862011-02-15 00:14:00 +0000154 return ConstantExpr::getBitCast(ConstantVector::get(V), DestPTy);
Chris Lattner2b0f8062007-12-11 05:55:02 +0000155 }
Dan Gohmanf8a87e82009-08-29 23:35:16 +0000156
Chris Lattner2b0f8062007-12-11 05:55:02 +0000157 // Finally, implement bitcast folding now. The code below doesn't handle
158 // bitcast right.
159 if (isa<ConstantPointerNull>(V)) // ptr->ptr cast.
Owen Anderson9e9a0d52009-07-30 23:03:37 +0000160 return ConstantPointerNull::get(cast<PointerType>(DestTy));
Dan Gohmanf8a87e82009-08-29 23:35:16 +0000161
Chris Lattner2b0f8062007-12-11 05:55:02 +0000162 // Handle integral constant input.
Nick Lewycky33c06ad2009-09-20 01:35:59 +0000163 if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
Duncan Sandsb0bc6c32010-02-15 16:12:20 +0000164 if (DestTy->isIntegerTy())
Chris Lattner2b0f8062007-12-11 05:55:02 +0000165 // Integral -> Integral. This is a no-op because the bit widths must
166 // be the same. Consequently, we just fold to V.
167 return V;
Duncan Sandsa06aef62009-02-04 10:17:14 +0000168
Duncan Sandsb0bc6c32010-02-15 16:12:20 +0000169 if (DestTy->isFloatingPointTy())
Chris Lattnerb29d5962010-02-01 20:48:08 +0000170 return ConstantFP::get(DestTy->getContext(),
Tim Northover0a29cb02013-01-22 09:46:31 +0000171 APFloat(DestTy->getFltSemantics(),
172 CI->getValue()));
Duncan Sandsa06aef62009-02-04 10:17:14 +0000173
Chris Lattner2b0f8062007-12-11 05:55:02 +0000174 // Otherwise, can't fold this (vector?)
175 return 0;
176 }
Duncan Sands09750272009-02-04 11:17:06 +0000177
Chris Lattnerb29d5962010-02-01 20:48:08 +0000178 // Handle ConstantFP input: FP -> Integral.
Nick Lewycky33c06ad2009-09-20 01:35:59 +0000179 if (ConstantFP *FP = dyn_cast<ConstantFP>(V))
Chris Lattnerb29d5962010-02-01 20:48:08 +0000180 return ConstantInt::get(FP->getContext(),
181 FP->getValueAPF().bitcastToAPInt());
Duncan Sands09750272009-02-04 11:17:06 +0000182
Chris Lattner2b0f8062007-12-11 05:55:02 +0000183 return 0;
184}
185
186
Chris Lattner59c4eba2009-10-17 21:53:27 +0000187/// ExtractConstantBytes - V is an integer constant which only has a subset of
188/// its bytes used. The bytes used are indicated by ByteStart (which is the
189/// first byte used, counting from the least significant byte) and ByteSize,
190/// which is the number of bytes used.
191///
192/// This function analyzes the specified constant to see if the specified byte
193/// range can be returned as a simplified constant. If so, the constant is
194/// returned, otherwise null is returned.
195///
196static Constant *ExtractConstantBytes(Constant *C, unsigned ByteStart,
197 unsigned ByteSize) {
Duncan Sands1df98592010-02-16 11:11:14 +0000198 assert(C->getType()->isIntegerTy() &&
Chris Lattner59c4eba2009-10-17 21:53:27 +0000199 (cast<IntegerType>(C->getType())->getBitWidth() & 7) == 0 &&
200 "Non-byte sized integer input");
201 unsigned CSize = cast<IntegerType>(C->getType())->getBitWidth()/8;
202 assert(ByteSize && "Must be accessing some piece");
203 assert(ByteStart+ByteSize <= CSize && "Extracting invalid piece from input");
204 assert(ByteSize != CSize && "Should not extract everything");
205
206 // Constant Integers are simple.
207 if (ConstantInt *CI = dyn_cast<ConstantInt>(C)) {
208 APInt V = CI->getValue();
209 if (ByteStart)
210 V = V.lshr(ByteStart*8);
Jay Foad40f8f622010-12-07 08:25:19 +0000211 V = V.trunc(ByteSize*8);
Chris Lattner59c4eba2009-10-17 21:53:27 +0000212 return ConstantInt::get(CI->getContext(), V);
213 }
214
215 // In the input is a constant expr, we might be able to recursively simplify.
216 // If not, we definitely can't do anything.
217 ConstantExpr *CE = dyn_cast<ConstantExpr>(C);
218 if (CE == 0) return 0;
219
220 switch (CE->getOpcode()) {
221 default: return 0;
222 case Instruction::Or: {
Chris Lattner0eeb9132009-10-28 05:14:34 +0000223 Constant *RHS = ExtractConstantBytes(CE->getOperand(1), ByteStart,ByteSize);
Chris Lattner59c4eba2009-10-17 21:53:27 +0000224 if (RHS == 0)
225 return 0;
226
227 // X | -1 -> -1.
228 if (ConstantInt *RHSC = dyn_cast<ConstantInt>(RHS))
229 if (RHSC->isAllOnesValue())
230 return RHSC;
231
Chris Lattner0eeb9132009-10-28 05:14:34 +0000232 Constant *LHS = ExtractConstantBytes(CE->getOperand(0), ByteStart,ByteSize);
Chris Lattner59c4eba2009-10-17 21:53:27 +0000233 if (LHS == 0)
234 return 0;
235 return ConstantExpr::getOr(LHS, RHS);
236 }
237 case Instruction::And: {
Chris Lattner0eeb9132009-10-28 05:14:34 +0000238 Constant *RHS = ExtractConstantBytes(CE->getOperand(1), ByteStart,ByteSize);
Chris Lattner59c4eba2009-10-17 21:53:27 +0000239 if (RHS == 0)
240 return 0;
241
242 // X & 0 -> 0.
243 if (RHS->isNullValue())
244 return RHS;
245
Chris Lattner0eeb9132009-10-28 05:14:34 +0000246 Constant *LHS = ExtractConstantBytes(CE->getOperand(0), ByteStart,ByteSize);
Chris Lattner59c4eba2009-10-17 21:53:27 +0000247 if (LHS == 0)
248 return 0;
249 return ConstantExpr::getAnd(LHS, RHS);
250 }
251 case Instruction::LShr: {
252 ConstantInt *Amt = dyn_cast<ConstantInt>(CE->getOperand(1));
253 if (Amt == 0)
254 return 0;
255 unsigned ShAmt = Amt->getZExtValue();
256 // Cannot analyze non-byte shifts.
257 if ((ShAmt & 7) != 0)
258 return 0;
259 ShAmt >>= 3;
260
261 // If the extract is known to be all zeros, return zero.
262 if (ByteStart >= CSize-ShAmt)
263 return Constant::getNullValue(IntegerType::get(CE->getContext(),
264 ByteSize*8));
265 // If the extract is known to be fully in the input, extract it.
266 if (ByteStart+ByteSize+ShAmt <= CSize)
Chris Lattner0eeb9132009-10-28 05:14:34 +0000267 return ExtractConstantBytes(CE->getOperand(0), ByteStart+ShAmt, ByteSize);
Chris Lattner59c4eba2009-10-17 21:53:27 +0000268
269 // TODO: Handle the 'partially zero' case.
270 return 0;
271 }
272
273 case Instruction::Shl: {
274 ConstantInt *Amt = dyn_cast<ConstantInt>(CE->getOperand(1));
275 if (Amt == 0)
276 return 0;
277 unsigned ShAmt = Amt->getZExtValue();
278 // Cannot analyze non-byte shifts.
279 if ((ShAmt & 7) != 0)
280 return 0;
281 ShAmt >>= 3;
282
283 // If the extract is known to be all zeros, return zero.
284 if (ByteStart+ByteSize <= ShAmt)
285 return Constant::getNullValue(IntegerType::get(CE->getContext(),
286 ByteSize*8));
287 // If the extract is known to be fully in the input, extract it.
288 if (ByteStart >= ShAmt)
Chris Lattner0eeb9132009-10-28 05:14:34 +0000289 return ExtractConstantBytes(CE->getOperand(0), ByteStart-ShAmt, ByteSize);
Chris Lattner59c4eba2009-10-17 21:53:27 +0000290
291 // TODO: Handle the 'partially zero' case.
292 return 0;
293 }
294
295 case Instruction::ZExt: {
296 unsigned SrcBitSize =
Chris Lattner0eeb9132009-10-28 05:14:34 +0000297 cast<IntegerType>(CE->getOperand(0)->getType())->getBitWidth();
Chris Lattner59c4eba2009-10-17 21:53:27 +0000298
299 // If extracting something that is completely zero, return 0.
300 if (ByteStart*8 >= SrcBitSize)
301 return Constant::getNullValue(IntegerType::get(CE->getContext(),
302 ByteSize*8));
303
304 // If exactly extracting the input, return it.
305 if (ByteStart == 0 && ByteSize*8 == SrcBitSize)
Chris Lattner0eeb9132009-10-28 05:14:34 +0000306 return CE->getOperand(0);
Chris Lattner59c4eba2009-10-17 21:53:27 +0000307
308 // If extracting something completely in the input, if if the input is a
309 // multiple of 8 bits, recurse.
310 if ((SrcBitSize&7) == 0 && (ByteStart+ByteSize)*8 <= SrcBitSize)
Chris Lattner0eeb9132009-10-28 05:14:34 +0000311 return ExtractConstantBytes(CE->getOperand(0), ByteStart, ByteSize);
Chris Lattner59c4eba2009-10-17 21:53:27 +0000312
313 // Otherwise, if extracting a subset of the input, which is not multiple of
314 // 8 bits, do a shift and trunc to get the bits.
315 if ((ByteStart+ByteSize)*8 < SrcBitSize) {
316 assert((SrcBitSize&7) && "Shouldn't get byte sized case here");
Chris Lattner0eeb9132009-10-28 05:14:34 +0000317 Constant *Res = CE->getOperand(0);
Chris Lattner59c4eba2009-10-17 21:53:27 +0000318 if (ByteStart)
319 Res = ConstantExpr::getLShr(Res,
320 ConstantInt::get(Res->getType(), ByteStart*8));
321 return ConstantExpr::getTrunc(Res, IntegerType::get(C->getContext(),
322 ByteSize*8));
323 }
324
325 // TODO: Handle the 'partially zero' case.
326 return 0;
327 }
328 }
329}
330
Dan Gohman4f8eea82010-02-01 18:27:38 +0000331/// getFoldedSizeOf - Return a ConstantExpr with type DestTy for sizeof
332/// on Ty, with any known factors factored out. If Folded is false,
333/// return null if no factoring was possible, to avoid endlessly
334/// bouncing an unfoldable expression back into the top-level folder.
335///
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000336static Constant *getFoldedSizeOf(Type *Ty, Type *DestTy,
Dan Gohman4f8eea82010-02-01 18:27:38 +0000337 bool Folded) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000338 if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
Dan Gohman4f8eea82010-02-01 18:27:38 +0000339 Constant *N = ConstantInt::get(DestTy, ATy->getNumElements());
340 Constant *E = getFoldedSizeOf(ATy->getElementType(), DestTy, true);
341 return ConstantExpr::getNUWMul(E, N);
342 }
Dan Gohman2440cf12010-02-25 16:05:33 +0000343
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000344 if (StructType *STy = dyn_cast<StructType>(Ty))
Dan Gohman4f8eea82010-02-01 18:27:38 +0000345 if (!STy->isPacked()) {
346 unsigned NumElems = STy->getNumElements();
347 // An empty struct has size zero.
348 if (NumElems == 0)
349 return ConstantExpr::getNullValue(DestTy);
Dan Gohman6acb86d2010-02-02 01:41:39 +0000350 // Check for a struct with all members having the same size.
351 Constant *MemberSize =
352 getFoldedSizeOf(STy->getElementType(0), DestTy, true);
Dan Gohman4f8eea82010-02-01 18:27:38 +0000353 bool AllSame = true;
354 for (unsigned i = 1; i != NumElems; ++i)
Dan Gohman6acb86d2010-02-02 01:41:39 +0000355 if (MemberSize !=
356 getFoldedSizeOf(STy->getElementType(i), DestTy, true)) {
Dan Gohman4f8eea82010-02-01 18:27:38 +0000357 AllSame = false;
358 break;
359 }
360 if (AllSame) {
361 Constant *N = ConstantInt::get(DestTy, NumElems);
Dan Gohman6acb86d2010-02-02 01:41:39 +0000362 return ConstantExpr::getNUWMul(MemberSize, N);
Dan Gohman4f8eea82010-02-01 18:27:38 +0000363 }
364 }
365
Dan Gohmana84ffed2010-02-10 06:13:07 +0000366 // Pointer size doesn't depend on the pointee type, so canonicalize them
367 // to an arbitrary pointee.
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000368 if (PointerType *PTy = dyn_cast<PointerType>(Ty))
Duncan Sandsb0bc6c32010-02-15 16:12:20 +0000369 if (!PTy->getElementType()->isIntegerTy(1))
Dan Gohmana84ffed2010-02-10 06:13:07 +0000370 return
371 getFoldedSizeOf(PointerType::get(IntegerType::get(PTy->getContext(), 1),
372 PTy->getAddressSpace()),
373 DestTy, true);
374
Dan Gohman4f8eea82010-02-01 18:27:38 +0000375 // If there's no interesting folding happening, bail so that we don't create
376 // a constant that looks like it needs folding but really doesn't.
377 if (!Folded)
378 return 0;
379
380 // Base case: Get a regular sizeof expression.
381 Constant *C = ConstantExpr::getSizeOf(Ty);
382 C = ConstantExpr::getCast(CastInst::getCastOpcode(C, false,
383 DestTy, false),
384 C, DestTy);
385 return C;
386}
387
Dan Gohman6acb86d2010-02-02 01:41:39 +0000388/// getFoldedAlignOf - Return a ConstantExpr with type DestTy for alignof
389/// on Ty, with any known factors factored out. If Folded is false,
390/// return null if no factoring was possible, to avoid endlessly
391/// bouncing an unfoldable expression back into the top-level folder.
392///
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000393static Constant *getFoldedAlignOf(Type *Ty, Type *DestTy,
Dan Gohman6acb86d2010-02-02 01:41:39 +0000394 bool Folded) {
395 // The alignment of an array is equal to the alignment of the
396 // array element. Note that this is not always true for vectors.
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000397 if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
Dan Gohman6acb86d2010-02-02 01:41:39 +0000398 Constant *C = ConstantExpr::getAlignOf(ATy->getElementType());
399 C = ConstantExpr::getCast(CastInst::getCastOpcode(C, false,
400 DestTy,
401 false),
402 C, DestTy);
403 return C;
404 }
405
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000406 if (StructType *STy = dyn_cast<StructType>(Ty)) {
Dan Gohman6acb86d2010-02-02 01:41:39 +0000407 // Packed structs always have an alignment of 1.
408 if (STy->isPacked())
409 return ConstantInt::get(DestTy, 1);
410
411 // Otherwise, struct alignment is the maximum alignment of any member.
412 // Without target data, we can't compare much, but we can check to see
413 // if all the members have the same alignment.
414 unsigned NumElems = STy->getNumElements();
415 // An empty struct has minimal alignment.
416 if (NumElems == 0)
417 return ConstantInt::get(DestTy, 1);
418 // Check for a struct with all members having the same alignment.
419 Constant *MemberAlign =
420 getFoldedAlignOf(STy->getElementType(0), DestTy, true);
421 bool AllSame = true;
422 for (unsigned i = 1; i != NumElems; ++i)
423 if (MemberAlign != getFoldedAlignOf(STy->getElementType(i), DestTy, true)) {
424 AllSame = false;
425 break;
426 }
427 if (AllSame)
428 return MemberAlign;
429 }
430
Dan Gohmana84ffed2010-02-10 06:13:07 +0000431 // Pointer alignment doesn't depend on the pointee type, so canonicalize them
432 // to an arbitrary pointee.
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000433 if (PointerType *PTy = dyn_cast<PointerType>(Ty))
Duncan Sandsb0bc6c32010-02-15 16:12:20 +0000434 if (!PTy->getElementType()->isIntegerTy(1))
Dan Gohmana84ffed2010-02-10 06:13:07 +0000435 return
436 getFoldedAlignOf(PointerType::get(IntegerType::get(PTy->getContext(),
437 1),
438 PTy->getAddressSpace()),
439 DestTy, true);
440
Dan Gohman6acb86d2010-02-02 01:41:39 +0000441 // If there's no interesting folding happening, bail so that we don't create
442 // a constant that looks like it needs folding but really doesn't.
443 if (!Folded)
444 return 0;
445
446 // Base case: Get a regular alignof expression.
447 Constant *C = ConstantExpr::getAlignOf(Ty);
448 C = ConstantExpr::getCast(CastInst::getCastOpcode(C, false,
449 DestTy, false),
450 C, DestTy);
451 return C;
452}
453
Dan Gohman4f8eea82010-02-01 18:27:38 +0000454/// getFoldedOffsetOf - Return a ConstantExpr with type DestTy for offsetof
455/// on Ty and FieldNo, with any known factors factored out. If Folded is false,
456/// return null if no factoring was possible, to avoid endlessly
457/// bouncing an unfoldable expression back into the top-level folder.
458///
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000459static Constant *getFoldedOffsetOf(Type *Ty, Constant *FieldNo,
460 Type *DestTy,
Dan Gohman4f8eea82010-02-01 18:27:38 +0000461 bool Folded) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000462 if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
Dan Gohman4f8eea82010-02-01 18:27:38 +0000463 Constant *N = ConstantExpr::getCast(CastInst::getCastOpcode(FieldNo, false,
464 DestTy, false),
465 FieldNo, DestTy);
466 Constant *E = getFoldedSizeOf(ATy->getElementType(), DestTy, true);
467 return ConstantExpr::getNUWMul(E, N);
468 }
Dan Gohman2440cf12010-02-25 16:05:33 +0000469
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000470 if (StructType *STy = dyn_cast<StructType>(Ty))
Dan Gohman4f8eea82010-02-01 18:27:38 +0000471 if (!STy->isPacked()) {
472 unsigned NumElems = STy->getNumElements();
473 // An empty struct has no members.
474 if (NumElems == 0)
475 return 0;
Dan Gohman6acb86d2010-02-02 01:41:39 +0000476 // Check for a struct with all members having the same size.
477 Constant *MemberSize =
478 getFoldedSizeOf(STy->getElementType(0), DestTy, true);
Dan Gohman4f8eea82010-02-01 18:27:38 +0000479 bool AllSame = true;
480 for (unsigned i = 1; i != NumElems; ++i)
Dan Gohman6acb86d2010-02-02 01:41:39 +0000481 if (MemberSize !=
482 getFoldedSizeOf(STy->getElementType(i), DestTy, true)) {
Dan Gohman4f8eea82010-02-01 18:27:38 +0000483 AllSame = false;
484 break;
485 }
486 if (AllSame) {
487 Constant *N = ConstantExpr::getCast(CastInst::getCastOpcode(FieldNo,
488 false,
489 DestTy,
490 false),
491 FieldNo, DestTy);
Dan Gohman6acb86d2010-02-02 01:41:39 +0000492 return ConstantExpr::getNUWMul(MemberSize, N);
Dan Gohman4f8eea82010-02-01 18:27:38 +0000493 }
494 }
495
496 // If there's no interesting folding happening, bail so that we don't create
497 // a constant that looks like it needs folding but really doesn't.
498 if (!Folded)
499 return 0;
500
501 // Base case: Get a regular offsetof expression.
502 Constant *C = ConstantExpr::getOffsetOf(Ty, FieldNo);
503 C = ConstantExpr::getCast(CastInst::getCastOpcode(C, false,
504 DestTy, false),
505 C, DestTy);
506 return C;
507}
Chris Lattner59c4eba2009-10-17 21:53:27 +0000508
Chris Lattnerb29d5962010-02-01 20:48:08 +0000509Constant *llvm::ConstantFoldCastInstruction(unsigned opc, Constant *V,
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000510 Type *DestTy) {
Chris Lattnerd2f09962007-07-20 22:09:02 +0000511 if (isa<UndefValue>(V)) {
512 // zext(undef) = 0, because the top bits will be zero.
513 // sext(undef) = 0, because the top bits will all be the same.
Chris Lattner46acf852008-02-19 06:22:12 +0000514 // [us]itofp(undef) = 0, because the result value is bounded.
515 if (opc == Instruction::ZExt || opc == Instruction::SExt ||
516 opc == Instruction::UIToFP || opc == Instruction::SIToFP)
Owen Andersona7235ea2009-07-31 20:28:14 +0000517 return Constant::getNullValue(DestTy);
Owen Anderson9e9a0d52009-07-30 23:03:37 +0000518 return UndefValue::get(DestTy);
Chris Lattnerd2f09962007-07-20 22:09:02 +0000519 }
Nick Lewycky4c93a0f2011-01-21 01:12:09 +0000520
Nick Lewycky4c93a0f2011-01-21 01:12:09 +0000521 if (V->isNullValue() && !DestTy->isX86_MMXTy())
522 return Constant::getNullValue(DestTy);
523
Reid Spencer3da59db2006-11-27 01:05:10 +0000524 // If the cast operand is a constant expression, there's a few things we can
525 // do to try to simplify it.
Nick Lewycky33c06ad2009-09-20 01:35:59 +0000526 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V)) {
Reid Spencer3da59db2006-11-27 01:05:10 +0000527 if (CE->isCast()) {
Reid Spencer575d95c2006-12-04 02:46:44 +0000528 // Try hard to fold cast of cast because they are often eliminable.
Reid Spencer3da59db2006-11-27 01:05:10 +0000529 if (unsigned newOpc = foldConstantCastPair(opc, CE, DestTy))
Owen Andersonbaf3c402009-07-29 18:55:55 +0000530 return ConstantExpr::getCast(newOpc, CE->getOperand(0), DestTy);
Chris Lattnereab20b52004-01-12 22:07:24 +0000531 } else if (CE->getOpcode() == Instruction::GetElementPtr) {
532 // If all of the indexes in the GEP are null values, there is no pointer
533 // adjustment going on. We might as well cast the source pointer.
534 bool isAllNull = true;
535 for (unsigned i = 1, e = CE->getNumOperands(); i != e; ++i)
536 if (!CE->getOperand(i)->isNullValue()) {
537 isAllNull = false;
538 break;
539 }
540 if (isAllNull)
Reid Spencer575d95c2006-12-04 02:46:44 +0000541 // This is casting one pointer type to another, always BitCast
Owen Andersonbaf3c402009-07-29 18:55:55 +0000542 return ConstantExpr::getPointerCast(CE->getOperand(0), DestTy);
Chris Lattnereab20b52004-01-12 22:07:24 +0000543 }
Chris Lattner71d37782004-10-16 23:31:32 +0000544 }
Chris Lattnereab20b52004-01-12 22:07:24 +0000545
Dan Gohman6de29f82009-06-15 22:12:54 +0000546 // If the cast operand is a constant vector, perform the cast by
547 // operating on each element. In the cast of bitcasts, the element
548 // count may be mismatched; don't attempt to handle that here.
Chris Lattnera78fa8c2012-01-27 03:08:05 +0000549 if ((isa<ConstantVector>(V) || isa<ConstantDataVector>(V)) &&
550 DestTy->isVectorTy() &&
551 DestTy->getVectorNumElements() == V->getType()->getVectorNumElements()) {
552 SmallVector<Constant*, 16> res;
553 VectorType *DestVecTy = cast<VectorType>(DestTy);
554 Type *DstEltTy = DestVecTy->getElementType();
Dan Gohman03e091f2012-04-27 17:50:22 +0000555 Type *Ty = IntegerType::get(V->getContext(), 32);
556 for (unsigned i = 0, e = V->getType()->getVectorNumElements(); i != e; ++i) {
557 Constant *C =
558 ConstantExpr::getExtractElement(V, ConstantInt::get(Ty, i));
559 res.push_back(ConstantExpr::getCast(opc, C, DstEltTy));
560 }
Chris Lattnera78fa8c2012-01-27 03:08:05 +0000561 return ConstantVector::get(res);
562 }
Dan Gohman6de29f82009-06-15 22:12:54 +0000563
Reid Spencer390437f2006-12-19 03:15:47 +0000564 // We actually have to do a cast now. Perform the cast according to the
565 // opcode specified.
Reid Spencer3da59db2006-11-27 01:05:10 +0000566 switch (opc) {
Chris Lattner59c4eba2009-10-17 21:53:27 +0000567 default:
568 llvm_unreachable("Failed to cast constant expression");
Reid Spencer3da59db2006-11-27 01:05:10 +0000569 case Instruction::FPTrunc:
Reid Spencer3da59db2006-11-27 01:05:10 +0000570 case Instruction::FPExt:
Nick Lewycky33c06ad2009-09-20 01:35:59 +0000571 if (ConstantFP *FPC = dyn_cast<ConstantFP>(V)) {
Dale Johannesen23a98552008-10-09 23:00:39 +0000572 bool ignored;
Dale Johannesenac122052007-09-19 14:22:58 +0000573 APFloat Val = FPC->getValueAPF();
Dan Gohmance163392011-12-17 00:04:22 +0000574 Val.convert(DestTy->isHalfTy() ? APFloat::IEEEhalf :
575 DestTy->isFloatTy() ? APFloat::IEEEsingle :
Chris Lattnercf0fe8d2009-10-05 05:54:46 +0000576 DestTy->isDoubleTy() ? APFloat::IEEEdouble :
577 DestTy->isX86_FP80Ty() ? APFloat::x87DoubleExtended :
578 DestTy->isFP128Ty() ? APFloat::IEEEquad :
Ulrich Weigand3467b9f2012-10-30 12:33:18 +0000579 DestTy->isPPC_FP128Ty() ? APFloat::PPCDoubleDouble :
Dale Johannesenac122052007-09-19 14:22:58 +0000580 APFloat::Bogus,
Dale Johannesen23a98552008-10-09 23:00:39 +0000581 APFloat::rmNearestTiesToEven, &ignored);
Chris Lattnerb29d5962010-02-01 20:48:08 +0000582 return ConstantFP::get(V->getContext(), Val);
Dale Johannesen43421b32007-09-06 18:13:44 +0000583 }
Reid Spencer85e36e42006-12-19 07:41:40 +0000584 return 0; // Can't fold.
585 case Instruction::FPToUI:
Reid Spencer85e36e42006-12-19 07:41:40 +0000586 case Instruction::FPToSI:
Nick Lewycky33c06ad2009-09-20 01:35:59 +0000587 if (ConstantFP *FPC = dyn_cast<ConstantFP>(V)) {
Chris Lattner3cab1c72007-10-15 05:34:10 +0000588 const APFloat &V = FPC->getValueAPF();
Dale Johannesen23a98552008-10-09 23:00:39 +0000589 bool ignored;
Dale Johannesenac122052007-09-19 14:22:58 +0000590 uint64_t x[2];
Reid Spencer9472c372007-02-27 06:23:51 +0000591 uint32_t DestBitWidth = cast<IntegerType>(DestTy)->getBitWidth();
Dale Johannesen350add82007-09-25 23:32:20 +0000592 (void) V.convertToInteger(x, DestBitWidth, opc==Instruction::FPToSI,
Dale Johannesen23a98552008-10-09 23:00:39 +0000593 APFloat::rmTowardZero, &ignored);
Jeffrey Yasskin3ba292d2011-07-18 21:45:40 +0000594 APInt Val(DestBitWidth, x);
Chris Lattnerb29d5962010-02-01 20:48:08 +0000595 return ConstantInt::get(FPC->getContext(), Val);
Reid Spencer9472c372007-02-27 06:23:51 +0000596 }
Reid Spencer85e36e42006-12-19 07:41:40 +0000597 return 0; // Can't fold.
598 case Instruction::IntToPtr: //always treated as unsigned
599 if (V->isNullValue()) // Is it an integral null value?
Owen Anderson9e9a0d52009-07-30 23:03:37 +0000600 return ConstantPointerNull::get(cast<PointerType>(DestTy));
Reid Spencer85e36e42006-12-19 07:41:40 +0000601 return 0; // Other pointer types cannot be casted
602 case Instruction::PtrToInt: // always treated as unsigned
Dan Gohman0f5efe52010-01-28 02:15:55 +0000603 // Is it a null pointer value?
604 if (V->isNullValue())
Owen Andersoneed707b2009-07-24 23:12:02 +0000605 return ConstantInt::get(DestTy, 0);
Dan Gohman4f8eea82010-02-01 18:27:38 +0000606 // If this is a sizeof-like expression, pull out multiplications by
607 // known factors to expose them to subsequent folding. If it's an
608 // alignof-like expression, factor out known factors.
Dan Gohman0f5efe52010-01-28 02:15:55 +0000609 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
610 if (CE->getOpcode() == Instruction::GetElementPtr &&
Dan Gohman4f8eea82010-02-01 18:27:38 +0000611 CE->getOperand(0)->isNullValue()) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000612 Type *Ty =
Dan Gohman4f8eea82010-02-01 18:27:38 +0000613 cast<PointerType>(CE->getOperand(0)->getType())->getElementType();
614 if (CE->getNumOperands() == 2) {
615 // Handle a sizeof-like expression.
616 Constant *Idx = CE->getOperand(1);
617 bool isOne = isa<ConstantInt>(Idx) && cast<ConstantInt>(Idx)->isOne();
618 if (Constant *C = getFoldedSizeOf(Ty, DestTy, !isOne)) {
619 Idx = ConstantExpr::getCast(CastInst::getCastOpcode(Idx, true,
Dan Gohman0f5efe52010-01-28 02:15:55 +0000620 DestTy, false),
Dan Gohman4f8eea82010-02-01 18:27:38 +0000621 Idx, DestTy);
622 return ConstantExpr::getMul(C, Idx);
Dan Gohman0f5efe52010-01-28 02:15:55 +0000623 }
Dan Gohman4f8eea82010-02-01 18:27:38 +0000624 } else if (CE->getNumOperands() == 3 &&
625 CE->getOperand(1)->isNullValue()) {
626 // Handle an alignof-like expression.
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000627 if (StructType *STy = dyn_cast<StructType>(Ty))
Dan Gohman4f8eea82010-02-01 18:27:38 +0000628 if (!STy->isPacked()) {
629 ConstantInt *CI = cast<ConstantInt>(CE->getOperand(2));
630 if (CI->isOne() &&
631 STy->getNumElements() == 2 &&
Duncan Sandsb0bc6c32010-02-15 16:12:20 +0000632 STy->getElementType(0)->isIntegerTy(1)) {
Dan Gohman6acb86d2010-02-02 01:41:39 +0000633 return getFoldedAlignOf(STy->getElementType(1), DestTy, false);
Dan Gohman4f8eea82010-02-01 18:27:38 +0000634 }
635 }
636 // Handle an offsetof-like expression.
Dan Gohmanfdbef822010-06-05 00:47:34 +0000637 if (Ty->isStructTy() || Ty->isArrayTy()) {
Dan Gohman4f8eea82010-02-01 18:27:38 +0000638 if (Constant *C = getFoldedOffsetOf(Ty, CE->getOperand(2),
639 DestTy, false))
640 return C;
641 }
642 }
643 }
Dan Gohman0f5efe52010-01-28 02:15:55 +0000644 // Other pointer types cannot be casted
645 return 0;
Reid Spencer85e36e42006-12-19 07:41:40 +0000646 case Instruction::UIToFP:
Reid Spencer85e36e42006-12-19 07:41:40 +0000647 case Instruction::SIToFP:
Nick Lewycky33c06ad2009-09-20 01:35:59 +0000648 if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
Dale Johannesen88216af2007-09-30 18:19:03 +0000649 APInt api = CI->getValue();
Tim Northover0a29cb02013-01-22 09:46:31 +0000650 APFloat apf(DestTy->getFltSemantics(),
651 APInt::getNullValue(DestTy->getPrimitiveSizeInBits()));
Dan Gohman37a9ca52008-02-29 01:42:52 +0000652 (void)apf.convertFromAPInt(api,
653 opc==Instruction::SIToFP,
654 APFloat::rmNearestTiesToEven);
Chris Lattnerb29d5962010-02-01 20:48:08 +0000655 return ConstantFP::get(V->getContext(), apf);
Dale Johannesen43421b32007-09-06 18:13:44 +0000656 }
Reid Spencer85e36e42006-12-19 07:41:40 +0000657 return 0;
Reid Spencer390437f2006-12-19 03:15:47 +0000658 case Instruction::ZExt:
Nick Lewycky33c06ad2009-09-20 01:35:59 +0000659 if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
Reid Spencer9472c372007-02-27 06:23:51 +0000660 uint32_t BitWidth = cast<IntegerType>(DestTy)->getBitWidth();
Jay Foad40f8f622010-12-07 08:25:19 +0000661 return ConstantInt::get(V->getContext(),
662 CI->getValue().zext(BitWidth));
Reid Spencer9472c372007-02-27 06:23:51 +0000663 }
Reid Spencer390437f2006-12-19 03:15:47 +0000664 return 0;
Reid Spencer3da59db2006-11-27 01:05:10 +0000665 case Instruction::SExt:
Nick Lewycky33c06ad2009-09-20 01:35:59 +0000666 if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
Reid Spencer9472c372007-02-27 06:23:51 +0000667 uint32_t BitWidth = cast<IntegerType>(DestTy)->getBitWidth();
Jay Foad40f8f622010-12-07 08:25:19 +0000668 return ConstantInt::get(V->getContext(),
669 CI->getValue().sext(BitWidth));
Reid Spencer9472c372007-02-27 06:23:51 +0000670 }
Reid Spencer390437f2006-12-19 03:15:47 +0000671 return 0;
Chris Lattner59c4eba2009-10-17 21:53:27 +0000672 case Instruction::Trunc: {
673 uint32_t DestBitWidth = cast<IntegerType>(DestTy)->getBitWidth();
Nick Lewycky33c06ad2009-09-20 01:35:59 +0000674 if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
Jay Foad40f8f622010-12-07 08:25:19 +0000675 return ConstantInt::get(V->getContext(),
676 CI->getValue().trunc(DestBitWidth));
Reid Spencer9472c372007-02-27 06:23:51 +0000677 }
Chris Lattner59c4eba2009-10-17 21:53:27 +0000678
679 // The input must be a constantexpr. See if we can simplify this based on
680 // the bytes we are demanding. Only do this if the source and dest are an
681 // even multiple of a byte.
682 if ((DestBitWidth & 7) == 0 &&
683 (cast<IntegerType>(V->getType())->getBitWidth() & 7) == 0)
684 if (Constant *Res = ExtractConstantBytes(V, 0, DestBitWidth / 8))
685 return Res;
686
Chris Lattner5be66252006-12-01 19:22:41 +0000687 return 0;
Chris Lattner59c4eba2009-10-17 21:53:27 +0000688 }
Reid Spencer3da59db2006-11-27 01:05:10 +0000689 case Instruction::BitCast:
Chris Lattnerb29d5962010-02-01 20:48:08 +0000690 return FoldBitCast(V, DestTy);
Chris Lattner4460f402006-04-02 01:38:28 +0000691 }
Chris Lattnereab20b52004-01-12 22:07:24 +0000692}
693
Chris Lattnerb29d5962010-02-01 20:48:08 +0000694Constant *llvm::ConstantFoldSelectInstruction(Constant *Cond,
Nick Lewycky33c06ad2009-09-20 01:35:59 +0000695 Constant *V1, Constant *V2) {
Chris Lattnerd59ae902012-01-26 02:32:04 +0000696 // Check for i1 and vector true/false conditions.
Nadav Rotemd2f27ea2011-02-11 19:37:55 +0000697 if (Cond->isNullValue()) return V2;
Chris Lattnerd59ae902012-01-26 02:32:04 +0000698 if (Cond->isAllOnesValue()) return V1;
Nadav Rotemd2f27ea2011-02-11 19:37:55 +0000699
Chris Lattnerd59ae902012-01-26 02:32:04 +0000700 // If the condition is a vector constant, fold the result elementwise.
701 if (ConstantVector *CondV = dyn_cast<ConstantVector>(Cond)) {
702 SmallVector<Constant*, 16> Result;
Dan Gohman03e091f2012-04-27 17:50:22 +0000703 Type *Ty = IntegerType::get(CondV->getContext(), 32);
Chris Lattnerd59ae902012-01-26 02:32:04 +0000704 for (unsigned i = 0, e = V1->getType()->getVectorNumElements(); i != e;++i){
705 ConstantInt *Cond = dyn_cast<ConstantInt>(CondV->getOperand(i));
706 if (Cond == 0) break;
707
Dan Gohman03e091f2012-04-27 17:50:22 +0000708 Constant *V = Cond->isNullValue() ? V2 : V1;
709 Constant *Res = ConstantExpr::getExtractElement(V, ConstantInt::get(Ty, i));
Chris Lattnerd59ae902012-01-26 02:32:04 +0000710 Result.push_back(Res);
Nadav Rotemd2f27ea2011-02-11 19:37:55 +0000711 }
Chris Lattnerd59ae902012-01-26 02:32:04 +0000712
713 // If we were able to build the vector, return it.
714 if (Result.size() == V1->getType()->getVectorNumElements())
715 return ConstantVector::get(Result);
Nadav Rotemd2f27ea2011-02-11 19:37:55 +0000716 }
Nadav Rotemd2f27ea2011-02-11 19:37:55 +0000717
Dan Gohman68c0dbc2011-07-01 01:03:43 +0000718 if (isa<UndefValue>(Cond)) {
719 if (isa<UndefValue>(V1)) return V1;
720 return V2;
721 }
Nick Lewycky33c06ad2009-09-20 01:35:59 +0000722 if (isa<UndefValue>(V1)) return V2;
723 if (isa<UndefValue>(V2)) return V1;
Nick Lewycky33c06ad2009-09-20 01:35:59 +0000724 if (V1 == V2) return V1;
Nick Lewycky175e7ae2011-01-29 20:35:06 +0000725
726 if (ConstantExpr *TrueVal = dyn_cast<ConstantExpr>(V1)) {
727 if (TrueVal->getOpcode() == Instruction::Select)
728 if (TrueVal->getOperand(0) == Cond)
Bill Wendling56cb2292012-07-19 00:11:40 +0000729 return ConstantExpr::getSelect(Cond, TrueVal->getOperand(1), V2);
Nick Lewycky175e7ae2011-01-29 20:35:06 +0000730 }
731 if (ConstantExpr *FalseVal = dyn_cast<ConstantExpr>(V2)) {
732 if (FalseVal->getOpcode() == Instruction::Select)
733 if (FalseVal->getOperand(0) == Cond)
Bill Wendling56cb2292012-07-19 00:11:40 +0000734 return ConstantExpr::getSelect(Cond, V1, FalseVal->getOperand(2));
Nick Lewycky175e7ae2011-01-29 20:35:06 +0000735 }
736
Chris Lattnere9714862004-03-12 05:53:32 +0000737 return 0;
738}
739
Chris Lattnerb29d5962010-02-01 20:48:08 +0000740Constant *llvm::ConstantFoldExtractElementInstruction(Constant *Val,
Nick Lewycky33c06ad2009-09-20 01:35:59 +0000741 Constant *Idx) {
Chris Lattner6fa4cdf2006-03-31 18:31:40 +0000742 if (isa<UndefValue>(Val)) // ee(undef, x) -> undef
Chris Lattnera78fa8c2012-01-27 03:08:05 +0000743 return UndefValue::get(Val->getType()->getVectorElementType());
Chris Lattnerf38d4712006-04-07 04:44:06 +0000744 if (Val->isNullValue()) // ee(zero, x) -> zero
Chris Lattnera78fa8c2012-01-27 03:08:05 +0000745 return Constant::getNullValue(Val->getType()->getVectorElementType());
746 // ee({w,x,y,z}, undef) -> undef
747 if (isa<UndefValue>(Idx))
748 return UndefValue::get(Val->getType()->getVectorElementType());
Dan Gohmanf8a87e82009-08-29 23:35:16 +0000749
Chris Lattnera78fa8c2012-01-27 03:08:05 +0000750 if (ConstantInt *CIdx = dyn_cast<ConstantInt>(Idx)) {
751 uint64_t Index = CIdx->getZExtValue();
752 // ee({w,x,y,z}, wrong_value) -> undef
753 if (Index >= Val->getType()->getVectorNumElements())
754 return UndefValue::get(Val->getType()->getVectorElementType());
755 return Val->getAggregateElement(Index);
Chris Lattner6fa4cdf2006-03-31 18:31:40 +0000756 }
Robert Bocchinobb90a7a2006-01-10 20:03:46 +0000757 return 0;
758}
759
Chris Lattnerb29d5962010-02-01 20:48:08 +0000760Constant *llvm::ConstantFoldInsertElementInstruction(Constant *Val,
Nick Lewycky33c06ad2009-09-20 01:35:59 +0000761 Constant *Elt,
762 Constant *Idx) {
763 ConstantInt *CIdx = dyn_cast<ConstantInt>(Idx);
Robert Bocchinoc152f9c2006-01-17 20:07:22 +0000764 if (!CIdx) return 0;
Chris Lattnerd59ae902012-01-26 02:32:04 +0000765 const APInt &IdxVal = CIdx->getValue();
766
767 SmallVector<Constant*, 16> Result;
Dan Gohman03e091f2012-04-27 17:50:22 +0000768 Type *Ty = IntegerType::get(Val->getContext(), 32);
Chris Lattnerd59ae902012-01-26 02:32:04 +0000769 for (unsigned i = 0, e = Val->getType()->getVectorNumElements(); i != e; ++i){
770 if (i == IdxVal) {
771 Result.push_back(Elt);
772 continue;
Robert Bocchinoc152f9c2006-01-17 20:07:22 +0000773 }
Chris Lattnerd59ae902012-01-26 02:32:04 +0000774
Dan Gohman03e091f2012-04-27 17:50:22 +0000775 Constant *C =
776 ConstantExpr::getExtractElement(Val, ConstantInt::get(Ty, i));
777 Result.push_back(C);
Robert Bocchinoc152f9c2006-01-17 20:07:22 +0000778 }
Chris Lattnerd59ae902012-01-26 02:32:04 +0000779
780 return ConstantVector::get(Result);
Chris Lattner7431c2b2007-12-11 07:49:37 +0000781}
782
Chris Lattnerb29d5962010-02-01 20:48:08 +0000783Constant *llvm::ConstantFoldShuffleVectorInstruction(Constant *V1,
Nick Lewycky33c06ad2009-09-20 01:35:59 +0000784 Constant *V2,
785 Constant *Mask) {
Chris Lattner0cd0d812012-01-30 05:34:13 +0000786 unsigned MaskNumElts = Mask->getType()->getVectorNumElements();
787 Type *EltTy = V1->getType()->getVectorElementType();
788
Chris Lattner7431c2b2007-12-11 07:49:37 +0000789 // Undefined shuffle mask -> undefined value.
Chris Lattner0cd0d812012-01-30 05:34:13 +0000790 if (isa<UndefValue>(Mask))
791 return UndefValue::get(VectorType::get(EltTy, MaskNumElts));
Mon P Wangaeb06d22008-11-10 04:46:22 +0000792
Chris Lattner29bb00b2012-01-26 03:10:45 +0000793 // Don't break the bitcode reader hack.
794 if (isa<ConstantExpr>(Mask)) return 0;
795
Chris Lattner71a494d2012-01-26 02:54:54 +0000796 unsigned SrcNumElts = V1->getType()->getVectorNumElements();
Mon P Wangaeb06d22008-11-10 04:46:22 +0000797
Chris Lattner7431c2b2007-12-11 07:49:37 +0000798 // Loop over the shuffle mask, evaluating each element.
799 SmallVector<Constant*, 32> Result;
Mon P Wangaeb06d22008-11-10 04:46:22 +0000800 for (unsigned i = 0; i != MaskNumElts; ++i) {
Chris Lattner71a494d2012-01-26 02:54:54 +0000801 int Elt = ShuffleVectorInst::getMaskValue(Mask, i);
802 if (Elt == -1) {
Chris Lattnerd59ae902012-01-26 02:32:04 +0000803 Result.push_back(UndefValue::get(EltTy));
804 continue;
Chris Lattner7431c2b2007-12-11 07:49:37 +0000805 }
Chris Lattner71a494d2012-01-26 02:54:54 +0000806 Constant *InElt;
807 if (unsigned(Elt) >= SrcNumElts*2)
Chris Lattnerd59ae902012-01-26 02:32:04 +0000808 InElt = UndefValue::get(EltTy);
Dan Gohman03e091f2012-04-27 17:50:22 +0000809 else if (unsigned(Elt) >= SrcNumElts) {
810 Type *Ty = IntegerType::get(V2->getContext(), 32);
811 InElt =
812 ConstantExpr::getExtractElement(V2,
813 ConstantInt::get(Ty, Elt - SrcNumElts));
814 } else {
815 Type *Ty = IntegerType::get(V1->getContext(), 32);
816 InElt = ConstantExpr::getExtractElement(V1, ConstantInt::get(Ty, Elt));
817 }
Chris Lattner7431c2b2007-12-11 07:49:37 +0000818 Result.push_back(InElt);
819 }
Mon P Wangaeb06d22008-11-10 04:46:22 +0000820
Chris Lattner2ca5c862011-02-15 00:14:00 +0000821 return ConstantVector::get(Result);
Chris Lattner00f10232006-04-08 01:18:18 +0000822}
823
Chris Lattnerb29d5962010-02-01 20:48:08 +0000824Constant *llvm::ConstantFoldExtractValueInstruction(Constant *Agg,
Jay Foadfc6d3a42011-07-13 10:26:04 +0000825 ArrayRef<unsigned> Idxs) {
Dan Gohman6e68f592008-06-03 00:15:20 +0000826 // Base case: no indices, so return the entire value.
Jay Foadfc6d3a42011-07-13 10:26:04 +0000827 if (Idxs.empty())
Nick Lewycky33c06ad2009-09-20 01:35:59 +0000828 return Agg;
Dan Gohman6e68f592008-06-03 00:15:20 +0000829
Chris Lattnerd59ae902012-01-26 02:32:04 +0000830 if (Constant *C = Agg->getAggregateElement(Idxs[0]))
831 return ConstantFoldExtractValueInstruction(C, Idxs.slice(1));
Dan Gohman6e68f592008-06-03 00:15:20 +0000832
Chris Lattnerd59ae902012-01-26 02:32:04 +0000833 return 0;
Dan Gohman041e2eb2008-05-15 19:50:34 +0000834}
835
Chris Lattnerb29d5962010-02-01 20:48:08 +0000836Constant *llvm::ConstantFoldInsertValueInstruction(Constant *Agg,
Nick Lewycky33c06ad2009-09-20 01:35:59 +0000837 Constant *Val,
Jay Foadfc6d3a42011-07-13 10:26:04 +0000838 ArrayRef<unsigned> Idxs) {
Dan Gohman6e68f592008-06-03 00:15:20 +0000839 // Base case: no indices, so replace the entire value.
Jay Foadfc6d3a42011-07-13 10:26:04 +0000840 if (Idxs.empty())
Nick Lewycky33c06ad2009-09-20 01:35:59 +0000841 return Val;
Dan Gohman6e68f592008-06-03 00:15:20 +0000842
Chris Lattnerd59ae902012-01-26 02:32:04 +0000843 unsigned NumElts;
844 if (StructType *ST = dyn_cast<StructType>(Agg->getType()))
845 NumElts = ST->getNumElements();
846 else if (ArrayType *AT = dyn_cast<ArrayType>(Agg->getType()))
847 NumElts = AT->getNumElements();
848 else
Nadav Rotema1753962013-02-19 19:36:59 +0000849 NumElts = Agg->getType()->getVectorNumElements();
850
Chris Lattnerd59ae902012-01-26 02:32:04 +0000851 SmallVector<Constant*, 32> Result;
852 for (unsigned i = 0; i != NumElts; ++i) {
853 Constant *C = Agg->getAggregateElement(i);
854 if (C == 0) return 0;
Chris Lattnerdd4238e2009-09-15 06:28:12 +0000855
Chris Lattnerd59ae902012-01-26 02:32:04 +0000856 if (Idxs[0] == i)
857 C = ConstantFoldInsertValueInstruction(C, Val, Idxs.slice(1));
Chris Lattnerdd4238e2009-09-15 06:28:12 +0000858
Chris Lattnerd59ae902012-01-26 02:32:04 +0000859 Result.push_back(C);
Dan Gohman6e68f592008-06-03 00:15:20 +0000860 }
Chris Lattnerdd4238e2009-09-15 06:28:12 +0000861
Chris Lattnerd59ae902012-01-26 02:32:04 +0000862 if (StructType *ST = dyn_cast<StructType>(Agg->getType()))
863 return ConstantStruct::get(ST, Result);
864 if (ArrayType *AT = dyn_cast<ArrayType>(Agg->getType()))
865 return ConstantArray::get(AT, Result);
866 return ConstantVector::get(Result);
Dan Gohman041e2eb2008-05-15 19:50:34 +0000867}
868
Reid Spencere4d87aa2006-12-23 06:05:41 +0000869
Chris Lattnerb29d5962010-02-01 20:48:08 +0000870Constant *llvm::ConstantFoldBinaryInstruction(unsigned Opcode,
Nick Lewycky33c06ad2009-09-20 01:35:59 +0000871 Constant *C1, Constant *C2) {
Chris Lattnerdd4238e2009-09-15 06:28:12 +0000872 // Handle UndefValue up front.
Reid Spencere4d87aa2006-12-23 06:05:41 +0000873 if (isa<UndefValue>(C1) || isa<UndefValue>(C2)) {
874 switch (Opcode) {
Evan Cheng26471c42008-03-25 20:08:07 +0000875 case Instruction::Xor:
876 if (isa<UndefValue>(C1) && isa<UndefValue>(C2))
877 // Handle undef ^ undef -> 0 special case. This is a common
878 // idiom (misuse).
Owen Andersona7235ea2009-07-31 20:28:14 +0000879 return Constant::getNullValue(C1->getType());
Evan Cheng26471c42008-03-25 20:08:07 +0000880 // Fallthrough
Reid Spencere4d87aa2006-12-23 06:05:41 +0000881 case Instruction::Add:
882 case Instruction::Sub:
Owen Anderson9e9a0d52009-07-30 23:03:37 +0000883 return UndefValue::get(C1->getType());
Reid Spencere4d87aa2006-12-23 06:05:41 +0000884 case Instruction::And:
Dan Gohman30cb6dd2011-07-01 00:42:17 +0000885 if (isa<UndefValue>(C1) && isa<UndefValue>(C2)) // undef & undef -> undef
886 return C1;
887 return Constant::getNullValue(C1->getType()); // undef & X -> 0
888 case Instruction::Mul: {
889 ConstantInt *CI;
890 // X * undef -> undef if X is odd or undef
891 if (((CI = dyn_cast<ConstantInt>(C1)) && CI->getValue()[0]) ||
892 ((CI = dyn_cast<ConstantInt>(C2)) && CI->getValue()[0]) ||
893 (isa<UndefValue>(C1) && isa<UndefValue>(C2)))
894 return UndefValue::get(C1->getType());
895
896 // X * undef -> 0 otherwise
Owen Andersona7235ea2009-07-31 20:28:14 +0000897 return Constant::getNullValue(C1->getType());
Dan Gohman30cb6dd2011-07-01 00:42:17 +0000898 }
Reid Spencere4d87aa2006-12-23 06:05:41 +0000899 case Instruction::UDiv:
900 case Instruction::SDiv:
Dan Gohman30cb6dd2011-07-01 00:42:17 +0000901 // undef / 1 -> undef
902 if (Opcode == Instruction::UDiv || Opcode == Instruction::SDiv)
903 if (ConstantInt *CI2 = dyn_cast<ConstantInt>(C2))
904 if (CI2->isOne())
905 return C1;
906 // FALL THROUGH
Reid Spencere4d87aa2006-12-23 06:05:41 +0000907 case Instruction::URem:
908 case Instruction::SRem:
Reid Spencere4d87aa2006-12-23 06:05:41 +0000909 if (!isa<UndefValue>(C2)) // undef / X -> 0
Owen Andersona7235ea2009-07-31 20:28:14 +0000910 return Constant::getNullValue(C1->getType());
Nick Lewycky33c06ad2009-09-20 01:35:59 +0000911 return C2; // X / undef -> undef
Reid Spencere4d87aa2006-12-23 06:05:41 +0000912 case Instruction::Or: // X | undef -> -1
Dan Gohman30cb6dd2011-07-01 00:42:17 +0000913 if (isa<UndefValue>(C1) && isa<UndefValue>(C2)) // undef | undef -> undef
914 return C1;
915 return Constant::getAllOnesValue(C1->getType()); // undef | X -> ~0
Reid Spencere4d87aa2006-12-23 06:05:41 +0000916 case Instruction::LShr:
917 if (isa<UndefValue>(C2) && isa<UndefValue>(C1))
Nick Lewycky33c06ad2009-09-20 01:35:59 +0000918 return C1; // undef lshr undef -> undef
Owen Andersona7235ea2009-07-31 20:28:14 +0000919 return Constant::getNullValue(C1->getType()); // X lshr undef -> 0
Reid Spencere4d87aa2006-12-23 06:05:41 +0000920 // undef lshr X -> 0
921 case Instruction::AShr:
Duncan Sandsc43cee32011-01-14 00:37:45 +0000922 if (!isa<UndefValue>(C2)) // undef ashr X --> all ones
923 return Constant::getAllOnesValue(C1->getType());
Reid Spencere4d87aa2006-12-23 06:05:41 +0000924 else if (isa<UndefValue>(C1))
Nick Lewycky33c06ad2009-09-20 01:35:59 +0000925 return C1; // undef ashr undef -> undef
Reid Spencere4d87aa2006-12-23 06:05:41 +0000926 else
Nick Lewycky33c06ad2009-09-20 01:35:59 +0000927 return C1; // X ashr undef --> X
Reid Spencere4d87aa2006-12-23 06:05:41 +0000928 case Instruction::Shl:
Dan Gohman30cb6dd2011-07-01 00:42:17 +0000929 if (isa<UndefValue>(C2) && isa<UndefValue>(C1))
930 return C1; // undef shl undef -> undef
Reid Spencere4d87aa2006-12-23 06:05:41 +0000931 // undef << X -> 0 or X << undef -> 0
Owen Andersona7235ea2009-07-31 20:28:14 +0000932 return Constant::getNullValue(C1->getType());
Reid Spencere4d87aa2006-12-23 06:05:41 +0000933 }
934 }
935
Nick Lewyckye47f59d2009-06-21 01:56:41 +0000936 // Handle simplifications when the RHS is a constant int.
Nick Lewycky33c06ad2009-09-20 01:35:59 +0000937 if (ConstantInt *CI2 = dyn_cast<ConstantInt>(C2)) {
Chris Lattner1c14c292008-04-19 21:58:19 +0000938 switch (Opcode) {
939 case Instruction::Add:
Nick Lewycky33c06ad2009-09-20 01:35:59 +0000940 if (CI2->equalsInt(0)) return C1; // X + 0 == X
Chris Lattner1c14c292008-04-19 21:58:19 +0000941 break;
942 case Instruction::Sub:
Nick Lewycky33c06ad2009-09-20 01:35:59 +0000943 if (CI2->equalsInt(0)) return C1; // X - 0 == X
Chris Lattner1c14c292008-04-19 21:58:19 +0000944 break;
945 case Instruction::Mul:
Nick Lewycky33c06ad2009-09-20 01:35:59 +0000946 if (CI2->equalsInt(0)) return C2; // X * 0 == 0
Chris Lattner1c14c292008-04-19 21:58:19 +0000947 if (CI2->equalsInt(1))
Nick Lewycky33c06ad2009-09-20 01:35:59 +0000948 return C1; // X * 1 == X
Chris Lattner1c14c292008-04-19 21:58:19 +0000949 break;
950 case Instruction::UDiv:
951 case Instruction::SDiv:
952 if (CI2->equalsInt(1))
Nick Lewycky33c06ad2009-09-20 01:35:59 +0000953 return C1; // X / 1 == X
Chris Lattnerc9a00582009-01-19 21:55:26 +0000954 if (CI2->equalsInt(0))
Owen Anderson9e9a0d52009-07-30 23:03:37 +0000955 return UndefValue::get(CI2->getType()); // X / 0 == undef
Chris Lattner1c14c292008-04-19 21:58:19 +0000956 break;
957 case Instruction::URem:
958 case Instruction::SRem:
959 if (CI2->equalsInt(1))
Owen Andersona7235ea2009-07-31 20:28:14 +0000960 return Constant::getNullValue(CI2->getType()); // X % 1 == 0
Chris Lattnerc9a00582009-01-19 21:55:26 +0000961 if (CI2->equalsInt(0))
Owen Anderson9e9a0d52009-07-30 23:03:37 +0000962 return UndefValue::get(CI2->getType()); // X % 0 == undef
Chris Lattner1c14c292008-04-19 21:58:19 +0000963 break;
964 case Instruction::And:
Nick Lewycky33c06ad2009-09-20 01:35:59 +0000965 if (CI2->isZero()) return C2; // X & 0 == 0
Chris Lattner1c14c292008-04-19 21:58:19 +0000966 if (CI2->isAllOnesValue())
Nick Lewycky33c06ad2009-09-20 01:35:59 +0000967 return C1; // X & -1 == X
Dan Gohmanf8a87e82009-08-29 23:35:16 +0000968
Nick Lewycky33c06ad2009-09-20 01:35:59 +0000969 if (ConstantExpr *CE1 = dyn_cast<ConstantExpr>(C1)) {
Chris Lattnerd881ad22008-04-19 22:17:26 +0000970 // (zext i32 to i64) & 4294967295 -> (zext i32 to i64)
Chris Lattner1c14c292008-04-19 21:58:19 +0000971 if (CE1->getOpcode() == Instruction::ZExt) {
972 unsigned DstWidth = CI2->getType()->getBitWidth();
973 unsigned SrcWidth =
974 CE1->getOperand(0)->getType()->getPrimitiveSizeInBits();
975 APInt PossiblySetBits(APInt::getLowBitsSet(DstWidth, SrcWidth));
976 if ((PossiblySetBits & CI2->getValue()) == PossiblySetBits)
Nick Lewycky33c06ad2009-09-20 01:35:59 +0000977 return C1;
Chris Lattner2ef14d92007-03-25 05:47:04 +0000978 }
Dan Gohmanf8a87e82009-08-29 23:35:16 +0000979
Chris Lattnerd881ad22008-04-19 22:17:26 +0000980 // If and'ing the address of a global with a constant, fold it.
Chris Lattner1c14c292008-04-19 21:58:19 +0000981 if (CE1->getOpcode() == Instruction::PtrToInt &&
982 isa<GlobalValue>(CE1->getOperand(0))) {
Chris Lattnerd881ad22008-04-19 22:17:26 +0000983 GlobalValue *GV = cast<GlobalValue>(CE1->getOperand(0));
Dan Gohmanf8a87e82009-08-29 23:35:16 +0000984
Chris Lattnerd881ad22008-04-19 22:17:26 +0000985 // Functions are at least 4-byte aligned.
986 unsigned GVAlign = GV->getAlignment();
987 if (isa<Function>(GV))
988 GVAlign = std::max(GVAlign, 4U);
Dan Gohmanf8a87e82009-08-29 23:35:16 +0000989
Chris Lattnerd881ad22008-04-19 22:17:26 +0000990 if (GVAlign > 1) {
991 unsigned DstWidth = CI2->getType()->getBitWidth();
Chris Lattner3e5d1d82008-04-20 19:59:12 +0000992 unsigned SrcWidth = std::min(DstWidth, Log2_32(GVAlign));
Chris Lattnerd881ad22008-04-19 22:17:26 +0000993 APInt BitsNotSet(APInt::getLowBitsSet(DstWidth, SrcWidth));
994
995 // If checking bits we know are clear, return zero.
996 if ((CI2->getValue() & BitsNotSet) == CI2->getValue())
Owen Andersona7235ea2009-07-31 20:28:14 +0000997 return Constant::getNullValue(CI2->getType());
Chris Lattnerd881ad22008-04-19 22:17:26 +0000998 }
Reid Spencere4d87aa2006-12-23 06:05:41 +0000999 }
Chris Lattner1c14c292008-04-19 21:58:19 +00001000 }
1001 break;
1002 case Instruction::Or:
Nick Lewycky33c06ad2009-09-20 01:35:59 +00001003 if (CI2->equalsInt(0)) return C1; // X | 0 == X
Chris Lattner1c14c292008-04-19 21:58:19 +00001004 if (CI2->isAllOnesValue())
Nick Lewycky33c06ad2009-09-20 01:35:59 +00001005 return C2; // X | -1 == -1
Chris Lattner1c14c292008-04-19 21:58:19 +00001006 break;
1007 case Instruction::Xor:
Nick Lewycky33c06ad2009-09-20 01:35:59 +00001008 if (CI2->equalsInt(0)) return C1; // X ^ 0 == X
Nick Lewycky3105ebf2009-09-20 06:24:51 +00001009
1010 if (ConstantExpr *CE1 = dyn_cast<ConstantExpr>(C1)) {
1011 switch (CE1->getOpcode()) {
1012 default: break;
1013 case Instruction::ICmp:
1014 case Instruction::FCmp:
Nick Lewyckyb13efda2009-09-20 06:27:35 +00001015 // cmp pred ^ true -> cmp !pred
Nick Lewycky3105ebf2009-09-20 06:24:51 +00001016 assert(CI2->equalsInt(1));
Nick Lewycky8577e272009-09-20 06:26:34 +00001017 CmpInst::Predicate pred = (CmpInst::Predicate)CE1->getPredicate();
Nick Lewycky3105ebf2009-09-20 06:24:51 +00001018 pred = CmpInst::getInversePredicate(pred);
1019 return ConstantExpr::getCompare(pred, CE1->getOperand(0),
1020 CE1->getOperand(1));
1021 }
1022 }
Chris Lattner1c14c292008-04-19 21:58:19 +00001023 break;
1024 case Instruction::AShr:
1025 // ashr (zext C to Ty), C2 -> lshr (zext C, CSA), C2
Nick Lewycky33c06ad2009-09-20 01:35:59 +00001026 if (ConstantExpr *CE1 = dyn_cast<ConstantExpr>(C1))
Chris Lattner2ef14d92007-03-25 05:47:04 +00001027 if (CE1->getOpcode() == Instruction::ZExt) // Top bits known zero.
Nick Lewycky33c06ad2009-09-20 01:35:59 +00001028 return ConstantExpr::getLShr(C1, C2);
Chris Lattner1c14c292008-04-19 21:58:19 +00001029 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00001030 }
Dan Gohman0e488b32010-02-22 22:43:23 +00001031 } else if (isa<ConstantInt>(C1)) {
1032 // If C1 is a ConstantInt and C2 is not, swap the operands.
1033 if (Instruction::isCommutative(Opcode))
1034 return ConstantExpr::get(Opcode, C2, C1);
Chris Lattner1c14c292008-04-19 21:58:19 +00001035 }
Dan Gohmanf8a87e82009-08-29 23:35:16 +00001036
Chris Lattner0e4b6c72008-04-20 18:24:14 +00001037 // At this point we know neither constant is an UndefValue.
Nick Lewycky33c06ad2009-09-20 01:35:59 +00001038 if (ConstantInt *CI1 = dyn_cast<ConstantInt>(C1)) {
1039 if (ConstantInt *CI2 = dyn_cast<ConstantInt>(C2)) {
Chris Lattner0e4b6c72008-04-20 18:24:14 +00001040 const APInt &C1V = CI1->getValue();
1041 const APInt &C2V = CI2->getValue();
Chris Lattnerd333d902007-01-12 18:42:52 +00001042 switch (Opcode) {
1043 default:
1044 break;
1045 case Instruction::Add:
Chris Lattnerb29d5962010-02-01 20:48:08 +00001046 return ConstantInt::get(CI1->getContext(), C1V + C2V);
Chris Lattnerd333d902007-01-12 18:42:52 +00001047 case Instruction::Sub:
Chris Lattnerb29d5962010-02-01 20:48:08 +00001048 return ConstantInt::get(CI1->getContext(), C1V - C2V);
Chris Lattnerd333d902007-01-12 18:42:52 +00001049 case Instruction::Mul:
Chris Lattnerb29d5962010-02-01 20:48:08 +00001050 return ConstantInt::get(CI1->getContext(), C1V * C2V);
Chris Lattnerd333d902007-01-12 18:42:52 +00001051 case Instruction::UDiv:
Chris Lattnerc9a00582009-01-19 21:55:26 +00001052 assert(!CI2->isNullValue() && "Div by zero handled above");
Chris Lattnerb29d5962010-02-01 20:48:08 +00001053 return ConstantInt::get(CI1->getContext(), C1V.udiv(C2V));
Chris Lattnerd333d902007-01-12 18:42:52 +00001054 case Instruction::SDiv:
Chris Lattnerc9a00582009-01-19 21:55:26 +00001055 assert(!CI2->isNullValue() && "Div by zero handled above");
Reid Spencer9472c372007-02-27 06:23:51 +00001056 if (C2V.isAllOnesValue() && C1V.isMinSignedValue())
Owen Anderson9e9a0d52009-07-30 23:03:37 +00001057 return UndefValue::get(CI1->getType()); // MIN_INT / -1 -> undef
Chris Lattnerb29d5962010-02-01 20:48:08 +00001058 return ConstantInt::get(CI1->getContext(), C1V.sdiv(C2V));
Reid Spencer9472c372007-02-27 06:23:51 +00001059 case Instruction::URem:
Chris Lattnerc9a00582009-01-19 21:55:26 +00001060 assert(!CI2->isNullValue() && "Div by zero handled above");
Chris Lattnerb29d5962010-02-01 20:48:08 +00001061 return ConstantInt::get(CI1->getContext(), C1V.urem(C2V));
Chris Lattnerc9a00582009-01-19 21:55:26 +00001062 case Instruction::SRem:
1063 assert(!CI2->isNullValue() && "Div by zero handled above");
Reid Spencer9472c372007-02-27 06:23:51 +00001064 if (C2V.isAllOnesValue() && C1V.isMinSignedValue())
Owen Anderson9e9a0d52009-07-30 23:03:37 +00001065 return UndefValue::get(CI1->getType()); // MIN_INT % -1 -> undef
Chris Lattnerb29d5962010-02-01 20:48:08 +00001066 return ConstantInt::get(CI1->getContext(), C1V.srem(C2V));
Chris Lattnerd333d902007-01-12 18:42:52 +00001067 case Instruction::And:
Chris Lattnerb29d5962010-02-01 20:48:08 +00001068 return ConstantInt::get(CI1->getContext(), C1V & C2V);
Chris Lattnerd333d902007-01-12 18:42:52 +00001069 case Instruction::Or:
Chris Lattnerb29d5962010-02-01 20:48:08 +00001070 return ConstantInt::get(CI1->getContext(), C1V | C2V);
Chris Lattnerd333d902007-01-12 18:42:52 +00001071 case Instruction::Xor:
Chris Lattnerb29d5962010-02-01 20:48:08 +00001072 return ConstantInt::get(CI1->getContext(), C1V ^ C2V);
Chris Lattner0e4b6c72008-04-20 18:24:14 +00001073 case Instruction::Shl: {
1074 uint32_t shiftAmt = C2V.getZExtValue();
1075 if (shiftAmt < C1V.getBitWidth())
Chris Lattnerb29d5962010-02-01 20:48:08 +00001076 return ConstantInt::get(CI1->getContext(), C1V.shl(shiftAmt));
Chris Lattner0e4b6c72008-04-20 18:24:14 +00001077 else
Owen Anderson9e9a0d52009-07-30 23:03:37 +00001078 return UndefValue::get(C1->getType()); // too big shift is undef
Chris Lattner0e4b6c72008-04-20 18:24:14 +00001079 }
1080 case Instruction::LShr: {
1081 uint32_t shiftAmt = C2V.getZExtValue();
1082 if (shiftAmt < C1V.getBitWidth())
Chris Lattnerb29d5962010-02-01 20:48:08 +00001083 return ConstantInt::get(CI1->getContext(), C1V.lshr(shiftAmt));
Chris Lattner0e4b6c72008-04-20 18:24:14 +00001084 else
Owen Anderson9e9a0d52009-07-30 23:03:37 +00001085 return UndefValue::get(C1->getType()); // too big shift is undef
Chris Lattner0e4b6c72008-04-20 18:24:14 +00001086 }
1087 case Instruction::AShr: {
1088 uint32_t shiftAmt = C2V.getZExtValue();
1089 if (shiftAmt < C1V.getBitWidth())
Chris Lattnerb29d5962010-02-01 20:48:08 +00001090 return ConstantInt::get(CI1->getContext(), C1V.ashr(shiftAmt));
Chris Lattner0e4b6c72008-04-20 18:24:14 +00001091 else
Owen Anderson9e9a0d52009-07-30 23:03:37 +00001092 return UndefValue::get(C1->getType()); // too big shift is undef
Chris Lattner0e4b6c72008-04-20 18:24:14 +00001093 }
Reid Spencere4d87aa2006-12-23 06:05:41 +00001094 }
1095 }
Nick Lewyckye47f59d2009-06-21 01:56:41 +00001096
1097 switch (Opcode) {
1098 case Instruction::SDiv:
1099 case Instruction::UDiv:
1100 case Instruction::URem:
1101 case Instruction::SRem:
1102 case Instruction::LShr:
1103 case Instruction::AShr:
1104 case Instruction::Shl:
Nick Lewycky33c06ad2009-09-20 01:35:59 +00001105 if (CI1->equalsInt(0)) return C1;
Nick Lewyckye47f59d2009-06-21 01:56:41 +00001106 break;
1107 default:
1108 break;
1109 }
Nick Lewycky33c06ad2009-09-20 01:35:59 +00001110 } else if (ConstantFP *CFP1 = dyn_cast<ConstantFP>(C1)) {
1111 if (ConstantFP *CFP2 = dyn_cast<ConstantFP>(C2)) {
Dale Johannesen43421b32007-09-06 18:13:44 +00001112 APFloat C1V = CFP1->getValueAPF();
1113 APFloat C2V = CFP2->getValueAPF();
1114 APFloat C3V = C1V; // copy for modification
Reid Spencere4d87aa2006-12-23 06:05:41 +00001115 switch (Opcode) {
1116 default:
1117 break;
Dan Gohmanae3a0be2009-06-04 22:49:04 +00001118 case Instruction::FAdd:
Dale Johannesen43421b32007-09-06 18:13:44 +00001119 (void)C3V.add(C2V, APFloat::rmNearestTiesToEven);
Chris Lattnerb29d5962010-02-01 20:48:08 +00001120 return ConstantFP::get(C1->getContext(), C3V);
Dan Gohmanae3a0be2009-06-04 22:49:04 +00001121 case Instruction::FSub:
Dale Johannesen43421b32007-09-06 18:13:44 +00001122 (void)C3V.subtract(C2V, APFloat::rmNearestTiesToEven);
Chris Lattnerb29d5962010-02-01 20:48:08 +00001123 return ConstantFP::get(C1->getContext(), C3V);
Dan Gohmanae3a0be2009-06-04 22:49:04 +00001124 case Instruction::FMul:
Dale Johannesen43421b32007-09-06 18:13:44 +00001125 (void)C3V.multiply(C2V, APFloat::rmNearestTiesToEven);
Chris Lattnerb29d5962010-02-01 20:48:08 +00001126 return ConstantFP::get(C1->getContext(), C3V);
Reid Spencere4d87aa2006-12-23 06:05:41 +00001127 case Instruction::FDiv:
Dale Johannesen43421b32007-09-06 18:13:44 +00001128 (void)C3V.divide(C2V, APFloat::rmNearestTiesToEven);
Chris Lattnerb29d5962010-02-01 20:48:08 +00001129 return ConstantFP::get(C1->getContext(), C3V);
Reid Spencere4d87aa2006-12-23 06:05:41 +00001130 case Instruction::FRem:
Dale Johannesen43421b32007-09-06 18:13:44 +00001131 (void)C3V.mod(C2V, APFloat::rmNearestTiesToEven);
Chris Lattnerb29d5962010-02-01 20:48:08 +00001132 return ConstantFP::get(C1->getContext(), C3V);
Reid Spencere4d87aa2006-12-23 06:05:41 +00001133 }
1134 }
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001135 } else if (VectorType *VTy = dyn_cast<VectorType>(C1->getType())) {
Chris Lattnerd59ae902012-01-26 02:32:04 +00001136 // Perform elementwise folding.
1137 SmallVector<Constant*, 16> Result;
Dan Gohman03e091f2012-04-27 17:50:22 +00001138 Type *Ty = IntegerType::get(VTy->getContext(), 32);
Chris Lattnerd59ae902012-01-26 02:32:04 +00001139 for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {
Dan Gohman03e091f2012-04-27 17:50:22 +00001140 Constant *LHS =
1141 ConstantExpr::getExtractElement(C1, ConstantInt::get(Ty, i));
1142 Constant *RHS =
1143 ConstantExpr::getExtractElement(C2, ConstantInt::get(Ty, i));
Chris Lattnerd59ae902012-01-26 02:32:04 +00001144
1145 Result.push_back(ConstantExpr::get(Opcode, LHS, RHS));
Reid Spencere4d87aa2006-12-23 06:05:41 +00001146 }
Chris Lattnerd59ae902012-01-26 02:32:04 +00001147
Dan Gohman03e091f2012-04-27 17:50:22 +00001148 return ConstantVector::get(Result);
Reid Spencere4d87aa2006-12-23 06:05:41 +00001149 }
1150
Dan Gohman4f8eea82010-02-01 18:27:38 +00001151 if (ConstantExpr *CE1 = dyn_cast<ConstantExpr>(C1)) {
Chris Lattner0e4b6c72008-04-20 18:24:14 +00001152 // There are many possible foldings we could do here. We should probably
1153 // at least fold add of a pointer with an integer into the appropriate
1154 // getelementptr. This will improve alias analysis a bit.
Dan Gohman4f8eea82010-02-01 18:27:38 +00001155
1156 // Given ((a + b) + c), if (b + c) folds to something interesting, return
1157 // (a + (b + c)).
Duncan Sands0d7ce5f2010-12-20 13:10:23 +00001158 if (Instruction::isAssociative(Opcode) && CE1->getOpcode() == Opcode) {
Dan Gohman4f8eea82010-02-01 18:27:38 +00001159 Constant *T = ConstantExpr::get(Opcode, CE1->getOperand(1), C2);
1160 if (!isa<ConstantExpr>(T) || cast<ConstantExpr>(T)->getOpcode() != Opcode)
1161 return ConstantExpr::get(Opcode, CE1->getOperand(0), T);
1162 }
Chris Lattner0e4b6c72008-04-20 18:24:14 +00001163 } else if (isa<ConstantExpr>(C2)) {
1164 // If C2 is a constant expr and C1 isn't, flop them around and fold the
1165 // other way if possible.
Dan Gohmand97439d2010-02-22 22:05:18 +00001166 if (Instruction::isCommutative(Opcode))
Chris Lattnerb29d5962010-02-01 20:48:08 +00001167 return ConstantFoldBinaryInstruction(Opcode, C2, C1);
Chris Lattner0e4b6c72008-04-20 18:24:14 +00001168 }
Dan Gohmanf8a87e82009-08-29 23:35:16 +00001169
Nick Lewyckyf4d18822009-09-20 00:04:02 +00001170 // i1 can be simplified in many cases.
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00001171 if (C1->getType()->isIntegerTy(1)) {
Nick Lewyckyf4d18822009-09-20 00:04:02 +00001172 switch (Opcode) {
1173 case Instruction::Add:
1174 case Instruction::Sub:
Nick Lewycky33c06ad2009-09-20 01:35:59 +00001175 return ConstantExpr::getXor(C1, C2);
Nick Lewyckyf4d18822009-09-20 00:04:02 +00001176 case Instruction::Mul:
Nick Lewycky33c06ad2009-09-20 01:35:59 +00001177 return ConstantExpr::getAnd(C1, C2);
Nick Lewyckyf4d18822009-09-20 00:04:02 +00001178 case Instruction::Shl:
1179 case Instruction::LShr:
1180 case Instruction::AShr:
1181 // We can assume that C2 == 0. If it were one the result would be
1182 // undefined because the shift value is as large as the bitwidth.
Nick Lewycky33c06ad2009-09-20 01:35:59 +00001183 return C1;
Nick Lewyckyf4d18822009-09-20 00:04:02 +00001184 case Instruction::SDiv:
1185 case Instruction::UDiv:
1186 // We can assume that C2 == 1. If it were zero the result would be
1187 // undefined through division by zero.
Nick Lewycky33c06ad2009-09-20 01:35:59 +00001188 return C1;
Nick Lewyckyf4d18822009-09-20 00:04:02 +00001189 case Instruction::URem:
1190 case Instruction::SRem:
1191 // We can assume that C2 == 1. If it were zero the result would be
1192 // undefined through division by zero.
Chris Lattnerb29d5962010-02-01 20:48:08 +00001193 return ConstantInt::getFalse(C1->getContext());
Nick Lewyckyf4d18822009-09-20 00:04:02 +00001194 default:
1195 break;
1196 }
1197 }
1198
Chris Lattner0e4b6c72008-04-20 18:24:14 +00001199 // We don't know how to fold this.
Reid Spencere4d87aa2006-12-23 06:05:41 +00001200 return 0;
1201}
Chris Lattner00f10232006-04-08 01:18:18 +00001202
Chris Lattnerce04a6d2005-01-28 19:09:51 +00001203/// isZeroSizedType - This type is zero sized if its an array or structure of
1204/// zero sized types. The only leaf zero sized type is an empty structure.
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001205static bool isMaybeZeroSizedType(Type *Ty) {
1206 if (StructType *STy = dyn_cast<StructType>(Ty)) {
Chris Lattner1afcace2011-07-09 17:41:24 +00001207 if (STy->isOpaque()) return true; // Can't say.
Chris Lattnerce04a6d2005-01-28 19:09:51 +00001208
1209 // If all of elements have zero size, this does too.
1210 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i)
Chris Lattnerf4aa3352005-01-28 23:17:27 +00001211 if (!isMaybeZeroSizedType(STy->getElementType(i))) return false;
Chris Lattnerce04a6d2005-01-28 19:09:51 +00001212 return true;
1213
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001214 } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
Chris Lattnerce04a6d2005-01-28 19:09:51 +00001215 return isMaybeZeroSizedType(ATy->getElementType());
1216 }
1217 return false;
1218}
Chris Lattnere9714862004-03-12 05:53:32 +00001219
Chris Lattner504e8fb2004-01-13 05:51:55 +00001220/// IdxCompare - Compare the two constants as though they were getelementptr
1221/// indices. This allows coersion of the types to be the same thing.
1222///
1223/// If the two constants are the "same" (after coersion), return 0. If the
1224/// first is less than the second, return -1, if the second is less than the
1225/// first, return 1. If the constants are not integral, return -2.
1226///
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001227static int IdxCompare(Constant *C1, Constant *C2, Type *ElTy) {
Chris Lattner504e8fb2004-01-13 05:51:55 +00001228 if (C1 == C2) return 0;
1229
Reid Spencercc615c32006-12-31 21:43:30 +00001230 // Ok, we found a different index. If they are not ConstantInt, we can't do
1231 // anything with them.
Chris Lattner504e8fb2004-01-13 05:51:55 +00001232 if (!isa<ConstantInt>(C1) || !isa<ConstantInt>(C2))
1233 return -2; // don't know!
Misha Brukmanfd939082005-04-21 23:48:37 +00001234
Chris Lattner28977af2004-04-05 01:30:19 +00001235 // Ok, we have two differing integer indices. Sign extend them to be the same
1236 // type. Long is always big enough, so we use it.
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00001237 if (!C1->getType()->isIntegerTy(64))
Chris Lattnerb29d5962010-02-01 20:48:08 +00001238 C1 = ConstantExpr::getSExt(C1, Type::getInt64Ty(C1->getContext()));
Reid Spencer3da59db2006-11-27 01:05:10 +00001239
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00001240 if (!C2->getType()->isIntegerTy(64))
Chris Lattnerb29d5962010-02-01 20:48:08 +00001241 C2 = ConstantExpr::getSExt(C2, Type::getInt64Ty(C1->getContext()));
Reid Spencer79e21d32006-12-31 05:26:44 +00001242
1243 if (C1 == C2) return 0; // They are equal
Chris Lattner504e8fb2004-01-13 05:51:55 +00001244
Chris Lattnerce04a6d2005-01-28 19:09:51 +00001245 // If the type being indexed over is really just a zero sized type, there is
1246 // no pointer difference being made here.
1247 if (isMaybeZeroSizedType(ElTy))
1248 return -2; // dunno.
1249
Chris Lattner504e8fb2004-01-13 05:51:55 +00001250 // If they are really different, now that they are the same type, then we
1251 // found a difference!
Reid Spencerb83eb642006-10-20 07:07:24 +00001252 if (cast<ConstantInt>(C1)->getSExtValue() <
1253 cast<ConstantInt>(C2)->getSExtValue())
Chris Lattner504e8fb2004-01-13 05:51:55 +00001254 return -1;
1255 else
1256 return 1;
1257}
1258
Chris Lattner898b2d52007-01-04 02:13:20 +00001259/// evaluateFCmpRelation - This function determines if there is anything we can
Reid Spencere4d87aa2006-12-23 06:05:41 +00001260/// decide about the two constants provided. This doesn't need to handle simple
1261/// things like ConstantFP comparisons, but should instead handle ConstantExprs.
1262/// If we can determine that the two constants have a particular relation to
1263/// each other, we should return the corresponding FCmpInst predicate,
Reid Spencerb913bba2006-12-24 18:52:08 +00001264/// otherwise return FCmpInst::BAD_FCMP_PREDICATE. This is used below in
1265/// ConstantFoldCompareInstruction.
Reid Spencere4d87aa2006-12-23 06:05:41 +00001266///
1267/// To simplify this code we canonicalize the relation so that the first
Reid Spencerb913bba2006-12-24 18:52:08 +00001268/// operand is always the most "complex" of the two. We consider ConstantFP
1269/// to be the simplest, and ConstantExprs to be the most complex.
Chris Lattnerb29d5962010-02-01 20:48:08 +00001270static FCmpInst::Predicate evaluateFCmpRelation(Constant *V1, Constant *V2) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00001271 assert(V1->getType() == V2->getType() &&
Reid Spencerb913bba2006-12-24 18:52:08 +00001272 "Cannot compare values of different types!");
Dale Johannesen5927d8e2007-10-14 01:56:47 +00001273
Reid Spencerb913bba2006-12-24 18:52:08 +00001274 // Handle degenerate case quickly
Reid Spencere4d87aa2006-12-23 06:05:41 +00001275 if (V1 == V2) return FCmpInst::FCMP_OEQ;
1276
Reid Spencerb913bba2006-12-24 18:52:08 +00001277 if (!isa<ConstantExpr>(V1)) {
1278 if (!isa<ConstantExpr>(V2)) {
1279 // We distilled thisUse the standard constant folder for a few cases
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00001280 ConstantInt *R = 0;
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00001281 R = dyn_cast<ConstantInt>(
Nick Lewycky33c06ad2009-09-20 01:35:59 +00001282 ConstantExpr::getFCmp(FCmpInst::FCMP_OEQ, V1, V2));
Reid Spencercae57542007-03-02 00:28:52 +00001283 if (R && !R->isZero())
Reid Spencere4d87aa2006-12-23 06:05:41 +00001284 return FCmpInst::FCMP_OEQ;
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00001285 R = dyn_cast<ConstantInt>(
Nick Lewycky33c06ad2009-09-20 01:35:59 +00001286 ConstantExpr::getFCmp(FCmpInst::FCMP_OLT, V1, V2));
Reid Spencercae57542007-03-02 00:28:52 +00001287 if (R && !R->isZero())
Reid Spencere4d87aa2006-12-23 06:05:41 +00001288 return FCmpInst::FCMP_OLT;
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00001289 R = dyn_cast<ConstantInt>(
Nick Lewycky33c06ad2009-09-20 01:35:59 +00001290 ConstantExpr::getFCmp(FCmpInst::FCMP_OGT, V1, V2));
Reid Spencercae57542007-03-02 00:28:52 +00001291 if (R && !R->isZero())
Reid Spencerb913bba2006-12-24 18:52:08 +00001292 return FCmpInst::FCMP_OGT;
1293
1294 // Nothing more we can do
Reid Spencere4d87aa2006-12-23 06:05:41 +00001295 return FCmpInst::BAD_FCMP_PREDICATE;
1296 }
Dan Gohmanf8a87e82009-08-29 23:35:16 +00001297
Reid Spencerb913bba2006-12-24 18:52:08 +00001298 // If the first operand is simple and second is ConstantExpr, swap operands.
Chris Lattnerb29d5962010-02-01 20:48:08 +00001299 FCmpInst::Predicate SwappedRelation = evaluateFCmpRelation(V2, V1);
Reid Spencerb913bba2006-12-24 18:52:08 +00001300 if (SwappedRelation != FCmpInst::BAD_FCMP_PREDICATE)
1301 return FCmpInst::getSwappedPredicate(SwappedRelation);
1302 } else {
1303 // Ok, the LHS is known to be a constantexpr. The RHS can be any of a
1304 // constantexpr or a simple constant.
Nick Lewycky33c06ad2009-09-20 01:35:59 +00001305 ConstantExpr *CE1 = cast<ConstantExpr>(V1);
Reid Spencerb913bba2006-12-24 18:52:08 +00001306 switch (CE1->getOpcode()) {
1307 case Instruction::FPTrunc:
1308 case Instruction::FPExt:
1309 case Instruction::UIToFP:
1310 case Instruction::SIToFP:
1311 // We might be able to do something with these but we don't right now.
1312 break;
1313 default:
1314 break;
1315 }
Reid Spencere4d87aa2006-12-23 06:05:41 +00001316 }
Reid Spencere4d87aa2006-12-23 06:05:41 +00001317 // There are MANY other foldings that we could perform here. They will
1318 // probably be added on demand, as they seem needed.
1319 return FCmpInst::BAD_FCMP_PREDICATE;
1320}
1321
1322/// evaluateICmpRelation - This function determines if there is anything we can
Chris Lattner504e8fb2004-01-13 05:51:55 +00001323/// decide about the two constants provided. This doesn't need to handle simple
Reid Spencer79703962004-07-17 23:47:01 +00001324/// things like integer comparisons, but should instead handle ConstantExprs
Chris Lattner36c24512006-12-11 02:16:58 +00001325/// and GlobalValues. If we can determine that the two constants have a
Reid Spencere4d87aa2006-12-23 06:05:41 +00001326/// particular relation to each other, we should return the corresponding ICmp
1327/// predicate, otherwise return ICmpInst::BAD_ICMP_PREDICATE.
Chris Lattner504e8fb2004-01-13 05:51:55 +00001328///
1329/// To simplify this code we canonicalize the relation so that the first
1330/// operand is always the most "complex" of the two. We consider simple
1331/// constants (like ConstantInt) to be the simplest, followed by
Reid Spencer79703962004-07-17 23:47:01 +00001332/// GlobalValues, followed by ConstantExpr's (the most complex).
Chris Lattner504e8fb2004-01-13 05:51:55 +00001333///
Chris Lattnerb29d5962010-02-01 20:48:08 +00001334static ICmpInst::Predicate evaluateICmpRelation(Constant *V1, Constant *V2,
Reid Spencere4d87aa2006-12-23 06:05:41 +00001335 bool isSigned) {
Chris Lattner504e8fb2004-01-13 05:51:55 +00001336 assert(V1->getType() == V2->getType() &&
1337 "Cannot compare different types of values!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00001338 if (V1 == V2) return ICmpInst::ICMP_EQ;
Chris Lattner504e8fb2004-01-13 05:51:55 +00001339
Chris Lattnerb63127d2010-02-01 19:35:08 +00001340 if (!isa<ConstantExpr>(V1) && !isa<GlobalValue>(V1) &&
1341 !isa<BlockAddress>(V1)) {
1342 if (!isa<GlobalValue>(V2) && !isa<ConstantExpr>(V2) &&
1343 !isa<BlockAddress>(V2)) {
Chris Lattner2f690c82006-01-05 07:49:30 +00001344 // We distilled this down to a simple case, use the standard constant
1345 // folder.
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00001346 ConstantInt *R = 0;
Reid Spencere4d87aa2006-12-23 06:05:41 +00001347 ICmpInst::Predicate pred = ICmpInst::ICMP_EQ;
Nick Lewycky33c06ad2009-09-20 01:35:59 +00001348 R = dyn_cast<ConstantInt>(ConstantExpr::getICmp(pred, V1, V2));
Reid Spencercae57542007-03-02 00:28:52 +00001349 if (R && !R->isZero())
Reid Spencere4d87aa2006-12-23 06:05:41 +00001350 return pred;
1351 pred = isSigned ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT;
Nick Lewycky33c06ad2009-09-20 01:35:59 +00001352 R = dyn_cast<ConstantInt>(ConstantExpr::getICmp(pred, V1, V2));
Reid Spencercae57542007-03-02 00:28:52 +00001353 if (R && !R->isZero())
Reid Spencere4d87aa2006-12-23 06:05:41 +00001354 return pred;
Nick Lewycky7f6aa2b2009-07-08 03:04:38 +00001355 pred = isSigned ? ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT;
Nick Lewycky33c06ad2009-09-20 01:35:59 +00001356 R = dyn_cast<ConstantInt>(ConstantExpr::getICmp(pred, V1, V2));
Reid Spencercae57542007-03-02 00:28:52 +00001357 if (R && !R->isZero())
Reid Spencere4d87aa2006-12-23 06:05:41 +00001358 return pred;
Dan Gohmanf8a87e82009-08-29 23:35:16 +00001359
Chris Lattner2f690c82006-01-05 07:49:30 +00001360 // If we couldn't figure it out, bail.
Reid Spencere4d87aa2006-12-23 06:05:41 +00001361 return ICmpInst::BAD_ICMP_PREDICATE;
Chris Lattner2f690c82006-01-05 07:49:30 +00001362 }
Dan Gohmanf8a87e82009-08-29 23:35:16 +00001363
Chris Lattner504e8fb2004-01-13 05:51:55 +00001364 // If the first operand is simple, swap operands.
Reid Spencere4d87aa2006-12-23 06:05:41 +00001365 ICmpInst::Predicate SwappedRelation =
Chris Lattnerb29d5962010-02-01 20:48:08 +00001366 evaluateICmpRelation(V2, V1, isSigned);
Reid Spencere4d87aa2006-12-23 06:05:41 +00001367 if (SwappedRelation != ICmpInst::BAD_ICMP_PREDICATE)
1368 return ICmpInst::getSwappedPredicate(SwappedRelation);
Chris Lattner504e8fb2004-01-13 05:51:55 +00001369
Chris Lattnerb63127d2010-02-01 19:35:08 +00001370 } else if (const GlobalValue *GV = dyn_cast<GlobalValue>(V1)) {
Chris Lattnerb97e2782004-02-01 01:23:19 +00001371 if (isa<ConstantExpr>(V2)) { // Swap as necessary.
Reid Spencere4d87aa2006-12-23 06:05:41 +00001372 ICmpInst::Predicate SwappedRelation =
Chris Lattnerb29d5962010-02-01 20:48:08 +00001373 evaluateICmpRelation(V2, V1, isSigned);
Reid Spencere4d87aa2006-12-23 06:05:41 +00001374 if (SwappedRelation != ICmpInst::BAD_ICMP_PREDICATE)
1375 return ICmpInst::getSwappedPredicate(SwappedRelation);
Chris Lattnerb63127d2010-02-01 19:35:08 +00001376 return ICmpInst::BAD_ICMP_PREDICATE;
Chris Lattnerb97e2782004-02-01 01:23:19 +00001377 }
Chris Lattner504e8fb2004-01-13 05:51:55 +00001378
Chris Lattnerb63127d2010-02-01 19:35:08 +00001379 // Now we know that the RHS is a GlobalValue, BlockAddress or simple
1380 // constant (which, since the types must match, means that it's a
1381 // ConstantPointerNull).
1382 if (const GlobalValue *GV2 = dyn_cast<GlobalValue>(V2)) {
Chris Lattnera0ef5ed2007-09-10 23:42:42 +00001383 // Don't try to decide equality of aliases.
Chris Lattnerb63127d2010-02-01 19:35:08 +00001384 if (!isa<GlobalAlias>(GV) && !isa<GlobalAlias>(GV2))
1385 if (!GV->hasExternalWeakLinkage() || !GV2->hasExternalWeakLinkage())
Chris Lattnera0ef5ed2007-09-10 23:42:42 +00001386 return ICmpInst::ICMP_NE;
Chris Lattnerb63127d2010-02-01 19:35:08 +00001387 } else if (isa<BlockAddress>(V2)) {
1388 return ICmpInst::ICMP_NE; // Globals never equal labels.
Chris Lattner504e8fb2004-01-13 05:51:55 +00001389 } else {
1390 assert(isa<ConstantPointerNull>(V2) && "Canonicalization guarantee!");
Chris Lattnerb63127d2010-02-01 19:35:08 +00001391 // GlobalVals can never be null unless they have external weak linkage.
1392 // We don't try to evaluate aliases here.
1393 if (!GV->hasExternalWeakLinkage() && !isa<GlobalAlias>(GV))
Reid Spencere4d87aa2006-12-23 06:05:41 +00001394 return ICmpInst::ICMP_NE;
Chris Lattner504e8fb2004-01-13 05:51:55 +00001395 }
Chris Lattnerb63127d2010-02-01 19:35:08 +00001396 } else if (const BlockAddress *BA = dyn_cast<BlockAddress>(V1)) {
1397 if (isa<ConstantExpr>(V2)) { // Swap as necessary.
1398 ICmpInst::Predicate SwappedRelation =
Chris Lattnerb29d5962010-02-01 20:48:08 +00001399 evaluateICmpRelation(V2, V1, isSigned);
Chris Lattnerb63127d2010-02-01 19:35:08 +00001400 if (SwappedRelation != ICmpInst::BAD_ICMP_PREDICATE)
1401 return ICmpInst::getSwappedPredicate(SwappedRelation);
1402 return ICmpInst::BAD_ICMP_PREDICATE;
1403 }
1404
1405 // Now we know that the RHS is a GlobalValue, BlockAddress or simple
1406 // constant (which, since the types must match, means that it is a
1407 // ConstantPointerNull).
1408 if (const BlockAddress *BA2 = dyn_cast<BlockAddress>(V2)) {
1409 // Block address in another function can't equal this one, but block
1410 // addresses in the current function might be the same if blocks are
1411 // empty.
1412 if (BA2->getFunction() != BA->getFunction())
1413 return ICmpInst::ICMP_NE;
1414 } else {
1415 // Block addresses aren't null, don't equal the address of globals.
1416 assert((isa<ConstantPointerNull>(V2) || isa<GlobalValue>(V2)) &&
1417 "Canonicalization guarantee!");
1418 return ICmpInst::ICMP_NE;
1419 }
Chris Lattner504e8fb2004-01-13 05:51:55 +00001420 } else {
1421 // Ok, the LHS is known to be a constantexpr. The RHS can be any of a
Chris Lattnerb63127d2010-02-01 19:35:08 +00001422 // constantexpr, a global, block address, or a simple constant.
Nick Lewycky33c06ad2009-09-20 01:35:59 +00001423 ConstantExpr *CE1 = cast<ConstantExpr>(V1);
1424 Constant *CE1Op0 = CE1->getOperand(0);
Chris Lattner504e8fb2004-01-13 05:51:55 +00001425
1426 switch (CE1->getOpcode()) {
Reid Spencer3da59db2006-11-27 01:05:10 +00001427 case Instruction::Trunc:
1428 case Instruction::FPTrunc:
1429 case Instruction::FPExt:
1430 case Instruction::FPToUI:
1431 case Instruction::FPToSI:
Reid Spencere4d87aa2006-12-23 06:05:41 +00001432 break; // We can't evaluate floating point casts or truncations.
1433
Reid Spencer3da59db2006-11-27 01:05:10 +00001434 case Instruction::UIToFP:
1435 case Instruction::SIToFP:
Reid Spencer3da59db2006-11-27 01:05:10 +00001436 case Instruction::BitCast:
Reid Spencere4d87aa2006-12-23 06:05:41 +00001437 case Instruction::ZExt:
1438 case Instruction::SExt:
Chris Lattner504e8fb2004-01-13 05:51:55 +00001439 // If the cast is not actually changing bits, and the second operand is a
1440 // null pointer, do the comparison with the pre-casted value.
1441 if (V2->isNullValue() &&
Duncan Sands1df98592010-02-16 11:11:14 +00001442 (CE1->getType()->isPointerTy() || CE1->getType()->isIntegerTy())) {
Chris Lattnerf286f6f2007-12-10 22:53:04 +00001443 if (CE1->getOpcode() == Instruction::ZExt) isSigned = false;
1444 if (CE1->getOpcode() == Instruction::SExt) isSigned = true;
Chris Lattnerb29d5962010-02-01 20:48:08 +00001445 return evaluateICmpRelation(CE1Op0,
Owen Andersona7235ea2009-07-31 20:28:14 +00001446 Constant::getNullValue(CE1Op0->getType()),
Nick Lewyckyd43737b2009-09-20 03:48:46 +00001447 isSigned);
Reid Spencere4d87aa2006-12-23 06:05:41 +00001448 }
Chris Lattnera0ae8192004-04-11 01:29:30 +00001449 break;
Chris Lattner504e8fb2004-01-13 05:51:55 +00001450
1451 case Instruction::GetElementPtr:
1452 // Ok, since this is a getelementptr, we know that the constant has a
1453 // pointer type. Check the various cases.
1454 if (isa<ConstantPointerNull>(V2)) {
1455 // If we are comparing a GEP to a null pointer, check to see if the base
1456 // of the GEP equals the null pointer.
Reid Spencerb913bba2006-12-24 18:52:08 +00001457 if (const GlobalValue *GV = dyn_cast<GlobalValue>(CE1Op0)) {
Reid Spencer87d5f6c2006-12-06 00:25:09 +00001458 if (GV->hasExternalWeakLinkage())
1459 // Weak linkage GVals could be zero or not. We're comparing that
1460 // to null pointer so its greater-or-equal
Reid Spencere4d87aa2006-12-23 06:05:41 +00001461 return isSigned ? ICmpInst::ICMP_SGE : ICmpInst::ICMP_UGE;
Reid Spencer87d5f6c2006-12-06 00:25:09 +00001462 else
1463 // If its not weak linkage, the GVal must have a non-zero address
1464 // so the result is greater-than
Nick Lewycky3892baa2009-09-20 04:27:06 +00001465 return isSigned ? ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT;
Chris Lattner504e8fb2004-01-13 05:51:55 +00001466 } else if (isa<ConstantPointerNull>(CE1Op0)) {
1467 // If we are indexing from a null pointer, check to see if we have any
1468 // non-zero indices.
1469 for (unsigned i = 1, e = CE1->getNumOperands(); i != e; ++i)
1470 if (!CE1->getOperand(i)->isNullValue())
1471 // Offsetting from null, must not be equal.
Reid Spencere4d87aa2006-12-23 06:05:41 +00001472 return isSigned ? ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT;
Chris Lattner504e8fb2004-01-13 05:51:55 +00001473 // Only zero indexes from null, must still be zero.
Reid Spencere4d87aa2006-12-23 06:05:41 +00001474 return ICmpInst::ICMP_EQ;
Chris Lattner504e8fb2004-01-13 05:51:55 +00001475 }
1476 // Otherwise, we can't really say if the first operand is null or not.
Chris Lattnerb63127d2010-02-01 19:35:08 +00001477 } else if (const GlobalValue *GV2 = dyn_cast<GlobalValue>(V2)) {
Chris Lattner504e8fb2004-01-13 05:51:55 +00001478 if (isa<ConstantPointerNull>(CE1Op0)) {
Chris Lattnerb63127d2010-02-01 19:35:08 +00001479 if (GV2->hasExternalWeakLinkage())
Reid Spencer87d5f6c2006-12-06 00:25:09 +00001480 // Weak linkage GVals could be zero or not. We're comparing it to
1481 // a null pointer, so its less-or-equal
Reid Spencere4d87aa2006-12-23 06:05:41 +00001482 return isSigned ? ICmpInst::ICMP_SLE : ICmpInst::ICMP_ULE;
Reid Spencer87d5f6c2006-12-06 00:25:09 +00001483 else
1484 // If its not weak linkage, the GVal must have a non-zero address
1485 // so the result is less-than
Reid Spencere4d87aa2006-12-23 06:05:41 +00001486 return isSigned ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT;
Chris Lattnerb63127d2010-02-01 19:35:08 +00001487 } else if (const GlobalValue *GV = dyn_cast<GlobalValue>(CE1Op0)) {
1488 if (GV == GV2) {
Chris Lattner504e8fb2004-01-13 05:51:55 +00001489 // If this is a getelementptr of the same global, then it must be
1490 // different. Because the types must match, the getelementptr could
1491 // only have at most one index, and because we fold getelementptr's
1492 // with a single zero index, it must be nonzero.
1493 assert(CE1->getNumOperands() == 2 &&
1494 !CE1->getOperand(1)->isNullValue() &&
Chris Lattner7a2bdde2011-04-15 05:18:47 +00001495 "Surprising getelementptr!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00001496 return isSigned ? ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT;
Chris Lattner504e8fb2004-01-13 05:51:55 +00001497 } else {
Dan Gohmand363ae52013-01-31 00:01:45 +00001498 // If they are different globals, we don't know what the value is.
1499 return ICmpInst::BAD_ICMP_PREDICATE;
Chris Lattner504e8fb2004-01-13 05:51:55 +00001500 }
1501 }
1502 } else {
Nick Lewycky33c06ad2009-09-20 01:35:59 +00001503 ConstantExpr *CE2 = cast<ConstantExpr>(V2);
1504 Constant *CE2Op0 = CE2->getOperand(0);
Chris Lattner504e8fb2004-01-13 05:51:55 +00001505
1506 // There are MANY other foldings that we could perform here. They will
1507 // probably be added on demand, as they seem needed.
1508 switch (CE2->getOpcode()) {
1509 default: break;
1510 case Instruction::GetElementPtr:
1511 // By far the most common case to handle is when the base pointers are
Dan Gohmand363ae52013-01-31 00:01:45 +00001512 // obviously to the same global.
Reid Spencer79703962004-07-17 23:47:01 +00001513 if (isa<GlobalValue>(CE1Op0) && isa<GlobalValue>(CE2Op0)) {
Dan Gohmand363ae52013-01-31 00:01:45 +00001514 if (CE1Op0 != CE2Op0) // Don't know relative ordering.
1515 return ICmpInst::BAD_ICMP_PREDICATE;
Chris Lattner504e8fb2004-01-13 05:51:55 +00001516 // Ok, we know that both getelementptr instructions are based on the
1517 // same global. From this, we can precisely determine the relative
1518 // ordering of the resultant pointers.
1519 unsigned i = 1;
Misha Brukmanfd939082005-04-21 23:48:37 +00001520
Dan Gohmane6992f72009-09-10 23:37:55 +00001521 // The logic below assumes that the result of the comparison
1522 // can be determined by finding the first index that differs.
1523 // This doesn't work if there is over-indexing in any
1524 // subsequent indices, so check for that case first.
1525 if (!CE1->isGEPWithNoNotionalOverIndexing() ||
1526 !CE2->isGEPWithNoNotionalOverIndexing())
1527 return ICmpInst::BAD_ICMP_PREDICATE; // Might be equal.
1528
Chris Lattner504e8fb2004-01-13 05:51:55 +00001529 // Compare all of the operands the GEP's have in common.
Chris Lattnerce04a6d2005-01-28 19:09:51 +00001530 gep_type_iterator GTI = gep_type_begin(CE1);
1531 for (;i != CE1->getNumOperands() && i != CE2->getNumOperands();
1532 ++i, ++GTI)
Chris Lattnerb29d5962010-02-01 20:48:08 +00001533 switch (IdxCompare(CE1->getOperand(i),
Owen Anderson0a5372e2009-07-13 04:09:18 +00001534 CE2->getOperand(i), GTI.getIndexedType())) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00001535 case -1: return isSigned ? ICmpInst::ICMP_SLT:ICmpInst::ICMP_ULT;
1536 case 1: return isSigned ? ICmpInst::ICMP_SGT:ICmpInst::ICMP_UGT;
1537 case -2: return ICmpInst::BAD_ICMP_PREDICATE;
Chris Lattner504e8fb2004-01-13 05:51:55 +00001538 }
1539
1540 // Ok, we ran out of things they have in common. If any leftovers
1541 // are non-zero then we have a difference, otherwise we are equal.
1542 for (; i < CE1->getNumOperands(); ++i)
Anton Korobeynikovae9f3a32008-02-20 11:08:44 +00001543 if (!CE1->getOperand(i)->isNullValue()) {
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00001544 if (isa<ConstantInt>(CE1->getOperand(i)))
Reid Spencere4d87aa2006-12-23 06:05:41 +00001545 return isSigned ? ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT;
Chris Lattnerce04a6d2005-01-28 19:09:51 +00001546 else
Reid Spencere4d87aa2006-12-23 06:05:41 +00001547 return ICmpInst::BAD_ICMP_PREDICATE; // Might be equal.
Anton Korobeynikovae9f3a32008-02-20 11:08:44 +00001548 }
Misha Brukmanfd939082005-04-21 23:48:37 +00001549
Chris Lattner504e8fb2004-01-13 05:51:55 +00001550 for (; i < CE2->getNumOperands(); ++i)
Anton Korobeynikovae9f3a32008-02-20 11:08:44 +00001551 if (!CE2->getOperand(i)->isNullValue()) {
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00001552 if (isa<ConstantInt>(CE2->getOperand(i)))
Reid Spencere4d87aa2006-12-23 06:05:41 +00001553 return isSigned ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT;
Chris Lattnerce04a6d2005-01-28 19:09:51 +00001554 else
Reid Spencere4d87aa2006-12-23 06:05:41 +00001555 return ICmpInst::BAD_ICMP_PREDICATE; // Might be equal.
Anton Korobeynikovae9f3a32008-02-20 11:08:44 +00001556 }
Reid Spencere4d87aa2006-12-23 06:05:41 +00001557 return ICmpInst::ICMP_EQ;
Chris Lattner504e8fb2004-01-13 05:51:55 +00001558 }
1559 }
1560 }
Chris Lattner504e8fb2004-01-13 05:51:55 +00001561 default:
1562 break;
1563 }
1564 }
1565
Reid Spencere4d87aa2006-12-23 06:05:41 +00001566 return ICmpInst::BAD_ICMP_PREDICATE;
Chris Lattner504e8fb2004-01-13 05:51:55 +00001567}
1568
Chris Lattnerb29d5962010-02-01 20:48:08 +00001569Constant *llvm::ConstantFoldCompareInstruction(unsigned short pred,
Nick Lewycky33c06ad2009-09-20 01:35:59 +00001570 Constant *C1, Constant *C2) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001571 Type *ResultTy;
1572 if (VectorType *VT = dyn_cast<VectorType>(C1->getType()))
Chris Lattnerb29d5962010-02-01 20:48:08 +00001573 ResultTy = VectorType::get(Type::getInt1Ty(C1->getContext()),
1574 VT->getNumElements());
Nick Lewycky7f6aa2b2009-07-08 03:04:38 +00001575 else
Chris Lattnerb29d5962010-02-01 20:48:08 +00001576 ResultTy = Type::getInt1Ty(C1->getContext());
Nick Lewycky7f6aa2b2009-07-08 03:04:38 +00001577
Chris Lattner155a4902008-07-08 05:46:34 +00001578 // Fold FCMP_FALSE/FCMP_TRUE unconditionally.
Nick Lewycky7f6aa2b2009-07-08 03:04:38 +00001579 if (pred == FCmpInst::FCMP_FALSE)
Owen Andersona7235ea2009-07-31 20:28:14 +00001580 return Constant::getNullValue(ResultTy);
Nick Lewycky7f6aa2b2009-07-08 03:04:38 +00001581
1582 if (pred == FCmpInst::FCMP_TRUE)
Owen Andersona7235ea2009-07-31 20:28:14 +00001583 return Constant::getAllOnesValue(ResultTy);
Nick Lewycky7f6aa2b2009-07-08 03:04:38 +00001584
Reid Spencere4d87aa2006-12-23 06:05:41 +00001585 // Handle some degenerate cases first
Dan Gohman0dd35492010-06-28 21:30:07 +00001586 if (isa<UndefValue>(C1) || isa<UndefValue>(C2)) {
1587 // For EQ and NE, we can always pick a value for the undef to make the
1588 // predicate pass or fail, so we can return undef.
Dan Gohman68c0dbc2011-07-01 01:03:43 +00001589 // Also, if both operands are undef, we can return undef.
1590 if (ICmpInst::isEquality(ICmpInst::Predicate(pred)) ||
1591 (isa<UndefValue>(C1) && isa<UndefValue>(C2)))
Dan Gohman0dd35492010-06-28 21:30:07 +00001592 return UndefValue::get(ResultTy);
1593 // Otherwise, pick the same value as the non-undef operand, and fold
1594 // it to true or false.
Chris Lattnerc8e14b32010-03-03 19:46:03 +00001595 return ConstantInt::get(ResultTy, CmpInst::isTrueWhenEqual(pred));
Dan Gohman0dd35492010-06-28 21:30:07 +00001596 }
Reid Spencere4d87aa2006-12-23 06:05:41 +00001597
1598 // icmp eq/ne(null,GV) -> false/true
1599 if (C1->isNullValue()) {
1600 if (const GlobalValue *GV = dyn_cast<GlobalValue>(C2))
Duncan Sands78016442007-09-19 10:16:17 +00001601 // Don't try to evaluate aliases. External weak GV can be null.
Anton Korobeynikovae9f3a32008-02-20 11:08:44 +00001602 if (!isa<GlobalAlias>(GV) && !GV->hasExternalWeakLinkage()) {
Reid Spencerb913bba2006-12-24 18:52:08 +00001603 if (pred == ICmpInst::ICMP_EQ)
Chris Lattnerb29d5962010-02-01 20:48:08 +00001604 return ConstantInt::getFalse(C1->getContext());
Reid Spencerb913bba2006-12-24 18:52:08 +00001605 else if (pred == ICmpInst::ICMP_NE)
Chris Lattnerb29d5962010-02-01 20:48:08 +00001606 return ConstantInt::getTrue(C1->getContext());
Anton Korobeynikovae9f3a32008-02-20 11:08:44 +00001607 }
Reid Spencere4d87aa2006-12-23 06:05:41 +00001608 // icmp eq/ne(GV,null) -> false/true
1609 } else if (C2->isNullValue()) {
1610 if (const GlobalValue *GV = dyn_cast<GlobalValue>(C1))
Duncan Sands78016442007-09-19 10:16:17 +00001611 // Don't try to evaluate aliases. External weak GV can be null.
Anton Korobeynikovae9f3a32008-02-20 11:08:44 +00001612 if (!isa<GlobalAlias>(GV) && !GV->hasExternalWeakLinkage()) {
Reid Spencerb913bba2006-12-24 18:52:08 +00001613 if (pred == ICmpInst::ICMP_EQ)
Chris Lattnerb29d5962010-02-01 20:48:08 +00001614 return ConstantInt::getFalse(C1->getContext());
Reid Spencerb913bba2006-12-24 18:52:08 +00001615 else if (pred == ICmpInst::ICMP_NE)
Chris Lattnerb29d5962010-02-01 20:48:08 +00001616 return ConstantInt::getTrue(C1->getContext());
Anton Korobeynikovae9f3a32008-02-20 11:08:44 +00001617 }
Chris Lattnereab20b52004-01-12 22:07:24 +00001618 }
1619
Nick Lewycky85958b02009-09-20 07:21:39 +00001620 // If the comparison is a comparison between two i1's, simplify it.
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00001621 if (C1->getType()->isIntegerTy(1)) {
Nick Lewycky85958b02009-09-20 07:21:39 +00001622 switch(pred) {
1623 case ICmpInst::ICMP_EQ:
1624 if (isa<ConstantInt>(C2))
1625 return ConstantExpr::getXor(C1, ConstantExpr::getNot(C2));
1626 return ConstantExpr::getXor(ConstantExpr::getNot(C1), C2);
1627 case ICmpInst::ICMP_NE:
1628 return ConstantExpr::getXor(C1, C2);
1629 default:
1630 break;
1631 }
1632 }
1633
Chris Lattnerd333d902007-01-12 18:42:52 +00001634 if (isa<ConstantInt>(C1) && isa<ConstantInt>(C2)) {
Reid Spencer9472c372007-02-27 06:23:51 +00001635 APInt V1 = cast<ConstantInt>(C1)->getValue();
1636 APInt V2 = cast<ConstantInt>(C2)->getValue();
1637 switch (pred) {
David Blaikie4d6ccb52012-01-20 21:51:11 +00001638 default: llvm_unreachable("Invalid ICmp Predicate");
Chris Lattnerb29d5962010-02-01 20:48:08 +00001639 case ICmpInst::ICMP_EQ: return ConstantInt::get(ResultTy, V1 == V2);
1640 case ICmpInst::ICMP_NE: return ConstantInt::get(ResultTy, V1 != V2);
1641 case ICmpInst::ICMP_SLT: return ConstantInt::get(ResultTy, V1.slt(V2));
1642 case ICmpInst::ICMP_SGT: return ConstantInt::get(ResultTy, V1.sgt(V2));
1643 case ICmpInst::ICMP_SLE: return ConstantInt::get(ResultTy, V1.sle(V2));
1644 case ICmpInst::ICMP_SGE: return ConstantInt::get(ResultTy, V1.sge(V2));
1645 case ICmpInst::ICMP_ULT: return ConstantInt::get(ResultTy, V1.ult(V2));
1646 case ICmpInst::ICMP_UGT: return ConstantInt::get(ResultTy, V1.ugt(V2));
1647 case ICmpInst::ICMP_ULE: return ConstantInt::get(ResultTy, V1.ule(V2));
1648 case ICmpInst::ICMP_UGE: return ConstantInt::get(ResultTy, V1.uge(V2));
Chris Lattner504e8fb2004-01-13 05:51:55 +00001649 }
Reid Spencere4d87aa2006-12-23 06:05:41 +00001650 } else if (isa<ConstantFP>(C1) && isa<ConstantFP>(C2)) {
Dale Johannesen43421b32007-09-06 18:13:44 +00001651 APFloat C1V = cast<ConstantFP>(C1)->getValueAPF();
1652 APFloat C2V = cast<ConstantFP>(C2)->getValueAPF();
1653 APFloat::cmpResult R = C1V.compare(C2V);
Reid Spencerb913bba2006-12-24 18:52:08 +00001654 switch (pred) {
David Blaikie4d6ccb52012-01-20 21:51:11 +00001655 default: llvm_unreachable("Invalid FCmp Predicate");
Chris Lattnerb29d5962010-02-01 20:48:08 +00001656 case FCmpInst::FCMP_FALSE: return Constant::getNullValue(ResultTy);
1657 case FCmpInst::FCMP_TRUE: return Constant::getAllOnesValue(ResultTy);
Reid Spencere4d87aa2006-12-23 06:05:41 +00001658 case FCmpInst::FCMP_UNO:
Chris Lattnerb29d5962010-02-01 20:48:08 +00001659 return ConstantInt::get(ResultTy, R==APFloat::cmpUnordered);
Reid Spencer53054782007-01-11 00:25:45 +00001660 case FCmpInst::FCMP_ORD:
Chris Lattnerb29d5962010-02-01 20:48:08 +00001661 return ConstantInt::get(ResultTy, R!=APFloat::cmpUnordered);
Reid Spencere4d87aa2006-12-23 06:05:41 +00001662 case FCmpInst::FCMP_UEQ:
Chris Lattnerb29d5962010-02-01 20:48:08 +00001663 return ConstantInt::get(ResultTy, R==APFloat::cmpUnordered ||
1664 R==APFloat::cmpEqual);
Reid Spencer579dca12007-01-12 04:24:46 +00001665 case FCmpInst::FCMP_OEQ:
Chris Lattnerb29d5962010-02-01 20:48:08 +00001666 return ConstantInt::get(ResultTy, R==APFloat::cmpEqual);
Reid Spencer53054782007-01-11 00:25:45 +00001667 case FCmpInst::FCMP_UNE:
Chris Lattnerb29d5962010-02-01 20:48:08 +00001668 return ConstantInt::get(ResultTy, R!=APFloat::cmpEqual);
Reid Spencer579dca12007-01-12 04:24:46 +00001669 case FCmpInst::FCMP_ONE:
Chris Lattnerb29d5962010-02-01 20:48:08 +00001670 return ConstantInt::get(ResultTy, R==APFloat::cmpLessThan ||
1671 R==APFloat::cmpGreaterThan);
Reid Spencer53054782007-01-11 00:25:45 +00001672 case FCmpInst::FCMP_ULT:
Chris Lattnerb29d5962010-02-01 20:48:08 +00001673 return ConstantInt::get(ResultTy, R==APFloat::cmpUnordered ||
1674 R==APFloat::cmpLessThan);
Reid Spencer579dca12007-01-12 04:24:46 +00001675 case FCmpInst::FCMP_OLT:
Chris Lattnerb29d5962010-02-01 20:48:08 +00001676 return ConstantInt::get(ResultTy, R==APFloat::cmpLessThan);
Reid Spencere4d87aa2006-12-23 06:05:41 +00001677 case FCmpInst::FCMP_UGT:
Chris Lattnerb29d5962010-02-01 20:48:08 +00001678 return ConstantInt::get(ResultTy, R==APFloat::cmpUnordered ||
1679 R==APFloat::cmpGreaterThan);
Reid Spencer579dca12007-01-12 04:24:46 +00001680 case FCmpInst::FCMP_OGT:
Chris Lattnerb29d5962010-02-01 20:48:08 +00001681 return ConstantInt::get(ResultTy, R==APFloat::cmpGreaterThan);
Reid Spencer53054782007-01-11 00:25:45 +00001682 case FCmpInst::FCMP_ULE:
Chris Lattnerb29d5962010-02-01 20:48:08 +00001683 return ConstantInt::get(ResultTy, R!=APFloat::cmpGreaterThan);
Reid Spencer579dca12007-01-12 04:24:46 +00001684 case FCmpInst::FCMP_OLE:
Chris Lattnerb29d5962010-02-01 20:48:08 +00001685 return ConstantInt::get(ResultTy, R==APFloat::cmpLessThan ||
1686 R==APFloat::cmpEqual);
Reid Spencere4d87aa2006-12-23 06:05:41 +00001687 case FCmpInst::FCMP_UGE:
Chris Lattnerb29d5962010-02-01 20:48:08 +00001688 return ConstantInt::get(ResultTy, R!=APFloat::cmpLessThan);
Reid Spencer579dca12007-01-12 04:24:46 +00001689 case FCmpInst::FCMP_OGE:
Chris Lattnerb29d5962010-02-01 20:48:08 +00001690 return ConstantInt::get(ResultTy, R==APFloat::cmpGreaterThan ||
1691 R==APFloat::cmpEqual);
Reid Spencere4d87aa2006-12-23 06:05:41 +00001692 }
Duncan Sands1df98592010-02-16 11:11:14 +00001693 } else if (C1->getType()->isVectorTy()) {
Chris Lattnerfea85c42008-07-10 00:29:28 +00001694 // If we can constant fold the comparison of each element, constant fold
1695 // the whole vector comparison.
1696 SmallVector<Constant*, 4> ResElts;
Dan Gohman03e091f2012-04-27 17:50:22 +00001697 Type *Ty = IntegerType::get(C1->getContext(), 32);
Chris Lattner2ca5c862011-02-15 00:14:00 +00001698 // Compare the elements, producing an i1 result or constant expr.
Chris Lattner56243b82012-01-26 02:51:13 +00001699 for (unsigned i = 0, e = C1->getType()->getVectorNumElements(); i != e;++i){
Dan Gohman03e091f2012-04-27 17:50:22 +00001700 Constant *C1E =
1701 ConstantExpr::getExtractElement(C1, ConstantInt::get(Ty, i));
1702 Constant *C2E =
1703 ConstantExpr::getExtractElement(C2, ConstantInt::get(Ty, i));
Chris Lattner56243b82012-01-26 02:51:13 +00001704
1705 ResElts.push_back(ConstantExpr::getCompare(pred, C1E, C2E));
1706 }
1707
Dan Gohman03e091f2012-04-27 17:50:22 +00001708 return ConstantVector::get(ResElts);
Reid Spencere4d87aa2006-12-23 06:05:41 +00001709 }
Chris Lattner504e8fb2004-01-13 05:51:55 +00001710
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00001711 if (C1->getType()->isFloatingPointTy()) {
Chris Lattner80139542008-07-08 18:47:38 +00001712 int Result = -1; // -1 = unknown, 0 = known false, 1 = known true.
Chris Lattnerb29d5962010-02-01 20:48:08 +00001713 switch (evaluateFCmpRelation(C1, C2)) {
Torok Edwinc23197a2009-07-14 16:55:14 +00001714 default: llvm_unreachable("Unknown relation!");
Reid Spencerb913bba2006-12-24 18:52:08 +00001715 case FCmpInst::FCMP_UNO:
1716 case FCmpInst::FCMP_ORD:
1717 case FCmpInst::FCMP_UEQ:
1718 case FCmpInst::FCMP_UNE:
1719 case FCmpInst::FCMP_ULT:
1720 case FCmpInst::FCMP_UGT:
1721 case FCmpInst::FCMP_ULE:
1722 case FCmpInst::FCMP_UGE:
1723 case FCmpInst::FCMP_TRUE:
1724 case FCmpInst::FCMP_FALSE:
1725 case FCmpInst::BAD_FCMP_PREDICATE:
1726 break; // Couldn't determine anything about these constants.
1727 case FCmpInst::FCMP_OEQ: // We know that C1 == C2
Chris Lattner155a4902008-07-08 05:46:34 +00001728 Result = (pred == FCmpInst::FCMP_UEQ || pred == FCmpInst::FCMP_OEQ ||
1729 pred == FCmpInst::FCMP_ULE || pred == FCmpInst::FCMP_OLE ||
1730 pred == FCmpInst::FCMP_UGE || pred == FCmpInst::FCMP_OGE);
1731 break;
Reid Spencerb913bba2006-12-24 18:52:08 +00001732 case FCmpInst::FCMP_OLT: // We know that C1 < C2
Chris Lattner155a4902008-07-08 05:46:34 +00001733 Result = (pred == FCmpInst::FCMP_UNE || pred == FCmpInst::FCMP_ONE ||
1734 pred == FCmpInst::FCMP_ULT || pred == FCmpInst::FCMP_OLT ||
1735 pred == FCmpInst::FCMP_ULE || pred == FCmpInst::FCMP_OLE);
1736 break;
Reid Spencerb913bba2006-12-24 18:52:08 +00001737 case FCmpInst::FCMP_OGT: // We know that C1 > C2
Chris Lattner155a4902008-07-08 05:46:34 +00001738 Result = (pred == FCmpInst::FCMP_UNE || pred == FCmpInst::FCMP_ONE ||
1739 pred == FCmpInst::FCMP_UGT || pred == FCmpInst::FCMP_OGT ||
1740 pred == FCmpInst::FCMP_UGE || pred == FCmpInst::FCMP_OGE);
1741 break;
Reid Spencerb913bba2006-12-24 18:52:08 +00001742 case FCmpInst::FCMP_OLE: // We know that C1 <= C2
1743 // We can only partially decide this relation.
1744 if (pred == FCmpInst::FCMP_UGT || pred == FCmpInst::FCMP_OGT)
Chris Lattner155a4902008-07-08 05:46:34 +00001745 Result = 0;
1746 else if (pred == FCmpInst::FCMP_ULT || pred == FCmpInst::FCMP_OLT)
1747 Result = 1;
Chris Lattner504e8fb2004-01-13 05:51:55 +00001748 break;
Reid Spencerb913bba2006-12-24 18:52:08 +00001749 case FCmpInst::FCMP_OGE: // We known that C1 >= C2
1750 // We can only partially decide this relation.
1751 if (pred == FCmpInst::FCMP_ULT || pred == FCmpInst::FCMP_OLT)
Chris Lattner155a4902008-07-08 05:46:34 +00001752 Result = 0;
1753 else if (pred == FCmpInst::FCMP_UGT || pred == FCmpInst::FCMP_OGT)
1754 Result = 1;
Reid Spencerb913bba2006-12-24 18:52:08 +00001755 break;
Nick Lewyckybb25e2c2011-01-30 01:49:58 +00001756 case FCmpInst::FCMP_ONE: // We know that C1 != C2
Reid Spencerb913bba2006-12-24 18:52:08 +00001757 // We can only partially decide this relation.
1758 if (pred == FCmpInst::FCMP_OEQ || pred == FCmpInst::FCMP_UEQ)
Chris Lattner155a4902008-07-08 05:46:34 +00001759 Result = 0;
1760 else if (pred == FCmpInst::FCMP_ONE || pred == FCmpInst::FCMP_UNE)
1761 Result = 1;
Reid Spencerb913bba2006-12-24 18:52:08 +00001762 break;
1763 }
Dan Gohmanf8a87e82009-08-29 23:35:16 +00001764
Chris Lattner155a4902008-07-08 05:46:34 +00001765 // If we evaluated the result, return it now.
Nick Lewycky7f6aa2b2009-07-08 03:04:38 +00001766 if (Result != -1)
Chris Lattnerb29d5962010-02-01 20:48:08 +00001767 return ConstantInt::get(ResultTy, Result);
Nick Lewycky7f6aa2b2009-07-08 03:04:38 +00001768
Reid Spencerb913bba2006-12-24 18:52:08 +00001769 } else {
1770 // Evaluate the relation between the two constants, per the predicate.
Chris Lattner155a4902008-07-08 05:46:34 +00001771 int Result = -1; // -1 = unknown, 0 = known false, 1 = known true.
Chris Lattnerb29d5962010-02-01 20:48:08 +00001772 switch (evaluateICmpRelation(C1, C2, CmpInst::isSigned(pred))) {
Torok Edwinc23197a2009-07-14 16:55:14 +00001773 default: llvm_unreachable("Unknown relational!");
Reid Spencerb913bba2006-12-24 18:52:08 +00001774 case ICmpInst::BAD_ICMP_PREDICATE:
1775 break; // Couldn't determine anything about these constants.
1776 case ICmpInst::ICMP_EQ: // We know the constants are equal!
1777 // If we know the constants are equal, we can decide the result of this
1778 // computation precisely.
Nick Lewycky3892baa2009-09-20 04:27:06 +00001779 Result = ICmpInst::isTrueWhenEqual((ICmpInst::Predicate)pred);
Chris Lattner155a4902008-07-08 05:46:34 +00001780 break;
Reid Spencerb913bba2006-12-24 18:52:08 +00001781 case ICmpInst::ICMP_ULT:
Nick Lewycky3892baa2009-09-20 04:27:06 +00001782 switch (pred) {
1783 case ICmpInst::ICMP_ULT: case ICmpInst::ICMP_NE: case ICmpInst::ICMP_ULE:
Nick Lewycky8de00362009-09-20 05:47:45 +00001784 Result = 1; break;
Nick Lewycky3892baa2009-09-20 04:27:06 +00001785 case ICmpInst::ICMP_UGT: case ICmpInst::ICMP_EQ: case ICmpInst::ICMP_UGE:
Nick Lewycky8de00362009-09-20 05:47:45 +00001786 Result = 0; break;
Nick Lewycky3892baa2009-09-20 04:27:06 +00001787 }
Chris Lattner155a4902008-07-08 05:46:34 +00001788 break;
Reid Spencerb913bba2006-12-24 18:52:08 +00001789 case ICmpInst::ICMP_SLT:
Nick Lewycky3892baa2009-09-20 04:27:06 +00001790 switch (pred) {
1791 case ICmpInst::ICMP_SLT: case ICmpInst::ICMP_NE: case ICmpInst::ICMP_SLE:
Nick Lewycky8de00362009-09-20 05:47:45 +00001792 Result = 1; break;
Nick Lewycky3892baa2009-09-20 04:27:06 +00001793 case ICmpInst::ICMP_SGT: case ICmpInst::ICMP_EQ: case ICmpInst::ICMP_SGE:
Nick Lewycky8de00362009-09-20 05:47:45 +00001794 Result = 0; break;
Nick Lewycky3892baa2009-09-20 04:27:06 +00001795 }
Chris Lattner155a4902008-07-08 05:46:34 +00001796 break;
Reid Spencerb913bba2006-12-24 18:52:08 +00001797 case ICmpInst::ICMP_UGT:
Nick Lewycky3892baa2009-09-20 04:27:06 +00001798 switch (pred) {
1799 case ICmpInst::ICMP_UGT: case ICmpInst::ICMP_NE: case ICmpInst::ICMP_UGE:
Nick Lewycky8de00362009-09-20 05:47:45 +00001800 Result = 1; break;
Nick Lewycky3892baa2009-09-20 04:27:06 +00001801 case ICmpInst::ICMP_ULT: case ICmpInst::ICMP_EQ: case ICmpInst::ICMP_ULE:
Nick Lewycky8de00362009-09-20 05:47:45 +00001802 Result = 0; break;
Nick Lewycky3892baa2009-09-20 04:27:06 +00001803 }
Chris Lattner155a4902008-07-08 05:46:34 +00001804 break;
Reid Spencerb913bba2006-12-24 18:52:08 +00001805 case ICmpInst::ICMP_SGT:
Nick Lewycky3892baa2009-09-20 04:27:06 +00001806 switch (pred) {
1807 case ICmpInst::ICMP_SGT: case ICmpInst::ICMP_NE: case ICmpInst::ICMP_SGE:
Nick Lewycky8de00362009-09-20 05:47:45 +00001808 Result = 1; break;
Nick Lewycky3892baa2009-09-20 04:27:06 +00001809 case ICmpInst::ICMP_SLT: case ICmpInst::ICMP_EQ: case ICmpInst::ICMP_SLE:
Nick Lewycky8de00362009-09-20 05:47:45 +00001810 Result = 0; break;
Nick Lewycky3892baa2009-09-20 04:27:06 +00001811 }
Chris Lattner155a4902008-07-08 05:46:34 +00001812 break;
Reid Spencerb913bba2006-12-24 18:52:08 +00001813 case ICmpInst::ICMP_ULE:
Chris Lattner155a4902008-07-08 05:46:34 +00001814 if (pred == ICmpInst::ICMP_UGT) Result = 0;
Nick Lewycky3892baa2009-09-20 04:27:06 +00001815 if (pred == ICmpInst::ICMP_ULT || pred == ICmpInst::ICMP_ULE) Result = 1;
Reid Spencerb913bba2006-12-24 18:52:08 +00001816 break;
1817 case ICmpInst::ICMP_SLE:
Chris Lattner155a4902008-07-08 05:46:34 +00001818 if (pred == ICmpInst::ICMP_SGT) Result = 0;
Nick Lewycky3892baa2009-09-20 04:27:06 +00001819 if (pred == ICmpInst::ICMP_SLT || pred == ICmpInst::ICMP_SLE) Result = 1;
Reid Spencerb913bba2006-12-24 18:52:08 +00001820 break;
Reid Spencerb913bba2006-12-24 18:52:08 +00001821 case ICmpInst::ICMP_UGE:
Chris Lattner155a4902008-07-08 05:46:34 +00001822 if (pred == ICmpInst::ICMP_ULT) Result = 0;
Nick Lewycky3892baa2009-09-20 04:27:06 +00001823 if (pred == ICmpInst::ICMP_UGT || pred == ICmpInst::ICMP_UGE) Result = 1;
Reid Spencerb913bba2006-12-24 18:52:08 +00001824 break;
1825 case ICmpInst::ICMP_SGE:
Chris Lattner155a4902008-07-08 05:46:34 +00001826 if (pred == ICmpInst::ICMP_SLT) Result = 0;
Nick Lewycky3892baa2009-09-20 04:27:06 +00001827 if (pred == ICmpInst::ICMP_SGT || pred == ICmpInst::ICMP_SGE) Result = 1;
Reid Spencerb913bba2006-12-24 18:52:08 +00001828 break;
Reid Spencerb913bba2006-12-24 18:52:08 +00001829 case ICmpInst::ICMP_NE:
Chris Lattner155a4902008-07-08 05:46:34 +00001830 if (pred == ICmpInst::ICMP_EQ) Result = 0;
1831 if (pred == ICmpInst::ICMP_NE) Result = 1;
Reid Spencerb913bba2006-12-24 18:52:08 +00001832 break;
1833 }
Dan Gohmanf8a87e82009-08-29 23:35:16 +00001834
Chris Lattner155a4902008-07-08 05:46:34 +00001835 // If we evaluated the result, return it now.
Nick Lewycky7f6aa2b2009-07-08 03:04:38 +00001836 if (Result != -1)
Chris Lattnerb29d5962010-02-01 20:48:08 +00001837 return ConstantInt::get(ResultTy, Result);
Dan Gohmanf8a87e82009-08-29 23:35:16 +00001838
Nick Lewycky55a722b2009-09-20 05:48:50 +00001839 // If the right hand side is a bitcast, try using its inverse to simplify
Chris Lattner6304b0d2010-02-01 20:04:40 +00001840 // it by moving it to the left hand side. We can't do this if it would turn
Duncan Sandsa419b562010-02-01 20:42:02 +00001841 // a vector compare into a scalar compare or visa versa.
Nick Lewycky55a722b2009-09-20 05:48:50 +00001842 if (ConstantExpr *CE2 = dyn_cast<ConstantExpr>(C2)) {
Chris Lattner6304b0d2010-02-01 20:04:40 +00001843 Constant *CE2Op0 = CE2->getOperand(0);
1844 if (CE2->getOpcode() == Instruction::BitCast &&
Nick Lewycky5bf7f882010-03-04 06:54:10 +00001845 CE2->getType()->isVectorTy() == CE2Op0->getType()->isVectorTy()) {
Nick Lewycky55a722b2009-09-20 05:48:50 +00001846 Constant *Inverse = ConstantExpr::getBitCast(C1, CE2Op0->getType());
1847 return ConstantExpr::getICmp(pred, Inverse, CE2Op0);
1848 }
1849 }
1850
Nick Lewycky149cbc22009-09-20 07:31:25 +00001851 // If the left hand side is an extension, try eliminating it.
1852 if (ConstantExpr *CE1 = dyn_cast<ConstantExpr>(C1)) {
Nick Lewycky5bf7f882010-03-04 06:54:10 +00001853 if ((CE1->getOpcode() == Instruction::SExt && ICmpInst::isSigned(pred)) ||
1854 (CE1->getOpcode() == Instruction::ZExt && !ICmpInst::isSigned(pred))){
Nick Lewycky149cbc22009-09-20 07:31:25 +00001855 Constant *CE1Op0 = CE1->getOperand(0);
1856 Constant *CE1Inverse = ConstantExpr::getTrunc(CE1, CE1Op0->getType());
1857 if (CE1Inverse == CE1Op0) {
1858 // Check whether we can safely truncate the right hand side.
1859 Constant *C2Inverse = ConstantExpr::getTrunc(C2, CE1Op0->getType());
1860 if (ConstantExpr::getZExt(C2Inverse, C2->getType()) == C2) {
1861 return ConstantExpr::getICmp(pred, CE1Inverse, C2Inverse);
1862 }
1863 }
1864 }
1865 }
1866
Eli Friedmane8e17832009-12-17 06:07:04 +00001867 if ((!isa<ConstantExpr>(C1) && isa<ConstantExpr>(C2)) ||
1868 (C1->isNullValue() && !C2->isNullValue())) {
Nick Lewycky7f6aa2b2009-07-08 03:04:38 +00001869 // If C2 is a constant expr and C1 isn't, flip them around and fold the
Reid Spencerb913bba2006-12-24 18:52:08 +00001870 // other way if possible.
Eli Friedmane8e17832009-12-17 06:07:04 +00001871 // Also, if C1 is null and C2 isn't, flip them around.
Nick Lewycky5bf7f882010-03-04 06:54:10 +00001872 pred = ICmpInst::getSwappedPredicate((ICmpInst::Predicate)pred);
1873 return ConstantExpr::getICmp(pred, C2, C1);
Chris Lattner504e8fb2004-01-13 05:51:55 +00001874 }
1875 }
1876 return 0;
Dan Gohmanf8a87e82009-08-29 23:35:16 +00001877}
Chris Lattnereab20b52004-01-12 22:07:24 +00001878
Dan Gohman3bfbc452009-09-11 00:04:14 +00001879/// isInBoundsIndices - Test whether the given sequence of *normalized* indices
1880/// is "inbounds".
Jay Foad25052d82011-01-14 08:07:43 +00001881template<typename IndexTy>
Jay Foaddab3d292011-07-21 14:31:17 +00001882static bool isInBoundsIndices(ArrayRef<IndexTy> Idxs) {
Dan Gohman3bfbc452009-09-11 00:04:14 +00001883 // No indices means nothing that could be out of bounds.
Jay Foaddab3d292011-07-21 14:31:17 +00001884 if (Idxs.empty()) return true;
Dan Gohman3bfbc452009-09-11 00:04:14 +00001885
1886 // If the first index is zero, it's in bounds.
Jay Foad25052d82011-01-14 08:07:43 +00001887 if (cast<Constant>(Idxs[0])->isNullValue()) return true;
Dan Gohman3bfbc452009-09-11 00:04:14 +00001888
1889 // If the first index is one and all the rest are zero, it's in bounds,
1890 // by the one-past-the-end rule.
1891 if (!cast<ConstantInt>(Idxs[0])->isOne())
1892 return false;
Jay Foaddab3d292011-07-21 14:31:17 +00001893 for (unsigned i = 1, e = Idxs.size(); i != e; ++i)
Jay Foad25052d82011-01-14 08:07:43 +00001894 if (!cast<Constant>(Idxs[i])->isNullValue())
Dan Gohman3bfbc452009-09-11 00:04:14 +00001895 return false;
1896 return true;
1897}
1898
Jay Foad25052d82011-01-14 08:07:43 +00001899template<typename IndexTy>
1900static Constant *ConstantFoldGetElementPtrImpl(Constant *C,
1901 bool inBounds,
Jay Foad7fc52e22011-07-19 15:30:30 +00001902 ArrayRef<IndexTy> Idxs) {
1903 if (Idxs.empty()) return C;
Jay Foad25052d82011-01-14 08:07:43 +00001904 Constant *Idx0 = cast<Constant>(Idxs[0]);
Jay Foad7fc52e22011-07-19 15:30:30 +00001905 if ((Idxs.size() == 1 && Idx0->isNullValue()))
Nick Lewycky33c06ad2009-09-20 01:35:59 +00001906 return C;
Chris Lattnereab20b52004-01-12 22:07:24 +00001907
Chris Lattnercfbf9fa2004-10-17 21:54:55 +00001908 if (isa<UndefValue>(C)) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001909 PointerType *Ptr = cast<PointerType>(C->getType());
Jay Foada9203102011-07-25 09:48:08 +00001910 Type *Ty = GetElementPtrInst::getIndexedType(Ptr, Idxs);
Chris Lattnercfbf9fa2004-10-17 21:54:55 +00001911 assert(Ty != 0 && "Invalid indices for GEP!");
Owen Anderson9e9a0d52009-07-30 23:03:37 +00001912 return UndefValue::get(PointerType::get(Ty, Ptr->getAddressSpace()));
Chris Lattnercfbf9fa2004-10-17 21:54:55 +00001913 }
1914
Chris Lattner2e9bb1a2004-02-16 20:46:13 +00001915 if (C->isNullValue()) {
1916 bool isNull = true;
Jay Foad7fc52e22011-07-19 15:30:30 +00001917 for (unsigned i = 0, e = Idxs.size(); i != e; ++i)
Jay Foad25052d82011-01-14 08:07:43 +00001918 if (!cast<Constant>(Idxs[i])->isNullValue()) {
Chris Lattner2e9bb1a2004-02-16 20:46:13 +00001919 isNull = false;
1920 break;
1921 }
1922 if (isNull) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001923 PointerType *Ptr = cast<PointerType>(C->getType());
Jay Foada9203102011-07-25 09:48:08 +00001924 Type *Ty = GetElementPtrInst::getIndexedType(Ptr, Idxs);
Chris Lattner2e9bb1a2004-02-16 20:46:13 +00001925 assert(Ty != 0 && "Invalid indices for GEP!");
Nick Lewyckyb8787f32011-01-30 01:48:50 +00001926 return ConstantPointerNull::get(PointerType::get(Ty,
1927 Ptr->getAddressSpace()));
Chris Lattner2e9bb1a2004-02-16 20:46:13 +00001928 }
1929 }
Chris Lattnereab20b52004-01-12 22:07:24 +00001930
Nick Lewycky33c06ad2009-09-20 01:35:59 +00001931 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
Chris Lattnereab20b52004-01-12 22:07:24 +00001932 // Combine Indices - If the source pointer to this getelementptr instruction
1933 // is a getelementptr instruction, combine the indices of the two
1934 // getelementptr instructions into a single instruction.
1935 //
1936 if (CE->getOpcode() == Instruction::GetElementPtr) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001937 Type *LastTy = 0;
Chris Lattnereab20b52004-01-12 22:07:24 +00001938 for (gep_type_iterator I = gep_type_begin(CE), E = gep_type_end(CE);
1939 I != E; ++I)
1940 LastTy = *I;
1941
Eli Friedmanadeb0a62011-12-15 04:33:48 +00001942 if ((LastTy && isa<SequentialType>(LastTy)) || Idx0->isNullValue()) {
Chris Lattner2b9a5da2007-01-31 04:40:28 +00001943 SmallVector<Value*, 16> NewIndices;
Jay Foad7fc52e22011-07-19 15:30:30 +00001944 NewIndices.reserve(Idxs.size() + CE->getNumOperands());
Chris Lattnereab20b52004-01-12 22:07:24 +00001945 for (unsigned i = 1, e = CE->getNumOperands()-1; i != e; ++i)
Chris Lattner7fa6e662004-10-11 22:52:25 +00001946 NewIndices.push_back(CE->getOperand(i));
Chris Lattnereab20b52004-01-12 22:07:24 +00001947
1948 // Add the last index of the source with the first index of the new GEP.
1949 // Make sure to handle the case when they are actually different types.
1950 Constant *Combined = CE->getOperand(CE->getNumOperands()-1);
Chris Lattner7fa6e662004-10-11 22:52:25 +00001951 // Otherwise it must be an array.
1952 if (!Idx0->isNullValue()) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001953 Type *IdxTy = Combined->getType();
Reid Spencer575d95c2006-12-04 02:46:44 +00001954 if (IdxTy != Idx0->getType()) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001955 Type *Int64Ty = Type::getInt64Ty(IdxTy->getContext());
Chris Lattnerb29d5962010-02-01 20:48:08 +00001956 Constant *C1 = ConstantExpr::getSExtOrBitCast(Idx0, Int64Ty);
1957 Constant *C2 = ConstantExpr::getSExtOrBitCast(Combined, Int64Ty);
Owen Andersonbaf3c402009-07-29 18:55:55 +00001958 Combined = ConstantExpr::get(Instruction::Add, C1, C2);
Reid Spencer575d95c2006-12-04 02:46:44 +00001959 } else {
1960 Combined =
Owen Andersonbaf3c402009-07-29 18:55:55 +00001961 ConstantExpr::get(Instruction::Add, Idx0, Combined);
Reid Spencer575d95c2006-12-04 02:46:44 +00001962 }
Chris Lattnerd3408672004-07-07 04:45:13 +00001963 }
Misha Brukmanfd939082005-04-21 23:48:37 +00001964
Chris Lattnereab20b52004-01-12 22:07:24 +00001965 NewIndices.push_back(Combined);
Jay Foad7fc52e22011-07-19 15:30:30 +00001966 NewIndices.append(Idxs.begin() + 1, Idxs.end());
Jay Foad4b5e2072011-07-21 15:15:37 +00001967 return
1968 ConstantExpr::getGetElementPtr(CE->getOperand(0), NewIndices,
1969 inBounds &&
1970 cast<GEPOperator>(CE)->isInBounds());
Chris Lattnereab20b52004-01-12 22:07:24 +00001971 }
1972 }
1973
Meador Inge8df7c392013-02-27 02:26:42 +00001974 // Attempt to fold casts to the same type away. For example, folding:
Chris Lattnereab20b52004-01-12 22:07:24 +00001975 //
Meador Inge8df7c392013-02-27 02:26:42 +00001976 // i32* getelementptr ([2 x i32]* bitcast ([3 x i32]* %X to [2 x i32]*),
1977 // i64 0, i64 0)
1978 // into:
1979 //
1980 // i32* getelementptr ([3 x i32]* %X, i64 0, i64 0)
1981 //
1982 // Don't fold if the cast is changing address spaces.
Jay Foad7fc52e22011-07-19 15:30:30 +00001983 if (CE->isCast() && Idxs.size() > 1 && Idx0->isNullValue()) {
Meador Inge8df7c392013-02-27 02:26:42 +00001984 PointerType *SrcPtrTy =
1985 dyn_cast<PointerType>(CE->getOperand(0)->getType());
1986 PointerType *DstPtrTy = dyn_cast<PointerType>(CE->getType());
1987 if (SrcPtrTy && DstPtrTy) {
1988 ArrayType *SrcArrayTy =
1989 dyn_cast<ArrayType>(SrcPtrTy->getElementType());
1990 ArrayType *DstArrayTy =
1991 dyn_cast<ArrayType>(DstPtrTy->getElementType());
1992 if (SrcArrayTy && DstArrayTy
1993 && SrcArrayTy->getElementType() == DstArrayTy->getElementType()
1994 && SrcPtrTy->getAddressSpace() == DstPtrTy->getAddressSpace())
1995 return ConstantExpr::getGetElementPtr((Constant*)CE->getOperand(0),
1996 Idxs, inBounds);
1997 }
Chris Lattnerfe9d82a2007-08-13 17:09:08 +00001998 }
Chris Lattnereab20b52004-01-12 22:07:24 +00001999 }
Dan Gohman3bfbc452009-09-11 00:04:14 +00002000
2001 // Check to see if any array indices are not within the corresponding
2002 // notional array bounds. If so, try to determine if they can be factored
2003 // out into preceding dimensions.
2004 bool Unknown = false;
2005 SmallVector<Constant *, 8> NewIdxs;
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002006 Type *Ty = C->getType();
2007 Type *Prev = 0;
Jay Foad7fc52e22011-07-19 15:30:30 +00002008 for (unsigned i = 0, e = Idxs.size(); i != e;
Dan Gohman3bfbc452009-09-11 00:04:14 +00002009 Prev = Ty, Ty = cast<CompositeType>(Ty)->getTypeAtIndex(Idxs[i]), ++i) {
2010 if (ConstantInt *CI = dyn_cast<ConstantInt>(Idxs[i])) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002011 if (ArrayType *ATy = dyn_cast<ArrayType>(Ty))
Dan Gohman3bfbc452009-09-11 00:04:14 +00002012 if (ATy->getNumElements() <= INT64_MAX &&
2013 ATy->getNumElements() != 0 &&
2014 CI->getSExtValue() >= (int64_t)ATy->getNumElements()) {
2015 if (isa<SequentialType>(Prev)) {
2016 // It's out of range, but we can factor it into the prior
2017 // dimension.
Jay Foad7fc52e22011-07-19 15:30:30 +00002018 NewIdxs.resize(Idxs.size());
Dan Gohman3bfbc452009-09-11 00:04:14 +00002019 ConstantInt *Factor = ConstantInt::get(CI->getType(),
2020 ATy->getNumElements());
2021 NewIdxs[i] = ConstantExpr::getSRem(CI, Factor);
2022
Jay Foad25052d82011-01-14 08:07:43 +00002023 Constant *PrevIdx = cast<Constant>(Idxs[i-1]);
Dan Gohman3bfbc452009-09-11 00:04:14 +00002024 Constant *Div = ConstantExpr::getSDiv(CI, Factor);
2025
2026 // Before adding, extend both operands to i64 to avoid
2027 // overflow trouble.
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00002028 if (!PrevIdx->getType()->isIntegerTy(64))
Dan Gohman3bfbc452009-09-11 00:04:14 +00002029 PrevIdx = ConstantExpr::getSExt(PrevIdx,
Chris Lattnerb29d5962010-02-01 20:48:08 +00002030 Type::getInt64Ty(Div->getContext()));
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00002031 if (!Div->getType()->isIntegerTy(64))
Dan Gohman3bfbc452009-09-11 00:04:14 +00002032 Div = ConstantExpr::getSExt(Div,
Chris Lattnerb29d5962010-02-01 20:48:08 +00002033 Type::getInt64Ty(Div->getContext()));
Dan Gohman3bfbc452009-09-11 00:04:14 +00002034
2035 NewIdxs[i-1] = ConstantExpr::getAdd(PrevIdx, Div);
2036 } else {
2037 // It's out of range, but the prior dimension is a struct
2038 // so we can't do anything about it.
2039 Unknown = true;
2040 }
2041 }
2042 } else {
2043 // We don't know if it's in range or not.
2044 Unknown = true;
2045 }
2046 }
2047
2048 // If we did any factoring, start over with the adjusted indices.
2049 if (!NewIdxs.empty()) {
Jay Foad7fc52e22011-07-19 15:30:30 +00002050 for (unsigned i = 0, e = Idxs.size(); i != e; ++i)
Jay Foad25052d82011-01-14 08:07:43 +00002051 if (!NewIdxs[i]) NewIdxs[i] = cast<Constant>(Idxs[i]);
Jay Foad4b5e2072011-07-21 15:15:37 +00002052 return ConstantExpr::getGetElementPtr(C, NewIdxs, inBounds);
Dan Gohman3bfbc452009-09-11 00:04:14 +00002053 }
2054
2055 // If all indices are known integers and normalized, we can do a simple
2056 // check for the "inbounds" property.
2057 if (!Unknown && !inBounds &&
Jay Foaddab3d292011-07-21 14:31:17 +00002058 isa<GlobalVariable>(C) && isInBoundsIndices(Idxs))
2059 return ConstantExpr::getInBoundsGetElementPtr(C, Idxs);
Dan Gohman3bfbc452009-09-11 00:04:14 +00002060
Chris Lattnereab20b52004-01-12 22:07:24 +00002061 return 0;
2062}
Jay Foad25052d82011-01-14 08:07:43 +00002063
2064Constant *llvm::ConstantFoldGetElementPtr(Constant *C,
2065 bool inBounds,
Jay Foad7fc52e22011-07-19 15:30:30 +00002066 ArrayRef<Constant *> Idxs) {
2067 return ConstantFoldGetElementPtrImpl(C, inBounds, Idxs);
Jay Foad25052d82011-01-14 08:07:43 +00002068}
2069
2070Constant *llvm::ConstantFoldGetElementPtr(Constant *C,
2071 bool inBounds,
Jay Foad7fc52e22011-07-19 15:30:30 +00002072 ArrayRef<Value *> Idxs) {
2073 return ConstantFoldGetElementPtrImpl(C, inBounds, Idxs);
Jay Foad25052d82011-01-14 08:07:43 +00002074}