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