Enhance constant folding of bitcast operations on vectors of floats.
[oota-llvm.git] / lib / VMCore / Constants.cpp
1 //===-- Constants.cpp - Implement Constant nodes --------------------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file implements the Constant* classes.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #include "llvm/Constants.h"
15 #include "LLVMContextImpl.h"
16 #include "ConstantFold.h"
17 #include "llvm/DerivedTypes.h"
18 #include "llvm/GlobalValue.h"
19 #include "llvm/Instructions.h"
20 #include "llvm/Module.h"
21 #include "llvm/Operator.h"
22 #include "llvm/ADT/FoldingSet.h"
23 #include "llvm/ADT/StringExtras.h"
24 #include "llvm/ADT/StringMap.h"
25 #include "llvm/Support/Compiler.h"
26 #include "llvm/Support/Debug.h"
27 #include "llvm/Support/ErrorHandling.h"
28 #include "llvm/Support/ManagedStatic.h"
29 #include "llvm/Support/MathExtras.h"
30 #include "llvm/Support/raw_ostream.h"
31 #include "llvm/Support/GetElementPtrTypeIterator.h"
32 #include "llvm/ADT/DenseMap.h"
33 #include "llvm/ADT/SmallVector.h"
34 #include <algorithm>
35 #include <map>
36 using namespace llvm;
37
38 //===----------------------------------------------------------------------===//
39 //                              Constant Class
40 //===----------------------------------------------------------------------===//
41
42 // Constructor to create a '0' constant of arbitrary type...
43 Constant *Constant::getNullValue(const Type *Ty) {
44   switch (Ty->getTypeID()) {
45   case Type::IntegerTyID:
46     return ConstantInt::get(Ty, 0);
47   case Type::FloatTyID:
48     return ConstantFP::get(Ty->getContext(),
49                            APFloat::getZero(APFloat::IEEEsingle));
50   case Type::DoubleTyID:
51     return ConstantFP::get(Ty->getContext(),
52                            APFloat::getZero(APFloat::IEEEdouble));
53   case Type::X86_FP80TyID:
54     return ConstantFP::get(Ty->getContext(),
55                            APFloat::getZero(APFloat::x87DoubleExtended));
56   case Type::FP128TyID:
57     return ConstantFP::get(Ty->getContext(),
58                            APFloat::getZero(APFloat::IEEEquad));
59   case Type::PPC_FP128TyID:
60     return ConstantFP::get(Ty->getContext(),
61                            APFloat(APInt::getNullValue(128)));
62   case Type::PointerTyID:
63     return ConstantPointerNull::get(cast<PointerType>(Ty));
64   case Type::StructTyID:
65   case Type::ArrayTyID:
66   case Type::VectorTyID:
67     return ConstantAggregateZero::get(Ty);
68   default:
69     // Function, Label, or Opaque type?
70     assert(!"Cannot create a null constant of that type!");
71     return 0;
72   }
73 }
74
75 Constant *Constant::getIntegerValue(const Type *Ty, const APInt &V) {
76   const Type *ScalarTy = Ty->getScalarType();
77
78   // Create the base integer constant.
79   Constant *C = ConstantInt::get(Ty->getContext(), V);
80
81   // Convert an integer to a pointer, if necessary.
82   if (const PointerType *PTy = dyn_cast<PointerType>(ScalarTy))
83     C = ConstantExpr::getIntToPtr(C, PTy);
84
85   // Broadcast a scalar to a vector, if necessary.
86   if (const VectorType *VTy = dyn_cast<VectorType>(Ty))
87     C = ConstantVector::get(std::vector<Constant *>(VTy->getNumElements(), C));
88
89   return C;
90 }
91
92 Constant *Constant::getAllOnesValue(const Type *Ty) {
93   if (const IntegerType *ITy = dyn_cast<IntegerType>(Ty))
94     return ConstantInt::get(Ty->getContext(),
95                             APInt::getAllOnesValue(ITy->getBitWidth()));
96
97   if (Ty->isFloatingPointTy()) {
98     APFloat FL = APFloat::getAllOnesValue(Ty->getPrimitiveSizeInBits(),
99                                           !Ty->isPPC_FP128Ty());
100     return ConstantFP::get(Ty->getContext(), FL);
101   }
102
103   SmallVector<Constant*, 16> Elts;
104   const VectorType *VTy = cast<VectorType>(Ty);
105   Elts.resize(VTy->getNumElements(), getAllOnesValue(VTy->getElementType()));
106   assert(Elts[0] && "Not a vector integer type!");
107   return cast<ConstantVector>(ConstantVector::get(Elts));
108 }
109
110 void Constant::destroyConstantImpl() {
111   // When a Constant is destroyed, there may be lingering
112   // references to the constant by other constants in the constant pool.  These
113   // constants are implicitly dependent on the module that is being deleted,
114   // but they don't know that.  Because we only find out when the CPV is
115   // deleted, we must now notify all of our users (that should only be
116   // Constants) that they are, in fact, invalid now and should be deleted.
117   //
118   while (!use_empty()) {
119     Value *V = use_back();
120 #ifndef NDEBUG      // Only in -g mode...
121     if (!isa<Constant>(V)) {
122       dbgs() << "While deleting: " << *this
123              << "\n\nUse still stuck around after Def is destroyed: "
124              << *V << "\n\n";
125     }
126 #endif
127     assert(isa<Constant>(V) && "References remain to Constant being destroyed");
128     Constant *CV = cast<Constant>(V);
129     CV->destroyConstant();
130
131     // The constant should remove itself from our use list...
132     assert((use_empty() || use_back() != V) && "Constant not removed!");
133   }
134
135   // Value has no outstanding references it is safe to delete it now...
136   delete this;
137 }
138
139 /// canTrap - Return true if evaluation of this constant could trap.  This is
140 /// true for things like constant expressions that could divide by zero.
141 bool Constant::canTrap() const {
142   assert(getType()->isFirstClassType() && "Cannot evaluate aggregate vals!");
143   // The only thing that could possibly trap are constant exprs.
144   const ConstantExpr *CE = dyn_cast<ConstantExpr>(this);
145   if (!CE) return false;
146   
147   // ConstantExpr traps if any operands can trap. 
148   for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
149     if (CE->getOperand(i)->canTrap()) 
150       return true;
151
152   // Otherwise, only specific operations can trap.
153   switch (CE->getOpcode()) {
154   default:
155     return false;
156   case Instruction::UDiv:
157   case Instruction::SDiv:
158   case Instruction::FDiv:
159   case Instruction::URem:
160   case Instruction::SRem:
161   case Instruction::FRem:
162     // Div and rem can trap if the RHS is not known to be non-zero.
163     if (!isa<ConstantInt>(CE->getOperand(1)) ||CE->getOperand(1)->isNullValue())
164       return true;
165     return false;
166   }
167 }
168
169 /// isConstantUsed - Return true if the constant has users other than constant
170 /// exprs and other dangling things.
171 bool Constant::isConstantUsed() const {
172   for (const_use_iterator UI = use_begin(), E = use_end(); UI != E; ++UI) {
173     const Constant *UC = dyn_cast<Constant>(*UI);
174     if (UC == 0 || isa<GlobalValue>(UC))
175       return true;
176     
177     if (UC->isConstantUsed())
178       return true;
179   }
180   return false;
181 }
182
183
184
185 /// getRelocationInfo - This method classifies the entry according to
186 /// whether or not it may generate a relocation entry.  This must be
187 /// conservative, so if it might codegen to a relocatable entry, it should say
188 /// so.  The return values are:
189 /// 
190 ///  NoRelocation: This constant pool entry is guaranteed to never have a
191 ///     relocation applied to it (because it holds a simple constant like
192 ///     '4').
193 ///  LocalRelocation: This entry has relocations, but the entries are
194 ///     guaranteed to be resolvable by the static linker, so the dynamic
195 ///     linker will never see them.
196 ///  GlobalRelocations: This entry may have arbitrary relocations.
197 ///
198 /// FIXME: This really should not be in VMCore.
199 Constant::PossibleRelocationsTy Constant::getRelocationInfo() const {
200   if (const GlobalValue *GV = dyn_cast<GlobalValue>(this)) {
201     if (GV->hasLocalLinkage() || GV->hasHiddenVisibility())
202       return LocalRelocation;  // Local to this file/library.
203     return GlobalRelocations;    // Global reference.
204   }
205   
206   if (const BlockAddress *BA = dyn_cast<BlockAddress>(this))
207     return BA->getFunction()->getRelocationInfo();
208   
209   // While raw uses of blockaddress need to be relocated, differences between
210   // two of them don't when they are for labels in the same function.  This is a
211   // common idiom when creating a table for the indirect goto extension, so we
212   // handle it efficiently here.
213   if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(this))
214     if (CE->getOpcode() == Instruction::Sub) {
215       ConstantExpr *LHS = dyn_cast<ConstantExpr>(CE->getOperand(0));
216       ConstantExpr *RHS = dyn_cast<ConstantExpr>(CE->getOperand(1));
217       if (LHS && RHS &&
218           LHS->getOpcode() == Instruction::PtrToInt &&
219           RHS->getOpcode() == Instruction::PtrToInt &&
220           isa<BlockAddress>(LHS->getOperand(0)) &&
221           isa<BlockAddress>(RHS->getOperand(0)) &&
222           cast<BlockAddress>(LHS->getOperand(0))->getFunction() ==
223             cast<BlockAddress>(RHS->getOperand(0))->getFunction())
224         return NoRelocation;
225     }
226   
227   PossibleRelocationsTy Result = NoRelocation;
228   for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
229     Result = std::max(Result,
230                       cast<Constant>(getOperand(i))->getRelocationInfo());
231   
232   return Result;
233 }
234
235
236 /// getVectorElements - This method, which is only valid on constant of vector
237 /// type, returns the elements of the vector in the specified smallvector.
238 /// This handles breaking down a vector undef into undef elements, etc.  For
239 /// constant exprs and other cases we can't handle, we return an empty vector.
240 void Constant::getVectorElements(SmallVectorImpl<Constant*> &Elts) const {
241   assert(getType()->isVectorTy() && "Not a vector constant!");
242   
243   if (const ConstantVector *CV = dyn_cast<ConstantVector>(this)) {
244     for (unsigned i = 0, e = CV->getNumOperands(); i != e; ++i)
245       Elts.push_back(CV->getOperand(i));
246     return;
247   }
248   
249   const VectorType *VT = cast<VectorType>(getType());
250   if (isa<ConstantAggregateZero>(this)) {
251     Elts.assign(VT->getNumElements(), 
252                 Constant::getNullValue(VT->getElementType()));
253     return;
254   }
255   
256   if (isa<UndefValue>(this)) {
257     Elts.assign(VT->getNumElements(), UndefValue::get(VT->getElementType()));
258     return;
259   }
260   
261   // Unknown type, must be constant expr etc.
262 }
263
264
265
266 //===----------------------------------------------------------------------===//
267 //                                ConstantInt
268 //===----------------------------------------------------------------------===//
269
270 ConstantInt::ConstantInt(const IntegerType *Ty, const APInt& V)
271   : Constant(Ty, ConstantIntVal, 0, 0), Val(V) {
272   assert(V.getBitWidth() == Ty->getBitWidth() && "Invalid constant for type");
273 }
274
275 ConstantInt* ConstantInt::getTrue(LLVMContext &Context) {
276   LLVMContextImpl *pImpl = Context.pImpl;
277   if (!pImpl->TheTrueVal)
278     pImpl->TheTrueVal = ConstantInt::get(Type::getInt1Ty(Context), 1);
279   return pImpl->TheTrueVal;
280 }
281
282 ConstantInt* ConstantInt::getFalse(LLVMContext &Context) {
283   LLVMContextImpl *pImpl = Context.pImpl;
284   if (!pImpl->TheFalseVal)
285     pImpl->TheFalseVal = ConstantInt::get(Type::getInt1Ty(Context), 0);
286   return pImpl->TheFalseVal;
287 }
288
289
290 // Get a ConstantInt from an APInt. Note that the value stored in the DenseMap 
291 // as the key, is a DenseMapAPIntKeyInfo::KeyTy which has provided the
292 // operator== and operator!= to ensure that the DenseMap doesn't attempt to
293 // compare APInt's of different widths, which would violate an APInt class
294 // invariant which generates an assertion.
295 ConstantInt *ConstantInt::get(LLVMContext &Context, const APInt& V) {
296   // Get the corresponding integer type for the bit width of the value.
297   const IntegerType *ITy = IntegerType::get(Context, V.getBitWidth());
298   // get an existing value or the insertion position
299   DenseMapAPIntKeyInfo::KeyTy Key(V, ITy);
300   ConstantInt *&Slot = Context.pImpl->IntConstants[Key]; 
301   if (!Slot) Slot = new ConstantInt(ITy, V);
302   return Slot;
303 }
304
305 Constant *ConstantInt::get(const Type* Ty, uint64_t V, bool isSigned) {
306   Constant *C = get(cast<IntegerType>(Ty->getScalarType()),
307                                V, isSigned);
308
309   // For vectors, broadcast the value.
310   if (const VectorType *VTy = dyn_cast<VectorType>(Ty))
311     return ConstantVector::get(SmallVector<Constant*,
312                                            16>(VTy->getNumElements(), C));
313
314   return C;
315 }
316
317 ConstantInt* ConstantInt::get(const IntegerType* Ty, uint64_t V, 
318                               bool isSigned) {
319   return get(Ty->getContext(), APInt(Ty->getBitWidth(), V, isSigned));
320 }
321
322 ConstantInt* ConstantInt::getSigned(const IntegerType* Ty, int64_t V) {
323   return get(Ty, V, true);
324 }
325
326 Constant *ConstantInt::getSigned(const Type *Ty, int64_t V) {
327   return get(Ty, V, true);
328 }
329
330 Constant *ConstantInt::get(const Type* Ty, const APInt& V) {
331   ConstantInt *C = get(Ty->getContext(), V);
332   assert(C->getType() == Ty->getScalarType() &&
333          "ConstantInt type doesn't match the type implied by its value!");
334
335   // For vectors, broadcast the value.
336   if (const VectorType *VTy = dyn_cast<VectorType>(Ty))
337     return ConstantVector::get(
338       SmallVector<Constant *, 16>(VTy->getNumElements(), C));
339
340   return C;
341 }
342
343 ConstantInt* ConstantInt::get(const IntegerType* Ty, StringRef Str,
344                               uint8_t radix) {
345   return get(Ty->getContext(), APInt(Ty->getBitWidth(), Str, radix));
346 }
347
348 //===----------------------------------------------------------------------===//
349 //                                ConstantFP
350 //===----------------------------------------------------------------------===//
351
352 static const fltSemantics *TypeToFloatSemantics(const Type *Ty) {
353   if (Ty->isFloatTy())
354     return &APFloat::IEEEsingle;
355   if (Ty->isDoubleTy())
356     return &APFloat::IEEEdouble;
357   if (Ty->isX86_FP80Ty())
358     return &APFloat::x87DoubleExtended;
359   else if (Ty->isFP128Ty())
360     return &APFloat::IEEEquad;
361   
362   assert(Ty->isPPC_FP128Ty() && "Unknown FP format");
363   return &APFloat::PPCDoubleDouble;
364 }
365
366 /// get() - This returns a constant fp for the specified value in the
367 /// specified type.  This should only be used for simple constant values like
368 /// 2.0/1.0 etc, that are known-valid both as double and as the target format.
369 Constant *ConstantFP::get(const Type* Ty, double V) {
370   LLVMContext &Context = Ty->getContext();
371   
372   APFloat FV(V);
373   bool ignored;
374   FV.convert(*TypeToFloatSemantics(Ty->getScalarType()),
375              APFloat::rmNearestTiesToEven, &ignored);
376   Constant *C = get(Context, FV);
377
378   // For vectors, broadcast the value.
379   if (const VectorType *VTy = dyn_cast<VectorType>(Ty))
380     return ConstantVector::get(
381       SmallVector<Constant *, 16>(VTy->getNumElements(), C));
382
383   return C;
384 }
385
386
387 Constant *ConstantFP::get(const Type* Ty, StringRef Str) {
388   LLVMContext &Context = Ty->getContext();
389
390   APFloat FV(*TypeToFloatSemantics(Ty->getScalarType()), Str);
391   Constant *C = get(Context, FV);
392
393   // For vectors, broadcast the value.
394   if (const VectorType *VTy = dyn_cast<VectorType>(Ty))
395     return ConstantVector::get(
396       SmallVector<Constant *, 16>(VTy->getNumElements(), C));
397
398   return C; 
399 }
400
401
402 ConstantFP* ConstantFP::getNegativeZero(const Type* Ty) {
403   LLVMContext &Context = Ty->getContext();
404   APFloat apf = cast <ConstantFP>(Constant::getNullValue(Ty))->getValueAPF();
405   apf.changeSign();
406   return get(Context, apf);
407 }
408
409
410 Constant *ConstantFP::getZeroValueForNegation(const Type* Ty) {
411   if (const VectorType *PTy = dyn_cast<VectorType>(Ty))
412     if (PTy->getElementType()->isFloatingPointTy()) {
413       SmallVector<Constant*, 16> zeros(PTy->getNumElements(),
414                            getNegativeZero(PTy->getElementType()));
415       return ConstantVector::get(zeros);
416     }
417
418   if (Ty->isFloatingPointTy()) 
419     return getNegativeZero(Ty);
420
421   return Constant::getNullValue(Ty);
422 }
423
424
425 // ConstantFP accessors.
426 ConstantFP* ConstantFP::get(LLVMContext &Context, const APFloat& V) {
427   DenseMapAPFloatKeyInfo::KeyTy Key(V);
428   
429   LLVMContextImpl* pImpl = Context.pImpl;
430   
431   ConstantFP *&Slot = pImpl->FPConstants[Key];
432     
433   if (!Slot) {
434     const Type *Ty;
435     if (&V.getSemantics() == &APFloat::IEEEsingle)
436       Ty = Type::getFloatTy(Context);
437     else if (&V.getSemantics() == &APFloat::IEEEdouble)
438       Ty = Type::getDoubleTy(Context);
439     else if (&V.getSemantics() == &APFloat::x87DoubleExtended)
440       Ty = Type::getX86_FP80Ty(Context);
441     else if (&V.getSemantics() == &APFloat::IEEEquad)
442       Ty = Type::getFP128Ty(Context);
443     else {
444       assert(&V.getSemantics() == &APFloat::PPCDoubleDouble && 
445              "Unknown FP format");
446       Ty = Type::getPPC_FP128Ty(Context);
447     }
448     Slot = new ConstantFP(Ty, V);
449   }
450   
451   return Slot;
452 }
453
454 ConstantFP *ConstantFP::getInfinity(const Type *Ty, bool Negative) {
455   const fltSemantics &Semantics = *TypeToFloatSemantics(Ty);
456   return ConstantFP::get(Ty->getContext(),
457                          APFloat::getInf(Semantics, Negative));
458 }
459
460 ConstantFP::ConstantFP(const Type *Ty, const APFloat& V)
461   : Constant(Ty, ConstantFPVal, 0, 0), Val(V) {
462   assert(&V.getSemantics() == TypeToFloatSemantics(Ty) &&
463          "FP type Mismatch");
464 }
465
466 bool ConstantFP::isNullValue() const {
467   return Val.isZero() && !Val.isNegative();
468 }
469
470 bool ConstantFP::isExactlyValue(const APFloat& V) const {
471   return Val.bitwiseIsEqual(V);
472 }
473
474 //===----------------------------------------------------------------------===//
475 //                            ConstantXXX Classes
476 //===----------------------------------------------------------------------===//
477
478
479 ConstantArray::ConstantArray(const ArrayType *T,
480                              const std::vector<Constant*> &V)
481   : Constant(T, ConstantArrayVal,
482              OperandTraits<ConstantArray>::op_end(this) - V.size(),
483              V.size()) {
484   assert(V.size() == T->getNumElements() &&
485          "Invalid initializer vector for constant array");
486   Use *OL = OperandList;
487   for (std::vector<Constant*>::const_iterator I = V.begin(), E = V.end();
488        I != E; ++I, ++OL) {
489     Constant *C = *I;
490     assert(C->getType() == T->getElementType() &&
491            "Initializer for array element doesn't match array element type!");
492     *OL = C;
493   }
494 }
495
496 Constant *ConstantArray::get(const ArrayType *Ty, 
497                              const std::vector<Constant*> &V) {
498   for (unsigned i = 0, e = V.size(); i != e; ++i) {
499     assert(V[i]->getType() == Ty->getElementType() &&
500            "Wrong type in array element initializer");
501   }
502   LLVMContextImpl *pImpl = Ty->getContext().pImpl;
503   // If this is an all-zero array, return a ConstantAggregateZero object
504   if (!V.empty()) {
505     Constant *C = V[0];
506     if (!C->isNullValue())
507       return pImpl->ArrayConstants.getOrCreate(Ty, V);
508     
509     for (unsigned i = 1, e = V.size(); i != e; ++i)
510       if (V[i] != C)
511         return pImpl->ArrayConstants.getOrCreate(Ty, V);
512   }
513   
514   return ConstantAggregateZero::get(Ty);
515 }
516
517
518 Constant *ConstantArray::get(const ArrayType* T, Constant *const* Vals,
519                              unsigned NumVals) {
520   // FIXME: make this the primary ctor method.
521   return get(T, std::vector<Constant*>(Vals, Vals+NumVals));
522 }
523
524 /// ConstantArray::get(const string&) - Return an array that is initialized to
525 /// contain the specified string.  If length is zero then a null terminator is 
526 /// added to the specified string so that it may be used in a natural way. 
527 /// Otherwise, the length parameter specifies how much of the string to use 
528 /// and it won't be null terminated.
529 ///
530 Constant *ConstantArray::get(LLVMContext &Context, StringRef Str,
531                              bool AddNull) {
532   std::vector<Constant*> ElementVals;
533   ElementVals.reserve(Str.size() + size_t(AddNull));
534   for (unsigned i = 0; i < Str.size(); ++i)
535     ElementVals.push_back(ConstantInt::get(Type::getInt8Ty(Context), Str[i]));
536
537   // Add a null terminator to the string...
538   if (AddNull) {
539     ElementVals.push_back(ConstantInt::get(Type::getInt8Ty(Context), 0));
540   }
541
542   ArrayType *ATy = ArrayType::get(Type::getInt8Ty(Context), ElementVals.size());
543   return get(ATy, ElementVals);
544 }
545
546
547
548 ConstantStruct::ConstantStruct(const StructType *T,
549                                const std::vector<Constant*> &V)
550   : Constant(T, ConstantStructVal,
551              OperandTraits<ConstantStruct>::op_end(this) - V.size(),
552              V.size()) {
553   assert(V.size() == T->getNumElements() &&
554          "Invalid initializer vector for constant structure");
555   Use *OL = OperandList;
556   for (std::vector<Constant*>::const_iterator I = V.begin(), E = V.end();
557        I != E; ++I, ++OL) {
558     Constant *C = *I;
559     assert(C->getType() == T->getElementType(I-V.begin()) &&
560            "Initializer for struct element doesn't match struct element type!");
561     *OL = C;
562   }
563 }
564
565 // ConstantStruct accessors.
566 Constant *ConstantStruct::get(const StructType* T,
567                               const std::vector<Constant*>& V) {
568   LLVMContextImpl* pImpl = T->getContext().pImpl;
569   
570   // Create a ConstantAggregateZero value if all elements are zeros...
571   for (unsigned i = 0, e = V.size(); i != e; ++i)
572     if (!V[i]->isNullValue())
573       return pImpl->StructConstants.getOrCreate(T, V);
574
575   return ConstantAggregateZero::get(T);
576 }
577
578 Constant *ConstantStruct::get(LLVMContext &Context,
579                               const std::vector<Constant*>& V, bool packed) {
580   std::vector<const Type*> StructEls;
581   StructEls.reserve(V.size());
582   for (unsigned i = 0, e = V.size(); i != e; ++i)
583     StructEls.push_back(V[i]->getType());
584   return get(StructType::get(Context, StructEls, packed), V);
585 }
586
587 Constant *ConstantStruct::get(LLVMContext &Context,
588                               Constant *const *Vals, unsigned NumVals,
589                               bool Packed) {
590   // FIXME: make this the primary ctor method.
591   return get(Context, std::vector<Constant*>(Vals, Vals+NumVals), Packed);
592 }
593
594 ConstantVector::ConstantVector(const VectorType *T,
595                                const std::vector<Constant*> &V)
596   : Constant(T, ConstantVectorVal,
597              OperandTraits<ConstantVector>::op_end(this) - V.size(),
598              V.size()) {
599   Use *OL = OperandList;
600   for (std::vector<Constant*>::const_iterator I = V.begin(), E = V.end();
601        I != E; ++I, ++OL) {
602     Constant *C = *I;
603     assert(C->getType() == T->getElementType() &&
604            "Initializer for vector element doesn't match vector element type!");
605     *OL = C;
606   }
607 }
608
609 // ConstantVector accessors.
610 Constant *ConstantVector::get(const VectorType *T,
611                               const std::vector<Constant*> &V) {
612   assert(!V.empty() && "Vectors can't be empty");
613   LLVMContextImpl *pImpl = T->getContext().pImpl;
614
615   // If this is an all-undef or all-zero vector, return a
616   // ConstantAggregateZero or UndefValue.
617   Constant *C = V[0];
618   bool isZero = C->isNullValue();
619   bool isUndef = isa<UndefValue>(C);
620
621   if (isZero || isUndef) {
622     for (unsigned i = 1, e = V.size(); i != e; ++i)
623       if (V[i] != C) {
624         isZero = isUndef = false;
625         break;
626       }
627   }
628   
629   if (isZero)
630     return ConstantAggregateZero::get(T);
631   if (isUndef)
632     return UndefValue::get(T);
633     
634   return pImpl->VectorConstants.getOrCreate(T, V);
635 }
636
637 Constant *ConstantVector::get(ArrayRef<Constant*> V) {
638   // FIXME: make this the primary ctor method.
639   assert(!V.empty() && "Vectors cannot be empty");
640   return get(VectorType::get(V.front()->getType(), V.size()), V.vec());
641 }
642
643 // Utility function for determining if a ConstantExpr is a CastOp or not. This
644 // can't be inline because we don't want to #include Instruction.h into
645 // Constant.h
646 bool ConstantExpr::isCast() const {
647   return Instruction::isCast(getOpcode());
648 }
649
650 bool ConstantExpr::isCompare() const {
651   return getOpcode() == Instruction::ICmp || getOpcode() == Instruction::FCmp;
652 }
653
654 bool ConstantExpr::isGEPWithNoNotionalOverIndexing() const {
655   if (getOpcode() != Instruction::GetElementPtr) return false;
656
657   gep_type_iterator GEPI = gep_type_begin(this), E = gep_type_end(this);
658   User::const_op_iterator OI = llvm::next(this->op_begin());
659
660   // Skip the first index, as it has no static limit.
661   ++GEPI;
662   ++OI;
663
664   // The remaining indices must be compile-time known integers within the
665   // bounds of the corresponding notional static array types.
666   for (; GEPI != E; ++GEPI, ++OI) {
667     ConstantInt *CI = dyn_cast<ConstantInt>(*OI);
668     if (!CI) return false;
669     if (const ArrayType *ATy = dyn_cast<ArrayType>(*GEPI))
670       if (CI->getValue().getActiveBits() > 64 ||
671           CI->getZExtValue() >= ATy->getNumElements())
672         return false;
673   }
674
675   // All the indices checked out.
676   return true;
677 }
678
679 bool ConstantExpr::hasIndices() const {
680   return getOpcode() == Instruction::ExtractValue ||
681          getOpcode() == Instruction::InsertValue;
682 }
683
684 const SmallVector<unsigned, 4> &ConstantExpr::getIndices() const {
685   if (const ExtractValueConstantExpr *EVCE =
686         dyn_cast<ExtractValueConstantExpr>(this))
687     return EVCE->Indices;
688
689   return cast<InsertValueConstantExpr>(this)->Indices;
690 }
691
692 unsigned ConstantExpr::getPredicate() const {
693   assert(getOpcode() == Instruction::FCmp || 
694          getOpcode() == Instruction::ICmp);
695   return ((const CompareConstantExpr*)this)->predicate;
696 }
697
698 /// getWithOperandReplaced - Return a constant expression identical to this
699 /// one, but with the specified operand set to the specified value.
700 Constant *
701 ConstantExpr::getWithOperandReplaced(unsigned OpNo, Constant *Op) const {
702   assert(OpNo < getNumOperands() && "Operand num is out of range!");
703   assert(Op->getType() == getOperand(OpNo)->getType() &&
704          "Replacing operand with value of different type!");
705   if (getOperand(OpNo) == Op)
706     return const_cast<ConstantExpr*>(this);
707   
708   Constant *Op0, *Op1, *Op2;
709   switch (getOpcode()) {
710   case Instruction::Trunc:
711   case Instruction::ZExt:
712   case Instruction::SExt:
713   case Instruction::FPTrunc:
714   case Instruction::FPExt:
715   case Instruction::UIToFP:
716   case Instruction::SIToFP:
717   case Instruction::FPToUI:
718   case Instruction::FPToSI:
719   case Instruction::PtrToInt:
720   case Instruction::IntToPtr:
721   case Instruction::BitCast:
722     return ConstantExpr::getCast(getOpcode(), Op, getType());
723   case Instruction::Select:
724     Op0 = (OpNo == 0) ? Op : getOperand(0);
725     Op1 = (OpNo == 1) ? Op : getOperand(1);
726     Op2 = (OpNo == 2) ? Op : getOperand(2);
727     return ConstantExpr::getSelect(Op0, Op1, Op2);
728   case Instruction::InsertElement:
729     Op0 = (OpNo == 0) ? Op : getOperand(0);
730     Op1 = (OpNo == 1) ? Op : getOperand(1);
731     Op2 = (OpNo == 2) ? Op : getOperand(2);
732     return ConstantExpr::getInsertElement(Op0, Op1, Op2);
733   case Instruction::ExtractElement:
734     Op0 = (OpNo == 0) ? Op : getOperand(0);
735     Op1 = (OpNo == 1) ? Op : getOperand(1);
736     return ConstantExpr::getExtractElement(Op0, Op1);
737   case Instruction::ShuffleVector:
738     Op0 = (OpNo == 0) ? Op : getOperand(0);
739     Op1 = (OpNo == 1) ? Op : getOperand(1);
740     Op2 = (OpNo == 2) ? Op : getOperand(2);
741     return ConstantExpr::getShuffleVector(Op0, Op1, Op2);
742   case Instruction::GetElementPtr: {
743     SmallVector<Constant*, 8> Ops;
744     Ops.resize(getNumOperands()-1);
745     for (unsigned i = 1, e = getNumOperands(); i != e; ++i)
746       Ops[i-1] = getOperand(i);
747     if (OpNo == 0)
748       return cast<GEPOperator>(this)->isInBounds() ?
749         ConstantExpr::getInBoundsGetElementPtr(Op, &Ops[0], Ops.size()) :
750         ConstantExpr::getGetElementPtr(Op, &Ops[0], Ops.size());
751     Ops[OpNo-1] = Op;
752     return cast<GEPOperator>(this)->isInBounds() ?
753       ConstantExpr::getInBoundsGetElementPtr(getOperand(0), &Ops[0],Ops.size()):
754       ConstantExpr::getGetElementPtr(getOperand(0), &Ops[0], Ops.size());
755   }
756   default:
757     assert(getNumOperands() == 2 && "Must be binary operator?");
758     Op0 = (OpNo == 0) ? Op : getOperand(0);
759     Op1 = (OpNo == 1) ? Op : getOperand(1);
760     return ConstantExpr::get(getOpcode(), Op0, Op1, SubclassOptionalData);
761   }
762 }
763
764 /// getWithOperands - This returns the current constant expression with the
765 /// operands replaced with the specified values.  The specified operands must
766 /// match count and type with the existing ones.
767 Constant *ConstantExpr::
768 getWithOperands(Constant *const *Ops, unsigned NumOps) const {
769   assert(NumOps == getNumOperands() && "Operand count mismatch!");
770   bool AnyChange = false;
771   for (unsigned i = 0; i != NumOps; ++i) {
772     assert(Ops[i]->getType() == getOperand(i)->getType() &&
773            "Operand type mismatch!");
774     AnyChange |= Ops[i] != getOperand(i);
775   }
776   if (!AnyChange)  // No operands changed, return self.
777     return const_cast<ConstantExpr*>(this);
778
779   switch (getOpcode()) {
780   case Instruction::Trunc:
781   case Instruction::ZExt:
782   case Instruction::SExt:
783   case Instruction::FPTrunc:
784   case Instruction::FPExt:
785   case Instruction::UIToFP:
786   case Instruction::SIToFP:
787   case Instruction::FPToUI:
788   case Instruction::FPToSI:
789   case Instruction::PtrToInt:
790   case Instruction::IntToPtr:
791   case Instruction::BitCast:
792     return ConstantExpr::getCast(getOpcode(), Ops[0], getType());
793   case Instruction::Select:
794     return ConstantExpr::getSelect(Ops[0], Ops[1], Ops[2]);
795   case Instruction::InsertElement:
796     return ConstantExpr::getInsertElement(Ops[0], Ops[1], Ops[2]);
797   case Instruction::ExtractElement:
798     return ConstantExpr::getExtractElement(Ops[0], Ops[1]);
799   case Instruction::ShuffleVector:
800     return ConstantExpr::getShuffleVector(Ops[0], Ops[1], Ops[2]);
801   case Instruction::GetElementPtr:
802     return cast<GEPOperator>(this)->isInBounds() ?
803       ConstantExpr::getInBoundsGetElementPtr(Ops[0], &Ops[1], NumOps-1) :
804       ConstantExpr::getGetElementPtr(Ops[0], &Ops[1], NumOps-1);
805   case Instruction::ICmp:
806   case Instruction::FCmp:
807     return ConstantExpr::getCompare(getPredicate(), Ops[0], Ops[1]);
808   default:
809     assert(getNumOperands() == 2 && "Must be binary operator?");
810     return ConstantExpr::get(getOpcode(), Ops[0], Ops[1], SubclassOptionalData);
811   }
812 }
813
814
815 //===----------------------------------------------------------------------===//
816 //                      isValueValidForType implementations
817
818 bool ConstantInt::isValueValidForType(const Type *Ty, uint64_t Val) {
819   unsigned NumBits = cast<IntegerType>(Ty)->getBitWidth(); // assert okay
820   if (Ty == Type::getInt1Ty(Ty->getContext()))
821     return Val == 0 || Val == 1;
822   if (NumBits >= 64)
823     return true; // always true, has to fit in largest type
824   uint64_t Max = (1ll << NumBits) - 1;
825   return Val <= Max;
826 }
827
828 bool ConstantInt::isValueValidForType(const Type *Ty, int64_t Val) {
829   unsigned NumBits = cast<IntegerType>(Ty)->getBitWidth(); // assert okay
830   if (Ty == Type::getInt1Ty(Ty->getContext()))
831     return Val == 0 || Val == 1 || Val == -1;
832   if (NumBits >= 64)
833     return true; // always true, has to fit in largest type
834   int64_t Min = -(1ll << (NumBits-1));
835   int64_t Max = (1ll << (NumBits-1)) - 1;
836   return (Val >= Min && Val <= Max);
837 }
838
839 bool ConstantFP::isValueValidForType(const Type *Ty, const APFloat& Val) {
840   // convert modifies in place, so make a copy.
841   APFloat Val2 = APFloat(Val);
842   bool losesInfo;
843   switch (Ty->getTypeID()) {
844   default:
845     return false;         // These can't be represented as floating point!
846
847   // FIXME rounding mode needs to be more flexible
848   case Type::FloatTyID: {
849     if (&Val2.getSemantics() == &APFloat::IEEEsingle)
850       return true;
851     Val2.convert(APFloat::IEEEsingle, APFloat::rmNearestTiesToEven, &losesInfo);
852     return !losesInfo;
853   }
854   case Type::DoubleTyID: {
855     if (&Val2.getSemantics() == &APFloat::IEEEsingle ||
856         &Val2.getSemantics() == &APFloat::IEEEdouble)
857       return true;
858     Val2.convert(APFloat::IEEEdouble, APFloat::rmNearestTiesToEven, &losesInfo);
859     return !losesInfo;
860   }
861   case Type::X86_FP80TyID:
862     return &Val2.getSemantics() == &APFloat::IEEEsingle || 
863            &Val2.getSemantics() == &APFloat::IEEEdouble ||
864            &Val2.getSemantics() == &APFloat::x87DoubleExtended;
865   case Type::FP128TyID:
866     return &Val2.getSemantics() == &APFloat::IEEEsingle || 
867            &Val2.getSemantics() == &APFloat::IEEEdouble ||
868            &Val2.getSemantics() == &APFloat::IEEEquad;
869   case Type::PPC_FP128TyID:
870     return &Val2.getSemantics() == &APFloat::IEEEsingle || 
871            &Val2.getSemantics() == &APFloat::IEEEdouble ||
872            &Val2.getSemantics() == &APFloat::PPCDoubleDouble;
873   }
874 }
875
876 //===----------------------------------------------------------------------===//
877 //                      Factory Function Implementation
878
879 ConstantAggregateZero* ConstantAggregateZero::get(const Type* Ty) {
880   assert((Ty->isStructTy() || Ty->isArrayTy() || Ty->isVectorTy()) &&
881          "Cannot create an aggregate zero of non-aggregate type!");
882   
883   LLVMContextImpl *pImpl = Ty->getContext().pImpl;
884   return pImpl->AggZeroConstants.getOrCreate(Ty, 0);
885 }
886
887 /// destroyConstant - Remove the constant from the constant table...
888 ///
889 void ConstantAggregateZero::destroyConstant() {
890   getRawType()->getContext().pImpl->AggZeroConstants.remove(this);
891   destroyConstantImpl();
892 }
893
894 /// destroyConstant - Remove the constant from the constant table...
895 ///
896 void ConstantArray::destroyConstant() {
897   getRawType()->getContext().pImpl->ArrayConstants.remove(this);
898   destroyConstantImpl();
899 }
900
901 /// isString - This method returns true if the array is an array of i8, and 
902 /// if the elements of the array are all ConstantInt's.
903 bool ConstantArray::isString() const {
904   // Check the element type for i8...
905   if (!getType()->getElementType()->isIntegerTy(8))
906     return false;
907   // Check the elements to make sure they are all integers, not constant
908   // expressions.
909   for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
910     if (!isa<ConstantInt>(getOperand(i)))
911       return false;
912   return true;
913 }
914
915 /// isCString - This method returns true if the array is a string (see
916 /// isString) and it ends in a null byte \\0 and does not contains any other
917 /// null bytes except its terminator.
918 bool ConstantArray::isCString() const {
919   // Check the element type for i8...
920   if (!getType()->getElementType()->isIntegerTy(8))
921     return false;
922
923   // Last element must be a null.
924   if (!getOperand(getNumOperands()-1)->isNullValue())
925     return false;
926   // Other elements must be non-null integers.
927   for (unsigned i = 0, e = getNumOperands()-1; i != e; ++i) {
928     if (!isa<ConstantInt>(getOperand(i)))
929       return false;
930     if (getOperand(i)->isNullValue())
931       return false;
932   }
933   return true;
934 }
935
936
937 /// getAsString - If the sub-element type of this array is i8
938 /// then this method converts the array to an std::string and returns it.
939 /// Otherwise, it asserts out.
940 ///
941 std::string ConstantArray::getAsString() const {
942   assert(isString() && "Not a string!");
943   std::string Result;
944   Result.reserve(getNumOperands());
945   for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
946     Result.push_back((char)cast<ConstantInt>(getOperand(i))->getZExtValue());
947   return Result;
948 }
949
950
951 //---- ConstantStruct::get() implementation...
952 //
953
954 namespace llvm {
955
956 }
957
958 // destroyConstant - Remove the constant from the constant table...
959 //
960 void ConstantStruct::destroyConstant() {
961   getRawType()->getContext().pImpl->StructConstants.remove(this);
962   destroyConstantImpl();
963 }
964
965 // destroyConstant - Remove the constant from the constant table...
966 //
967 void ConstantVector::destroyConstant() {
968   getRawType()->getContext().pImpl->VectorConstants.remove(this);
969   destroyConstantImpl();
970 }
971
972 /// This function will return true iff every element in this vector constant
973 /// is set to all ones.
974 /// @returns true iff this constant's emements are all set to all ones.
975 /// @brief Determine if the value is all ones.
976 bool ConstantVector::isAllOnesValue() const {
977   // Check out first element.
978   const Constant *Elt = getOperand(0);
979   const ConstantInt *CI = dyn_cast<ConstantInt>(Elt);
980   if (!CI || !CI->isAllOnesValue()) return false;
981   // Then make sure all remaining elements point to the same value.
982   for (unsigned I = 1, E = getNumOperands(); I < E; ++I) {
983     if (getOperand(I) != Elt) return false;
984   }
985   return true;
986 }
987
988 /// getSplatValue - If this is a splat constant, where all of the
989 /// elements have the same value, return that value. Otherwise return null.
990 Constant *ConstantVector::getSplatValue() const {
991   // Check out first element.
992   Constant *Elt = getOperand(0);
993   // Then make sure all remaining elements point to the same value.
994   for (unsigned I = 1, E = getNumOperands(); I < E; ++I)
995     if (getOperand(I) != Elt) return 0;
996   return Elt;
997 }
998
999 //---- ConstantPointerNull::get() implementation.
1000 //
1001
1002 ConstantPointerNull *ConstantPointerNull::get(const PointerType *Ty) {
1003   return Ty->getContext().pImpl->NullPtrConstants.getOrCreate(Ty, 0);
1004 }
1005
1006 // destroyConstant - Remove the constant from the constant table...
1007 //
1008 void ConstantPointerNull::destroyConstant() {
1009   getRawType()->getContext().pImpl->NullPtrConstants.remove(this);
1010   destroyConstantImpl();
1011 }
1012
1013
1014 //---- UndefValue::get() implementation.
1015 //
1016
1017 UndefValue *UndefValue::get(const Type *Ty) {
1018   return Ty->getContext().pImpl->UndefValueConstants.getOrCreate(Ty, 0);
1019 }
1020
1021 // destroyConstant - Remove the constant from the constant table.
1022 //
1023 void UndefValue::destroyConstant() {
1024   getRawType()->getContext().pImpl->UndefValueConstants.remove(this);
1025   destroyConstantImpl();
1026 }
1027
1028 //---- BlockAddress::get() implementation.
1029 //
1030
1031 BlockAddress *BlockAddress::get(BasicBlock *BB) {
1032   assert(BB->getParent() != 0 && "Block must have a parent");
1033   return get(BB->getParent(), BB);
1034 }
1035
1036 BlockAddress *BlockAddress::get(Function *F, BasicBlock *BB) {
1037   BlockAddress *&BA =
1038     F->getContext().pImpl->BlockAddresses[std::make_pair(F, BB)];
1039   if (BA == 0)
1040     BA = new BlockAddress(F, BB);
1041   
1042   assert(BA->getFunction() == F && "Basic block moved between functions");
1043   return BA;
1044 }
1045
1046 BlockAddress::BlockAddress(Function *F, BasicBlock *BB)
1047 : Constant(Type::getInt8PtrTy(F->getContext()), Value::BlockAddressVal,
1048            &Op<0>(), 2) {
1049   setOperand(0, F);
1050   setOperand(1, BB);
1051   BB->AdjustBlockAddressRefCount(1);
1052 }
1053
1054
1055 // destroyConstant - Remove the constant from the constant table.
1056 //
1057 void BlockAddress::destroyConstant() {
1058   getFunction()->getRawType()->getContext().pImpl
1059     ->BlockAddresses.erase(std::make_pair(getFunction(), getBasicBlock()));
1060   getBasicBlock()->AdjustBlockAddressRefCount(-1);
1061   destroyConstantImpl();
1062 }
1063
1064 void BlockAddress::replaceUsesOfWithOnConstant(Value *From, Value *To, Use *U) {
1065   // This could be replacing either the Basic Block or the Function.  In either
1066   // case, we have to remove the map entry.
1067   Function *NewF = getFunction();
1068   BasicBlock *NewBB = getBasicBlock();
1069   
1070   if (U == &Op<0>())
1071     NewF = cast<Function>(To);
1072   else
1073     NewBB = cast<BasicBlock>(To);
1074   
1075   // See if the 'new' entry already exists, if not, just update this in place
1076   // and return early.
1077   BlockAddress *&NewBA =
1078     getContext().pImpl->BlockAddresses[std::make_pair(NewF, NewBB)];
1079   if (NewBA == 0) {
1080     getBasicBlock()->AdjustBlockAddressRefCount(-1);
1081     
1082     // Remove the old entry, this can't cause the map to rehash (just a
1083     // tombstone will get added).
1084     getContext().pImpl->BlockAddresses.erase(std::make_pair(getFunction(),
1085                                                             getBasicBlock()));
1086     NewBA = this;
1087     setOperand(0, NewF);
1088     setOperand(1, NewBB);
1089     getBasicBlock()->AdjustBlockAddressRefCount(1);
1090     return;
1091   }
1092
1093   // Otherwise, I do need to replace this with an existing value.
1094   assert(NewBA != this && "I didn't contain From!");
1095   
1096   // Everyone using this now uses the replacement.
1097   uncheckedReplaceAllUsesWith(NewBA);
1098   
1099   destroyConstant();
1100 }
1101
1102 //---- ConstantExpr::get() implementations.
1103 //
1104
1105 /// This is a utility function to handle folding of casts and lookup of the
1106 /// cast in the ExprConstants map. It is used by the various get* methods below.
1107 static inline Constant *getFoldedCast(
1108   Instruction::CastOps opc, Constant *C, const Type *Ty) {
1109   assert(Ty->isFirstClassType() && "Cannot cast to an aggregate type!");
1110   // Fold a few common cases
1111   if (Constant *FC = ConstantFoldCastInstruction(opc, C, Ty))
1112     return FC;
1113
1114   LLVMContextImpl *pImpl = Ty->getContext().pImpl;
1115
1116   // Look up the constant in the table first to ensure uniqueness
1117   std::vector<Constant*> argVec(1, C);
1118   ExprMapKeyType Key(opc, argVec);
1119   
1120   return pImpl->ExprConstants.getOrCreate(Ty, Key);
1121 }
1122  
1123 Constant *ConstantExpr::getCast(unsigned oc, Constant *C, const Type *Ty) {
1124   Instruction::CastOps opc = Instruction::CastOps(oc);
1125   assert(Instruction::isCast(opc) && "opcode out of range");
1126   assert(C && Ty && "Null arguments to getCast");
1127   assert(CastInst::castIsValid(opc, C, Ty) && "Invalid constantexpr cast!");
1128
1129   switch (opc) {
1130   default:
1131     llvm_unreachable("Invalid cast opcode");
1132     break;
1133   case Instruction::Trunc:    return getTrunc(C, Ty);
1134   case Instruction::ZExt:     return getZExt(C, Ty);
1135   case Instruction::SExt:     return getSExt(C, Ty);
1136   case Instruction::FPTrunc:  return getFPTrunc(C, Ty);
1137   case Instruction::FPExt:    return getFPExtend(C, Ty);
1138   case Instruction::UIToFP:   return getUIToFP(C, Ty);
1139   case Instruction::SIToFP:   return getSIToFP(C, Ty);
1140   case Instruction::FPToUI:   return getFPToUI(C, Ty);
1141   case Instruction::FPToSI:   return getFPToSI(C, Ty);
1142   case Instruction::PtrToInt: return getPtrToInt(C, Ty);
1143   case Instruction::IntToPtr: return getIntToPtr(C, Ty);
1144   case Instruction::BitCast:  return getBitCast(C, Ty);
1145   }
1146   return 0;
1147
1148
1149 Constant *ConstantExpr::getZExtOrBitCast(Constant *C, const Type *Ty) {
1150   if (C->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
1151     return getBitCast(C, Ty);
1152   return getZExt(C, Ty);
1153 }
1154
1155 Constant *ConstantExpr::getSExtOrBitCast(Constant *C, const Type *Ty) {
1156   if (C->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
1157     return getBitCast(C, Ty);
1158   return getSExt(C, Ty);
1159 }
1160
1161 Constant *ConstantExpr::getTruncOrBitCast(Constant *C, const Type *Ty) {
1162   if (C->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
1163     return getBitCast(C, Ty);
1164   return getTrunc(C, Ty);
1165 }
1166
1167 Constant *ConstantExpr::getPointerCast(Constant *S, const Type *Ty) {
1168   assert(S->getType()->isPointerTy() && "Invalid cast");
1169   assert((Ty->isIntegerTy() || Ty->isPointerTy()) && "Invalid cast");
1170
1171   if (Ty->isIntegerTy())
1172     return getPtrToInt(S, Ty);
1173   return getBitCast(S, Ty);
1174 }
1175
1176 Constant *ConstantExpr::getIntegerCast(Constant *C, const Type *Ty, 
1177                                        bool isSigned) {
1178   assert(C->getType()->isIntOrIntVectorTy() &&
1179          Ty->isIntOrIntVectorTy() && "Invalid cast");
1180   unsigned SrcBits = C->getType()->getScalarSizeInBits();
1181   unsigned DstBits = Ty->getScalarSizeInBits();
1182   Instruction::CastOps opcode =
1183     (SrcBits == DstBits ? Instruction::BitCast :
1184      (SrcBits > DstBits ? Instruction::Trunc :
1185       (isSigned ? Instruction::SExt : Instruction::ZExt)));
1186   return getCast(opcode, C, Ty);
1187 }
1188
1189 Constant *ConstantExpr::getFPCast(Constant *C, const Type *Ty) {
1190   assert(C->getType()->isFPOrFPVectorTy() && Ty->isFPOrFPVectorTy() &&
1191          "Invalid cast");
1192   unsigned SrcBits = C->getType()->getScalarSizeInBits();
1193   unsigned DstBits = Ty->getScalarSizeInBits();
1194   if (SrcBits == DstBits)
1195     return C; // Avoid a useless cast
1196   Instruction::CastOps opcode =
1197     (SrcBits > DstBits ? Instruction::FPTrunc : Instruction::FPExt);
1198   return getCast(opcode, C, Ty);
1199 }
1200
1201 Constant *ConstantExpr::getTrunc(Constant *C, const Type *Ty) {
1202 #ifndef NDEBUG
1203   bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1204   bool toVec = Ty->getTypeID() == Type::VectorTyID;
1205 #endif
1206   assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1207   assert(C->getType()->isIntOrIntVectorTy() && "Trunc operand must be integer");
1208   assert(Ty->isIntOrIntVectorTy() && "Trunc produces only integral");
1209   assert(C->getType()->getScalarSizeInBits() > Ty->getScalarSizeInBits()&&
1210          "SrcTy must be larger than DestTy for Trunc!");
1211
1212   return getFoldedCast(Instruction::Trunc, C, Ty);
1213 }
1214
1215 Constant *ConstantExpr::getSExt(Constant *C, const Type *Ty) {
1216 #ifndef NDEBUG
1217   bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1218   bool toVec = Ty->getTypeID() == Type::VectorTyID;
1219 #endif
1220   assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1221   assert(C->getType()->isIntOrIntVectorTy() && "SExt operand must be integral");
1222   assert(Ty->isIntOrIntVectorTy() && "SExt produces only integer");
1223   assert(C->getType()->getScalarSizeInBits() < Ty->getScalarSizeInBits()&&
1224          "SrcTy must be smaller than DestTy for SExt!");
1225
1226   return getFoldedCast(Instruction::SExt, C, Ty);
1227 }
1228
1229 Constant *ConstantExpr::getZExt(Constant *C, const Type *Ty) {
1230 #ifndef NDEBUG
1231   bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1232   bool toVec = Ty->getTypeID() == Type::VectorTyID;
1233 #endif
1234   assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1235   assert(C->getType()->isIntOrIntVectorTy() && "ZEXt operand must be integral");
1236   assert(Ty->isIntOrIntVectorTy() && "ZExt produces only integer");
1237   assert(C->getType()->getScalarSizeInBits() < Ty->getScalarSizeInBits()&&
1238          "SrcTy must be smaller than DestTy for ZExt!");
1239
1240   return getFoldedCast(Instruction::ZExt, C, Ty);
1241 }
1242
1243 Constant *ConstantExpr::getFPTrunc(Constant *C, const Type *Ty) {
1244 #ifndef NDEBUG
1245   bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1246   bool toVec = Ty->getTypeID() == Type::VectorTyID;
1247 #endif
1248   assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1249   assert(C->getType()->isFPOrFPVectorTy() && Ty->isFPOrFPVectorTy() &&
1250          C->getType()->getScalarSizeInBits() > Ty->getScalarSizeInBits()&&
1251          "This is an illegal floating point truncation!");
1252   return getFoldedCast(Instruction::FPTrunc, C, Ty);
1253 }
1254
1255 Constant *ConstantExpr::getFPExtend(Constant *C, const Type *Ty) {
1256 #ifndef NDEBUG
1257   bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1258   bool toVec = Ty->getTypeID() == Type::VectorTyID;
1259 #endif
1260   assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1261   assert(C->getType()->isFPOrFPVectorTy() && Ty->isFPOrFPVectorTy() &&
1262          C->getType()->getScalarSizeInBits() < Ty->getScalarSizeInBits()&&
1263          "This is an illegal floating point extension!");
1264   return getFoldedCast(Instruction::FPExt, C, Ty);
1265 }
1266
1267 Constant *ConstantExpr::getUIToFP(Constant *C, const Type *Ty) {
1268 #ifndef NDEBUG
1269   bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1270   bool toVec = Ty->getTypeID() == Type::VectorTyID;
1271 #endif
1272   assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1273   assert(C->getType()->isIntOrIntVectorTy() && Ty->isFPOrFPVectorTy() &&
1274          "This is an illegal uint to floating point cast!");
1275   return getFoldedCast(Instruction::UIToFP, C, Ty);
1276 }
1277
1278 Constant *ConstantExpr::getSIToFP(Constant *C, const Type *Ty) {
1279 #ifndef NDEBUG
1280   bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1281   bool toVec = Ty->getTypeID() == Type::VectorTyID;
1282 #endif
1283   assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1284   assert(C->getType()->isIntOrIntVectorTy() && Ty->isFPOrFPVectorTy() &&
1285          "This is an illegal sint to floating point cast!");
1286   return getFoldedCast(Instruction::SIToFP, C, Ty);
1287 }
1288
1289 Constant *ConstantExpr::getFPToUI(Constant *C, const Type *Ty) {
1290 #ifndef NDEBUG
1291   bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1292   bool toVec = Ty->getTypeID() == Type::VectorTyID;
1293 #endif
1294   assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1295   assert(C->getType()->isFPOrFPVectorTy() && Ty->isIntOrIntVectorTy() &&
1296          "This is an illegal floating point to uint cast!");
1297   return getFoldedCast(Instruction::FPToUI, C, Ty);
1298 }
1299
1300 Constant *ConstantExpr::getFPToSI(Constant *C, const Type *Ty) {
1301 #ifndef NDEBUG
1302   bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1303   bool toVec = Ty->getTypeID() == Type::VectorTyID;
1304 #endif
1305   assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1306   assert(C->getType()->isFPOrFPVectorTy() && Ty->isIntOrIntVectorTy() &&
1307          "This is an illegal floating point to sint cast!");
1308   return getFoldedCast(Instruction::FPToSI, C, Ty);
1309 }
1310
1311 Constant *ConstantExpr::getPtrToInt(Constant *C, const Type *DstTy) {
1312   assert(C->getType()->isPointerTy() && "PtrToInt source must be pointer");
1313   assert(DstTy->isIntegerTy() && "PtrToInt destination must be integral");
1314   return getFoldedCast(Instruction::PtrToInt, C, DstTy);
1315 }
1316
1317 Constant *ConstantExpr::getIntToPtr(Constant *C, const Type *DstTy) {
1318   assert(C->getType()->isIntegerTy() && "IntToPtr source must be integral");
1319   assert(DstTy->isPointerTy() && "IntToPtr destination must be a pointer");
1320   return getFoldedCast(Instruction::IntToPtr, C, DstTy);
1321 }
1322
1323 Constant *ConstantExpr::getBitCast(Constant *C, const Type *DstTy) {
1324   assert(CastInst::castIsValid(Instruction::BitCast, C, DstTy) &&
1325          "Invalid constantexpr bitcast!");
1326   
1327   // It is common to ask for a bitcast of a value to its own type, handle this
1328   // speedily.
1329   if (C->getType() == DstTy) return C;
1330   
1331   return getFoldedCast(Instruction::BitCast, C, DstTy);
1332 }
1333
1334 Constant *ConstantExpr::getTy(const Type *ReqTy, unsigned Opcode,
1335                               Constant *C1, Constant *C2,
1336                               unsigned Flags) {
1337   // Check the operands for consistency first
1338   assert(Opcode >= Instruction::BinaryOpsBegin &&
1339          Opcode <  Instruction::BinaryOpsEnd   &&
1340          "Invalid opcode in binary constant expression");
1341   assert(C1->getType() == C2->getType() &&
1342          "Operand types in binary constant expression should match");
1343
1344   if (ReqTy == C1->getType() || ReqTy == Type::getInt1Ty(ReqTy->getContext()))
1345     if (Constant *FC = ConstantFoldBinaryInstruction(Opcode, C1, C2))
1346       return FC;          // Fold a few common cases...
1347
1348   std::vector<Constant*> argVec(1, C1); argVec.push_back(C2);
1349   ExprMapKeyType Key(Opcode, argVec, 0, Flags);
1350   
1351   LLVMContextImpl *pImpl = ReqTy->getContext().pImpl;
1352   return pImpl->ExprConstants.getOrCreate(ReqTy, Key);
1353 }
1354
1355 Constant *ConstantExpr::getCompareTy(unsigned short predicate,
1356                                      Constant *C1, Constant *C2) {
1357   switch (predicate) {
1358     default: llvm_unreachable("Invalid CmpInst predicate");
1359     case CmpInst::FCMP_FALSE: case CmpInst::FCMP_OEQ: case CmpInst::FCMP_OGT:
1360     case CmpInst::FCMP_OGE:   case CmpInst::FCMP_OLT: case CmpInst::FCMP_OLE:
1361     case CmpInst::FCMP_ONE:   case CmpInst::FCMP_ORD: case CmpInst::FCMP_UNO:
1362     case CmpInst::FCMP_UEQ:   case CmpInst::FCMP_UGT: case CmpInst::FCMP_UGE:
1363     case CmpInst::FCMP_ULT:   case CmpInst::FCMP_ULE: case CmpInst::FCMP_UNE:
1364     case CmpInst::FCMP_TRUE:
1365       return getFCmp(predicate, C1, C2);
1366
1367     case CmpInst::ICMP_EQ:  case CmpInst::ICMP_NE:  case CmpInst::ICMP_UGT:
1368     case CmpInst::ICMP_UGE: case CmpInst::ICMP_ULT: case CmpInst::ICMP_ULE:
1369     case CmpInst::ICMP_SGT: case CmpInst::ICMP_SGE: case CmpInst::ICMP_SLT:
1370     case CmpInst::ICMP_SLE:
1371       return getICmp(predicate, C1, C2);
1372   }
1373 }
1374
1375 Constant *ConstantExpr::get(unsigned Opcode, Constant *C1, Constant *C2,
1376                             unsigned Flags) {
1377 #ifndef NDEBUG
1378   switch (Opcode) {
1379   case Instruction::Add:
1380   case Instruction::Sub:
1381   case Instruction::Mul:
1382     assert(C1->getType() == C2->getType() && "Op types should be identical!");
1383     assert(C1->getType()->isIntOrIntVectorTy() &&
1384            "Tried to create an integer operation on a non-integer type!");
1385     break;
1386   case Instruction::FAdd:
1387   case Instruction::FSub:
1388   case Instruction::FMul:
1389     assert(C1->getType() == C2->getType() && "Op types should be identical!");
1390     assert(C1->getType()->isFPOrFPVectorTy() &&
1391            "Tried to create a floating-point operation on a "
1392            "non-floating-point type!");
1393     break;
1394   case Instruction::UDiv: 
1395   case Instruction::SDiv: 
1396     assert(C1->getType() == C2->getType() && "Op types should be identical!");
1397     assert(C1->getType()->isIntOrIntVectorTy() &&
1398            "Tried to create an arithmetic operation on a non-arithmetic type!");
1399     break;
1400   case Instruction::FDiv:
1401     assert(C1->getType() == C2->getType() && "Op types should be identical!");
1402     assert(C1->getType()->isFPOrFPVectorTy() &&
1403            "Tried to create an arithmetic operation on a non-arithmetic type!");
1404     break;
1405   case Instruction::URem: 
1406   case Instruction::SRem: 
1407     assert(C1->getType() == C2->getType() && "Op types should be identical!");
1408     assert(C1->getType()->isIntOrIntVectorTy() &&
1409            "Tried to create an arithmetic operation on a non-arithmetic type!");
1410     break;
1411   case Instruction::FRem:
1412     assert(C1->getType() == C2->getType() && "Op types should be identical!");
1413     assert(C1->getType()->isFPOrFPVectorTy() &&
1414            "Tried to create an arithmetic operation on a non-arithmetic type!");
1415     break;
1416   case Instruction::And:
1417   case Instruction::Or:
1418   case Instruction::Xor:
1419     assert(C1->getType() == C2->getType() && "Op types should be identical!");
1420     assert(C1->getType()->isIntOrIntVectorTy() &&
1421            "Tried to create a logical operation on a non-integral type!");
1422     break;
1423   case Instruction::Shl:
1424   case Instruction::LShr:
1425   case Instruction::AShr:
1426     assert(C1->getType() == C2->getType() && "Op types should be identical!");
1427     assert(C1->getType()->isIntOrIntVectorTy() &&
1428            "Tried to create a shift operation on a non-integer type!");
1429     break;
1430   default:
1431     break;
1432   }
1433 #endif
1434
1435   return getTy(C1->getType(), Opcode, C1, C2, Flags);
1436 }
1437
1438 Constant *ConstantExpr::getSizeOf(const Type* Ty) {
1439   // sizeof is implemented as: (i64) gep (Ty*)null, 1
1440   // Note that a non-inbounds gep is used, as null isn't within any object.
1441   Constant *GEPIdx = ConstantInt::get(Type::getInt32Ty(Ty->getContext()), 1);
1442   Constant *GEP = getGetElementPtr(
1443                  Constant::getNullValue(PointerType::getUnqual(Ty)), &GEPIdx, 1);
1444   return getPtrToInt(GEP, 
1445                      Type::getInt64Ty(Ty->getContext()));
1446 }
1447
1448 Constant *ConstantExpr::getAlignOf(const Type* Ty) {
1449   // alignof is implemented as: (i64) gep ({i1,Ty}*)null, 0, 1
1450   // Note that a non-inbounds gep is used, as null isn't within any object.
1451   const Type *AligningTy = StructType::get(Ty->getContext(),
1452                                    Type::getInt1Ty(Ty->getContext()), Ty, NULL);
1453   Constant *NullPtr = Constant::getNullValue(AligningTy->getPointerTo());
1454   Constant *Zero = ConstantInt::get(Type::getInt64Ty(Ty->getContext()), 0);
1455   Constant *One = ConstantInt::get(Type::getInt32Ty(Ty->getContext()), 1);
1456   Constant *Indices[2] = { Zero, One };
1457   Constant *GEP = getGetElementPtr(NullPtr, Indices, 2);
1458   return getPtrToInt(GEP,
1459                      Type::getInt64Ty(Ty->getContext()));
1460 }
1461
1462 Constant *ConstantExpr::getOffsetOf(const StructType* STy, unsigned FieldNo) {
1463   return getOffsetOf(STy, ConstantInt::get(Type::getInt32Ty(STy->getContext()),
1464                                            FieldNo));
1465 }
1466
1467 Constant *ConstantExpr::getOffsetOf(const Type* Ty, Constant *FieldNo) {
1468   // offsetof is implemented as: (i64) gep (Ty*)null, 0, FieldNo
1469   // Note that a non-inbounds gep is used, as null isn't within any object.
1470   Constant *GEPIdx[] = {
1471     ConstantInt::get(Type::getInt64Ty(Ty->getContext()), 0),
1472     FieldNo
1473   };
1474   Constant *GEP = getGetElementPtr(
1475                 Constant::getNullValue(PointerType::getUnqual(Ty)), GEPIdx, 2);
1476   return getPtrToInt(GEP,
1477                      Type::getInt64Ty(Ty->getContext()));
1478 }
1479
1480 Constant *ConstantExpr::getCompare(unsigned short pred, 
1481                             Constant *C1, Constant *C2) {
1482   assert(C1->getType() == C2->getType() && "Op types should be identical!");
1483   return getCompareTy(pred, C1, C2);
1484 }
1485
1486 Constant *ConstantExpr::getSelectTy(const Type *ReqTy, Constant *C,
1487                                     Constant *V1, Constant *V2) {
1488   assert(!SelectInst::areInvalidOperands(C, V1, V2)&&"Invalid select operands");
1489
1490   if (ReqTy == V1->getType())
1491     if (Constant *SC = ConstantFoldSelectInstruction(C, V1, V2))
1492       return SC;        // Fold common cases
1493
1494   std::vector<Constant*> argVec(3, C);
1495   argVec[1] = V1;
1496   argVec[2] = V2;
1497   ExprMapKeyType Key(Instruction::Select, argVec);
1498   
1499   LLVMContextImpl *pImpl = ReqTy->getContext().pImpl;
1500   return pImpl->ExprConstants.getOrCreate(ReqTy, Key);
1501 }
1502
1503 template<typename IndexTy>
1504 Constant *ConstantExpr::getGetElementPtrTy(const Type *ReqTy, Constant *C,
1505                                            IndexTy const *Idxs,
1506                                            unsigned NumIdx, bool InBounds) {
1507   assert(GetElementPtrInst::getIndexedType(C->getType(), Idxs,
1508                                            Idxs+NumIdx) ==
1509          cast<PointerType>(ReqTy)->getElementType() &&
1510          "GEP indices invalid!");
1511
1512   if (Constant *FC = ConstantFoldGetElementPtr(C, InBounds, Idxs, NumIdx))
1513     return FC;          // Fold a few common cases.
1514
1515   assert(C->getType()->isPointerTy() &&
1516          "Non-pointer type for constant GetElementPtr expression");
1517   // Look up the constant in the table first to ensure uniqueness
1518   std::vector<Constant*> ArgVec;
1519   ArgVec.reserve(NumIdx+1);
1520   ArgVec.push_back(C);
1521   for (unsigned i = 0; i != NumIdx; ++i)
1522     ArgVec.push_back(cast<Constant>(Idxs[i]));
1523   const ExprMapKeyType Key(Instruction::GetElementPtr, ArgVec, 0,
1524                            InBounds ? GEPOperator::IsInBounds : 0);
1525
1526   LLVMContextImpl *pImpl = ReqTy->getContext().pImpl;
1527   return pImpl->ExprConstants.getOrCreate(ReqTy, Key);
1528 }
1529
1530 template<typename IndexTy>
1531 Constant *ConstantExpr::getGetElementPtrImpl(Constant *C, IndexTy const *Idxs,
1532                                              unsigned NumIdx, bool InBounds) {
1533   // Get the result type of the getelementptr!
1534   const Type *Ty = 
1535     GetElementPtrInst::getIndexedType(C->getType(), Idxs, Idxs+NumIdx);
1536   assert(Ty && "GEP indices invalid!");
1537   unsigned As = cast<PointerType>(C->getType())->getAddressSpace();
1538   return getGetElementPtrTy(PointerType::get(Ty, As), C, Idxs, NumIdx,InBounds);
1539 }
1540
1541 Constant *ConstantExpr::getGetElementPtr(Constant *C, Value* const *Idxs,
1542                                          unsigned NumIdx, bool InBounds) {
1543   return getGetElementPtrImpl(C, Idxs, NumIdx, InBounds);
1544 }
1545
1546 Constant *ConstantExpr::getGetElementPtr(Constant *C, Constant *const *Idxs,
1547                                          unsigned NumIdx, bool InBounds) {
1548   return getGetElementPtrImpl(C, Idxs, NumIdx, InBounds);
1549 }
1550
1551 Constant *
1552 ConstantExpr::getICmp(unsigned short pred, Constant *LHS, Constant *RHS) {
1553   assert(LHS->getType() == RHS->getType());
1554   assert(pred >= ICmpInst::FIRST_ICMP_PREDICATE && 
1555          pred <= ICmpInst::LAST_ICMP_PREDICATE && "Invalid ICmp Predicate");
1556
1557   if (Constant *FC = ConstantFoldCompareInstruction(pred, LHS, RHS))
1558     return FC;          // Fold a few common cases...
1559
1560   // Look up the constant in the table first to ensure uniqueness
1561   std::vector<Constant*> ArgVec;
1562   ArgVec.push_back(LHS);
1563   ArgVec.push_back(RHS);
1564   // Get the key type with both the opcode and predicate
1565   const ExprMapKeyType Key(Instruction::ICmp, ArgVec, pred);
1566
1567   const Type *ResultTy = Type::getInt1Ty(LHS->getContext());
1568   if (const VectorType *VT = dyn_cast<VectorType>(LHS->getType()))
1569     ResultTy = VectorType::get(ResultTy, VT->getNumElements());
1570
1571   LLVMContextImpl *pImpl = LHS->getType()->getContext().pImpl;
1572   return pImpl->ExprConstants.getOrCreate(ResultTy, Key);
1573 }
1574
1575 Constant *
1576 ConstantExpr::getFCmp(unsigned short pred, Constant *LHS, Constant *RHS) {
1577   assert(LHS->getType() == RHS->getType());
1578   assert(pred <= FCmpInst::LAST_FCMP_PREDICATE && "Invalid FCmp Predicate");
1579
1580   if (Constant *FC = ConstantFoldCompareInstruction(pred, LHS, RHS))
1581     return FC;          // Fold a few common cases...
1582
1583   // Look up the constant in the table first to ensure uniqueness
1584   std::vector<Constant*> ArgVec;
1585   ArgVec.push_back(LHS);
1586   ArgVec.push_back(RHS);
1587   // Get the key type with both the opcode and predicate
1588   const ExprMapKeyType Key(Instruction::FCmp, ArgVec, pred);
1589
1590   const Type *ResultTy = Type::getInt1Ty(LHS->getContext());
1591   if (const VectorType *VT = dyn_cast<VectorType>(LHS->getType()))
1592     ResultTy = VectorType::get(ResultTy, VT->getNumElements());
1593
1594   LLVMContextImpl *pImpl = LHS->getType()->getContext().pImpl;
1595   return pImpl->ExprConstants.getOrCreate(ResultTy, Key);
1596 }
1597
1598 Constant *ConstantExpr::getExtractElementTy(const Type *ReqTy, Constant *Val,
1599                                             Constant *Idx) {
1600   if (Constant *FC = ConstantFoldExtractElementInstruction(Val, Idx))
1601     return FC;          // Fold a few common cases.
1602   // Look up the constant in the table first to ensure uniqueness
1603   std::vector<Constant*> ArgVec(1, Val);
1604   ArgVec.push_back(Idx);
1605   const ExprMapKeyType Key(Instruction::ExtractElement,ArgVec);
1606   
1607   LLVMContextImpl *pImpl = ReqTy->getContext().pImpl;
1608   return pImpl->ExprConstants.getOrCreate(ReqTy, Key);
1609 }
1610
1611 Constant *ConstantExpr::getExtractElement(Constant *Val, Constant *Idx) {
1612   assert(Val->getType()->isVectorTy() &&
1613          "Tried to create extractelement operation on non-vector type!");
1614   assert(Idx->getType()->isIntegerTy(32) &&
1615          "Extractelement index must be i32 type!");
1616   return getExtractElementTy(cast<VectorType>(Val->getType())->getElementType(),
1617                              Val, Idx);
1618 }
1619
1620 Constant *ConstantExpr::getInsertElementTy(const Type *ReqTy, Constant *Val,
1621                                            Constant *Elt, Constant *Idx) {
1622   if (Constant *FC = ConstantFoldInsertElementInstruction(Val, Elt, Idx))
1623     return FC;          // Fold a few common cases.
1624   // Look up the constant in the table first to ensure uniqueness
1625   std::vector<Constant*> ArgVec(1, Val);
1626   ArgVec.push_back(Elt);
1627   ArgVec.push_back(Idx);
1628   const ExprMapKeyType Key(Instruction::InsertElement,ArgVec);
1629   
1630   LLVMContextImpl *pImpl = ReqTy->getContext().pImpl;
1631   return pImpl->ExprConstants.getOrCreate(ReqTy, Key);
1632 }
1633
1634 Constant *ConstantExpr::getInsertElement(Constant *Val, Constant *Elt, 
1635                                          Constant *Idx) {
1636   assert(Val->getType()->isVectorTy() &&
1637          "Tried to create insertelement operation on non-vector type!");
1638   assert(Elt->getType() == cast<VectorType>(Val->getType())->getElementType()
1639          && "Insertelement types must match!");
1640   assert(Idx->getType()->isIntegerTy(32) &&
1641          "Insertelement index must be i32 type!");
1642   return getInsertElementTy(Val->getType(), Val, Elt, Idx);
1643 }
1644
1645 Constant *ConstantExpr::getShuffleVectorTy(const Type *ReqTy, Constant *V1,
1646                                            Constant *V2, Constant *Mask) {
1647   if (Constant *FC = ConstantFoldShuffleVectorInstruction(V1, V2, Mask))
1648     return FC;          // Fold a few common cases...
1649   // Look up the constant in the table first to ensure uniqueness
1650   std::vector<Constant*> ArgVec(1, V1);
1651   ArgVec.push_back(V2);
1652   ArgVec.push_back(Mask);
1653   const ExprMapKeyType Key(Instruction::ShuffleVector,ArgVec);
1654   
1655   LLVMContextImpl *pImpl = ReqTy->getContext().pImpl;
1656   return pImpl->ExprConstants.getOrCreate(ReqTy, Key);
1657 }
1658
1659 Constant *ConstantExpr::getShuffleVector(Constant *V1, Constant *V2, 
1660                                          Constant *Mask) {
1661   assert(ShuffleVectorInst::isValidOperands(V1, V2, Mask) &&
1662          "Invalid shuffle vector constant expr operands!");
1663
1664   unsigned NElts = cast<VectorType>(Mask->getType())->getNumElements();
1665   const Type *EltTy = cast<VectorType>(V1->getType())->getElementType();
1666   const Type *ShufTy = VectorType::get(EltTy, NElts);
1667   return getShuffleVectorTy(ShufTy, V1, V2, Mask);
1668 }
1669
1670 Constant *ConstantExpr::getInsertValueTy(const Type *ReqTy, Constant *Agg,
1671                                          Constant *Val,
1672                                         const unsigned *Idxs, unsigned NumIdx) {
1673   assert(ExtractValueInst::getIndexedType(Agg->getType(), Idxs,
1674                                           Idxs+NumIdx) == Val->getType() &&
1675          "insertvalue indices invalid!");
1676   assert(Agg->getType() == ReqTy &&
1677          "insertvalue type invalid!");
1678   assert(Agg->getType()->isFirstClassType() &&
1679          "Non-first-class type for constant InsertValue expression");
1680   Constant *FC = ConstantFoldInsertValueInstruction(Agg, Val, Idxs, NumIdx);
1681   assert(FC && "InsertValue constant expr couldn't be folded!");
1682   return FC;
1683 }
1684
1685 Constant *ConstantExpr::getInsertValue(Constant *Agg, Constant *Val,
1686                                      const unsigned *IdxList, unsigned NumIdx) {
1687   assert(Agg->getType()->isFirstClassType() &&
1688          "Tried to create insertelement operation on non-first-class type!");
1689
1690   const Type *ReqTy = Agg->getType();
1691 #ifndef NDEBUG
1692   const Type *ValTy =
1693     ExtractValueInst::getIndexedType(Agg->getType(), IdxList, IdxList+NumIdx);
1694 #endif
1695   assert(ValTy == Val->getType() && "insertvalue indices invalid!");
1696   return getInsertValueTy(ReqTy, Agg, Val, IdxList, NumIdx);
1697 }
1698
1699 Constant *ConstantExpr::getExtractValueTy(const Type *ReqTy, Constant *Agg,
1700                                         const unsigned *Idxs, unsigned NumIdx) {
1701   assert(ExtractValueInst::getIndexedType(Agg->getType(), Idxs,
1702                                           Idxs+NumIdx) == ReqTy &&
1703          "extractvalue indices invalid!");
1704   assert(Agg->getType()->isFirstClassType() &&
1705          "Non-first-class type for constant extractvalue expression");
1706   Constant *FC = ConstantFoldExtractValueInstruction(Agg, Idxs, NumIdx);
1707   assert(FC && "ExtractValue constant expr couldn't be folded!");
1708   return FC;
1709 }
1710
1711 Constant *ConstantExpr::getExtractValue(Constant *Agg,
1712                                      const unsigned *IdxList, unsigned NumIdx) {
1713   assert(Agg->getType()->isFirstClassType() &&
1714          "Tried to create extractelement operation on non-first-class type!");
1715
1716   const Type *ReqTy =
1717     ExtractValueInst::getIndexedType(Agg->getType(), IdxList, IdxList+NumIdx);
1718   assert(ReqTy && "extractvalue indices invalid!");
1719   return getExtractValueTy(ReqTy, Agg, IdxList, NumIdx);
1720 }
1721
1722 Constant *ConstantExpr::getNeg(Constant *C, bool HasNUW, bool HasNSW) {
1723   assert(C->getType()->isIntOrIntVectorTy() &&
1724          "Cannot NEG a nonintegral value!");
1725   return getSub(ConstantFP::getZeroValueForNegation(C->getType()),
1726                 C, HasNUW, HasNSW);
1727 }
1728
1729 Constant *ConstantExpr::getFNeg(Constant *C) {
1730   assert(C->getType()->isFPOrFPVectorTy() &&
1731          "Cannot FNEG a non-floating-point value!");
1732   return getFSub(ConstantFP::getZeroValueForNegation(C->getType()), C);
1733 }
1734
1735 Constant *ConstantExpr::getNot(Constant *C) {
1736   assert(C->getType()->isIntOrIntVectorTy() &&
1737          "Cannot NOT a nonintegral value!");
1738   return get(Instruction::Xor, C, Constant::getAllOnesValue(C->getType()));
1739 }
1740
1741 Constant *ConstantExpr::getAdd(Constant *C1, Constant *C2,
1742                                bool HasNUW, bool HasNSW) {
1743   unsigned Flags = (HasNUW ? OverflowingBinaryOperator::NoUnsignedWrap : 0) |
1744                    (HasNSW ? OverflowingBinaryOperator::NoSignedWrap   : 0);
1745   return get(Instruction::Add, C1, C2, Flags);
1746 }
1747
1748 Constant *ConstantExpr::getFAdd(Constant *C1, Constant *C2) {
1749   return get(Instruction::FAdd, C1, C2);
1750 }
1751
1752 Constant *ConstantExpr::getSub(Constant *C1, Constant *C2,
1753                                bool HasNUW, bool HasNSW) {
1754   unsigned Flags = (HasNUW ? OverflowingBinaryOperator::NoUnsignedWrap : 0) |
1755                    (HasNSW ? OverflowingBinaryOperator::NoSignedWrap   : 0);
1756   return get(Instruction::Sub, C1, C2, Flags);
1757 }
1758
1759 Constant *ConstantExpr::getFSub(Constant *C1, Constant *C2) {
1760   return get(Instruction::FSub, C1, C2);
1761 }
1762
1763 Constant *ConstantExpr::getMul(Constant *C1, Constant *C2,
1764                                bool HasNUW, bool HasNSW) {
1765   unsigned Flags = (HasNUW ? OverflowingBinaryOperator::NoUnsignedWrap : 0) |
1766                    (HasNSW ? OverflowingBinaryOperator::NoSignedWrap   : 0);
1767   return get(Instruction::Mul, C1, C2, Flags);
1768 }
1769
1770 Constant *ConstantExpr::getFMul(Constant *C1, Constant *C2) {
1771   return get(Instruction::FMul, C1, C2);
1772 }
1773
1774 Constant *ConstantExpr::getUDiv(Constant *C1, Constant *C2, bool isExact) {
1775   return get(Instruction::UDiv, C1, C2,
1776              isExact ? PossiblyExactOperator::IsExact : 0);
1777 }
1778
1779 Constant *ConstantExpr::getSDiv(Constant *C1, Constant *C2, bool isExact) {
1780   return get(Instruction::SDiv, C1, C2,
1781              isExact ? PossiblyExactOperator::IsExact : 0);
1782 }
1783
1784 Constant *ConstantExpr::getFDiv(Constant *C1, Constant *C2) {
1785   return get(Instruction::FDiv, C1, C2);
1786 }
1787
1788 Constant *ConstantExpr::getURem(Constant *C1, Constant *C2) {
1789   return get(Instruction::URem, C1, C2);
1790 }
1791
1792 Constant *ConstantExpr::getSRem(Constant *C1, Constant *C2) {
1793   return get(Instruction::SRem, C1, C2);
1794 }
1795
1796 Constant *ConstantExpr::getFRem(Constant *C1, Constant *C2) {
1797   return get(Instruction::FRem, C1, C2);
1798 }
1799
1800 Constant *ConstantExpr::getAnd(Constant *C1, Constant *C2) {
1801   return get(Instruction::And, C1, C2);
1802 }
1803
1804 Constant *ConstantExpr::getOr(Constant *C1, Constant *C2) {
1805   return get(Instruction::Or, C1, C2);
1806 }
1807
1808 Constant *ConstantExpr::getXor(Constant *C1, Constant *C2) {
1809   return get(Instruction::Xor, C1, C2);
1810 }
1811
1812 Constant *ConstantExpr::getShl(Constant *C1, Constant *C2,
1813                                bool HasNUW, bool HasNSW) {
1814   unsigned Flags = (HasNUW ? OverflowingBinaryOperator::NoUnsignedWrap : 0) |
1815                    (HasNSW ? OverflowingBinaryOperator::NoSignedWrap   : 0);
1816   return get(Instruction::Shl, C1, C2, Flags);
1817 }
1818
1819 Constant *ConstantExpr::getLShr(Constant *C1, Constant *C2, bool isExact) {
1820   return get(Instruction::LShr, C1, C2,
1821              isExact ? PossiblyExactOperator::IsExact : 0);
1822 }
1823
1824 Constant *ConstantExpr::getAShr(Constant *C1, Constant *C2, bool isExact) {
1825   return get(Instruction::AShr, C1, C2,
1826              isExact ? PossiblyExactOperator::IsExact : 0);
1827 }
1828
1829 // destroyConstant - Remove the constant from the constant table...
1830 //
1831 void ConstantExpr::destroyConstant() {
1832   getRawType()->getContext().pImpl->ExprConstants.remove(this);
1833   destroyConstantImpl();
1834 }
1835
1836 const char *ConstantExpr::getOpcodeName() const {
1837   return Instruction::getOpcodeName(getOpcode());
1838 }
1839
1840
1841
1842 GetElementPtrConstantExpr::
1843 GetElementPtrConstantExpr(Constant *C, const std::vector<Constant*> &IdxList,
1844                           const Type *DestTy)
1845   : ConstantExpr(DestTy, Instruction::GetElementPtr,
1846                  OperandTraits<GetElementPtrConstantExpr>::op_end(this)
1847                  - (IdxList.size()+1), IdxList.size()+1) {
1848   OperandList[0] = C;
1849   for (unsigned i = 0, E = IdxList.size(); i != E; ++i)
1850     OperandList[i+1] = IdxList[i];
1851 }
1852
1853
1854 //===----------------------------------------------------------------------===//
1855 //                replaceUsesOfWithOnConstant implementations
1856
1857 /// replaceUsesOfWithOnConstant - Update this constant array to change uses of
1858 /// 'From' to be uses of 'To'.  This must update the uniquing data structures
1859 /// etc.
1860 ///
1861 /// Note that we intentionally replace all uses of From with To here.  Consider
1862 /// a large array that uses 'From' 1000 times.  By handling this case all here,
1863 /// ConstantArray::replaceUsesOfWithOnConstant is only invoked once, and that
1864 /// single invocation handles all 1000 uses.  Handling them one at a time would
1865 /// work, but would be really slow because it would have to unique each updated
1866 /// array instance.
1867 ///
1868 void ConstantArray::replaceUsesOfWithOnConstant(Value *From, Value *To,
1869                                                 Use *U) {
1870   assert(isa<Constant>(To) && "Cannot make Constant refer to non-constant!");
1871   Constant *ToC = cast<Constant>(To);
1872
1873   LLVMContextImpl *pImpl = getRawType()->getContext().pImpl;
1874
1875   std::pair<LLVMContextImpl::ArrayConstantsTy::MapKey, ConstantArray*> Lookup;
1876   Lookup.first.first = cast<ArrayType>(getRawType());
1877   Lookup.second = this;
1878
1879   std::vector<Constant*> &Values = Lookup.first.second;
1880   Values.reserve(getNumOperands());  // Build replacement array.
1881
1882   // Fill values with the modified operands of the constant array.  Also, 
1883   // compute whether this turns into an all-zeros array.
1884   bool isAllZeros = false;
1885   unsigned NumUpdated = 0;
1886   if (!ToC->isNullValue()) {
1887     for (Use *O = OperandList, *E = OperandList+getNumOperands(); O != E; ++O) {
1888       Constant *Val = cast<Constant>(O->get());
1889       if (Val == From) {
1890         Val = ToC;
1891         ++NumUpdated;
1892       }
1893       Values.push_back(Val);
1894     }
1895   } else {
1896     isAllZeros = true;
1897     for (Use *O = OperandList, *E = OperandList+getNumOperands();O != E; ++O) {
1898       Constant *Val = cast<Constant>(O->get());
1899       if (Val == From) {
1900         Val = ToC;
1901         ++NumUpdated;
1902       }
1903       Values.push_back(Val);
1904       if (isAllZeros) isAllZeros = Val->isNullValue();
1905     }
1906   }
1907   
1908   Constant *Replacement = 0;
1909   if (isAllZeros) {
1910     Replacement = ConstantAggregateZero::get(getRawType());
1911   } else {
1912     // Check to see if we have this array type already.
1913     bool Exists;
1914     LLVMContextImpl::ArrayConstantsTy::MapTy::iterator I =
1915       pImpl->ArrayConstants.InsertOrGetItem(Lookup, Exists);
1916     
1917     if (Exists) {
1918       Replacement = I->second;
1919     } else {
1920       // Okay, the new shape doesn't exist in the system yet.  Instead of
1921       // creating a new constant array, inserting it, replaceallusesof'ing the
1922       // old with the new, then deleting the old... just update the current one
1923       // in place!
1924       pImpl->ArrayConstants.MoveConstantToNewSlot(this, I);
1925       
1926       // Update to the new value.  Optimize for the case when we have a single
1927       // operand that we're changing, but handle bulk updates efficiently.
1928       if (NumUpdated == 1) {
1929         unsigned OperandToUpdate = U - OperandList;
1930         assert(getOperand(OperandToUpdate) == From &&
1931                "ReplaceAllUsesWith broken!");
1932         setOperand(OperandToUpdate, ToC);
1933       } else {
1934         for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
1935           if (getOperand(i) == From)
1936             setOperand(i, ToC);
1937       }
1938       return;
1939     }
1940   }
1941  
1942   // Otherwise, I do need to replace this with an existing value.
1943   assert(Replacement != this && "I didn't contain From!");
1944   
1945   // Everyone using this now uses the replacement.
1946   uncheckedReplaceAllUsesWith(Replacement);
1947   
1948   // Delete the old constant!
1949   destroyConstant();
1950 }
1951
1952 void ConstantStruct::replaceUsesOfWithOnConstant(Value *From, Value *To,
1953                                                  Use *U) {
1954   assert(isa<Constant>(To) && "Cannot make Constant refer to non-constant!");
1955   Constant *ToC = cast<Constant>(To);
1956
1957   unsigned OperandToUpdate = U-OperandList;
1958   assert(getOperand(OperandToUpdate) == From && "ReplaceAllUsesWith broken!");
1959
1960   std::pair<LLVMContextImpl::StructConstantsTy::MapKey, ConstantStruct*> Lookup;
1961   Lookup.first.first = cast<StructType>(getRawType());
1962   Lookup.second = this;
1963   std::vector<Constant*> &Values = Lookup.first.second;
1964   Values.reserve(getNumOperands());  // Build replacement struct.
1965   
1966   
1967   // Fill values with the modified operands of the constant struct.  Also, 
1968   // compute whether this turns into an all-zeros struct.
1969   bool isAllZeros = false;
1970   if (!ToC->isNullValue()) {
1971     for (Use *O = OperandList, *E = OperandList + getNumOperands(); O != E; ++O)
1972       Values.push_back(cast<Constant>(O->get()));
1973   } else {
1974     isAllZeros = true;
1975     for (Use *O = OperandList, *E = OperandList+getNumOperands(); O != E; ++O) {
1976       Constant *Val = cast<Constant>(O->get());
1977       Values.push_back(Val);
1978       if (isAllZeros) isAllZeros = Val->isNullValue();
1979     }
1980   }
1981   Values[OperandToUpdate] = ToC;
1982   
1983   LLVMContextImpl *pImpl = getRawType()->getContext().pImpl;
1984   
1985   Constant *Replacement = 0;
1986   if (isAllZeros) {
1987     Replacement = ConstantAggregateZero::get(getRawType());
1988   } else {
1989     // Check to see if we have this struct type already.
1990     bool Exists;
1991     LLVMContextImpl::StructConstantsTy::MapTy::iterator I =
1992       pImpl->StructConstants.InsertOrGetItem(Lookup, Exists);
1993     
1994     if (Exists) {
1995       Replacement = I->second;
1996     } else {
1997       // Okay, the new shape doesn't exist in the system yet.  Instead of
1998       // creating a new constant struct, inserting it, replaceallusesof'ing the
1999       // old with the new, then deleting the old... just update the current one
2000       // in place!
2001       pImpl->StructConstants.MoveConstantToNewSlot(this, I);
2002       
2003       // Update to the new value.
2004       setOperand(OperandToUpdate, ToC);
2005       return;
2006     }
2007   }
2008   
2009   assert(Replacement != this && "I didn't contain From!");
2010   
2011   // Everyone using this now uses the replacement.
2012   uncheckedReplaceAllUsesWith(Replacement);
2013   
2014   // Delete the old constant!
2015   destroyConstant();
2016 }
2017
2018 void ConstantVector::replaceUsesOfWithOnConstant(Value *From, Value *To,
2019                                                  Use *U) {
2020   assert(isa<Constant>(To) && "Cannot make Constant refer to non-constant!");
2021   
2022   std::vector<Constant*> Values;
2023   Values.reserve(getNumOperands());  // Build replacement array...
2024   for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
2025     Constant *Val = getOperand(i);
2026     if (Val == From) Val = cast<Constant>(To);
2027     Values.push_back(Val);
2028   }
2029   
2030   Constant *Replacement = get(cast<VectorType>(getRawType()), Values);
2031   assert(Replacement != this && "I didn't contain From!");
2032   
2033   // Everyone using this now uses the replacement.
2034   uncheckedReplaceAllUsesWith(Replacement);
2035   
2036   // Delete the old constant!
2037   destroyConstant();
2038 }
2039
2040 void ConstantExpr::replaceUsesOfWithOnConstant(Value *From, Value *ToV,
2041                                                Use *U) {
2042   assert(isa<Constant>(ToV) && "Cannot make Constant refer to non-constant!");
2043   Constant *To = cast<Constant>(ToV);
2044   
2045   Constant *Replacement = 0;
2046   if (getOpcode() == Instruction::GetElementPtr) {
2047     SmallVector<Constant*, 8> Indices;
2048     Constant *Pointer = getOperand(0);
2049     Indices.reserve(getNumOperands()-1);
2050     if (Pointer == From) Pointer = To;
2051     
2052     for (unsigned i = 1, e = getNumOperands(); i != e; ++i) {
2053       Constant *Val = getOperand(i);
2054       if (Val == From) Val = To;
2055       Indices.push_back(Val);
2056     }
2057     Replacement = ConstantExpr::getGetElementPtr(Pointer,
2058                                                  &Indices[0], Indices.size(),
2059                                          cast<GEPOperator>(this)->isInBounds());
2060   } else if (getOpcode() == Instruction::ExtractValue) {
2061     Constant *Agg = getOperand(0);
2062     if (Agg == From) Agg = To;
2063     
2064     const SmallVector<unsigned, 4> &Indices = getIndices();
2065     Replacement = ConstantExpr::getExtractValue(Agg,
2066                                                 &Indices[0], Indices.size());
2067   } else if (getOpcode() == Instruction::InsertValue) {
2068     Constant *Agg = getOperand(0);
2069     Constant *Val = getOperand(1);
2070     if (Agg == From) Agg = To;
2071     if (Val == From) Val = To;
2072     
2073     const SmallVector<unsigned, 4> &Indices = getIndices();
2074     Replacement = ConstantExpr::getInsertValue(Agg, Val,
2075                                                &Indices[0], Indices.size());
2076   } else if (isCast()) {
2077     assert(getOperand(0) == From && "Cast only has one use!");
2078     Replacement = ConstantExpr::getCast(getOpcode(), To, getRawType());
2079   } else if (getOpcode() == Instruction::Select) {
2080     Constant *C1 = getOperand(0);
2081     Constant *C2 = getOperand(1);
2082     Constant *C3 = getOperand(2);
2083     if (C1 == From) C1 = To;
2084     if (C2 == From) C2 = To;
2085     if (C3 == From) C3 = To;
2086     Replacement = ConstantExpr::getSelect(C1, C2, C3);
2087   } else if (getOpcode() == Instruction::ExtractElement) {
2088     Constant *C1 = getOperand(0);
2089     Constant *C2 = getOperand(1);
2090     if (C1 == From) C1 = To;
2091     if (C2 == From) C2 = To;
2092     Replacement = ConstantExpr::getExtractElement(C1, C2);
2093   } else if (getOpcode() == Instruction::InsertElement) {
2094     Constant *C1 = getOperand(0);
2095     Constant *C2 = getOperand(1);
2096     Constant *C3 = getOperand(1);
2097     if (C1 == From) C1 = To;
2098     if (C2 == From) C2 = To;
2099     if (C3 == From) C3 = To;
2100     Replacement = ConstantExpr::getInsertElement(C1, C2, C3);
2101   } else if (getOpcode() == Instruction::ShuffleVector) {
2102     Constant *C1 = getOperand(0);
2103     Constant *C2 = getOperand(1);
2104     Constant *C3 = getOperand(2);
2105     if (C1 == From) C1 = To;
2106     if (C2 == From) C2 = To;
2107     if (C3 == From) C3 = To;
2108     Replacement = ConstantExpr::getShuffleVector(C1, C2, C3);
2109   } else if (isCompare()) {
2110     Constant *C1 = getOperand(0);
2111     Constant *C2 = getOperand(1);
2112     if (C1 == From) C1 = To;
2113     if (C2 == From) C2 = To;
2114     if (getOpcode() == Instruction::ICmp)
2115       Replacement = ConstantExpr::getICmp(getPredicate(), C1, C2);
2116     else {
2117       assert(getOpcode() == Instruction::FCmp);
2118       Replacement = ConstantExpr::getFCmp(getPredicate(), C1, C2);
2119     }
2120   } else if (getNumOperands() == 2) {
2121     Constant *C1 = getOperand(0);
2122     Constant *C2 = getOperand(1);
2123     if (C1 == From) C1 = To;
2124     if (C2 == From) C2 = To;
2125     Replacement = ConstantExpr::get(getOpcode(), C1, C2, SubclassOptionalData);
2126   } else {
2127     llvm_unreachable("Unknown ConstantExpr type!");
2128     return;
2129   }
2130   
2131   assert(Replacement != this && "I didn't contain From!");
2132   
2133   // Everyone using this now uses the replacement.
2134   uncheckedReplaceAllUsesWith(Replacement);
2135   
2136   // Delete the old constant!
2137   destroyConstant();
2138 }